Ejemplo n.º 1
0
def test_distance_comparison():
    """Ensure comparisons of distances work (#2206, #2250)"""
    a = Distance(15 * u.kpc)
    b = Distance(15 * u.kpc)
    assert a == b
    c = Distance(1. * u.Mpc)
    assert a < c
Ejemplo n.º 2
0
def get_pc_per_arcsec(distance, cosmo=WMAP9):
    """

    Args:
        distance: float
            Distance in Mpc
        cosmo: astropy.cosmology
            Cosmology. Default is None: will then
            use the default_cosmology from astropy

    Returns:
        pc_per_arcsec: float
            Conversion parsec per arcsecond

    """
    from astropy.cosmology import default_cosmology
    from astropy.coordinates import Distance
    from astropy import units as u

    # Use default cosmology from astropy
    if cosmo is None:
        cosmo = default_cosmology.get()

    # Use astropy units
    dist = Distance(distance, u.Mpc)
    # get the corresponding redshift
    redshift = dist.compute_z(cosmo)
    # And nore the proper conversion
    kpc_per_arcmin = cosmo.kpc_proper_per_arcmin(redshift)
    return kpc_per_arcmin.to(u.pc / u.arcsec)
Ejemplo n.º 3
0
def test_distmod():

    d = Distance(10, u.pc)
    assert d.distmod.value == 0

    d = Distance(distmod=20)
    assert d.distmod.value == 20
    assert d.kpc == 100

    d = Distance(distmod=-1., unit=u.au)
    npt.assert_allclose(d.value, 1301442.9440836983)

    with pytest.raises(ValueError):
        d = Distance(value=d, distmod=20)

    with pytest.raises(ValueError):
        d = Distance(z=.23, distmod=20)

    # check the Mpc/kpc/pc behavior
    assert Distance(distmod=1).unit == u.pc
    assert Distance(distmod=11).unit == u.kpc
    assert Distance(distmod=26).unit == u.Mpc
    assert Distance(distmod=-21).unit == u.AU

    # if an array, uses the mean of the log of the distances
    assert Distance(distmod=[1, 11, 26]).unit == u.kpc
Ejemplo n.º 4
0
Archivo: rad.py Proyecto: ezanatta/MLE
    def correct_rgc(coord,
                    glx_ctr=ICRS('00h42m44.33s +41d16m07.5s'),
                    glx_PA=Angle('37d42m54s'),
                    glx_incl=Angle('77.5d'),
                    glx_dist=Distance(783, unit=u.kpc)):
        """Computes deprojected galactocentric distance.
        Inspired by: http://idl-moustakas.googlecode.com/svn-history/
            r560/trunk/impro/hiiregions/im_hiiregion_deproject.pro
        Parameters
        ----------
        coord : :class:`astropy.coordinates.ICRS`
            Coordinate of points to compute galactocentric distance for.
            Can be either a single coordinate, or array of coordinates.
        glx_ctr : :class:`astropy.coordinates.ICRS`
            Galaxy center.
        glx_PA : :class:`astropy.coordinates.Angle`
            Position angle of galaxy disk.
        glx_incl : :class:`astropy.coordinates.Angle`
            Inclination angle of the galaxy disk.
        glx_dist : :class:`astropy.coordinates.Distance`
            Distance to galaxy.
        Returns
        -------
        obj_dist : class:`astropy.coordinates.Distance`
            Galactocentric distance(s) for coordinate point(s).
        """
        # distance from coord to glx centre
        sky_radius = glx_ctr.separation(coord)
        avg_dec = 0.5 * (glx_ctr.dec + coord.dec).radian
        x = (glx_ctr.ra - coord.ra) * np.cos(avg_dec)
        y = glx_ctr.dec - coord.dec
        if x == Angle('0d00m00s'):
            x = Angle('0d00m0.0001s')
        # azimuthal angle from coord to glx  -- not completely happy with this
        phi = glx_PA - Angle('90d') \
                + Angle(np.arctan(y.arcsec / x.arcsec), unit=u.rad)

        # convert to coordinates in rotated frame, where y-axis is galaxy major
        # ax; have to convert to arcmin b/c can't do sqrt(x^2+y^2) when x and y
        # are angles
        xp = (sky_radius * np.cos(phi.radian)).arcmin
        yp = (sky_radius * np.sin(phi.radian)).arcmin

        # de-project
        ypp = yp / np.cos(glx_incl.radian)
        obj_radius = np.sqrt(xp**2 + ypp**2)  # in arcmin
        obj_dist = Distance(Angle(obj_radius, unit=u.arcmin).radian * glx_dist,
                            unit=glx_dist.unit)

        # Computing PA in disk (unused)
        #    obj_phi = Angle(np.arctan(ypp / xp), unit=u.rad)
        # TODO Zero out very small angles, i.e.
        # if np.abs(Angle(xp, unit=u.arcmin)) < Angle(1e-5, unit=u.rad):
        #     obj_phi = Angle(0.0)

        return xp, obj_dist
