def correct_vel(ra, dec, vel, vlsr=None): """Corrects the proper motion for the speed of the Sun Arguments: ra - RA in deg dec -- Declination in deg pmra -- pm in RA in mas/yr pmdec -- pm in declination in mas/yr dist -- distance in kpc Returns: (pmra,pmdec) the tuple with the proper motions corrected for the Sun's motion """ if vlsr is not None: print('WARNING vlsr is ignored') C = acoo.ICRS(ra=ra * auni.deg, dec=dec * auni.deg, radial_velocity=vel * auni.km / auni.s, distance=np.ones_like(vel) * auni.kpc, pm_ra_cosdec=np.zeros_like(vel) * auni.mas / auni.year, pm_dec=np.zeros_like(vel) * auni.mas / auni.year) frame = acoo.Galactocentric(**GCPARAMS) Cg = C.transform_to(frame) Cg1 = acoo.Galactocentric(x=Cg.x, y=Cg.y, z=Cg.z, v_x=Cg.v_x * 0, v_y=Cg.v_y * 0, v_z=Cg.v_z * 0, **GCPARAMS) C1 = Cg1.transform_to(acoo.ICRS()) return np.asarray(((C.radial_velocity - C1.radial_velocity) / (auni.km / auni.s)).decompose())
def test_vhel_to_vgsr(): filename = get_pkg_data_filename('idl_vgsr_vhel.txt') data = np.genfromtxt(filename, names=True, skip_header=2) # one row row = data[0] l = coord.Angle(row["lon"] * u.degree) b = coord.Angle(row["lat"] * u.degree) c = coord.Galactic(l, b) vhel = row["vhelio"] * u.km / u.s vlsr = [row["vx"], row["vy"], row["vz"]] * u.km / u.s # this is right vcirc = row["vcirc"] * u.km / u.s vsun = vlsr + [0, 1, 0] * vcirc vgsr = vhel_to_vgsr(c, vhel, vsun=vsun) assert np.allclose(vgsr.value, row['vgsr'], atol=1e-3) # now check still get right answer passing in ICRS coordinates vgsr = vhel_to_vgsr(c.transform_to(coord.ICRS()), vhel, vsun=vsun) assert np.allclose(vgsr.value, row['vgsr'], atol=1e-3) # all together now l = coord.Angle(data["lon"] * u.degree) b = coord.Angle(data["lat"] * u.degree) c = coord.Galactic(l, b) vhel = data["vhelio"] * u.km / u.s vgsr = vhel_to_vgsr(c, vhel, vsun=vsun) assert np.allclose(vgsr.value, data['vgsr'], atol=1e-3) # now check still get right answer passing in ICRS coordinates vgsr = vhel_to_vgsr(c.transform_to(coord.ICRS()), vhel, vsun=vsun) assert np.allclose(vgsr.value, data['vgsr'], atol=1e-3)
def correct_vel(ra, dec, vel, vlsr=vlsr0, vz=0): """Corrects the proper motion for the speed of the Sun Arguments: ra - RA in deg dec -- Declination in deg pmra -- pm in RA in mas/yr pmdec -- pm in declination in mas/yr dist -- distance in kpc Returns: (pmra,pmdec) the tuple with the proper motions corrected for the Sun's motion """ C = acoo.ICRS(ra=ra * auni.deg, dec=dec * auni.deg, radial_velocity=vel * auni.km / auni.s, distance=np.ones_like(vel) * auni.kpc, pm_ra_cosdec=np.zeros_like(vel) * auni.mas / auni.year, pm_dec=np.zeros_like(vel) * auni.mas / auni.year) kw = dict(galcen_v_sun=acoo.CartesianDifferential( np.array([11.1, vlsr + 12.24, vz + 7.25]) * auni.km / auni.s)) frame = acoo.Galactocentric(**kw) Cg = C.transform_to(frame) Cg1 = acoo.Galactocentric(x=Cg.x, y=Cg.y, z=Cg.z, v_x=Cg.v_x * 0, v_y=Cg.v_y * 0, v_z=Cg.v_z * 0, **kw) C1 = Cg1.transform_to(acoo.ICRS()) return np.asarray(((C.radial_velocity - C1.radial_velocity) / (auni.km / auni.s)).decompose())
def setup_class(cls): """Setup fixtures for testing.""" num = 40 cls.arclength = np.linspace(0, 10, num=num) * u.deg lon = np.linspace(0, 25, num=num) * u.deg lat = np.linspace(-10, 10, num=num) * u.deg distance = np.linspace(8, 15, num=num) * u.kpc cls.data = coord.ICRS( coord.SphericalRepresentation(lon=lon, lat=lat, distance=distance), ) cls.interps = dict( lon=IUSU(cls.arclength, lon), lat=IUSU(cls.arclength, lat), distance=IUSU(cls.arclength, distance), ) # origin i = num // 2 cls.origin = coord.ICRS(ra=lon[i], dec=lat[i]) # track cls.track = StreamTrack( cls.interps, stream_data=cls.data, origin=cls.origin, )
def test_query_region_async_polygon(self): polygon = [coord.ICRS(ra=10.1, dec=10.1, unit=(u.deg, u.deg)), coord.ICRS(ra=10.0, dec=10.1, unit=(u.deg, u.deg)), coord.ICRS(ra=10.0, dec=10.0, unit=(u.deg, u.deg))] response = lcogt.core.Lcogt.query_region_async("m31", catalog="lco_img", spatial="Polygon", polygon=polygon) assert response is not None
def correct_pm0(ra, dec, pmra, pmdec, dist): """Corrects the proper motion for the speed of the Sun Arguments: ra - RA in deg dec -- Declination in deg pmra -- pm in RA in mas/yr pmdec -- pm in declination in mas/yr dist -- distance in kpc Returns: (pmra,pmdec) the tuple with the proper motions corrected for the Sun's motion """ C = acoo.ICRS(ra=ra * auni.deg, dec=dec * auni.deg, radial_velocity=0 * auni.km / auni.s, distance=dist * auni.kpc, pm_ra_cosdec=pmra * auni.mas / auni.year, pm_dec=pmdec * auni.mas / auni.year) frame = acoo.Galactocentric(**GCPARAMS) Cg = C.transform_to(frame) Cg1 = acoo.Galactocentric(x=Cg.x, y=Cg.y, z=Cg.z, v_x=Cg.v_x * 0, v_y=Cg.v_y * 0, v_z=Cg.v_z * 0, **GCPARAMS) C1 = Cg1.transform_to(acoo.ICRS()) return ((C.pm_ra_cosdec - C1.pm_ra_cosdec).to_value(auni.mas / auni.year), (C.pm_dec - C1.pm_dec).to_value(auni.mas / auni.year))
def posang(l1, b1, l2, b2, system='galactic', units='degrees', **kwargs): """ Return the position angle between two points assuming a rectilinear coordinate system (I think; at the very least I am making no corrections for wcs). INPUT: longitude1, latitude1, longitude2, latitude2 Defaults to GALACTIC coordinates. **kwargs are passed to coords.Position """ if system.lower() == 'galactic': pos1 = coordinates.Galactic(l1, b1, unit=('deg', 'deg')) pos2 = coordinates.Galactic(l2, b2, unit=('deg', 'deg')) elif system.lower() in ('radec', 'fk5', 'icrs'): pos1 = coordinates.ICRS(l1, b1, unit=('deg', 'deg')) pos2 = coordinates.ICRS(l2, b2, unit=('deg', 'deg')) ra1, dec1 = pos1.icrs.ra.deg, pos1.icrs.dec.deg ra2, dec2 = pos2.icrs.ra.deg, pos2.icrs.dec.deg radiff = (ra1 - ra2) / 180. * pi angle = arctan2( sin(radiff), cos(dec1 * pi / 180.) * tan(dec2 * pi / 180.) - sin(dec1 * pi / 180.) * cos(radiff)) if units == 'degrees': return angle / pi * 180 elif units == 'radians': return angle else: raise ValueError("Invalid units: %s" % units)
def test_frame_is_SkyCoord(): """Test when frame is a SkyCoord.""" c = coord.ICRS(ra=1 * u.deg, dec=2 * u.deg) sc = coord.SkyCoord(c) # basic usage assert resolve_framelike(frame=sc) == coord.ICRS()
def test_simple(): c = coord.ICRS(coord.Angle(217.2141, u.degree), coord.Angle(-11.4351, u.degree)) c.transform_to(Pal5PriceWhelan18()) c = coord.Galactic(coord.Angle(217.2141, u.degree), coord.Angle(-11.4351, u.degree)) c.transform_to(Pal5PriceWhelan18()) c = Pal5PriceWhelan18(217.2141 * u.degree, -11.4351 * u.degree) c.transform_to(coord.ICRS()) c.transform_to(coord.Galactic()) c = coord.Galactic(coord.Angle(217.2141, u.degree), coord.Angle(-11.4351, u.degree)) c.transform_to(Pal5PriceWhelan18()) # with distance c = Pal5PriceWhelan18(coord.Angle(217.2141, u.degree), coord.Angle(-11.4351, u.degree), distance=15 * u.kpc) c.transform_to(coord.ICRS()) c2 = c.transform_to(coord.Galactic()) assert np.allclose(c2.distance.value, c.distance.value) # TODO: remove this in next version # For now: make sure old class still works from astropy.tests.helper import catch_warnings with catch_warnings(DeprecationWarning) as w: c = Pal5(217.2141 * u.degree, -11.4351 * u.degree) assert len(w) > 0 c2 = c.transform_to(coord.Galactic()) c3 = c2.transform_to(Pal5()) assert np.allclose(c3.phi1.degree, c.phi1.degree) assert np.allclose(c3.phi2.degree, c.phi2.degree)
def test___init__(self): """Test method ``__init__``.""" # frame inst = self.klass(self.points, **self.kwargs) assert inst.frame is None # points are converted inst = self.klass( self.points.represent_as(coord.CartesianRepresentation), frame="icrs", **self.kwargs, ) assert isinstance(inst.points, self.rep_cls) # resolve_frame with pytest.raises(TypeError): # not instance self.klass(self.points, frame=object, **self.kwargs) for frame in (coord.ICRS, coord.ICRS(), "icrs"): inst = self.klass(self.points, frame=frame, **self.kwargs) assert inst.frame == coord.ICRS() # ------------------- # errors # if different units with pytest.raises(u.UnitsError, match="equivalent units"): inp = [list(itm) for itm in self.kwargs.items()] inp[0][1] = 1 * u.one # assign wrong unit self.klass(self.points, **dict(inp)) # if not base-representation with pytest.raises(TypeError, match="<BaseRepresentation>"): self.klass(object(), **self.kwargs)
def test_frame_is_BaseCoordinateFrame(): """Test when frame is a BaseCoordinateFrame.""" # basic usage assert resolve_framelike(frame=coord.ICRS) == coord.ICRS() assert resolve_framelike(frame=coord.ICRS()) == coord.ICRS() # replicates without data c = coord.ICRS(ra=1 * u.deg, dec=2 * u.deg) assert resolve_framelike(frame=c) == coord.ICRS()
def get_props(cc, spm, z_name_spm): # initialize the properties to measure highest_sfrs = [] youngest_ages = [] sep_r200c = [] delta_z = [] stellar_masses = [] stellar_ages = [] volume = [] is_member = [] z_gal = [] # gets the cluster properties z_clus = cc['CLUZSPEC'] #optical center #center = coord.ICRS(ra=cc['RA_OPT']*u.degree, dec=cc['DEC_OPT']*u.degree) # x ray center center = coord.ICRS(ra=cc['RA'] * u.degree, dec=cc['DEC'] * u.degree) gal = (cc['ALLFIBERID'] > 0) Ngal = len(gal.nonzero()[0]) # loops over the galaxy members r200c = cc['R200C_DEG'] * u.deg / aa.arcsec_per_kpc_proper(0.5).to( u.deg / u.Mpc) volume_cc = 4 * n.pi * r200c.value**3. / 3. for id_cc, (pla, mjd, fib, is_M) in enumerate( zip(cc['ALLPLATE'][gal], cc['ALLMJD'][gal], cc['ALLFIBERID'][gal], cc['ISMEMBER'][gal])): # selects members sel = (spm['PLATE'] == pla) & (spm['MJD'] == mjd) & (spm['FIBERID'] == fib) if len(sel.nonzero()[0]) > 0: z_gal.append(spm[z_name_spm][sel][0]) delta_z.append(z_clus) stellar_masses.append(spm['Chabrier_MILES_stellar_mass'][sel][0]) stellar_ages.append(spm['Chabrier_MILES_age_massW'][sel][0]) is_member.append(is_M) position = coord.ICRS(cc['ALLRA'][id_cc] * u.degree, cc['ALLDEC'][id_cc] * u.degree) sep_r200c.append((center.separation(position) / (cc['R200C_DEG'] * u.degree)).value) volume.append(volume_cc) #n_cp = spm['Chabrier_MILES_nComponentsSSP'][sel].astype('int')[0] #if n_cp > 0 : #all_ages = n.array([ spm['Chabrier_MILES_age_ssp_'+str(ii)][sel][0] for ii in n.arange(n_cp) ]) #all_masses = n.array([ spm['Chabrier_MILES_stellar_mass_ssp_'+str(ii)][sel][0] for ii in n.arange(n_cp) ]) #sfr_inst = all_masses / all_ages #youngest_ages.append(n.min(all_ages)) #highest_sfrs.append(n.max(sfr_inst)) #return n.array(delta_z), n.array(highest_sfrs), n.array(youngest_ages), n.array(sep_r200c), n.array(stellar_masses), n.array(is_member) return n.array(delta_z), n.array(sep_r200c), n.array( stellar_masses), n.array(is_member), n.array(stellar_ages), n.array( volume), n.array(z_gal)
def test_axis_physical_type(): assert icrs.axis_physical_types == ("pos.eq.ra", "pos.eq.dec") assert spec1.axis_physical_types == ("em.freq",) assert spec2.axis_physical_types == ("em.wl",) assert spec3.axis_physical_types == ("em.energy",) assert spec4.axis_physical_types == ("custom:unknown",) assert spec5.axis_physical_types == ("spect.dopplerVeloc",) assert comp1.axis_physical_types == ("pos.eq.ra", "pos.eq.dec", "em.freq") assert comp2.axis_physical_types == ("custom:x", "custom:y", "em.wl") assert comp3.axis_physical_types == ("pos.eq.ra", "pos.eq.dec", "em.energy") assert comp.axis_physical_types == ('pos.eq.ra', 'pos.eq.dec', 'em.freq', 'em.wl') spec6 = cf.SpectralFrame(name='waven', axes_order=(1,), axis_physical_types='em.wavenumber') assert spec6.axis_physical_types == ('em.wavenumber',) t = cf.TemporalFrame(reference_frame=Time("2018-01-01T00:00:00"), unit=u.s) assert t.axis_physical_types == ('time',) fr2d = cf.Frame2D(name='d', axes_names=("x", "y")) assert fr2d.axis_physical_types == ('custom:x', 'custom:y') fr2d = cf.Frame2D(name='d', axes_names=None) assert fr2d.axis_physical_types == ('custom:SPATIAL', 'custom:SPATIAL') fr2d = cf.Frame2D(name='d', axis_physical_types=("pos.x", "pos.y")) assert fr2d.axis_physical_types == ('custom:pos.x', 'custom:pos.y') with pytest.raises(ValueError): cf.CelestialFrame(reference_frame=coord.ICRS(), axis_physical_types=("pos.eq.ra",)) fr = cf.CelestialFrame(reference_frame=coord.ICRS(), axis_physical_types=("ra", "dec")) assert fr.axis_physical_types == ("custom:ra", "custom:dec") fr = cf.CelestialFrame(reference_frame=coord.BarycentricTrueEcliptic()) assert fr.axis_physical_types == ('pos.ecliptic.lon', 'pos.ecliptic.lat') frame = cf.CoordinateFrame(name='custom_frame', axes_type=("SPATIAL",), axes_order=(0,), axis_physical_types="length", axes_names="x", naxes=1) assert frame.axis_physical_types == ("custom:length",) frame = cf.CoordinateFrame(name='custom_frame', axes_type=("SPATIAL",), axes_order=(0,), axis_physical_types=("length",), axes_names="x", naxes=1) assert frame.axis_physical_types == ("custom:length",) with pytest.raises(ValueError): cf.CoordinateFrame(name='custom_frame', axes_type=("SPATIAL",), axes_order=(0,), axis_physical_types=("length", "length"), naxes=1)
def test_query_region_async(patch_get, patch_parse_coordinates): response = nrao.core.Nrao.query_region_async( coord.ICRS("04h33m11.1s 05d21m15.5s"), radius='5d0m0s', equinox='B1950', freq_low=1000 * u.kHz, freq_up=2000 * u.kHz, get_query_payload=True) assert response['SRAD'].startswith('5') and response['SRAD'].endswith('d') assert response['EQUINOX'] == 'B1950' assert response['OBSFREQ1'] == '1.0-2.0' response = nrao.core.Nrao.query_region_async( coord.ICRS("04h33m11.1s 05d21m15.5s")) assert response is not None
def get_psr_coords(self, epoch=None): """Returns pulsar sky coordinates as an astropy ICRS object instance. If epoch (MJD) is specified, proper motion is included to return the position at the given epoch. If the ecliptic coordinates are provided, """ if epoch is None or (self.PMRA.value == 0.0 and self.PMDEC.value == 0.0): return coords.ICRS(ra=self.RAJ.quantity, dec=self.DECJ.quantity) else: dt = (epoch - self.POSEPOCH.quantity.mjd) * u.d dRA = dt * self.PMRA.quantity / numpy.cos(self.DECJ.quantity.radian) dDEC = dt * self.PMDEC.quantity return coords.ICRS(ra=self.RAJ.quantity+dRA, dec=self.DECJ.quantity+dDEC)
def create_coord_frames(): gdetector = cf.Frame2D(name='grism_detector', axes_order=(0, 1), unit=(u.pix, u.pix)) detector = cf.Frame2D(name='full_detector', axes_order=(0, 1), axes_names=('dx', 'dy'), unit=(u.pix, u.pix)) v2v3_spatial = cf.Frame2D(name='v2v3_spatial', axes_order=(0, 1), axes_names=('v2', 'v3'), unit=(u.deg, u.deg)) v2v3vacorr_spatial = cf.Frame2D(name='v2v3vacorr_spatial', axes_order=(0, 1), axes_names=('v2', 'v3'), unit=(u.arcsec, u.arcsec)) sky_frame = cf.CelestialFrame(reference_frame=coord.ICRS(), name='icrs') spec = cf.SpectralFrame(name='spectral', axes_order=(2, ), unit=(u.micron, ), axes_names=('wavelength', )) frames = { 'grism_detector': gdetector, 'direct_image': cf.CompositeFrame([detector, spec], name='direct_image'), 'v2v3': cf.CompositeFrame([v2v3_spatial, spec], name='v2v3'), 'v2v3vacorr': cf.CompositeFrame([v2v3vacorr_spatial, spec], name='v2v3vacorr'), 'world': cf.CompositeFrame([sky_frame, spec], name='world') } return frames
def test_get_image_list(self): urls = vista.core.Vista.get_image_list(coord.ICRS(ra=83.633083, dec=22.0145, unit=(u.deg, u.deg)), frame_type='all', waveband='all') assert len(urls) > 0
def gbm_to_j2000(gbm_coord, j2000_frame): """ Compute the transformation from heliocentric Sgr coordinates to spherical Galactic. """ sc_matrix = gbm_coord._set_quaternion( gbm_coord.quaternion_1, gbm_coord.quaternion_2, gbm_coord.quaternion_3, gbm_coord.quaternion_4, ) # X,Y,Z = gbm_coord.cartesian pos = gbm_coord.cartesian.xyz.value X0 = np.dot(sc_matrix[:, 0], pos) X1 = np.dot(sc_matrix[:, 1], pos) X2 = np.clip(np.dot(sc_matrix[:, 2], pos), -1.0, 1.0) # dec = np.arcsin(X2) dec = np.pi / 2.0 - np.arccos(X2) idx = np.logical_and(np.abs(X0) < 1e-6, np.abs(X1) < 1e-6) ra = np.zeros_like(dec) ra[~idx] = np.arctan2(X1, X0) % (2 * np.pi) return coord.ICRS(ra=ra * u.radian, dec=dec * u.radian)
def annular_search(self): from astropy_healpix import HEALPix from astropy.coordinates import SkyCoord import astropy.coordinates as cc hp = HEALPix(nside=self.nside, order='nested', frame=cc.ICRS()) self.set_geometry(healpix=False) r_min = self.ra_min - self.ra r_max = self.ra_max - self.ra radius = self.ra_max - self.ra #get the healpix IDs covering an annulus centred on self.ra,dec in_annulus = [] self.healpix_indices = [] print 'Populating annulus and determining HEALPix coverage...' while (len(in_annulus)) < 500: rnd_ra = self.ra + (2 * (random.random() - 0.5) * radius) rnd_dec = self.dec + (2 * (random.random() - 0.5) * radius) rnd_dist = (((rnd_ra - self.ra)**2) + ((rnd_dec - self.dec)**2))**0.5 if rnd_dist > r_min: if rnd_dist < r_max: self.healpix_indices.append( hp.skycoord_to_healpix( SkyCoord(rnd_ra, rnd_dec, unit='deg'))) in_annulus.append([rnd_ra, rnd_dec]) #print len(in_annulus) print '....done' self.healpix_indices = unique(self.healpix_indices) print self.healpix_indices self.retrieve_guidecats() target = self.select_target(annular=True) return target
def create_error_samples(nominal_position, errors, n_samples=100): """Create a random sample of cluster positions using the errors.""" dist = np.random.normal(nominal_position.distance.value, errors.distance.value, n_samples) * nominal_position.distance.unit pm_ra_cosdec = np.random.normal( nominal_position.pm_ra_cosdec.value, errors.pm_ra_cosdec.value, n_samples) * nominal_position.pm_ra_cosdec.unit pm_dec = np.random.normal(nominal_position.pm_dec.value, errors.pm_dec.value, n_samples) * nominal_position.pm_dec.unit rv = np.random.normal(nominal_position.radial_velocity.value, errors.radial_velocity.value, n_samples) * nominal_position.radial_velocity.unit ra = np.full(n_samples, nominal_position.ra.degree) * u.degree dec = np.full(n_samples, nominal_position.dec.degree) * u.degree return coord.ICRS(ra=ra, dec=dec, distance=dist, pm_ra_cosdec=pm_ra_cosdec, pm_dec=pm_dec, radial_velocity=rv)
def gwcs_simple_imaging_units(): shift_by_crpix = models.Shift(-2048 * u.pix) & models.Shift(-1024 * u.pix) matrix = np.array([[1.290551569736E-05, 5.9525007864732E-06], [5.0226382102765E-06, -1.2644844123757E-05]]) rotation = models.AffineTransformation2D(matrix * u.deg, translation=[0, 0] * u.deg) rotation.input_units_equivalencies = { "x": u.pixel_scale(1 * u.deg / u.pix), "y": u.pixel_scale(1 * u.deg / u.pix) } rotation.inverse = models.AffineTransformation2D( np.linalg.inv(matrix) * u.pix, translation=[0, 0] * u.pix) rotation.inverse.input_units_equivalencies = { "x": u.pixel_scale(1 * u.pix / u.deg), "y": u.pixel_scale(1 * u.pix / u.deg) } tan = models.Pix2Sky_TAN() celestial_rotation = models.RotateNative2Celestial(5.63056810618 * u.deg, -72.05457184279 * u.deg, 180 * u.deg) det2sky = shift_by_crpix | rotation | tan | celestial_rotation det2sky.name = "linear_transform" detector_frame = cf.Frame2D(name="detector", axes_names=("x", "y"), unit=(u.pix, u.pix)) sky_frame = cf.CelestialFrame(reference_frame=coord.ICRS(), name='icrs', unit=(u.deg, u.deg)) pipeline = [(detector_frame, det2sky), (sky_frame, None)] return wcs.WCS(pipeline)
def gwcs_4d_identity_units(): """ A simple 1-1 gwcs that converts from pixels to arcseconds """ identity = (models.Multiply(1 * u.arcsec / u.pixel) & models.Multiply(1 * u.arcsec / u.pixel) & models.Multiply(1 * u.nm / u.pixel) & models.Multiply(1 * u.s / u.pixel)) sky_frame = cf.CelestialFrame(axes_order=(0, 1), name='icrs', reference_frame=coord.ICRS()) wave_frame = cf.SpectralFrame(axes_order=(2, ), unit=u.nm) time_frame = cf.TemporalFrame(axes_order=(3, ), unit=u.s, reference_frame=Time("2000-01-01T00:00:00")) frame = cf.CompositeFrame([sky_frame, wave_frame, time_frame]) detector_frame = cf.CoordinateFrame(name="detector", naxes=4, axes_order=(0, 1, 2, 3), axes_type=("pixel", "pixel", "pixel", "pixel"), axes_names=("x", "y", "z", "s"), unit=(u.pix, u.pix, u.pix, u.pix)) return wcs.WCS(forward_transform=identity, output_frame=frame, input_frame=detector_frame)
def gwcs_3d_identity_units(): """ A simple 1-1 gwcs that converts from pixels to arcseconds """ identity = (models.Multiply(1 * u.arcsec / u.pixel) & models.Multiply(1 * u.arcsec / u.pixel) & models.Multiply(1 * u.nm / u.pixel)) sky_frame = cf.CelestialFrame(axes_order=(0, 1), name='icrs', reference_frame=coord.ICRS(), axes_names=("longitude", "latitude")) wave_frame = cf.SpectralFrame(axes_order=(2, ), unit=u.nm, axes_names=("wavelength", )) frame = cf.CompositeFrame([sky_frame, wave_frame]) detector_frame = cf.CoordinateFrame(name="detector", naxes=3, axes_order=(0, 1, 2), axes_type=("pixel", "pixel", "pixel"), axes_names=("x", "y", "z"), unit=(u.pix, u.pix, u.pix)) return wcs.WCS(forward_transform=identity, output_frame=frame, input_frame=detector_frame)
def spi_to_j2000(spi_coord, j2000_frame): """ """ sc_matrix = _construct_sc_matrix(spi_coord.scx_ra, spi_coord.scx_dec, spi_coord.scy_ra, spi_coord.scy_dec, spi_coord.scz_ra, spi_coord.scz_dec) # X,Y,Z = gbm_coord.cartesian pos = spi_coord.cartesian.xyz.value X0 = np.dot(sc_matrix[:, 0], pos) X1 = np.dot(sc_matrix[:, 1], pos) X2 = np.clip(np.dot(sc_matrix[:, 2], pos), -1., 1.) dec = np.pi / 2. - np.arccos(X2) # np.arcsin(X2) idx = np.logical_and(np.abs(X0) < 1E-6, np.abs(X1) < 1E-6) ra = np.zeros_like(dec) ra[~idx] = np.arctan2(X1[~idx], X0[~idx]) % (2 * np.pi) return coord.ICRS(ra=ra * u.radian, dec=dec * u.radian)
def test_simple(): c = coord.ICRS(coord.Angle(217.2141, u.degree), coord.Angle(-11.4351, u.degree)) c.transform_to(Sagittarius) c = coord.Galactic(coord.Angle(217.2141, u.degree), coord.Angle(-11.4351, u.degree)) c.transform_to(Sagittarius) c = Sagittarius(coord.Angle(217.2141, u.degree), coord.Angle(-11.4351, u.degree)) c.transform_to(coord.ICRS) c.transform_to(coord.Galactic) c = coord.Galactic(coord.Angle(217.2141, u.degree), coord.Angle(-11.4351, u.degree)) s = c.transform_to(Sagittarius) # with distance c = Sagittarius(coord.Angle(217.2141, u.degree), coord.Angle(-11.4351, u.degree), distance=15 * u.kpc) c.transform_to(coord.ICRS) c2 = c.transform_to(coord.Galactic) assert c2.distance.value == c.distance.value
def test_sanity(): rep1 = coord.CartesianRepresentation(x=[0, 1.], y=0, z=0, unit=u.pc) rep2 = coord.CartesianRepresentation(x=0, y=[0, 1.], z=0, unit=u.pc) rep3 = coord.CartesianRepresentation(x=0, y=0, z=[0, 1.], unit=u.pc) # Try for many origins: rnd = np.random.RandomState(seed=42) for _ in range(128): origin = coord.ICRS(ra=rnd.uniform(0, 360) * u.deg, dec=rnd.uniform(-90, 90) * u.deg, distance=rnd.uniform(10, 100) * u.pc) ref_c = ReferencePlaneFrame(rep1, origin=origin) icrs = ref_c.transform_to(coord.ICRS) assert icrs.dec[1] > icrs.dec[0] assert quantity_allclose(icrs.ra[0], icrs.ra[1]) ref_c = ReferencePlaneFrame(rep2, origin=origin) icrs = ref_c.transform_to(coord.ICRS) assert icrs.ra[1] > icrs.ra[0] ref_c = ReferencePlaneFrame(rep3, origin=origin) icrs = ref_c.transform_to(coord.ICRS) assert icrs.distance[0] > icrs.distance[1] assert quantity_allclose(icrs.ra[0], icrs.ra[1]) assert quantity_allclose(icrs.dec[0], icrs.dec[1])
def _generate_wcs_transform(dispaxis): """Create mock gwcs.WCS object for resampled s2d data""" detector = cf.Frame2D(name='detector', axes_order=(0, 1), unit=(u.pix, u.pix)) icrs = cf.CelestialFrame(name='icrs', reference_frame=coord.ICRS(), axes_order=(0, 1), unit=(u.deg, u.deg), axes_names=('RA', 'DEC')) spec = cf.SpectralFrame(name='spec', axes_order=(2, ), unit=(u.micron, ), axes_names=('lambda', )) world = cf.CompositeFrame(name="world", frames=[icrs, spec]) if dispaxis == 1: mapping = models.Mapping((0, 1, 0)) if dispaxis == 2: mapping = models.Mapping((0, 1, 1)) transform = mapping | (models.Const1D(42) & models.Const1D(42) & (models.Shift(30) | models.Scale(0.1))) pipeline = [(detector, transform), (world, None)] wcs = WCS(pipeline) return wcs
def test_footprint(): icrs = cf.CelestialFrame(name='icrs', reference_frame=coord.ICRS(), axes_order=(0, 1)) spec = cf.SpectralFrame(name='freq', unit=[ u.Hz, ], axes_order=(2, )) world = cf.CompositeFrame([icrs, spec]) transform = (models.Shift(10) & models.Shift(-1)) & models.Scale(2) pipe = [('det', transform), (world, None)] w = wcs.WCS(pipe) with pytest.raises(TypeError): w.footprint() w.bounding_box = ((1, 5), (1, 3), (1, 6)) assert_equal( w.footprint(), np.array([[11, 0, 2], [11, 0, 12], [11, 2, 2], [11, 2, 12], [15, 0, 2], [15, 0, 12], [15, 2, 2], [15, 2, 12]])) assert_equal(w.footprint(axis_type='spatial'), np.array([[11., 0.], [11., 2.], [15., 2.], [15., 0.]])) assert_equal(w.footprint(axis_type='spectral'), np.array([2, 12]))
def imaging(input_model, reference_files): """ The FGS imaging pipeline includes 3 coordinate frames - detector, focal plane and sky. reference_files={'distortion': 'jwst_fgs_distortioon_0001.asdf'} """ detector = cf.Frame2D(name='detector', axes_order=(0, 1), unit=(u.pix, u.pix)) v2v3 = cf.Frame2D(name='v2v3', axes_order=(0, 1), unit=(u.deg, u.deg)) world = cf.CelestialFrame(name='world', reference_frame=coord.ICRS()) # V2, V3 to sky tel2sky = pointing.v23tosky(input_model) subarray2full = subarray_transform(input_model) if reference_files: imdistortion = imaging_distortion(input_model, reference_files) distortion = subarray2full | imdistortion distortion.bounding_box = imdistortion.bounding_box del imdistortion.bounding_box else: distortion = subarray2full pipeline = [(detector, distortion), (v2v3, tel2sky), (world, None)] return pipeline
def imaging(input_model, reference_files): """ The NIRISS imaging WCS pipeline. It includes three coordinate frames - "detector" "v2v3" and "world". It uses the "distortion" reference file. """ detector = cf.Frame2D(name='detector', axes_order=(0, 1), unit=(u.pix, u.pix)) v2v3 = cf.Frame2D(name='v2v3', axes_order=(0, 1), unit=(u.arcsec, u.arcsec)) world = cf.CelestialFrame(reference_frame=coord.ICRS(), name='world') subarray2full = subarray_transform(input_model) imdistortion = imaging_distortion(input_model, reference_files) distortion = subarray2full | imdistortion distortion.bounding_box = imdistortion.bounding_box del imdistortion.bounding_box tel2sky = pointing.v23tosky(input_model) pipeline = [(detector, distortion), (v2v3, tel2sky), (world, None)] return pipeline