def kawa_fit_err(y, l, ro, b, ro_err, b_err, uplow="up"):
    ro_term = ro_err * (l / M_to_lum(-21))**b
    beta_term = b_err * ro * (l / M_to_lum(-21)) ** b \
                * np.log(l / M_to_lum(-21))

    if uplow == "up":
        return y + np.sqrt(ro_term**2 + beta_term**2)
    else:
        return y - np.sqrt(ro_term**2 + beta_term**2)
Beispiel #2
0
def lf_for_z(z, log10L_bin_centres, models, legend=False):
    # THIS WILL BE individual LF plot

    colors = [
        'b', 'r', 'orange', 'g', 'k', 'c', 'y', 'm', 'darkslateblue', 'gray',
        'tomato', 'lawngreen', 'teal', 'wheat'
    ]

    fig = plt.figure()

    if type(models) == str:
        models = [models]

    for i, model in enumerate(models):

        m = getattr(lf_parameters, model)()

        if hasattr(m, 'beta'):
            s = abs(np.array(m.redshifts) - z) < 0.1

            x = 0.4 * (lum_to_M(10**log10L_bin_centres) -
                       np.array(m.M_star)[s][0])
            phistar = 10**np.array(m.phi_star)[s][0]
            alpha = np.array(m.alpha)[s][0]
            beta = np.array(m.beta)[s][0]

            phi = phistar / (10**(x * (alpha + 1)) + 10**(x * (beta + 1)))

            plt.scatter(log10L_bin_centres,
                        np.log10(phi),
                        c=colors[i],
                        label=model)

        else:

            s = abs(np.array(m.redshifts) - z) < 0.1

            x = 10**(log10L_bin_centres -
                     np.log10(M_to_lum(np.array(m.M_star)[s][0])))
            phistar = 10**np.array(m.phi_star)[s][0]
            alpha = np.array(m.alpha)[s][0]
            plt.scatter(log10L_bin_centres,
                        np.log10(phistar * (x)**(alpha + 1) * np.exp(-x)),
                        c=colors[i],
                        label=model)

    plt.ylabel(r'$\rm log_{10}(\phi \; / \; cMpc^{-3} \; dex^{-1})$')
    plt.xlabel(r"$\rm log_{10}(L_{UV} \; / \; erg\, s^{-1}\, Hz^{-1})$")

    if legend:
        plt.legend(loc='best')

    return fig
Beispiel #3
0
    def sample(self, area=1., cosmo=False, redshift_limits=[8., 15.], log10L_limits=[27., 30.], dz=0.05,
                     seed=False):

        # samples the LF evolution model in a given area

        if not cosmo: cosmo = flare.core.default_cosmo()

        area_sm = area  # Area in square arcmin
        area_sd = area_sm / 3600.  # Area in square degrees
        area_sr = (np.pi / 180.) ** 2 * area_sd  # Area in steradian

        # Setting the bin edges as well as centres for later operations
        bin_edges = {'z': np.arange(redshift_limits[0], redshift_limits[-1] + dz, dz)}
        bin_centres = {'z': bin_edges['z'][:-1] + dz / 2.}

        # Using astropy.cosmology to calculate the volume in each redshift bin
        volumes = np.asarray([cp.quad(dVc, bin_edges['z'][i - 1], bin_edges['z'][i], args=cosmo)[0] for i in
                              range(1, len(bin_edges['z']))])

        # Initialising the output array
        sample = {'log10L': np.asarray([]), 'z': np.asarray([])}

        if seed: np.random.seed(seed)

        for i in range(len(bin_centres['z'])):
            params = self.parameters(bin_centres['z'][i])

            sp = {}
            sp['alpha'] = params['alpha']
            sp['phi*'] = 10 ** params['log10phi*']
            sp['log10L*'] = np.log10(M_to_lum(params['M*']))

            LF = LF_interpolation(sp)

            samples = LF.sample(volumes[i] * area_sr, log10L_limits[0])
            sample['log10L'] = np.concatenate((sample['log10L'], samples))
            sample['z'] = np.concatenate(
                (sample['z'], np.array([bin_centres['z'][i] + dz * (np.random.random() - 0.5) for item in samples])))

        return sample
Beispiel #4
0
}
kawa_low_params = {
    'beta': {
        6: 0.09,
        7: 0.09,
        8: 0.78,
        9: 0.27
    },
    'r_0': {
        6: 0.15,
        7: 0.15,
        8: 0.26,
        9: 0.74
    }
}
kawa_fit = lambda l, r0, b: r0 * (l / M_to_lum(-21))**b


def m_to_M(m, cosmo, z):
    flux = photconv.m_to_flux(m)
    lum = photconv.flux_to_L(flux, cosmo, z)
    M = photconv.lum_to_M(lum)
    return M


def M_to_m(M, cosmo, z):
    lum = photconv.M_to_lum(M)
    flux = photconv.lum_to_flux(lum, cosmo, z)
    m = photconv.flux_to_m(flux)
    return m
Beispiel #5
0
# Define filter
filters = ('FAKE.TH.FUV', 'FAKE.TH.NUV', 'FAKE.TH.V')

csoft = 0.001802390 / (0.6777) * 1e3

nlim = 800

hlr_dict = {}
hlr_app_dict = {}
hlr_pix_dict = {}
lumin_dict = {}
mass_dict = {}
weight_dict = {}

lumin_bins = np.logspace(np.log10(M_to_lum(-16)), np.log10(M_to_lum(-24)), 20)
M_bins = np.linspace(-24, -16, 20)

lumin_bin_wid = lumin_bins[1] - lumin_bins[0]
M_bin_wid = M_bins[1] - M_bins[0]

lumin_bin_cents = lumin_bins[1:] - (lumin_bin_wid / 2)
M_bin_cents = M_bins[1:] - (M_bin_wid / 2)

# Load weights
df = pd.read_csv('../weight_files/weights_grid.txt')
weights = np.array(df['weights'])

