Пример #1
0
def update(val):
      zL,zS = slzL.val,slzS.val
      xL,yL = slxL.val, slyL.val
      ML,eL,PAL = slML.val,sleL.val,slPAL.val
      sh,sha = slss.val,slsa.val
      xs,ys = slxs.val, slys.val
      Fs,ws = slFs.val, slws.val
      ns,ars,pas = slns.val,slars.val,slPAs.val
      newDd = cosmo.angular_diameter_distance(zL).value
      newDs = cosmo.angular_diameter_distance(zS).value
      newDds= cosmo.angular_diameter_distance_z1z2(zL,zS).value
      newLens = vl.SIELens(zLens,xL,yL,10**ML,eL,PAL)
      newShear = vl.ExternalShear(sh,sha)
      newSource = vl.SersicSource(zS,True,xs,ys,Fs,ws,ns,ars,pas)
      xs,ys = vl.LensRayTrace(xim,yim,[newLens,newShear],newDd,newDs,newDds)
      imbg = vl.SourceProfile(xim,yim,newSource,[newLens,newShear])
      imlensed = vl.SourceProfile(xs,ys,newSource,[newLens,newShear])
      caustics = vl.CausticsSIE(newLens,newDd,newDs,newDds,newShear)

      ax.cla()

      ax.imshow(imbg,cmap=cmbg,extent=[xim.min(),xim.max(),yim.min(),yim.max()],origin='lower')
      ax.imshow(imlensed,cmap=cmlens,extent=[xim.min(),xim.max(),yim.min(),yim.max()],origin='lower')
      mu = imlensed.sum()*(xim[0,1]-xim[0,0])**2 / newSource.flux['value']
      ax.text(0.9,1.02,'$\\mu$ = {0:.2f}'.format(mu),transform=ax.transAxes)

      #for i in range(caustics.shape[0]):
      #      ax.plot(caustics[i,0,:],caustics[i,1,:],'k-')
      for caustic in caustics:
      		ax.plot(caustic[:,0],caustic[:,1],'k-')

      f.canvas.draw_idle()
Пример #2
0
def create_modelimage(lens,source,xmap,ymap,xemit,yemit,indices,
      Dd=None,Ds=None,Dds=None,sourcedatamap=None):
      """
      Creates a model lensed image given the objects and map
      coordinates specified.  Supposed to be common for both
      image fitting and visibility fitting, so we don't need
      any data here.

      Returns:
      immap
            A 2D array representing the field evaluated at
            xmap,ymap with all sources included.
      mus:
            A numpy array of length N_sources containing the
            magnifications of each source (1 if unlensed).
      """
      
      lens = list(np.array([lens]).flatten()) # Ensure lens(es) are a list
      source = list(np.array([source]).flatten()) # Ensure source(s) are a list
      mus = np.zeros(len(source))
      immap, imsrc = np.zeros(xmap.shape), np.zeros(xemit.shape)

      # If we didn't get pre-calculated distances, figure them here assuming Planck15
      if np.any((Dd is None,Ds is None, Dds is None)):
            from astropy.cosmology import Planck15 as cosmo
            Dd = cosmo.angular_diameter_distance(lens[0].z).value
            Ds = cosmo.angular_diameter_distance(source[0].z).value
            Dds= cosmo.angular_diameter_distance_z1z2(lens[0].z,source[0].z).value

      # Do the raytracing for this set of lens & shear params
      xsrc,ysrc = LensRayTrace(xemit,yemit,lens,Dd,Ds,Dds)

      if sourcedatamap is not None: # ... then particular source(s) are specified for this map
            for jsrc in sourcedatamap:
                  if source[jsrc].lensed: 
                        ims = SourceProfile(xsrc,ysrc,source[jsrc],lens)
                        imsrc += ims
                        mus[jsrc] = ims.sum()*(xemit[0,1]-xemit[0,0])**2./source[jsrc].flux['value']
                  else: immap += SourceProfile(xmap,ymap,source[jsrc],lens); mus[jsrc] = 1.
      else: # Assume we put all sources in this map/field
            for j,src in enumerate(source):
                  if src.lensed: 
                        ims = SourceProfile(xsrc,ysrc,src,lens)
                        imsrc += ims
                        mus[j] = ims.sum()*(xemit[0,1]-xemit[0,0])**2./src.flux['value']
                  else: immap += SourceProfile(xmap,ymap,src,lens); mus[j] = 1.

      # Try to reproduce matlab's antialiasing thing; this uses a 3lobe lanczos low-pass filter
      imsrc = Image.fromarray(imsrc)
      resize = np.array(imsrc.resize((int(indices[1]-indices[0]),int(indices[3]-indices[2])),Image.ANTIALIAS))
      immap[indices[2]:indices[3],indices[0]:indices[1]] += resize

      # Flip image to match sky coords (so coordinate convention is +y = N, +x = W, angle is deg E of N)
      immap = immap[::-1,:]

      # last, correct for pixel size.
      immap *= (xmap[0,1]-xmap[0,0])**2.

      return immap,mus
Пример #3
0
def amplitude_of_best_fit_greybody(Trf = None, b = 2.0, Lrf = None, zin = None):
	'''
	Same as single_simple_flux_from_greybody, but to made an amplitude lookup table
	'''

	nsed = 1e4
	lambda_mod = loggen(1e3, 8.0, nsed) # microns
	nu_mod = c * 1.e6/lambda_mod # Hz

	#cosmo = Planck15#(H0 = 70.5 * u.km / u.s / u.Mpc, Om0 = 0.273)
	conversion = 4.0 * np.pi *(1.0E-13 * cosmo.luminosity_distance(zin) * 3.08568025E22)**2.0 / L_sun # 4 * pi * D_L^2    units are L_sun/(Jy x Hz)

	Lir = Lrf / conversion # Jy x Hz

	Ain = 1.0e-36 #good starting parameter
	betain =  b
	alphain=  2.0

	fit_params = Parameters()
	fit_params.add('Ain', value= Ain)

	#THE LM FIT IS HERE
	Pfin = minimize(sedint, fit_params, args=(nu_mod,Lir.value,Trf/(1.+zin),b,alphain))
	#pdb.set_trace()
	return Pfin.params['Ain'].value
Пример #4
0
def _configure(infiles, z, df):
    conf.infiles = infiles
    img_hdr = fits.getheader(conf.infiles[0])
    conf.nx = img_hdr['naxis1']
    conf.ny = img_hdr['naxis2']
    conf.nf = MWA_FREQ_EOR_ALL_80KHZ.size
    conf.dx = np.abs(img_hdr['cdelt1']) * np.pi / 180
    conf.dy = np.abs(img_hdr['cdelt2']) * np.pi / 180
    conf.df = df
    conf.du = 1 / (conf.nx * conf.dx)
    conf.dv = 1 / (conf.ny * conf.dy)
    conf.deta = 1 / (conf.nf * conf.df)
    conf.freq = MWA_FREQ_EOR_ALL_80KHZ
    conf.u = fftshift(fftfreq(conf.nx, conf.dx))
    conf.v = fftshift(fftfreq(conf.ny, conf.dy))
    conf.eta = fftshift(fftfreq(conf.nf, conf.df))
    conf.z = z
    conf.cosmo_d = Cosmo.comoving_transverse_distance(conf.z).value
    conf.cosmo_e = np.sqrt(Cosmo.Om0 * (1 + conf.z) ** 3 + Cosmo.Ok0 *
                           (1 + conf.z) ** 2 + Cosmo.Ode0)
    conf.cosmo_h0 = Cosmo.H0.value * 1e3
    conf.cosmo_c = const.si.c.value
    conf.kx = conf.u * 2 * np.pi / conf.cosmo_d
    conf.ky = conf.v * 2 * np.pi / conf.cosmo_d
    conf.dkx = conf.du * 2 * np.pi / conf.cosmo_d
    conf.dky = conf.dv * 2 * np.pi / conf.cosmo_d
    conf.k_perp = np.sqrt(conf.kx ** 2 + conf.ky[np.newaxis, ...].T ** 2)
    conf.k_par = conf.eta * 2 * np.pi * conf.cosmo_h0 * _F21 * \
        conf.cosmo_e / (conf.cosmo_c * (1 + conf.z) ** 2)
Пример #5
0
def gen_wedge_psf(nx, ny, nf, dx, dy, df, z, out, threads=None):
    u = fftshift(fftfreq(nx, dx * np.pi / 180))
    v = fftshift(fftfreq(ny, dy * np.pi / 180))
    e = fftshift(fftfreq(nf, df))

    E = np.sqrt(Cosmo.Om0 * (1 + z) ** 3 +
                Cosmo.Ok0 * (1 + z) ** 2 + Cosmo.Ode0)
    D = Cosmo.comoving_transverse_distance(z).value
    H0 = Cosmo.H0.value * 1e3
    c = const.c.value
    print(E, D, H0)
    kx = u * 2 * np.pi / D
    ky = v * 2 * np.pi / D
    k_perp = np.sqrt(kx ** 2 + ky[np.newaxis, ...].T ** 2)
    k_par = e * 2 * np.pi * H0 * f21 * E / (c * (1 + z) ** 2)
    arr = np.ones((nf, nx, ny), dtype='complex128')
    for i in range(nf):
        mask = (k_perp > np.abs(k_par[i]) * c * (1 + z) / (H0 * E * D))
        arr[i][mask] = 0
    np.save('kx.npy', kx)
    np.save('ky.npy', ky)
    np.save('kpar.npy', k_par)
    np.save('wedge_window.npy', arr.real)
    fft_arr = fftshift(fftn(ifftshift(arr))).real
    hdu = fits.PrimaryHDU(data=fft_arr)
    hdr_dict = dict(cdelt1=dx, cdelt2=dy, cdelt3=df,
                    crpix1=nx/2, crpix2=ny/2, crpix3=nf/2,
                    crval1=0, crval2=0, crval3=0,
                    ctype1='RA---SIN', ctype2='DEC--SIN', ctype3='FREQ',
                    cunit1='deg', cunit2='deg', cunit3='Hz')
    for k, v in hdr_dict.items():
        hdu.header[k] = v
    hdu.writeto(out, clobber=True)
Пример #6
0
    def hmp(self, z=0):
        """Generating halo mass profiles

        Parameters
        ----------
        z : float
            Redshift of the snapshot
        """

        rhocrit = Planck15.critical_density(z).to(units.Msun / units.kpc**3) \
                  / (Planck15.H(z) / 100)

        for i in range(len(self.params)):
            _input = self.params[i]
            halos = _input['rockstar'].binnedhalos[_input['bin']]

            _input['hmp'] = MyHMP(
                halos,
                _input['gadget'].data,
                float(_input['rockstar'].header['Particle_mass'][0]))


            rmin = _input['rockstar'].header['Softening_length'] / 2.0
            rmax = 2 * np.max(halos['rvir'])
            _input['rockstar'].binnedhalos['mean_rvir'] = sum(halos['rvir']) \
                                                          / len(halos['rvir'])
            rbins = np.logspace(np.log10(rmin), np.log10(rmax), num=50, base=10)

            _input['hmp'].hmp(rbins, rhocrit.value)
Пример #7
0
def simple_flux_from_greybody(lambdavector, Trf = None, b = None, Lrf = None, zin = None, ngal = None):
	'''
	Return flux densities at any wavelength of interest (in the range 1-10000 micron),
	assuming a galaxy (at given redshift) graybody spectral energy distribution (SED),
	with a power law replacing the Wien part of the spectrum to account for the
	variability of dust temperatures within the galaxy. The two different functional
	forms are stitched together by imposing that the two functions and their first
	derivatives coincide. The code contains the nitty-gritty details explicitly.

	Inputs:
	alphain = spectral index of the power law replacing the Wien part of the spectrum, to account for the variability of dust temperatures within a galaxy [default = 2; see Blain 1999 and Blain et al. 2003]
	betain = spectral index of the emissivity law for the graybody [default = 2; see Hildebrand 1985]
	Trf = rest-frame temperature [in K; default = 20K]
	Lrf = rest-frame FIR bolometric luminosity [in L_sun; default = 10^10]
	zin = galaxy redshift [default = 0.001]
	lambdavector = array of wavelengths of interest [in microns; default = (24, 70, 160, 250, 350, 500)];

	AUTHOR:
	Lorenzo Moncelsi [[email protected]]

	HISTORY:
	20June2012: created in IDL
	November2015: converted to Python
	'''

	nwv = len(lambdavector)
	nuvector = c * 1.e6 / lambdavector # Hz

	nsed = 1e4
	lambda_mod = loggen(1e3, 8.0, nsed) # microns
	nu_mod = c * 1.e6/lambda_mod # Hz

	#Lorenzo's version had: H0=70.5, Omega_M=0.274, Omega_L=0.726 (Hinshaw et al. 2009)
	#cosmo = Planck15#(H0 = 70.5 * u.km / u.s / u.Mpc, Om0 = 0.273)
	conversion = 4.0 * np.pi *(1.0E-13 * cosmo.luminosity_distance(zin) * 3.08568025E22)**2.0 / L_sun # 4 * pi * D_L^2    units are L_sun/(Jy x Hz)

	Lir = Lrf / conversion # Jy x Hz

	Ain = np.zeros(ngal) + 1.0e-36 #good starting parameter
	betain =  np.zeros(ngal) + b
	alphain=  np.zeros(ngal) + 2.0

	fit_params = Parameters()
	fit_params.add('Ain', value= Ain)
	#fit_params.add('Tin', value= Trf/(1.+zin), vary = False)
	#fit_params.add('betain', value= b, vary = False)
	#fit_params.add('alphain', value= alphain, vary = False)

	#pdb.set_trace()
	#THE LM FIT IS HERE
	#Pfin = minimize(sedint, fit_params, args=(nu_mod,Lir.value,ngal))
	Pfin = minimize(sedint, fit_params, args=(nu_mod,Lir.value,ngal,Trf/(1.+zin),b,alphain))

	#pdb.set_trace()
	flux_mJy=sed(Pfin.params,nuvector,ngal,Trf/(1.+zin),b,alphain)

	return flux_mJy
