def calc_sfr(nsample=40000): ### setup SPS run_params = model_setup.get_run_params(param_file=param_file) sps = model_setup.load_sps(**run_params) model = model_setup.load_model(**run_params) obs = return_fake_obs({}) nbins = model.params['sfr_fraction'].shape[0] #### create chain to sample from flatchain = np.random.dirichlet(tuple(1.0 for x in xrange(6)),nsample) flatchain = flatchain[:,:-1] ### define time array for SFHs in_years = 10**model.params['agebins']/1e9 t = in_years.sum(axis=1)/2. ### output bins sfr = np.zeros(shape=(t.shape[0],nsample)) #### sample the posterior for jj in xrange(nsample): if jj % 100 == 0: print float(jj)/nsample ##### model call, to set parameters thetas = flatchain[jj,:] _,_,sm = model.mean_model(thetas, obs, sps=sps) ##### extract sfh parameters # pass stellar mass to avoid extra model call sfh_params = prosp_dutils.find_sfh_params(model,thetas, obs,sps,sm=sm) #### SFR sfr[:,jj] = prosp_dutils.return_full_sfh(t, sfh_params,minsfr=-np.inf) out = {} out['sfr'] = sfr out['flatchain'] = flatchain[:nsample,:] out['model'] = model return out
def cloudy_spectrum(ax): from prospect.models import model_setup param_file = '/Users/joel/code/python/prospector_alpha/parameter_files/brownseds_np/brownseds_np_params.py' run_params = model_setup.get_run_params(param_file=param_file) sps = model_setup.load_sps(**run_params) model = model_setup.load_model(**run_params) model.params['dust2'] = np.array(0.0) obs = model_setup.load_obs(**run_params) spec,_,_ = model.mean_model(model.initial_theta, obs, sps=sps) model.params['add_neb_emission'] = np.array(False) model.params['add_neb_continuum'] = np.array(False) spec_neboff,_,_ = model.mean_model(model.initial_theta, obs, sps=sps) spec_neb = (spec-spec_neboff)*3e18/sps.wavelengths**2 in_plot = (sps.wavelengths/1e4 > 6) & (sps.wavelengths/1e4 < 30) spec_neb_smooth = smooth_spectrum(sps.wavelengths[in_plot], spec_neb[in_plot], 3500) spec_neb_smooth *= 1e5 / spec_neb_smooth.max() ''' neb_color = '0.7' alpha = 0.7 ax.fill_between(sps.wavelengths[in_plot]/1e4, np.zeros_like(spec_neb_smooth), spec_neb_smooth, color=neb_color, alpha=alpha) ### label H2 + [ArII] (second is in cloudy but very small) ax.fill_between([9.55,9.85],[0,0],[1,1],color=neb_color,alpha=alpha) ax.fill_between([6.8,7.1],[0,0],[1,1],color=neb_color,alpha=alpha) ''' lines = ['[ArII]',r'H$_2$','[SIV]','[NeIII]','[SIII]'] lam = [6.95,9.7,10.45,15.5,18.7] # removed because they're too weak, just distracting #lines = ['[ArIII]','[NeII]'] #lam = [9.0,12.8] for ii in xrange(len(lines)): ax.text(lam[ii]*1.008,0.14,lines[ii], ha='left',fontsize=9.5) for ii in xrange(len(lam)): ax.plot([lam[ii],lam[ii]],[0,1e5],linestyle='--',lw=1.5,color='k')
import numpy as np import matplotlib.pyplot as plt import spot_utils as pread from prospect.io.read_results import results_from from prospect.models import model_setup paramfile = 'ad_params.py' clargs = {'param_file': paramfile} run_params = model_setup.get_run_params(argv=paramfile, **clargs) print(run_params) obs = model_setup.load_obs(**run_params) sps = model_setup.load_sps(**run_params) model = model_setup.load_model(**run_params) wspec = sps.csp.wavelengths # *restframe* spectral wavelengths a = 1.0 + model.params.get('zred', 0.6) # cosmological redshifting wphot = np.array([f.wave_effective for f in obs['filters']]) # In [21] # grab results, powell results, and our corresponding models #res, pr, mod = results_from("{}_mcmc.h5".format(outroot)) res, pr, mod = results_from("demo_galphot_1508433060_mcmc.h5") # In [22] # To see how our MCMC samples look, we can examine a few traces choice = np.random.choice tracefig = pread.param_evol(res, figsize=(20, 10), chains=choice(128, size=10, replace=False))
def compare_sed(): ### custom parameter file ### where mass is a six-parameter thing param_file = 'brownseds_np_params.py' run_params = model_setup.get_run_params(param_file=param_file) sps = model_setup.load_sps(**run_params) model = model_setup.load_model(**run_params) obs = model_setup.load_obs(**run_params) thetas = model.initial_theta ### create star formation history and metallicity history mformed = 1e10 m_constant = return_declining_sfh(model,mformed, tau=1e12) met = return_zt(model) #met = np.ones_like(met) thetas[model.theta_labels().index('logzsol')] = 0.0 ### simple i1, i2 = model.theta_index['mass'] thetas[i1:i2] = m_constant nsamp = 21 met_comp = np.linspace(-1,0,nsamp) spec, phot = [], [] for m in met_comp: thetas[model.theta_labels().index('logzsol')] = m specx, photx, x = model.mean_model(thetas, obs, sps=sps) spec.append(specx) phot.append(photx) ### complex for i in xrange(met.shape[0]): # zero out all masses thetas[i1:i2] = np.zeros_like(m_constant) # fill in masses and metallicities thetas[model.theta_labels().index('logzsol')] = np.log10(met[i]) thetas[i1+i] = m_constant[i] # generate spectrum, add to existing spectrum sps.ssp.params.dirtiness = 1 specx, photx, x = model.mean_model(thetas, obs, sps=sps) if i == 0: spec_agez, phot_agez = specx, photx else: spec_agez += specx phot_agez += photx ### plot fig, ax = plt.subplots(1,1, figsize=(8, 7)) cmap = get_cmap(nsamp) for i in xrange(0,nsamp,4): ax.plot(sps.wavelengths/1e4, np.log10(spec[i] / spec_agez),color=cmap(i), label=met_comp[i]) ax.axhline(0, linestyle='--', color='0.1') ax.legend(loc=4,prop={'size':20},title=r'log(Z/Z$_{\odot}$) [fixed]') ax.set_xlim(0.1,10) ax.set_xscale('log',nonposx='clip',subsx=(2,5)) ax.xaxis.set_minor_formatter(minorFormatter) ax.xaxis.set_major_formatter(majorFormatter) ax.set_ylabel(r'log(f$_{\mathrm{Z}_{\mathrm{fixed}}}$ / f$_{\mathrm{Z(t)}}$)') ax.set_xlabel('wavelength [microns]') ax.set_ylim(-0.4,0.4) plt.tight_layout() plt.show() print 1/0
mpl.rc('text', usetex=True) mpl.rcParams['text.latex.preamble']=[r"\usepackage{bm}"] mpl.rcParams.update({'font.size': 30}) sfhsize = 40 #### parameter plot style colors = ['blue', 'black', 'red'] alpha = 0.8 lw = 3 #### define model param_file='/Users/joel/code/python/prospector_alpha/parameter_files/brownseds_np/brownseds_np_params.py' run_params = model_setup.get_run_params(param_file=param_file) sps = model_setup.load_sps(**run_params) model = model_setup.load_model(**run_params) obs = model_setup.load_obs(**run_params) #### output locations out1 = '/Users/joel/code/python/prospector_alpha/plots/brownseds_np/pcomp/model_diagram1.png' out2 = '/Users/joel/code/python/prospector_alpha/plots/brownseds_np/pcomp/model_diagram2.png' #### set initial theta # 'logmass','sfr_fraction_1', sfr_fraction_2, # sfr_fraction_3, sfr_fraction_4, 'sfr_fraction_5', # dust2', 'logzsol', 'dust_index', # 'dust1', 'duste_qpah', 'duste_gamma', # 'duste_umin' labels = model.theta_labels() itheta = np.array([10, 0.02, 0.1,
def return_dat(runname, runname_comp, pltcorner=False, pltchain=False): #filebase, pfile, ancilname = generate_basenames(runname) #filebase2, pfile2, ancilname2 = generate_basenames(runname_comp) size = 500000 filebase = ['/Users/joel/code/python/prospector_alpha/results/guillermo_nestle/guillermo_nestle'] pfile = ['/Users/joel/code/python/prospector_alpha/parameter_files/guillermo_nestle/guillermo_nestle_params.py'] filebase2 = ['/Users/joel/code/python/prospector_alpha/results/guillermo/guillermo'] pfile2 = ['/Users/joel/code/python/prospector_alpha/parameter_files/guillermo/guillermo_params.py'] #bad = ['NGC 0584','UGCA 166','Mrk 1450','UM 461','UGC 06850','NGC 4125','NGC 4551','Mrk 0475'] objname, hinformation, logz, logzerr, dlogz, ncall = [], [], [], [], [], [] for i, file in enumerate(filebase): sresults, _, model, _ = load_prospector_data(file,load_extra_output=False) ### some of the nestle runs terminated due to time limit ### must regenerate the models if model is None: run_params = model_setup.get_run_params(param_file=pfile) run_params['objname'] = file.split('_')[-1] model = model_setup.load_model(**run_params) sresults_mcmc, _, model_mcmc, _ = load_prospector_data(filebase2[i],load_extra_output=False) flatchain = chop_chain(sresults_mcmc['chain'],**sresults_mcmc['run_params']) flatchain, pnames_emcee = transform_chain(flatchain, model_mcmc) ### save some stuff # logz_est.append(sresults['logvol'][sresults['lnprobability'].argmax()]+np.log10(np.exp(sresults['lnprobability'].max())) npoints = sresults['run_params']['nestle_npoints'] logz_remain = np.max(sresults['lnprobability']) - (sresults['chain'].shape[0]/1000.) dlogz.append(np.logaddexp(sresults['logz'], logz_remain) - sresults['logz']) ncall.append(sresults['ncall']) hinformation.append(sresults['h_information'][0]) logz.append(sresults['logz'][0]) logzerr.append(sresults['logzerr'][0]) sresults['dlogz'] = dlogz[-1] ### define output containers if len(objname) == 0: parnames = model.theta_labels() mcmc, nestle = {}, {} percs = ['q50','q84','q16','q2.5','q97.5',] for dic in [mcmc, nestle]: for par in parnames: dic[par] = {} for p in percs: dic[par][p] = [] dic['maxlnprob'] = [] ### corner plot? outname = file.split('results')[0]+'plots/'+runname+'/'+file.split('_')[-1] if pltcorner: # outname = outname+'.corner.png' range = [tuple(np.percentile(flatchain[:,i],[1,99]).tolist()) for i in xrange(flatchain.shape[1])] range = None fig, nestle_pnames = ncorner(sresults, model, range=range) ecorner(sresults_mcmc, flatchain, fig, pnames_emcee, outname+'.corner.png',n_pnames = nestle_pnames, range=range) if pltchain: plot_chain(sresults, parnames, outname+'.chain.png') ### load all data for i,par in enumerate(parnames): p1 = np.random.choice(sresults['chain'][:,i],size=size, p=sresults['weights']) p2 = flatchain[:,i] for dic, chain in zip([nestle,mcmc],[p1,p2]): for q in dic[par].keys(): dic[par][q].append(np.percentile(chain, [float(q[1:])])[0]) nestle['maxlnprob'].append(sresults['lnprobability'].max()) mcmc['maxlnprob'].append(sresults_mcmc['lnprobability'].max()) objname.append(sresults['run_params'].get('objname','galaxy')) print 1/0 dat = {'nestle': nestle, 'emcee': mcmc} dat['labels'] = model.theta_labels() dat['objname'] = objname nestle_pars = { 'hinformation': hinformation, 'logz': logz, 'logzerr': logzerr, 'dlogz': dlogz, 'ncall': ncall } dat['nestle_pars'] = nestle_pars return dat