def fsps_filter_indices(bands): # Find the filter indices import fsps flist = fsps.list_filters() findex = [flist.index(filt) for b in bands for filt in fsps.find_filter(b)] if len(findex) != len(bands): raise ValueError("Your band names {} do not give " "a one-to-one mapping to FSPS filter " "names {}".format(bands, [flist[i] for i in findex])) return [flist[i] for i in findex], findex
def test_single_model(model, spop, sdss_data, wave_min=3700, wave_max=7400, em_list=SDSS_EMLINES): """Simulate the spectrum and SED of a SF dwarf galaxy.""" # Get SDSS filters sdss_bands = fsps.find_filter('SDSS') # Generate model spectrum and SED model = simulate_dwarf_sed(model, spop, wave_min=3700, wave_max=7400, filters=sdss_bands, spec_no_emline=True, peraa=True) # Measure EWs of key emission lines model['ew_halpha'] = measure_ew_emission_line(model, em_list['H_alpha'], wave_margin=200, redshift=0.0) model['ew_hbeta'] = measure_ew_emission_line(model, em_list['H_beta'], wave_margin=200, redshift=0.0) model['ew_oiii_5007'] = measure_ew_emission_line(model, em_list['OIII_5007'], wave_margin=200, redshift=0.0) # Get magnitudes model['ur_color'] = model['sed'][0] - model['sed'][2] model['ug_color'] = model['sed'][0] - model['sed'][1] model['gr_color'] = model['sed'][1] - model['sed'][2] model['gi_color'] = model['sed'][1] - model['sed'][3] # Print a few important parameters print("# Model u-r color : %7.3f" % model['ur_color']) print("# Model u-g color : %7.3f" % model['ug_color']) print("# Model g-r color : %7.3f" % model['gr_color']) print("# Model EW(Halpha) : %7.3f" % model['ew_halpha']) print("# Model EW([OIII]) : %7.3f" % model['ew_oiii_5007']) print("# Current stellar mass : %8.5f" % model['mstar']) print("# log(SFR) : %8.3f" % np.log10(model['sfr'])) # ---------------------------------------------------------------------------------------------------- # # make a summary plot fig = plt.figure(figsize=(14, 20)) # Grids gs = fig.add_gridspec(3, 2) # ---------------------------------------------------------------------------------------------------- # # Plot the spectrum ax1 = fig.add_subplot(gs[0, :]) ax1.grid(linestyle='--') flag_use = (model['wave'] >= 3708) & (model['wave'] <= 7225) ax1.step(model['wave'][flag_use], model['spec_em'][flag_use], alpha=0.8) ax1.step(model['wave'][flag_use], model['spec_ne'][flag_use], alpha=0.8) _ = ax1.set_xlabel(r'$\mathrm{Wavelength}\ [\AA]$') # ---------------------------------------------------------------------------------------------------- # # Color-Color plot: u-g v.s. g-r ax2 = fig.add_subplot(gs[1, 0]) _ = ax2.hist2d(sdss_data['M_u'] - sdss_data['M_g'], sdss_data['M_g'] - sdss_data['M_r'], range=[[-0.05, 1.79], [-0.05, 0.79]], bins=[40, 35], cmap='viridis', cmin=5, alpha=0.8) ax2.scatter(np.asarray(model['ur_color']) - np.asarray(model['gr_color']), model['gr_color'], s=125, alpha=0.8, edgecolor='k', facecolor='r') ax2.grid(linestyle='--') _ = ax2.set_xlabel(r'$u-g\ [\mathrm{mag}]$') _ = ax2.set_ylabel(r'$g-r\ [\mathrm{mag}]$') # ---------------------------------------------------------------------------------------------------- # # (g-r) v.s. EW(Halpha) ax3 = fig.add_subplot(gs[1, 1]) _ = ax3.hist2d(sdss_data['M_g'] - sdss_data['M_r'], np.log10(-1.0 * (sdss_data['H_ALPHA_EQW'])), range=[[-0.05, 0.79], [0.05, 2.9]], bins=[40, 35], cmap='viridis', cmin=5, alpha=0.8) ax3.scatter(model['gr_color'], np.log10(model['ew_halpha']), s=125, alpha=0.8, edgecolor='k', facecolor='r') ax3.grid(linestyle='--') _ = ax3.set_xlabel(r'$g-r\ [\mathrm{mag}]$') _ = ax3.set_ylabel(r'$\log\ \mathrm{EW(H}\alpha)\ \AA$') # ---------------------------------------------------------------------------------------------------- # # (u-r) v.s. EW([OIII]) ax4 = fig.add_subplot(gs[2, 0]) _ = ax4.hist2d(sdss_use['M_u'] - sdss_use['M_r'], np.log10(-1.0 * (sdss_use['OIII_5007_EQW'])), range=[[0.05, 2.49], [-0.9, 2.9]], bins=[40, 35], cmap='viridis', cmin=5, alpha=0.8) ax4.scatter(model['ur_color'], np.log10(model['ew_oiii_5007']), s=125, alpha=0.8, edgecolor='k', facecolor='r') ax4.grid(linestyle='--') _ = ax4.set_xlabel(r'$u-r\ [\mathrm{mag}]$') _ = ax4.set_ylabel(r'$\log\ \mathrm{EW([OIII]\ 5007)}\ \AA$') # ---------------------------------------------------------------------------------------------------- # # (g-i) v.s. EW(Hbeta) ax5 = fig.add_subplot(gs[2, 1]) _ = ax5.hist2d(sdss_use['M_g'] - sdss_use['M_i'], np.log10(-1.0 * (sdss_use['H_BETA_EQW'])), range=[[-0.05, 0.99], [0.01, 1.9]], bins=[40, 35], cmap='viridis', cmin=5, alpha=0.8) ax5.scatter(model['gi_color'], np.log10(model['ew_hbeta']), s=125, alpha=0.8, edgecolor='k', facecolor='r') ax5.grid(linestyle='--') _ = ax5.set_xlabel(r'$g-i\ [\mathrm{mag}]$') _ = ax5.set_ylabel(r'$\log\ \mathrm{EW(H}\beta)\ \AA$') return model, fig
def loss_function(args): tau_mean, const_mean, tage_mean, fburst_mean, tburst_mean, logzsol_mean, gas_logz_mean, gas_logu_mean,\ tau_sig, const_sig, tage_sig, fburst_sig, tburst_sig, logzsol_sig, gas_logz_sig, gas_logu_sig = args set_size = 3000 tau_arr = [ float( priors.ClippedNormal(mean=abs(tau_mean), sigma=abs(tau_sig), mini=1.0, maxi=8.0).sample()) for _ in range(set_size) ] const_arr = [ float( priors.ClippedNormal(mean=abs(const_mean), sigma=abs(const_sig), mini=0.0, maxi=0.5).sample()) for _ in range(set_size) ] tage_arr = [ float( priors.ClippedNormal(mean=abs(tage_mean), sigma=abs(tage_sig), mini=1.0, maxi=11.0).sample()) for _ in range(set_size) ] fburst_arr = [ float( priors.ClippedNormal(mean=abs(fburst_mean), sigma=abs(fburst_sig), mini=0.0, maxi=0.8).sample()) for _ in range(set_size) ] tburst_arr = [ float( priors.ClippedNormal(mean=abs(tburst_mean), sigma=abs(tburst_sig), mini=0.0, maxi=abs(tage_mean)).sample()) for _ in range(set_size) ] logzsol_arr = [ float( priors.ClippedNormal(mean=-1 * abs(logzsol_mean), sigma=abs(logzsol_sig), mini=-1.5, maxi=0.0).sample()) for _ in range(set_size) ] gas_logz_arr = [ float( priors.ClippedNormal(mean=-1 * abs(gas_logz_mean), sigma=abs(gas_logz_sig), mini=-1.5, maxi=0.0).sample()) for _ in range(set_size) ] gas_logu_arr = [ float( priors.ClippedNormal(mean=-1 * abs(gas_logu_mean), sigma=abs(gas_logu_sig), mini=-4.0, maxi=-1.0).sample()) for _ in range(set_size) ] # Fix the fburst + const > 1 issue for ii in np.arange(len(const_arr)): if const_arr[ii] + fburst_arr[ii] >= 0.95: f_over = (const_arr[ii] + fburst_arr[ii]) - 0.95 if fburst_arr[ii] >= (f_over + 0.01): fburst_arr[ii] = fburst_arr[ii] - (f_over + 0.01) else: const_arr[ii] = const_arr[ii] - (f_over + 0.01) # Fixed the rest dust1_arr = np.full(set_size, 0.1) dust2_arr = np.full(set_size, 0.0) sf_trunc_arr = np.full(set_size, 0.0) # List of model parameters dwarf_sample_parameters = [{ 'dust1': dust1_arr[ii], 'dust2': dust2_arr[ii], 'logzsol': logzsol_arr[ii], 'gas_logz': gas_logz_arr[ii], 'gas_logu': gas_logu_arr[ii], 'const': const_arr[ii], 'tau': tau_arr[ii], 'tage': tage_arr[ii], 'sf_trunc': sf_trunc_arr[ii], 'fburst': fburst_arr[ii], 'tburst': tburst_arr[ii] } for ii in np.arange(set_size)] # Double check for ii, model in enumerate(dwarf_sample_parameters): if model['fburst'] + model['const'] >= 0.99: print(ii, model['fburst'], model['const']) # Initialize the spop model spop_tau = setup_fsps_spop(zcontinuous=1, imf_type=2, sfh=1, dust_type=0, dust_index=-1.3, dust1_index=-1.0) # Get the SDSS filters sdss_bands = fsps.find_filter('SDSS') dwarf_sample_gaussian = generate_dwarf_population(spop_tau, dwarf_sample_parameters, filters=sdss_bands, n_jobs=6) # Measure colors and emission line EWs # - SDSS_EMLINES is a pre-defined dict of emission lines center wavelength and the # wavelength window for measuring EW. # - You can save the results in a numpy array dwarf_sample_table = measure_color_ew(dwarf_sample_gaussian, em_list=SDSS_EMLINES, output=None) bin_size = 200 ur_size = np.linspace(0.0, 2.5, bin_size) ug_size = np.linspace(0.0, 2.0, bin_size) gr_size = np.linspace(-0.1, 0.8, bin_size) gi_size = np.linspace(-0.2, 1.3, bin_size) ha_size = np.linspace(0.0, 3.0, bin_size) hb_size = np.linspace(-0.5, 2.5, bin_size) oiii_size = np.linspace(-1.0, 3.0, bin_size) obs_ur = data_to_distribution( np.asarray(sdss_use['M_u'] - sdss_use['M_r']), ur_size) obs_ug = data_to_distribution( np.asarray(sdss_use['M_u'] - sdss_use['M_g']), ug_size) obs_gr = data_to_distribution( np.asarray(sdss_use['M_g'] - sdss_use['M_r']), gr_size) obs_gi = data_to_distribution( np.asarray(sdss_use['M_g'] - sdss_use['M_i']), gi_size) obs_ha = data_to_distribution(np.log10(abs(sdss_use['H_ALPHA_EQW'])), ha_size) obs_hb = data_to_distribution(np.log10(abs(sdss_use['H_BETA_EQW'])), hb_size) obs_oiii = data_to_distribution(np.log10(abs(sdss_use['OIII_5007_EQW'])), oiii_size) model_ur = data_to_distribution(dwarf_sample_table['ur_color'], ur_size) model_ug = data_to_distribution(dwarf_sample_table['ug_color'], ug_size) model_gr = data_to_distribution(dwarf_sample_table['gr_color'], gr_size) model_gi = data_to_distribution(dwarf_sample_table['gi_color'], gi_size) model_ha = data_to_distribution( np.log10(abs(dwarf_sample_table['ew_halpha'])), ha_size) model_hb = data_to_distribution( np.log10(abs(dwarf_sample_table['ew_hbeta'])), hb_size) model_oiii = data_to_distribution( np.log10(abs(dwarf_sample_table['ew_oiii_5007'])), oiii_size) obs_stack = np.transpose( np.vstack([obs_ur, obs_ug, obs_gr, obs_gi, obs_ha, obs_hb, obs_oiii])) model_stack = np.transpose( np.vstack([ model_ur, model_ug, model_gr, model_gi, model_ha, model_hb, model_oiii ])) total_loss = entropy(obs=obs_stack, model=model_stack) return total_loss
#plt.rc('text', usetex=True) mlim = 8.7 mmax = 12.5 boxsize = int(MODEL[1:3]) size_comp = True plotvar = 'sdss_r' #if len(sys.argv)==5: plotvar=sys.argv[4] #plotvar = 'sfr' plot_dir = '/home/sapple/simba_sizes/plots/' data_dir = '/home/sapple/simba_sizes/data/' if plotvar not in ['mstar', 'sfr']: try: sdss_bands = fsps.find_filter(plotvar) except: sys.exit('Filter %s not found' % plotvar) print('Doing rhalf in band %s, generating FSPS stellar pop...' % plotvar) spop = fsps.StellarPopulation(zcontinuous=1, sfh=0, logzsol=0.0, dust_type=2, dust2=0.2) print spop.ssp_ages # load in input file fig, ax = plt.subplots() for iwind in range(0, len(WIND)): snapfile = '/home/rad/data/%s/%s/snap_%s_%03d.hdf5' % (
""" import fsps import matplotlib.pyplot as plt import numpy as np import seaborn as sns sns.set_context("poster") ## PROBLEM 1 Gal_age = 12.5 # Age of Galaxy in Gyrs Uni_age = 13.8 # Age of the Universe in Gyr sf_start = Uni_age - Gal_age sp = fsps.StellarPopulation(compute_vega_mags=False, sfh=1, zmet=20, dust_type=2, dust2=0.2, sf_start=sf_start) sdss_filters = fsps.find_filter('sdss') tau_grid = np.logspace(-2,2,50) A = Gal_age def mean_age(tau): return A - tau * (1.0-np.exp(-A/tau)*(1.0+A/tau)) / (1.0-np.exp(-A/tau)) mean_age_grid = [] for tau in tau_grid: mean_age_grid.append(mean_age(tau)) # Find what tau is needed to provide appropriate colors for # red or blue galaxy
skip_lowmass = 0 low_mass = 10. want_random = '' #''#'_scatter' sfh_ap = '_30kpc' #'_30kpc'#'_3rad'#'_30kpc'#'' cam_filt = 'sdss_desi' # should be desi; use des with fsps filters # No implementation error if want_random == '_scatter': print("For now we are not incorporating redshift uncertainties") exit(0) # create a list of the wanted color bands bands = [] filts = cam_filt.split('_') for i in range(len(filts)): bands += fsps.find_filter(filts[i]) # If using the sedpy magnitudes with decam filters bands = [ 'sdss_u0', 'sdss_g0', 'sdss_r0', 'sdss_i0', 'sdss_z0', 'decam_g', 'decam_r', 'decam_i', 'decam_z', 'decam_Y' ] print(bands) # list of all redshifts we have redshifts = np.array([ 1.74324, 1.5, 1.41131, 1.35539, 1.30228, 1.25173, 1.20355, 1.15755, 1.11358, 1.07147, 1.03111, 1, 0.95514, 0.91932, 0.88482, 0.85156, 0.81947, 0.78847, 0.7585, 0.7295, 0.7, 0.5, 0 ])
def loss_function(args): tau_mean, const_mean, tage_mean, fburst_mean, tburst_mean, logzsol_mean, gas_logz_mean, gas_logu_mean = args set_size = 3000 tau_arr = [ float( priors.ClippedNormal(mean=tau_mean, sigma=tau_sig, mini=1.0, maxi=8.0).sample()) for _ in range(set_size) ] const_arr = [ float( priors.ClippedNormal(mean=const_mean, sigma=const_sig, mini=0.0, maxi=0.5).sample()) for _ in range(set_size) ] tage_arr = [ float( priors.ClippedNormal(mean=tage_mean, sigma=tage_sig, mini=1.0, maxi=11.0).sample()) for _ in range(set_size) ] fburst_arr = [ float( priors.ClippedNormal(mean=fburst_mean, sigma=fbust_sig, mini=0.0, maxi=0.8).sample()) for _ in range(set_size) ] tburst_arr = [ float( priors.ClippedNormal(mean=tburst_mean, sigma=tburst_sig, mini=0.0, maxi=8.0).sample()) for _ in range(set_size) ] logzsol_arr = [ float( priors.ClippedNormal(mean=logzsol_mean, sigma=logzsol_sig, mini=-1.5, maxi=0.0).sample()) for _ in range(set_size) ] gas_logz_arr = [ float( priors.ClippedNormal(mean=gas_logz_mean, sigma=gas_logz_sig, mini=-1.5, maxi=0.0).sample()) for _ in range(set_size) ] gas_logu_arr = [ float( priors.ClippedNormal(mean=gas_logu_mean, sigma=gas_logu_sig, mini=-4.0, maxi=-1.0).sample()) for _ in range(set_size) ] # Fix the fburst + const > 1 issue for ii in np.arange(len(const_arr)): if const_arr[ii] + fburst_arr[ii] >= 0.95: f_over = (const_arr[ii] + fburst_arr[ii]) - 0.95 if fburst_arr[ii] >= (f_over + 0.01): fburst_arr[ii] = fburst_arr[ii] - (f_over + 0.01) else: const_arr[ii] = const_arr[ii] - (f_over + 0.01) # Fixed the rest dust1_arr = np.full(set_size, 0.1) dust2_arr = np.full(set_size, 0.0) sf_trunc_arr = np.full(set_size, 0.0) # List of model parameters dwarf_sample_parameters = [{ 'dust1': dust1_arr[ii], 'dust2': dust2_arr[ii], 'logzsol': logzsol_arr[ii], 'gas_logz': gas_logz_arr[ii], 'gas_logu': gas_logu_arr[ii], 'const': const_arr[ii], 'tau': tau_arr[ii], 'tage': tage_arr[ii], 'sf_trunc': sf_trunc_arr[ii], 'fburst': fburst_arr[ii], 'tburst': tburst_arr[ii] } for ii in np.arange(set_size)] # Double check for ii, model in enumerate(dwarf_sample_parameters): if model['fburst'] + model['const'] >= 0.99: print(ii, model['fburst'], model['const']) # Initialize the spop model spop_tau = setup_fsps_spop(zcontinuous=1, imf_type=2, sfh=1, dust_type=0, dust_index=-1.3, dust1_index=-1.0) # Get the SDSS filters sdss_bands = fsps.find_filter('SDSS') dwarf_sample_gaussian = generate_dwarf_population(spop_tau, dwarf_sample_parameters, filters=sdss_bands, n_jobs=4) # Measure colors and emission line EWs # - SDSS_EMLINES is a pre-defined dict of emission lines center wavelength and the # wavelength window for measuring EW. # - You can save the results in a numpy array dwarf_sample_table = measure_color_ew(dwarf_sample_gaussian, em_list=SDSS_EMLINES, output=None) bin_size = 200 ur_loss = loss(dwarf_sample_table['ur_color'], np.asarray(sdss_use['M_u'] - sdss_use['M_r']), np.linspace(0, 2.5, bin_size)) ug_loss = loss(dwarf_sample_table['ug_color'], np.asarray(sdss_use['M_u'] - sdss_use['M_g']), np.linspace(0, 1.75, bin_size)) gr_loss = loss(dwarf_sample_table['gr_color'], np.asarray(sdss_use['M_g'] - sdss_use['M_r']), np.linspace(-0.1, 0.8, bin_size)) gi_loss = loss(dwarf_sample_table['gi_color'], np.asarray(sdss_use['M_g'] - sdss_use['M_i']), np.linspace(-0.2, 1.2, bin_size)) OIII_loss = loss(np.log10(dwarf_sample_table['ew_oiii_5007']), np.log10(-1.0 * (sdss_use['OIII_5007_EQW'])), np.linspace(-1, 3, bin_size)) Ha_loss = loss(np.log10(np.log10(dwarf_sample_table['ew_halpha'])), np.log10(-1.0 * sdss_use['H_ALPHA_EQW']), np.linspace(0, 3, bin_size)) Hb_loss = loss(np.log10(dwarf_sample_table['ew_hbeta']), np.log10(-1.0 * sdss_use['H_BETA_EQW']), np.linspace(-0.5, 2.5, bin_size)) total_loss = (ur_loss + ug_loss + gr_loss + gi_loss + OIII_loss + Ha_loss + Hb_loss) / 7 part_loss = [ ur_loss, ug_loss, gr_loss, gi_loss, OIII_loss, Ha_loss, Hb_loss ] return total_loss
# s_m = matplotlib.cm.ScalarMappable(cmap=c_m, norm=norm) # s_m.set_array([]) # plt.figure(2) # for i in bump: # plt.plot(wlinv,attenuation.conroy(wl,f_bump=i),color=s_m.to_rgba(i)) # plt.colorbar(s_m,label='Bump Fraction') # plt.plot(wlinv,cardelli,'k--' ,label='Cardelli Law',linewidth=1,alpha=0.7) # plt.legend() ## To select the UV filters plot each one to pick the ones you ## like. Picking manually. uv = fsps.find_filter('uv') # for fil in uv: # plt.figure() # plt.plot(wlinv,10*attenuation.conroy(wl,f_bump=0.5),'-') # f = fsps.get_filter(fil) # plt.plot((f.transmission[0]*1e-4)**-1,f.transmission[1],label=f.name) # plt.legend() ## Amplify all the HST (WFC3) filters: wfc3 = fsps.find_filter('wfc3_uvis') for fil in wfc3: plt.figure() plt.plot(wlinv, attenuation.conroy(wl, f_bump=0.5) / 10, '-')
if __name__ == '__main__': import fsps sp = fsps.StellarPopulation(compute_vega_mags=False, zcontinuous=1, sfh=0, logzsol=0.0, dust_type=2, dust2=0.2) sdss_bands = fsps.find_filter('sdss') print(sp.get_mags(tage=13.7, bands=sdss_bands))
# parts a and b import fsps sp = fsps.StellarPopulation(compute_vega_mags=False, sfh=0, zmet=1, dust_type=1, uvb=.08, sf_start=.1) hst_bands = fsps.find_filter('wfc_acs') wanted = [hst_bands[1], hst_bands[-1]] got_absmags = sp.get_mags(tage=14.1, bands=wanted) import numpy as np import emcee got_noise = np.array([np.random.normal(.1), np.random.normal(.1)]) got_wave = np.array([8.14e-7, 6.06e-7]) distance = 8.2e3 got_appmags = got_absmags + got_noise + 5 * np.log10(distance / 10.) got_error = np.array([.1, .1]) def model(theta): # met, age, dist, extinction sp.params['zmet'] = np.round(theta[0]) sp.params['sf_start'] = 14.1 - theta[1] sp.params['uvb'] = theta[3] got_absmags1 = sp.get_mags(tage=14.1, bands=wanted) got_appmags1 = got_absmags1 + 5 * np.log10(theta[2] / 10.)
"""theta = (zmet,age,distance)""" lp = lnprior(theta) print(lp) if (np.isfinite(lp)).all() == False: return -np.inf z, age, dist = lp[0], lp[1], lp[2] mag = ssp.get_mags(zmet=z, tage=age, bands=f) mag += -5 + 5 * np.log10(dist * 1e3) d = norm.logpdf(data, loc=mag, scale=sigma) return np.sum(d) f = [fsps.find_filter('f606w')[1], fsps.find_filter('f814w')[1]] #data = gen_data(f,0.1) data = [20.58183853, 20.37690413] ssp = fsps.StellarPopulation(dust_type=1) ndim, nwalkers = 3, 100 sampler = emcee.EnsembleSampler(nwalkers, ndim, lnP, args=(data, ssp, 0.1)) theta0 = np.array([np.random.ranf(ndim) for i in range(nwalkers)]) theta0[:, 0] = (-2.5 + 2) * theta0[:, 0] - 2.00 theta0[:, 1] = (14 - 5) * theta0[:, 1] + 5 theta0[:, 2] = (10 - 8) * theta0[:, 2] + 8 sampler.run_mcmc(theta0, 100) print("Ran the Markov chain! Plotting now..")