regions = []
for reg in range(0, 40):
    if reg < 10:
}
kawa_low_params = {
    'beta': {
        6: 0.09,
        7: 0.09,
        8: 0.78,
        9: 0.27
    },
    'r_0': {
        6: 0.15,
        7: 0.15,
        8: 0.26,
        9: 0.74
    }
}
kawa_fit = lambda l, r0, b: r0 * (l / M_to_lum(-21))**b


def m_to_M(m, cosmo, z):
    flux = photconv.m_to_flux(m)
    lum = photconv.flux_to_L(flux, cosmo, z)
    M = photconv.lum_to_M(lum)
    return M


def M_to_m(M, cosmo, z):
    lum = photconv.M_to_lum(M)
    flux = photconv.lum_to_flux(lum, cosmo, z)
    m = photconv.flux_to_m(flux)
    return m
Beispiel #7
0
def lf_multi(zs, log10L_bin_centres, models, binned_lf=False, legend=False):
    # THIS WILL BE LF PLOT FOR A SELECTION OF MODELS

    markers = ['D', 's', 'h', '^', 'o', '*', 'v']

    cmap = mpl.cm.tab20
    cmap_marker = mpl.cm.Dark2_r

    if len(zs) % 2 == 1:
        N = int(len(zs) / 2) + 1
    else:
        N = int(len(zs) / 2)

    fig, axes = plt.subplots(N,
                             2,
                             figsize=(6, N * 2),
                             sharex=True,
                             sharey=True)

    plt.subplots_adjust(left=0.10,
                        bottom=0.10,
                        top=0.95,
                        right=0.85,
                        wspace=0.,
                        hspace=-0.)

    if type(models) == str:
        models = [models]

    Nxx = len(models)

    for z, ax in zip(zs, axes.flatten()):

        if legend:
            if Nxx > 7:
                if ax == axes[0, 0]:
                    try:
                        g = []
                        for i, model in enumerate(models[:7]):
                            label = getattr(lf_parameters, model)().label
                            g.append(
                                Line2D([-99., -98.], [-99., -98.],
                                       color=cmap(i / 19),
                                       label=label,
                                       alpha=0.6))
                        ax.legend(handles=g, loc='lower left', fontsize=6)

                    except:
                        continue
                if ax == axes[0, 1]:
                    try:
                        g = []
                        for i, model in enumerate(models[7:]):
                            i = i + 7
                            label = getattr(lf_parameters, model)().label
                            g.append(
                                Line2D([-99., -98.], [-99., -98.],
                                       color=cmap(i / 19),
                                       label=label,
                                       alpha=0.6))
                        ax.legend(handles=g, loc='lower left', fontsize=6)

                    except:
                        continue
            else:
                if ax == axes[0, 0]:
                    try:
                        g = []
                        for i, model in enumerate(models):
                            label = getattr(lf_parameters, model)().label
                            g.append(
                                Line2D([-99., -98.], [-99., -98.],
                                       color=cmap(i / 19),
                                       label=label,
                                       alpha=0.6))
                        ax.legend(handles=g, loc='lower left', fontsize=6)

                    except:
                        continue

        if ax == axes[1, 0]:

            if binned_lf:

                if type(binned_lf) == list:
                    g = []

                    for l, lf in enumerate(binned_lf):
                        g.append(
                            plt.errorbar(-99.,
                                         -99.,
                                         yerr=1.,
                                         color=cmap_marker(l / 7),
                                         linestyle='',
                                         marker=markers[l],
                                         mec='k',
                                         alpha=0.6,
                                         label=lf['label'],
                                         markersize=3,
                                         elinewidth=1,
                                         capsize=1,
                                         capthick=1))
                    ax.legend(handles=g, loc='lower left', fontsize=6)

                else:
                    g = []

                    for l in range(1):
                        g.append(
                            plt.errorbar(-99.,
                                         -99.,
                                         yerr=1.,
                                         fmt='kD',
                                         alpha=0.6,
                                         label=binned_lf['label'],
                                         markersize=3,
                                         elinewidth=1,
                                         capsize=1,
                                         capthick=1))
                    ax.legend(handles=g, loc='lower left', fontsize=6)

            # except:
            #    continue

        for i, model in enumerate(models):

            m = getattr(lf_parameters, model)()

            if hasattr(m, 'beta'):
                s = abs(np.array(m.redshifts) - z) < 0.5

                try:
                    x = 0.4 * (lum_to_M(10**log10L_bin_centres) -
                               np.array(m.M_star)[s][0])
                    phistar = 10**np.array(m.phi_star)[s][0]
                    alpha = np.array(m.alpha)[s][0]
                    beta = np.array(m.beta)[s][0]

                    phi = phistar / (10**(x * (alpha + 1)) + 10**(x *
                                                                  (beta + 1)))

                    ax.plot(log10L_bin_centres,
                            np.log10(phi),
                            c=cmap(i / 19),
                            alpha=0.6)
                except:
                    continue

            else:

                s = abs(np.array(m.redshifts) - z) < 0.5

                try:
                    x = 10**(log10L_bin_centres -
                             np.log10(M_to_lum(np.array(m.M_star)[s][0])))
                    phistar = 10**np.array(m.phi_star)[s][0]
                    alpha = np.array(m.alpha)[s][0]
                    ax.plot(log10L_bin_centres,
                            np.log10(phistar * (x)**(alpha + 1) * np.exp(-x)),
                            c=cmap(i / 19),
                            alpha=0.6)

                except:
                    continue

        if binned_lf:
            if type(binned_lf) == list:
                for l, lf in enumerate(binned_lf):
                    try:
                        q = abs(
                            np.array([float(k)
                                      for k in [*lf['LF'].keys()]]) - z) < 0.5
                        z_key = str(
                            int(
                                np.array([
                                    float(k) for k in [*lf['LF'].keys()]
                                ])[q]))
                        log10L_bin = np.log10(
                            M_to_lum(np.array(lf['LF'][str(int(z_key))]['M'])))
                        phi_bin = np.array(lf['LF'][str(int(z_key))]['phi'])
                        err = np.array(lf['LF'][str(int(z_key))]['phi_err'])
                        uplims = lf['LF'][str(int(z_key))]['uplim']

                        if lf['both_err']:
                            if lf['log_err']:
                                phi_err = err
                            else:
                                phi_err = [
                                    logerr_lo(phi_bin, err[0], uplims),
                                    logerr_hi(phi_bin, err[1])
                                ]
                        else:
                            if lf['log_err']:
                                phi_err = err
                            else:
                                phi_err = [
                                    logerr_lo(phi_bin, err, uplims),
                                    logerr_hi(phi_bin, err)
                                ]

                        ax.errorbar(log10L_bin,
                                    np.log10(phi_bin),
                                    yerr=phi_err,
                                    color=cmap_marker(l / 7),
                                    linestyle='',
                                    marker=markers[l],
                                    mec='k',
                                    alpha=0.8,
                                    zorder=50 + l,
                                    markersize=3,
                                    elinewidth=1,
                                    capsize=1,
                                    capthick=1,
                                    uplims=uplims)

                    except:
                        continue

            else:
                try:
                    q = abs(
                        np.array([float(k)
                                  for k in [*binned_lf['LF'].keys()]]) -
                        z) < 0.5
                    z_key = str(
                        int(
                            np.array([
                                float(k) for k in [*binned_lf['LF'].keys()]
                            ])[q]))
                    log10L_bin = np.log10(
                        M_to_lum(
                            np.array(binned_lf['LF'][str(int(z_key))]['M'])))
                    phi_bin = np.array(binned_lf['LF'][str(int(z_key))]['phi'])
                    err = np.array(binned_lf['LF'][str(int(z_key))]['phi_err'])
                    uplims = binned_lf['LF'][str(int(z_key))]['uplim']
                    if binned_lf['both_err']:
                        if binned_lf['log_err']:
                            phi_err = err
                        else:
                            phi_err = [
                                logerr_lo(phi_bin, err[0], uplims),
                                logerr_hi(phi_bin, err[1])
                            ]
                            print(phi_err)
                    else:
                        if binned_lf['log_err']:
                            phi_err = err
                        else:
                            phi_err = [
                                logerr_lo(phi_bin, err, uplims),
                                logerr_hi(phi_bin, err)
                            ]
                    ax.errorbar(log10L_bin,
                                np.log10(phi_bin),
                                yerr=phi_err,
                                fmt='kD',
                                alpha=0.6,
                                zorder=50,
                                markersize=3,
                                elinewidth=1,
                                capsize=1,
                                capthick=1,
                                uplims=uplims)

                except:
                    continue

        ax.text(0.7,
                0.9,
                r'$\rm z=[{0:.1f}, {1:.1f})$'.format(z - 0.5, z + 0.5),
                fontsize=8,
                transform=ax.transAxes)

        ylim = np.array([-8., -4.01])

        ax.set_ylim(-8., -1.5)
        ax.set_xlim([min(log10L_bin_centres), max(log10L_bin_centres)])

    fig.text(0.5,
             0.05,
             r'$\rm\log_{10}[L_{FUV} \; / \; (erg \; s^{-1} \; Hz^{-1})]$',
             horizontalalignment='center',
             verticalalignment='center')
    fig.text(0.05,
             0.5,
             r'$\rm\log_{10}[\phi \; / \; Mpc^{-3}]$',
             horizontalalignment='center',
             verticalalignment='center',
             rotation=90)

    return fig