Пример #8
0
def update(val):
      zL,zS = slzL.val,slzS.val
      xL,yL = slxL.val, slyL.val
      ML,eL,PAL = slML.val,sleL.val,slPAL.val
      sh,sha = slss.val,slsa.val
      newDd = cosmo.angular_diameter_distance(zL).value
      newDs = cosmo.angular_diameter_distance(zS).value
      newDds= cosmo.angular_diameter_distance_z1z2(zL,zS).value
      newLens = vl.SIELens(zLens,xL,yL,10**ML,eL,PAL)
      newShear = vl.ExternalShear(sh,sha)
      xsource,ysource = vl.LensRayTrace(xim,yim,[newLens,newShear],newDd,newDs,newDds)
      caustics = vl.get_caustics([newLens,newShear],newDd,newDs,newDds)
      ax.cla()
      ax.plot(xsource,ysource,'b-')
      for caustic in caustics:
            ax.plot(caustic[:,0],caustic[:,1],'k-')
      #ax.set_xlim(-0.5,0.5)
      #ax.set_ylim(-0.5,0.5)
      #for i in range(len(xs)):
      #      p[i].set_xdata(xs[i])
      #      p[i].set_ydata(ys[i])
      f.canvas.draw_idle()
Пример #9
0
def measure_sfrd(stacked_object, area_deg=1.62, tsfrd=False, cosmo=cosmo):
	if area_deg == 1.62:
		print 'defaulting to uVista/COSMOS area of 1.62deg2'
	area_sr = area_deg * (3.1415926535 / 180.)**2
	sfrd = np.zeros(np.shape(stacked_object.simstack_nuInu_array))
	for i in range(stacked_object.nz):
		zn = stacked_object.z_nodes[i:i+2]
		z_suf = '{:.2f}'.format(zn[0])+'-'+'{:.2f}'.format(zn[1])
		vol = cosmo.comoving_volume(zn[1]) - cosmo.comoving_volume(zn[0])
		for iwv in range(stacked_object.nw):
			for j in range(stacked_object.nm):
				mn = stacked_object.m_nodes[j:j+2]
				m_suf = '{:.2f}'.format(mn[0])+'-'+'{:.2f}'.format(mn[1])
				for p in range(stacked_object.npops):
					arg = clean_args('z_'+z_suf+'__m_'+m_suf+'_'+stacked_object.pops[p])
					ng = len(stacked_object.bin_ids[arg])
					sfr = conv_lir_to_sfr * stacked_object.simstack_flux_array[iwv,i,j,p]
					sfrd[iwv,i,j,p] += float(ng) / area_sr * sfr
	if tsfrd == True:
		return np.sum(np.sum(np.sum(sfrd,axis=1),axis=1),axis=1)
	else:
		return sfrd
Пример #10
0
	def get_sf_qt_mass_lookback_time_bins(self, tnodes, mnodes):
		self.id_lookt_mass = {}
		age_universe = cosmo.age(0).value # 13.797617455819209 Gyr
		znodes = np.array([z_at_value(cosmo.age,(age_universe - i) * u.Gyr) for i in tnodes])

		for iz in range(len(znodes[:-1])):
			for jm in range(len(mnodes[:-1])):
				ind_mt_sf =( (self.table.sfg == 1) & (self.table[self.zkey] >= np.min(znodes[iz:iz+2])) & (self.table[self.zkey] < np.max(znodes[iz:iz+2])) &
					(10**self.table[self.mkey] >= 10**np.min(mnodes[jm:jm+2])) & (10**self.table[self.mkey] < 10**np.max(mnodes[jm:jm+2])) )
				ind_mt_qt =( (self.table.sfg == 0) & (self.table[self.zkey] >= np.min(znodes[iz:iz+2])) & (self.table[self.zkey] < np.max(znodes[iz:iz+2])) &
					(10**self.table[self.mkey] >= 10**np.min(mnodes[jm:jm+2])) & (10**self.table[self.mkey] < 10**np.max(mnodes[jm:jm+2])) )

				self.id_lookt_mass['lookt_'+clean_args(str('{:.2f}'.format(tnodes[iz])))+'_'+clean_args(str('{:.2f}'.format(tnodes[iz+1])))+'__m_'+clean_args(str('{:.2f}'.format(mnodes[jm])))+'_'+clean_args(str('{:.2f}'.format(mnodes[jm+1])))+'_sf'] = self.table.ID[ind_mt_sf].values
				self.id_lookt_mass['lookt_'+clean_args(str('{:.2f}'.format(tnodes[iz])))+'_'+clean_args(str('{:.2f}'.format(tnodes[iz+1])))+'__m_'+clean_args(str('{:.2f}'.format(mnodes[jm])))+'_'+clean_args(str('{:.2f}'.format(mnodes[jm+1])))+'_qt'] = self.table.ID[ind_mt_qt].values
Пример #11
0
def fast_Lir(m,zin): #Tin,betain,alphain,z):
  '''I dont know how to do this yet'''
  wavelength_range = np.linspace(8.,1000.,10.*992.)
  model_sed = fast_sed(m,wavelength_range)

  nu_in = c * 1.e6 / wavelength_range
  ns = len(nu_in)

  dnu = nu_in[0:ns-1] - nu_in[1:ns]
  dnu = np.append(dnu[0],dnu)
  Lir = np.sum(model_sed * dnu, axis=1)
  conversion = 4.0 * np.pi *(1.0E-13 * cosmo.luminosity_distance(zin) * 3.08568025E22)**2.0 / L_sun # 4 * pi * D_L^2    units are L_sun/(Jy x Hz)

  Lrf = Lir * conversion # Jy x Hz
  return Lrf
Пример #12
0
	def get_subpop_ids(self, znodes, mnodes, pop_dict, linear_mass=1, lookback_time = False):
		self.subpop_ids = {}
		if lookback_time == True:
			age_universe = cosmo.age(0).value # 13.797617455819209 Gyr
			znodes = np.array([z_at_value(cosmo.age,(age_universe - i) * u.Gyr) for i in znodes])

		for iz in range(len(znodes[:-1])):
			for jm in range(len(mnodes[:-1])):
				for k in pop_dict:
					if linear_mass == 1:
						ind_mz =( (self.table.sfg.values == pop_dict[k][0]) & (self.table[self.zkey] >= np.min(znodes[iz:iz+2])) & (self.table[self.zkey] < np.max(znodes[iz:iz+2])) &
							(10**self.table[self.mkey] >= 10**np.min(mnodes[jm:jm+2])) & (10**self.table[self.mkey] < 10**np.max(mnodes[jm:jm+2])) )
					else:
						ind_mz =( (self.table.sfg == pop_dict[k][0]) & (self.table[self.zkey] >= np.min(znodes[iz:iz+2])) & (self.table[self.zkey] < np.max(znodes[iz:iz+2])) &
							(self.table[self.mkey] >= np.min(mnodes[jm:jm+2])) & (self.table[self.mkey] < np.max(mnodes[jm:jm+2])) )

					self.subpop_ids['z_'+clean_args(str('{:.2f}'.format(znodes[iz])))+'_'+clean_args(str('{:.2f}'.format(znodes[iz+1])))+'__m_'+clean_args(str('{:.2f}'.format(mnodes[jm])))+'_'+clean_args(str('{:.2f}'.format(mnodes[jm+1])))+'_'+k] = self.table.ID[ind_mz].values
Пример #13
0
def main(args=None):
    from linetools.scripts.utils import coord_arg_to_coord
    from linetools import utils as ltu
    from astropy.io import fits, ascii
    from astropy.coordinates import SkyCoord
    import astropy.units as u
    from pyntejos.catalogs import add_radec_deg_columns

    pargs = parser(options=args)
    # RA,DEC
    icoord = coord_arg_to_coord(pargs.radec)
    coord = ltu.radec_to_coord(icoord)

    # define catalog
    print('Reading {} catalog'.format(pargs.catalog))
    if pargs.catalog == 'QSO':
        # read qsos from MILLIQUAS catalog
        col_names = ['ra_d', 'dec_d', 'name', 'description', 'rmag', 'bmag', 'comment', 'psf_r', 'psf_b', 'z', 'cite', 'zcite', 'qso_prob', 'Xname', 'Rname', 'Lobe1', 'Lobe2'] 
        cat = ascii.read('/media/ntejos/disk1/catalogs/qsos/milliquas/milliquas.txt', format='fixed_width', names=col_names)
    elif pargs.catalog == 'GC':
        # read MW globular cluster catalog 
        cat = ascii.read('/media/ntejos/disk1/catalogs/globular_clusters/mwgc10_1.dat', format='fixed_width')
        # add ra_d, dec_d columns
        cat = add_radec_deg_columns(cat)
    else:
        print(' Not implemented for such catalog.')
        return

    # cross-match
    print('Cross-matching...')
    cat_coords = SkyCoord(cat['ra_d'], cat['dec_d'], unit='deg')
    seplim = pargs.angsep * u.arcmin
    sep2d = coord.separation(cat_coords)
    cond = sep2d <= seplim
    cat = cat[cond]
    if len(cat) < 1:
        print("No matches found.")
    else:
        cat['sep2d'] = sep2d[cond]
        if pargs.redshift is not None:
            from astropy.cosmology import Planck15 as cosmo
            import pdb; pdb.set_trace()
            sep = (cosmo.kpc_comoving_per_arcmin(float(pargs.redshift)) * cat['sep2d']).to('Mpc')
            cat['sep_mpc'] = sep.value
        cat.sort('sep2d')
        print(cat)
Пример #14
0
def z_to_mpc(redshift):
    """
    Convert a redshift to a comoving distance

    Parameters
    ----------
    redshift : float

    Returns
    -------
    Comoving distance of redshift in Mpc

    """

    if redshift <= 1e-10:
        return 0 * u.Mpc
    else:
        return cosmo.comoving_distance(redshift)
Пример #15
0
def css(ax, col, legend):
    """ 6 GHz light curve """
    d = Planck15.luminosity_distance(z=0.034).cgs.value

    # low frequency
    nu = 6E9

    # add the points from Deanne's paper
    x = np.array([69, 99, 162, 357])
    y = np.array([4.5, 6.1, 2.3, 0.07]) * nu
    lum = plot_line(ax, d, x, y, 'AT2018cow', None, col, legend, zorder=10)
    print(lum)
    ax.text(x[0],
            lum[0] * 1.1,
            'CSS161010',
            fontsize=11,
            verticalalignment='bottom',
            horizontalalignment='right')
Пример #16
0
def get_years(redshift):
    """ return number of years source remains above threshold
    for a given distance """
    d = Planck15.luminosity_distance(z=redshift).cgs.value

    # initial flux is around 2e31 erg/s/Hz until 10-20 days post-burst
    # (Chandra & Frail 2012)
    f0 = 2e31 / (4 * np.pi * d**2)
    t_yr = np.logspace(-1, 4, 1000)
    f = f0 * ((t_yr * 365) / (15))**(-1)

    # convert to mJy
    f_mjy = (f / 10**(-23)) * 10**3

    # let's say that "detectable" means above 100 uJy
    choose = f_mjy > 0.1

    return t_yr[choose][-1]
Пример #17
0
def grb111209a(ax, col, legend):
    """ 
    Hancock+ 2012, GCN 12804
    """
    z = 0.677
    d = Planck15.luminosity_distance(z=z).cgs.value

    t = np.array([5.1]) / (1 + z)
    f = np.array([0.97])
    nu = np.array([9E9] * len(f))

    lum = plot_line(ax, d, t, nu * f, 'GRB111209A', 'GRB', col, legend)
    ax.text(t[0] * 1.5,
            lum[0] * 1.3,
            'GRB111209A/SN2011kl',
            fontsize=11,
            verticalalignment='bottom',
            horizontalalignment='center')
