def eval_matrix(config, n_taylor=10): filters, filter_lambdas = load_filters(config) print 'Calculating Taylor coefficients matrix for n_taylor = %i.' % n_taylor bt = StarlightBase(config['base_file'], config['base_path']) z = np.arange(config['z_ini'], config['z_fin'] + config['z_delta'], config['z_delta']) m, a, f = taylor_matrix_ssp(config['taylor_file'], bt, n_taylor, z, filters) config['filters'] = ','.join(sorted(config['filters'].keys())) f.attrs.update(config) f.close()
def test_matrix_time(): print 'Test time to calculate all the matrix over a range of redshifts of (0, 7, 0.001)' bt = StarlightBase( '/Users/william/BasesDir/Base.bc03.Padova1994.chab.All.hdf5', 'Base.bc03.Padova1994.chab.All') z = np.arange(0.001, 1, 0.001) for n_taylor in range(1, 10): t0 = time.time() aux_fname = '/Users/william/tmp_out/m_av.hdf5' os.unlink(aux_fname) m, a, f = taylor_matrix_ssp(aux_fname, bt, n_taylor, z, filters) print 'n_taylor, t:', n_taylor, time.time() - t0 f.close()
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 __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
file_fit = h5py.File('%s/%s' % (save_dir, config['fit_bpz_outfile']), 'r') # Doing this copy due bug: https://github.com/h5py/h5py/issues/480 params = np.copy(file_fit.get('/model_parameters').value) n_z, n_t, n_models, n_parameters = params.shape file_fit_processed = h5py.File('%s/%s' % (save_dir, config['fit_bpz_post']), 'w') post_parameters_data = np.empty( dtype=np.dtype([('at_mass', np.float), ('at_flux', np.float), ('metallicity', np.float), ('a_v', np.float), ('m2l', np.float)]), shape=(n_z, n_t, n_models)) # m2l_spec = np.zeros((n_z, n_t, n_models, len(config["m2l_lambdas"]))) bt = StarlightBase(config['base_file'], config['base_path']) bt.ageBase[bt.ageBase == 0] = 1e5 # Avoid NaN on log10(age) i_norm = np.argmin((bt.l_ssp - config['lambda_norm']) ** 2) # i_met = int(np.argwhere(bt.metBase == metallicity)) l2m_norm_ssp = np.empty((len(bt.metBase), len(bt.ageBase))) for i_met in range(len(bt.metBase)): for i_age in range(len(bt.ageBase)): l2m_norm_ssp[i_met, i_age] = bt.f_ssp[i_met, i_age, i_norm] # from pystarlight, eval l2m on filter filter_m2l = readfilterfile(config['filter_m2l'], ).data aux_l = np.arange(filter_m2l['lambda'].min(), filter_m2l['lambda'].max()) filter_m2l_new = np.empty(len(aux_l), dtype=filter_m2l.dtype) filter_m2l_new['lambda'] = aux_l filter_m2l_new['transm'] = np.interp(aux_l, filter_m2l['lambda'], filter_m2l['transm']) filter_m2l = filter_m2l_new
# For the A_V Arrow: e_c1 = Cardelli_RedLaw([4580])[0] - Cardelli_RedLaw([7680])[0] e_c2 = Cardelli_RedLaw([3650])[0] - Cardelli_RedLaw([6440])[0] # M/L calculations ## Filter filter_m2l = readfilterfile(config['filter_m2l'], norm=False).data aux_l = np.arange(filter_m2l['lambda'].min(), filter_m2l['lambda'].max()) filter_m2l_new = np.empty(len(aux_l), dtype=filter_m2l.dtype) filter_m2l_new['lambda'] = aux_l filter_m2l_new['transm'] = np.interp(aux_l, filter_m2l['lambda'], filter_m2l['transm']) filter_m2l = filter_m2l_new LsunFilter = calc_LsunFilter(filter_m2l) ## Base bt = StarlightBase(config['base_file'], config['base_path']) m2l_ssp = np.empty((len(bt.metBase), len(bt.ageBase))) i_norm = np.argmin((bt.l_ssp - config['lambda_norm']) ** 2) l2m_norm_ssp = np.empty((len(bt.metBase), len(bt.ageBase))) for i_met in range(len(bt.metBase)): for i_age in range(len(bt.ageBase)): aux = np.interp(filter_m2l['lambda'], bt.l_ssp, bt.f_ssp[i_met, i_age]) m2l_ssp[i_met, i_age] = bt.Mstars[i_met, i_age] * LsunFilter / np.trapz(aux * filter_m2l['transm'], filter_m2l['lambda']) l2m_norm_ssp[i_met, i_age] = bt.f_ssp[i_met, i_age, i_norm] # Open BPZ magnitudes templates = np.loadtxt(config['bpz_library'], np.str) aux = templates[:, 0] if len(templates.shape) > 1 else templates templates_data = [ np.loadtxt('%s/%s' % (config['bpz_library_dir'], t), dtype=np.dtype([('lambda', np.float), ('flux', np.float)]))
# guess = lib_guess() # for key in guess.keys(): # 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
################################################################################ ################################################################################ ########## ########## Population model setup ########## ################################################################################ logger.setLevel(-1) args = parse_args() logger.info("Loading base %s", path.basename(args.baseFile)) t1 = time.clock() base = StarlightBase(args.baseFile, args.baseDir) l_ssp = np.arange(3650.0, 6850.0, 2.0) f_ssp = base.f_sspResam(l_ssp) logger.info("Took %.2f seconds to read the base (%d files)" % (time.clock() - t1, base.sspfile.size)) wl_norm_window = (l_ssp < 5680.0) & (l_ssp > 5590.0) ################################################################################ ########## ########## Morphology model setup ########## ################################################################################ logger.info("Creating original B-D model.") norm_model = get_model(args.trueModel, with_default=True) norm_params = np.array(norm_model.getParams(), dtype=norm_model.dtype) logger.info("Original model at normalization window:\n%s\n" % str(norm_model))
norm_h = norm_model.disk.h.value plt.suptitle(r'Modelo original (sem convoluir com PSF)') gs.tight_layout(fig, rect=[0, 0, 1, 0.95]) plt.savefig('plots/tese/simulation_initmodel.pdf') ################################################################################ ########## ########## Plot original population model ########## ################################################################################ logger.debug('Plotting original population model.') #index_norm = find_nearest_index(l_ssp, 5635.0) logger.info('Loading base %s', path.basename(args.baseFile)) t1 = time.clock() base = StarlightBase(args.baseFile, args.baseDir) wl = np.arange(3650.0, 6850.0, 2.0) f_ssp = base.f_sspResam(wl) logger.info('Took %.2f seconds to read the base (%d files)' % (time.clock() - t1, base.sspfile.size)) wl_norm_window = (wl < 5680.0) & (wl > 5590.0) t0 = base.ageBase.max() r = np.arange(30) tau = tau_r(args.tau0, args.dtau_dr, r) print tau bulge_sfh_tau0 = get_synth_sfh(t0, args.tau0, base.ageBase) bulge_sfh_tau1 = get_synth_sfh(t0, 4e9, base.ageBase) bulge_sfh_tau2 = get_synth_sfh(t0, 8e9, base.ageBase) disk_sfh_tauInf = get_synth_sfh(t0, 1e12, base.ageBase)
def main_CSP(argv): from pystarlight.util.base import StarlightBase from pystarlight.util.redenninglaws import calc_redlaw base_select = 'Padova2000.salp' base_file = '/Users/lacerda/LOCAL/data/Base.bc03.h5' base = StarlightBase(base_file, base_select, hdf5=True) M = 1e10 tauV = np.linspace(0, 1, 10) t0 = np.linspace(0, 20e9, 11) tau = np.logspace(9, 11, 12) q = calc_redlaw(base.l_ssp, R_V=3.1, redlaw='CCM') t = base.ageBase.max() - base.ageBase[::-1] steps = (t[1:] - t[:-1]) / 2.0 t_edges = np.empty((len(t) + 1)) t_edges[1:-1] = t[1:] - steps t_edges[0] = t[0] - steps[0] if t_edges[0] < 0: t_edges[0] = 0. t_edges[-1] = t[-1] + steps[-1] if t_edges[-1] > t[-1]: t_edges[-1] = t[-1] # shape_model = (len(t0), len(tau), len(tauV)) M__t0tautauVl = np.ndarray((len(t0), len(tau), len(tauV), len(base.l_ssp)), dtype='float') dM__t0taut = np.ndarray((len(t0), len(tau), base.nAges), dtype='float') for it0, _t0 in enumerate(t0): for itau, _tau in enumerate(tau): dM = [] for i in range(len(t)): l, r = t_edges[i], t_edges[i + 1] dM.append(deltaM_integral(M, t.max(), _t0, _tau, l, r)) # print 't0:', _t0,' tau:', _tau, ' dM:', dM[-1] dM = np.array(dM) dM__t0taut[it0, itau, :] = dM for itauV, _tV in enumerate(tauV): norm_lambda = 5635.0 spec_window = np.bitwise_and( np.greater(base.l_ssp, norm_lambda - 45.0), np.less(base.l_ssp, norm_lambda + 45.0)) # spec_window = (base.l_ssp > norm_lambda - 45.0) & (base.l_ssp < norm_lambda + 45.0) spec = np.tensordot( base.f_ssp.sum(axis=0) * np.exp(_tV * q), dM[::-1], (0, 0)) spec_norm = np.median(spec[spec_window]) M__t0tautauVl[it0, itau, itauV, :] = spec / spec_norm # Save FITS from astropy.io import fits hdu = fits.HDUList() header = fits.Header() header['NL'] = len(base.l_ssp) header['NBURSTINI'] = len(t0) header['NBURSTLENGTH'] = len(tau) header['NTAUV'] = len(tauV) hdu.append(fits.PrimaryHDU(header=header)) hdu.append(fits.ImageHDU(data=t, name='ages')) hdu.append(fits.ImageHDU(data=t_edges, name='ages_edges')) hdu.append(fits.ImageHDU(data=t0, name='burst_ini')) hdu.append(fits.ImageHDU(data=tau, name='burst_length')) hdu.append(fits.ImageHDU(data=tauV, name='tau_V')) tmp = fits.ImageHDU(data=dM__t0taut, name='dM') tmp.header['COMMENT'] = 'Dimension [BURSTINI,BURSTLENGTH,AGES]' hdu.append(tmp) tmp = fits.ImageHDU(data=M__t0tautauVl, name='F_CSP') tmp.header['COMMENT'] = 'Dimension [BURSTINI,BURSTLENGTH,TAUV,LAMBDA]' hdu.append(tmp) hdu.append(fits.ImageHDU(data=base.l_ssp, name='L_CSP')) hdu.writeto('CSPModels.fits')