Beispiel #8
0
def lf_params_zs(zs, log10L_bin_centres, models, legend=False):
    # THIS WILL BE LF PLOT FOR A SELECTION OF MODELS

    colours = [
        'b', 'r', 'orange', 'g', 'k', 'c', 'y', 'm', 'darkslateblue', 'gray',
        'tomato', 'lawngreen', 'teal', 'wheat'
    ]

    if len(zs) % 2 == 1:
        N = int(len(zs) / 2) + 1
    else:
        N = int(len(zs) / 2)

    fig, axes = plt.subplots(N,
                             2,
                             figsize=(6, N * 2),
                             sharex=True,
                             sharey=True)

    plt.subplots_adjust(left=0.10,
                        bottom=0.10,
                        top=0.95,
                        right=0.85,
                        wspace=0.,
                        hspace=-0.)

    if type(models) == str:
        models = [models]

    Nxx = len(models)

    for z, ax in zip(zs, axes.flatten()):

        if legend:
            if Nxx > 7:
                if ax == axes[0, 0]:
                    try:
                        g = []
                        for i, model in enumerate(models[:7]):
                            colors_plot = colours[:7]
                            g.append(
                                ax.scatter([-99.], [-99.],
                                           c=colors_plot[i],
                                           s=5,
                                           label=model))
                        ax.legend(handles=g, loc='lower left')

                    except:
                        continue
                if ax == axes[0, 1]:
                    try:
                        g = []
                        for i, model in enumerate(models[7:]):
                            colors_plot = colours[7:]
                            g.append(
                                ax.scatter([-99.], [-99.],
                                           c=colors_plot[i],
                                           s=5,
                                           label=model))
                        ax.legend(handles=g, loc='lower left')

                    except:
                        continue
            else:
                if ax == axes[0, 0]:
                    try:
                        g = []
                        for i, model in enumerate(models):
                            g.append(
                                ax.scatter([-99.], [-99.],
                                           c=colours[i],
                                           s=5,
                                           label=model))
                        ax.legend(handles=g, loc='lower left')

                    except:
                        continue

        for i, model in enumerate(models):

            m = getattr(lf_parameters, model)()

            if hasattr(m, 'beta'):
                s = abs(np.array(m.redshifts) - z) < 0.5

                try:
                    x = 0.4 * (lum_to_M(10**log10L_bin_centres) -
                               np.array(m.M_star)[s][0])
                    phistar = 10**np.array(m.phi_star)[s][0]
                    alpha = np.array(m.alpha)[s][0]
                    beta = np.array(m.beta)[s][0]

                    phi = phistar / (10**(x * (alpha + 1)) + 10**(x *
                                                                  (beta + 1)))

                    ax.scatter(log10L_bin_centres,
                               np.log10(phi),
                               s=5,
                               c=colours[i])
                except:
                    continue

            else:

                s = abs(np.array(m.redshifts) - z) < 0.5

                try:
                    x = 10**(log10L_bin_centres -
                             np.log10(M_to_lum(np.array(m.M_star)[s][0])))
                    phistar = 10**np.array(m.phi_star)[s][0]
                    alpha = np.array(m.alpha)[s][0]
                    ax.scatter(log10L_bin_centres,
                               np.log10(phistar * (x)**(alpha + 1) *
                                        np.exp(-x)),
                               s=5,
                               c=colours[i])

                except:
                    continue

        ax.text(0.7,
                0.9,
                r'$\rm z=[{0:.1f}, {1:.1f})$'.format(z - 0.5, z + 0.5),
                fontsize=8,
                transform=ax.transAxes)

        ylim = np.array([-8., -4.01])

        ax.set_ylim(-8., -1.5)
        ax.set_xlim([min(log10L_bin_centres), max(log10L_bin_centres)])

    fig.text(0.5,
             0.05,
             r'$\rm\log_{10}[L_{FUV} \; / \; (erg \; s^{-1} \; Hz^{-1})]$',
             horizontalalignment='center',
             verticalalignment='center')
    fig.text(0.05,
             0.5,
             r'$\rm\log_{10}[\phi \; / \; Mpc^{-3}]$',
             horizontalalignment='center',
             verticalalignment='center',
             rotation=90)

    return fig