Пример #18
0
    def __init__(self, units='uK_CMB'):
        # Prepare the analytic expression
        x_nu = '(nu * h_over_k / Tcmb)'
        analytic_expr = 'Tcmb * (x_nu * (exp(x_nu) + 1) / expm1(x_nu) - 4)'
        analytic_expr = analytic_expr.replace('x_nu', x_nu)
        if 'K_CMB' in units:
            pass
        elif 'K_RJ' in units:
            analytic_expr += ' / ' + K_RJ2K_CMB
        else:
            raise ValueError("Unsupported units: %s" % units)
        if units[0] == 'u':
            analytic_expr = '1e6 * ' + analytic_expr
        elif units[0] == 'm':
            analytic_expr = '1e3 * ' + analytic_expr

        kwargs = dict(Tcmb=Planck15.Tcmb(0).value, h_over_k=H_OVER_K)
        super(ThermalSZ, self).__init__(analytic_expr, **kwargs)
Пример #19
0
 def __init__(self,cosmo_params=cosmo_fid,pk_params=pk_params,cosmo=cosmo,
              silence_camb=False,pk_func=None,SSV_cov=False,scenario=None,
              logger=None):
     self.logger=logger
     self.cosmo_params=cosmo_params
     self.pk_params=pk_params
     self.cosmo=cosmo
     self.silence_camb=silence_camb
     self.cosmo_h=cosmo.clone(H0=100)
     #self.pk_func=self.camb_pk_too_many_z if pk_func is None else pk_func
     #self.pk_func=self.ccl_pk if pk_func is None else pk_func
     self.pk_func=self.class_pk if pk_func is None else getattr(self,pk_func)
     self.SSV_cov=SSV_cov
     self.scenario = scenario
     self.pk=None
     if not pk_params is None:
         self.kh=np.logspace(np.log10(pk_params['kmin']),np.log10(pk_params['kmax']),
         pk_params['nk'])
Пример #20
0
def d4ec(ax):
    ax = axarr[0,1]
    name = 'SNLS04D4ec'
    z = 0.593
    offset = 3
    dm = Planck15.distmod(z=z).value
    choose = np.logical_and.reduce((names == name, ~islim, filt=='i'))
    ax.errorbar(
            (jd[choose]-jd[choose][0])/(1+z)+offset, mag[choose]-dm,
            yerr=emag[choose].astype(float), mec='k', mfc='white', fmt='s',
            label="D4ec, $i$", c='k')
    choose = np.logical_and.reduce((names == name, ~islim, filt=='g'))
    ax.errorbar(
            (jd[choose]-jd[choose][0])/(1+z)+offset, mag[choose]-dm,
            yerr=emag[choose].astype(float), mec='k', mfc='white', fmt='D',
            label="D4ec, $i$", c='k')
    plot_18gep(ax, 'g')
    plot_18gep(ax, 'UVW1', c='grey')
Пример #21
0
def get_convolved_flux_density(flux_density, redshift, beam_FWHM_arcsec):

    kpc_per_arcsec = _cosmo.kpc_proper_per_arcmin(redshift).to(_u.kpc /
                                                               _u.arcsec)

    # beam information
    sigma_beam_arcsec = beam_FWHM_arcsec / 2.355
    area_beam_kpc2 = (_np.pi * (sigma_beam_arcsec * kpc_per_arcsec)**2).to(
        _u.kpc**2)

    beam_kernel = _Gaussian2DKernel(
        (sigma_beam_arcsec * kpc_per_arcsec).to(_u.kpc).value)

    flux_density = (
        _convolve(flux_density.to(_u.Jy), beam_kernel, boundary="extend") *
        _u.Jy)

    return flux_density
Пример #22
0
def power(redshift, total_flux, alpha=-0.78):
    """
	Calculates the power of a source(s) given the 
	redshift,
	integrated flux,
	and assumed average spectral index alpha
	# see https://arxiv.org/pdf/1609.00537.pdf
	"""

    # luminosity distance
    Dl = Planck15.luminosity_distance(redshift)
    Dl = Dl.to(u.kpc)

    # see (https://arxiv.org/pdf/0802.2770.pdf) 9: Appendix (Page 53)
    L = total_flux * 4 * np.pi * Dl**2 * (1 + redshift)**(-1.0 * alpha - 1)
    print(L)

    return L
Пример #23
0
def test_template_spectra():

    from astropy import units
    from skypy.galaxy.spectrum import mag_ab, magnitudes_from_templates
    from astropy.cosmology import Planck15
    from specutils import Spectrum1D

    # 3 Flat Templates
    lam = np.logspace(0, 4, 1000)*units.AA
    A = np.array([[2], [3], [4]])
    flam = A * 0.10884806248538730623*units.Unit('erg s-1 cm-2 AA')/lam**2
    spec = Spectrum1D(spectral_axis=lam, flux=flam)

    # Gaussian bandpass
    bp_lam = np.logspace(0, 4, 1000)*units.AA
    bp_tx = np.exp(-((bp_lam - 1000*units.AA)/(100*units.AA))**2)*units.dimensionless_unscaled
    bp = Spectrum1D(spectral_axis=bp_lam, flux=bp_tx)

    # Each test galaxy is exactly one of the templates
    coefficients = np.diag(np.ones(3))
    mt = magnitudes_from_templates(coefficients, spec, bp)
    m = mag_ab(spec, bp)
    np.testing.assert_allclose(mt, m)

    # Test distance modulus
    redshift = np.array([1, 2, 3])
    dm = Planck15.distmod(redshift).value
    mt = magnitudes_from_templates(coefficients, spec, bp, distance_modulus=dm)
    np.testing.assert_allclose(mt, m + dm)

    # Test stellar mass
    sm = np.array([1, 2, 3])
    mt = magnitudes_from_templates(coefficients, spec, bp, stellar_mass=sm)
    np.testing.assert_allclose(mt, m - 2.5*np.log10(sm))

    # Redshift interpolation test; linear interpolation sufficient over a small
    # redshift range at low relative tolerance
    z = np.linspace(0, 0.1, 3)
    m_true = magnitudes_from_templates(coefficients, spec, bp, redshift=z, resolution=4)
    m_interp = magnitudes_from_templates(coefficients, spec, bp, redshift=z, resolution=2)
    np.testing.assert_allclose(m_true, m_interp, rtol=1e-2)
    with pytest.raises(AssertionError):
        np.testing.assert_allclose(m_true, m_interp, rtol=1e-5)
Пример #24
0
def ksn2015k(ax):
    diff = Planck15.distmod(z=0.09).value
    gr = -0.17
    G = 20.01 - diff
    ax.errorbar(gr,
                G,
                xerr=0.20,
                yerr=0.12,
                fmt='v',
                c='#84206b',
                mfc='#84206b',
                ms=12,
                label=None)
    ax.text(gr,
            G,
            "KSN2015K",
            fontsize=14,
            horizontalalignment='right',
            verticalalignment='bottom')
Пример #25
0
def zint(mass, zmin, zmax, nstep=1000):
    z = np.linspace(zmin, zmax, nstep)

    integral = 0

    if mass > 100:
        #Shitty check if mass was given as just the exponant
        mass = np.log(mass)

    for i in range(len(z) - 1):
        ztemp = (z[i + 1] + z[i]) / 2
        print(i)
        integrand = lambda m: mass_function.massFunction(
            m, ztemp, mdef='500m', model='tinker08', q_out='dndlnM')
        integrated_density = log_int(integrand, mass, 20.5)
        #Comoving volume computed over full sky i.e. 4pi steradians. Scale accordingly
        comov_vol = Planck15.comoving_volume(ztemp).value
        integral += integrated_density * comov_vol * (z[i + 1] - z[i])
    return integral
Пример #26
0
def get_cosmo(z):
    """Return transverse comoving distance and 3-parameter density term 
     (Omega_m, Omega_k, Lambda) for the given redshifts.

    Parameters
    ----------
    z : float
        Redshift

    Returns
    -------
    out : tuple
        (transverse comoving distance, density term)
    
    """
    cosmo_d = Cosmo.comoving_transverse_distance(z).value
    cosmo_e = np.sqrt(Cosmo.Om0 * (1 + z)**3 + Cosmo.Ok0 * (1 + z)**2 +
                      Cosmo.Ode0)
    return cosmo_d, cosmo_e
Пример #27
0
def comoving_voxel_volume(z, dnu, omega):
    """
    Get comoving voxel volume in Mpc^3

    dnu = Channel width in Hz
    Omega = pixel area in steradian
    """
    if isinstance(z, np.ndarray):
        if isinstance(omega, np.ndarray):
            z, omega = np.meshgrid(z, omega)
        elif isinstance(dnu, np.ndarray):
            z, dnu = np.meshgrid(z, dnu)
    elif isinstance(dnu, np.ndarray) and isinstance(omega, np.ndarray):
        dnu, omega = np.meshgrid(dnu, omega)
    nu0 = f21 / (z + 1) - dnu / 2.0
    nu1 = nu0 + dnu
    dz = f21 * (1 / nu0 - 1 / nu1)
    vol = cosmo.differential_comoving_volume(z).value * dz * omega
    return vol
Пример #28
0
def red_sequence_cut(config, data, **kwargs):
    """
    Identify RS galaxies using color-magnitude diagram.

    First do a radial cut on catalogue and identify the RS from the inner galaxies
    --> increase the contrast of the RS
    Then go back and apply the cut on the entire catalogue as some RS galaxies are
    located far away from the centre

    Returns bool array, where False means the object does not pass the cut

    List of available kwargs:

    :param float mag_cut: rband magnitude cut - default is 25
    :param float plot: if keywords exists, plot stuff for visual inspection
    """

    mcut = kwargs.get('mag_cut', 25.)
    plot = kwargs.get('plot', False)

    da = cosmo.angular_diameter_distance(
        config['redshift'])  # Mpc - using Planck15 cosmo
    rcut_rs = 1 * u.Mpc
    sub_sample = cutils.filter_around(data, config, exclude_outer=N.arctan(rcut_rs / da).value,
                                      unit='rad', plot=plot)

    color_gr = sub_sample['modelfit_CModel_mag'][sub_sample['filter'] == 'g'] \
        - sub_sample['modelfit_CModel_mag'][sub_sample['filter'] == 'r']
    mag = sub_sample['modelfit_CModel_mag'][sub_sample['filter'] == 'r']
    # slopes and intercepts of the RS band
    params = fit_red_sequence(color_gr, mag, plot=plot)

    # apply cut to entire dataset
    color_gr = data['modelfit_CModel_mag'][data['filter'] == 'g'] \
        - data['modelfit_CModel_mag'][data['filter'] == 'r']
    mag = data['modelfit_CModel_mag'][data['filter'] == 'r']
    lower_bound = params[0][0] * mag + params[0][1]
    upper_bound = params[1][0] * mag + params[1][1]
    filt = ((color_gr < lower_bound) & (mag < mcut)) | (
        (color_gr > upper_bound) & (mag < mcut))

    return filt
Пример #29
0
def grb030329(ax, col, legend):
    """ 
    Berger 2003
    Van der Horst et al. 2008
    
    Explosion day was obviously 03/29
    """
    z = 0.1686
    d = Planck15.luminosity_distance(z=z).cgs.value

    # LOW FREQUENCY

    # Berger: this is the best frequency to pick from this paper
    t = np.array([
        0.58, 1.05, 2.65, 3.57, 4.76, 6.89, 7.68, 9.49, 11.90, 12.69, 14.87,
        16.66, 18.72, 20.58, 25.70, 28.44, 31.51, 33.58, 36.52, 42.55, 44.55,
        59.55, 66.53
    ]) / (1 + z)
    f = np.array([
        3.50, 1.98, 8.50, 6.11, 9.68, 15.56, 12.55, 13.58, 17.70, 17.28, 19.15,
        17.77, 15.92, 16.08, 15.34, 12.67, 13.55, 13.10, 10.64, 8.04, 8.68,
        4.48, 4.92
    ])
    nu = np.array([8.5E9] * len(f))

    # Van der Horst: best frequency is 2.3 GHz
    t = np.append(
        t,
        np.array([
            268.577, 306.753, 365.524, 420.168, 462.078, 583.683, 743.892,
            984.163
        ]) / (1 + z))
    f = np.append(f,
                  np.array([1613, 1389, 871, 933, 707, 543, 504, 318]) * 1E-3)
    nu = np.append(nu, np.array([2.3E9] * 8))
    lum = plot_line(ax, d, t, nu * f, 'GRB030329', 'GRB', col, legend)
    ax.text(t[6] * 1.05,
            lum[10] * 1.05,
            'GRB030329',
            fontsize=11,
            verticalalignment='bottom',
            horizontalalignment='left')