Ejemplo n.º 5
0
def test_parallax():

    d = Distance(parallax=1 * u.arcsecond)
    assert d.pc == 1.

    with pytest.raises(ValueError):
        d = Distance(15 * u.pc, parallax=20 * u.milliarcsecond)

    with pytest.raises(ValueError):
        d = Distance(parallax=20 * u.milliarcsecond, distmod=20)

    # array
    plx = [1, 10, 100.] * u.mas
    d = Distance(parallax=plx)
    assert quantity_allclose(d.pc, [1000., 100., 10.])
    assert quantity_allclose(plx, d.parallax)

    # check behavior for negative parallax
    with pytest.raises(ValueError):
        Distance(parallax=-1 * u.mas)

    with pytest.raises(ValueError):
        Distance(parallax=[10, 1, -1] * u.mas)

    with pytest.warns(AstropyWarning):
        Distance(parallax=-1 * u.mas, allow_negative=True)

    with pytest.warns(AstropyWarning):
        Distance(parallax=[10, 1, -1] * u.mas, allow_negative=True)

    # Regression test for #12569; `unit` was ignored if `parallax` was given.
    d = Distance(parallax=1 * u.mas, unit=u.kpc)
    assert d.value == 1.
    assert d.unit is u.kpc
def cross_match_umachine_sdss_meert15_with_meert15(mpc_match_dist_cut=1.7,
                                                   umachine_sdss_fname=None,
                                                   meert15_dir=None,
                                                   verbose=False):
    """
    Examples
    --------
    >>> result = cross_match_umachine_sdss_meert15_with_meert15()
    """
    if umachine_sdss_fname is None:
        umachine_sdss_dirname = "/Users/aphearin/work/sdss/cross_matched_catalogs"
        umachine_sdss_basename = "umachine_sdss_dr10_value_added_bt.hdf5"
        umachine_sdss_fname = os.path.join(umachine_sdss_dirname,
                                           umachine_sdss_basename)
    umachine_sdss = Table.read(umachine_sdss_fname, path='data')

    meert15_sdss = load_meert15(datadir=meert15_dir)

    #  Cross-match the two catalogs on ra and dec
    meert15_sdss_coords = SkyCoord(ra=meert15_sdss['ra'] * u.degree,
                                   dec=meert15_sdss['dec'] * u.degree,
                                   distance=Distance(z=meert15_sdss['z']))

    umachine_sdss_coords = SkyCoord(ra=umachine_sdss['ra'] * u.degree,
                                    dec=umachine_sdss['dec'] * u.degree,
                                    distance=Distance(z=umachine_sdss['z']))

    idx, d2d, d3d = umachine_sdss_coords.match_to_catalog_3d(
        meert15_sdss_coords)
    cross_matched_meert15_sdss = meert15_sdss[idx]

    good_match_mask = d3d.value <= mpc_match_dist_cut
    num_good_matches = len(d3d[good_match_mask])
    if verbose:
        print(
            "Fraction of objects in umachine catalog with a clean match = {0:.2f}"
            .format(num_good_matches / float(len(d3d))))

    umachine_sdss['has_meert15_match'] = 0
    umachine_sdss['has_meert15_match'][good_match_mask] = 1

    keys_to_inherit = ('r50_magr_kpc', 'Magr_tot', 'Magr_bulge', 'Magr_disk',
                       'gr_bulge', 'gr_disk', 'morph_type_T', 'gr_kcorr',
                       'bulge_to_total_rband', 'logsm_bell03')

    for key in keys_to_inherit:
        umachine_sdss[key + '_meert15'] = np.nan
        umachine_sdss[key + '_meert15'][
            good_match_mask] = cross_matched_meert15_sdss[key][good_match_mask]

    return umachine_sdss
Ejemplo n.º 7
0
def test_parallax():

    d = Distance(parallax=1 * u.arcsecond)
    assert d.pc == 1.

    with pytest.raises(ValueError):
        d = Distance(15 * u.pc, parallax=20 * u.milliarcsecond)

    with pytest.raises(ValueError):
        d = Distance(parallax=20 * u.milliarcsecond, distmod=20)

    # array
    plx = [1, 10, 100.] * u.mas
    d = Distance(parallax=plx)
    assert quantity_allclose(d.pc, [1000., 100., 10.])
    assert quantity_allclose(plx, d.parallax)

    # check behavior for negative parallax
    with pytest.raises(ValueError):
        Distance(parallax=-1 * u.mas)

    with pytest.raises(ValueError):
        Distance(parallax=[10, 1, -1] * u.mas)

    with catch_warnings(AstropyWarning) as w:
        Distance(parallax=-1 * u.mas, allow_negative=True)
    assert len(w) > 0

    with catch_warnings(AstropyWarning) as w:
        Distance(parallax=[10, 1, -1] * u.mas, allow_negative=True)
    assert len(w) > 0
Ejemplo n.º 8
0
 def r(self):
     '''Compute the distance of the rock from the center of the coordinate system'''
     if not hasattr(self, '_r'):
         if hasattr(self, '_position'):
             self.r = Distance(self.position.norm)
         else:
             rs = np.zeros(len(self))
             rs[self.e < 1] = self.a[self.e < 1] * \
                 (1 - self.e[self.e < 1] * np.cos(self.E[self.e < 1].rad))
             rs[self.e >= 1] = self.p[self.e >= 1] / \
                 (1 + self.e[self.e >= 1] *
                  np.cos(self.f[self.e >= 1]))
             self.r = Distance(rs, u.au)
     return self._r