Beispiel #9
0
nlim = 10**8

hlr_dict = {}
hlr_app_dict = {}
hlr_pix_dict = {}
lumin_dict = {}
weight_dict = {}
mass_dict = {}

intr_hlr_dict = {}
intr_hlr_app_dict = {}
intr_hlr_pix_dict = {}
intr_lumin_dict = {}
intr_weight_dict = {}

lumin_bins = np.logspace(np.log10(M_to_lum(-16)), np.log10(M_to_lum(-24)), 20)
M_bins = np.linspace(-24, -16, 20)

lumin_bin_wid = lumin_bins[1] - lumin_bins[0]
M_bin_wid = M_bins[1] - M_bins[0]

lumin_bin_cents = lumin_bins[1:] - (lumin_bin_wid / 2)
M_bin_cents = M_bins[1:] - (M_bin_wid / 2)

# Load weights
df = pd.read_csv('../weight_files/weights_grid.txt')
weights = np.array(df['weights'])

regions = []
for reg in range(0, 40):
    if reg < 10:
Beispiel #10
0
def size_lumin_grid(data, snaps, filters, orientation, Type, extinction, mtype,
                    weight_norm, xlims, ylims):

    extent = (np.log10(xlims[0]), np.log10(xlims[1]), np.log10(ylims[0]),
              np.log10(ylims[1]))

    for f in filters:

        print("Plotting for:")
        print("Orientation =", orientation)
        print("Type =", Type)
        print("Filter =", f)

        fig = plt.figure(figsize=(18, 5))
        gs = gridspec.GridSpec(1, len(snaps))
        gs.update(wspace=0.0, hspace=0.0)
        axes = []
        i = 0
        while i < len(snaps):
            axes.append(fig.add_subplot(gs[0, i]))
            if i > 0:
                axes[-1].tick_params(axis='y',
                                     left=False,
                                     right=False,
                                     labelleft=False,
                                     labelright=False)
            i += 1

        legend_elements = []

        for i, snap in enumerate(snaps):

            z_str = snap.split('z')[1].split('p')
            z = float(z_str[0] + '.' + z_str[1])

            if mtype == "part":
                hlrs = np.array(data[snap][f]["HLR_0.5"])
                lumins = np.array(data[snap][f]["Luminosity"])
                intr_lumins = np.array(data[snap][f]["Luminosity"])
            elif mtype == "app":
                hlrs = np.array(data[snap][f]["HLR_Aperture_0.5"])
                lumins = np.array(data[snap][f]["Image_Luminosity"])
                intr_lumins = np.array(data[snap][f]["Image_Luminosity"])
            else:
                hlrs = np.array(data[snap][f]["HLR_Pixel_0.5"])
                lumins = np.array(data[snap][f]["Image_Luminosity"])
                intr_lumins = np.array(data[snap][f]["Image_Luminosity"])
            w = np.array(data[snap][f]["Weight"])
            mass = np.array(data[snap][f]["Mass"])

            compact_ncom = data[snap][f]["Compact_Population_NotComplete"]
            diffuse_ncom = data[snap][f]["Diffuse_Population_NotComplete"]
            compact_com = data[snap][f]["Compact_Population_Complete"]
            diffuse_com = data[snap][f]["Diffuse_Population_Complete"]

            # bins = np.logspace(np.log10(0.08), np.log10(20), 40)
            # lumin_bins = np.logspace(np.log10(10 ** 27.),
            #                          np.log10(10 ** 30.5),
            #                          40)
            # H, xbins, ybins = np.histogram2d(lumins[okinds2], hlrs[okinds2],
            #                                  bins=(lumin_bins, bins),
            #                                  weights=w[okinds2])
            #
            # # Resample your data grid by a factor of 3 using cubic spline interpolation.
            # H = scipy.ndimage.zoom(H, 3)
            #
            # # percentiles = [np.min(w),
            # #                10**-3,
            # #                10**-1,
            # #                1, 2, 5]
            #
            # try:
            #     percentiles = [np.percentile(H[H > 0], 50),
            #                    np.percentile(H[H > 0], 80),
            #                    np.percentile(H[H > 0], 90),
            #                    np.percentile(H[H > 0], 95),
            #                    np.percentile(H[H > 0], 99)]
            # except IndexError:
            #     continue
            #
            # print(percentiles)
            #
            # bins = np.logspace(np.log10(0.08), np.log10(20), H.shape[0] + 1)
            # lumin_bins = np.logspace(np.log10(10 ** 27.), np.log10(10 ** 30.5),
            #                          H.shape[0] + 1)
            #
            # xbin_cents = (bins[1:] + bins[:-1]) / 2
            # ybin_cents = (bins[1:] + bins[:-1]) / 2
            #
            # XX, YY = np.meshgrid(xbin_cents, ybin_cents)

            try:
                cbar = axes[i].hexbin(lumins[diffuse_ncom],
                                      hlrs[diffuse_ncom],
                                      gridsize=50,
                                      mincnt=1,
                                      C=w[diffuse_ncom],
                                      reduce_C_function=np.sum,
                                      xscale='log',
                                      yscale='log',
                                      norm=weight_norm,
                                      linewidths=0.2,
                                      cmap='Greys',
                                      alpha=0.2,
                                      extent=extent)
            except ValueError as e:
                print(e, "Diffuse incomplete", snap, f)
                print(lumins[diffuse_ncom][lumins[diffuse_ncom] <= 0],
                      lumins[diffuse_ncom][lumins[diffuse_ncom] <= 0].size)
            try:
                axes[i].hexbin(lumins[compact_ncom],
                               hlrs[compact_ncom],
                               gridsize=50,
                               mincnt=1,
                               C=w[compact_ncom],
                               reduce_C_function=np.sum,
                               xscale='log',
                               yscale='log',
                               norm=weight_norm,
                               linewidths=0.2,
                               cmap='viridis',
                               alpha=0.2,
                               extent=extent)
            except ValueError as e:
                print(e, "Compact incomplete", snap, f)
                print(lumins[compact_ncom][lumins[compact_ncom] <= 0],
                      lumins[compact_ncom][lumins[compact_ncom] <= 0].size)
            try:
                cbar = axes[i].hexbin(lumins[diffuse_com],
                                      hlrs[diffuse_com],
                                      gridsize=50,
                                      mincnt=1,
                                      C=w[diffuse_com],
                                      reduce_C_function=np.sum,
                                      xscale='log',
                                      yscale='log',
                                      norm=weight_norm,
                                      linewidths=0.2,
                                      cmap='Greys',
                                      extent=extent)
            except ValueError as e:
                print(e, "Diffuse complete", snap, f)
            try:
                axes[i].hexbin(lumins[compact_com],
                               hlrs[compact_com],
                               gridsize=50,
                               mincnt=1,
                               C=w[compact_com],
                               reduce_C_function=np.sum,
                               xscale='log',
                               yscale='log',
                               norm=weight_norm,
                               linewidths=0.2,
                               cmap='viridis',
                               extent=extent)
            except ValueError as e:
                print(e, "Compact complete", snap, f)

                # popt, pcov = curve_fit(kawa_fit, lumins, hlrs,
                #                        p0=(kawa_params['r_0'][7],
                #                            kawa_params['beta'][7]),
                #                        sigma=w)
                #
                # popt1, pcov1 = curve_fit(kawa_fit, lumins[okinds1],
                #                          hlrs[okinds1],
                #                          p0=(kawa_params['r_0'][7],
                #                              kawa_params['beta'][7]),
                #                          sigma=w[okinds1])
                #
                # popt2, pcov2 = curve_fit(kawa_fit, lumins[okinds2],
                #                          hlrs[okinds2],
                #                          p0=(kawa_params['r_0'][7],
                #                              kawa_params['beta'][7]),
                #                          sigma=w[okinds2])
                #
                # print("Total")
                # print(popt)
                # print(pcov)
                # print("Low")
                # print(popt2)
                # print(pcov2)
                # print("High")
                # print(popt1)
                # print(pcov1)
                #
                # fit_lumins = np.logspace(np.log10(lumins.min()),
                #                          np.log10(lumins.max()),
                #                          1000)
                # fit_lumins_low = np.logspace(np.log10(lumins[okinds2].min()),
                #                              np.log10(lumins[okinds2].max()),
                #                              1000)
                # fit_lumins_high = np.logspace(np.log10(lumins[okinds1].min()),
                #                               np.log10(lumins[okinds1].max()),
                #                               1000)

                # fit = kawa_fit(fit_lumins, popt[0], popt[1])
                # fit_low = kawa_fit(fit_lumins_low, popt2[0], popt2[1])
                # fit_high = kawa_fit(fit_lumins_high, popt1[0], popt1[1])
                #
                # axes[i].plot(fit_lumins_high, fit_high,
                #              linestyle='-', color="m",
                #              alpha=0.9, zorder=5,
                #              linewidth=2)
                # axes[i].plot(fit_lumins_low, fit_low,
                #              linestyle='--', color="m",
                #              alpha=0.9, zorder=4,
                #              linewidth=2)
                # axes[i].plot(fit_lumins, fit,
                #              linestyle='dotted', color="m",
                #              alpha=0.9, zorder=3,
                #              linewidth=2)

            if Type != "Intrinsic":

                for p in colors_in_order:
                    okinds = papers == p
                    plt_m = mags[okinds]
                    plt_r_es = r_es[okinds]
                    plt_zs = zs[okinds]

                    okinds = np.logical_and(
                        plt_zs >= (z - 0.5),
                        np.logical_and(
                            plt_zs < (z + 0.5),
                            np.logical_and(plt_r_es > 0.08,
                                           plt_m <= M_to_m(-16, cosmo, z))))
                    plt_m = plt_m[okinds]
                    plt_r_es = plt_r_es[okinds]

                    if plt_m.size == 0:
                        continue
                    plt_M = m_to_M(plt_m, cosmo, z)
                    plt_lumins = M_to_lum(plt_M)

                    legend_elements.append(
                        Line2D([0], [0],
                               marker=markers[p],
                               color='w',
                               label=labels[p],
                               markerfacecolor=colors[p],
                               markersize=8,
                               alpha=0.9))

                    axes[i].scatter(plt_lumins,
                                    plt_r_es,
                                    marker=markers[p],
                                    label=labels[p],
                                    s=20,
                                    color=colors[p],
                                    alpha=0.9)

                # if int(z) in [6, 7, 8, 9]:
                #
                #     if z == 7 or z == 6:
                #         low_lim = -16
                #     elif z == 8:
                #         low_lim = -16.8
                #     else:
                #         low_lim = -15.4
                #     fit_lumins = np.logspace(np.log10(M_to_lum(-21.6)),
                #                              np.log10(M_to_lum(low_lim)),
                #                              1000)
                #
                #     fit = kawa_fit(fit_lumins, kawa_params['r_0'][int(z)],
                #                    kawa_params['beta'][int(z)])
                #     axes[i].plot(fit_lumins, fit,
                #                  linestyle='dashed', color="g",
                #                  alpha=0.9, zorder=2,
                #                  label="Kawamata+18", linewidth=4)

            axes[i].text(0.95,
                         0.05,
                         f'$z={z}$',
                         bbox=dict(boxstyle="round,pad=0.3",
                                   fc='w',
                                   ec="k",
                                   lw=1,
                                   alpha=0.8),
                         transform=axes[i].transAxes,
                         horizontalalignment='right',
                         fontsize=8)

            axes[i].tick_params(axis='both',
                                which='minor',
                                bottom=True,
                                left=True)

            # Label axes
            axes[i].set_xlabel(r"$L_{" + f.split(".")[-1] +
                               "}/$ [erg $/$ s $/$ Hz]")

            axes[i].tick_params(axis='x', which='both', bottom=True)

            axes[i].set_xlim(xlims[0], xlims[1])

        for i in range(len(axes)):
            axes[i].set_ylim(ylims[0], ylims[1])

        axes[0].set_ylabel('$R_{1/2}/ [pkpc]$')
        axes[0].tick_params(axis='y', which='both', left=True)

        uni_legend_elements = []
        uni_legend_elements.append(
            Line2D([0], [0],
                   color="k",
                   linestyle="none",
                   marker="h",
                   label="FLARES"))
        # uni_legend_elements.append(
        #     Line2D([0], [0], color="g", linestyle="--",
        #            label=labels["K18"]))
        included = []
        for l in legend_elements:
            if (l.get_label(), l.get_marker()) not in included:
                print((l.get_label(), l.get_marker()))
                uni_legend_elements.append(l)
                included.append((l.get_label(), l.get_marker()))

        axes[2].legend(handles=uni_legend_elements,
                       loc='upper center',
                       bbox_to_anchor=(0.5, -0.15),
                       fancybox=True,
                       ncol=len(uni_legend_elements))

        fig.savefig('plots/HalfLightRadius_' + mtype + "_" + f + '_' +
                    orientation + '_' + Type + "_" + extinction + ".png",
                    bbox_inches='tight',
                    dpi=300)

        plt.close(fig)
