def load_model(agelims=[], nbins_sfh=7, sigma=0.3, df=2, **extras): # we'll need this to access specific model parameters n = [p['name'] for p in model_params] # first calculate t_universe at z=1 tuniv = WMAP9.age(1.0).value*1e9 # now construct the nonparametric SFH # current scheme: last bin is 15% age of the Universe, first two are 0-30, 30-100 # remaining N-3 bins spaced equally in logarithmic space tbinmax = (tuniv*0.85) agelims = agelims[:2] + np.linspace(agelims[2],np.log10(tbinmax),nbins_sfh-2).tolist() + [np.log10(tuniv)] agebins = np.array([agelims[:-1], agelims[1:]]) # load nvariables and agebins model_params[n.index('agebins')]['N'] = nbins_sfh model_params[n.index('agebins')]['init'] = agebins.T model_params[n.index('mass')]['N'] = nbins_sfh model_params[n.index('logsfr_ratios')]['N'] = nbins_sfh-1 model_params[n.index('logsfr_ratios')]['init'] = np.full(nbins_sfh-1,0.0) # constant SFH model_params[n.index('logsfr_ratios')]['prior'] = priors.StudentT(mean=np.full(nbins_sfh-1,0.0), scale=np.full(nbins_sfh-1,sigma), df=np.full(nbins_sfh-1,df)) # insert redshift into model dictionary model_params[n.index('zred')]['init'] = 0.0 return sedmodel.SedModel(model_params)
def load_model(nbins_sfh=6,sigma=0.3,datfile=None,objname=None, **extras): # we'll need this to access specific model parameters n = [p['name'] for p in model_params] # create SFH bins with open(datfile,'r') as f: data = json.load(f) zred = float(data[objname]['redshift']) model_params[n.index('zred')]['init'] = zred tuniv = WMAP9.age(zred).value*1e9 # now construct the nonparametric SFH # set number of components # set logsfr_ratio prior # propagate to agebins model_params[n.index('agebins')]['N'] = nbins_sfh model_params[n.index('mass')]['N'] = nbins_sfh model_params[n.index('logsfr_ratios')]['N'] = nbins_sfh-1 model_params[n.index('logsfr_ratios')]['init'] = np.full(nbins_sfh-1,0.0) # constant SFH model_params[n.index('logsfr_ratios')]['prior'] = SFR_Ratio(mean=np.full(nbins_sfh-1,0.0),sigma=np.full(nbins_sfh-1,sigma)) model_params.append({'name': 'tuniv', 'N': 1, 'isfree': False, 'init': tuniv}) # set mass-metallicity prior model_params[n.index('massmet')]['prior'] = MassMet(z_mini=-1.98, z_maxi=0.19, mass_mini=7, mass_maxi=12.5) return sedmodel.SedModel(model_params)
def load_model(objname, field, agelims=[], **extras): # REDSHIFT # open file, load data photname, zname, filtername, filts = get_names(field) with open(photname, 'r') as f: hdr = f.readline().split() dtype = np.dtype([(hdr[1], 'S20')] + [(n, np.float) for n in hdr[2:]]) dat = np.loadtxt(photname, comments='#', delimiter=' ', dtype=dtype) with open(zname, 'r') as fz: hdr_z = fz.readline().split() dtype_z = np.dtype([(hdr_z[1], 'S20')] + [(n, np.float) for n in hdr_z[2:]]) zout = np.loadtxt(zname, comments='#', delimiter=' ', dtype=dtype_z) idx = dat['id'] == objname # creates array of True/False: True when dat[id] = objname zred = zout['z_spec'][idx][0] # use z_spec if zred == -99: # if z_spec doesn't exist zred = zout['z_peak'][idx][0] # use z_phot print(zred, 'zred') # CALCULATE AGE OF THE UNIVERSE (TUNIV) AT REDSHIFT ZRED tuniv = WMAP9.age(zred).value print(tuniv, 'tuniv') n = [p['name'] for p in model_params] # model_params[n.index('tage')]['prior_args']['maxi'] = tuniv # NONPARAMETRIC SFH # NEW agelims = [0.0, 7.7, 8.0, 9.0, (9.0 + (np.log10(tuniv*1e9) - 9.0)/3), (9.0 + 2 * (np.log10(tuniv*1e9) - 9.0)/3), np.log10(tuniv*1e9)] ncomp = len(agelims) - 1 agebins = np.array([agelims[:-1], agelims[1:]]) # why agelims[1:] instead of agelims[0:]? # INSERT REDSHIFT INTO MODEL PARAMETER DICTIONARY zind = n.index('zred') model_params[zind]['init'] = zred # SET UP AGEBINS model_params[n.index('agebins')]['N'] = ncomp model_params[n.index('agebins')]['init'] = agebins.T # FRACTIONAL MASS INITIALIZATION # NEW # N-1 bins, last is set by x = 1 - np.sum(sfr_fraction) model_params[n.index('sfr_fraction')]['N'] = ncomp-1 model_params[n.index('sfr_fraction')]['prior_args'] = { 'maxi': np.full(ncomp-1, 1.0), 'mini': np.full(ncomp-1, 0.0), # NOTE: ncomp instead of ncomp-1 makes the prior take into # account the implicit Nth variable too } model_params[n.index('sfr_fraction')]['init'] = np.zeros(ncomp-1)+1./ncomp model_params[n.index('sfr_fraction')]['init_disp'] = 0.02 # CREATE MODEL model = BurstyModel(model_params) return model
def load_model(objname=None, datdir=None, nbins_sfh=7, sigma=0.3, df=2, agelims=[], zred=None, runname=None, **extras): # we'll need this to access specific model parameters n = [p['name'] for p in model_params] # first calculate redshift and corresponding t_universe # if no redshift is specified, read from file if zred is None: datname = datdir + objname.split('_')[0] + '_' + runname + '.dat' dat = ascii.read(datname) idx = dat['phot_id'] == int(objname.split('_')[-1]) zred = float(dat['z_best'][idx]) tuniv = WMAP9.age(zred).value*1e9 model_params[n.index('zred')]['init'] = zred # now construct the nonparametric SFH # current scheme: last bin is 15% age of the Universe, first two are 0-30, 30-100 # remaining N-3 bins spaced equally in logarithmic space tbinmax = (tuniv*0.85) agelims = agelims[:2] + np.linspace(agelims[2],np.log10(tbinmax),nbins_sfh-2).tolist() + [np.log10(tuniv)] agebins = np.array([agelims[:-1], agelims[1:]]) # load nvariables and agebins model_params[n.index('agebins')]['N'] = nbins_sfh model_params[n.index('agebins')]['init'] = agebins.T model_params[n.index('mass')]['N'] = nbins_sfh model_params[n.index('logsfr_ratios')]['N'] = nbins_sfh-1 model_params[n.index('logsfr_ratios')]['init'] = np.full(nbins_sfh-1,0.0) # constant SFH model_params[n.index('logsfr_ratios')]['prior'] = priors.StudentT(mean=np.full(nbins_sfh-1,0.0), scale=np.full(nbins_sfh-1,sigma), df=np.full(nbins_sfh-1,df)) return sedmodel.SedModel(model_params)
def load_model(nbins_sfh=7,sigma=0.3,df=2.,agelims=None,objname=None, **extras): # we'll need this to access specific model parameters n = [p['name'] for p in model_params] # replace nbins_sfh nbins_sfh = 4 + (int(objname)-1) / 9 # create SFH bins zred = model_params[n.index('zred')]['init'] tuniv = WMAP9.age(zred).value # now construct the nonparametric SFH # current scheme: six bins, four spaced equally in logarithmic # last bin is 15% age of the Universe, first two are 0-30, 30-100 tbinmax = (tuniv*0.85)*1e9 agelims = agelims[:2] + np.linspace(agelims[2],np.log10(tbinmax),nbins_sfh-2).tolist() + [np.log10(tuniv*1e9)] agebins = np.array([agelims[:-1], agelims[1:]]) # load nvariables and agebins model_params[n.index('agebins')]['N'] = nbins_sfh model_params[n.index('agebins')]['init'] = agebins.T model_params[n.index('mass')]['N'] = nbins_sfh model_params[n.index('logsfr_ratios')]['N'] = nbins_sfh-1 model_params[n.index('logsfr_ratios')]['init'] = np.full(nbins_sfh-1,0.0) # constant SFH model_params[n.index('logsfr_ratios')]['prior'] = priors.StudentT(mean=np.full(nbins_sfh-1,0.0), scale=np.full(nbins_sfh-1,sigma), df=np.full(nbins_sfh-1,df)) return sedmodel.SedModel(model_params)
def load_model(datname='', objname='', **extras): ###### REDSHIFT ###### hdulist = fits.open(datname) idx = hdulist[1].data['Name'] == objname zred = hdulist[1].data['cz'][idx][0] / 3e5 hdulist.close() #### TUNIV ##### tuniv = WMAP9.age(zred).value #### TAGE ##### tage_init = 1.1 tage_mini = 0.11 # FSPS standard tage_maxi = tuniv #### INSERT MAXIMUM AGE AND REDSHIFT INTO MODEL PARAMETER DICTIONARY #### pnames = [m['name'] for m in model_params] zind = pnames.index('zred') model_params[zind]['init'] = zred tind = pnames.index('tage') model_params[tind]['prior_args']['maxi'] = tuniv model = BurstyModel(model_params) return model
def cosmoAge(redshift, WMAP9=False, H0=70.0, Om0=0.30, Planck15=False, Myr=False): """ Get the Age of the Universe at redshift=z. This is simply a wrapper of astropy.cosmology The input redsfhit can be an array """ if WMAP9: from astropy.cosmology import WMAP9 as cosmo elif Planck15: from astropy.cosmology import Planck15 as cosmo else: from astropy.cosmology import FlatLambdaCDM cosmo = FlatLambdaCDM(H0=H0, Om0=Om0) age = cosmo.age(redshift) if not Myr: return age.value else: return age.to(u.Myr).value
def draw_sfrs(objs, flds, new_logmass=None, ndraw=1e4, alpha_sfh=1.0, pfile=None, show=True): # pfile=e_params or n_params # let's do it ndraw = int(ndraw) zred = np.array([3.5]) logmass = np.array([10.]) smass_factor = 0.8 # add in a not-unreasonable stellar mass <--> total mass conversion minssfr, maxssfr = 1e-14, 1e-5 # new redshift, new model if new_logmass is None: new_logmass = 10.17 new_SFRs = [] for i in range(len(objs)): new_model = pfile.load_model(objname=objs[i], field=flds[i]) new_zred = new_model.params['zred'] tuniv = WMAP9.age(new_zred).value new_SFRs.append(new_logmass / tuniv) return new_SFRs
def load_model(alpha_sfh=0.2,agelims=None, **extras): # we'll need this to access specific model parameters n = [p['name'] for p in model_params] # create SFH bins zred = model_params[n.index('zred')]['init'] tuniv = WMAP9.age(zred).value # now construct the nonparametric SFH # current scheme: six bins, four spaced equally in logarithmic # last bin is 15% age of the Universe, first two are 0-30, 30-100 tbinmax = (tuniv*0.85)*1e9 agelims = agelims[:2] + np.linspace(agelims[2],np.log10(tbinmax),len(agelims)-3).tolist() + [np.log10(tuniv*1e9)] agebins = np.array([agelims[:-1], agelims[1:]]) ncomp = len(agelims) - 1 # load nvariables and agebins model_params[n.index('agebins')]['N'] = ncomp model_params[n.index('agebins')]['init'] = agebins.T model_params[n.index('mass')]['N'] = ncomp model_params[n.index('mass')]['init'] = np.full(ncomp,1e6) model_params[n.index('mass')]['prior'] = priors.TopHat(mini=np.full(ncomp,1e5), maxi=np.full(ncomp,1e12)) return sedmodel.SedModel(model_params)
def load_model(nbins_sfh=5,sigma=0.3,df=2, **extras): # we'll need this to access specific model parameters n = [p['name'] for p in model_params] # create SFH bins zred = model_params[n.index('zred')]['init'] tuniv = WMAP9.age(zred).value*1e9 # now construct the nonparametric SFH # set number of components # set logsfr_ratio prior # propagate to agebins model_params[n.index('agebins')]['N'] = nbins_sfh model_params[n.index('mass')]['N'] = nbins_sfh model_params[n.index('logsfr_ratios')]['N'] = nbins_sfh-1 model_params[n.index('logsfr_ratios')]['init'] = np.full(nbins_sfh-1,0.0) # constant SFH model_params[n.index('logsfr_ratios')]['prior'] = priors.StudentT(mean=np.full(nbins_sfh-1,0.0), scale=np.full(nbins_sfh-1,sigma), df=np.full(nbins_sfh-1,df)) model_params[n.index('logsfr_ratio30')]['prior'] = priors.StudentT(mean=0.0, scale=sigma, df=df) model_params[n.index('logsfr_ratiomax')]['prior'] = priors.StudentT(mean=0.0, scale=sigma, df=df) model_params.append({'name': 'tuniv', 'N': 1, 'isfree': False, 'init': tuniv}) return sedmodel.SedModel(model_params)
def cosmoAge(redshift, WMAP9=False, H0=70.0, Om0=0.30, Planck15=False, Myr=False): """ Get the Age of the Universe at redshift=z. This is simply a wrapper of astropy.cosmology The input redsfhit can be an array """ if WMAP9: from astropy.cosmology import WMAP9 as cosmo elif Planck15: from astropy.cosmology import Planck15 as cosmo else: from astropy.cosmology import FlatLambdaCDM cosmo = FlatLambdaCDM(H0=H0, Om0=Om0) age = cosmo.age(redshift) if not Myr: return age.value else: return age.to(u.Myr).value
def load_model(**extras): # set tage_max, fix redshift n = [p['name'] for p in model_params] zred = 0.0001 tuniv = WMAP9.age(zred).value model_params[n.index('tage')]['prior'].update(maxi=tuniv) return sedmodel.SedModel(model_params)
def load_model(**extras): # set tage_max, fix redshift n = [p['name'] for p in model_params] zred = model_params[n.index('zred')]['init'] tuniv = WMAP9.age(zred).value model_params[n.index('tage')]['prior'].update(maxi=tuniv) return sedmodel.SedModel(model_params)
def load_model(objname=None, datdir=None, runname=None, agelims=[], zred=None, alpha_sfh=0.3, **extras): # we'll need this to access specific model parameters n = [p['name'] for p in model_params] # first calculate redshift and corresponding t_universe # if no redshift is specified, read from file hdu = fits.open(APPS+'/prospector_alpha/data/3dhst/shivaei_sample.fits') fields = np.array([f.replace('-','') for f in hdu[1].data['FIELD']]) ids = hdu[1].data['V4ID'].astype(str) idx_obj = (fields == objname.split('_')[0]) & (ids == objname.split('_')[1]) zred = float(hdu[1].data['Z_MOSFIRE'][idx_obj][0]) tuniv = WMAP9.age(zred).value # now construct the nonparametric SFH # current scheme: six bins, four spaced equally in logarithmic # last bin is 15% age of the Universe, first two are 0-30, 30-100 tbinmax = (tuniv*0.85)*1e9 agelims = agelims[:2] + np.linspace(agelims[2],np.log10(tbinmax),len(agelims)-3).tolist() + [np.log10(tuniv*1e9)] agebins = np.array([agelims[:-1], agelims[1:]]) ncomp = len(agelims) - 1 # load into `agebins` in the model_params dictionary model_params[n.index('agebins')]['N'] = ncomp model_params[n.index('agebins')]['init'] = agebins.T # now we do the computational z-fraction setup # number of zfrac variables = (number of SFH bins - 1) # set initial with a constant SFH # if alpha_SFH is a vector, use this as the alpha array # else assume all alphas are the same model_params[n.index('mass')]['N'] = ncomp model_params[n.index('z_fraction')]['N'] = ncomp-1 if type(alpha_sfh) != type(np.array([])): alpha = np.repeat(alpha_sfh,ncomp-1) else: alpha = alpha_sfh tilde_alpha = np.array([alpha[i-1:].sum() for i in xrange(1,ncomp)]) model_params[n.index('z_fraction')]['prior'] = priors.Beta(alpha=tilde_alpha, beta=alpha, mini=0.0, maxi=1.0) model_params[n.index('z_fraction')]['init'] = np.array([(i-1)/float(i) for i in range(ncomp,1,-1)]) model_params[n.index('z_fraction')]['init_disp'] = 0.02 # set mass-metallicity prior # insert redshift into model dictionary model_params[n.index('massmet')]['prior'] = MassMet(z_mini=-1.98, z_maxi=0.19, mass_mini=7, mass_maxi=12.5) model_params[n.index('zred')]['init'] = zred # set gas-phase metallicity prior # log(Z/Zsun) = -3.07 for model mean = hdu[1].data['m_12LOGOH'][idx_obj][0] if (mean > -100): gas_logz_mean = np.clip((mean - 12) + 3.06, -2, 0.5) sigma = (hdu[1].data['U68_12LOGOH'] - hdu[1].data['L68_12LOGOH'])[idx_obj][0] / 2. model_params[n.index('gas_logz')]['prior'] = priors.ClippedNormal(mean=gas_logz_mean,sigma=sigma,mini=-2,maxi=0.5) return sedmodel.SedModel(model_params)
def load_model(objname='', datname='', fastname='', agelims=[], **extras): ###### REDSHIFT ###### ### open file, load data ''' with open(datname, 'r') as f: hdr = f.readline().split() dtype = np.dtype([(hdr[1],'S20')] + [(n, np.float) for n in hdr[2:]]) dat = np.loadtxt(datname, comments = '#', delimiter=' ', dtype = dtype) ''' with open(fastname, 'r') as f: hdr = f.readline().split() # dtype = np.dtype([(hdr[1], 'S20')] + [(n, np.float) for n in hdr[2:]]) fast = np.loadtxt(fastname, comments='#', delimiter=' ') # , dtype=dtype) ''' with open(fastname, 'r') as f: # drop the comment hash header = f.readline().split() fast = np.genfromtxt(fastname, comments='#', dtype=np.dtype([(n, np.float) for n in header])) f.close() ''' idx = 0 # fast['id'] == objname print(fast) zred = fast[1] # 3.0815 print(zred) #### INITIAL VALUES tau = 10 ** fast[2] / 1e9 # 10 ** 7.80 / 1e9 # tage = 10 ** fast[4] / 1e9 # 10 ** 8.40 / 1e9 # logmass = fast[6] # 11.23 # dust2 = fast[5] / 1.086 # 1.70 / 1.086 # # logzsol = 0 # np.log10(fast['metal']) n = [p['name'] for p in model_params] model_params[n.index('tau')]['init'] = tau model_params[n.index('tage')]['init'] = tage model_params[n.index('logmass')]['init'] = logmass model_params[n.index('dust2')]['init'] = dust2 # model_params[n.index('logzsol')]['init'] = logzsol #### CALCULATE TUNIV ##### tuniv = WMAP9.age(zred).value model_params[n.index('tage')]['prior_args']['maxi'] = tuniv #### INSERT REDSHIFT INTO MODEL PARAMETER DICTIONARY #### zind = n.index('zred') model_params[zind]['init'] = zred #### CREATE MODEL model = BurstyModel(model_params) return model
def load_model(**extras): # we'll need this to access specific model parameters n = [p['name'] for p in model_params] # set tmax = tuniv zred = model_params[n.index('zred')]['init'] tuniv = WMAP9.age(zred).value model_params[n.index('tage')]['prior'].update(maxi=tuniv) return sedmodel.SedModel(model_params)
def CSFH(SPS, p, redshift=0.0, log10Z=-2.): log10ages = SPS.grid['log10age'] iZ = (np.abs(SPS.grid['log10Z'] - log10Z)).argmin() SFZH = np.zeros((len(SPS.grid['log10age']), len(SPS.grid['log10Z']))) from astropy.cosmology import WMAP9 as cosmo dz = 0.01 z = np.arange(10., redshift, -dz) ages = -(cosmo.age(z).to('yr').value - cosmo.age(redshift).to('yr').value) csfh = lambda z, p1, p2, p3, p4: p1 * (1 + z)**p2 / (1 + ((1 + z) / p3)**p4) sfrd = csfh(z, *p) f = lambda x: np.interp(x, ages, sfrd[::-1]) start = 0. for ia, log10age in enumerate(log10ages[:-1]): end = 10**log10age # determine the amount of star formation in this bin sf = integrate.quad(f, start, end)[0] SFZH[ia, iZ] = sf # print('{0:.1f}-{1:.1f}: SF={2:.2f}'.format(start/1E6, end/1E6, sf)) start = end SFZH /= np.sum(SFZH) SFR = csfh(redshift, *p) return SFZH, SFR
def tuniv_ssfr_prior(objs, flds, pfile=None): # NEW TUNIV PRIOR ssfrs = [] for i in range(len(objs)): model = pfile.load_model( objname=objs[i], field=flds[i]) # load_model prints zred, tuniv tuniv = WMAP9.age(model.params['zred']).value ssfrs.append(1 / tuniv) print(i) perc = np.percentile(ssfrs, [16., 50., 84.]) print(perc) return perc
def make_galaxy(): ## integrate Zg(mstar) #### take mstar as an array ## Zstar = int(Zg, mstar) ? ## can be done numerically? or analytically? ## let's start numerically because I'm lazy sfr = 15. * u.Msun / u.yr # msun per year nsteps = 2000 time_start = 2 * u.Gyr init_Mstar = 1.e6 * u.Msun dt = (cosmo.age(z=0) - time_start) / nsteps galaxy = initialize_galaxy(nsteps) weight = np.zeros(nsteps) * u.Msun zstar = np.zeros(len(galaxy)) Mzstar = np.zeros(len(galaxy)) * u.Msun for i in range(nsteps): galaxy['age'][i] = i * dt galaxy['dt'][i] = dt galaxy['lookback'][i] = (nsteps - i - 1) * dt galaxy['sfr'][i] = sfr if i == 0: galaxy['Ms'][i] = init_Mstar else: galaxy['Ms'][i] = galaxy['Ms'][ i - 1] + sfr * dt - sfr * (1 - fml(galaxy['age'][i])) * dt weight[i] = sfr * (1 - fml(galaxy['age'][i])) * dt galaxy['tlogoh'][i] = get_tlogoh(np.log10(galaxy['Ms'][i].value), "am13") Zism = (O_AMU / HELIUM_CORR) * np.power(10.0, galaxy['tlogoh'] - 12) galaxy['Zism'] = Zism zstar[i], sum_weight = np.average(galaxy['Zism'], weights=weight, returned=True) Mzstar[i] = np.sum(galaxy['Zism'] * weight) ## / np.cumsum(weight) ## how many metals made? dMoxyiidt = Y_O_II * galaxy['sfr'] Moxymade = np.cumsum(dMoxyiidt * galaxy['dt']) ## Need to account for metals made by stars existing in 0th timestep; assume from eq(2) of peeples14 Moxyinit = np.power(10.0, P.oxyii(np.log10( galaxy['Ms'][0].value))) * u.Msun galaxy['Moxymade'] = Moxymade + Moxyinit galaxy['dMoxymadedt'] = dMoxyiidt galaxy['Zstar'] = zstar galaxy['Mzstar'] = Mzstar return galaxy
def load_model(objname=None, datdir=None, runname=None, agelims=[], **extras): ###### REDSHIFT ###### ### open file, load data # this is zgris datname = datdir + objname.split('_')[0] + '_' + runname + '.dat' dat = ascii.read(datname) zred = dat['z_max_grism'][np.array(dat['phot_id']) == int(objname.split('_')[-1])][0] #### CALCULATE TUNIV ##### tuniv = WMAP9.age(zred).value #### NONPARAMETRIC SFH ##### # six bins, four spaced equally in logarithmic space AFTER t=100 Myr + BEFORE tuniv-1 Gyr if tuniv > 5: tbinmax = (tuniv-2)*1e9 else: tbinmax = (tuniv-1)*1e9 agelims = [agelims[0]] + np.linspace(agelims[1],np.log10(tbinmax),5).tolist() + [np.log10(tuniv*1e9)] agebins = np.array([agelims[:-1], agelims[1:]]) ncomp = len(agelims) - 1 #### ADJUST MODEL PARAMETERS ##### n = [p['name'] for p in model_params] #### SET UP AGEBINS model_params[n.index('agebins')]['N'] = ncomp model_params[n.index('agebins')]['init'] = agebins.T ### computational z-fraction setup # N-1 bins # set initial by drawing randomly from the prior model_params[n.index('mass')]['N'] = ncomp model_params[n.index('z_fraction')]['N'] = ncomp-1 tilde_alpha = np.array([ncomp-i for i in xrange(1,ncomp)]) model_params[n.index('z_fraction')]['prior'] = priors.Beta(alpha=tilde_alpha, beta=np.ones_like(tilde_alpha),mini=0.0,maxi=1.0) model_params[n.index('z_fraction')]['init'] = np.array([(i-1)/float(i) for i in range(ncomp,1,-1)]) model_params[n.index('z_fraction')]['init_disp'] = 0.02 ### apply SDSS mass-metallicity prior model_params[n.index('logzsol')]['prior'] = MassMet(mini=-1.98, maxi=0.19) #### INSERT REDSHIFT INTO MODEL PARAMETER DICTIONARY #### zind = n.index('zred') model_params[zind]['init'] = zred #### CREATE MODEL model = SedMet(model_params) return model
def grid(Nage=80, NZ=20, nebular=True, dust=False): """ Generate grid of spectra with FSPS Returns: spec (array, float) spectra, dimensions NZ*Nage metallicities (array, float) metallicity array, units Z / Zsol scale_factors (array, flota) age array in units of the scale factor wl (array, float) wavelength array in Angstroms """ if dust: sp = fsps.StellarPopulation(zcontinuous=1, sfh=0, logzsol=0.0, add_neb_emission=nebular, dust_type=2, dust2=0.2, cloudy_dust=True, dust1=0.0) else: sp = fsps.StellarPopulation(zcontinuous=1, sfh=0, cloudy_dust=True, logzsol=0.0, add_neb_emission=nebular) wl = np.array(sp.get_spectrum(tage=13, peraa=True)).T[:, 0] ages = np.logspace(-3.5, np.log10(cosmo.age(0).value - 0.4), num=Nage, base=10) scale_factors = cosmo.scale_factor( [z_at_value(cosmo.lookback_time, age * u.Gyr) for age in ages]) metallicities = np.linspace(-3, 1, num=NZ) # log(Z / Zsol) spec = np.zeros((len(metallicities), len(ages), len(wl))) for i, Z in enumerate(metallicities): for j, a in enumerate(ages): sp.params['logzsol'] = Z if nebular: sp.params['gas_logz'] = Z spec[i, j] = sp.get_spectrum(tage=a, peraa=True)[1] # Lsol / AA return spec, scale_factors, metallicities, wl
def load_model(objname=None, datdir=None, runname=None, agelims=[], zred=None, alpha_sfh=0.2, **extras): # we'll need this to access specific model parameters n = [p['name'] for p in model_params] # first calculate redshift and corresponding t_universe # if no redshift is specified, read from file if zred is None: datname = datdir + objname.split('_')[0] + '_' + runname + '.dat' dat = ascii.read(datname) idx = dat['phot_id'] == int(objname.split('_')[-1]) zred = float(dat['z_best'][idx]) tuniv = WMAP9.age(zred).value # now construct the nonparametric SFH # current scheme: six bins, four spaced equally in logarithmic # last bin is 15% age of the Universe, first two are 0-30, 30-100 tbinmax = (tuniv*0.85)*1e9 agelims = agelims[:2] + np.linspace(agelims[2],np.log10(tbinmax),len(agelims)-3).tolist() + [np.log10(tuniv*1e9)] agebins = np.array([agelims[:-1], agelims[1:]]) ncomp = len(agelims) - 1 # load into `agebins` in the model_params dictionary model_params[n.index('agebins')]['N'] = ncomp model_params[n.index('agebins')]['init'] = agebins.T # now we do the computational z-fraction setup # number of zfrac variables = (number of SFH bins - 1) # set initial with a constant SFH # if alpha_SFH is a vector, use this as the alpha array # else assume all alphas are the same model_params[n.index('mass')]['N'] = ncomp model_params[n.index('z_fraction')]['N'] = ncomp-1 if type(alpha_sfh) != type(np.array([])): alpha = np.repeat(alpha_sfh,ncomp-1) else: alpha = alpha_sfh tilde_alpha = np.array([alpha[i-1:].sum() for i in xrange(1,ncomp)]) model_params[n.index('z_fraction')]['prior'] = priors.Beta(alpha=tilde_alpha, beta=alpha, mini=0.0, maxi=1.0) model_params[n.index('z_fraction')]['init'] = np.array([(i-1)/float(i) for i in range(ncomp,1,-1)]) model_params[n.index('z_fraction')]['init_disp'] = 0.02 # set mass-metallicity prior # insert redshift into model dictionary model_params[n.index('massmet')]['prior'] = MassMet(z_mini=-1.98, z_maxi=0.19, mass_mini=7, mass_maxi=12.5) model_params[n.index('zred')]['init'] = zred return sedmodel.SedModel(model_params)
def make_scattered_galaxy(filename, **kwargs): print "attempting to read in ", filename input_galaxy = ascii.read(filename) galaxy = initialize_galaxy(len(input_galaxy)) dt = 1.e7 print "assuming timestep is 1.e7 years!!!!!" galaxy['dt'] += 1.e7*u.yr galaxy['sfr'] = np.power(10.0,input_galaxy['SFR']) * u.Msun/u.yr galaxy['dMrdt'] = np.power(10.0,input_galaxy['Mrec'])* u.Msun / galaxy['dt'] # galaxy['dMrdt'].unit = u.Msun / u.yr ## Need to get gas masses from Gergo's code fake_radius = 3000. + np.zeros(len(galaxy['sfr'])) gas = ig.gas_masses(galaxy['sfr'], input_galaxy['Ms'], fake_radius) Mgas, Mhi, Mh2 = gas[0], gas[1], gas[2] galaxy['Mg'] = Mgas * HELIUM_CORR * u.Msun galaxy['Mhi'] = Mhi * u.Msun galaxy['Mh2'] = Mh2 * u.Msun galaxy['Ms'] = np.power(10.0,input_galaxy['Ms']) * u.Msun col_dummy = Column(name='z',data=input_galaxy['z']) galaxy.add_column(col_dummy) print "ASSUMING PROBABLY A WRONG COSMOLOGY FYI" age = cosmo.age(galaxy['z']) ### THIS COSMOLOGY IS WRONG galaxy['age'] = age tlb = cosmo.lookback_time(galaxy['z']) galaxy['lookback'] = tlb galaxy.remove_column('Mh') galaxy.remove_column('Mcgm') galaxy.remove_column('tlogoh') ## check to make sure sorted so earlier is earlier galaxy.sort('age') print galaxy return galaxy
def read_in_galaxy(filename, index): print "attempting to read in",filename if ".pkl" in filename: print "assuming that",filename,"is a pickle file with only a dict of galaxies in it" galaxies = pickle.load(open(filename,"r")) print "for now we're only dealing with one galaxy at a time; taking galaxy #",index assert(index in galaxies.keys()), "index %i not in file :-(" % index galaxy = galaxies[index] col_z = Column(name='z',data=galaxies['z']) galaxy.add_column(col_z,0) elif "peter" in filename: print "assuming that",filename,"is an ascii file from peter behroozi and gergo popping with Mh,Ms,dMhdt,sfr,Mg,Mhi,Mh2" print "also assuming that",filename,"only has one iteration" z,Mh,Ms,dMhdt,sfr,Mg,Mhi,Mh2 = np.loadtxt(filename,usecols=(0,7*index+1,7*index+2,7*index+3,7*index+4,7*index+5,7*index+6,7*index+7),unpack=True) galaxy = QTable([z,Mh,Ms,dMhdt,sfr,Mg,Mhi,Mh2],names=('z','Mh','Ms','dMhdt','sfr','Mg','Mhi','Mh2')) ## need to add units galaxy['Mh'].unit = u.Msun galaxy['Ms'].unit = u.Msun galaxy['Mg'].unit = u.Msun galaxy['Mhi'].unit = u.Msun galaxy['Mh2'].unit = u.Msun galaxy['dMhdt'].unit = u.Msun / u.yr if 'dMrdt' in galaxy.colnames: galaxy['dMrdt'].unit = u.Msun / u.yr galaxy['sfr'].unit = u.Msun / u.yr ### Helium is not included in the gas masses!! galaxy['Mg'] = galaxy['Mg'] * HELIUM_CORR ### Let's make a CGM! ### galaxy['Mcgm'] = galaxy['Mh']*cosmo.Ob0/cosmo.Om0 - galaxy['Ms'] - galaxy['Mg'] age = cosmo.age(galaxy['z']) col_age = Column(name='age', data=age) galaxy.add_column(col_age,1) tlb = cosmo.lookback_time(galaxy['z']) col_tlb = Column(name='lookback', data=tlb) galaxy.add_column(col_tlb,2) ## check to make sure sorted so earlier is earlier galaxy.sort('age') return galaxy
def load_model(objname='',datname='', agelims=[], **extras): ###### REDSHIFT ###### hdulist = fits.open(datname) idx = hdulist[1].data['Name'] == objname zred = hdulist[1].data['cz'][idx][0] / 3e5 lumdist = hdulist[1].data['Dist'][idx][0] hdulist.close() #### CALCULATE TUNIV ##### tuniv = WMAP9.age(zred).value #### NONPARAMETRIC SFH ###### agelims[-1] = np.log10(tuniv*1e9) agebins = np.array([agelims[:-1], agelims[1:]]) ncomp = len(agelims) - 1 #### ADJUST MODEL PARAMETERS ##### n = [p['name'] for p in model_params] #### SET UP AGEBINS model_params[n.index('agebins')]['N'] = ncomp model_params[n.index('agebins')]['init'] = agebins.T #### FRACTIONAL MASS INITIALIZATION # N-1 bins, last is set by x = 1 - np.sum(sfr_fraction) model_params[n.index('z_fraction')]['N'] = ncomp-1 tilde_alpha = np.array([ncomp-i for i in xrange(1,ncomp)]) model_params[n.index('z_fraction')]['prior'] = priors.Beta(alpha=tilde_alpha, beta=np.ones_like(tilde_alpha),mini=0.0,maxi=1.0) model_params[n.index('z_fraction')]['init'] = model_params[n.index('z_fraction')]['prior'].sample() model_params[n.index('z_fraction')]['init_disp'] = 0.02 model_params[n.index('sfr_fraction')]['N'] = ncomp-1 model_params[n.index('sfr_fraction')]['prior'] = priors.TopHat(maxi=np.full(ncomp-1,1.0), mini=np.full(ncomp-1,0.0)) model_params[n.index('sfr_fraction')]['init'] = np.zeros(ncomp-1)+1./ncomp model_params[n.index('sfr_fraction')]['init_disp'] = 0.02 #### INSERT REDSHIFT INTO MODEL PARAMETER DICTIONARY #### model_params[n.index('zred')]['init'] = zred model_params[n.index('lumdist')]['init'] = lumdist #### CREATE MODEL model = BurstyModel(model_params) return model
def load_model(objname='', datname='', agelims=[], **extras): ###### REDSHIFT ###### hdulist = fits.open(datname) idx = hdulist[1].data['Name'] == objname zred = hdulist[1].data['cz'][idx][0] / 3e5 hdulist.close() #### CALCULATE TUNIV ##### tuniv = WMAP9.age(zred).value #### NONPARAMETRIC SFH ###### agelims[-1] = np.log10(tuniv*1e9) agebins = np.array([agelims[:-1], agelims[1:]]) ncomp = len(agelims) - 1 mass_init = expsfh(agelims, **extras)*1e5 #### ADJUST MODEL PARAMETERS ##### n = [p['name'] for p in model_params] #### SET UP AGEBINS model_params[n.index('agebins')]['N'] = ncomp model_params[n.index('agebins')]['init'] = agebins.T #### FRACTIONAL MASS # N-1 bins, last is set by x = 1 - np.sum(sfr_fraction) model_params[n.index('sfr_fraction')]['N'] = ncomp-1 model_params[n.index('sfr_fraction')]['init'] = mass_init[:-1] / np.sum(mass_init) model_params[n.index('sfr_fraction')]['prior_args'] = { 'maxi':np.full(ncomp-1,1.0), 'mini':np.full(ncomp-1,0.0), 'alpha':1.0, 'alpha_sum':ncomp # NOTE: ncomp instead of ncomp-1 makes the prior take into account the implicit Nth variable too } model_params[n.index('sfr_fraction')]['init_disp'] = 0.15 #### INSERT REDSHIFT INTO MODEL PARAMETER DICTIONARY #### zind = n.index('zred') model_params[zind]['init'] = zred #### CREATE MODEL model = BurstyModel(model_params) return model
def load_model(objname=None, datloc=None, agelims=[], zred=None, nbins_sfh=7, sigma=0.3,df=2, **extras): # we'll need this to access specific model parameters n = [p['name'] for p in model_params] # first calculate redshift and corresponding t_universe # if no redshift is specified, read from file if zred is None: ### open file, load data with open(datloc, 'r') as f: hdr = f.readline().split() dtype = np.dtype([(hdr[1],'S20')] + [(nam, np.float) for nam in hdr[2:]]) dat = np.loadtxt(datloc, comments = '#', dtype = dtype) obj_idx = (dat['ID'] == objname) zred = dat['zz'][obj_idx] tuniv = WMAP9.age(zred).value # now construct the nonparametric SFH # current scheme: six bins, four spaced equally in logarithmic # last bin is 15% age of the Universe, first two are 0-30, 30-100 tbinmax = (tuniv*0.85)*1e9 agelims = agelims[:2] + np.linspace(agelims[2],np.log10(tbinmax),len(agelims)-3).tolist() + [np.log10(tuniv*1e9)] agebins = np.array([agelims[:-1], agelims[1:]]) ncomp = len(agelims) - 1 # load into `agebins` in the model_params dictionary model_params[n.index('agebins')]['N'] = ncomp model_params[n.index('agebins')]['init'] = agebins.T # load nvariables and agebins model_params[n.index('agebins')]['N'] = ncomp model_params[n.index('agebins')]['init'] = agebins.T model_params[n.index('mass')]['N'] = ncomp model_params[n.index('logsfr_ratios')]['N'] = nbins_sfh-1 model_params[n.index('logsfr_ratios')]['init'] = np.full(nbins_sfh-1,0.0) # constant SFH model_params[n.index('logsfr_ratios')]['prior'] = priors.StudentT(mean=np.full(nbins_sfh-1,0.0), scale=np.full(nbins_sfh-1,sigma), df=np.full(nbins_sfh-1,df)) # set mass-metallicity prior # insert redshift into model dictionary model_params[n.index('massmet')]['prior'] = MassMet(z_mini=-1.98, z_maxi=0.19, mass_mini=7, mass_maxi=12.5) model_params[n.index('zred')]['init'] = zred return sedmodel.SedModel(model_params)
def test_magnitudes(): bt = StarlightBase( '/Users/william/BasesDir/Base.bc03.Padova1994.chab.All.hdf5', 'Base.bc03.Padova1994.chab.All') i_met = 0 i_z = 0 z = np.array([0.5, 1.0, 1.5]) # Generate random parameters to test: z_age_limit = cosmo.age(0.01).to('yr').value t0_young = np.log10(6e6) + np.random.rand() * (np.log10(5e9) - np.log10(6e6)) tau_young = np.log10(.001) + np.random.rand() * (np.log10(.001) - np.log10(1000)) t0_old = np.log10(1e9) + np.random.rand() * (np.log10(z_age_limit) - np.log10(1e9)) tau_old = np.log10(.001) + np.random.rand() * (np.log10(.001) - np.log10(1000)) frac_young = np.random.rand() a_v = 2 * np.random.rand() print 'Parameters: ', z_age_limit, t0_young, tau_young, t0_old, tau_old, frac_young, a_v # Create the CSP with it csp_model = n_component(bt.ageBase) csp_model.add_exp(t0_young, tau_young, frac_young) csp_model.add_exp(t0_old, tau_old, 1 - frac_young) # Calculate the analytic integral spec = np.sum(bt.f_ssp[i_met] * csp_model.get_sfh()[:, np.newaxis], axis=0) # Base spectra [??units??] spec *= 10**(-0.4 * (Cardelli_RedLaw(bt.l_ssp) * a_v)) mags_analytic = mag_in_z(bt.l_ssp, spec, z[i_z], filters) # Calculate the Taylor Approximation for n_taylor in range(1, 10): t0 = time.time() m, a, f = taylor_matrix_ssp(bt, n_taylor, z, filters) mags_taylor = mag_in_z_taylor(csp_model.get_sfh(), a_v, i_z, i_met, m, a) print 'n_taylor, t, max |delta_m| = ', n_taylor, time.time( ) - t0, np.max(np.abs(mags_taylor - mags_analytic))
def load_model(objname=None, datloc=None, agelims=[0.0,7.4772,8.0,8.5,9.0,9.5,9.8,10.0], zred=None, nbins_sfh=7, sigma=0.3,df=2, **extras): # we'll need this to access specific model parameters n = [p['name'] for p in model_params] # first calculate redshift and corresponding t_universe # if no redshift is specified, read from file if zred is None: dat = fits.open(datloc)[1].data obj_idx = (dat['CATAID'] == int(objname)) zred = dat['Z'][obj_idx] tuniv = WMAP9.age(zred).value # now construct the nonparametric SFH # current scheme: six bins, four spaced equally in logarithmic # last bin is 15% age of the Universe, first two are 0-30, 30-100 tbinmax = (tuniv*0.85)*1e9 agelims = agelims[:2] + np.linspace(agelims[2],np.log10(tbinmax),len(agelims)-3).tolist() + [float(np.log10(tuniv*1e9))] if type(agelims[-3]) == type([]): # workaround for odyssey numpy agelims = [np.atleast_1d(x)[0] for x in agelims] agebins = np.array([agelims[:-1], agelims[1:]]) ncomp = len(agelims) - 1 # load into `agebins` in the model_params dictionary model_params[n.index('agebins')]['N'] = ncomp model_params[n.index('agebins')]['init'] = agebins.T # load nvariables and agebins model_params[n.index('agebins')]['N'] = ncomp model_params[n.index('agebins')]['init'] = agebins.T model_params[n.index('mass')]['N'] = ncomp model_params[n.index('logsfr_ratios')]['N'] = nbins_sfh-1 model_params[n.index('logsfr_ratios')]['init'] = np.full(nbins_sfh-1,0.0) # constant SFH model_params[n.index('logsfr_ratios')]['prior'] = priors.StudentT(mean=np.full(nbins_sfh-1,0.0), scale=np.full(nbins_sfh-1,sigma), df=np.full(nbins_sfh-1,df)) # set mass-metallicity prior # insert redshift into model dictionary model_params[n.index('massmet')]['prior'] = MassMet(z_mini=-1.98, z_maxi=0.19, mass_mini=7, mass_maxi=12.5) model_params[n.index('zred')]['init'] = zred return sedmodel.SedModel(model_params)
def load_model(objname=None, datdir=None, runname=None, zred=None, **extras): # we'll need this to access specific model parameters n = [p['name'] for p in model_params] # first calculate redshift and corresponding t_universe # if no redshift is specified, read from file if zred is None: datname = datdir + objname.split('_')[0] + '_' + runname + '.dat' dat = ascii.read(datname) idx = dat['phot_id'] == int(objname.split('_')[-1]) zred = float(dat['z_best'][idx]) tuniv = WMAP9.age(zred).value model_params[n.index('tage')]['prior'].update(maxi=tuniv) # set mass-metallicity prior # insert redshift into model dictionary model_params[n.index('massmet')]['prior'] = MassMet(z_mini=-1.98, z_maxi=0.19, mass_mini=7, mass_maxi=12.5) model_params[n.index('zred')]['init'] = zred return sedmodel.SedModel(model_params)
def load_model(objname=None, datdir=None, agelims=[], runname=None, zred=None, **extras): ###### REDSHIFT ###### # first calculate redshift and corresponding t_universe # if no redshift is specified, read from file if zred is None: datname = datdir + objname.split('_')[0] + '_' + runname + '.dat' dat = ascii.read(datname) idx = dat['phot_id'] == int(objname.split('_')[-1]) zred = float(dat['z_best'][idx]) tuniv = WMAP9.age(zred).value # Update parameters n = [p['name'] for p in model_params] model_params[n.index('tage')]['prior'].update(maxi=tuniv) model_params[n.index('zred')]['init'] = zred #### CREATE MODEL model = sedmodel.SedModel(model_params) return model
def load_model(objname=None, datloc=None, agelims=[], zred=None, nbins_sfh=7, sigma=0.3,df=2, **extras): # we'll need this to access specific model parameters n = [p['name'] for p in model_params] # first calculate redshift and corresponding t_universe # if no redshift is specified, read from file if zred is None: dat = fits.open(datloc)[1].data obj_idx = (dat['CATAID'] == int(objname)) zred = dat['Z'][obj_idx] tuniv = WMAP9.age(zred).value # update prior for tage model_params[n.index('tage')]['prior'].update(maxi=tuniv) # set mass-metallicity prior # insert redshift into model dictionary model_params[n.index('massmet')]['prior'] = MassMet(z_mini=-1.98, z_maxi=0.19, mass_mini=7, mass_maxi=12.5) model_params[n.index('zred')]['init'] = zred return sedmodel.SedModel(model_params)
def load_model(objname='',datname='', agelims=[], **extras): ###### REDSHIFT ###### hdulist = fits.open(datname) idx = hdulist[1].data['Name'] == objname zred = hdulist[1].data['cz'][idx][0] / 3e5 hdulist.close() #### CALCULATE TUNIV ##### tuniv = WMAP9.age(zred).value #### NONPARAMETRIC SFH ###### agelims[-1] = np.log10(tuniv*1e9) agebins = np.array([agelims[:-1], agelims[1:]]) ncomp = len(agelims) - 1 #### ADJUST MODEL PARAMETERS ##### n = [p['name'] for p in model_params] #### SET UP AGEBINS model_params[n.index('agebins')]['N'] = ncomp model_params[n.index('agebins')]['init'] = agebins.T #### FRACTIONAL MASS INITIALIZATION # N-1 bins, last is set by x = 1 - np.sum(sfr_fraction) model_params[n.index('mass')]['N'] = ncomp model_params[n.index('mass')]['prior_args'] = {'maxi':np.full(ncomp,1e5), 'mini':np.full(ncomp,1e14),} model_params[n.index('mass')]['init'] = np.full(ncomp,1e10) #### INSERT REDSHIFT INTO MODEL PARAMETER DICTIONARY #### zind = n.index('zred') model_params[zind]['init'] = zred #### CREATE MODEL model = BurstyModel(model_params) return model
def load_model(alpha_sfh=0.2,agelims=None, **extras): # we'll need this to access specific model parameters n = [p['name'] for p in model_params] # create SFH bins zred = model_params[n.index('zred')]['init'] tuniv = WMAP9.age(zred).value # now construct the nonparametric SFH # current scheme: six bins, four spaced equally in logarithmic # last bin is 15% age of the Universe, first two are 0-30, 30-100 tbinmax = (tuniv*0.85)*1e9 agelims = agelims[:2] + np.linspace(agelims[2],np.log10(tbinmax),len(agelims)-3).tolist() + [np.log10(tuniv*1e9)] agebins = np.array([agelims[:-1], agelims[1:]]) ncomp = len(agelims) - 1 # load into `agebins` in the model_params dictionary model_params[n.index('agebins')]['N'] = ncomp model_params[n.index('agebins')]['init'] = agebins.T # now we do the computational z-fraction setup # number of zfrac variables = (number of SFH bins - 1) # set initial with a constant SFH # if alpha_SFH is a vector, use this as the alpha array # else assume all alphas are the same model_params[n.index('mass')]['N'] = ncomp model_params[n.index('z_fraction')]['N'] = ncomp-1 if type(alpha_sfh) != type(np.array([])): alpha = np.repeat(alpha_sfh,ncomp-1) else: alpha = alpha_sfh tilde_alpha = np.array([alpha[i-1:].sum() for i in xrange(1,ncomp)]) model_params[n.index('z_fraction')]['prior'] = priors.Beta(alpha=tilde_alpha, beta=alpha, mini=0.0, maxi=1.0) model_params[n.index('z_fraction')]['init'] = np.array([(i-1)/float(i) for i in range(ncomp,1,-1)]) model_params[n.index('z_fraction')]['init_disp'] = 0.02 return sedmodel.SedModel(model_params)
def load_model(objname='', agelims=[], **extras): ###### LOAD REDSHIFT ###### zred = 0.0 #### CALCULATE TUNIV ##### tuniv = WMAP9.age(zred).value #### NONPARAMETRIC SFH ###### agelims[-1] = np.log10(tuniv*1e9) agebins = np.array([agelims[:-1], agelims[1:]]) ncomp = len(agelims) - 1 mass_init = expsfh(agelims, **extras)*1e5 #### ADJUST MODEL PARAMETERS ##### n = [p['name'] for p in model_params] model_params[n.index('logmass')]['N'] = ncomp model_params[n.index('logmass')]['init'] = np.log10(mass_init) model_params[n.index('logmass')]['prior_args'] = {'maxi':np.full(ncomp,14.0), 'mini':np.full(ncomp,1.0)} model_params[n.index('logmass')]['init_disp'] = 0.3 model_params[n.index('mass')]['N'] = ncomp model_params[n.index('mass')]['init'] = mass_init model_params[n.index('mass')]['prior_args'] = {'maxi':np.full(ncomp,10**14.0), 'mini':np.full(ncomp,10**1.0)} model_params[n.index('agebins')]['N'] = ncomp model_params[n.index('agebins')]['init'] = agebins.T #### INSERT REDSHIFT INTO MODEL PARAMETER DICTIONARY #### zind = n.index('zred') model_params[zind]['init'] = zred #### CREATE AND RETURN MODEL model = BurstyModel(model_params) return model
def load_model(objname='',datname='', agelims=[], nbins_sfh=7, sigma=0.3, df=2, **extras): # we'll need this to access specific model parameters n = [p['name'] for p in model_params] # set redshift, tuniv hdulist = fits.open(datname) idx = hdulist[1].data['Name'] == objname zred = hdulist[1].data['cz'][idx][0] / 3e5 tuniv = WMAP9.age(zred).value*1e9 lumdist = hdulist[1].data['Dist'][idx][0] hdulist.close() # now construct the nonparametric SFH # current scheme: last bin is 15% age of the Universe, first two are 0-30, 30-100 # remaining N-3 bins spaced equally in logarithmic space tbinmax = (tuniv*0.85) agelims = agelims[:2] + np.linspace(agelims[2],np.log10(tbinmax),nbins_sfh-2).tolist() + [np.log10(tuniv)] agebins = np.array([agelims[:-1], agelims[1:]]) # load nvariables and agebins model_params[n.index('agebins')]['N'] = nbins_sfh model_params[n.index('agebins')]['init'] = agebins.T model_params[n.index('mass')]['N'] = nbins_sfh model_params[n.index('logsfr_ratios')]['N'] = nbins_sfh-1 model_params[n.index('logsfr_ratios')]['init'] = np.full(nbins_sfh-1,0.0) # constant SFH model_params[n.index('logsfr_ratios')]['prior'] = priors.StudentT(mean=np.full(nbins_sfh-1,0.0), scale=np.full(nbins_sfh-1,sigma), df=np.full(nbins_sfh-1,df)) # set mass-metallicity prior # insert redshift into model dictionary model_params[n.index('massmet')]['prior'] = MassMet(z_mini=-1.98, z_maxi=0.19, mass_mini=7, mass_maxi=12.5) model_params[n.index('zred')]['init'] = zred model_params[n.index('lumdist')]['init'] = lumdist return sedmodel.SedModel(model_params)
def __init__(self, template_magnitudes, filters, z, base_file, base_path, taylor_file=None, magerr=1e-14, is_single=False): # Template magnitudes self.template_magnitudes = template_magnitudes # self.chi2_constant = np.average(template_magnitudes) # This will be summed to chi2, avoiding to get them ~ 0. self.filters = filters self.z = z self.z_age_limit = cosmo.age(z).to('yr').value # Base self.bt = StarlightBase(base_file, base_path) ## Metallicity aux = np.log10(self.bt.metBase) aux2 = (aux[1:] - aux[0:-1]) / 2 self.met_min = aux - np.append(aux2[0], aux2) self.met_max = aux + np.append(aux2, aux2[-1]) self.met_low = min(self.met_min) self.met_upp = max(self.met_max) # Extinction Law self.q = Cardelli_RedLaw(self.bt.l_ssp) # If Taylor expansion: if taylor_file: self.m, self.a, self.tz, self.int_f = load_taylor(config, filters) # Magnitude error self.magerr = magerr
def load_model(nbins_sfh=7, sigma=0.3, df=2, agelims=[], objname=None, datdir=None, runname=None, zred=None,**extras): # we'll need this to access specific model parameters n = [p['name'] for p in model_params] # first calculate redshift and corresponding t_universe # if no redshift is specified, read from file if zred is None: datname = datdir + 'joel_'+objname.split('_')[0].lower() + '.csv' dat = read_csv(datname) idx = dat['ID'] == int(objname.split('_')[-1]) zred = float(dat['REDSHIFT'][idx]) tuniv = WMAP9.age(zred).value*1e9 # now construct the nonparametric SFH # current scheme: last bin is 15% age of the Universe, first two are 0-30, 30-100 # remaining N-3 bins spaced equally in logarithmic space tbinmax = (tuniv*0.85) agelims = agelims[:2] + np.linspace(agelims[2],np.log10(tbinmax),nbins_sfh-2).tolist() + [np.log10(tuniv)] agebins = np.array([agelims[:-1], agelims[1:]]) # load nvariables and agebins model_params[n.index('agebins')]['N'] = nbins_sfh model_params[n.index('agebins')]['init'] = agebins.T model_params[n.index('mass')]['N'] = nbins_sfh model_params[n.index('logsfr_ratios')]['N'] = nbins_sfh-1 model_params[n.index('logsfr_ratios')]['init'] = np.full(nbins_sfh-1,0.0) # constant SFH model_params[n.index('logsfr_ratios')]['prior'] = priors.StudentT(mean=np.full(nbins_sfh-1,0.0), scale=np.full(nbins_sfh-1,sigma), df=np.full(nbins_sfh-1,df)) # set mass-metallicity prior # insert redshift into model dictionary model_params[n.index('massmet')]['prior'] = MassMet(z_mini=-1.98, z_maxi=0.19, mass_mini=7, mass_maxi=12.5) model_params[n.index('zred')]['init'] = zred return sedmodel.SedModel(model_params)
def load_model(agelims=[], nbins_sfh=7, sigma=0.3, df=2, **extras): # we'll need this to access specific model parameters n = [p['name'] for p in model_params] # first calculate redshift and corresponding t_universe # if no redshift is specified, read from file zred = model_params[n.index('zred')]['init'] tuniv = WMAP9.age(zred).value # now construct the nonparametric SFH # current scheme: six bins, four spaced equally in logarithmic # space AFTER t=100 Myr + BEFORE tuniv-1 Gyr tbinmax = (tuniv-4)*1e9 if tbinmax < 0: tbinmax = (tuniv-0.25)*1e9 agelims = agelims[:1] + np.linspace(agelims[1],np.log10(tbinmax),len(agelims)-2).tolist() + [np.log10(tuniv*1e9)] agebins = np.array([agelims[:-1], agelims[1:]]) ncomp = len(agelims) - 1 # load into `agebins` in the model_params dictionary model_params[n.index('agebins')]['N'] = ncomp model_params[n.index('agebins')]['init'] = agebins.T # load nvariables and agebins model_params[n.index('agebins')]['N'] = ncomp model_params[n.index('agebins')]['init'] = agebins.T model_params[n.index('mass')]['N'] = ncomp model_params[n.index('logsfr_ratios')]['N'] = nbins_sfh-1 model_params[n.index('logsfr_ratios')]['init'] = np.full(nbins_sfh-1,0.0) # constant SFH model_params[n.index('logsfr_ratios')]['prior'] = priors.StudentT(mean=np.full(nbins_sfh-1,0.0), scale=np.full(nbins_sfh-1,sigma), df=np.full(nbins_sfh-1,df)) return sedmodel.SedModel(model_params)
def load_model(objname='', agelims=[], **extras): ###### LOAD REDSHIFT ###### zred = 0.0 #### CALCULATE TUNIV ##### tuniv = WMAP9.age(zred).value #### NONPARAMETRIC SFH ###### agelims[-1] = np.log10(tuniv*1e9) agebins = np.array([agelims[:-1], agelims[1:]]) ncomp = len(agelims) - 1 mass_init = expsfh(agelims, **extras)*1e5 #### ADJUST MODEL PARAMETERS ##### n = [p['name'] for p in model_params] #### SET UP AGEBINS model_params[n.index('agebins')]['N'] = ncomp model_params[n.index('agebins')]['init'] = agebins.T #### FRACTIONAL MASS # N-1 bins, last is set by x = 1 - np.sum(fracmass) model_params[n.index('fracmass')]['N'] = ncomp-1 model_params[n.index('fracmass')]['init'] = mass_init[:-1] / np.sum(mass_init) model_params[n.index('fracmass')]['prior_args'] = {'maxi':np.full(ncomp-1,1.0), 'mini':np.full(ncomp-1,0.0)} model_params[n.index('fracmass')]['init_disp'] = 0.15 #### INSERT REDSHIFT INTO MODEL PARAMETER DICTIONARY #### zind = n.index('zred') model_params[zind]['init'] = zred #### CREATE MODEL model = BurstyModel(model_params) return model
def build_model_un(object_redshift=None, fixed_metallicity=None, add_duste=False, **extras): from prospect.models.sedmodel import SedModel from prospect.models.templates import TemplateLibrary from prospect.models import priors from prospect.models import transforms from prospect.models.templates import adjust_continuity_agebins from astropy.cosmology import WMAP9 as cosmos import prospect # Get (a copy of) one of the prepackaged model set dictionaries. # Get the 2018 prospector-alpha model manually model_params = (TemplateLibrary["continuity_sfh"]) model_params.update(TemplateLibrary["dust_emission"]) model_params.update(TemplateLibrary["nebular"]) model_params.update(TemplateLibrary["agn"]) # Set the dust and agn emission free model_params["fagn"]["isfree"] = True model_params["agn_tau"]["isfree"] = True # Complexify the dust attenuation model_params["dust_type"] = { "N": 1, "isfree": False, "init": 4, "units": "FSPS index" } model_params["dust2"]["prior"] = priors.TopHat(mini=0.0, maxi=4.0) model_params["dust1"] = { "N": 1, "isfree": False, 'depends_on': transforms.dustratio_to_dust1, "init": 0.0, "units": "optical depth towards young stars" } model_params["dust_ratio"] = { "N": 1, "isfree": True, "init": 1.0, "units": "ratio of birth-cloud to diffuse dust", "prior": priors.ClippedNormal(mini=0.0, maxi=2.0, mean=1.0, sigma=0.3) } model_params["dust_index"] = { "N": 1, "isfree": True, "init": 0.0, "units": "power-law multiplication of Calzetti", "prior": priors.TopHat(mini=-2.0, maxi=0.5) } # in Gyr tuniv = cosmos.age(object_redshift).value model_params = adjust_continuity_agebins(model_params, tuniv) model_params["duste_qpah"]["isfree"] = False model_params["duste_umin"]["isfree"] = False model_params["duste_gamma"]["isfree"] = False model_params["duste_qpah"]["init"] = 2.0 model_params["duste_umin"]["init"] = 1.0 model_params["duste_gamma"]["init"] = 0.01 model_params["duste_qpah"]["prior"] = priors.TopHat(mini=0.0, maxi=7.0) model_params["duste_umin"]["prior"] = priors.TopHat(mini=0.1, maxi=25.0) model_params["duste_gamma"]["prior"] = priors.TopHat(mini=0.0, maxi=1.0) model_params["duste_qpah"]["disp_floor"] = 3.0 model_params["duste_umin"]["disp_floor"] = 4.5 model_params["duste_gamma"]["disp_floor"] = 0.15 model_params["duste_qpah"]["init_disp"] = 3.0 model_params["duste_umin"]["init_disp"] = 5.0 model_params["duste_gamma"]["init_disp"] = 0.2 model_params['gas_logz']["isfree"] = True model_params['gas_logz']["init"] = 0.0 model_params['gas_logz']["prior"] = priors.TopHat(mini=-2.0, maxi=0.5) model_params['gas_logu']["isfree"] = False model_params['gas_logu']["init"] = -1.0 model_params['gas_logu']["prior"] = priors.TopHat(mini=-4.0, maxi=-1.0) # Now add the lumdist parameter by hand as another entry in the dictionary. # This will control the distance since we are setting the redshift to zero. # In `build_obs` above we used a distance of 10pc to convert from absolute to apparent magnitudes, # so we use that here too, since the `maggies` are appropriate for that distance. # Let's make some changes to values appropriate for our objects and data model_params["logzsol"]["prior"] = priors.TopHat(mini=-2.0, maxi=0.2) model_params["dust_index"]["prior"] = priors.TopHat(mini=-2.2, maxi=0.4) model_params["agn_tau"]["prior"] = priors.LogUniform(mini=5, maxi=1.5e2) model_params["dust2"]["prior"] = priors.TopHat(mini=1e-6, maxi=3.0) model_params['dust_type']['init'] = 0 model_params['fagn']['init'] = 0.5 model_params['dust2']['init'] = 0.1 # If we are going to be using emcee, it is useful to provide a # minimum scale for the cloud of walkers (the default is 0.1) model_params["agn_tau"]["disp_floor"] = 1 model_params["dust2"]["disp_floor"] = 1e-2 model_params["logzsol"]["disp_floor"] = 1e-3 model_params['fagn']['disp_floor'] = 1e-3 model_params['dust_index']['disp_floor'] = 1e-3 # Change the model parameter specifications based on some keyword arguments if object_redshift is not None: # make sure zred is fixed model_params["zred"]['isfree'] = False # And set the value to the object_redshift keyword model_params["zred"]['init'] = object_redshift # Change fit orders tparams = {} parnames = [m for m in model_params] fit_order = [ 'logmass', 'dust_index', 'dust2', 'logzsol', 'fagn', 'dust_ratio' ] for param in fit_order: tparams[param] = model_params[param] for param in model_params: if param not in fit_order: tparams[param] = model_params[param] model_params = tparams ######## model_params['add_neb_emission']['init'] = False ######## model_params['sfh']['init'] = 0 # Now instantiate the model object using this dictionary of parameter specifications model = SedModel(model_params) #print(model_params['agebins']) return model
Create a custom cosmology object >>> from astropy.cosmology import FlatLambdaCDM >>> cosmo = FlatLambdaCDM(H0=70, Om0=0.3) >>> cosmo FlatLambdaCDM(H0=70, Om0=0.3, Ode0=0.7) Compute the comoving volume to z=6.5 in cubic Mpc using this cosmology >>> cosmo.comoving_volume(6.5) 2521696198211.6924 Compute the age of the universe in Gyr using the pre-defined WMAP 5-year and WMAP 9-year cosmologies >>> from astropy.cosmology import WMAP5, WMAP9 >>> WMAP5.age(0) 13.723782349795023 >>> WMAP9.age(0) 13.768899510689097 Create a cosmology with a varying `w' >>> from astropy.cosmology import Flatw0waCDM >>> cosmo = Flatw0waCDM(H0=70, Om0=0.3, w0=-1, wa=0.2) Find the separation in proper kpc at z=4 corresponding to 10 arcsec in this cosmology compared to a WMAP9 cosmology >>> cosmo.kpc_proper_per_arcmin(4) * 10 / 60. 68.87214405278925 >>> WMAP9.kpc_proper_per_arcmin(4) * 10 / 60. 71.21374615575363
def sfr_flux_relationship(): # initialize thetas = copy.copy(mod.initial_theta) thetas[mod.theta_index['fagn']] = 0.0 thetas[mod.theta_index['dust2']] = prosp_dutils.av_to_dust2(20) # grids and constants ngrid_sfr, ngrid_zred = 31, 30 sfr_grid = np.linspace(1,1000,ngrid_sfr) zred_grid = np.linspace(0.1,3,ngrid_zred) mags = np.zeros(shape=(ngrid_zred,ngrid_sfr,len(obs['filters']))) wlam = np.array([f.wave_effective for f in obs['filters']]) flux_conversion = 3631*1e-23 tuniv = WMAP9.age(mod.params['zred']).value * 1e9 # loop for j in range(ngrid_zred): # set zred mod.params['zred'] = zred_grid[j] for i in range(ngrid_sfr): # set SFR value thetas[0] = np.log10(sfr_grid[i]*tuniv) _, mags[j,i,:], _ = mod.mean_model(thetas, obs, sps=sps) # convert to cgs mags *= flux_conversion # plot values colors = ['#e31a1c', '#ff7f00','#33a02c','#1f78b4','#6a3d9a','ochre'] labels = ['10$\mu$m','12$\mu$m','15$\mu$m','18$\mu$m','21$\mu$m','24$\mu$m'] fig, ax = plt.subplots(1,2, figsize=(7, 3.5)) zred_idx = np.abs(zred_grid-2).argmin() sfr_idx = np.abs(sfr_grid-100).argmin() for j in range(5): ax[0].plot(np.log10(sfr_grid),np.log10(mags[zred_idx,:,j]),'o-',color=colors[j],label=labels[j],lw=1.4,ms=2.4) ax[1].plot(zred_grid,np.log10(mags[:,sfr_idx,j]),'o-',color=colors[j],label=labels[j],lw=1.4,ms=2.4) ax[0].legend() ax[1].legend() ax[0].set_title('z=2') ax[1].set_title('SFR=100 M$_{\odot}$/yr') for a in ax: a.set_ylabel(r'log(f$_{\nu}$) [cgs]') ax[0].set_xlabel(r'log(SFR) [M$_{\odot}$/yr]') ax[1].set_xlabel(r'redshift') plt.tight_layout() plt.savefig('flux_sfr_redshift.png',dpi=200) plt.close() ascii_write(mags,zred_grid,sfr_grid,'redshift','SFR','flux_sfr_redshift.dat') # loop over fagn thetas[mod.theta_index['agn_tau']] = 10 fagn_grid = np.array([0.0,0.05,0.5]) mags = np.zeros(shape=(ngrid_zred,len(fagn_grid),len(obs['filters']))) # loop for j in range(len(fagn_grid)): # set fagn thetas[mod.theta_index['fagn']] = fagn_grid[j] for i in range(ngrid_zred): # set zred mod.params['zred'] = zred_grid[i] _, mags[i,j,:], _ = mod.mean_model(thetas, obs, sps=sps) # convert to cgs mags *= flux_conversion # plot values fig, ax = plt.subplots(1,1, figsize=(4, 4)) for j in range(5): ax.plot(zred_grid,np.log10(mags[:,0,j]/mags[:,-1,j]),'o-',color=colors[j],label=labels[j],lw=1.4,ms=2.4) ax.set_ylim(-1.5,0) ax.legend() ax.set_ylabel(r'log(f$_{\nu}$/f$_{\nu,AGN}$)') ax.set_xlabel(r'redshift') plt.tight_layout() plt.savefig('agn.png',dpi=200) plt.close() ascii_write(mags,zred_grid,fagn_grid,'redshift','fagn','flux_redshift_agn.dat') # loop over PAH thetas[mod.theta_index['fagn']] = 0.0 qpah_grid = np.array([0.0,2,7]) mags = np.zeros(shape=(ngrid_zred,len(qpah_grid),len(obs['filters']))) # loop for j in range(len(qpah_grid)): # set qph mod.params['duste_qpah'] = qpah_grid[j] for i in range(ngrid_zred): # set zred mod.params['zred'] = zred_grid[i] _, mags[i,j,:], _ = mod.mean_model(thetas, obs, sps=sps) # convert to cgs mags *= flux_conversion # plot values fig, ax = plt.subplots(1,1, figsize=(4, 4)) for j in range(5): ax.plot(zred_grid,np.log10(mags[:,0,j]/mags[:,-1,j]),'o-',color=colors[j],label=labels[j],lw=1.4,ms=2.4) ax.set_ylim(-1.5,0.5) ax.legend() ax.set_ylabel(r'log(f$_{\nu,lowPAH}$/f$_{\nu,highPAH}$)') ax.set_xlabel(r'redshift') ax.axhline(0, linestyle='--', color='k',lw=1,zorder=-1) plt.tight_layout() plt.savefig('qpah.png',dpi=200) plt.close() ascii_write(mags,zred_grid,qpah_grid,'redshift','qpah','flux_redshift_qpah.dat')
print 'Loading gas cell mass...' gas_mass = dd['gas', 'cell_mass'] print 'Loading gas cell position...' gas_x = dd['index', 'x'].in_units('kpc') gas_y = dd['index', 'y'].in_units('kpc') gas_z = dd['index', 'z'].in_units('kpc') print 'Loading star positions...' star_x = dd['stars', 'particle_position_x'].in_units('kpc') star_y = dd['stars', 'particle_position_y'].in_units('kpc') star_z = dd['stars', 'particle_position_z'].in_units('kpc') star_mass = dd['stars', 'particle_mass'].in_units('Msun') star_creation_time = dd['stars', 'particle_creation_time'].in_units('yr') star_age_all = ds.arr(cosmo.age(ds.current_redshift).value, 'Gyr').in_units('yr') - star_creation_time print 'Loading star velocities...' star_vx = dd['stars', 'particle_velocity_x'].in_units('km/s') star_vy = dd['stars', 'particle_velocity_y'].in_units('km/s') star_vz = dd['stars', 'particle_velocity_z'].in_units('km/s') #Recenter the gas cells to galaxy center cen_x = star_x[id_cen_star-1] - ds.arr(cen_star_offset[0], 'kpc') cen_y = star_y[id_cen_star-1] - ds.arr(cen_star_offset[1], 'kpc') cen_z = star_z[id_cen_star-1] - ds.arr(cen_star_offset[2], 'kpc') cen_vx = star_vx[id_cen_star-1] - ds.arr(cen_star_voffset[0], 'km/s') cen_vy = star_vy[id_cen_star-1] - ds.arr(cen_star_voffset[1], 'km/s') cen_vz = star_vz[id_cen_star-1] - ds.arr(cen_star_voffset[2], 'km/s')
from astropy.cosmology import WMAP9 as cosmo import h5py from magal.io.readfilterset import FilterSet from magal.photometry.syntphot import spec2filterset from magal.util.cosmo import zcor import pystarlight.io # #### Defs ##### bases_dir = '%s/BasesDir/' % os.environ.get('HOME') # base_file = '%s/Base.bc03.Padova1994.chab.All' % bases_dir base_file = '%s/Base.BC03.N' % bases_dir bt = atpy.Table(base_file, '/Users/william/BasesDir/', type='starlightv4_base', read_basedir=True) base_ages = bt['age_base'] base_maxage = np.max(base_ages) min_z_age = cosmo.age(0.001).to('yr').value if base_maxage > min_z_age: base_maxage = min_z_age from parametric_library import lib_guess Z_model = 0.02 # Z_\odot flag_Z = (bt['Z_base'] == bt['Z_base'][np.argmin((Z_model - bt['Z_base']) ** 2)]) # Get a mask to the desired metallicity n_model = 10000 _i_norm = int(np.argwhere(bt.l_ssp[0] == 4020.)) at_flux = []
def univ_age(): z = ((df_sel.sort_values(['redshift'], ascending=False).reset_index(drop=True))['redshift'][0]) u_age = (cosmo.age(z).value)*1000 u_age = np.round(u_age, decimals=4) return u_age
red = df6['redshift'] flu = df6['fluence'] fig = plt.figure(figsize=(14,8)) ax = fig.add_subplot(111) ax.scatter(red, flu, color='DarkBlue') ax.grid(True) plt.title("Modeling GRB's observed by Swift", fontsize=36) plt.xlabel("Redshift", fontsize=24) plt.ylabel("Fluence(erg/cm^2)", fontsize=24) plt.ylim([0,.00005]) plt.xlim([0,12]) plt.show() continue elif plot_choice.lower() == 'ra': z = df6['redshift'] u_age = (cosmo.age(z).value)*1000 fig = plt.figure(figsize=(14,8)) ax = fig.add_subplot(111) ax.scatter(u_age, z, color='#CC0000') ax.grid(True) ax.annotate('Big Bang', fontsize=20, xy=(0, 0), xytext=(20, 2), arrowprops=dict(facecolor='black'), ) plt.title("GRB Redshifts and Age of the Universe", fontsize=36) plt.xlabel("Age of Universe(in millions of years)", fontsize=24) plt.ylabel("Redshift", fontsize=24) plt.ylim([0,12]) plt.xlim([0,2000]) plt.show() continue elif plot_choice == 'q':
def build_model(fixed_metallicity=None, luminosity_distance=None, **extras): """Construct a model. This method defines a number of parameter specification dictionaries and uses them to initialize a `models.sedmodel.SedModel` object. :param object_redshift: If given, given the model redshift to this value. :param add_dust: (optional, default: False) Switch to add (fixed) parameters relevant for dust emission. :param add_neb: (optional, default: False) Switch to add (fixed) parameters relevant for nebular emission, and turn nebular emission on. :param luminosity_distance: (optional) If present, add a `"lumdist"` parameter to the model, and set it's value (in Mpc) to this. This allows one to decouple redshift from distance, and fit, e.g., absolute magnitudes (by setting luminosity_distance to 1e-5 (10pc)) """ from prospect.models.templates import TemplateLibrary, adjust_continuity_agebins from prospect.models import priors, sedmodel, transforms model_params = TemplateLibrary['continuity_sfh'] ### BASIC PARAMETERS ### model_params["imf_type"] = { 'N': 1, 'isfree': False, 'init': 1, #1=Chabrier 'prior': None } model_params['zred'] = { 'N': 1, 'isfree': True, 'init': obj_red, "prior": priors.TopHat(mini=obj_red - 0.05, maxi=obj_red + 0.05) } model_params['add_igm_absorption'] = { 'N': 1, 'isfree': False, 'init': 1, 'units': None, 'prior': None } model_params['add_agb_dust_model'] = { 'N': 1, 'isfree': False, 'init': 1, 'units': None, 'prior': None } # model_params['pmetals'] = {'N': 1, # 'isfree': False, # 'init': -99, # 'units': '', # 'prior': priors.TopHat(mini=-3, maxi=-1)} ### SFH ### tuniv = WMAP9.age(obj_red).value model_params = adjust_continuity_agebins(model_params, tuniv=tuniv, nbins=7) ### DUST ABSORPTION ### model_params['dust_type'] = { 'N': 1, 'isfree': False, 'init': 4, #4=Kriek & Conroy 'units': 'index', 'prior': None } model_params['dust1'] = { 'N': 1, 'isfree': False, 'depends_on': transforms.dustratio_to_dust1, 'init': 0., 'units': 'optical depth towards young stars' } model_params['dust_ratio'] = { 'N': 1, 'isfree': True, 'init': 1.0, 'init_disp': 0.8, 'disp_floor': 0.8, 'units': 'ratio of birth-cloud to diffuse dust', 'prior': priors.ClippedNormal(mini=0.0, maxi=2.0, mean=1.0, sigma=0.3) } model_params['dust2'] = { 'N': 1, 'isfree': True, 'init': 1.0, 'init_disp': 0.25, 'disp_floor': 0.15, 'units': 'optical depth at 5500AA', 'prior': priors.ClippedNormal(mini=0.0, maxi=4.0, mean=0.3, sigma=1) } model_params['dust_index'] = { 'N': 1, 'isfree': True, 'init': 0.0, 'init_disp': 0.25, 'disp_floor': 0.15, 'units': 'power-law multiplication of Calzetti', 'prior': priors.TopHat(mini=-2.0, maxi=0.5) } ### DUST EMISSION ### model_params.update(TemplateLibrary["dust_emission"]) ### NEBULAR EMISSION ### model_params['add_neb_emission'] = { 'N': 1, 'isfree': False, 'init': True, 'prior': None } model_params['add_neb_continuum'] = { 'N': 1, 'isfree': False, 'init': True, 'prior': None } model_params['gas_logz'] = { 'N': 1, 'isfree': True, 'init': 0.0, 'units': r'log Z/Z_\odot', 'prior': priors.TopHat(mini=-2.0, maxi=0.5) } model_params['gas_logu'] = { 'N': 1, 'isfree': True, 'init': -1.0, 'units': '', 'prior': priors.TopHat(mini=-4.0, maxi=-1.0) } ### CALIBRATION ### model_params['polyorder'] = {'N': 1, 'init': 10, 'isfree': False} model_params['spec_norm'] = { 'N': 1, 'init': 1.0, 'isfree': True, 'prior': priors.Normal(sigma=0.2, mean=1.0), 'units': 'f_true/f_obs' } model_params['spec_jitter'] = { "N": 1, "isfree": True, "init": 1.0, "prior": priors.TopHat(mini=0., maxi=4.0) } model_params['f_outlier_spec'] = { "N": 1, "isfree": True, "init": 0.01, "prior": priors.TopHat(mini=1e-5, maxi=0.5) } model_params['nsigma_outlier_spec'] = { "N": 1, "isfree": False, "init": 5.0 } ### SMOOTHING ### model_params.update(TemplateLibrary["spectral_smoothing"]) model_params["sigma_smooth"]["prior"] = priors.TopHat(mini=150, maxi=250) # Now instantiate the model using this new dictionary of parameter specifications model = sedmodel.SedModel(model_params) return model
def time(self): return cosmo.age(self.z)
def load_model(objname, field, agelims=[], **extras): # REDSHIFT # open file, load data photname, zname, filtername, filts = get_names(field) with open(photname, 'r') as f: hdr = f.readline().split() dtype = np.dtype([(hdr[1], 'S20')] + [(n, np.float) for n in hdr[2:]]) dat = np.loadtxt(photname, comments='#', delimiter=' ', dtype=dtype) with open(zname, 'r') as fz: hdr_z = fz.readline().split() dtype_z = np.dtype([(hdr_z[1], 'S20')] + [(n, np.float) for n in hdr_z[2:]]) zout = np.loadtxt(zname, comments='#', delimiter=' ', dtype=dtype_z) idx = dat['id'] == objname # creates array of True/False: True when dat[id] = objname # zred = zout['z_spec'][idx][0] # use z_spec # if zred == -99: # if z_spec doesn't exist # zred = zout['z_peak'][idx][0] # use z_phot zred = 3.5 print(zred, 'zred') # CALCULATE AGE OF THE UNIVERSE (TUNIV) AT REDSHIFT ZRED tuniv = WMAP9.age(zred).value print(tuniv, 'tuniv') n = [p['name'] for p in model_params] # model_params[n.index('tage')]['prior_args']['maxi'] = tuniv # NONPARAMETRIC SFH # NEW ''' agelims = [0.0, 8.0, 8.7, 9.0, (9.0 + (np.log10(tuniv*1e9) - 9.0)/3), (9.0 + 2 * (np.log10(tuniv*1e9) - 9.0)/3), np.log10(tuniv*1e9)] ''' agelims = [0.0, 7.7, 8.0, 9.0, (9.0 + (np.log10(tuniv*1e9) - 9.0)/3), (9.0 + 2 * (np.log10(tuniv*1e9) - 9.0)/3), np.log10(tuniv*1e9)] ncomp = len(agelims) - 1 agebins = np.array([agelims[:-1], agelims[1:]]) # why agelims[1:] instead of agelims[0:]? # print(agebins, 'grab these agebins') # INSERT REDSHIFT INTO MODEL PARAMETER DICTIONARY zind = n.index('zred') model_params[zind]['init'] = zred # model_params[n.index('tage')]['init'] = tuniv # set tage to the age of the Universe # set dust and metallicity to be the same dust and metallicity you find in the actual fits: get_out = '/home/jonathan/.conda/envs/snowflakes/lib/python2.7/site-packages/prospector/git/out/out_efico/' for plop in os.listdir(get_out): if plop.startswith(str(objname)) and plop.endswith(".h5"): # print(str(objname)) get = gmd.printer(get_out + plop) # [mass, dust, metal, gasmet] model_params[n.index('logmass')]['init'] = 9.9 # 9. # get[0] model_params[n.index('dust2')]['init'] = 0.3 # get[1] model_params[n.index('logzsol')]['init'] = -0.06 # -1.7 # get[2] model_params[n.index('gas_logz')]['init'] = get[3] # SET UP AGEBINS model_params[n.index('agebins')]['N'] = ncomp model_params[n.index('agebins')]['init'] = agebins.T # FRACTIONAL MASS INITIALIZATION # NEW # N-1 bins, last is set by x = 1 - np.sum(sfr_fraction) model_params[n.index('sfr_fraction')]['N'] = ncomp-1 model_params[n.index('sfr_fraction')]['prior_args'] = { 'maxi': np.full(ncomp-1, 1.0), 'mini': np.full(ncomp-1, 0.0), # NOTE: ncomp instead of ncomp-1 makes the prior take into # account the implicit Nth variable too } eelg_frac1 = 0.3 # mfrac in most recent bin eelg_frac2 = 0.05 # mfrac in second most recent bin sf_inits = np.zeros(ncomp-1)+(1.-(eelg_frac1 + eelg_frac2))/(ncomp-2.) sf_inits[0] = eelg_frac1 sf_inits[1] = eelg_frac2 # print(sf_inits, 'look at me!!!') model_params[n.index('sfr_fraction')]['init'] = sf_inits # np.zeros(ncomp-1)+1./ncomp model_params[n.index('sfr_fraction')]['init_disp'] = 0.02 # CREATE MODEL model = BurstyModel(model_params) print('model') # print(model_params) # print(model_params[n.index('sfr_fraction')]) return model
import numpy as np import matplotlib.pyplot as plt from astropy.cosmology import WMAP9 as cosmo import astropy.units as u from astropy.cosmology import Planck13, z_at_value import pandas as pd dataframe = pd.read_csv('glenna.csv') r_z = np.array(dataframe['redshift']) for n in range(len(r_z)): ##find age at z= whatever... age = cosmo.age(r_z[n]) # age13 = cosmo.age(13) #add 1 billion years newage = age + (1 * u.Gyr) ## convert newage (the age plus a billion years) back to redshift: newredshift = z_at_value(Planck13.age, newage) print(age) print(newredshift) redshiftdata = np.column_stack((r_z, age, newredshift)) np.savetxt('/Users/Olivia/Desktop/redshiftdata.csv', redshiftdata, fmt='%.11', delimiter=',', header='r_z, age, redshift')
def load_model(objname, field, agelims=[], **extras): # REDSHIFT # open file, load data photname, zname, fname, filtername, filts = get_names(field) with open(photname, 'r') as f: hdr = f.readline().split() dtype = np.dtype([(hdr[1], 'S20')] + [(n, np.float) for n in hdr[2:]]) dat = np.loadtxt(photname, comments='#', delimiter=' ', dtype=dtype) with open(zname, 'r') as fz: hdr_z = fz.readline().split() dtype_z = np.dtype([(hdr_z[1], 'S20')] + [(n, np.float) for n in hdr_z[2:]]) zout = np.loadtxt(zname, comments='#', delimiter=' ', dtype=dtype_z) idx = dat['id'] == objname # creates T/F array: True when dat[id] = objname zred = zout['z_spec'][idx][0] # use z_spec if zred == -99: # if z_spec doesn't exist zred = zout['z_peak'][idx][0] # use z_phot print(zred, 'zred') # NEW FOUT (MASS-METALLICITY) with open(fname, 'r') as ff: hdr_f = ff.readline().split() dtype_f = np.dtype([(hdr_f[1], 'S20')] + [(n, np.float) for n in hdr_f[2:]]) fout = np.loadtxt(fname, comments='#', delimiter=' ', dtype=dtype_f) idx_f = fout[ 'id'] == objname # creates T/F array: True when fout[id] = objname lmass = fout['lmass'][idx_f][0] print(lmass, 'lmass') # met = [-1.5, 0.5, -0.3] if lmass <= 9.7: met = [-1.0, 0.0, -0.6] elif 9.7 < lmass <= 10.0: met = [-0.9, 0.1, -0.4] elif 10.0 < lmass <= 10.3: met = [-0.8, 0.15, -0.2] elif lmass > 10.3: met = [-0.2, 0.3, 0.0] # CALCULATE AGE OF THE UNIVERSE (TUNIV) AT REDSHIFT ZRED tuniv = WMAP9.age(zred).value print(tuniv, 'tuniv') n = [p['name'] for p in model_params] # model_params[n.index('tage')]['prior_args']['maxi'] = tuniv # NEW FOUT MASS-METALLICITY model_params[n.index('logzsol')]['prior_args'] = { 'mini': met[0], 'maxi': met[1] } # {'mini': -0.8, 'maxi': 0.15} model_params[n.index('logzsol')]['init'] = met[2] # -0.25 # 4942_cosmos_noelgmet was run with met[2] = -0.4 # 4942_cosmos_noelg25 was run with met[2] = -0.25 # NONPARAMETRIC SFH agelims = [ 0.0, 8.48, 8.78, 8.95, (8.95 + (np.log10(tuniv * 1e9) - 8.95) / 3), (8.95 + 2 * (np.log10(tuniv * 1e9) - 8.95) / 3), np.log10(tuniv * 1e9) ] # 0, 300, 600, 900, three evenly spaced to tuniv ncomp = len(agelims) - 1 agebins = np.array([agelims[:-1], agelims[1:] ]) # why agelims[1:] instead of agelims[0:]? # INSERT REDSHIFT INTO MODEL PARAMETER DICTIONARY zind = n.index('zred') model_params[zind]['init'] = zred # SET UP AGEBINS model_params[n.index('agebins')]['N'] = ncomp model_params[n.index('agebins')]['init'] = agebins.T # FRACTIONAL MASS INITIALIZATION # NEW # N-1 bins, last is set by x = 1 - np.sum(sfr_fraction) model_params[n.index('sfr_fraction')]['N'] = ncomp - 1 model_params[n.index('sfr_fraction')]['prior_args'] = { 'maxi': np.full(ncomp - 1, 1.0), 'mini': np.full(ncomp - 1, 0.0), # NOTE: ncomp instead of ncomp-1 makes the prior take into # account the implicit Nth variable too } model_params[n.index('sfr_fraction')]['init'] = np.zeros(ncomp - 1) + 1. / ncomp model_params[n.index('sfr_fraction')]['init_disp'] = 0.02 # CREATE MODEL model = BurstyModel(model_params) return model
# lib_param[key] = guess[key] # print lib_param # # spec = lib.get_model_spectrum(0)[0] # # plt.clf() # cut = np.bitwise_and(spec['wl'] > 3000, spec['wl'] < 9000) # plt.plot(spec['wl'][cut], spec['flux'][cut]) # # raw_input('next...') f = FilterSet('/Users/william/doutorado/photo_filters/Alhambra_24.hdf5') f.load('Alhambra_24', 1) n_filters = len(f.filter_wls) aux_base = StarlightBase(base_file, base_path) base_maxage = np.max(aux_base.ageBase) min_z_age = cosmo.age(0.001).to('yr').value if base_maxage > min_z_age: base_maxage = min_z_age allow_overwrite_bpz = True allow_overwrite_lib = True bpz_lib_file = '/Users/william/tmp_out/pzT_parametric_noelines.hdf5' parametric_lib = '/Users/william/tmp_out/zT_weights_noelines.hdf5' if allow_overwrite_bpz: try: os.unlink(bpz_lib_file) except OSError: pass if allow_overwrite_lib: try:
def load_model(objname='', datname='', zname='', agelims=[], **extras): ###### REDSHIFT ###### ### open file, load data with open(datname, 'r') as f: hdr = f.readline().split() dtype = np.dtype([(hdr[1], 'S20')] + [(n, np.float) for n in hdr[2:]]) dat = np.loadtxt(datname, comments='#', delimiter=' ', dtype=dtype) with open(zname, 'r') as fz: hdr_z = fz.readline().split() dtype_z = np.dtype([(hdr_z[1], 'S20')] + [(n, np.float) for n in hdr_z[2:]]) zout = np.loadtxt(zname, comments='#', delimiter=' ', dtype=dtype_z) idx = dat['id'] == objname zred = zout['z_spec'][idx][0] # use z_spec if zred == -99: # if z_spec doesn't exist zred = zout['z_peak'][idx][0] # use z_phot print(zred, 'zred') #### CALCULATE TUNIV ##### tuniv = WMAP9.age(zred).value print(tuniv, 'tuniv') n = [p['name'] for p in model_params] model_params[n.index('tage')]['prior_args']['maxi'] = tuniv #### NONPARAMETRIC SFH ###### # NEW # agelims[-1] = np.log10(tuniv*1e9) ncomp = len(agelims) - 1 agelims = [ 0.0, 7.0, 8.0, (8.0 + (np.log10(tuniv * 1e9) - 8.0) / 4), (8.0 + 2 * (np.log10(tuniv * 1e9) - 8.0) / 4), (8.0 + 3 * (np.log10(tuniv * 1e9) - 8.0) / 4), np.log10(tuniv * 1e9) ] agebins = np.array([agelims[:-1], agelims[1:]]) # agelims[1:] or agelims[0:]? # calculate the somethings: [0, a, b, b + (f-b)/4, b + 2*(f-b)/4, b + 3*(f-b)/4, b + 4*(f-b)/4 = f] #### INSERT REDSHIFT INTO MODEL PARAMETER DICTIONARY #### zind = n.index('zred') model_params[zind]['init'] = zred #### SET UP AGEBINS model_params[n.index('agebins')]['N'] = ncomp model_params[n.index('agebins')]['init'] = agebins.T #### FRACTIONAL MASS INITIALIZATION # NEW # BUCKET2: don't want all 5 bins equal for quickstart (also try 4 bins) # N-1 bins, last is set by x = 1 - np.sum(sfr_fraction) model_params[n.index('sfr_fraction')]['N'] = ncomp - 1 model_params[n.index('sfr_fraction')]['prior_args'] = { 'maxi': np.full(ncomp - 1, 1.0), 'mini': np.full(ncomp - 1, 0.0), # NOTE: ncomp instead of ncomp-1 makes the prior take into # account the implicit Nth variable too } # use 5 bins (6th is implicit, so sum over the 5 bins = 1 - 6th bin) model_params[n.index('sfr_fraction')]['init'] = np.array( [0.7, 0.2, 0.05, 0.03, 0.01]) # np.zeros(ncomp-1)+1./ncomp model_params[n.index('sfr_fraction')]['init_disp'] = 0.02 #### CREATE MODEL model = BurstyModel(model_params) return model
def fit_one_SED(gal_ID,base_dust_curve,filters,bpass_folder,photometry,EBVres=0.0025,Rv=2.74,maxage=5e8): # Determine which ages to use based on age of the universe at z=redshift redshift = photometry.data[str(gal_ID)]['redshift'] ages = 10.**(np.array([6. + 0.1*_i for _i in range(51)])) cage = cosmo.age(redshift).to_value(units.year) tage = np.where(cage-maxage > ages)[0] nages = len(tage) # BPASS SPECTRA FILE NAMES/LOCATIONS bpass_spectra = glob.glob(f'{bpass_folder}/spectra*.gz') # CREATE EBV AND AGE ARRAYS EBVs = np.arange(0.,0.2,EBVres) ages = np.arange(0,nages,1).astype(int)+1 # SETTING BOUNDS ON RETURNED MASSES FOR OUTPUT MODEL, # PREVENTS NEGATIVE MASS MODELS BEING INCLUDED bnd = [0.,1.e13] bounds = [] for i in range(33): bounds.append(tuple(bnd)) bounds = tuple(bounds) # DETERMINE WHICH FILTERS ARE IN USE AND SET UP PHOTOMETRY FOR FITTING fit_filters = photometry.get_fit_filters(gal_ID,filters) wav = filter_wavs(filters,fit_filters) flux,error = fit_photometry(photometry.data[str(gal_ID)]['phot'],fit_filters) grid,tft = bpt.make_grid(bpass_spectra[0],filters,fit_filters,redshift) alosses = np.zeros(len(bpass_spectra)) aopts = np.zeros((len(bpass_spectra),grid.shape[0])) aEBVs = np.zeros(len(bpass_spectra)) for j,bps in enumerate(bpass_spectra): grid,tft = bpt.make_grid(bps,filters,fit_filters,redshift) tFit = list(set(tft)) theta = np.zeros(grid.shape[0])*1.e8 losses = np.copy(EBVs)*0. topts = np.empty((len(EBVs),len(theta))) for i,EBV in enumerate(EBVs): dust_grid = dm.add_grid(wav,grid,base_dust_curve.wav,base_dust_curve.base_curve,EBV,redshift,Rv=Rv) Res = opt.minimize(fun = lrm.cost, x0 = theta, args = (dust_grid[:,tFit],flux[tFit],error[tFit]), method = 'TNC', jac = lrm.grad, bounds = bounds ) theta_opt = Res.x SED_opt = lrm.h(theta_opt,dust_grid) topts[i,:] = theta_opt losses[i] = lrm.SED_loss(SED_opt,flux[tFit],error[tFit]) tbest = np.where(losses == np.min(losses))[0] tEBV = EBVs[tbest] tOPT = topts[tbest][0,:] alosses[j] = losses[tbest] aopts[j] = tOPT aEBVs[j] = tEBV abest = np.where(alosses == np.min(alosses))[0][0] EBV_out = aEBVs[abest] OPT_out = aopts[abest] swav,out_spec = bpt.out_spec(OPT_out, bpass_spectra[abest], redshift, base_dust_curve.wav, base_dust_curve.base_curve, EBV_out ) bpf,tf2 = bpt.BPASS_phot(swav,out_spec,fit_filters,filters,redshift) return {'wav':swav, 'spec':out_spec, 'BPASS_mod':bpass_spectra[abest], 'theta_opt':OPT_out, 'EBV':EBV_out, 'attenuation_curve':np.exp((-1.)*(np.interp(swav,base_dust_curve.wav,base_dust_curve.base_curve)*EBV_out*Rv/1.086)), 'z':redshift, 'obs_phot':{ 'wav':wav/(1.+redshift), 'flx':flux, 'err':error, 'fit':tFit } }