Exemplo n.º 1
0
def extract_posteriors():

    logMs, logZs, dusts, t0s, logTaus = [], [], [], [], []
    clusters = ['a370', 'a1063', 'a2744', 'm416', 'm717', 'm1149']
    for cluster in clusters:

        h5_files = glob.glob('{}/h5/*.h5'.format(cluster))

        h5s = []
        for file in h5_files:
            file = file.replace(os.sep, '/')  # compatibility for Windows
            h5s.append(file)

        for file in h5s:
            result, obs, _ = reader.results_from(file, dangerous=True)

            samples = sample_posterior(result['chain'],
                                       weights=result['weights'],
                                       nsample=len(result['chain']))

            samples[:, 1] = np.log10(samples[:, 1])
            samples[:, 5] = np.log10(samples[:, 5])

            logMs.append(list(samples[:, 1]))
            logZs.append(list(samples[:, 2]))
            dusts.append(list(samples[:, 3]))
            t0s.append(list(samples[:, 4]))
            logTaus.append(list(samples[:, 5]))

    logM = flatten_posteriors(logMs)
    logZ = flatten_posteriors(logZs)
    dust = flatten_posteriors(dusts)
    t0 = flatten_posteriors(t0s)
    logTau = flatten_posteriors(logTaus)

    # np.savez('subsample_posteriors.npz', logM=logM, logZ=logZ, dust=dust,
    #          t0=t0, logTau=tau)

    solMetal = u.def_unit(['solMetal', 'Z_sun', 'Zsun'],
                          prefixes=False,
                          format={
                              'latex': r'Z_{\odot}',
                              'unicode': 'Z\N{SUN}'
                          })

    table = Table(
        [logM / u.solMass, logZ / solMetal, dust, t0 * u.Gyr, logTau / u.Gyr],
        names=('logM', 'logZ', 'dust', 't0', 'logTau'))
    table.write('boneyard/subsample_posteriors.fits')

    return
Exemplo n.º 2
0
def determine_age_gradients(cluster, ID, bins, radius_array, version='') :
    
    mwas = []
    radii = []
    for binNum, radius in zip(bins, radius_array) :
        infile = '{}/h5/{}_ID_{}_bin_{}{}.h5'.format(
            cluster, cluster, ID, binNum, version)
        result, obs, _ = reader.results_from(infile, dangerous=True)
        
        samples = sample_posterior(result['chain'], weights=result['weights'])
        
        mwas.append(mwa_calc(samples[:, 5], samples[:, 4], power=1))
        
        radii.append(np.full(len(samples), radius))
    
    return np.concatenate(radii).ravel(), np.concatenate(mwas).ravel()
Exemplo n.º 3
0
def save_mass_metallicity_images():

    HFF = Table.read('output/tables/nbCGs.fits')

    for cluster, ID in zip(HFF['cluster'], HFF['ID']):
        # ensure the output directories for the images are available
        os.makedirs('{}/logM_images'.format(cluster), exist_ok=True)
        os.makedirs('{}/logZ_images'.format(cluster), exist_ok=True)

        bins_image = core.open_image(cluster, ID, 'bins')
        bins = np.sort(np.unique(
            bins_image[~np.isnan(bins_image)])).astype(int)

        mass = bins_image.copy()
        metal = bins_image.copy()

        if not (cluster == 'm717') & (ID == 3692):  # fitting issue for bin_4
            for binNum in bins:  # loop over all the bins
                result, obs, _ = reader.results_from(
                    '{}/h5/{}_ID_{}_bin_{}.h5'.format(cluster, cluster, ID,
                                                      binNum),
                    dangerous=True)
                samples = sample_posterior(result['chain'],
                                           weights=result['weights'])

                mass[mass == binNum] = np.percentile(samples[:, 1], 50)
                metal[metal == binNum] = np.percentile(samples[:, 2], 50)

            hdu = fits.PrimaryHDU(mass)
            hdu.writeto('{}/logM_images/{}_ID_{}_logM.fits'.format(
                cluster, cluster, ID))

            hdu = fits.PrimaryHDU(metal)
            hdu.writeto('{}/logZ_images/{}_ID_{}_logZ.fits'.format(
                cluster, cluster, ID))

    return