Ejemplo n.º 9
0
def test_distances_scipy():
    """
    The distance-related tests that require scipy due to the cosmology
    module needing scipy integration routines
    """
    from astropy.cosmology import WMAP5

    # try different ways to initialize a Distance
    d4 = Distance(z=0.23)  # uses default cosmology - as of writing, WMAP7
    npt.assert_allclose(d4.z, 0.23, rtol=1e-8)

    d5 = Distance(z=0.23, cosmology=WMAP5)
    npt.assert_allclose(d5.compute_z(WMAP5), 0.23, rtol=1e-8)

    d6 = Distance(z=0.23, cosmology=WMAP5, unit=u.km)
    npt.assert_allclose(d6.value, 3.5417046898762366e+22)

    with pytest.raises(ValueError):
        Distance(cosmology=WMAP5, unit=u.km)

    with pytest.raises(ValueError):
        Distance()

    # vectors!  regression test for #11949
    d4 = Distance(z=[0.23, 0.45])  # as of writing, Planck18
    npt.assert_allclose(d4.z, [0.23, 0.45], rtol=1e-8)
Ejemplo n.º 10
0
def mk_mock_srch(radecfile, nzdictfile, Nsph, simul_cosmo):

    if simul_cosmo == "Planck":
        # First make h free
        Planck13.__init__(100.0, Planck13.Om0)
        cosmo = Planck13
    elif simul_cosmo == "WMAP":
        WMAP5.__init__(100.0, WMAP5.Om0)
        cosmo = WMAP5
    comv = cosmo.comoving_distance

    radecarr = h5_arr(radecfile, "good_pts")
    nzdict = json.load(open(nzdictfile))

    Nrands = radecarr.shape[0]
    Narrs = Nsph / Nrands
    remain = Nsph % Nrands

    radecz = np.zeros((Nsph, 3))

    for i in range(Narrs):

        start = Nrands * i
        stop = Nrands * (i + 1)
        radecz[start:stop, :2] = radecarr[:, :]

    endchunk = Nrands * (Narrs)
    radecz[endchunk:, :2] = radecarr[:remain, :]

    rad = np.arange(1.0, 67.0, 5.0)
    zlo = nzdict["zlo"]
    zhi = nzdict["zhi"]

    radeczlist = len(rad) * [radecz]

    for r_i, r in enumerate(rad):

        dis_near = Distance(comv(zlo) + r, u.Mpc)
        dis_far = Distance(comv(zhi) - r, u.Mpc)

        z_a = dis_near.compute_z(cosmology=cosmo)

        z_b = dis_far.compute_z(cosmology=cosmo)

        randz = (z_a ** 3 + \
                 (z_b ** 3 - z_a ** 3) * np.random.rand(Nsph)) ** (1. / 3.)

        radeczlist[r_i][:, 2] = randz[:]

        arr2h5(radeczlist[r_i], "{0}/{1}/mocks/mock_srch_pts.hdf5".format(os.path.dirname(radecfile), simul_cosmo), "radecz_{0}".format(str(r_i * 5 + 1)))
Ejemplo n.º 11
0
def test_negative_distance():
    """ Test optional kwarg allow_negative """

    with pytest.raises(ValueError):
        Distance([-2, 3.1], u.kpc)

    with pytest.raises(ValueError):
        Distance([-2, -3.1], u.kpc)

    with pytest.raises(ValueError):
        Distance(-2, u.kpc)

    d = Distance(-2, u.kpc, allow_negative=True)
    assert d.value == -2
Ejemplo n.º 12
0
def geocent(geolong, geolat, height) :

# computes the geocentric coordinates from the geodetic 
# (standard map-type) longitude, latitude, and height. 
# Notation generally follows 1992 Astr Almanac, p. K11 */
# NOTE that if you replace "geolong" with the local sidereal
# time, this automatically gives you XYZ in the equatorial frame
# of date.
# In this version, geolong and geolat are assumed to be 
# Angles and height is assumed to be in meters; returns 
# a triplet of explicit Distances.

        denom = (1. - thorconsts.FLATTEN) * np.sin(geolat)
        denom = np.cos(geolat) * np.cos(geolat) + denom*denom;
        C_geo = 1. / np.sqrt(denom);
        S_geo = (1. - thorconsts.FLATTEN) * (1. - thorconsts.FLATTEN) * C_geo;
        C_geo = C_geo + height / thorconsts.EQUAT_RAD;  
              #  deviation from almanac notation -- include height here. 
        S_geo = S_geo + height / thorconsts.EQUAT_RAD;
        distancemultiplier = Distance(thorconsts.EQUAT_RAD, unit = u.m)
        x_geo = thorconsts.EQUAT_RAD * C_geo * np.cos(geolat) * np.cos(geolong)
        y_geo = thorconsts.EQUAT_RAD * C_geo * np.cos(geolat) * np.sin(geolong)
        z_geo = thorconsts.EQUAT_RAD * S_geo * np.sin(geolat)
 
        return x_geo,y_geo,z_geo