def fit_size_lumin_grid_nosmooth(data, snaps, filters, orientation, Type,
                                 extinction, mtype, sample, xlims, ylims,
                                 weight_norm):

    extent = (np.log10(xlims[0]), np.log10(xlims[1]),
              np.log10(ylims[0]), np.log10(ylims[1]))

    for f in filters:

        print("Plotting for:")
        print("Orientation =", orientation)
        print("Type =", Type)
        print("Filter =", f)

        fig = plt.figure(figsize=(18, 5))
        gs = gridspec.GridSpec(1, len(snaps))
        gs.update(wspace=0.0, hspace=0.0)
        axes = []
        i = 0
        while i < len(snaps):
            axes.append(fig.add_subplot(gs[0, i]))
            axes[-1].loglog()
            if i > 0:
                axes[-1].tick_params(axis='y', left=False, right=False,
                                     labelleft=False, labelright=False)
            i += 1

        legend_elements = []

        for i, snap in enumerate(snaps):

            z_str = snap.split('z')[1].split('p')
            z = float(z_str[0] + '.' + z_str[1])

            if mtype == "part":
                hlrs = np.array(data[snap][f]["HLR_0.5"])
                lumins = np.array(data[snap][f]["Luminosity"])
                intr_lumins = np.array(data[snap][f]["Luminosity"])
            elif mtype == "app":
                hlrs = np.array(data[snap][f]["HLR_Aperture_0.5"])
                lumins = np.array(data[snap][f]["Image_Luminosity"])
                intr_lumins = np.array(data[snap][f]["Image_Luminosity"])
            else:
                hlrs = np.array(data[snap][f]["HLR_Pixel_0.5_No_Smooth"])
                lumins = np.array(data[snap][f]["Image_Luminosity"])
                intr_lumins = np.array(data[snap][f]["Image_Luminosity_No_Smooth"])
            w = np.array(data[snap][f]["Weight"])
            mass = np.array(data[snap][f]["Mass"])

            compact_ncom = data[snap][f]["Compact_Population_NotComplete"]
            diffuse_ncom = data[snap][f]["Diffuse_Population_NotComplete"]
            compact_com = data[snap][f]["Compact_Population_Complete"]
            diffuse_com = data[snap][f]["Diffuse_Population_Complete"]
            if sample == "Complete":
                complete = np.logical_or(compact_com, diffuse_com)
            else:
                complete = data[snap][f]["okinds"]

            try:
                cbar = axes[i].hexbin(lumins[diffuse_ncom], hlrs[diffuse_ncom],
                                      gridsize=50,
                                      mincnt=1, C=w[diffuse_ncom],
                                      reduce_C_function=np.sum,
                                      xscale='log', yscale='log',
                                      norm=weight_norm, linewidths=0.2,
                                      cmap='Greys', alpha=0.2, extent=extent)
            except ValueError as e:
                print(e, "Diffuse incomplete", snap, f)
                print(lumins[diffuse_ncom][lumins[diffuse_ncom] <= 0],
                      lumins[diffuse_ncom][lumins[diffuse_ncom] <= 0].size)
            try:
                axes[i].hexbin(lumins[compact_ncom], hlrs[compact_ncom],
                               gridsize=50,
                               mincnt=1,
                               C=w[compact_ncom],
                               reduce_C_function=np.sum,
                               xscale='log', yscale='log',
                               norm=weight_norm, linewidths=0.2,
                               cmap='plasma', alpha=0.2, extent=extent)
            except ValueError as e:
                print(e, "Compact incomplete", snap, f)
                print(lumins[compact_ncom][lumins[compact_ncom] <= 0],
                      lumins[compact_ncom][lumins[compact_ncom] <= 0].size)
            try:
                cbar = axes[i].hexbin(lumins[diffuse_com], hlrs[diffuse_com],
                                      gridsize=50,
                                      mincnt=1, C=w[diffuse_com],
                                      reduce_C_function=np.sum,
                                      xscale='log', yscale='log',
                                      norm=weight_norm, linewidths=0.2,
                                      cmap='Greys', extent=extent)
            except ValueError as e:
                print(e, "Diffuse complete", snap, f)
            try:
                axes[i].hexbin(lumins[compact_com],
                               hlrs[compact_com], gridsize=50,
                               mincnt=1,
                               C=w[compact_com],
                               reduce_C_function=np.sum,
                               xscale='log', yscale='log',
                               norm=weight_norm, linewidths=0.2,
                               cmap='plasma', extent=extent)
            except ValueError as e:
                print(e, "Compact complete", snap, f)

            try:

                popt, pcov = curve_fit(r_fit, lumins[complete],
                                       hlrs[complete],
                                       p0=(kawa_params['r_0'][7],
                                           kawa_params['beta'][7]),
                                       sigma=w[complete])
            except ValueError as e:
                print(e)

            try:
                popt1, pcov1 = curve_fit(r_fit, lumins[compact_com],
                                         hlrs[compact_com],
                                         p0=(kawa_params['r_0'][7],
                                             kawa_params['beta'][7]),
                                         sigma=w[compact_com])
            except ValueError as e:
                print(e)

            try:
                popt2, pcov2 = curve_fit(r_fit, lumins,
                                         hlrs,
                                         p0=(kawa_params['r_0'][7],
                                             kawa_params['beta'][7]),
                                         sigma=w)
            except ValueError as e:
                print(e)

            try:
                print("--------------", "Total", "No smooth", Type, mtype,
                      f, snap,
                      "--------------")
                print("R_0=", popt[0], "+/-", np.sqrt(pcov[0, 0]))
                print("beta=", popt[1], "+/-", np.sqrt(pcov[1, 1]))

                # print("--------------", "Total", "Compact", mtype, f,
                #       "--------------")
                # print("R_0=", popt1[0], "+/-", np.sqrt(pcov1[0, 0]))
                # print("beta=", popt1[1], "+/-", np.sqrt(pcov1[1, 1]))
                # print(pcov1)
                print("--------------", "Kawamata", "All", mtype, f,
                      "--------------")
                if int(z) in [6, 7, 8, 9]:
                    print("R_0=", kawa_params['r_0'][int(z)])
                    print("beta=", kawa_params['beta'][int(z)])
                else:
                    print("R_0= ---")
                    print("beta= ---")
                print(
                    "----------------------------------------------------------")

                fit_lumins = np.logspace(np.log10(np.min(lumins[complete])),
                                         np.log10(np.max(lumins[complete])),
                                         1000)

                fit = r_fit(fit_lumins, popt[0], popt[1])

                axes[i].plot(fit_lumins, fit,
                             linestyle='-', color="r",
                             zorder=3)

                # fit = r_fit(fit_lumins, popt1[0], popt1[1])
                #
                # axes[i].plot(fit_lumins, fit,
                #              linestyle='-', color="m",
                #              zorder=3,
                #              linewidth=2)

            except ValueError as e:
                print(e)
                continue

            if int(z) in [6, 7, 8, 9]:

                if z == 7 or z == 6:
                    low_lim = -16
                elif z == 8:
                    low_lim = -16.8
                else:
                    low_lim = -15.4
                fit_lumins = np.logspace(np.log10(M_to_lum(-21.6)),
                                         np.log10(M_to_lum(low_lim)),
                                         1000)

                fit = kawa_fit(fit_lumins, kawa_params['r_0'][int(z)],
                               kawa_params['beta'][int(z)])
                axes[i].plot(fit_lumins, fit,
                             linestyle='dashed', color="g",
                             zorder=2,
                             label="Kawamata+18")

            # if int(z) in [7, 8, 9, 10, 11]:
            #
            #     fit_lumins = np.logspace(28.5,
            #                              bt_fit_uplims[int(z)],
            #                              1000)
            #
            #     fit = r_fit(fit_lumins, bt_params['r_0'][int(z)],
            #                    bt_params['beta'][int(z)])
            #     axes[i].plot(fit_lumins, fit,
            #                  linestyle='dashed', color="b",
            #                  zorder=2,
            #                  label="Marshall+21")
            #
            # if int(z) in [5, 6, 7, 8, 9, 10]:
            #
            #     fit_lumins = np.logspace(np.log10(M_to_lum(-22)),
            #                              np.log10(M_to_lum(-14)),
            #                              1000)
            #
            #     fit = r_fit(fit_lumins, mer_params['r_0'][int(z)],
            #                    mer_params['beta'][int(z)])
            #     axes[i].plot(fit_lumins, fit,
            #                  linestyle='dashed', color="m",
            #                  zorder=2,
            #                  label="Liu+17")

            axes[i].text(0.95, 0.05, f'$z={z}$',
                         bbox=dict(boxstyle="round,pad=0.3", fc='w',
                                   ec="k", lw=1, alpha=0.8),
                         transform=axes[i].transAxes,
                         horizontalalignment='right',
                         fontsize=8)

            axes[i].tick_params(axis='both', which='both',
                                bottom=True, left=True)

            # Label axes
            axes[i].set_xlabel(r"$L_{" + f.split(".")[-1]
                               + "}/$ [erg $/$ s $/$ Hz]")

            axes[i].set_xlim(xlims[0], xlims[1])

        for i in range(len(axes)):
            axes[i].set_ylim(ylims[0], ylims[1])

        axes[0].set_ylabel('$R_{1/2}/ [pkpc]$')
        axes[0].tick_params(axis='y', which='both', left=True)

        uni_legend_elements = []
        # uni_legend_elements.append(
        #     Line2D([0], [0], color="m", linestyle="dotted",
        #            label="FLARES (All)"))
        uni_legend_elements.append(
            Line2D([0], [0], color="r", linestyle="-",
                   label="FLARES"))
        # uni_legend_elements.append(
        #     Line2D([0], [0], color="m", linestyle="--",
        #            label="FLARES ($M_{\star}/M_\odot<10^{9}$)"))
        uni_legend_elements.append(
            Line2D([0], [0], color="g", linestyle="--",
                   label=labels["K18"]))
        # uni_legend_elements.append(
        #     Line2D([0], [0], color="b", linestyle="--",
        #            label="Marshall+2021"))
        # uni_legend_elements.append(
        #     Line2D([0], [0], color="m", linestyle="--",
        #            label="Liu+2017"))
        included = []
        for l in legend_elements:
            if (l.get_label(), l.get_marker()) not in included:
                print((l.get_label(), l.get_marker()))
                uni_legend_elements.append(l)
                included.append((l.get_label(), l.get_marker()))

        axes[2].legend(handles=uni_legend_elements, loc='upper center',
                       bbox_to_anchor=(0.5, -0.15), fancybox=True,
                       ncol=len(uni_legend_elements))

        fig.savefig(
            'plots/FitHalfLightRadius_NoSmooth_' + mtype + "_" + f + '_'
            + orientation + '_' + Type + "_" + extinction + "_"
            + sample + ".png",
            bbox_inches='tight', dpi=300)

        plt.close(fig)