Пример #30
0
    def __init__(self,TwoMRSMaps=None,sim=True, pthresh=3.e-3, zslices = 16, smoothing=0.0, m=3, zmax=3.):
        self.HESEMaps=TwoMRSMaps
        self.sim=sim
        self.pthresh = pthresh
        self.obs = ICPSObservations()
        self.perf = ICPSPerformance('DiscoSens.txt')
        self.NU, self.NL, self.NO, self.SU, self.SL, self.SO = self.obs.GetHSCounts(pthresh)
        self.PTDisc=False
        self.Det={}
        if sim:
            print 'Total Median Hotspots above threshold p value ',pthresh,':', (self.NU+self.NL+self.SU+self.SL)/2,'N:S', (self.NU+self.NL)/2, (self.SU+self.SL)/2
            print 'Total Observed Hotspots', self.NO + self.SO
            self.Det["IsotropicHS"]=Detector(Name="IceCubePSSkyMap", EvList=IsoGenerator((self.NU+self.NL+self.SU+self.SL)/2, self.NU+self.NL, self.SU+self.SL))
        self.c_evWeights={}
        self.c_evWeights["IsotropicHS"]=TCanvas()
        self.h_injPattern={}
        self.h_injPattern["IsotropicHS"]=None

        self.TwoMRSMapsSum={}
        self.TwoMRSMapsSum["IsotropicHS"]=self.HESEMapsSumf("IsotropicHS")
        self.CRSet={}
        self.CRSet["IsotropicHS"]=[]
        self.sigWsum={}
        self.TomoMaps={}
        self.Zslices = zslices
        self.Zarr = np.linspace(0., 0.15, zslices)
        
        for i in range(len(self.Zarr)-1):
            print PF(), 'Loading map in range ', self.Zarr[i], ' to ', self.Zarr[i+1]
            self.TomoMaps[self.Zarr[i]] = TwoMRSMap(Make2MRSMap(self.Zarr[i],  self.Zarr[i+1], 16), "SourceDist", smoothing)
        self.Nsrc = 0
        self.Ndensity = 0.
        self.M = m
        self.TotDiffuseFlux=0.
        self.Fluxes=[]
        self.Zmax=zmax
        self.scaler = N0Scaler(self.M, self.Zmax)
        self.DCMRmax=cosmo.comoving_distance(self.Zmax).value
        if self.M:
            self.Evoprobx = np.linspace(0, self.Zmax, 1500)
            self.Evoproby = np.power(1.+self.Evoprobx, self.M)*np.power(self.Evoprobx, 2.)
            self.backpolate = InterpolatedUnivariateSpline(self.Evoproby, self.Evoprobx)
Пример #31
0
def fast_double_Lir(m, zin):  #Tin,betain,alphain,z):
    '''I dont know how to do this yet'''
    wavelength_range = np.linspace(8., 1000., 10. * 992.)

    v = m.valuesdict()
    betain = np.asarray(v['beta'])
    alphain = np.asarray(v['alpha'])
    A_hot = np.asarray(v['A_hot'])
    A_cold = np.asarray(v['A_cold'])
    T_hot = np.asarray(v['T_hot'])
    T_cold = np.asarray(v['T_cold'])

    #Hot
    p_hot = Parameters()
    p_hot.add('A', value=A_hot, vary=True)
    p_hot.add('T_observed', value=T_hot, vary=True)
    p_hot.add('beta', value=betain, vary=False)
    p_hot.add('alpha', value=alphain, vary=False)
    hot_sed = fast_sed(p_hot, wavelength_range)

    #Hot
    p_cold = Parameters()
    p_cold.add('A', value=A_cold, vary=True)
    p_cold.add('T_observed', value=T_cold, vary=True)
    p_cold.add('beta', value=betain, vary=False)
    p_cold.add('alpha', value=alphain, vary=False)
    cold_sed = fast_sed(p_cold, wavelength_range)

    nu_in = c * 1.e6 / wavelength_range
    ns = len(nu_in)

    dnu = nu_in[0:ns - 1] - nu_in[1:ns]
    dnu = np.append(dnu[0], dnu)
    Lir_hot = np.sum(hot_sed * dnu, axis=1)
    Lir_cold = np.sum(cold_sed * dnu, axis=1)
    conversion = 4.0 * np.pi * (
        1.0E-13 * cosmo.luminosity_distance(zin) * 3.08568025E22
    )**2.0 / L_sun  # 4 * pi * D_L^2    units are L_sun/(Jy x Hz)

    Lrf_hot = Lir_hot * conversion  # Jy x Hz
    Lrf_cold = Lir_cold * conversion  # Jy x Hz
    return [Lrf_hot, Lrf_cold]
Пример #32
0
    def update_ssfr_params(self):
        try:
            delta_t = self.t_old - self.t
        except:
            self.t_old = cosmo.lookback_time(self.z_init).value
            delta_t = self.t_old - self.t

        print(delta_t)

        if delta_t >= self.ssfr_update_time_interval:  #Gyr
            n = len(self.sf_masses)
            self.ssfr_params = self.gen_ssfr_params(n)

            m = len(self.cluster_masses)
            self.cluster_ssfr_p = self.gen_ssfr_params(m)

            self.t_old = self.t
            print('*new ssfr params*')
        else:
            pass
Пример #33
0
    def DZ_int(
        self,
        z=[0],
        cosmo=None
    ):  #linear growth factor.. full integral.. eq 63 in Lahav and suto
        if not cosmo:
            cosmo = self.cosmo

        def intf(z):
            return (1 + z) / (cosmo.H(z).value)**3

        j = 0
        Dz = np.zeros_like(z, dtype='float32')

        for i in z:
            Dz[j] = cosmo.H(i).value * scipy_int1d(
                intf, i, np.inf, epsrel=1.e-6, epsabs=1.e-6)[0]
            j = j + 1
        Dz *= (2.5 * cosmo.Om0 * cosmo.H0.value**2)
        return Dz / Dz[0]
Пример #34
0
def get_surface_brightness(flux_density, simulation_data, unit_values,
                           redshift, beam_FWHM_arcsec):
    """Calculates the surface brightness from a given flux density"""

    kpc_per_arcsec = _cosmo.kpc_proper_per_arcmin(redshift).to(_u.kpc /
                                                               _u.arcsec)
    # beam information
    sigma_beam_arcsec = beam_FWHM_arcsec / 2.355
    area_beam_kpc2 = (_np.pi * (sigma_beam_arcsec * kpc_per_arcsec)**2).to(
        _u.kpc**2)

    radio_cell_areas = _ps.calculate_cell_area(simulation_data)

    # in physical units
    radio_cell_areas_physical = radio_cell_areas * unit_values.length**2

    # n beams per cell
    n_beams_per_cell = (radio_cell_areas_physical / area_beam_kpc2).si

    return flux_density / n_beams_per_cell
Пример #35
0
def double_beta_dust_FGB_Model():

    H_OVER_K = constants.h * 1e9 / constants.k
    # Conversion factor at frequency nu
    K_RJ2K_CMB = ('(expm1(h_over_k * nu / Tcmb)**2'
                  '/ (exp(h_over_k * nu / Tcmb) * (h_over_k * nu / Tcmb)**2))')
    K_RJ2K_CMB = K_RJ2K_CMB.replace('Tcmb', str(Planck15.Tcmb(0).value))
    K_RJ2K_CMB = K_RJ2K_CMB.replace('h_over_k', str(H_OVER_K))
    K_RJ2K_CMB_NU0 = K_RJ2K_CMB + ' / ' + K_RJ2K_CMB.replace('nu', 'nu0')

    analytic_expr1 = ('(exp(nu0 / temp * h_over_k) -1)'
                     '/ (exp(nu / temp * h_over_k) - 1)'
                     '* (nu / nu0)**(1 + beta_d0)   * (nu0 / nubreak)**(beta_d0-beta_d1) * '+K_RJ2K_CMB_NU0 + '* (1-heaviside(nu-nubreak,0.5))')

    analytic_expr2 = ('(exp(nu0 / temp * h_over_k) -1)'
                     '/ (exp(nu / temp * h_over_k) - 1)'
                     '* (nu / nu0)**(1 + beta_d1) * '+K_RJ2K_CMB_NU0 + '* heaviside(nu-nubreak,0.5)')
    analytic_expr = analytic_expr1 + ' + ' + analytic_expr2

    return analytic_expr
Пример #36
0
def at2018cow(ax, col, legend):
    """ 231.5 GHz light curve and 9 GHz light curve """
    d = Planck15.luminosity_distance(z=0.014).cgs.value

    # high frequency
    a, b, c = sma_lc()
    dt, f, ef = b
    ef_comb = np.sqrt(ef**2 + (0.15 * f)**2)
    nu = 231.5E9

    # low frequency
    nu = 9E9
    data_dir = "/Users/annaho/Dropbox/Projects/Research/AT2018cow/data"
    dat = Table.read("%s/radio_lc.dat" % data_dir,
                     delimiter="&",
                     format='ascii.no_header')
    tel = np.array(dat['col2'])
    choose = np.logical_or(tel == 'SMA', tel == 'ATCA')

    days = np.array(dat['col1'][choose])
    freq = np.array(dat['col3'][choose]).astype(float)
    flux_raw = np.array(dat['col4'][choose])
    flux = np.array([float(val.split("pm")[0][1:]) for val in flux_raw])
    eflux_sys = np.array([0.1 * f for f in flux])
    eflux_form = np.array(
        [float(val.split("pm")[1][0:-1]) for val in flux_raw])
    eflux = np.sqrt(eflux_sys**2 + eflux_form**2)
    choose = freq == 9

    # add the Margutti point and the Bietenholz point
    margutti_x = np.array([84, 287])
    margutti_y = np.array([6E28, 3.2E26]) / (4 * np.pi * d**2) / 1E-23 / 1E-3
    x = np.hstack((days[choose], margutti_x))
    y = np.hstack((flux[choose], margutti_y)) * nu
    lum = plot_line(ax, d, x, y, 'AT2018cow', None, col, legend, zorder=10)
    ax.text(x[0],
            lum[0] / 1.4,
            'AT2018cow',
            fontsize=11,
            verticalalignment='top',
            horizontalalignment='center')
Пример #37
0
def get_Jaguar(mag, redshift, path, refwl):
    """
    get spectrum from jaguar and write (spec.fits) of the simulated Lyman break galaxy
    Normalize the spectrum to the requested absolute Magnitude at refwl and
    return observed flambda with zero point magnitude = 0
    Args:
        
        mag (float) = absolute magtitude at referenced wavelength.
        redshift (float) = Input redshift of the artificial source.
        refwl (float) = Must provide if absmag is True. Wavelength for absmag 
                        reference in angstrom.
    """
    #randomly draw spec
    s_hdu = fits.open('Files/Jaguar_Spectra.fits', ignore_missing_end=True)
    wavelength = s_hdu[0].data  # angstrom
    specnum = random.randrange(len(s_hdu[1].data))
    template_spec = s_hdu[1].data[specnum]
    s_hdu.close()
    #make the flux at refwl equal to 1
    template_spec = template_spec / template_spec[int(
        refwl)]  #note that the template spec must start from 1,2,3,...angstrom

    #normalize with theoretical observed flux at ref wl (flambda)
    #this flux has zero_point magnitude = 0
    c = 2.99792458e18  # In angstrom
    Lumdis = cosmo.luminosity_distance(redshift).to(u.parsec).value
    spec = (template_spec * (10**(-mag / 2.5)) * (c / refwl**2) *
            (10. / Lumdis)**2) / (1. + redshift)

    wavelength = wavelength * (1 + redshift)
    data = [[wavelength], [spec]]
    hdu = fits.PrimaryHDU()
    hdu.header['CTYPE1'] = 'Wavelength'
    hdu.header['CTYPE2'] = 'Flux'
    t = Table(data, names=('Wavelength', 'flux'))
    data = np.array(t)
    fits.writeto('%sResults/images/spec_z%.2f.fits' % (path, redshift),
                 data,
                 header=None,
                 overwrite=True)
    return specnum