Ejemplo n.º 13
0
    def estimate_mag(self):
        '''
        Estimate the apparent magnitude of a TNO
        https://iopscience.iop.org/article/10.3847/1538-3881/ab18a9/pdf for light curves
        '''
        e = earth.at(self.epoch)
        s = sun.at(self.epoch)

        x_helio = self.x + e.x - s.x
        y_helio = self.y + e.y - s.y
        z_helio = self.z + e.z - s.z

        r_helio = Distance(
            sqrt(x_helio * x_helio + y_helio * y_helio +
                 z_helio * z_helio).value, u.au)

        earth_dist = ((e.x - s.x)**2 + (e.y - s.y)**2 + (e.z - s.z)**2)**0.5

        q = (r_helio.au**2 + self.delta.au**2 - earth_dist.value) / \
            (2 * r_helio.au * self.delta.au)

        # pyephem
        beta = arccos(q)
        beta[where(q <= -1)[0]] = pi * u.rad
        beta[where(q >= 1)[0]] = 0 * u.rad

        Psi_1 = exp(-3.332 * tan(beta / 2)**0.631)
        Psi_2 = exp(-1.862 * tan(beta / 2)**1.218)
        mag = self.H + 5 * log10(r_helio.au * self.delta.au)

        not_zero = where((Psi_1 != 0) | (Psi_2 != 0))[0]
        mag[not_zero] -= 2.5 * log10((1 - self.G[not_zero]) * Psi_1[not_zero] +
                                     self.G[not_zero] * Psi_2[not_zero])

        return mag
Ejemplo n.º 14
0
def radecz_skymap(npoints=1, skymap={}):
    """
    """
    if not HEALPY_IMPORTED:
        raise ImportError(
            "healpy could not be imported. Please make sure it is installed.")

    prob = skymap["prob"]
    prob[~np.isfinite(skymap["distmu"])] = 0.
    prob[skymap["distmu"] < 0.] = 0.
    npix = len(prob)
    nside = hp.npix2nside(npix)
    prob = prob / np.sum(prob)
    distn = scipy.stats.rv_discrete(values=(np.arange(npix), prob))
    ipix = distn.rvs(size=npoints)
    ra, dec = hp.pix2ang(nside, ipix, lonlat=True)

    zs = []
    for ii in ipix:
        dist = -1
        while (dist < 0):
            dist = norm(skymap["distmu"][ii], skymap["distsigma"][ii]).rvs()
        zs.append(Distance(dist * u.Mpc).z)
    zs = np.array(zs)

    return ra, dec, zs
Ejemplo n.º 15
0
def load_select_effect(sel_func_name,sel_priors,num_sel):

	if sel_func_name == False or sel_func_name == 'False': sel_func = lambda *x : 1.
	else: sel_func = get_select_func(sel_func_name)
	
	m1lb,m1ub,m2lb,m2ub,dllb,dlub = [float(val) for val in (sel_priors).split(',')]
	
	m1_u = np.random.uniform(m1lb,m1ub,num_sel)
	m2_u = np.random.uniform(m2lb,m2ub,num_sel)
	dl_select = np.random.uniform(dllb,dlub,num_sel)
	z_select = [Distance(dL,unit=u.Mpc).compute_z(cosmology=cosmo) for dL in dl_select]
	
	m1_select = []
	m2_select = []
	for m1u,m2u in zip(m1_u,m2_u):
		while m1u < m2u:
			m1u = np.random.uniform(m1lb,m1ub,1)[0]
			m2u = np.random.uniform(m2lb,m2ub,1)[0]
			
		m1_select += [m1u]
		m2_select += [m2u]
	
	sel_samps = [np.array(m1_select), np.array(m2_select), np.array(dl_select), np.array(z_select)] # uniform m1,m2,dl samples subject to m1 > m2

	return sel_func, sel_samps
Ejemplo n.º 16
0
def coordinate_propagator(ra, dec, parallax, pmra, pmdec, ref_epoch,
                          target_epoch, tic_id):
    '''Authors:
		Patrick Tamburo, Boston University, July 2020
	Purpose:
        Given a target's position, parallax, proper motion, and reference epoch, propagate space motion to target epoch. 
        See https://docs.astropy.org/en/stable/coordinates/apply_space_motion.html for more examples. 
	Inputs:
        ra (float): The target's DECIMAL RA at your reference epoch
        dec (float): The target's DECIMAL Dec at your reference epoch 
        parallax (float): The target's parallax in milliarcsec
        pmra (flaot): The target's RA proper motion in milliarcsec/year
        pmdec (float): The target's Dec proper motion in millarcsec/year
        ref_epoch (float): Decimal year representing the epoch when coordinates, parallax, and proper motions were measured (e.g., 2015.5 for Gaia measurements)
        target_epoch (str): A string representing the epoch you want to propagate motion to (e.g., '2019-09-25')
        tic_id (str): The target's TIC ID (e.g., 'TIC 326109505')
    Outputs:
        new_ra, new_dec (float): The propagated position of the target at target_epoch.
	TODO:
    '''
    c = SkyCoord(ra=ra * u.deg,
                 dec=dec * u.deg,
                 distance=Distance(parallax=parallax * u.mas),
                 pm_ra_cosdec=pmra * u.mas / u.yr,
                 pm_dec=pmdec * u.mas / u.yr,
                 obstime=Time(ref_epoch, format='decimalyear'))
    target_obstime = Time(target_epoch)
    c_target_epoch = c.apply_space_motion(
        target_obstime)  #Apply space motion to TESS epoch
    new_ra = c_target_epoch.ra.value
    new_dec = c_target_epoch.dec.value
    return new_ra, new_dec
