def llhood_pbd_wcdm(model_param, ndim, nparam): om, h0, w0, MB, od, g = [model_param[i] for i in range(6)] wa = 0 A = [] for i in range(0, len(pb.zcmb.values)): At = 10**(od) * attenuation(om, h0, pb.zcmb.values[i], w0, wa, g) A.append(At) #A_inter = interp1d(z50, A) #DUST = A_inter(pb.zcmb.values) dist_th = wCDM(h0, om, 1 - om, w0).luminosity_distance(pb.zcmb.values).value mod_th = 5 * np.log10(dist_th) + 25 hub_res = pb.mb.values - mod_th - MB - A chisq = np.dot(hub_res.T, np.dot(pb_icm, hub_res)) if cmb == 1: T = cmb_chisq(om, h0, w0, wa) chisq += T return -0.5 * chisq
def llhood_jlad_wcdm(model_param, ndim, nparam): om, w0, a, b, MB, DM, od, g = [model_param[i] for i in range(8)] h0 = 70 wa = 0 A = [] for i in range(0, 50): At = 10**(od) * attenuation(om, h0, z50[i], w0, wa, g) A.append(At) A_inter = interp1d(z50, A) DUST = A_inter(jla.zcmb.values) dist_th = wCDM(h0, om, 1 - om, w0).luminosity_distance(jla.zcmb.values).value mod_th = 5 * np.log10(dist_th) + 25 hub_res = jla.mb.values + a * jla.x1.values - b * jla.color.values - MB - mod_th - DUST hub_res[jla.hm.values >= 10.] += DM C = mu_cov(a, b) iC = np.linalg.inv(C) chisq = np.dot(hub_res.T, np.dot(iC, hub_res)) if cmb == 1: T = cmb_chisq(om, h0, w0, wa) chisq += T return -0.5 * chisq
def test_redshift_array(nz=4096): from astropy import cosmology cosmo = cosmology.wCDM(H0=0.71,Om0=0.31,Ode0=0.69,w0=-1) zmax = 10. distance = lambda z: cosmo.comoving_distance(z).value*cosmo.h redshift = DistanceToRedshiftArray(distance=distance,zmax=zmax,nz=nz) z = scipy.random.uniform(0.,2.,10000) print scipy.absolute(redshift(distance(z))-z).max()
def load_cosmology(self, handle: h5py.File) -> Cosmology: """ Save the (astropy) cosmology to a HDF5 dataset. Parameters ---------- handle: h5py.File h5py file handle for the catalogue file. Returns ------- astropy.cosmology.Cosmology: Astropy cosmology instance extracted from the HDF5 file. Also sets ``self.cosmology``. """ try: group = handle["Configuration"].attrs except: return None # Note that some of these are unused - commented out if not. H0 = 100.0 * float(group["h_val"]) w_of_DE = float(group["w_of_DE"]) Omega_DE = float(group["Omega_DE"]) # Omega_Lambda = float(group["Omega_Lambda"]) Omega_b = float(group["Omega_b"]) # Omega_cdm = float(group["Omega_cdm"]) # Omega_k = float(group["Omega_k"]) Omega_m = float(group["Omega_m"]) # Omega_nu = float(group["Omega_nu"]) # Omega_r = float(group["Omega_r"]) if w_of_DE != -1.0: cosmology = wCDM( H0=H0, Om0=Omega_m, Ode0=Omega_DE, w0=w_of_DE, Ob0=Omega_b, ) else: # No EoS cosmology = FlatLambdaCDM( H0=H0, Om0=Omega_m, Ob0=Omega_b, ) self.cosmology = cosmology return cosmology
def HaloLensedImage(self, *args): self.ax.clear() self.ax.axis('off') fileimage = CWD + "/tmp/" + self.img_filenamedir + "_image.jpg" Simu_Dir = self.model_select() + "/Lens-Maps/" filelens = self.simdir + "/" + Simu_Dir + self.model_name + '_Halo.fits' image, xsize, ysize = readimage(fileimage) image_arr = np.array(image) alpha1, alpha2 = buildlens(filelens) cosmo = wCDM(70.3, self.slider_dm.value, self.slider_de.value, w0=-1.0) self.halolensedimage = deflect(image_arr, alpha1, alpha2, xsize, ysize, self.slider_comdist.value, cosmo, "HALO") self.ax.imshow(self.halolensedimage) arr_hand1 = mpimg.imread("./icons/simcode.png") imagebox1 = OffsetImage(arr_hand1, zoom=.1) xy = [950.0, 85.0] ab1 = AnnotationBbox(imagebox1, xy, xybox=(0., 0.), xycoords='data', boxcoords="offset points", pad=0.1) self.ax.add_artist(ab1) sim_details_text = '%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s' % ( text_dict['t42'], self.input_name.text, text_dict['t53'], self.SC_Type, text_dict['t20'], self.spinner_de.text, text_dict['t24'], self.spinner_dm.text, text_dict['t27'], self.spinner_png.text, text_dict['t31'], self.spinner_gvr.text) print sim_details_text self.ax.text(0.1, 0.83, sim_details_text, color='white', bbox=dict(facecolor='none', edgecolor='white', boxstyle='round,pad=1', alpha=0.5), transform=self.ax.transAxes, alpha=0.5) self.ax.axis('off') self.ax.get_xaxis().set_visible(False) self.ax.get_yaxis().set_visible(False) self.canvas.draw() #imsave(self.savedir + "/" + self.img_filename + "_LensedHalo_Photo.jpg", self.halolensedimage) self.fig.savefig(self.savedir + "/" + self.img_filenamedir + "/" + self.img_filenamedir + "_LensedHalo_Photo.png") self.LensedHalo_Photo = self.img_filename + "_LensedHalo_Photo.png" self.showlenscluster()
def plot_hd(self, fname, f='yD', showplot=True, res=False, rowtoskip=2): cols=np.loadtxt(fname, usecols=(1,2,3), skiprows=rowtoskip) #default cosmology, flat, (om, w) = (0.27, -1) wc = wCDM(70, 0.27, 0.73) if res: hres = cols[:,1] - np.mean(cols[:,1]) else: hres = 5*np.log10(wc.luminosity_distance(cols[:,0]).value)+25 + cols[:,1] plt.errorbar(cols[:,0], hres, cols[:,2], fmt=f) plt.show()
def plot_hd(self, fname, f='yD', showplot=True, res=False, rowtoskip=2): cols = np.loadtxt(fname, usecols=(1, 2, 3), skiprows=rowtoskip) #default cosmology, flat, (om, w) = (0.27, -1) wc = wCDM(70, 0.27, 0.73) if res: hres = cols[:, 1] - np.mean(cols[:, 1]) else: hres = 5 * np.log10(wc.luminosity_distance( cols[:, 0]).value) + 25 + cols[:, 1] plt.errorbar(cols[:, 0], hres, cols[:, 2], fmt=f) plt.show()
def define_cosmology(self, cosmology_config): """Define the cosmology based on `cfg.bnn_omega.cosmology` Parameters ---------- cosmology_config : dict Copy of cfg.bnn_omega.cosmology Returns ------- astropy.cosmology.wCDM object the cosmology with which to generate all the training samples """ self.cosmo = wCDM(**cosmology_config)
def load_cosmology(handle: h5py.File): """ Save the (astropy) cosmology to a HDF5 dataset. Parameters ---------- handle: h5py.File h5py file handle to read the cosmology from. Returns ------- astropy.cosmology.Cosmology: Astropy cosmology instance extracted from the HDF5 file. """ try: group = handle["cosmology"].attrs except: return None try: cosmology = wCDM( H0=group["H0"], Om0=group["Om0"], Ode0=group["Ode0"], w0=group["w0"], Tcmb0=group["Tcmb0"], Neff=group["Neff"], m_nu=Quantity(group["m_nu"], unit=group["m_nu_units"]), Ob0=group["Ob0"], name=group["name"], ) except KeyError: # No EoS cosmology = FlatLambdaCDM( H0=group["H0"], Om0=group["Om0"], Tcmb0=group["Tcmb0"], Neff=group["Neff"], m_nu=Quantity(group["m_nu"], unit=group["m_nu_units"]), Ob0=group["Ob0"], name=group["name"], ) return cosmology
def llhood_jbc_wcdm(model_param, ndim, nparam): om, h0, w0 = [model_param[i] for i in range(3)] wa = 0 dist_th = wCDM(h0, om, 1 - om, w0).luminosity_distance(jb.zb.values).value mod_th = 5 * np.log10(dist_th) + 25 hub_res = jb.mub.values - mod_th chisq = np.dot(hub_res.T, np.dot(jb_icm, hub_res)) if cmb == 1: T = cmb_chisq(om, h0, w0, wa) chisq += T return -0.5 * chisq
def set_cosmology(cosmology=None): """ Get an instance of a astropy.cosmology.FLRW subclass. To avoid repeatedly instantiating the same class, test if it is the same as the last used cosmology. Parameters ========== cosmology: astropy.cosmology.FLRW, str, dict Description of cosmology, one of: None - Use DEFAULT_COSMOLOGY Instance of astropy.cosmology.FLRW subclass String with name of known Astropy cosmology, e.g., "Planck13" Dictionary with arguments required to instantiate the cosmology class. Returns ======= cosmo: astropy.cosmology.FLRW Cosmology instance """ from astropy import cosmology as cosmo _set_default_cosmology() if cosmology is None: cosmology = DEFAULT_COSMOLOGY elif isinstance(cosmology, cosmo.FLRW): cosmology = cosmology elif isinstance(cosmology, str): cosmology = cosmo.__dict__[cosmology] elif isinstance(cosmology, dict): if 'Ode0' in cosmology.keys(): if 'w0' in cosmology.keys(): cosmology = cosmo.wCDM(**cosmology) else: cosmology = cosmo.LambdaCDM(**cosmology) else: cosmology = cosmo.FlatLambdaCDM(**cosmology) COSMOLOGY[0] = cosmology if cosmology.name is not None: COSMOLOGY[1] = cosmology.name else: COSMOLOGY[1] = repr(cosmology)
def llhood_jlac_wcdm(model_param, ndim, nparam): om, w0, a, b, MB, DM = [model_param[i] for i in range(6)] h0 = 70 wa = 0 dist_th = wCDM(h0, om, 1 - om, w0).luminosity_distance(jla.zcmb.values).value mod_th = 5 * np.log10(dist_th) + 25 hub_res = jla.mb.values + a * jla.x1.values - b * jla.color.values - MB - mod_th hub_res[jla.hm.values >= 10.] += DM C = mu_cov(a, b) iC = np.linalg.inv(C) chisq = np.dot(hub_res.T, np.dot(iC, hub_res)) if cmb == 1: T = cmb_chisq(om, h0, w0, wa) chisq += T return -0.5 * chisq
def sim_nonStand(self): Simu_Dir = self.model_select() + "/Dens-Maps/" cosmo = wCDM(70.3, self.slider_dm.value, self.slider_de.value, w0=-1.0) filenames = sorted(glob.glob(self.simdir + "/" + Simu_Dir + '*.npy')) lga = np.linspace(np.log(0.05), np.log(1.0), 300) a = np.exp(lga) z = 1. / a - 1.0 lktime = cosmo.lookback_time(z).value def animate(filename): image = np.load(filename) indx = filenames.index( filename ) #; image=ndimage.gaussian_filter(image, sigma= sigmaval, truncate=truncateval, mode='wrap') im.set_data(image + 1) #; im.set_clim(image.min()+1.,image.max()+1.) self.time.set_text('%s %s' % (round(lktime[indx], 4), text_dict['t49'])) return im dens_map = np.load( filenames[0] ) #; dens_map=ndimage.gaussian_filter(dens_map, sigma= sigmaval, truncate=truncateval, mode='wrap') #; dens_map0 = load(filenames[-1]); #print dens_map0.min()+1, dens_map0.max()+1. im = self.ax.imshow(dens_map + 1, cmap=cm.magma, norm=colors.LogNorm(vmin=1., vmax=1800., clip=True), interpolation="bicubic") #, clim = (1, 1800.+1.)) self.time = self.ax.text(0.1, 0.05, text_dict['t43'] + ' %s Gyr' % round(lktime[0], 4), horizontalalignment='left', verticalalignment='top', color='white', transform=self.ax.transAxes, fontsize=10) arr_hand = mpimg.imread(CWD + "/tmp/" + self.img_filenamedir + "_image.jpg") imagebox = OffsetImage(arr_hand, zoom=.1) xy = (0.1, 0.15) # coordinates to position this image ab = AnnotationBbox(imagebox, xy, xybox=(0.1, 0.15), xycoords='axes fraction', boxcoords='axes fraction', pad=0.1) self.ax.add_artist(ab) arr_hand1 = mpimg.imread("./icons/simcode.png") imagebox1 = OffsetImage(arr_hand1, zoom=.1) xy = (0.9, 0.9) # coordinates to position this image ab1 = AnnotationBbox(imagebox1, xy, xybox=(0.9, 0.9), xycoords='axes fraction', boxcoords='axes fraction', pad=0.1) self.ax.add_artist(ab1) #iMpc = lambda x: x*1024/125 #x in Mpc, return in Pixel *3.085e19 ob = AnchoredHScaleBar(size=0.1, label="10Mpc", loc=4, frameon=False, pad=0.6, sep=2, color="white", linewidth=0.8) self.ax.add_artist(ob) sim_details_text = '%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s' % ( text_dict['t42'], self.input_name.text, text_dict['t53'], self.SC_Type, text_dict['t20'], self.spinner_de.text, text_dict['t24'], self.spinner_dm.text, text_dict['t27'], self.spinner_png.text, text_dict['t31'], self.spinner_gvr.text) print sim_details_text self.ax.text(0.1, 0.83, sim_details_text, color='white', bbox=dict(facecolor='none', edgecolor='white', boxstyle='round,pad=1', alpha=0.5), transform=self.ax.transAxes, alpha=0.5) self.ani = animation.FuncAnimation(self.fig, animate, filenames, repeat=False, interval=25, blit=False) self.ax.axis('off') self.ax.get_xaxis().set_visible(False) self.ax.get_yaxis().set_visible(False) self.canvas.draw()
raise TypeError('Angular resolution parameter must be a scalar') fwhm_angres = fwhm_angres * U.arcmin cosmoparms = parms['sim']['cosmo'] if cosmoparms['name'] is None: cosmo = None elif cosmoparms['name'].lower() == 'custom': h = cosmoparms['h'] H0 = 100.0 * h Om0 = cosmoparms['Om0'] Ode0 = cosmoparms['Ode0'] if Ode0 is None: Ode0 = 1.0 - Om0 Ob0 = cosmoparms['Ob0'] / h**2 w0 = cosmoparms['w0'] cosmo = cosmology.wCDM(H0, Om0, Ode0, w0=w0, Ob0=Ob0) elif cosmoparms['name'].lower() == 'wmap9': cosmo = cosmology.WMAP9 else: raise ValueError('{0} preset not currently accepted for cosmology'.format(cosmoparms['name'].lower())) units = parms['sim']['units'] if not isinstance(units, str): raise TypeError('Input units must be a string') if units not in ['mK', 'K']: raise ValueError('Supported units are "mK" and "K"') if units == 'mK': conv_factor = 1e-3 units = 'K' else: conv_factor = 1.0
def Comoving_Distance(z, Omega_M, Omega_L, w_o, w_a): wcdm = cosmo.wCDM(H0=70., Om0=Omega_M, Ode0=Omega_L, w0=w_o) return np.array(wcdm.comoving_distance(z))
# plot the contour positions - they're half way between the edges: xbins = 0.5 * (xedges[:-1] + xedges[1:]) ybins = 0.5 * (yedges[:-1] + yedges[1:]) # now plot the contours ax.hist2d(x, y, bins=150) ax.contour(xbins, ybins, vals.T, 20, colors='k', zorder=10) ax.set_xlim([-23, -16]) ax.set_ylim([0, 3.5]) ax.set_xlabel('M r,petro') ax.set_ylabel('(u-r)model') title_str = 'Observed bivariate distribution of the sample in rest-frame color vs. \ absolute magnitude. Sample size ' + str( len(x)) + ' galaxies. Colour plot 150 bins, Contour plot 30 bins.' ax.set_title(title_str) plt.show() cosmo = FlatLambdaCDM(H0=70 * u.km / u.s / u.Mpc, Om0=0.3) cosmo3 = wCDM(H0=70, Om0=0.3, Ode0=0.7, w0=-0.9) cosmo4 = LambdaCDM(H0=70, Om0=0.3, Ode0=0.7) cosmo5 = wCDM(H0=70, Om0=0, Ode0=0.7, w0=-0.9) #choose_cosmo_cm_diagram(cosmo) #choose_cosmo_cm_diagram(cosmo1) choose_cosmo_cm_diagram(cosmo2) #choose_cosmo_cm_diagram(cosmo3) #choose_cosmo_cm_diagram(cosmo4) #choose_cosmo_cm_diagram(cosmo5)
def generate_elg_random(mjd, chunk, area, output_path, random_path, out_random, out_catalog, out_dndz, z_min, z_max, binwidth_z, weights, tiling_compl_cut, redshift_compl_cut, down_sample_fact, H0, omega_m, omega_lam, w_DE): run_info = open(output_path + '/run.info', 'a') # Read plate centers tilelist = ascii.read('data/ebosstiles.dat') tiles = tilelist["TILE"] racen = tilelist["racen"] deccen = tilelist["deccen"] obs_tiles = np.loadtxt(output_path + '/tiles.txt') rac = [] decc = [] i = 0 for tile in tiles: if tile in obs_tiles: rac.append(racen[i]) decc.append(deccen[i]) i += 1 rac = np.asarray(rac) rac = np.where(rac > 270., rac - 360., rac) decc = np.asarray(decc) nplates = len(rac) #---------------------- # open random fits catalog hdu = fits.open(random_path) data = hdu[1].data tmp = data['ra'] randra = np.where(tmp > 270., tmp - 360., tmp) randdec = data['dec'] #---------------------- # Modify the random number density idx = np.random.choice(len(randra), size=int(len(randra) / down_sample_fact)) new_density = (10000. / down_sample_fact) info_line = ("Number density in the random catalog: %.2f deg^-2\n\n" % new_density) print info_line run_info.write(info_line) randra = randra[idx] randdec = randdec[idx] nrand = len(randra) randSkyCoord = SkyCoord(ra=randra * u.deg, dec=randdec * u.deg, frame='fk5') #-------------------- # open data ascii file created by function 'generate_elg_catalog' tmp = ascii.read(out_catalog + '.dat') datara = tmp['ra'] datadec = tmp['dec'] dataz = tmp['z'] dataw_compl = tmp['w_compl'] dataw_sys = tmp['w_sys'] ndata = len(datara) #-------------------- # selecting randoms within the plate inplate = np.zeros(nrand, dtype='bool') tile_rad = 1.49 for k in range(nplates): cenSkyCoord = SkyCoord(ra=rac[k] * u.deg, dec=decc[k] * u.deg, frame='fk5') tmp = (randSkyCoord.separation(cenSkyCoord).deg <= tile_rad) inplate[tmp] = True randra = np.asarray(randra[inplate]) randdec = np.asarray(randdec[inplate]) #------------------------------------- # Remove randoms with a completeness below a certain treshold randc = rand_compl('tiling', randra, randdec, mjd, chunk) if tiling_compl_cut > 0.: tmp = (randc >= tiling_compl_cut) randra = randra[tmp] randdec = randdec[tmp] randc = rand_compl('redshift', randra, randdec, mjd, chunk) if redshift_compl_cut > 0.: tmp = (randc >= redshift_compl_cut) randra = randra[tmp] randdec = randdec[tmp] nrand = len(randra) # assign random redshift to random objects, # following the same redshift distribution as in data dataw_tot = dataw_compl * dataw_sys randz = np.random.choice(dataz, size=nrand, p=dataw_tot / sum(dataw_tot)) #------------------------------------ mbins = my_arange(z_min, z_max, binwidth_z) ###---------------### ### TOTAL WEIGHTS ### ###---------------### # To be assigned to data and random randw = np.ones(nrand) dataw_FKP = np.ones(ndata) if 3 in weights: # The FKP weights def weight_FKP(x): return 1. / (1. + x * 10000.) # open the data redshift distribution tmp = ascii.read(out_dndz + '.dat') bincenters = tmp['z'] nz = tmp['nz'] # Calculation of the comoving volume cosmo = wCDM(H0=H0, Om0=omega_m, Ode0=omega_lam, w0=w_DE) # sky surface = 4pi sr = 129600/pi deg^2 tmp = cosmo.comoving_volume(mbins).value * ( np.pi / 129600.) * cosmo.h**3. # h^-3 * Mpc^3 / deg^2 dV = tmp[1:] - tmp[:-1] nz = nz / area / dV #----------------------------------- # Fitting of the redshift distribution with a skew gaussian # mu, sigmag, alpha, a, c1, c2, c3 skew_init = [np.mean(dataz), np.std(dataz), 0., max(nz), 0., 0., 0.] # initial guess popt = fit_redshift_dist(bincenters, nz, skew_init) # optimal parameters of the fit info_line = ("Initial guess for the fit of n(z):\n") info_line += ("mu = %.2f\n" % skew_init[0]) info_line += ("sigma = %.2f\n" % skew_init[1]) info_line += ("alpha = %.2f\n" % skew_init[2]) info_line += ("amp = %.2e\n" % skew_init[3]) info_line += ("c1 = %.2e\n" % skew_init[4]) info_line += ("c2 = %.2e\n" % skew_init[5]) info_line += ("c3 = %.2e\n\n" % skew_init[6]) print info_line run_info.write(info_line) info_line = ("Output parameters for the fit of n(z):\n") info_line += ("mu = %.2f\n" % popt[0]) info_line += ("sigma = %.2f\n" % popt[1]) info_line += ("alpha = %.2f\n" % popt[2]) info_line += ("amp = %.2e\n" % popt[3]) info_line += ("c1 = %.2e\n" % popt[4]) info_line += ("c2 = %.2e\n" % popt[5]) info_line += ("c3 = %.2e\n\n" % popt[6]) print info_line run_info.write(info_line) #------------------------------------------------------- # Calculate the FKP for data and randoms nz_fit = skew_gauss(randz, *popt) randw = weight_FKP(nz_fit) nz_fit = skew_gauss(dataz, *popt) dataw_FKP = weight_FKP(nz_fit) #--------------------------------------- # print n(z) plt.figure() tmp = np.linspace(z_min, z_max, 1000) plt.plot(bincenters, nz * 1.e4, 'bo', label='data') plt.plot(tmp, skew_gauss(tmp, *skew_init) * 1.e4, 'g-', label='inital guess') plt.plot(tmp, skew_gauss(tmp, *popt) * 1.e4, 'r-', label='final fit') plt.legend(loc='upper right') plt.xlabel(r'$z$', size=18) plt.ylabel(r'$n(z)$ [$10^{-4}h^3$Mpc$^{-3}$]', size=18) plt.savefig(output_path + '/nz_fit.pdf', format='pdf') # Calculate the total weights to assign to data dataw_tot = np.ones(ndata) if 1 in weights: dataw_tot *= dataw_compl info_line = ('Using completeness weights\n') print info_line run_info.write(info_line) if 2 in weights: dataw_tot *= dataw_sys info_line = ('Using systematic weights\n') print info_line run_info.write(info_line) if 3 in weights: dataw_tot *= dataw_FKP info_line = ('Using FKP weights\n') print info_line run_info.write(info_line) if len(weights) == 0: info_line = ('No weights are used\n') print info_line run_info.write(info_line) # The effective redshift tmp = np.average(dataz, weights=dataw_tot) info_line = ("\n") info_line += ("Effective redshift: %.2f\n" % tmp) # The effective number of data tmp = sum(dataw_tot) info_line += ("Effective number of data: %.6f\n" % tmp) # The effective number of randoms tmp = sum(randw) info_line += ("Effective number of randoms: %.6f\n\n" % tmp) print info_line run_info.write(info_line) #---------------------------------------------- # writing the catalog for data tmp = np.transpose(np.vstack((datara, datadec, dataz, dataw_tot))) ascii.write(tmp, out_catalog + '.dat', format='no_header', names=['ra', 'dec', 'z', 'w'], formats={ 'ra': '%.6f', 'dec': '%.6f', 'z': '%.6f', 'w': '%.6f' }) col1 = fits.Column(name='ra', format='D', array=datara) col2 = fits.Column(name='dec', format='D', array=datadec) col3 = fits.Column(name='z', format='D', array=dataz) col4 = fits.Column(name='w_FKP', format='D', array=dataw_FKP) col5 = fits.Column(name='w_compl', format='D', array=dataw_compl) col6 = fits.Column(name='w_sys', format='D', array=dataw_sys) cols = fits.ColDefs([col1, col2, col3, col4, col5, col6]) tbhdu = fits.BinTableHDU.from_columns(cols) tbhdu.writeto(out_catalog + '.fits', clobber=True) # writing the random tmp = np.transpose(np.array([randra, randdec, randz, randw])) ascii.write(tmp, out_random + '.dat', format='no_header', names=['randra', 'randdec', 'randz', 'randw'], formats={ 'randra': '%.6f', 'randdec': '%.6f', 'randz': '%.6f', 'randw': '%.6f' }) col1 = fits.Column(name='randra', format='D', array=randra) col2 = fits.Column(name='randdec', format='D', array=randdec) col3 = fits.Column(name='randz', format='D', array=randz) col4 = fits.Column(name='randw', format='D', array=randw) cols = fits.ColDefs([col1, col2, col3, col4]) tbhdu = fits.BinTableHDU.from_columns(cols) tbhdu.writeto(out_random + '.fits', clobber=True) #---- Figures ---- if chunk == 'eboss21': plt.figure(figsize=(20, 8.8)) footprint_ra = np.array([-43.0, 0.0, 0.0, -43.0, -43.0]) footprint_dec = np.array([-2.0, -2.0, 2.0, 2.0, -2.0]) xlim = [-48.5, 5] ylim = [-2.5, 2.5] elif chunk == 'eboss22': plt.figure(figsize=(20, 8.8)) footprint_ra = np.array([0.0, 45.0, 45.0, 0.0, 0.0]) footprint_dec = np.array([-5.0, -5.0, 5.0, 5.0, -5.0]) xlim = [-3, 48] ylim = [-6, 6] elif chunk == 'eboss23': plt.figure(figsize=(16, 8)) footprint_ra = np.array( [126, 126, 142.5, 142.5, 157, 157, 136.5, 136.5, 126]) footprint_dec = np.array([16, 29, 29, 27, 27, 13.8, 13.8, 16, 16]) xlim = [125, 158] ylim = [13, 30] # ra, dec plt.scatter(datara, datadec, s=1, color='b', alpha=0.4, zorder=2, label='Data : ' + str(ndata) + ' objects') plt.scatter(randra, randdec, s=0.2, color='r', zorder=1, label='Randoms : ' + str(nrand) + ' objects') plt.plot(footprint_ra, footprint_dec, c='k', zorder=10, linewidth=2) plt.xlabel(r'R.A. [deg]', size=16) plt.ylabel(r'DEC. [deg]', size=16) plt.xlim(xlim) plt.ylim(ylim) plt.tight_layout() plt.grid(True, linestyle='-', alpha=0.3) plt.savefig(output_path + '/footprint.png', format='png') # z histogram of randoms plt.figure() plt.hist(dataz, bins=mbins, color='b', edgecolor='none', normed=True, histtype='bar', label='Data : ' + str(ndata) + ' galaxies') plt.hist(randz, bins=mbins, color='r', linewidth=2, normed=True, histtype='step', label='Randoms : ' + str(nrand) + ' objects') plt.xlabel(r'$z$', size=18) plt.ylabel(r'$n(z)$', size=18) plt.xlim(z_min, z_max) plt.legend() plt.grid(True, linestyle='-', alpha=0.3) plt.savefig(output_path + '/hist_rand.pdf', format='pdf') run_info.close()