Пример #38
0
def core_collapse(ax):
    """ Light curves of 230 CC SNe from RCF provided by Yashvi Sharma """
    # Load the table of events
    df = pd.read_csv("../data/ccsne/ccsne_final.csv")
    keep = df['redshift'] != 'None'

    nearby = df['redshift'][keep].astype(float)<0.05
    sampled = df['numpoints_lc'][keep]>50
    choose = np.logical_and(nearby, sampled)
    z = df['redshift'][keep].values[choose].astype(float)

    # Load the array of light curves
    lcs = np.load(
            "../data/ccsne/ccsne_lcs.npy", 
            allow_pickle=True, encoding='latin1')
    lcs = lcs[keep][choose]

    # Plot one of them
    leg = True
    for ii in np.arange(sum(choose)):
        lc = lcs[ii]
        filt = lc['filter']
        jd = lc['jd']
        mag = lc['mag']
        gband = filt == 'g'
        if sum(gband) > 30:
            x = jd[gband]-jd[gband].values[0]
            y = mag[gband]
            peakmag = np.min(mag)
            thalf = np.interp(peakmag+0.75, y, x)
            absmag = peakmag-Planck15.distmod(z=z[ii]).value
            if leg:
                ax.scatter(
                        thalf, absmag, c='lightgrey', marker='s', zorder=0, 
                        label="630 CC SNe")
                leg = False
            else:
                ax.scatter(
                        thalf, absmag, c='lightgrey', marker='s', zorder=0, 
                        label="_nolegend_")
            leg = False
Пример #39
0
def gap(ax):
    """ Data points from Dan Perley """
    dat = Table.read(
        "../data/from_dan_perley.txt", delimiter='|',
        format='ascii.fast_no_header')
    cl = np.array([val.split(" ")[0] for val in dat['col7']])
    z = np.array([val[13:20] for val in dat['col7']])
    maxcol = dat['col3']
    filt = np.array([val.split(" ")[1] for val in maxcol])
    maxmag = np.array([val.split(" ")[2] for val in maxcol]).astype(float)
    timecol = dat['col6']
    rise = np.array([val[0:6] for val in timecol])
    fade = np.array([val[6:] for val in timecol])

    useind = np.where(['Gap' in val for val in cl])[0]
    leg = 'Ca-rich Gap'
    for ii in useind:
        bad = np.logical_or('+' in rise[ii], '+' in fade[ii])
        if bad==False: 
            timescale = float(rise[ii]) + float(fade[ii])
            ax.scatter(
                timescale, maxmag[ii]-Planck15.distmod(float(z[ii])).value,
                marker='^', c='k', label=leg)
            leg = '_nolegend_'

    """ Data from KDE """
    cadata = ascii.read('../data/carich_gap.txt')
    name = cadata['Object']
    risetime = cadata['Rise']
    falltime = cadata['Fade']
    peakmag = cadata['PeakMag']
    
    for i in range(len(name)):
         if risetime[i] == -99 or falltime[i] == -99:
             continue
         timescale = risetime[i] + falltime[i]

	 if 'ZTF' in name[i]:
              ax.scatter(timescale, peakmag[i], marker='^', c='k', label='_nolegend_')
         else:
              ax.scatter(timescale, peakmag[i], marker='^', c='grey', label='_nolegend_')
Пример #40
0
def stack_spec(spec_file, dv=100 * u.km / u.s, cut_on_rho=4.):
    # Load
    xspec, tpe, spec_tbl = load_spec(spec_file)
    # Cut on separation (should do this much earlier in the process)
    if cut_on_rho is not None:
        warnings.warn("Cutting on rho in stack.  Should do this earlier")
        b_coords = SkyCoord(ra=tpe['BG_RA'], dec=tpe['BG_DEC'], unit='deg')
        f_coords = SkyCoord(ra=tpe['FG_RA'], dec=tpe['FG_DEC'], unit='deg')
        kpc_amin = cosmo.kpc_comoving_per_arcmin(tpe['FG_Z'])  # kpc per arcmin
        ang_seps = b_coords.separation(f_coords)
        rho = ang_seps.to('arcmin') * kpc_amin / (1 + tpe['FG_Z'])
        cut_rho = rho.to('Mpc').value < cut_on_rho
        print("We have {:d} spectra after the cut.".format(np.sum(cut_rho)))
        xspec = xspec[cut_rho]
        tpe = tpe[cut_rho]
        spec_tbl = spec_tbl[cut_rho]
    # Remove those without continua
    has_co = spec_tbl['HAS_CO'].data
    co_spec = xspec[has_co]
    co_spec.normed = True  # Apply continuum
    #  May also wish to isolate in wavelength to avoid rejected pixels
    for ii in range(co_spec.nspec):
        co_spec.select = ii
        co = co_spec.co.value
        sig = co_spec.sig.value
        bad_pix = np.any([(co == 0.), (co == 1.), (sig <= 0.)], axis=0)
        co_spec.add_to_mask(bad_pix, compressed=True)

    # Rebin to rest
    zarr = tpe['FG_Z'][has_co]
    rebin_spec = lspu.rebin_to_rest(co_spec, zarr, dv)

    # Stack
    stack = lspu.smash_spectra(rebin_spec)

    # Plot
    tpep.plot_stack(stack, 'all_stack.pdf')
    tpep.plot_spec_img(rebin_spec, 'spec_img.pdf')
    pdb.set_trace()
    # Return
    return
Пример #41
0
def physical_size(redshift, angular_size):
    '''
	Calculates the physical size of a source in Kpc

	'''

    # physical distance corresponding to 1 radian at redshift z
    size = Planck15.angular_diameter_distance(redshift)

    # to not adjust the actual size column
    angular_size = np.copy(angular_size)
    # angular_size is in arcsec, convert to radian
    angular_size /= 3600  # to degrees
    angular_size *= np.pi / 180  # to radians

    # physical distance corresponding to angular distance
    size *= angular_size

    size = size.to(u.kpc)

    return size
Пример #42
0
   def light_curve(self,time_series,frequencies):
       """ SImulate the afterglow light curve for a given wavelength"""
       #Make sure that we are working with arrays
       time_series=np.atleast_1d(time_series)
       frequencies=np.atleast_1d(frequencies)


       self.DL = cosmo.luminosity_distance(self.parameters['z']).value

       lc=[] 
       t1=len(time_series)
       nu1=len(frequencies)
       for t in range(t1):
           # Check if nu is a sequence or float
           sed=[]
           for nu in range(nu1):
               sed.append( self.granot_sari(td=time_series[t],nu=frequencies[nu]) ) # Flux in obs frame in mJy 
  
           lc.append(sed) # Flux in obs frame in mJy

       return np.array(lc)
Пример #43
0
def full_log_likelihood(params):
    alpha = params[0]
    beta = params[1]
    MB = params[2]
    sigma_int = params[3]
    meanx = params[4]
    meanc = params[5]
    sigpriorx = params[6]
    sigpriorc = params[7]
    if sigma_int < 0:
        return -np.inf
    if sigpriorx < 0:
        return -np.inf
    if sigpriorc < 0:
        return -np.inf

    cosmomu = cosmo.distmod(z).value
    return np.sum(
        negtwoLL(alpha, beta, cosmomu, MB, mb_obs, x1_obs, c_obs, mbe**2,
                 sigma_int**2, x1e**2, ce**2, 0.0, 0.0, 0.0, meanx, meanc,
                 sigpriorx**2, sigpriorc**2)) / (-2.0)
Пример #44
0
def fast_double_Lir(m,zin): #Tin,betain,alphain,z):
  '''I dont know how to do this yet'''
  wavelength_range = np.linspace(8.,1000.,10.*992.)

  v = m.valuesdict()
  betain = np.asarray(v['beta'])
  alphain = np.asarray(v['alpha'])
  A_hot= np.asarray(v['A_hot'])
  A_cold= np.asarray(v['A_cold'])
  T_hot = np.asarray(v['T_hot'])
  T_cold = np.asarray(v['T_cold'])

  #Hot
  p_hot = Parameters()
  p_hot.add('A', value = A_hot, vary = True)
  p_hot.add('T_observed', value = T_hot, vary = True)
  p_hot.add('beta', value = betain, vary = False)
  p_hot.add('alpha', value = alphain, vary = False)
  hot_sed = fast_sed(p_hot,wavelength_range)

  #Hot
  p_cold = Parameters()
  p_cold.add('A', value = A_cold, vary = True)
  p_cold.add('T_observed', value = T_cold, vary = True)
  p_cold.add('beta', value = betain, vary = False)
  p_cold.add('alpha', value = alphain, vary = False)
  cold_sed = fast_sed(p_cold,wavelength_range)

  nu_in = c * 1.e6 / wavelength_range
  ns = len(nu_in)

  dnu = nu_in[0:ns-1] - nu_in[1:ns]
  dnu = np.append(dnu[0],dnu)
  Lir_hot = np.sum(hot_sed * dnu, axis=1)
  Lir_cold = np.sum(cold_sed * dnu, axis=1)
  conversion = 4.0 * np.pi *(1.0E-13 * cosmo.luminosity_distance(zin) * 3.08568025E22)**2.0 / L_sun # 4 * pi * D_L^2    units are L_sun/(Jy x Hz)

  Lrf_hot = Lir_hot * conversion # Jy x Hz
  Lrf_cold = Lir_cold * conversion # Jy x Hz
  return [Lrf_hot, Lrf_cold]
Пример #45
0
def cube2healpix(cube, cube_res, cube_freq, hpx_nside):
    """
    Tile and grid a 21 cm simulation cube to a full-sky HEALPix map.

    The projection assumes Planck15 cosmology.

    Parameters
    ----------
    cube: numpy.ndarray
        Simulation cube, 3-dimensional
    cube_res: float
        Resolution of the cube in Mpc.
    cube_freq: float
        Observed frequency matching the cube's cosmology in MHz.
    hpx_nside: integer
        NSIDE of the output HEALPix image. Must be a valid NSIDE for HEALPix,
        i.e. 2**i for integer i.

    """
    cube_shape = cube.shape

    # Determine the radial comoving distance dc to the "Universe" shell at the
    # observed frequency.
    f21 = 1420.40575177  # MHz
    z21 = f21 / cube_freq - 1
    dc = Cosmo.comoving_distance(z21).value

    # Get the vector coordinates (vx, vy, vz) of the HEALPix pixels.
    vx, vy, vz = hp.pix2vec(hpx_nside, np.arange(hp.nside2npix(hpx_nside)))

    # Translate vector coordinates to comoving coordinates and determine the
    # corresponding cube indexes (xi, yi, zi). For faster operation, we will
    # use the mod function to determine the nearest neighboring pixels and
    # just grab the data points from those pixels instead of doing linear
    # interpolation. This sets the origin of the projecting shell to pixel
    # (x, y, z) = (0, 0, 0).
    xi = np.mod(np.around(vx * dc / cube_res).astype(int), cube_shape[0])
    yi = np.mod(np.around(vy * dc / cube_res).astype(int), cube_shape[1])
    zi = np.mod(np.around(vz * dc / cube_res).astype(int), cube_shape[2])
    return cube[xi, yi, zi]
Пример #46
0
def get_params_string(tag):
    p=read_tag(tag)
    mtot=float(p["M"])
    q=float(p["q"])
    snr=0
    if("snr" in p["z"]):
        d=0;
    else:
        d=float(cosmo.luminosity_distance(float(p["z"]))/units.Mpc)
    inc=math.pi/float(p["inc"])
    m1=mtot/(1.0+1.0/q)
    m2=mtot/(1.0+q)
    t0=0
    phi0=math.pi/3.0
    beta=math.pi/3.0
    lamb=3.0*math.pi/4.0
    pol=math.pi/3.0
    val={"m1":m1,"m2":m2,"tRef":t0,"phiRef":phi0,"distance":d,"lambda":lamb,"beta":beta,"inclination":inc,"polarization":pol}
    s=""
    for par in flare_submit.parnames:
        s=s+str(val[par])+" "
    return s
Пример #47
0
def calc_Q(N=2001,zlow=0,zhigh=20, ap=0.01376, bp=3.26, cp=2.59, dp=5.68):
	global zbuf, tbuf
	z = np.linspace(zhigh,zlow,N)
	if zbuf is None or np.any(zbuf != z):
		t_Gyr = np.array(cosmo.age(z)) # In units of Gyr
		t = t_Gyr*GYR_S # Time t in seconds
		zbuf, tbuf = z, t
	else:
		z, t = zbuf, tbuf
	Q = np.zeros(N)
	dt = np.zeros(N)
	Qprev = np.zeros(N)
	Qdotprev = np.zeros(N)
	'''Evolving the differential equation Qdot to solve for Q(z) using Euler's method'''
	for i in xrange(1, N):
		Qprev[i] = Q[i-1]
		Qdotprev[i] = Qdot(z[i-1], Qprev[i], ap=ap, bp=bp, cp=cp, dp=dp)
		dt[i] = t[i] - t[i-1]	
		Q[i] = Qprev[i] + dt[i]*Qdotprev[i]
		if Q[i] > 1.0:
			Q[i] = 1.0
	return Q, z
    def set_redshift(self):
        """
        Function which takes the input desired observation redshift and
        cosmologically redshifts the source SED. This sets the redshifted_model
        which is what is needed for making observations.
        """

        z = self.z
        # Deepcopy the model to local variable to get proper behavior of model
        # object methods.
        redshifted_model = deepcopy(self.transient_model)
        # Compute the luminosity distance using Planck15 cosmological
        # parameters, by which to decrease the amplitude of the SED
        lumdist = cosmo.luminosity_distance(z).value * 1e6  # in pc
        # SED is assumed to be at 10pc so scale accordingly.
        amp = pow(np.divide(10.0, lumdist), 2)
        # Set the redshift of the SED, this stretches the wavelength
        # distribution.
        redshifted_model.set(z=z)
        # Separately set the amplitude, this rescales the flux at each
        # wavelength.
        redshifted_model.set(amplitude=amp)
        self.redshifted_model = redshifted_model