Ejemplo n.º 17
0
def mk_coords(radecfile, outfile, cosmology):

    # Set the cosmology with h free
    if cosmology == "Planck":
        Planck13.__init__(100.0, Planck13.Om0)
        cosmo = Planck13
    elif cosmology == "WMAP":
        WMAP5.__init__(100.0, WMAP5.Om0)
        cosmo = WMAP5

    f_in = h5.File(radecfile)
    radecz = f_in["radecz"]

    f_out = h5.File(outfile)
    cart = f_out.create_dataset("cart_pts",
                                shape=(radecz.shape[0], 3),
                                dtype='float64')

    for i in range(radecz.shape[0]):
        ra = Angle(radecz[i, 0], u.deg)
        dec = Angle(radecz[i, 1], u.deg)

        losd = cosmo.comoving_distance(radecz[i, 2])
        dis = Distance(losd)

        coord = ICRSCoordinates(ra, dec, distance=dis)

        cart[i, :] = np.array([coord.x, coord.y, coord.z])

    f_in.close()
    f_out.close()
Ejemplo n.º 18
0
    def luminosity(self):
        '''Takes the SED that was fit to the data and calcualtes the luminosity of the galaxy'''

        T_mcmc,beta_mcmc,log_A_mcmc = self.param_vals()

        int_wvs = np.arange(15,1000,0.001) * 1e-6
        int_nus = list(_c/int_wvs)
        int_nus.reverse()
        int_nus_1 = np.array(int_nus)
        int_fluxes = list(bb(int_wvs,T_mcmc[0],beta_mcmc[0],10**(log_A_mcmc[0])))
        int_fluxes.reverse()
        int_fluxes_1 = np.array(int_fluxes)

        integrated_flux = simps(int_fluxes_1,int_nus_1) * 1e-26
        print integrated_flux, 'integrated flux'

        dl = Distance(z = self.z).value * 3.086 * 1e22

        L = 4*np.pi*(dl**2)*integrated_flux

        L_sun  = constants.L_sun.value

        L_L_sun = L/L_sun

        Ls = {}
        Ls['L_IR'] = L
        Ls['L_IR/L_sun'] = L_L_sun

        return Ls
Ejemplo n.º 19
0
def test_distance_change():

    ra = Longitude("4:08:15.162342", unit=u.hour)
    dec = Latitude("-41:08:15.162342", unit=u.degree)
    c1 = ICRS(ra, dec, Distance(1, unit=u.kpc))

    oldx = c1.cartesian.x.value
    assert (oldx - 0.35284083171901953) < 1e-10

    # first make sure distances are immutible
    with pytest.raises(AttributeError):
        c1.distance = Distance(2, unit=u.kpc)

    # now x should increase with a bigger distance increases
    c2 = ICRS(ra, dec, Distance(2, unit=u.kpc))
    assert c2.cartesian.x.value == oldx * 2
Ejemplo n.º 20
0
def cut_Teff_Mann_on_Mks(df):
    '''
    Apply the Mks cuts that are given in Mann+2015.
    '''
    # Find distances:
    dft = df.loc[:,df.columns.str.contains("Gaia")].rename(columns = lambda x : str(x)[:-5])
    dft = calculate_distance_from_parallax(dft, check_GoF=False)

    #Convert to distance modulus:
    dft["distmod"] = Distance(np.abs(dft.distance.values), u.pc).distmod

    #Calculate Mks
    dft["Mks"] = df.K_2MASS - dft.distmod

    # Do the cuts:
    teffmann = df.loc[:,df.columns.str.startswith('Teff_Mann')].columns.values
    e_teffmann = df.loc[:,df.columns.str.startswith('e_Teff_Mann')].columns.values
    for col, e_col in zip(teffmann, e_teffmann):
        #print("misfits mks: ",
        #      df.loc[(dft["Mks"] > 9.8), col].shape[0],
        #      df.loc[(dft["Mks"] < 4.6),col].shape[0],
        #      df.loc[dft.Mks.isnull(), col].shape[0])
        df.loc[((dft["Mks"] > 9.8) | (dft["Mks"] < 4.6) | dft.Mks.isnull()), [col, e_col]] = np.nan
#

    return df
