def test_loadmodel(self): # assertTrue should fail if ezgal.model returns None self.assertTrue(self.model) # Trying to load a non-existent model should fail with self.assertRaises(Exception): ezgal.model('Non_Existent.model')
def _make_model(filters): """ Make an EzGal object. This also takes care of making sure that the model exists and is pre-evolved in the way we like. :param filters: List of filters that the model needs to contain calculations for. :return: EzGal object. """ # we have an evolved model in the local directory pre-evolved that we # want to grab if we can. code_dir = os.path.dirname(os.path.realpath(__file__)) evolved_model = code_dir + os.sep +"bc03_exp_0.1_z_0.02_chab_evolved.model" # if it's not there, then get the un-evolved model. default_model = "bc03_exp_0.1_z_0.02_chab.model" try: # to open the evolved model model = ezgal.ezgal(evolved_model) # see if all the filters we want are already in the model. if not all([filt in model.filters for filt in filters]): # if not, add them _evolve_model(model, filters, evolved_model) except ValueError: # the default model wasn't found try: # to open the default model model = ezgal.model(default_model) # add the filters we need _evolve_model(model, filters, save_name=evolved_model) except ValueError: # the default model doesn't exist raise ValueError("Please download the default model, which is " "bc03_exp_0.1_z_0.02_chab.model. This can be " "found on the EzGal website at " "http://www.baryons.org/ezgal/download.php") return model
def color_function(zs, znorm,zf,Z): model = ezgal.model("/net/delft/data2/vakili/easy/ezgal_models/www.baryons.org/ezgal/models/bc03_burst_0.1_z_"+str(Z)+"_chab.model") model.add_filter("/net/vuntus/data1/vakili/easy/u.dat" , "u" , units = "nm") model.add_filter("/net/vuntus/data1/vakili/easy/g.dat" , "g" , units = "nm") model.add_filter("/net/vuntus/data1/vakili/easy/r.dat" , "r" , units = "nm") model.add_filter("/net/vuntus/data1/vakili/easy/i.dat" , "i" , units = "nm") kcorr_sloan = model.get_kcorrects(zf=3.0 , zs = znorm , filters = "sloan_i") model.set_normalization("sloan_i" , znorm , mstar(znorm)-kcorr_sloan, vega=False, apparent=True) mu = model.get_apparent_mags(zf=zf , filters = "u" , zs= zs) mg = model.get_apparent_mags(zf=zf , filters = "g" , zs= zs) mr = model.get_apparent_mags(zf=zf , filters = "r" , zs= zs) mi = model.get_apparent_mags(zf=zf , filters = "i" , zs= zs) return np.vstack([mu-mg, mg-mr, mr-mi, mi])
def setup_models(zf, tau): #model = ezgal.model('bc03_exp_0.1_z_0.02_salp.model') model = ezgal.model('bc03_ssp_z_0.02_chab.model') if isinstance(tau, list): raise ValueError('tau cannot be a list') exp = model.make_exponential(tau) # set cosmology exp.set_cosmology(Om=0.3, Ol=0.7, h=0.7, w=-1) # set the model normalization to Dai et al 2009 (ApJ, 697, 506) exp.set_normalization('ch1', 0.24, -25.06, vega=True) exp.add_filter('g_MOSAICII.res', name='g_MOSAICII_MAG_ISO') exp.add_filter('r_MOSAICII.res', name='r_MOSAICII_MAG_ISO') exp.add_filter('SLOAN-SDSS.i.res', name='i_MOSAICII_MAG_ISO') exp.add_filter('SLOAN-SDSS.z.res', name='z_MOSAICII_MAG_ISO') exp.add_filter('K_KittPeak.res', name='K_KittPeak_MAG_ISO') exp.set_zfs(zf) return exp
#!/usr/bin/env python import ezgal, sys import numpy as np # get call parameters from python model_file = sys.argv[1] # input file output_file = sys.argv[2] # output file # list of ages ages = np.asarray([float(val) for val in sys.argv[3:]]) nages = len(ages) # load the model file into EzGal model = ezgal.model(model_file) # and get the list of wavelengths ls = model.ls # interpolate to get the mass at each age if model.has_masses: masses = np.interp(ages, model.ages / 1e9, model.masses) # now build an array to hold all the data which we will print to the output file seds = np.empty((ls.size, nages + 1)) # store the wavelengths in the array seds[:, 0] = ls # now loop through the age list, fetch the SED, and store in the output array # while we are at it make a list of format strings for writing the data to the file
from scipy.stats import norm import seaborn as sns import scipy.optimize as op import h5py reduced_kids = h5py.File("reduced_kids.h5") ID = reduced_kids['ID'][:] RA = reduced_kids['RA'][:] DEC = reduced_kids['DEC'][:] mi = reduced_kids['mi'][:] redshift = reduced_kids['redshift'] colors = reduced_kids['colors'][:] color_errs = reduced_kids['color_errs'][:] Ngals = mi.shape[0] print "Ngals", Ngals result_file = h5py.File("red_photometric_sample_v2.h5" , 'w') result_file.create_dataset("opt", (Ngals, 4) , data = np.zeros((Ngals,4))) result_file.close() model = ezgal.model("/net/delft/data2/vakili/easy/ezgal_models/www.baryons.org/ezgal/models/bc03_burst_0.1_z_0.02_salp.model") zf = 3.0 #HARDCODED model.add_filter("/net/delft/data2/vakili/easy/i.dat" , "kids" , units = "nm") #kcorr_sloan = model.get_kcorrects(zf=3.0 , zs = 0.25 , filters = "sloan_i") model.set_normalization("sloan_i" , 0.2 , 17.85, vega=False, apparent=True) cosmo = {'omega_M_0':0.3, 'omega_lambda_0':0.7, 'omega_k_0':0.0, 'h':1.0} zmin , zmax , dz = 0.1 , 0.8 , 0.02 sampler(0.1, 0.8, 0.02, 10, 1000, 2000, 60)
def make_prediction_dictionary(spacing): """ Use the EzGal module to get model predictions, find correct slopes of RS, and turn this info into a dictionary where keys are redshifts, and values are objects storing all the data about the model prediction for that redshift :param spacing: float of how far apart the redshift predictions will be. :return: dictionary, where keys=redshifts and values=predictions object """ # Make the models # For simplicity right now, just use the 0.1 gyr exponential model evolved_model = "bc03_exp_0.1_z_0.02_chab_evolved_zf_3.0.model" default_model = "bc03_exp_0.1_z_0.02_chab.model" try: # to open the evolved model model = ezgal.ezgal(evolved_model) build = False except ValueError: # the evolved model wasn't found, so we need to build one try: # to open the basic model that isn't evolved. model = ezgal.model(default_model) except ValueError: # We couldn't find a basic model, so we need to download one. raise ValueError("The basic model file was not found. Please download one from the ezgal website " "(http://www.baryons.org/ezgal/download.php) and move it to the exgal package directory. " "(ezgal/data/models/)\nbc03 is recommended, but you can choose another if you wish.") build = True # Set formation redshift and observed redshifts zf = 3.0 zs = np.arange(0.5, 1.5000001, spacing) # Normalize to Coma model.set_normalization(filter='ks', mag=10.9, apparent=True, vega=True, z=0.023) print config_data.filters_list # Calculate observables in AB mags mags = model.get_apparent_mags(zf, filters=config_data.filters_list, zs=zs, vega=False) # mags has dimensions of: [redshifts, filters] print mags # If we recently build and evolved the model, save it so we don't have to do that again. if build: # before doing that, though, evolve all the filters, to make it easier for future users who might want to add # bands # find the place ezgal stores all the filters filters_dir = model.data_dir + "filters/" # make a list of all filters in that directory. We will make predictions for all filters all_filters = [f for f in os.listdir(filters_dir) if f != "README"] all_filters = ["sloan_r", "sloan_z"] # Calculate observables in AB mags model.get_apparent_mags(zf, filters=all_filters, zs=zs, vega=False) # Save the model. location = model.data_dir + "models/" + evolved_model model.save_model(location) # change redshifts to string format, so they don't get floating point errors zs = [str(round(z, 2)) for z in zs] # Initialize an empty dictionary predictions_dict = dict() # fill the dictionary with values generated by the models. for z_index, z in enumerate(zs): mag_dict = dict() for filter_index, filter in enumerate(config_data.filters_list): mag_dict[filter] = mags[z_index][filter_index] predictions_dict[z] = other_classes.Predictions(redshift=z, mags=mag_dict) return predictions_dict
if __name__ == '__main__': from scipy.stats import norm import scipy.optimize as op lrg_dense = h5py.File("LRG_lmin_0.5_nbar_0.001_auto.h5" , "r") lrg_lum = h5py.File("LRG_lmin_1.0_nbar_0.0002_auto.h5" , "r") z_dense = lrg_dense["redshift"][:] ID_dense = lrg_dense["ID"][:] mi_dense = lrg_dense["mi"][:] colors_dense = lrg_dense["colors"][:] cerrs_dense = lrg_dense["color_errs"][:] z_lum = lrg_lum["redshift"][:] ID_lum = lrg_lum["ID"][:] mi_lum = lrg_lum["mi"][:] colors_lum = lrg_lum["colors"][:] cerrs_lum = lrg_lum["color_errs"][:] model = ezgal.model("data/bc03_burst_0.1_z_0.02_salp.model") zf = 3.0 #HARDCODED model.add_filter("data/i.dat" , "kids" , units = "nm") #kcorr_sloan = model.get_kcorrects(zf=3.0 , zs = 0.25 , filters = "sloan_i") model.set_normalization("sloan_i" , 0.2 , 17.85, vega=False, apparent=True) cosmo = {'omega_M_0':0.3, 'omega_lambda_0':0.7, 'omega_k_0':0.0, 'h':1.0} zmin , zmax , dz = 0.1 , 0.8 , 0.02 sampler(0.1, 0.8, 0.02, 10, 1000, 2000, 54)
def test_load_model(): print "*************Testing Load Module" assert ezgal.model('bc03_ssp_z_0.02_chab.model')
#!/usr/bin/python import ezgal,sys import numpy as np # get call parameters from python model_file = sys.argv[1] # input file output_file = sys.argv[2] # output file # list of ages ages = np.asarray([float(val) for val in sys.argv[3:]]) nages = len(ages) # load the model file into EzGal model = ezgal.model(model_file) # and get the list of wavelengths ls = model.ls # interpolate to get the mass at each age if model.has_masses: masses = np.interp(ages, model.ages/1e9, model.masses) # now build an array to hold all the data which we will print to the output file seds = np.empty((ls.size,nages+1)) # store the wavelengths in the array seds[:,0] = ls # now loop through the age list, fetch the SED, and store in the output array # while we are at it make a list of format strings for writing the data to the file
import ezgal import numpy as np model = ezgal.model('www.baryons.org/ezgal/models/bc03_burst_0.1_z_0.008_salp.model') #model = ezgal.model('www.baryons.org/ezgal/models/bc03_ssp_z_0.02_chab.model') # Desired formation redshift zf = 1.4 # Fetch an array of redshifts out to given formation redshift zs = np.arange(0.35, zf, 0.005) #print(np.shape(zs)) model.set_normalization('sloan_g', 0.00000000000000001, -22.4) thresh_mags = model.get_apparent_mags(zf, filters=['sloan_u', 'sloan_g', 'sloan_r', 'sloan_i', 'sloan_z'], zs=zs) thefile = open('Ezgal mag.txt', 'w') for item in thresh_mags: thefile.write("%s\n" % item) print(thresh_mags)
def pdf_func(data_arr, bins_arr,): N_pix, edg_f = binned(data_arr, data_arr, statistic = 'count', bins = bins_arr)[:2] pdf_pix = (N_pix / np.sum(N_pix) ) / (edg_f[1] - edg_f[0]) pdf_err = ( np.sqrt(N_pix) / np.sum(N_pix) ) / (edg_f[1] - edg_f[0]) f_cen = 0.5 * ( edg_f[1:] + edg_f[:-1]) id_zero = N_pix < 1. pdf_arr = pdf_pix[ id_zero == False] err_arr = pdf_err[ id_zero == False] pdf_x = f_cen[ id_zero == False] return pdf_arr, err_arr, pdf_x model_me = ezgal.model('bc03_ssp_z_0.008_chab.model') model_me.add_filter('sloan_g') model_me.add_filter('sloan_r') model_me.add_filter('sloan_i') model_me.set_cosmology(Om = Test_model.Om0, Ol = Test_model.Odm0, h = Test_model.h,) # model_0 = ezgal.model('bc03_ssp_z_0.008_chab.model') # model_1 = ezgal.model('bc03_ssp_z_0.02_chab.model') # model_me = ezgal.weight( 97 ) * model_1 # model_me = model_me + ezgal.weight( 3 ) * model_0 # model_me.set_cosmology( Om = Test_model.Om0, Ol = Test_model.Ode0, h = Test_model.h, ) # model_me.add_filter('sloan_g') # model_me.add_filter('sloan_r') # model_me.add_filter('sloan_i')
self.name2 = name2 self.zclust = zclust self.sigmaz = sigmaz self.filterinfo = filterinfo self.maglim = maglim self.data = mypy.readcat('%s/masslimits_%s_%s.dat' % (data_dir, name, filterinfo[0])) ######################################### ### mass limits from maximally old SSP ######################################### ezgal_dir = '/Users/atomczak/pydir/ezgal' bc03_dir = '/Users/atomczak/DATA/TEMPLATES/bc03/models' model_ssp = ezgal.model('%s/bc03_ssp_z_0.02_chab.model' % bc03_dir) model_exp = ezgal.model('%s/bc03_exp_1.0_z_0.02_chab.model' % bc03_dir) model_ssp.add_filter('%s/data/filters/sloan_r' % ezgal_dir) # index = 0 model_ssp.add_filter('%s/data/filters/sloan_i' % ezgal_dir) # index = 1 model_ssp.add_filter('%s/data/filters/sloan_z' % ezgal_dir) # index = 2 model_ssp.add_filter('%s/data/filters/ukidss_y' % ezgal_dir) # index = 3 model_exp.add_filter('%s/data/filters/sloan_r' % ezgal_dir) # index = 0 model_exp.add_filter('%s/data/filters/sloan_i' % ezgal_dir) # index = 1 model_exp.add_filter('%s/data/filters/sloan_z' % ezgal_dir) # index = 2 model_exp.add_filter('%s/data/filters/ukidss_y' % ezgal_dir) # index = 3 zform = 5. masslim_fields = []
def Stellar_SED(logMs, age, zs, wave, band="h", zf_guess=1.0, spsmodel="bc03_ssp_z_0.02_chab.model"): """ This function obtain the galaxy stellar SED given the stellar mass, age and redshift. The default model is Bruzual & Charlot (2003) with solar metallicity and Chabrier IMF. The stellar synthesis models are organised by the module EzGal (http://www.baryons.org/ezgal/). Parameters ---------- logMs : float The stellar mass in log10 of solar unit. age : float The age of the galaxy, in the unit of Gyr. zs : float The redshift of the source. wave : array The sed wavelength corresponding to the sedflux. In units micron. band : str, default: "h" The reference band used to calculate the mass-to-light ratio. zf_guess : float. zf_guess=1.0 by default. The initial guess to solve the zf that allowing the age between zs and zf is as required. spsmodel : string. spsmodel="bc03_ssp_z_0.02_chab.model" by default. The stellar population synthesis model that is used. Returns ------- flux : array The sed flux of the bulge. In units mJy. Notes ----- None. """ import ezgal #Import the package for stellar synthesis. from scipy.optimize import fsolve ls_mic = 2.99792458e14 #micron/s model = ezgal.model(spsmodel) #Choose a stellar population synthesis model. model.set_cosmology(Om=0.308, Ol=0.692, h=0.678) func_age = lambda zf, zs, age: age - model.get_age(zf, zs) #To solve the formation redshift given the #redshift of the source and the stellar age. func_MF = lambda Msun, Mstar, m2l: Msun - 2.5*np.log10(Mstar/m2l) #Calculate the absolute magnitude of #the galaxy. Msun is the absolute mag #of the sun. Mstar is the mass of the #star. m2l is the mass to light ratio. func_flux = lambda f0, MF, mu: f0 * 10**(-0.4*(MF + mu)) #Calculate the flux density of the galaxy. f0 #is the zero point. MF is the absolute magnitude #of the galaxy at certain band. mu is the distance #module. Ms = 10**logMs #Calculate the stellar mass. age_up = model.get_age(1500., zs) if age > age_up: raise ValueError("The age is too large!") zf = fsolve(func_age, zf_guess, args=(zs, age)) #Given the source redshift and the age, calculate the redshift #for the star formation. Msun_H = model.get_solar_rest_mags(nzs=1, filters=band, ab=True) #The absolute magnitude of the Sun in given band. m2l = model.get_rest_ml_ratios(zf, band, zs) #Calculate the mass-to-light ratio. M_H = func_MF(Msun_H, Ms, m2l) #The absolute magnitude of the galaxy in given band. #Calculate the flux at given band for comparison. f0 = 3.631e6 #Zero point of AB magnitude, in unit of mJy. mu = model.get_distance_moduli(zs) #The distance module flux_H = func_flux(f0, M_H, mu) wave_H = 1.6448 #Pivot wavelength of given band, in unit of micron. #Obtain the SED wave_rst = model.ls / 1e4 #In unit micron. flux_rst = model.get_sed(age, age_units="gyrs", units="Fv") * 1e26 #In unit mJy. wave_ext = np.linspace(200, 1000, 30) flux_ext = np.zeros(30) wave_extd = np.concatenate([wave_rst, wave_ext]) flux_extd = np.concatenate([flux_rst, flux_ext]) #Normalize the SED at the given band. #The normalization provided by EzGal is not well understood, so I do not use it. f_int = interp1d(wave_extd, flux_extd) f_H = f_int(wave_H) flux = flux_extd * flux_H/f_H sedflux = f_int(wave) * flux_H/f_H #return sedflux, wave_extd, flux_extd, wave_H, flux_H #For debug return sedflux
return equa_dt_z cat_lis = ['low_BCG_star-Mass', 'high_BCG_star-Mass'] fig_name = ['low $M_{\\ast}$', 'high $M_{\\ast}$'] ## or line name color_s = ['g', 'r', 'b'] path = '/home/xkchen/project/tmp_sed_fit/' out_path = '/home/xkchen/project/tmp_sed_fit/' zs = 0.25 Dl_ref = Test_model.luminosity_distance(zs).value ## SED models model_0 = ezgal.model('bc03_ssp_z_0.008_chab.model') model_0.set_cosmology(Om=Test_model.Om0, Ol=Test_model.Ode0, h=Test_model.h) model_0.add_filter('sloan_g', ) model_0.add_filter('sloan_r', ) model_0.add_filter('sloan_i', ) model_1 = ezgal.model('bc03_ssp_z_0.02_chab.model') model_1.set_cosmology(Om=Test_model.Om0, Ol=Test_model.Ode0, h=Test_model.h) model_1.add_filter('sloan_g', ) model_1.add_filter('sloan_r', ) model_1.add_filter('sloan_i', ) #=== model_me = ezgal.weight(97) * model_1 model_me = model_me + ezgal.weight(3) * model_0 model_me.set_cosmology(Om=Test_model.Om0, Ol=Test_model.Ode0, h=Test_model.h)
args=parray, pool=pool) sampler.run_mcmc(starting_guesses, nsteps) print("done") pool.close() # print(sampler.flatchain.shape) Rabs = sampler.flatchain[:, 0] zf = sampler.flatchain[:, 1] return lgms, zf, Rabs if __name__ == "__main__": modelrich = ezgal.model('bc03_ssp_z_0.02_chab.model') modelpoor = ezgal.model('bc03_ssp_z_0.008_chab.model') model = ezgal.weight(97) * modelrich model += ezgal.weight(3) * modelpoor # model.set_cosmology(Om=Test_model.Om0, Ol=Test_model.Ode0, h=Test_model.h) model.add_filter('sloan_g', grid=True) model.add_filter('sloan_r', grid=True) model.add_filter('sloan_i', grid=True) ncpu = 2 cat_lis = ['low_BCG_star-Mass', 'high_BCG_star-Mass'] path = '/home/xkchen/mywork/ICL/code/rig_common_cat/mass_bin_BG/' out_path = '/home/xkchen/mywork/ICL/code/ezgal_files/'
print('Can not cut in bounds') return # Main method that can be wired for multiprocessing purposes using Pool if __name__ == '__main__': #multiprocessing.set_start_method('spawn') #dust_table = Table.read('final_catalog_full.fit') #dr12_table = Table.read('DR12Q.fits') mgtable = Table.read('QSObased_Trimmed_SDSS_DR7_107.fits') #reader = open('Full Data.txt', 'r') # Load ezgal model file with 100 Myr burst, low metallicity model = ezgal.model( 'www.baryons.org/ezgal/models/cb07_burst_0.1_z_0.008_chab.model') #model = ezgal.model('www.baryons.org/ezgal/models/bc03_ssp_z_0.02_chab.model') # Desired formation redshift zf = 2.0 # Fetch an array of redshifts out to given formation redshift zs = np.arange(0.005, zf, 0.005) #print(np.shape(zs)) model.set_normalization('sloan_g', 0.00000000000000001, -22.4) thresh_mags = model.get_apparent_mags( zf, filters=['sloan_u', 'sloan_g', 'sloan_r', 'sloan_i', 'sloan_z'], zs=zs) # Normalize to the SED of a galaxy with rest-frame absolute magnitude = -22.4 # According to Ned Wright's UCLA CosmoCalc, at redshift 0.0072, the light travel time is 100 Myr, the burst time the model uses
import ezgal from pylab import * model_list = [ 'cb07_burst_0.1_z_0.008_salp.model', 'c09_exp_1.0_z_0.002_salp.model', 'basti_ssp_n_0.4_z_0.008_krou.model' ] #===============================HERE #try_name='c09 model, exp SFH 0.1 Gyr, different IMF' for elements in range(len(model_list)): #============================Load in Ezgal model================================================ # load ezgal model file model = ezgal.model(model_list[elements]) # desired formation redshift zf = 4.5 # fetch an array of redshifts out to given formation redshift zs = model.get_zs(zf) # plot magnitude evolution versus redshift for three filters model.set_vega_output() j_mag = model.get_apparent_mags(zf, filters='j', zs=zs) h_mag = model.get_apparent_mags(zf, filters='h', zs=zs) ks_mag = model.get_apparent_mags(zf, filters='ks', zs=zs) #===============Now we have zs, j_mag, h_mag, ks_mag============================================ #plot( zs, j_mag, 'k-', label='J' ) #plot( zs, h_mag, 'r--', label='H' )
def setup_func(): model = ezgal.model('bc03_ssp_z_0.02_chab.model') print "*************Setting Up Here"