def writeDists(o):
    """ Writes bias and dn/dz files for
        redmagic like sample.
    Eli Rykoff says

    Density is ~constant comoving density 1.5e-3 h^3 Mpc^-3, sigma_z/(1+z)
    ~0.01, and bias is 2-2.5ish.
    """

    zmin=0.01
    zmax=1.2
    Nz=1000
    rho_comoving=1.5e-3
    #Nz shaping
    zshape=1.0

    d=o.outpath
    fn=open (d+"/Nz.txt",'w')
    fb=open (d+"/bz.txt",'w')
    pi=np.pi
    for z in np.linspace(zmin, zmax,Nz):
            fb.write("%g %g\n"%(z,2.2))
            ## for density, need to convert Mpc/h into n/sqdeg/dz
            ## c over H(z) for Mpc/h units
            coHz=(const.c/co.H(z)).to(u.Mpc).value*co.h
            # radius in Mpc/h
            r=co.comoving_distance(z).to("Mpc").value*co.h
            #volume of 1sq * dz
            # 4pir^2 * (1deg/rad)**2 * dr/dz
            # hMpc^3 per dz per 1sqd
            vrat=r**2 * (pi/180.)**2  * coHz
            dens=rho_comoving*vrat
            ## shape distribution to avoid sharep cut
            if (z>zshape):
                sup=(z-zshape)/(zmax-zshape)
                dens*=np.exp(-10*sup**2)
            fn.write("%g %g\n"%(z,dens))
def Dc2(z1,z2):
    Dcz1 = (p15.comoving_distance(z1).value*p15.h)
    Dcz2 = (p15.comoving_distance(z2).value*p15.h)
    res = Dcz2-Dcz1+1e-8
    return res
def Dc(z):
    res = p15.comoving_distance(z).value*p15.h
    return res
Пример #52
0
def derive_and_sanitize():
    # Calculate some columns based on imported data, sanitize some fields
    for name in events:
        set_first_max_light(name)
        if 'claimedtype' in events[name]:
            events[name]['claimedtype'][:] = [ct for ct in events[name]['claimedtype'] if (ct['value'] != '?' and ct['value'] != '-')]
        if 'redshift' in events[name] and 'hvel' not in events[name]:
            # Find the "best" redshift to use for this
            bestsig = 0
            for z in events[name]['redshift']:
                sig = get_sig_digits(z['value'])
                if sig > bestsig:
                    bestz = z['value']
                    bestsig = sig
            if bestsig > 0:
                bestz = float(bestz)
                add_quanta(name, 'hvel', pretty_num(clight/1.e5*((bestz + 1.)**2. - 1.)/
                    ((bestz + 1.)**2. + 1.), sig = bestsig), 'D')
        elif 'hvel' in events[name] and 'redshift' not in events[name]:
            # Find the "best" hvel to use for this
            bestsig = 0
            for hv in events[name]['hvel']:
                sig = get_sig_digits(hv['value'])
                if sig > bestsig:
                    besthv = hv['value']
                    bestsig = sig
            if bestsig > 0 and is_number(besthv):
                voc = float(besthv)*1.e5/clight
                add_quanta(name, 'redshift', pretty_num(sqrt((1. + voc)/(1. - voc)) - 1., sig = bestsig), 'D')
        if 'maxabsmag' not in events[name] and 'maxappmag' in events[name] and 'lumdist' in events[name]:
            # Find the "best" distance to use for this
            bestsig = 0
            for ld in events[name]['lumdist']:
                sig = get_sig_digits(ld['value'])
                if sig > bestsig:
                    bestld = ld['value']
                    bestsig = sig
            if bestsig > 0 and is_number(bestld) and float(bestld) > 0.:
                add_quanta(name, 'maxabsmag', pretty_num(float(events[name]['maxappmag'][0]['value']) -
                    5.0*(log10(float(bestld)*1.0e6) - 1.0), sig = bestsig), 'D')
        if 'redshift' in events[name]:
            # Find the "best" redshift to use for this
            bestsig = 0
            for z in events[name]['redshift']:
                sig = get_sig_digits(z['value'])
                if sig > bestsig:
                    bestz = z['value']
                    bestsig = sig
            if bestsig > 0 and float(bestz) > 0.:
                if 'lumdist' not in events[name]:
                    dl = cosmo.luminosity_distance(float(bestz))
                    add_quanta(name, 'lumdist', pretty_num(dl.value, sig = bestsig), 'D')
                    if 'maxabsmag' not in events[name] and 'maxappmag' in events[name]:
                        add_quanta(name, 'maxabsmag', pretty_num(float(events[name]['maxappmag'][0]['value']) -
                            5.0*(log10(dl.to('pc').value) - 1.0), sig = bestsig), 'D')
        if 'photometry' in events[name]:
            events[name]['photometry'].sort(key=lambda x: (float(x['time']),
                x['band'] if 'band' in x else '', float(x['magnitude'] if 'magnitude' in x else x['counts'])))
        if 'spectra' in events[name] and list(filter(None, ['time' in x for x in events[name]['spectra']])):
            events[name]['spectra'].sort(key=lambda x: float(x['time']))
        events[name] = OrderedDict(sorted(events[name].items(), key=lambda key: event_attr_priority(key[0])))
Пример #53
0
def grab_sdss_spectra(radec, radius=0.1*u.deg, outfil=None,
                      debug=False, maxsep=None, timeout=600., zmin=None):
    """ Grab SDSS spectra

    Parameters
    ----------
    radec : tuple
      RA, DEC in deg
    radius : float, optional (0.1*u.deg)
      Search radius -- Astroquery actually makes a box, not a circle
    timeout : float, optional
      Timeout limit for connection with SDSS
    outfil : str ('tmp.fits')
      Name of output file for FITS table
    maxsep : float (None) :: Mpc
      Maximum separation to include
    zmin : float (None)
      Minimum redshift to include

    Returns
    -------
    tbl : Table

    """

    cC = coords.SkyCoord(ra=radec[0], dec=radec[1])

    # Query
    photoobj_fs = ['ra', 'dec', 'objid', 'run', 'rerun', 'camcol', 'field']
    mags = ['petroMag_u', 'petroMag_g', 'petroMag_r', 'petroMag_i', 'petroMag_z']
    magsErr = ['petroMagErr_u', 'petroMagErr_g', 'petroMagErr_r', 'petroMagErr_i', 'petroMagErr_z']

    phot_catalog = SDSS.query_region(cC,spectro=True,radius=radius, timeout=timeout,
                                     photoobj_fields=photoobj_fs+mags+magsErr) # Unique
    spec_catalog = SDSS.query_region(cC,spectro=True, radius=radius, timeout=timeout) # Duplicates exist
    nobj = len(phot_catalog)

    #
    print('grab_sdss_spectra: Found {:d} sources in the search box.'.format(nobj))

    # Coordinates
    cgal = SkyCoord(ra=phot_catalog['ra']*u.degree, dec=phot_catalog['dec']*u.degree)
    sgal = SkyCoord(ra=spec_catalog['ra']*u.degree, dec=spec_catalog['dec']*u.degree)
    sepgal = cgal.separation(cC) #in degrees

    # Check for problems and parse z
    zobj = np.zeros(nobj)
    idx, d2d, d3d = coords.match_coordinates_sky(cgal, sgal, nthneighbor=1)
    if np.max(d2d) > 1.*u.arcsec:
        print('No spectral match!')
        xdb.set_trace()
    else:
        zobj = spec_catalog['z'][idx]

    idx, d2d, d3d = coords.match_coordinates_sky(cgal, cgal, nthneighbor=2)
    if np.min(d2d.to('arcsec')) < 1.*u.arcsec:
        print('Two photometric sources with same RA/DEC')
        xdb.set_trace()

    #xdb.set_trace()


    # Cut on Separation
    if not maxsep is None:
        print('grab_sdss_spectra: Restricting to {:g} Mpc separation.'.format(maxsep))
        sepgal_kpc = cosmo.kpc_comoving_per_arcmin(zobj) * sepgal.to('arcmin')
        sepgal_mpc = sepgal_kpc.to('Mpc')
        gdg = np.where( sepgal_mpc < (maxsep * u.Unit('Mpc')))[0]
        phot_catalog = phot_catalog[gdg]
        #xdb.set_trace()

    nobj = len(phot_catalog)
    print('grab_sdss_spectra: Grabbing data for {:d} sources.'.format(nobj))

    # Grab Spectra from SDSS

    # Generate output table
    attribs = galaxy_attrib()
    npix = 5000 #len( spec_hdus[0][1].data.flux )
    spec_attrib = [(str('FLUX'), np.float32, (npix,)),
                   (str('SIG'), np.float32, (npix,)),
                   (str('WAVE'), np.float64, (npix,))]
    tbl = np.recarray( (nobj,), dtype=attribs+spec_attrib)

    tbl['RA'] = phot_catalog['ra']
    tbl['DEC'] = phot_catalog['dec']
    tbl['TELESCOPE'] = str('SDSS 2.5-M')

    # Deal with spectra separately (for now)
    npix = 5000 #len( spec_hdus[0][1].data.flux )

    for idx,obj in enumerate(phot_catalog):
        #print('idx = {:d}'.format(idx))

        # Grab spectra (there may be duplicates)
        mt = np.where( sgal.separation(cgal[idx]).to('arcsec') < 1.*u.Unit('arcsec'))[0]
        if len(mt) > 1:
            # Use BOSS if you have it
            mmt = np.where( spec_catalog[mt]['instrument'] == 'BOSS')[0]
            if len(mmt) > 0:
                mt = mt[mmt[0]]
            else:
                mt = mt[0]
        elif len(mt) == 0:
            xdb.set_trace()
        else:
            mt = mt[0]

        # Grab spectra
        spec_hdus = SDSS.get_spectra(matches=Table(spec_catalog[mt]))

        tbl[idx]['INSTRUMENT'] = spec_catalog[mt]['instrument']
        spec = spec_hdus[0][1].data
        npp = len(spec.flux)
        tbl[idx]['FLUX'][0:npp] = spec.flux
        sig = np.zeros(npp)
        gdi = np.where(spec.ivar > 0.)[0]
        if len(gdi) > 0:
            sig[gdi] = np.sqrt( 1./spec.ivar[gdi] )
        tbl[idx]['SIG'][0:npp] = sig
        tbl[idx]['WAVE'][0:npp] = 10.**spec.loglam

        # Redshifts
        meta = spec_hdus[0][2].data
        for attrib in ['Z','Z_ERR']:
            tbl[idx][attrib] = meta[attrib]

        if debug:
            sep_to_qso = cgal[idx].separation(cC).to('arcmin')
            print('z = {:g}, Separation = {:g}'.format(tbl[idx].Z, sep_to_qso))
            xdb.set_trace()

        # Fill in rest
        tbl[idx].SDSS_MAG = np.array( [obj[phot] for phot in mags])
        tbl[idx].SDSS_MAGERR = np.array( [obj[phot] for phot in magsErr])

    # Clip on redshift to excise stars/quasars
    if zmin is not None:
        gd = np.where(tbl['Z'] > zmin)[0]
        tbl = tbl[gd]

    # Write to FITS file
    if outfil is not None:
        prihdr = fits.Header()
        prihdr['COMMENT'] = 'SDSS Spectra'
        prihdu = fits.PrimaryHDU(header=prihdr)

        tbhdu = fits.BinTableHDU(tbl)

        thdulist = fits.HDUList([prihdu, tbhdu])
        thdulist.writeto(outfil,clobber=True)

    print('Wrote SDSS table to {:s}'.format(outfil))
    return tbl