Ejemplo n.º 21
0
    def plot_isoc_grid_ages(self, ax, band1, band2, show_cb=False, cb_ax=None):
        isoc_set = get_demo_age_grid(
            **dict(isoc_kind='parsec_CAF09_v1.2S', photsys_version='yang'))
        cmap = cubehelix.cmap(startHue=240,
                              endHue=-300,
                              minSat=1,
                              maxSat=2.5,
                              minLight=.3,
                              maxLight=.8,
                              gamma=.9)
        norm = mpl.colors.Normalize(vmin=7., vmax=10.1)
        scalar_map = mpl.cm.ScalarMappable(norm=norm, cmap=cmap)
        scalar_map.set_array(np.array([isoc.age for isoc in isoc_set]))

        d = Distance(785 * u.kpc)
        for isoc in isoc_set:
            ax.plot(isoc[band1] - isoc[band2],
                    isoc[band2] + d.distmod.value,
                    c=scalar_map.to_rgba(np.log10(isoc.age)),
                    lw=0.8)
        if show_cb:
            cb = plt.colorbar(mappable=scalar_map,
                              cax=cb_ax,
                              ax=ax,
                              ticks=np.arange(6., 10.2))
            cb.set_label(r"log(age)")
Ejemplo n.º 22
0
    def __calc_H_from_mag(self, obscode):
        obs = self.observe(obscode=obscode)

        e = earth.at(self.epoch)
        s = sun.at(self.epoch)

        x_helio = self.x - s.x
        y_helio = self.y - s.y
        z_helio = self.z - s.z

        r_helio = Distance(
            np.sqrt(x_helio * x_helio + y_helio * y_helio +
                    z_helio * z_helio).value, u.au)
        earth_dist = ((e.x - s.x)**2 + (e.y - s.y)**2 + (e.z - s.z)**2)**0.5

        q = (r_helio.au**2 + obs.delta.au**2 -
             earth_dist.value**2) / (2 * r_helio.au * obs.delta.au)

        beta = np.arccos(q)
        beta[np.where(q <= -1)[0]] = np.pi * u.rad
        beta[np.where(q >= 1)[0]] = 0 * u.rad

        Psi_1 = np.exp(-3.332 * np.tan(beta / 2)**0.631)
        Psi_2 = np.exp(-1.862 * np.tan(beta / 2)**1.218)

        H = self.mag - 5 * np.log10(r_helio.au * obs.delta.au)

        not_zero = np.where((Psi_1 != 0) | (Psi_2 != 0))[0]
        H[not_zero] += 2.5 * np.log10(
            (1 - self.G[not_zero]) * Psi_1[not_zero] +
            self.G[not_zero] * Psi_2[not_zero])

        return H
Ejemplo n.º 23
0
def makeCoordsCol(TableName):
    global coordsCol
    coordsCol = SkyCoord(TableName['RA'],
                         TableName['DEC'],
                         unit=(u.degree, u.degree),
                         distance=Distance(TableName['DISTANCE'], u.pc),
                         frame='icrs')
Ejemplo n.º 24
0
    def dust_mass_A(self):

        T_mcmc, log_A_mcmc = self.param_vals()

        k = 0.192

        dl = Distance(z=self.z).value * 3.086 * 1e22

        M_sun = constants.M_sun.value

        md = (10**log_A_mcmc[0]) * (dl**2) * (1 / k) * 2.3 * 1e-11

        mass = md / M_sun

        # Get error on dust mass

        log_A_error = (log_A_mcmc[1] + log_A_mcmc[2]) / 2

        las_rand = np.random.normal(log_A_mcmc[0], log_A_error, 1000)

        md_rands = [(10**la) * (dl**2) * (1 / k) * 2.3 * 1e-11
                    for la in las_rand]

        m_e = np.std([m / M_sun for m in md_rands])

        Ms = {}
        Ms['M_dust/M_sun'] = mass
        Ms['M_error'] = m_e

        return Ms
Ejemplo n.º 25
0
def distance_to_theta(redshift, radius):
    R = Distance(z=redshift).to(u.kpc)
    try:
        radius = radius.to(u.kpc)
    except AttributeError:
        radius = radius * u.kpc
    return 2 * np.arcsin(radius / (2 * R))  # RADIUS MUST HAVE ASTROPY UNITS
Ejemplo n.º 26
0
Archivo: egs.py Proyecto: suchanek/PMA
def make_single_skycoord(stars, index):
    """create a SkyCoord object containing all of the Proper Motion parameters
    initialized from the input DataFrame (normal Gaia query result).

    Parameters:
        stars: normal Gaia DataFrame object

        index: the numeric index into the array that you want to retrieve and use

    Returns: a single SkyCoord object, representing the star of interest with
    Proper Motion params initialized.
    """
    pos = stars.iloc[index]
    ra = pos['ra'] * u.deg
    dec = pos['dec'] * u.deg
    pmra = pos['pmra'] * u.mas / u.yr
    pmdec = pos['pmdec'] * u.mas / u.yr
    distance = Distance(pos['parallax'] * u.mas, allow_negative=True)
    sc = SkyCoord(ra,
                  dec,
                  pm_ra_cosdec=pmra,
                  pm_dec=pmdec,
                  distance=distance,
                  frame='icrs')
    return sc