Exemplo n.º 4
0
#sys.exit(0)

results_type = 'dynesty'

result, obs, _ = reader.results_from(adap_dir + results_type + "_" + \
                 field + "_" + str(galaxy_seq) + ".h5", dangerous=False)

parnames = np.array(result['theta_labels'])
print('Parameters in this model:', parnames)


# ------------------
from prospect.plotting.utils import sample_posterior

wts = result.get("weights", None)
theta = sample_posterior(result["chain"], weights=wts, nsample=nsamp)

"""
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)

ax1.set_xlabel(r'$\mathrm{Time\, [Gyr]}$', fontsize=13)
ax1.set_ylabel(r'$\mathrm{SFR\, [M_\odot/yr]}$', fontsize=13)

t = np.arange(0.0, 14.0, 0.001)

tau_arr = theta[:, -1]

mid_tau = np.mean(tau_arr)
min_tau = np.min(tau_arr)
max_tau = np.max(tau_arr)
Exemplo n.º 5
0
def determine_lines(cluster, ID, bins, best=False, version='') :
    
    metals_16, metals_50, metals_84 = [], [], []
    dusts_16, dusts_50, dusts_84 = [], [], []
    mwas_16, mwas_50, mwas_84 = [], [], []
    
    metals_best, dusts_best, mwas_best = [], [], []
    
    for binNum in bins : # loop over all the bins in the table
        infile = '{}/h5/{}_ID_{}_bin_{}{}.h5'.format(
            cluster, cluster, ID, binNum, version)
        result, obs, _ = reader.results_from(infile, dangerous=True)
        
        zred, mass, logzsol, dust2, tage, tau = result['bestfit']['parameter']
        
        dusts_best.append(dust2)            
        metals_best.append(logzsol)
        mwas_best.append(mwa_calc(tau, tage, power=1))
        
        # now pull samples to compute 1sigma errors
        samples = sample_posterior(result['chain'],
                                   weights=result['weights'])
        
        metal_16, metal_50, metal_84 = np.percentile(samples[:, 2],
                                                     [16, 50, 84])
        metals_16.append(metal_16)
        metals_50.append(metal_50)
        metals_84.append(metal_84)
        
        dust_16, dust_50, dust_84 = np.percentile(samples[:, 3],
                                                  [16, 50, 84])
        dusts_16.append(dust_16)
        dusts_50.append(dust_50)
        dusts_84.append(dust_84)
        
        mwa_16, mwa_50, mwa_84 = np.percentile(mwa_calc(samples[:, 5],
                                                        samples[:, 4],
                                                        power=1),
                                               [16, 50, 84])
        mwas_16.append(mwa_16)
        mwas_50.append(mwa_50)
        mwas_84.append(mwa_84)
    
    metal_lo = np.abs(np.array(metals_50) - np.array(metals_16))
    metal_hi = np.abs(np.array(metals_84) - np.array(metals_50))
    
    dust_lo = np.abs(np.array(dusts_50) - np.array(dusts_16))
    dust_hi = np.abs(np.array(dusts_84) - np.array(dusts_50))
    
    mwa_lo = np.abs(np.array(mwas_50) - np.array(mwas_16))
    mwa_hi = np.abs(np.array(mwas_84) - np.array(mwas_50))
    
    metal_median = np.array(metals_50)
    dust_median = np.array(dusts_50)
    mwa_median = np.array(mwas_50)
    
    metal_best = np.array(metals_best)
    dust_best = np.array(dusts_best)
    mwa_best = np.array(mwas_best)
    
    if best :
        return (metal_median, metal_lo, metal_hi,
                dust_median, dust_lo, dust_hi,
                mwa_median, mwa_lo, mwa_hi,
                metal_best, dust_best, mwa_best)
    else :
        return (metal_median, metal_lo, metal_hi,
                dust_median, dust_lo, dust_hi,
                mwa_median, mwa_lo, mwa_hi)
Exemplo n.º 6
0
        mwas, mwa_16, mwa_84 = [], [], []
        metals, metals_16, metals_84 = [], [], []
        for binNum in bins:  # loop over all the bins in the table
            infile = '{}/h5/ID_{}_bin_{}.h5'.format(cluster, ID, binNum)
            result, obs, _ = reader.results_from(infile, dangerous=True)
            zred, mass, logzsol, dust2, tage, tau = result['bestfit'][
                'parameter']

            metals.append(logzsol)
            mwa = mwa_calc(tau, tage, power=1)
            mwas.append(mwa)

            # print(mwa, mwa_calc_alt(tau, tage, power=1))
            # print(cosmo.age(zred).value, tage, tau, mwa)

            samples = sample_posterior(result['chain'],
                                       weights=result['weights'])

            sample_metals = samples[:, 2]
            sample_mwas = mwa_calc(samples[:, 5], samples[:, 4], power=1)

            mwa_16.append(np.percentile(sample_mwas, 16))
            mwa_84.append(np.percentile(sample_mwas, 84))

            metals_16.append(np.percentile(sample_metals, 16))
            metals_84.append(np.percentile(sample_metals, 84))

        mwa_lo = np.abs(mwas - np.array(mwa_16))
        mwa_hi = np.abs(np.array(mwa_84) - mwas)

        metals_lo = np.abs(metals - np.array(metals_16))
        metals_hi = np.abs(np.array(metals_84) - metals)
Exemplo n.º 7
0
def results_corner(cluster,
                   ID,
                   binNum,
                   full=False,
                   results_type='dynesty',
                   save=False,
                   version=''):
    # create corner plots

    result, obs, model, sps = get_results(cluster,
                                          ID,
                                          binNum,
                                          results_type=results_type,
                                          version=version)

    if save:
        os.makedirs(
            '{}/images_corner_plots'.format(cluster),  # ensure the output
            exist_ok=True)  # directory for the figures is available
    outfile = '{}/images_corner_plots/{}_ID_{}_bin_{}{}.pdf'.format(
        cluster, cluster, ID, binNum, version)

    samples = sample_posterior(result['chain'], weights=result['weights'])
    mwas = mwa_calc(samples[:, 5], samples[:, 4], power=1)

    # logify the mass and tau parameters
    samples[:, 1] = np.log10(samples[:, 1])
    samples[:, 5] = np.log10(samples[:, 5])

    samples = np.c_[samples, mwas]

    z_lo, z_hi = np.percentile(samples[:, 0], [0.15, 99.85])
    M_lo, M_hi = np.percentile(samples[:, 1], [0.15, 99.85])
    Z_lo, Z_hi = np.percentile(samples[:, 2], [0.15, 99.85])
    d_lo, d_hi = np.percentile(samples[:, 3], [0.15, 99.85])
    t_lo, t_hi = np.percentile(samples[:, 4], [0.15, 99.85])
    T_lo, T_hi = np.percentile(samples[:, 5], [0.15, 99.85])
    MWA_lo, MWA_hi = np.percentile(samples[:, 6], [0.15, 99.85])

    if full:
        ranges = [(z_lo, z_hi), (M_lo, M_hi), (Z_lo, Z_hi), (d_lo, d_hi),
                  (t_lo, t_hi), (T_lo, T_hi), (MWA_lo, MWA_hi)]
        labels = [
            r'$z_{\rm red}$', r'$\log(M_{*})$', r'$\log(Z_{*})$',
            r'$\hat{\tau}_{\lambda, 2}$', r'$T_{0}$', r'$\log(\tau)$', 'MWA'
        ]
        plt.plot_corner(samples,
                        labels,
                        len(labels),
                        result,
                        ranges=ranges,
                        outfile=outfile,
                        save=save)
    else:
        sub_samples = np.delete(samples, [4, 5], 1)
        sub_labels = [
            r'$z_{\rm red}$', r'$\log(M_{*})$', r'$\log(Z_{*})$',
            r'$\hat{\tau}_{\lambda, 2}$', 'MWA'
        ]
        sub_ranges = [(z_lo, z_hi), (M_lo, M_hi), (Z_lo, Z_hi), (d_lo, d_hi),
                      (MWA_lo, MWA_hi)]
        plt.plot_corner(sub_samples,
                        sub_labels,
                        len(sub_labels),
                        result,
                        ranges=sub_ranges,
                        outfile=outfile,
                        save=save)

    return