Пример #54
0
def do_cleanup(catalog):
    """Task to cleanup catalog before final write."""
    task_str = catalog.get_current_task_str()

    # Set preferred names, calculate some columns based on imported data,
    # sanitize some fields
    keys = catalog.entries.copy().keys()

    cleanupcnt = 0
    for oname in pbar(keys, task_str):
        name = catalog.add_entry(oname)

        # Set the preferred name, switching to that name if name changed.
        name = catalog.entries[name].set_preferred_name()

        aliases = catalog.entries[name].get_aliases()
        catalog.entries[name].set_first_max_light()

        if TIDALDISRUPTION.DISCOVER_DATE not in catalog.entries[name]:
            prefixes = ['MLS', 'SSS', 'CSS', 'GRB ']
            for alias in aliases:
                for prefix in prefixes:
                    if (alias.startswith(prefix) and
                            is_number(alias.replace(prefix, '')[:2])):
                        discoverdate = ('/'.join([
                            '20' + alias.replace(prefix, '')[:2],
                            alias.replace(prefix, '')[2:4],
                            alias.replace(prefix, '')[4:6]
                        ]))
                        if catalog.args.verbose:
                            tprint('Added discoverdate from name [' + alias +
                                   ']: ' + discoverdate)
                        source = catalog.entries[name].add_self_source()
                        catalog.entries[name].add_quantity(
                            TIDALDISRUPTION.DISCOVER_DATE,
                            discoverdate,
                            source,
                            derived=True)
                        break
                if TIDALDISRUPTION.DISCOVER_DATE in catalog.entries[name]:
                    break
        if TIDALDISRUPTION.DISCOVER_DATE not in catalog.entries[name]:
            prefixes = [
                'ASASSN-', 'PS1-', 'PS1', 'PS', 'iPTF', 'PTF', 'SCP-', 'SNLS-',
                'SPIRITS', 'LSQ', 'DES', 'SNHiTS', 'Gaia', 'GND', 'GNW', 'GSD',
                'GSW', 'EGS', 'COS', 'OGLE', 'HST'
            ]
            for alias in aliases:
                for prefix in prefixes:
                    if (alias.startswith(prefix) and
                            is_number(alias.replace(prefix, '')[:2]) and
                            is_number(alias.replace(prefix, '')[:1])):
                        discoverdate = '20' + alias.replace(prefix, '')[:2]
                        if catalog.args.verbose:
                            tprint('Added discoverdate from name [' + alias +
                                   ']: ' + discoverdate)
                        source = catalog.entries[name].add_self_source()
                        catalog.entries[name].add_quantity(
                            TIDALDISRUPTION.DISCOVER_DATE,
                            discoverdate,
                            source,
                            derived=True)
                        break
                if TIDALDISRUPTION.DISCOVER_DATE in catalog.entries[name]:
                    break
        if TIDALDISRUPTION.DISCOVER_DATE not in catalog.entries[name]:
            prefixes = ['SNF']
            for alias in aliases:
                for prefix in prefixes:
                    if (alias.startswith(prefix) and
                            is_number(alias.replace(prefix, '')[:4])):
                        discoverdate = ('/'.join([
                            alias.replace(prefix, '')[:4],
                            alias.replace(prefix, '')[4:6],
                            alias.replace(prefix, '')[6:8]
                        ]))
                        if catalog.args.verbose:
                            tprint('Added discoverdate from name [' + alias +
                                   ']: ' + discoverdate)
                        source = catalog.entries[name].add_self_source()
                        catalog.entries[name].add_quantity(
                            TIDALDISRUPTION.DISCOVER_DATE,
                            discoverdate,
                            source,
                            derived=True)
                        break
                if TIDALDISRUPTION.DISCOVER_DATE in catalog.entries[name]:
                    break
        if TIDALDISRUPTION.DISCOVER_DATE not in catalog.entries[name]:
            prefixes = ['PTFS', 'SNSDF']
            for alias in aliases:
                for prefix in prefixes:
                    if (alias.startswith(prefix) and
                            is_number(alias.replace(prefix, '')[:2])):
                        discoverdate = ('/'.join([
                            '20' + alias.replace(prefix, '')[:2],
                            alias.replace(prefix, '')[2:4]
                        ]))
                        if catalog.args.verbose:
                            tprint('Added discoverdate from name [' + alias +
                                   ']: ' + discoverdate)
                        source = catalog.entries[name].add_self_source()
                        catalog.entries[name].add_quantity(
                            TIDALDISRUPTION.DISCOVER_DATE,
                            discoverdate,
                            source,
                            derived=True)
                        break
                if TIDALDISRUPTION.DISCOVER_DATE in catalog.entries[name]:
                    break
        if TIDALDISRUPTION.DISCOVER_DATE not in catalog.entries[name]:
            prefixes = ['AT', 'SN', 'OGLE-', 'SM ', 'KSN-']
            for alias in aliases:
                for prefix in prefixes:
                    if alias.startswith(prefix):
                        year = re.findall(r'\d+', alias)
                        if len(year) == 1:
                            year = year[0]
                        else:
                            continue
                        if alias.replace(prefix, '').index(year) != 0:
                            continue
                        if (year and is_number(year) and '.' not in year and
                                len(year) <= 4):
                            discoverdate = year
                            if catalog.args.verbose:
                                tprint('Added discoverdate from name [' +
                                       alias + ']: ' + discoverdate)
                            source = catalog.entries[name].add_self_source()
                            catalog.entries[name].add_quantity(
                                TIDALDISRUPTION.DISCOVER_DATE,
                                discoverdate,
                                source,
                                derived=True)
                            break
                if TIDALDISRUPTION.DISCOVER_DATE in catalog.entries[name]:
                    break

        if (TIDALDISRUPTION.RA not in catalog.entries[name] or
                TIDALDISRUPTION.DEC not in catalog.entries[name]):
            prefixes = [
                'PSN J', 'MASJ', 'CSS', 'SSS', 'MASTER OT J', 'HST J', 'TCP J',
                'MACS J', '2MASS J', 'EQ J', 'CRTS J', 'SMT J'
            ]
            for alias in aliases:
                for prefix in prefixes:
                    if (alias.startswith(prefix) and
                            is_number(alias.replace(prefix, '')[:6])):
                        noprefix = alias.split(':')[-1].replace(
                            prefix, '').replace('.', '')
                        decsign = '+' if '+' in noprefix else '-'
                        noprefix = noprefix.replace('+', '|').replace('-', '|')
                        nops = noprefix.split('|')
                        if len(nops) < 2:
                            continue
                        rastr = nops[0]
                        decstr = nops[1]
                        ra = ':'.join([rastr[:2], rastr[2:4], rastr[4:6]]) + \
                            ('.' + rastr[6:] if len(rastr) > 6 else '')
                        dec = (decsign + ':'.join(
                            [decstr[:2], decstr[2:4], decstr[4:6]]) +
                            ('.' + decstr[6:] if len(decstr) > 6 else ''))
                        if catalog.args.verbose:
                            tprint('Added ra/dec from name: ' + ra + ' ' + dec)
                        source = catalog.entries[name].add_self_source()
                        catalog.entries[name].add_quantity(
                            TIDALDISRUPTION.RA, ra, source, derived=True)
                        catalog.entries[name].add_quantity(
                            TIDALDISRUPTION.DEC, dec, source, derived=True)
                        break
                if TIDALDISRUPTION.RA in catalog.entries[name]:
                    break

        no_host = (TIDALDISRUPTION.HOST not in catalog.entries[name] or
                   not any([
                       x[QUANTITY.VALUE] == 'Milky Way'
                       for x in catalog.entries[name][TIDALDISRUPTION.HOST]
                   ]))
        if (TIDALDISRUPTION.RA in catalog.entries[name] and
                TIDALDISRUPTION.DEC in catalog.entries[name] and no_host):
            from astroquery.irsa_dust import IrsaDust
            if name not in catalog.extinctions_dict:
                try:
                    ra_dec = (catalog.entries[name][TIDALDISRUPTION.RA][0][
                        QUANTITY.VALUE] + " " + catalog.entries[name][
                            TIDALDISRUPTION.DEC][0][QUANTITY.VALUE])
                    result = IrsaDust.get_query_table(ra_dec, section='ebv')
                except (KeyboardInterrupt, SystemExit):
                    raise
                except Exception:
                    warnings.warn("Coordinate lookup for " + name +
                                  " failed in IRSA.")
                else:
                    ebv = result['ext SandF mean'][0]
                    ebverr = result['ext SandF std'][0]
                    catalog.extinctions_dict[name] = [ebv, ebverr]
            if name in catalog.extinctions_dict:
                sources = uniq_cdl([
                    catalog.entries[name].add_self_source(),
                    catalog.entries[name]
                    .add_source(bibcode='2011ApJ...737..103S')
                ])
                (catalog.entries[name].add_quantity(
                    TIDALDISRUPTION.EBV,
                    str(catalog.extinctions_dict[name][0]),
                    sources,
                    e_value=str(catalog.extinctions_dict[name][1]),
                    derived=True))
        if ((TIDALDISRUPTION.HOST in catalog.entries[name] and
             (TIDALDISRUPTION.HOST_RA not in catalog.entries[name] or
              TIDALDISRUPTION.HOST_DEC not in catalog.entries[name]))):
            for host in catalog.entries[name][TIDALDISRUPTION.HOST]:
                alias = host[QUANTITY.VALUE]
                if ' J' in alias and is_number(alias.split(' J')[-1][:6]):
                    noprefix = alias.split(' J')[-1].split(':')[-1].replace(
                        '.', '')
                    decsign = '+' if '+' in noprefix else '-'
                    noprefix = noprefix.replace('+', '|').replace('-', '|')
                    nops = noprefix.split('|')
                    if len(nops) < 2:
                        continue
                    rastr = nops[0]
                    decstr = nops[1]
                    hostra = (':'.join([rastr[:2], rastr[2:4], rastr[4:6]]) +
                              ('.' + rastr[6:] if len(rastr) > 6 else ''))
                    hostdec = decsign + ':'.join([
                        decstr[:2], decstr[2:4], decstr[4:6]
                    ]) + ('.' + decstr[6:] if len(decstr) > 6 else '')
                    if catalog.args.verbose:
                        tprint('Added hostra/hostdec from name: ' + hostra +
                               ' ' + hostdec)
                    source = catalog.entries[name].add_self_source()
                    catalog.entries[name].add_quantity(
                        TIDALDISRUPTION.HOST_RA, hostra, source, derived=True)
                    catalog.entries[name].add_quantity(
                        TIDALDISRUPTION.HOST_DEC,
                        hostdec,
                        source,
                        derived=True)
                    break
                if TIDALDISRUPTION.HOST_RA in catalog.entries[name]:
                    break

        if (TIDALDISRUPTION.REDSHIFT not in catalog.entries[name] and
                TIDALDISRUPTION.VELOCITY in catalog.entries[name]):
            # Find the "best" velocity to use for this
            bestsig = 0
            for hv in catalog.entries[name][TIDALDISRUPTION.VELOCITY]:
                sig = get_sig_digits(hv[QUANTITY.VALUE])
                if sig > bestsig:
                    besthv = hv[QUANTITY.VALUE]
                    bestsrc = hv['source']
                    bestsig = sig
            if bestsig > 0 and is_number(besthv):
                voc = float(besthv) * 1.e5 / CLIGHT
                source = catalog.entries[name].add_self_source()
                sources = uniq_cdl([source] + bestsrc.split(','))
                (catalog.entries[name].add_quantity(
                    TIDALDISRUPTION.REDSHIFT,
                    pretty_num(
                        sqrt((1. + voc) / (1. - voc)) - 1., sig=bestsig),
                    sources,
                    kind='heliocentric',
                    derived=True))
        if (TIDALDISRUPTION.REDSHIFT not in catalog.entries[name] and
                len(catalog.nedd_dict) > 0 and
                TIDALDISRUPTION.HOST in catalog.entries[name]):
            reference = "NED-D"
            refurl = "http://ned.ipac.caltech.edu/Library/Distances/"
            for host in catalog.entries[name][TIDALDISRUPTION.HOST]:
                if host[QUANTITY.VALUE] in catalog.nedd_dict:
                    source = catalog.entries[name].add_source(
                        bibcode='2016A&A...594A..13P')
                    secondarysource = catalog.entries[name].add_source(
                        name=reference, url=refurl, secondary=True)
                    meddist = statistics.median(catalog.nedd_dict[host[
                        QUANTITY.VALUE]])
                    redz = z_at_value(cosmo.comoving_distance,
                                      float(meddist) * un.Mpc)
                    redshift = pretty_num(
                        redz, sig=get_sig_digits(str(meddist)))
                    catalog.entries[name].add_quantity(
                        TIDALDISRUPTION.REDSHIFT,
                        redshift,
                        uniq_cdl([source, secondarysource]),
                        kind='host',
                        derived=True)
        if (TIDALDISRUPTION.MAX_ABS_MAG not in catalog.entries[name] and
                TIDALDISRUPTION.MAX_APP_MAG in catalog.entries[name] and
                TIDALDISRUPTION.LUM_DIST in catalog.entries[name]):
            # Find the "best" distance to use for this
            bestsig = 0
            for ld in catalog.entries[name][TIDALDISRUPTION.LUM_DIST]:
                sig = get_sig_digits(ld[QUANTITY.VALUE])
                if sig > bestsig:
                    bestld = ld[QUANTITY.VALUE]
                    bestsrc = ld['source']
                    bestsig = sig
            if bestsig > 0 and is_number(bestld) and float(bestld) > 0.:
                source = catalog.entries[name].add_self_source()
                sources = uniq_cdl([source] + bestsrc.split(','))
                bestldz = z_at_value(cosmo.luminosity_distance,
                                     float(bestld) * un.Mpc)
                pnum = (float(catalog.entries[name][
                    TIDALDISRUPTION.MAX_APP_MAG][0][QUANTITY.VALUE]) - 5.0 *
                    (log10(float(bestld) * 1.0e6) - 1.0
                     ) + 2.5 * log10(1.0 + bestldz))
                pnum = pretty_num(pnum, sig=bestsig)
                catalog.entries[name].add_quantity(
                    TIDALDISRUPTION.MAX_ABS_MAG, pnum, sources, derived=True)
        if TIDALDISRUPTION.REDSHIFT in catalog.entries[name]:
            # Find the "best" redshift to use for this
            bestz, bestkind, bestsig, bestsrc = catalog.entries[
                name].get_best_redshift()
            if bestsig > 0:
                try:
                    bestz = float(bestz)
                except Exception:
                    print(catalog.entries[name])
                    raise
                if TIDALDISRUPTION.VELOCITY not in catalog.entries[name]:
                    source = catalog.entries[name].add_self_source()
                    # FIX: what's happening here?!
                    pnum = CLIGHT / KM * \
                        ((bestz + 1.)**2. - 1.) / ((bestz + 1.)**2. + 1.)
                    pnum = pretty_num(pnum, sig=bestsig)
                    catalog.entries[name].add_quantity(
                        TIDALDISRUPTION.VELOCITY,
                        pnum,
                        source,
                        kind=PREF_KINDS[bestkind],
                        derived=True)
                if bestz > 0.:
                    from astropy.cosmology import Planck15 as cosmo
                    if TIDALDISRUPTION.LUM_DIST not in catalog.entries[name]:
                        dl = cosmo.luminosity_distance(bestz)
                        sources = [
                            catalog.entries[name].add_self_source(),
                            catalog.entries[name]
                            .add_source(bibcode='2016A&A...594A..13P')
                        ]
                        sources = uniq_cdl(sources + bestsrc.split(','))
                        catalog.entries[name].add_quantity(
                            TIDALDISRUPTION.LUM_DIST,
                            pretty_num(
                                dl.value, sig=bestsig),
                            sources,
                            kind=PREF_KINDS[bestkind],
                            derived=True)
                        if (TIDALDISRUPTION.MAX_ABS_MAG not in
                                catalog.entries[name] and
                                TIDALDISRUPTION.MAX_APP_MAG in
                                catalog.entries[name]):
                            source = catalog.entries[name].add_self_source()
                            pnum = pretty_num(
                                float(catalog.entries[name][
                                    TIDALDISRUPTION.MAX_APP_MAG][0][
                                        QUANTITY.VALUE]) - 5.0 *
                                (log10(dl.to('pc').value) - 1.0
                                 ) + 2.5 * log10(1.0 + bestz),
                                sig=bestsig + 1)
                            catalog.entries[name].add_quantity(
                                TIDALDISRUPTION.MAX_ABS_MAG,
                                pnum,
                                sources,
                                derived=True)
                    if TIDALDISRUPTION.COMOVING_DIST not in catalog.entries[
                            name]:
                        cd = cosmo.comoving_distance(bestz)
                        sources = [
                            catalog.entries[name].add_self_source(),
                            catalog.entries[name]
                            .add_source(bibcode='2016A&A...594A..13P')
                        ]
                        sources = uniq_cdl(sources + bestsrc.split(','))
                        catalog.entries[name].add_quantity(
                            TIDALDISRUPTION.COMOVING_DIST,
                            pretty_num(
                                cd.value, sig=bestsig),
                            sources,
                            derived=True)
        if all([
                x in catalog.entries[name]
                for x in [
                    TIDALDISRUPTION.RA, TIDALDISRUPTION.DEC,
                    TIDALDISRUPTION.HOST_RA, TIDALDISRUPTION.HOST_DEC
                ]
        ]):
            # For now just using first coordinates that appear in entry
            try:
                c1 = coord(
                    ra=catalog.entries[name][TIDALDISRUPTION.RA][0][
                        QUANTITY.VALUE],
                    dec=catalog.entries[name][TIDALDISRUPTION.DEC][0][
                        QUANTITY.VALUE],
                    unit=(un.hourangle, un.deg))
                c2 = coord(
                    ra=catalog.entries[name][TIDALDISRUPTION.HOST_RA][0][
                        QUANTITY.VALUE],
                    dec=catalog.entries[name][TIDALDISRUPTION.HOST_DEC][0][
                        QUANTITY.VALUE],
                    unit=(un.hourangle, un.deg))
            except (KeyboardInterrupt, SystemExit):
                raise
            except Exception:
                pass
            else:
                sources = uniq_cdl(
                    [catalog.entries[name].add_self_source()] + catalog.
                    entries[name][TIDALDISRUPTION.RA][0]['source'].split(',') +
                    catalog.entries[name][TIDALDISRUPTION.DEC][0]['source'].
                    split(',') + catalog.entries[name][TIDALDISRUPTION.HOST_RA]
                    [0]['source'].split(',') + catalog.entries[name][
                        TIDALDISRUPTION.HOST_DEC][0]['source'].split(','))
                if 'hostoffsetang' not in catalog.entries[name]:
                    hosa = Decimal(
                        hypot(c1.ra.degree - c2.ra.degree, c1.dec.degree -
                              c2.dec.degree))
                    hosa = pretty_num(hosa * Decimal(3600.))
                    catalog.entries[name].add_quantity(
                        TIDALDISRUPTION.HOST_OFFSET_ANG,
                        hosa,
                        sources,
                        derived=True,
                        u_value='arcseconds')
                if (TIDALDISRUPTION.COMOVING_DIST in catalog.entries[name] and
                        TIDALDISRUPTION.REDSHIFT in catalog.entries[name] and
                        TIDALDISRUPTION.HOST_OFFSET_DIST not in
                        catalog.entries[name]):
                    offsetsig = get_sig_digits(catalog.entries[name][
                        TIDALDISRUPTION.HOST_OFFSET_ANG][0][QUANTITY.VALUE])
                    sources = uniq_cdl(
                        sources.split(',') + (catalog.entries[name][
                            TIDALDISRUPTION.COMOVING_DIST][0]['source']).
                        split(',') + (catalog.entries[name][
                            TIDALDISRUPTION.REDSHIFT][0]['source']).split(','))
                    (catalog.entries[name].add_quantity(
                        TIDALDISRUPTION.HOST_OFFSET_DIST,
                        pretty_num(
                            float(catalog.entries[name][
                                TIDALDISRUPTION.HOST_OFFSET_ANG][0][
                                QUANTITY.VALUE]) / 3600. * (pi / 180.) *
                            float(catalog.entries[name][
                                TIDALDISRUPTION.COMOVING_DIST][0][
                                    QUANTITY.VALUE]) * 1000. /
                            (1.0 + float(catalog.entries[name][
                                TIDALDISRUPTION.REDSHIFT][0][QUANTITY.VALUE])),
                            sig=offsetsig),
                        sources))

        catalog.entries[name].sanitize()
        catalog.journal_entries(bury=True, final=True, gz=True)
        cleanupcnt = cleanupcnt + 1
        if catalog.args.travis and cleanupcnt % 1000 == 0:
            break

    catalog.save_caches()

    return