Ejemplo n.º 27
0
    def sed_flux(self, nu, z, mu_s):
        """Black Body SED generated by the SS Disk:

        .. math::
            \\nu F_{\\nu} \, [\mathrm{erg}\,\mathrm{cm}^{-2}\,\mathrm{s}^{-1}]
        
        ----------
        nu : :class:`~astropy.units.Quantity`
            array of frequencies, in Hz, to compute the sed, **note** these are 
            observed frequencies (observer frame).
        z : float
            redshift of the galaxy, to correct the observed frequencies and to 
            compute the flux once the distance is obtained
        mu_s : float
            cosine of the angle between the disk axis and the line of sight,
            same as the jet viewing angle
        """
        nu = nu.to("Hz").value * (1 + z)
        d_L = Distance(z=z).to("cm").value
        prefactor = 2 * np.pi * mu_s / np.power(d_L, 2)
        R = np.logspace(np.log10(self._R_in), np.log10(self._R_out)) * u.cm
        T = self.T(R)
        _R = R.value.reshape(R.size, 1)
        _T = T.value.reshape(T.size, 1)
        _nu = nu.reshape(1, nu.size)
        _integrand = _R * I_nu_bb(_nu, _T)
        return prefactor * nu * np.trapz(_integrand, R,
                                         axis=0) * u.Unit(SED_UNIT)
Ejemplo n.º 28
0
def dmod(redshift, distance=None):
    if distance is not None:
        dist = distance.to(parsec).value / 10.
    else:
        dist = Distance(z=redshift).parsec / 10.
    dm = 5 * np.log10(dist - 5)
    return dm
Ejemplo n.º 29
0
    def load_dsph_property(self,
                           dsph_name,
                           ra=None,
                           dec=None,
                           distance=None,
                           distance_err=None,
                           verbose=True):
        dsph_prop = ascii.read(__filedir__ +
                               "NearbyGalaxies.dat").to_pandas().set_index(
                                   "GalaxyName").loc[dsph_name]
        self.dsph_prop = dsph_prop
        _ra = "{}h{}m{}s".format(dsph_prop.RAh, dsph_prop.RAm,
                                 dsph_prop.RAs) if (ra is None) else ra
        _dec = "{}d{}m{}s".format(dsph_prop.DEd, dsph_prop.DEm,
                                  dsph_prop.DEs) if (dec is None) else dec
        _distance = Distance(
            distmod=dsph_prop["(m-M)o"]).pc if (distance is None) else distance
        self.dsph_prop_sc = SkyCoord(ra=_ra,
                                     dec=_dec,
                                     distance=_distance * u.pc)

        if verbose:
            print(self.dsph_prop_sc)

        if not distance_err is None:
            self.dsph_prop_sc.distance_err = distance_err
            print("distance_err = {}".format(distance_err))
Ejemplo n.º 30
0
def mk_mock_coords(radeczfile, outfile, simul_cosmo):

    if simul_cosmo == "Planck":
        Planck13.__init__(100.0, Planck13.Om0)
        cosmo = Planck13
    elif simul_cosmo == "WMAP":
        WMAP5.__init__(100.0, WMAP5.Om0)
        cosmo = WMAP5

    rad = np.arange(1.0, 67.0, 5.0)

    radecz = h5_arr(radeczfile, "radecz")

    cart = np.zeros(radecz.shape)

    for i, rdz in enumerate(radecz):

        ra = Angle(rdz[0], u.deg)
        dec = Angle(rdz[1], u.deg)

        losd = cosmo.comoving_distance(rdz[2])
        dis = Distance(losd)

        coord = ICRSCoordinates(ra, dec, distance=dis)

        cart[i, :] = np.array([coord.x.value, coord.y.value, coord.z.value])

    np.savetxt(outfile, cart)
Ejemplo n.º 31
0
def test_regression_10094():
    """
    Make sure that when we include the proper motion and radial velocity of
    a SkyCoord, our velocity corrections remain close to TEMPO2.

    We check that tau Ceti is within 5mm/s
    """
    # Wright & Eastman (2014) Table2
    # Corrections for tau Ceti
    wright_table = Table.read(
        download_file(
            'http://data.astropy.org/coordinates/wright_eastmann_2014_tau_ceti.fits'
        ))
    reduced_jds = wright_table['JD-2400000']
    tempo2 = wright_table['TEMPO2']
    barycorr = wright_table['BARYCORR']

    # tau Ceti Hipparchos data
    tauCet = SkyCoord('01 44 05.1275 -15 56 22.4006',
                      unit=(u.hour, u.deg),
                      pm_ra_cosdec=-1721.05 * u.mas / u.yr,
                      pm_dec=854.16 * u.mas / u.yr,
                      distance=Distance(parallax=273.96 * u.mas),
                      radial_velocity=-16.597 * u.km / u.s,
                      obstime=Time(48348.5625, format='mjd'))
    # CTIO location as used in Wright & Eastmann
    xyz = u.Quantity([1814985.3, -5213916.8, -3187738.1], u.m)
    obs = EarthLocation(*xyz)
    times = Time(2400000, reduced_jds, format='jd')
    tempo2 = tempo2 * speed_of_light
    barycorr = barycorr * speed_of_light
    astropy = tauCet.radial_velocity_correction(location=obs, obstime=times)

    assert_quantity_allclose(astropy, tempo2, atol=5 * u.mm / u.s)
    assert_quantity_allclose(astropy, barycorr, atol=5 * u.mm / u.s)