Beispiel #12
0
# Define Kawamata17 fit and parameters
kawa_params = {
    'beta': {
        6: 0.46,
        7: 0.46,
        8: 0.38,
        9: 0.56
    },
    'r_0': {
        6: 0.94,
        7: 0.94,
        8: 0.81,
        9: 1.2
    }
}
kawa_fit = lambda l, r0, b: r0 * (l / M_to_lum(-21))**b
ono_fit = lambda z, a, m: 10**(m * np.log10(1 + z) + a)

L_star = M_to_lum(-21)


def m_to_M(m, cosmo, z):
    flux = photconv.m_to_flux(m)
    lum = photconv.flux_to_L(flux, cosmo, z)
    M = photconv.lum_to_M(lum)
    return M


def M_to_m(M, cosmo, z):
    lum = photconv.M_to_lum(M)
    flux = photconv.lum_to_flux(lum, cosmo, z)
Beispiel #13
0
    def N(self, area=1., cosmo=False, redshift_limits=[8., 15.], log10L_limits=[27.5, 30.], dz=0.05, dlog10L=0.05, per_arcmin=False, return_volumes=False):

        # calculates the number of galaxies in each bin on a grid defined by redshift_limits, log10L_limits, dz, dlog10L
        # and area based on a luminosity function evolution model.

        area_sm = area  # Area in square arcmin
        area_sd = area_sm / 3600.  # Area in square degrees
        area_sr = (np.pi / 180.) ** 2 * area_sd  # Area in steradian

        if not cosmo: cosmo = flare.core.default_cosmo()

        # Setting the bin edges as well as centres for later operations
        bin_edges = {'log10L': np.arange(log10L_limits[0], log10L_limits[-1] + dlog10L, dlog10L),
                     'z': np.arange(redshift_limits[0], redshift_limits[-1] + dz, dz)}
        bin_centres = {'log10L': bin_edges['log10L'][:-1] + dlog10L / 2., 'z': bin_edges['z'][:-1] + dz / 2.}

        # Using astropy.cosmology to calculate the volume in each redshift bin
        volumes = np.asarray([cp.quad(dVc, bin_edges['z'][i - 1], bin_edges['z'][i], args=cosmo)[0] for i in
                              range(1, len(bin_edges['z']))])

        params = self.parameters(bin_centres['z'])

        if 'beta' in params.keys():
            alphas = params['alpha']
            Lstars = M_to_lum(params['M*'])
            Mstars = params['M*']
            phistars = 10 ** params['log10phi*']
            betas = params['beta']

            N = phistars[None, :] * np.vectorize(quadfunct2)(_integ_dblpow,
                                                             0.4 * (lum_to_M(
                                                                 10 ** bin_edges['log10L'][1:, None]) - Mstars[None,
                                                                                                        :]),
                                                             0.4 * (lum_to_M(
                                                                 10 ** bin_edges['log10L'][:-1, None]) - Mstars[None,
                                                                                                         :]),
                                                             alphas[None, :], betas[None, :]) * volumes[None,
                                                                                               :] * area_sr

            ''' Left in for possible future implementation
                        #N = phistars[None, :] * np.vectorize(quadfunct2)(_integ_dblpow2,
                        #                                                10**(bin_edges['log10L'][:-1, None] - Lstars[None, :]),
                        #                                                10**(bin_edges['log10L'][1:, None] - Lstars[None, :]),
                        #                                                alphas[None, :], betas[None, :] ) * volumes[None, :] * area_sr
            '''

        else:
            alphas = params['alpha']
            Lstars = M_to_lum(params['M*'])
            phistars = 10 ** params['log10phi*']
            Mstars = params['M*']
            N = phistars[None, :] * np.vectorize(quadfunct)(_integ,
                                                         10 ** bin_edges['log10L'][:-1, None] / Lstars[None, :],
                                                         10 ** bin_edges['log10L'][1:, None] / Lstars[None, :],

                                                         args=(alphas[None, :])) * volumes[None, :] * area_sr
            ''' Left in for possible future implementation
            N = phistars[None, :] * np.vectorize(quadfunct)(_integ2,
                                                         lum_to_M(10**bin_edges['log10L'][1:, None]) - Mstars[None, :],
                                                         lum_to_M(10**bin_edges['log10L'][:-1, None]) - Mstars[None, :],
                                                         args=(alphas[None, :])) * volumes[None, :] * area_sr
            '''

        if per_arcmin:
            N /= area_sm

        if return_volumes:
            return bin_edges, bin_centres, volumes, N

        else:
            return bin_edges, bin_centres, N