Пример #55
0
def u2kperp(u,z):
    return u*2.*pi/pl15.comoving_distance(z).value
Пример #56
0
def X(f):
    z=f21/f-1
    return pl15.comoving_distance(z).value
Пример #57
0
Zneb.set_index('label', inplace=True)
Zneb['Zneb_solar'] = 10**(Zneb['12+logOH'] - 8.69)
Zneb['Zneb_sig']   = 10**(Zneb['12+logOH'] + Zneb['sigZ'] - 8.69) - 10**(Zneb['12+logOH']  - 8.69)
Zneb.loc[Zneb['sigZ'] == -99, 'Zneb_sig'] = np.int(-99)
Zneb.loc[Zneb['sigZ'] == -9, 'Zneb_sig'] = np.int(-9)

# Load the Megasaura spectra
(sp, resoln, dresoln, LL, zz_sys, speclist) = jrr.mage.open_many_spectra(mage_mode, which_list="wcont", zchoice='neb', addS99=True, MWdr=True, silent=True, verbose=False)

wave_targ = 1500.0  # where to measure rest-frame flux density, Angstroms
wave_win = 10.      # window +-1500, to measure rest-frame flux density.  units are rest-frame Angstroms

print("label   EBV_S99  sigma_EBV  Zneb  sigZ  Z_S99   age_S99  fnu1500  fnu1500_dered  SFR_raw  SFR_dered")
print("#(SFRs and fnus not yet corrected for magnification)")
for label in speclist['short_label'] :
    fnu1500 = sp[label]['rest_fnu'].loc[sp[label]['rest_wave'].between(wave_targ - wave_win, wave_targ + wave_win)].median()
    if label in S99.index :  # if there's a EBV from S99 fit
        jrr.spec.deredden_internal_extinction(sp[label], S99.loc[label]['EBV'])
        fnu1500_dered = sp[label]['rest_fnu_dered'].loc[sp[label]['rest_wave'].between(wave_targ - wave_win, wave_targ + wave_win)].median()
        zz = speclist.loc[label]['z_syst']
        flux_to_lum = 4 * pi * (cosmo.luminosity_distance(zz).cgs.value)**2     # Apply luminosity distance
        K98_convert = 1.4E-28  # Eqn 1 of Kennicutt et al. 1998, units are erg/s/Hz
        SFR_raw   =  fnu1500 * flux_to_lum * K98_convert        # ** Magnification should be divided here
        SFR_dered =  fnu1500_dered * flux_to_lum * K98_convert  # ** Magnification should be divided here
        print(label, S99.loc[label]['EBV'],  S99.loc[label]['sigmaEBV'], Zneb.loc[label]['Zneb_solar'],  Zneb.loc[label]['Zneb_sig'], end=' ')
        print(S99.loc[label]['ZS99'],  S99.loc[label]['tS99'], fnu1500, fnu1500_dered, SFR_raw, SFR_dered)


# Make a new data frame w results, and dump it to a file.
galprops =  pandas.read_table("mage_galproperties.txt", delim_whitespace=True, comment="#")
Пример #58
0
xim = np.arange(-3,3,.03)
yim = np.arange(-3,3,.03)

xim,yim = np.meshgrid(xim,yim)

zLens,zSource = 0.8,5.656
xLens,yLens = 0.,0.
MLens,eLens,PALens = 2.87e11,0.5,90.
xSource,ySource,FSource,sSource = 0.216,-0.24,0.023,0.074

Lens = vl.SIELens(zLens,xLens,yLens,MLens,eLens,PALens)
Shear= vl.ExternalShear(0.,0.)
lens = [Lens,Shear]
Source = vl.GaussSource(zSource,True,xSource,ySource,FSource,sSource)
Dd = cosmo.angular_diameter_distance(zLens).value
Ds = cosmo.angular_diameter_distance(zSource).value
Dds = cosmo.angular_diameter_distance_z1z2(zLens,zSource).value
caustics = vl.get_caustics(lens,Dd,Ds,Dds)

xsource,ysource = vl.LensRayTrace(xim,yim,lens,Dd,Ds,Dds)


f = pl.figure()
ax = f.add_subplot(111,aspect='equal')
pl.subplots_adjust(bottom=0.25,top=0.98)

ax.plot(xsource,ysource,'b-')
for caustic in caustics:
      ax.plot(caustic[:,0],caustic[:,1],'k-')
Пример #59
0
from opstats.utils import MWA_FREQ_EOR_ALL_80KHZ as F
from opstats.utils import F21


# Simulation parameters
nf = F.size
nside = 4096
cube_res = 1000 / 128
cube_size = 128

cube_files = ['/data6/piyanat/models/21cm/cubes/interpolated/'
              'interp_delta_21cm_l128_{:.3f}MHz.npy'
              .format(f) for f in F]

dc = Cosmo.comoving_distance(F21 / (F * 1e6) - 1).value

vx0, vy0, vz0 = hp.pix2vec(nside, 0)  # North Pole vector
zi0 = np.mod(np.around(vz0 * dc / cube_res).astype(int), cube_size)

# We will concatenate zi0[j] slices, so that pixels (j, 0, 0) of
# the cube match central l.o.s. pixels on the sine projected lightcone.
trad_lightcone = np.empty((nf, cube_size, cube_size))
for j in range(nf):
    cube = np.load(cube_files[j])
    cube -= cube.mean()
    trad_lightcone[j] = cube[:, :, zi0[j]].T

# Save out the traditional lightcone
trad_lightcone_x = np.arange(-64, 64) * 1000 / 128
trad_lightcone_da = xr.DataArray(