Ejemplo n.º 32
0
def vpf(dat_dir, Nsph, simul_cosmo, rad):

    # Grab the data coordinates
    gals = h5_arr("./dat/out/{0}/{1}/gals_cart_coords.hdf5".
                      format(dat_dir, simul_cosmo), "cart_pts")

    # Get details about the redshift interval being considered
    nbar_dict = json.load(open("./dat/out/{0}/{1}/nbar_zrange.json".
                                   format(dat_dir, simul_cosmo)))
    zlo = nbar_dict["zlo"]
    zhi = nbar_dict["zhi"]

    # Get the search points
    good_pts = h5_arr("./dat/out/{0}/srch_radec.hdf5".format(dat_dir), "good_pts")
    bad_pts = h5_arr("./dat/out/{0}/veto.hdf5".format(dat_dir),
                     "bad_pts")

    # Set angular radius of effective area around bad points
    bad_r = np.arccos(1.0 - (np.pi * 9.8544099e-05) / (2 * 180 ** 2))
    bad_r_deg = np.rad2deg(bad_r)

    # Set the cosmology with h free
    # Here the cosmology is based on WMAP (for first MultiDark simulation)
    if simul_cosmo == "Planck":
        # First make h free
        Planck13.__init__(100.0, Planck13.Om0)
        cosmo = Planck13
    elif simul_cosmo == "WMAP":
        WMAP5.__init__(100.0, WMAP5.Om0)
        cosmo = WMAP5
    comv = cosmo.comoving_distance

    # Build the trees

    # galaxy tree
    gal_baum = cKDTree(gals)

    # tree of bad points (angular coordinates on unit sphere)
    bad_xyz = radec2xyz(bad_pts)
    veto_baum = cKDTree(bad_xyz)

    # Initialise final output arrays
#    rad = np.arange(1.0, 67.0, 5.0)  doing it one radius at a time
#    P_0 = np.zeros(rad.shape)

    # No. of spheres and norm
#     Nsph_arr = Nsph * np.array(4 * [0.01] + 4 * [0.1] + 4 * [1.0])
#     norm = 1. / Nsph_arr
#    norm = 1. / Nsph

    rand_i = 0

    for r_i, r in enumerate(rad):

        # start the count of successful voids
        count = 0

        # Custom zrange for sphere size
        dis_near = Distance(comv(zlo).value + r, u.Mpc)
        dis_far = Distance(comv(zhi).value - r, u.Mpc)

        z_a = dis_near.compute_z(cosmology=cosmo)

        z_b = dis_far.compute_z(cosmology=cosmo)

        for i in range(Nsph):  # _arr[r_i]):

            # compensate for finite length of mask file
            rand_i = rand_i % 999999

            radec = good_pts[rand_i, :]

            rang = Angle(radec[0], u.deg)
            decang = Angle(radec[1], u.deg)

            randz = (z_a ** 3 + \
                     (z_b ** 3 - z_a ** 3) * np.random.rand(1)[0]) ** (1. / 3.)
            dis = Distance(comv(randz), u.Mpc)

            coord = ICRSCoordinates(rang, decang, distance=dis)

            sph_cen = np.array([coord.x.value, coord.y.value, coord.z.value])

            nn = gal_baum.query(sph_cen)

            print "rad: ", r, ", sphere: ", i

            if not nn[0] < r:

                # add instance to probability count
                count += 1

                # record quality of sphere using spline values for intersection
                # with bad points

                # Get radius of circular projection of sphere
                R = np.arcsin(r / np.sqrt(np.sum(sph_cen[:] ** 2)))

                # Get coordinates of circle centre on unit sphere
                crc_cen = radec2xyz(radec)[0]

                # Compute tree search radius from Cosine rule
                # (include points extending beyond sphere edge to account for
                # finite area around bad points)
                l_srch = np.sqrt(2. - 2. * np.cos(R))

                # Run search
                pierce_l = veto_baum.query_ball_point(crc_cen, l_srch)

                bad_vol = 0.

                R = np.degrees(R)  # need in degrees for bad_vol computation

                for pt in pierce_l:

                    pt_ang = bad_pts[pt]
                    dis = np.degrees(central_angle(pt_ang, radec))
                    l = dis / R

                    bad_vol += 1.5 * (bad_r_deg / R) ** 2 \
                                   * np.sqrt(1.0 - l ** 2)

                f_r = open("./dat/out/{0}/{1}/vpf_out/volfrac_{2}.dat".
                               format(dat_dir, simul_cosmo, r),
                           'a')
                f_r.write("{0}\n".format(bad_vol))
                f_r.close()

            rand_i += 1
def dist_to_z(D):
    return Distance.compute_z(D,cosmo)