Exemplo n.º 1
0
def plot_ts_pub(ts,
                xlabel=r'\textit{time} (day)',
                ylabel=r'\textit(num of attacks)',
                legend='',
                title='',
                col='blue',
                lstyle='-',
                lw=2,
                marker='',
                outfile=None):
    # rcParams['figure.figsize'] = 15, 6
    rcParams.update(params)

    plt.plot(ts,
             color=col,
             label=legend,
             linestyle=lstyle,
             linewidth=lw,
             marker=marker)
    plt.xlabel(xlabel, fontsize=20)
    plt.ylabel(ylabel, fontsize=20)

    plt.legend(loc="upper left")
    # plt.title(title)
    if outfile is not None:
        plt.savefig(outfile, format="pdf")
    return plt
Exemplo n.º 2
0
def plot_momentum(output_path, name_list):

    # Plot parameters
    params = {
        "font.size": 12,
        "font.family": "Times",
        "text.usetex": True,
        "figure.figsize": (5, 4),
        "figure.subplot.left": 0.15,
        "figure.subplot.right": 0.95,
        "figure.subplot.bottom": 0.18,
        "figure.subplot.top": 0.9,
        "lines.markersize": 2,
        "lines.linewidth": 2.0,
    }
    rcParams.update(params)

    parttype_list = [0, 4]

    for parttype in parttype_list:

        plt.figure()
        ax = plt.subplot(1, 1, 1)
        if parttype == 4:
            ax.set_title("Stellar component")
            ylabel = "$j_{\mathrm{stars}}$ [kpc km/s]"

        if parttype == 0:
            ax.set_title("HI+H2 gas")
            ylabel = "$j_{\mathrm{gas}}$ [kpc km/s]"

        plt.grid("True")

        for i, name in enumerate(name_list):
            data = np.loadtxt(f"{output_path}/momentum_parttype_%i_" %
                              (parttype) + name + ".txt")

            # In case of no objects len(shape) = 1
            if len(np.shape(data)) > 1:
                plt.plot(data[:, 0],
                         data[:, 1],
                         "o",
                         color=color[i],
                         label=name)

        plt.xlabel("Stellar Mass [M$_{\odot}$]")
        plt.ylabel(ylabel)
        plt.yscale("log")
        plt.xscale("log")
        plt.xlim(1e6, 1e12)
        plt.ylim(1e-1, 1e4)
        ax.tick_params(direction="in", axis="both", which="both", pad=4.5)
        plt.legend(labelspacing=0.2,
                   handlelength=2,
                   handletextpad=0.4,
                   frameon=False)
        plt.savefig(f"{output_path}/momentum_parttype_%i.png" % parttype,
                    dpi=200)
        plt.close()
Exemplo n.º 3
0
def plot_simplex(points, names=('C1', 'C2'), proba_triplet=None):
    import matplotlib.pyplot as plt
    from matplotlib.lines import Line2D
    from matplotlib.pylab import rcParams

    def _project(points):
        from math import sqrt, sin, cos, pi
        p1, p2, p3 = points.T / sqrt(3)
        x = (p2 - p1) * cos(pi / 6) + 0.5
        y = p3 - (p1 + p2) * sin(pi / 6) + 1 / (2 * sqrt(3))
        return np.vstack((x, y)).T

    vert0 = _project(
        np.array([[0.3333, 0.3333, 0.3333], [0.5, 0.5, 0], [0.5, 0, 0.5],
                  [0, 0.5, 0.5]]))

    fig = plt.figure()
    fig.set_size_inches(8, 7)

    nl, ne, nr = np.max(points, axis=0)
    for i, n in enumerate((nl, ne, nr)):
        if n < 0.001:
            print("p{} is too small, switching to 2d plot".format(names[::-1] +
                                                                  ["rope"]))
            coords = sorted(set(range(3)) - i)
            return plot2d(points[:, coords], labels[coords])

    # triangle
    fig.gca().add_line(
        Line2D([0, 0.5, 1.0, 0], [0, np.sqrt(3) / 2, 0, 0], color='black'))
    # decision lines
    for i in (1, 2, 3):
        fig.gca().add_line(
            Line2D([vert0[0, 0], vert0[i, 0]], [vert0[0, 1], vert0[i, 1]],
                   color='black'))
    # vertex labels
    rcParams.update({'font.size': 16})
    fig.gca().text(-0.08,
                   -0.08,
                   'p({} ({}))'.format(names[0], proba_triplet[0]),
                   color='black')
    fig.gca().text(0.44, np.sqrt(3) / 2 + 0.05, 'p(rope)', color='black')
    fig.gca().text(0.650,
                   -0.08,
                   'p({} ({}))'.format(names[1], proba_triplet[2]),
                   color='black')

    # project and draw points
    tripts = _project(points[:, [0, 2, 1]])
    plt.hexbin(tripts[:, 0], tripts[:, 1], mincnt=1, cmap=plt.cm.Greens_r)
    # Leave some padding around the triangle for vertex labels
    fig.gca().set_xlim(-0.2, 1.2)
    fig.gca().set_ylim(-0.2, 1.2)
    fig.gca().axis('off')
    return fig
Exemplo n.º 4
0
def test_plot():
    params = {
        'axes.labelsize': 8,
        'text.fontsize': 8,
        'legend.fontsize': 10,
        'xtick.labelsize': 10,
        'ytick.labelsize': 10,
        'text.usetex': False,
        'figure.figsize': [6.5, 4.0]
    }
    rcParams.update(params)
Exemplo n.º 5
0
def plot_simplex(points, names=('C1', 'C2')):
    import matplotlib.pyplot as plt
    from matplotlib.lines import Line2D
    from matplotlib.pylab import rcParams

    def _project(points):
        from math import sqrt, sin, cos, pi
        p1, p2, p3 = points.T / sqrt(3)
        x = (p2 - p1) * cos(pi / 6) + 0.5
        y = p3 - (p1 + p2) * sin(pi / 6) + 1 / (2 * sqrt(3))
        return np.vstack((x, y)).T 

    vert0 = _project(np.array(
        [[0.3333, 0.3333, 0.3333], [0.5, 0.5, 0], [0.5, 0, 0.5], [0, 0.5, 0.5]]))

    fig = plt.figure()
    fig.set_size_inches(8, 7)  
    
    nl, ne, nr = np.max(points, axis=0)
    for i, n in enumerate((nl, ne, nr)):
        if n < 0.001:
            print("p{} is too small, switching to 2d plot".format(names[::-1] + ["rope"]))
            coords = sorted(set(range(3)) - i)
            return plot2d(points[:, coords], labels[coords])

    # triangle
    fig.gca().add_line(
        Line2D([0, 0.5, 1.0, 0],
               [0, np.sqrt(3) / 2, 0, 0], color='orange'))
    # decision lines
    for i in (1, 2, 3):
        fig.gca().add_line(
            Line2D([vert0[0, 0], vert0[i, 0]],
                   [vert0[0, 1], vert0[i, 1]], color='orange'))
    # vertex labels
    rcParams.update({'font.size': 16})
    fig.gca().text(-0.08, -0.08, 'p({})'.format(names[0]), color='orange')
    fig.gca().text(0.44, np.sqrt(3) / 2 + 0.05, 'p(rope)', color='orange')
    fig.gca().text(1.00, -0.08, 'p({})'.format(names[1]), color='orange')

    # project and draw points
    tripts = _project(points[:, [0, 2, 1]])
    plt.hexbin(tripts[:, 0], tripts[:, 1], mincnt=1, cmap=plt.cm.Blues_r)            
    # Leave some padding around the triangle for vertex labels
    fig.gca().set_xlim(-0.2, 1.2)
    fig.gca().set_ylim(-0.2, 1.2)
    fig.gca().axis('off')
    return fig
def matplot_settings():
    from matplotlib.pylab import rcParams
    rcParams['figure.figsize'] = 4,4
    pgf_with_xelatex = {
        'text.usetex': True,
        'text.latex.unicode': True,
        'pgf.rcfonts': False,
        'font.family': 'sans-serif',
        "pgf.texsystem": "xelatex",
        "pgf.preamble": [
            r"\usepackage{amssymb}",
            r"\usepackage{amsmath}",
            r"\usepackage{fontspec}",
            r"\setmainfont{Gentium Book Basic}",
            r"\setsansfont{Open Sans Light}",
            r"\usepackage{unicode-math}",
            r"\setmathfont{TeX Gyre Termes Math}"
        ]
    }
    rcParams.update(pgf_with_xelatex)
Exemplo n.º 7
0
def plot_surface_densities(sigma_SFR, sigma_gas, sigma_H2, stellar_mass,
                           MorphologyPlotsInWeb, output_path):

    # Get the default KS relation for correct IMF
    def KS(sigma_g, n, A):
        return A * sigma_g**n

    Sigma_g = np.logspace(-2, 3, 1000)
    Sigma_star = KS(Sigma_g, 1.4, 1.515e-4)

    # Plot parameters
    params = {
        "font.size": 12,
        "font.family": "Times",
        "text.usetex": True,
        "figure.figsize": (5.5, 4),
        "figure.subplot.left": 0.15,
        "figure.subplot.right": 0.85,
        "figure.subplot.bottom": 0.18,
        "figure.subplot.top": 0.9,
        "lines.markersize": 4,
        "lines.linewidth": 2.0,
    }
    rcParams.update(params)

    fig = plt.figure()
    ax = plt.subplot(1, 1, 1)
    plt.grid("True")

    plt.plot(
        np.log10(Sigma_g),
        np.log10(Sigma_star),
        "--",
        color="grey",
        label=r"1.51e-4 $\times$ $\Sigma_{g}^{1.4}$",
    )
    plt.scatter(
        sigma_H2,
        sigma_SFR,
        c=stellar_mass,
        alpha=0.9,
        s=25,
        vmin=6,
        vmax=10,
        cmap="CMRmap_r",
        edgecolors="none",
        zorder=2,
    )

    plt.xlabel("log $\\Sigma_{H_2}$  $[{\\rm M_\\odot\\cdot pc^{-2}}]$")
    plt.ylabel(
        "log $\\Sigma_{\\rm SFR}$ $[{\\rm M_\\odot \\cdot yr^{-1} \\cdot kpc^{-2}}]$"
    )
    plt.xlim(-1.0, 3.0)
    plt.ylim(-6.0, 0.0)

    plt.legend()
    cbar_ax = fig.add_axes([0.87, 0.18, 0.018, 0.5])
    cbar_ax.tick_params(labelsize=15)
    cb = plt.colorbar(ticks=[6, 7, 8, 9, 10, 11, 12], cax=cbar_ax)
    cb.set_label(label="$\log_{10}$ M$_{*}$/M$_{\odot}$", labelpad=0.5)
    ax.tick_params(direction="in", axis="both", which="both", pad=4.5)
    plt.savefig(f"{output_path}/surface_density_gas.png", dpi=200)
    plt.close()

    title = "$\\Sigma_{H_2}$ vs $\\Sigma_{\\rm SFR}$"
    caption = "Integrated surface densities of H2 gas and star-forming gas for each individual galaxy. "
    caption += "Quantities are calculated summing up all gas (and SFR) within the galaxies' stellar half mass radius."
    filename = "surface_density_gas.png"
    id = abs(hash("surface_density_gas"))

    MorphologyPlotsInWeb.load_plots(title, caption, filename, id)

    #######
    fig = plt.figure()
    ax = plt.subplot(1, 1, 1)
    plt.grid("True")

    plt.plot(
        np.log10(Sigma_g),
        np.log10(Sigma_star),
        "--",
        color="grey",
        label=r"1.51e-4 $\times$ $\Sigma_{g}^{1.4}$",
    )
    plt.scatter(
        sigma_gas,
        sigma_SFR,
        c=stellar_mass,
        alpha=0.9,
        s=25,
        vmin=6,
        vmax=10,
        cmap="CMRmap_r",
        edgecolors="none",
        zorder=2,
    )

    plt.xlabel(
        "log $\\Sigma_{HI}+ \\Sigma_{H_2}$  $[{\\rm M_\\odot\\cdot pc^{-2}}]$")
    plt.ylabel(
        "log $\\Sigma_{\\rm SFR}$ $[{\\rm M_\\odot \\cdot yr^{-1} \\cdot kpc^{-2}}]$"
    )
    plt.xlim(-1.0, 3.0)
    plt.ylim(-6.0, 0.0)
    plt.legend()
    cbar_ax = fig.add_axes([0.87, 0.18, 0.018, 0.5])
    cbar_ax.tick_params(labelsize=15)
    cb = plt.colorbar(ticks=[6, 7, 8, 9, 10, 11, 12], cax=cbar_ax)
    cb.set_label(label="$\log_{10}$ M$_{*}$/M$_{\odot}$", labelpad=0.5)
    ax.tick_params(direction="in", axis="both", which="both", pad=4.5)
    plt.savefig(f"{output_path}/surface_density_H2.png", dpi=200)
    plt.close()

    caption = "Integrated surface densities of H2+HI gas and star-forming gas for each individual galaxy. "
    caption += "Quantities are calculated summing up all gas (and SFR) within the galaxies' stellar half mass radius."
    filename = "surface_density_H2.png"
    id = abs(hash("surface_density_H2"))

    MorphologyPlotsInWeb.load_plots(title, caption, filename, id)
Exemplo n.º 8
0
def survival_plots(SAVE_PATH, KM_FILE_NAME, rules, lifelinesModels):
    # generate pdf with survival model (all rules) and each rule (vs cmp and pop)
    print('> generating plots')

    def get_RuleString(rule_id, rule_dict):
        return '{}: '.format(rule_id) + ' and '.join([
            '<{}={}>'.format(str(attr),
                             str(val).replace('.0', ''))
            for (attr, val) in rule_dict.items()
        ])

    pdf = matplotlib.backends.backend_pdf.PdfPages(SAVE_PATH)  # .pdf file

    # Final rule-model figure
    rcParams.update({'font.size': 14})
    rcParams['figure.figsize'] = 15, 10

    plt.figure(num='ruleModel')
    ax = plt.subplot(111)

    kmModels = pd.read_csv(KM_FILE_NAME, header=0)
    x = kmModels.times.values
    columns = list(kmModels.columns)
    columns.remove('times')
    for column in columns:
        if column == "population":
            ax.plot(x,
                    kmModels[column],
                    color='k',
                    label='{}'.format(column),
                    linestyle=':')
        else:
            ax.plot(x, kmModels[column], label='{}'.format(column))

    plt.title('Rule-Set (subgroups) Survival Models')
    plt.tight_layout(pad=1.25)
    plt.xlabel('Time')
    plt.xlim(0, x[-1] + 3)
    plt.xticks([])
    plt.ylabel('Survival probability')
    plt.yticks([0, 0.2, 0.4, 0.6, 0.8, 1])
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    plt.legend(frameon=False, bbox_to_anchor=(1.01, 1), loc=2)
    pdf.savefig(plt.figure(num='ruleModel'), bbox_inches='tight')
    plt.close(fig='ruleModel')

    # Individual rules
    n_rows = math.ceil(len(rules) / 2)
    rcParams['figure.figsize'] = 15, 3 * n_rows
    rcParams['axes.titlesize'] = 11

    #plt.figure(num='indiv_rules')
    fig, axes = plt.subplots(nrows=n_rows,
                             ncols=2,
                             sharex=True,
                             sharey=True,
                             num='indiv_rules')
    ax_id = 0

    for rule_id in rules.keys():

        ax = axes.flatten()[ax_id]
        ax_id += 1

        lifelinesModels['population'].plot(ax=ax, ci_show=False, c='k', ls=':')
        lifelinesModels[rule_id]['sg'].plot(ax=ax,
                                            ci_show=False,
                                            c='firebrick')
        lifelinesModels[rule_id]['cmp'].plot(ax=ax,
                                             ci_show=False,
                                             c='tab:blue')

        ax.set_title(get_RuleString(rule_id, rules[rule_id]), loc='left')
        ax.set_xlabel('Time')
        ax.set_ylabel('Survival probability')
        ax.set_ylim([0, 1])
        ax.set_xlim([0, x[-1] + 3])
        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)
        ax.legend(frameon=False, bbox_to_anchor=(1.01, 1), loc=2)
        plt.tight_layout(pad=1.25)
        plt.xticks([])

    for i in range(ax_id, 2 * n_rows):
        fig.delaxes(axes.flatten()[i])

    pdf.savefig(plt.figure(num='indiv_rules'), bbox_inches='tight')
    plt.close(fig='indiv_rules')
    pdf.close()
    return
Exemplo n.º 9
0
def plot_galaxy_parts(partsDATA, parttype, ang_momentum, halo_data, index,
                      output_path, simulation_name):

    # Plot ranges
    r_limit = 5 * halo_data.half_mass_radius_star[index]
    r_img = 30.0
    if r_limit < r_img:
        r_img = r_limit
    xmin = -r_img
    ymin = -r_img
    xmax = r_img
    ymax = r_img

    pos_parts = partsDATA[:, 0:3].copy()
    face_on_rotation_matrix = rotation_matrix_from_vector(ang_momentum,
                                                          axis="z")
    edge_on_rotation_matrix = rotation_matrix_from_vector(ang_momentum,
                                                          axis="y")

    pos_face_on = np.matmul(face_on_rotation_matrix, pos_parts.T)
    pos_face_on = pos_face_on.T
    pos_edge_on = np.matmul(edge_on_rotation_matrix, pos_parts.T)
    pos_edge_on = pos_edge_on.T

    if parttype == 0:
        density = np.log10(partsDATA[:, 11])
    if parttype == 4:
        density = np.log10(partsDATA[:, 8])

    # Sort particles for better viewing
    arg_sort = np.argsort(density)
    density = density[arg_sort]
    pos_face_on = pos_face_on[arg_sort, :]
    pos_edge_on = pos_edge_on[arg_sort, :]

    denmin = np.min(density)
    denmax = np.max(density)

    rcParams.update(params)
    fig = plt.figure()
    ax = plt.subplot(1, 2, 1)

    if parttype == 4:
        title = "Stellar component"
    if parttype == 0:
        title = "Gas component"

    ax.set_title(title)
    ax.tick_params(labelleft=True, labelbottom=True, length=0)
    plt.xlabel("x [kpc]")
    plt.ylabel("y [kpc]")
    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax)

    plt.scatter(
        pos_face_on[:, 0],
        pos_face_on[:, 1],
        c=density,
        alpha=1,
        s=10,
        vmin=denmin,
        vmax=denmax,
        cmap="magma",
        edgecolors="none",
    )
    ax.autoscale(False)

    ax = plt.subplot(1, 2, 2)
    if parttype == 4:
        kappa = halo_data.kappa_co[index]
        mass = halo_data.log10_stellar_mass[index]
        ac = halo_data.axis_ca[index]
        cb = halo_data.axis_cb[index]
        ba = halo_data.axis_ba[index]
        radius = halo_data.half_mass_radius_star[index]
        title = r" $\kappa_{\mathrm{co}} = $%0.2f" % (kappa)
        title += " - $\log_{10}$ $M_{*}/M_{\odot} = $%0.2f" % (mass)
        title += " \n c/a = %0.2f," % (ac)
        title += " c/b = %0.2f," % (cb)
        title += " b/a = %0.2f" % (ba)
        title += "\n Stellar half mass radius %0.2f kpc" % (radius)
    if parttype == 0:
        kappa = halo_data.gas_kappa_co[index]
        mass = halo_data.log10_gas_mass[index]
        ac = halo_data.gas_axis_ca[index]
        cb = halo_data.gas_axis_cb[index]
        ba = halo_data.gas_axis_ba[index]
        radius = halo_data.half_mass_radius_star[index]
        title = r" $\kappa_{\mathrm{co}} = $%0.2f" % (kappa)
        title += " - $\log_{10}$ $M_{gas}/M_{\odot} = $%0.2f" % (mass)
        title += " \n c/a = %0.2f," % (ac)
        title += " c/b = %0.2f," % (cb)
        title += " b/a = %0.2f" % (ba)
        title += "\n Stellar half mass radius %0.2f kpc" % (radius)
    ax.set_title(title)

    ax.tick_params(labelleft=True, labelbottom=True, length=0)
    plt.xlabel("x [kpc]")
    plt.ylabel("z [kpc]")
    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax)

    plt.scatter(
        pos_edge_on[:, 0],
        pos_edge_on[:, 1],
        c=density,
        alpha=1,
        s=10,
        vmin=denmin,
        vmax=denmax,
        cmap="magma",
        edgecolors="none",
    )

    ax.autoscale(False)

    cbar_ax = fig.add_axes([0.86, 0.22, 0.018, 0.5])
    cbar_ax.tick_params(labelsize=15)
    cb = plt.colorbar(ticks=[4, 6, 8, 10], cax=cbar_ax)
    cb.set_label(label=r"$\log_{10}$ $\rho$ [M$_{\odot}$/kpc$^{3}$]",
                 labelpad=0.5)

    if parttype == 4:
        outfile = (f"{output_path}/galaxy_sparts_%i_" % (index) +
                   simulation_name + ".png")
    if parttype == 0:
        outfile = f"{output_path}/galaxy_parts_%i_" % (
            index) + simulation_name + ".png"
    fig.savefig(outfile, dpi=150)
    plt.close("all")
Exemplo n.º 10
0
def render_luminosity_map(
    parts_data,
    luminosity,
    filtname,
    ang_momentum,
    halo_data,
    index,
    output_path,
    simulation_name,
):
    pos_parts = parts_data[:, 0:3].copy()

    face_on_rotation_matrix = rotation_matrix_from_vector(ang_momentum)
    edge_on_rotation_matrix = rotation_matrix_from_vector(ang_momentum,
                                                          axis="y")

    pos_face_on = np.matmul(face_on_rotation_matrix, pos_parts.T)
    pos_face_on = pos_face_on.T
    pos_edge_on = np.matmul(edge_on_rotation_matrix, pos_parts.T)
    pos_edge_on = pos_edge_on.T

    hsml_parts = parts_data[:, 7]

    r_limit = 5 * halo_data.half_mass_radius_star[index]
    r_img = 30.0
    if r_limit < r_img:
        r_img = r_limit
    xmin = -r_img
    ymin = -r_img
    xmax = r_img
    ymax = r_img

    rcParams.update(params)
    fig = plt.figure()
    ax = plt.subplot(1, 2, 1)

    ###### plot one side ########################
    qv = QuickView(
        pos_face_on,
        mass=luminosity,
        hsml=hsml_parts,
        logscale=True,
        plot=False,
        r="infinity",
        p=0,
        t=0,
        extent=[xmin, xmax, ymin, ymax],
        x=0,
        y=0,
        z=0,
    )
    img = qv.get_image()
    ext = qv.get_extent()
    ax.tick_params(labelleft=True, labelbottom=True, length=0)
    plt.xlabel("x [kpc]")
    plt.ylabel("y [kpc]")
    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax)
    img = get_normalized_image(img, vmin=img.max() - 2.3)
    ax.imshow(img, cmap="magma", extent=ext, vmin=img.max() - 2.3)
    ax.autoscale(False)

    ###### plot another side ########################
    ax = plt.subplot(1, 2, 2)
    qv = QuickView(
        pos_edge_on,
        mass=luminosity,
        hsml=hsml_parts,
        logscale=True,
        plot=False,
        r="infinity",
        p=90,
        t=0,
        extent=[xmin, xmax, ymin, ymax],
        x=0,
        y=0,
        z=0,
    )
    img = qv.get_image()
    ext = qv.get_extent()
    ax.tick_params(labelleft=True, labelbottom=True, length=0)
    plt.xlabel("x [kpc]")
    plt.ylabel("z [kpc]")
    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax)
    img = get_normalized_image(img, vmin=img.max() - 2.3)
    ims = ax.imshow(img, cmap="magma", vmin=img.max() - 2.3, extent=ext)
    ax.autoscale(False)

    cbar_ax = fig.add_axes([0.86, 0.22, 0.018, 0.5])
    cbar_ax.tick_params(labelsize=15)
    cb = plt.colorbar(ims, ticks=[4, 6, 8, 10, 12], cax=cbar_ax)
    cb.set_label(label=r"$\log_{10}$ $\Sigma$ [Jy/kpc$^{2}$]", labelpad=0.5)

    outfile = (f"{output_path}/galaxy_%s_map_%i_" % (filtname, index) +
               simulation_name + ".png")
    fig.savefig(outfile, dpi=150)
    plt.close("all")

    return
Exemplo n.º 11
0
def plot_integrated_surface_densities(sigma_SFR, sigma_gas, sigma_H2,
                                      stellar_mass, output_path,
                                      simulation_name):
    # Plot parameters
    params = {
        "font.size": 12,
        "font.family": "Times",
        "text.usetex": True,
        "figure.figsize": (5.5, 4),
        "figure.subplot.left": 0.15,
        "figure.subplot.right": 0.85,
        "figure.subplot.bottom": 0.18,
        "figure.subplot.top": 0.9,
        "lines.markersize": 4,
        "lines.linewidth": 2.0,
    }

    # Get the default KS relation for correct IMF
    def KS(sigma_g, n, A):
        return A * sigma_g**n

    Sigma_g = np.logspace(-2, 3, 1000)
    Sigma_star = KS(Sigma_g, 1.4, 1.515e-4)

    rcParams.update(params)

    fig = plt.figure()
    ax = plt.subplot(1, 1, 1)
    plt.grid("True")

    plt.plot(
        np.log10(Sigma_g),
        np.log10(Sigma_star),
        "--",
        color="grey",
        label=r"1.51e-4 $\times$ $\Sigma_{\rm g}^{1.4}$",
    )
    plt.scatter(
        sigma_H2,
        sigma_SFR,
        c=stellar_mass,
        alpha=0.9,
        s=25,
        vmin=6,
        vmax=10,
        cmap="CMRmap_r",
        edgecolors="none",
        zorder=2,
    )

    plt.xlabel("log $\\Sigma_{\\rm H_2}$  $[{\\rm M_\\odot\\cdot pc^{-2}}]$")
    plt.ylabel(
        "log $\\Sigma_{\\rm SFR}$ $[{\\rm M_\\odot \\cdot yr^{-1} \\cdot kpc^{-2}}]$"
    )
    plt.xlim(-1.0, 4.0)
    plt.ylim(-6.0, 1.0)

    plt.legend()
    cbar_ax = fig.add_axes([0.87, 0.18, 0.018, 0.5])
    cbar_ax.tick_params(labelsize=15)
    cb = plt.colorbar(ticks=[6, 7, 8, 9, 10, 11, 12], cax=cbar_ax)
    cb.set_label(label="$\log_{10}$ M$_{*}$/M$_{\odot}$", labelpad=0.5)
    ax.tick_params(direction="in", axis="both", which="both", pad=4.5)
    plt.savefig(f"{output_path}/surface_density_gas_" + simulation_name +
                ".png",
                dpi=200)
    plt.close()

    #######
    fig = plt.figure()
    ax = plt.subplot(1, 1, 1)
    plt.grid("True")

    plt.plot(
        np.log10(Sigma_g),
        np.log10(Sigma_star),
        "--",
        color="grey",
        label=r"1.51e-4 $\times$ $\Sigma_{\rm g}^{1.4}$",
    )
    plt.scatter(
        sigma_gas,
        sigma_SFR,
        c=stellar_mass,
        alpha=0.9,
        s=25,
        vmin=6,
        vmax=10,
        cmap="CMRmap_r",
        edgecolors="none",
        zorder=2,
    )

    plt.xlabel(
        "log $\\Sigma_{\\rm HI}+ \\Sigma_{\\rm H_2}$  $[{\\rm M_\\odot\\cdot pc^{-2}}]$"
    )
    plt.ylabel(
        "log $\\Sigma_{\\rm SFR}$ $[{\\rm M_\\odot \\cdot yr^{-1} \\cdot kpc^{-2}}]$"
    )
    plt.xlim(-1.0, 4.0)
    plt.ylim(-6.0, 1.0)
    plt.legend()
    cbar_ax = fig.add_axes([0.87, 0.18, 0.018, 0.5])
    cbar_ax.tick_params(labelsize=15)
    cb = plt.colorbar(ticks=[6, 7, 8, 9, 10, 11, 12], cax=cbar_ax)
    cb.set_label(label="$\log_{10}$ M$_{*}$/M$_{\odot}$", labelpad=0.5)
    ax.tick_params(direction="in", axis="both", which="both", pad=4.5)
    plt.savefig(f"{output_path}/surface_density_H2_" + simulation_name +
                ".png",
                dpi=200)
    plt.close()
Exemplo n.º 12
0
def plot_combined_surface_densities(combined_data, output_path,
                                    simulation_name):

    # Get the default KS relation for correct IMF
    def KS(sigma_g, n, A):
        return A * sigma_g**n

    # Plot parameters
    params = {
        "font.size": 12,
        "font.family": "Times",
        "text.usetex": True,
        "figure.figsize": (5.5, 4),
        "figure.subplot.left": 0.15,
        "figure.subplot.right": 0.85,
        "figure.subplot.bottom": 0.18,
        "figure.subplot.top": 0.9,
        "lines.markersize": 2,
        "lines.linewidth": 2.0,
    }
    rcParams.update(params)

    sigma_SFR = combined_data.SFR_surface_density
    metals = combined_data.gas_metallicity
    metals[metals == 0] = 1e-6
    metals = np.log10(np.array(metals, dtype="float"))
    arg_sort = np.argsort(metals)
    metals = metals[arg_sort[::-1]]
    sigma_SFR = sigma_SFR[arg_sort[::-1]]

    for plot in ["gas", "H2"]:

        # star formation rate surgface density vs surface density
        fig = plt.figure()
        ax = plt.subplot(1, 1, 1)
        plt.grid("True")

        Sigma_g = np.logspace(-2, 3, 1000)
        Sigma_star = KS(Sigma_g, 1.4, 1.515e-4)
        plt.plot(
            np.log10(Sigma_g),
            np.log10(Sigma_star),
            "--",
            color="grey",
            label=r"1.51e-4 $\times$ $\Sigma_{\rm g}^{1.4}$",
        )
        Sigma_g = np.logspace(-1, 4, 1000)
        Sigma_star = KS(Sigma_g, 1.06, 2.511e-4)
        plt.plot(
            np.log10(Sigma_g),
            np.log10(Sigma_star),
            lw=1,
            color="green",
            label=r"2.51e-4 $\times$ $\Sigma_{\rm g}^{1.06}$ (Pessa+ 2021)",
            linestyle="-",
        )

        if plot == "gas":
            sigma_gas = combined_data.neutral_gas_surface_density
            t_gas = combined_data.depletion_time_neutral_gas
        else:
            sigma_gas = combined_data.molecular_gas_surface_density
            t_gas = combined_data.depletion_time_molecular_gas

        sigma_gas = sigma_gas[arg_sort[::-1]]
        t_gas = t_gas[arg_sort[::-1]]

        plt.scatter(
            sigma_gas,
            sigma_SFR,
            c=metals,
            alpha=0.9,
            s=10,
            vmin=-3,
            vmax=1,
            cmap="CMRmap_r",
            edgecolors="none",
            zorder=2,
        )

        select = np.where((metals > -1.2) & (metals < -0.8))[0]
        x, y, y_down, y_up = median_relations(sigma_gas[select],
                                              sigma_SFR[select])
        plt.plot(x, y, "-", lw=2, color="white")
        plt.plot(
            x,
            y,
            "-",
            lw=1.5,
            color="crimson",
            label="log Z$_{\mathrm{gas}}$/Z$_{\odot}$=-1",
        )

        select = np.where((metals > -0.2) & (metals < 0.2))[0]
        x, y, y_down, y_up = median_relations(sigma_gas[select],
                                              sigma_SFR[select])
        plt.plot(x, y, "-", lw=2, color="white")
        plt.plot(
            x,
            y,
            "-",
            lw=1.5,
            color="mediumpurple",
            label="log Z$_{\mathrm{gas}}$/Z$_{\odot}$=0",
        )

        select = np.where(metals > 0.6)[0]
        x, y, y_down, y_up = median_relations(sigma_gas[select],
                                              sigma_SFR[select])
        plt.plot(x, y, "-", lw=2, color="white")
        plt.plot(
            x,
            y,
            "-",
            lw=1.5,
            color="lightblue",
            label="log Z$_{\mathrm{gas}}$/Z$_{\odot}$=1",
        )

        x, y, y_down, y_up = median_relations(sigma_gas, sigma_SFR)
        plt.plot(x, y, "-", lw=2, color="white")
        plt.plot(x, y, "-", lw=1.5, color="grey", label="All")

        select = np.where(sigma_SFR > -5.5)[0]
        x, y, y_down, y_up = median_relations(sigma_gas[select],
                                              sigma_SFR[select])
        plt.plot(x, y, "-", lw=2, color="white")
        plt.plot(x, y, "-", lw=1.5, color="black", label="star-forming")

        if plot == "gas":
            plt.xlabel(
                "log $\\Sigma_{\\rm HI} + \\Sigma_{\\rm H_2}$  $[{\\rm M_\\odot\\cdot pc^{-2}}]$"
            )
        else:
            plt.xlabel(
                "log $\\Sigma_{\\rm H_2}$  $[{\\rm M_\\odot\\cdot pc^{-2}}]$")

        plt.ylabel(
            "log $\\Sigma_{\\rm SFR}$ $[{\\rm M_\\odot \\cdot yr^{-1} \\cdot kpc^{-2}}]$"
        )
        plt.xlim(-1.0, 4.0)
        plt.ylim(-6.0, 1.0)
        plt.legend(
            loc=[0.0, 0.5],
            labelspacing=0.2,
            handlelength=1,
            handletextpad=0.2,
            frameon=False,
        )

        cbar_ax = fig.add_axes([0.87, 0.18, 0.018, 0.5])
        cbar_ax.tick_params(labelsize=15)
        cb = plt.colorbar(ticks=[-3, -2, -1, 0, 1], cax=cbar_ax)
        cb.set_label(label="log Z$_{\mathrm{gas}}$/Z$_{\odot}$", labelpad=0.5)
        ax.tick_params(direction="in", axis="both", which="both", pad=4.5)
        plt.savefig(
            f"{output_path}/combined_surface_density_{plot}_" +
            simulation_name + ".png",
            dpi=200,
        )
        plt.close()

        # Depletion time vs surface density
        fig = plt.figure()
        ax = plt.subplot(1, 1, 1)
        plt.grid("True")

        Sigma_g = np.logspace(-1, 4, 1000)
        Sigma_star = KS(Sigma_g, 1.4, 1.515e-4)
        plt.plot(
            np.log10(Sigma_g),
            np.log10(Sigma_g) - np.log10(Sigma_star) + 6.0,
            color="red",
            label="KS law (Kennicutt 98)",
            linestyle="--",
        )

        plt.scatter(
            sigma_gas,
            t_gas,
            c=metals,
            alpha=0.9,
            s=10,
            vmin=-3,
            vmax=1,
            cmap="CMRmap_r",
            edgecolors="none",
            zorder=2,
        )

        select = np.where((metals > -1.2) & (metals < -0.8))[0]
        x, y, y_down, y_up = median_relations(sigma_gas[select], t_gas[select])
        plt.plot(x, y, "-", lw=2, color="white")
        plt.plot(
            x,
            y,
            "-",
            lw=1.5,
            color="crimson",
            label="log Z$_{\mathrm{gas}}$/Z$_{\odot}$=-1",
        )

        select = np.where((metals > -0.2) & (metals < 0.2))[0]
        x, y, y_down, y_up = median_relations(sigma_gas[select], t_gas[select])
        plt.plot(x, y, "-", lw=2, color="white")
        plt.plot(
            x,
            y,
            "-",
            lw=1.5,
            color="mediumpurple",
            label="log Z$_{\mathrm{gas}}$/Z$_{\odot}$=0",
        )

        select = np.where(metals > 0.6)[0]
        x, y, y_down, y_up = median_relations(sigma_gas[select],
                                              sigma_SFR[select])
        plt.plot(x, y, "-", lw=2, color="white")
        plt.plot(
            x,
            y,
            "-",
            lw=1.5,
            color="lightblue",
            label="log Z$_{\mathrm{gas}}$/Z$_{\odot}$=1",
        )

        x, y, y_down, y_up = median_relations(sigma_gas, t_gas)
        plt.plot(x, y, "-", lw=2, color="white")
        plt.plot(x, y, "-", lw=1.5, color="grey", label="All")

        select = np.where(sigma_SFR > -5.5)[0]
        x, y, y_down, y_up = median_relations(sigma_gas[select], t_gas[select])
        plt.plot(x, y, "-", lw=2, color="white")
        plt.plot(x, y, "-", lw=1.5, color="black", label="star-forming")

        if plot == "gas":
            plt.xlabel(
                "log $\\Sigma_{\\rm HI} + \\Sigma_{\\rm H_2}$  $[{\\rm M_\\odot\\cdot pc^{-2}}]$"
            )
            plt.ylabel(
                "log $\\rm t_{gas} = (\\Sigma_{\\rm HI} + \\Sigma_{\\rm H_2})/ \\Sigma_{\\rm SFR}$ $[{\\rm yr }]$"
            )
        else:
            plt.xlabel(
                "log $\\Sigma_{\\rm H_2}$  $[{\\rm M_\\odot\\cdot pc^{-2}}]$")
            plt.ylabel(
                "log $\\rm t_{H_2} = \\Sigma_{\\rm H_2} / \\Sigma_{\\rm SFR}$ $[{\\rm yr }]$"
            )

        plt.xlim(-1, 4.0)
        plt.ylim(7, 12)
        plt.legend(
            loc=[0.0, 0.5],
            labelspacing=0.2,
            handlelength=1,
            handletextpad=0.2,
            frameon=False,
        )

        cbar_ax = fig.add_axes([0.87, 0.18, 0.018, 0.5])
        cbar_ax.tick_params(labelsize=15)
        cb = plt.colorbar(ticks=[-3, -2, -1, 0, 1], cax=cbar_ax)
        cb.set_label(label="log Z$_{\mathrm{gas}}$/Z$_{\odot}$", labelpad=0.5)
        ax.tick_params(direction="in", axis="both", which="both", pad=4.5)
        plt.savefig(
            f"{output_path}/depletion_time_combined_surface_density_{plot}_" +
            simulation_name + ".png",
            dpi=200,
        )
        plt.close()

    #######
    fig = plt.figure()
    ax = plt.subplot(1, 1, 1)
    plt.grid("True")

    sigma_gas = combined_data.neutral_gas_surface_density
    sigma_ratio = combined_data.H2_to_neutral_surface_density_ratio
    sigma_gas = sigma_gas[arg_sort[::-1]]
    sigma_ratio = sigma_ratio[arg_sort[::-1]]

    plt.scatter(
        sigma_gas,
        sigma_ratio,
        c=metals,
        alpha=0.9,
        s=5,
        vmin=-3,
        vmax=1,
        cmap="CMRmap_r",
        edgecolors="none",
        zorder=2,
        label="method:grid",
    )

    select = np.where((metals > -1.2) & (metals < -0.8))[0]
    x, y, y_down, y_up = median_relations(sigma_gas[select],
                                          sigma_ratio[select])
    plt.plot(x, y, "-", lw=2, color="white")
    plt.plot(
        x,
        y,
        "-",
        lw=1.5,
        color="crimson",
        label="log Z$_{\mathrm{gas}}$/Z$_{\odot}$=-1",
    )

    select = np.where((metals > -0.2) & (metals < 0.2))[0]
    x, y, y_down, y_up = median_relations(sigma_gas[select],
                                          sigma_ratio[select])
    plt.plot(x, y, "-", lw=2, color="white")
    plt.plot(
        x,
        y,
        "-",
        lw=1.5,
        color="mediumpurple",
        label="log Z$_{\mathrm{gas}}$/Z$_{\odot}$=0",
    )

    select = np.where(metals > 0.6)[0]
    x, y, y_down, y_up = median_relations(sigma_gas[select],
                                          sigma_ratio[select])
    plt.plot(x, y, "-", lw=2, color="white")
    plt.plot(
        x,
        y,
        "-",
        lw=1.5,
        color="lightblue",
        label="log Z$_{\mathrm{gas}}$/Z$_{\odot}$=1",
    )

    x, y, y_down, y_up = median_relations(sigma_gas, sigma_ratio)
    plt.plot(x, y, "-", lw=2, color="white")
    plt.plot(x, y, "-", lw=1.5, color="grey", label="All")

    sigma_gas = combined_data.radii_neutral_gas_surface_density
    sigma_ratio = combined_data.radii_H2_to_neutral_surface_density_ratio
    plt.plot(
        sigma_gas,
        sigma_ratio,
        "o",
        ms=4,
        alpha=0.5,
        color="tab:blue",
        label="method:annuli",
    )

    plt.xlabel(
        "log $\\Sigma_{\\rm HI} + \\Sigma_{\\rm H_2}$  $[{\\rm M_\\odot\\cdot pc^{-2}}]$"
    )
    plt.ylabel(
        r"log $\Sigma_{\mathrm{H2}} / (\Sigma_{\mathrm{HI}}+\Sigma_{\mathrm{H2}})$"
    )
    plt.xlim(-1.0, 4.0)
    plt.ylim(-8.0, 0.5)
    plt.legend(
        loc=[0.65, 0.0],
        labelspacing=0.2,
        handlelength=1,
        handletextpad=0.2,
        frameon=False,
    )

    cbar_ax = fig.add_axes([0.87, 0.18, 0.018, 0.5])
    cbar_ax.tick_params(labelsize=15)
    cb = plt.colorbar(ticks=[-3, -2, -1, 0, 1], cax=cbar_ax)
    cb.set_label(label="log Z$_{\mathrm{gas}}$/Z$_{\odot}$", labelpad=0.5)
    ax.tick_params(direction="in", axis="both", which="both", pad=4.5)
    plt.savefig(
        f"{output_path}/combined_surface_density_ratios_" + simulation_name +
        ".png",
        dpi=200,
    )
    plt.close()
Exemplo n.º 13
0
def surface_ratios_plots(output_path, index, name_list):

    # Load data from Schruba +2021
    SchrubaData = np.loadtxt("./plotter/obs_data/Schruba2011_data.txt",
                             usecols=(4, 5, 6))
    nonan = np.logical_and(
        np.isnan(SchrubaData[:, 0]) == False,
        np.isnan(SchrubaData[:, 1]) == False)
    Schruba_H1 = SchrubaData[nonan, 0]  # HI surface density [Msol / pc-2]
    Schruba_H2 = SchrubaData[nonan, 1]  # H2 surface density [Msol / pc-2]
    flags = SchrubaData[nonan, 2]
    select_flags = np.logical_or(flags == 1,
                                 flags == 0)  # Disregarding upper limits
    Schruba_H1 = Schruba_H1[select_flags]
    Schruba_H2 = Schruba_H2[select_flags]

    x_Schruba = np.log10(Schruba_H1 + Schruba_H2)
    y_Schruba = np.log10(Schruba_H2 / (Schruba_H1 + Schruba_H2))

    rcParams.update(params)

    methods = ["grid", "radii"]
    for method in methods:

        plt.figure()
        ax = plt.subplot(1, 1, 1)

        # Krumholz 2009 lines
        Sigma_neutral = np.arange(-1, 3, 0.2)
        RH2 = 1.0 / Krumholz_eq39(10**Sigma_neutral, 0.5)
        FH2 = np.log10(1.0 / (1.0 + RH2))
        plt.plot(Sigma_neutral,
                 FH2,
                 "--",
                 color="darkred",
                 label="Krumholz+ (2009): f = 0.5")
        RH2 = 1.0 / Krumholz_eq39(10**Sigma_neutral, 0.1)
        FH2 = np.log10(1.0 / (1.0 + RH2))
        plt.plot(Sigma_neutral,
                 FH2,
                 ":",
                 color="tab:red",
                 label="Krumholz+ (2009): f = 0.1")
        plt.plot(x_Schruba,
                 y_Schruba,
                 "o",
                 color="darkred",
                 label="Schruba+ (2011)")

        color = ["tab:blue", "tab:orange"]

        for i, name in enumerate(name_list):
            if method == "grid":
                data = np.loadtxt(f"{output_path}/Surface_density_ratio_" +
                                  method + "_%i_" % (index) + name + ".txt")
                Sigma_gas = data[:, 0]
                Sigma_ratio = data[:, 1]
                (
                    Median_Sigma_gas,
                    Median_Sigma_ratio,
                    Sigma_ratio_err_down,
                    Sigma_ratio_err_up,
                ) = median_relations(Sigma_gas, Sigma_ratio)
                plt.plot(Sigma_gas,
                         Sigma_ratio,
                         "o",
                         color=color[i],
                         alpha=0.6)
                plt.plot(Median_Sigma_gas,
                         Median_Sigma_ratio,
                         "-",
                         lw=2,
                         color="white")
                plt.plot(
                    Median_Sigma_gas,
                    Median_Sigma_ratio,
                    "-",
                    lw=1.2,
                    color=color[i],
                    label=name,
                )
                plt.fill_between(
                    Median_Sigma_gas,
                    Sigma_ratio_err_down,
                    Sigma_ratio_err_up,
                    alpha=0.2,
                    color=color[i],
                )
            if method == "radii":
                data1 = np.loadtxt(
                    f"{output_path}/Surface_density_ratio_radii_250pc_%i_" %
                    (index) + name + ".txt")
                data2 = np.loadtxt(
                    f"{output_path}/Surface_density_ratio_radii_800pc_%i_" %
                    (index) + name + ".txt")
                plt.plot(data1[:, 0],
                         data1[:, 1],
                         "o",
                         ms=4,
                         color=color[i],
                         alpha=0.2)
                plt.plot(data2[:, 0],
                         data2[:, 1],
                         "o",
                         ms=4,
                         color=color[i],
                         label=name)

        plt.xlim(-1.0, 4.0)
        plt.ylim(-8.0, 0.5)
        plt.ylabel(
            r"log $\Sigma_{\mathrm{H2}} / (\Sigma_{\mathrm{HI}}+\Sigma_{\mathrm{H2}})$"
        )
        plt.xlabel(
            r"log $\Sigma_{\mathrm{HI}}+\Sigma_{\mathrm{H2}}$  [M$_{\odot}$ pc$^{-2}$]"
        )
        plt.legend(
            loc="lower right",
            labelspacing=0.2,
            handlelength=2,
            handletextpad=0.4,
            frameon=False,
        )
        ax.tick_params(direction="in", axis="both", which="both", pad=4.5)
        plt.savefig(
            f"{output_path}/Surface_density_ratio_" + method + "_%i.png" %
            (index),
            dpi=200,
        )
        plt.close()
Exemplo n.º 14
0
def KS_relation_plots(output_path, index, name_list):

    # read the observational data for the KS relations
    observational_data = read_obs_data("./plotter/obs_data")

    # Get the default KS relation for correct IMF
    def KS(sigma_g, n, A):
        return A * sigma_g**n

    rcParams.update(params)
    methods = ["grid", "radii"]
    for method in methods:

        for mode in range(2):
            plt.figure()
            ax = plt.subplot(1, 1, 1)

            Sigma_g = np.logspace(-1, 4, 1000)
            Sigma_star = KS(Sigma_g, 1.4, 1.515e-4)
            plt.plot(
                np.log10(Sigma_g),
                np.log10(Sigma_star),
                color="red",
                label=r"1.51e-4 $\times$ $\Sigma_{g}^{1.4}$",
                linestyle="--",
            )

            Sigma_g = np.logspace(-1, 4, 1000)
            Sigma_star = KS(Sigma_g, 1.06, 2.511e-4)
            plt.plot(
                np.log10(Sigma_g),
                np.log10(Sigma_star),
                lw=1,
                color="green",
                label=r"2.51e-4 $\times$ $\Sigma_{g}^{1.06}$ (Pessa+ 2021)",
                linestyle="-",
            )

            # load the observational data
            if mode == 0:

                for ind, observation in enumerate(observational_data):
                    if observation.gas_surface_density is not None:
                        if observation.description == "Bigiel et al. (2008) inner":
                            data = observation.bin_data_KS(
                                np.arange(-1, 3, 0.25), 0.4)
                            plt.errorbar(
                                data[0],
                                data[1],
                                yerr=[data[2], data[3]],
                                fmt="v",
                                ms=6,
                                label=observation.description,
                                color="darkred",
                            )
                        elif observation.description == "Bigiel et al. (2010) outer":
                            data2 = observation.bin_data_KS(
                                np.arange(-1, 3, 0.25), 0.4)
                            plt.errorbar(
                                data2[0],
                                data2[1],
                                yerr=[data2[2], data2[3]],
                                fmt="o",
                                ms=6,
                                label=observation.description,
                                color="darkred",
                            )
                plt.xlabel(
                    "log $\\Sigma_{\\rm HI}+ \\Sigma_{\\rm H_2}$  $[{\\rm M_\\odot\\cdot pc^{-2}}]$"
                )

            elif mode == 1:

                for ind, observation in enumerate(observational_data):
                    if observation.gas_surface_density is not None:
                        if observation.description == "Bigiel et al. (2008) inner":
                            data = observation.bin_data_KS_molecular(
                                np.arange(-1, 3, 0.25), 0.4)
                            plt.errorbar(
                                data[0],
                                data[1],
                                yerr=[data[2], data[3]],
                                fmt="<",
                                ms=6,
                                label=observation.description,
                                color="darkred",
                            )
                plt.xlabel(
                    "log $\\Sigma_{\\rm H_2}$  $[{\\rm M_\\odot\\cdot pc^{-2}}]$"
                )

            color = ["tab:blue", "tab:orange"]

            for i, name in enumerate(name_list):
                if mode == 0:
                    data = np.loadtxt(f"{output_path}/KS_relation_best_" +
                                      method + "_%i_" % (index) + name +
                                      ".txt")
                elif mode == 1:
                    data = np.loadtxt(f"{output_path}/KS_molecular_relation_" +
                                      method + "_%i_" % (index) + name +
                                      ".txt")

                surface_density = data[:, 0]
                SFR_surface_density = data[:, 1]

                # Get median lines
                (
                    median_surface_density,
                    median_SFR_surface_density,
                    SFR_surface_density_err_down,
                    SFR_surface_density_err_up,
                ) = median_relations(surface_density, SFR_surface_density)

                plt.plot(surface_density,
                         SFR_surface_density,
                         "o",
                         color=color[i])
                plt.plot(
                    median_surface_density,
                    median_SFR_surface_density,
                    "-",
                    lw=2,
                    color="white",
                )
                plt.plot(
                    median_surface_density,
                    median_SFR_surface_density,
                    "-",
                    lw=1.2,
                    color=color[i],
                    label=name,
                )
                plt.fill_between(
                    median_surface_density,
                    SFR_surface_density_err_down,
                    SFR_surface_density_err_up,
                    alpha=0.2,
                    color=color[i],
                )

            plt.legend(
                loc="upper left",
                labelspacing=0.2,
                handlelength=1,
                handletextpad=0.2,
                frameon=False,
            )
            ax.tick_params(direction="in", axis="both", which="both", pad=4.5)
            plt.ylabel(
                "log $\\Sigma_{\\rm SFR}$ $[{\\rm M_\\odot \\cdot yr^{-1} \\cdot kpc^{-2}}]$"
            )
            plt.xlim(-1.0, 4.0)
            plt.ylim(-6.5, 1.0)
            if mode == 0:
                plt.savefig(
                    f"{output_path}/KS_relation_best_" + method + "_%i.png" %
                    (index),
                    dpi=200,
                )
                plt.close()
            elif mode == 1:
                plt.savefig(
                    f"{output_path}/KS_molecular_relation_" + method +
                    "_%i.png" % (index),
                    dpi=200,
                )
                plt.close()
Exemplo n.º 15
0
def plot_axis_ratios(output_path, name_list):

    # Plot parameters
    params = {
        "font.size": 12,
        "font.family": "Times",
        "text.usetex": True,
        "figure.figsize": (11, 3.5),
        "figure.subplot.left": 0.05,
        "figure.subplot.right": 0.95,
        "figure.subplot.bottom": 0.15,
        "figure.subplot.top": 0.9,
        "figure.subplot.wspace": 0.3,
        "figure.subplot.hspace": 0.3,
        "lines.markersize": 2,
        "lines.linewidth": 2.0,
    }
    rcParams.update(params)

    for title, parttype in zip(["HI+H2 gas", "Stellar component"], [0, 4]):

        ########
        plt.figure()
        ax = plt.subplot(1, 3, 1)
        ax.set_title(title)
        plt.grid("True")

        for i, name in enumerate(name_list):
            data = np.loadtxt(f"{output_path}/Axis_ratios_parttype_%i_" %
                              (parttype) + name + ".txt")

            # In case of no objects len(shape) = 1
            if len(np.shape(data)) > 1:
                plt.plot(data[:, 0],
                         data[:, 1],
                         "o",
                         color=color[i],
                         label=name)

        plt.xscale("log")
        plt.xlabel("Stellar Mass [M$_{\odot}$]")
        plt.ylabel("c/a")
        plt.xlim(1e6, 1e12)
        plt.ylim(0.0, 1.0)
        ax.tick_params(direction="in", axis="both", which="both", pad=4.5)

        ########
        ax = plt.subplot(1, 3, 2)
        plt.grid("True")

        for i, name in enumerate(name_list):
            data = np.loadtxt(f"{output_path}/Axis_ratios_parttype_%i_" %
                              (parttype) + name + ".txt")

            # In case of no objects len(shape) = 1
            if len(np.shape(data)) > 1:
                plt.plot(data[:, 0],
                         data[:, 2],
                         "o",
                         color=color[i],
                         label=name)

        plt.xscale("log")
        plt.xlabel("Stellar Mass [M$_{\odot}$]")
        plt.ylabel("c/b")
        plt.xlim(1e6, 1e12)
        plt.ylim(0.0, 1.0)
        ax.tick_params(direction="in", axis="both", which="both", pad=4.5)

        ########
        ax = plt.subplot(1, 3, 3)
        plt.grid("True")

        for i, name in enumerate(name_list):
            data = np.loadtxt(f"{output_path}/Axis_ratios_parttype_%i_" %
                              (parttype) + name + ".txt")

            # In case of no objects len(shape) = 1
            if len(np.shape(data)) > 1:
                plt.plot(data[:, 0],
                         data[:, 3],
                         "o",
                         color=color[i],
                         label=name)

        plt.xscale("log")
        plt.xlabel("Stellar Mass [M$_{\odot}$]")
        plt.ylabel("b/a")
        plt.xlim(1e6, 1e12)
        plt.ylim(0.0, 1.0)
        ax.tick_params(direction="in", axis="both", which="both", pad=4.5)
        plt.legend(labelspacing=0.2,
                   handlelength=2,
                   handletextpad=0.4,
                   frameon=False)
        plt.savefig(f"{output_path}/Axis_ratios_parttype_%i.png" % parttype,
                    dpi=200)
        plt.close()
Exemplo n.º 16
0
def plot_galaxy(parts_data, parttype, ang_momentum, halo_data, index,
                output_path, simulation_name):
    # partsDATA contains particles data and is structured as follow
    # [ (:3)Position[Mpc]: (0)X | (1)Y | (2)Z ]
    if parttype == 4:
        cmap = plt.cm.magma
    if parttype == 0:
        cmap = plt.cm.viridis

    pos_parts = parts_data[:, 0:3].copy()
    face_on_rotation_matrix = rotation_matrix_from_vector(ang_momentum,
                                                          axis="z")
    edge_on_rotation_matrix = rotation_matrix_from_vector(ang_momentum,
                                                          axis="y")

    pos_face_on = np.matmul(face_on_rotation_matrix, pos_parts.T)
    pos_face_on = pos_face_on.T
    pos_edge_on = np.matmul(edge_on_rotation_matrix, pos_parts.T)
    pos_edge_on = pos_edge_on.T

    hsml_parts = parts_data[:, 7]
    mass = parts_data[:, 3]

    r_limit = 5 * halo_data.half_mass_radius_star[index]
    r_img = 30.0
    if r_limit < r_img:
        r_img = r_limit
    xmin = -r_img
    ymin = -r_img
    xmax = r_img
    ymax = r_img

    rcParams.update(params)
    fig = plt.figure()
    ax = plt.subplot(1, 2, 1)

    if parttype == 4:
        title = "Stellar component"
    if parttype == 0:
        title = "HI+H2 gas"
    ax.set_title(title)

    ###### plot one side ########################
    qv = QuickView(
        pos_face_on,
        mass=mass,
        hsml=hsml_parts,
        logscale=True,
        plot=False,
        r="infinity",
        p=0,
        t=0,
        extent=[xmin, xmax, ymin, ymax],
        x=0,
        y=0,
        z=0,
    )
    img = qv.get_image()
    ext = qv.get_extent()
    ax.tick_params(labelleft=True, labelbottom=True, length=0)
    plt.xlabel("x [kpc]")
    plt.ylabel("y [kpc]")
    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax)
    img = get_normalized_image(img)
    ax.imshow(img, cmap=cmap, extent=ext)
    ax.autoscale(False)

    ###### plot another side ########################
    ax = plt.subplot(1, 2, 2)
    if parttype == 4:
        kappa = halo_data.kappa_co[index]
        mass_galaxy = halo_data.log10_stellar_mass[index]
        ac = halo_data.axis_ca[index]
        cb = halo_data.axis_cb[index]
        ba = halo_data.axis_ba[index]
        title = r" $\kappa_{\mathrm{co}} = $%0.2f" % (kappa)
        title += " - $\log_{10}$ $M_{*}/M_{\odot} = $%0.2f" % (mass_galaxy)
        title += " \n c/a = %0.2f," % (ac)
        title += " c/b = %0.2f," % (cb)
        title += " b/a = %0.2f" % (ba)
    if parttype == 0:
        kappa = halo_data.gas_kappa_co[index]
        mass_galaxy = halo_data.log10_gas_mass[index]
        ac = halo_data.gas_axis_ca[index]
        cb = halo_data.gas_axis_cb[index]
        ba = halo_data.gas_axis_ba[index]
        title = r" $\kappa_{\mathrm{co}} = $%0.2f" % (kappa)
        title += " - $\log_{10}$ $M_{gas}/M_{\odot} = $%0.2f" % (mass_galaxy)
        title += " \n c/a = %0.2f," % (ac)
        title += " c/b = %0.2f," % (cb)
        title += " b/a = %0.2f" % (ba)
    ax.set_title(title)

    qv = QuickView(
        pos_edge_on,
        mass=mass,
        hsml=hsml_parts,
        logscale=True,
        plot=False,
        r="infinity",
        p=0,
        t=0,
        extent=[xmin, xmax, ymin, ymax],
        x=0,
        y=0,
        z=0,
    )
    img = qv.get_image()
    ext = qv.get_extent()
    ax.tick_params(labelleft=True, labelbottom=True, length=0)
    plt.xlabel("x [kpc]")
    plt.ylabel("z [kpc]")
    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax)
    img = get_normalized_image(img)
    ims = ax.imshow(img, cmap=cmap, extent=ext)
    ax.autoscale(False)

    cbar_ax = fig.add_axes([0.86, 0.22, 0.018, 0.5])
    cbar_ax.tick_params(labelsize=15)
    cb = plt.colorbar(ims, ticks=[4, 6, 8, 10, 12], cax=cbar_ax)
    cb.set_label(label=r"$\log_{10}$ $\Sigma$ [M$_{\odot}$/kpc$^{2}$]",
                 labelpad=0.5)

    if parttype == 0:
        outfile = f"{output_path}/galaxy_gas_%i_" % (
            index) + simulation_name + ".png"
    if parttype == 4:
        outfile = f"{output_path}/galaxy_stars_%i_" % (
            index) + simulation_name + ".png"
    fig.savefig(outfile, dpi=150)
    plt.close("all")

    return
Exemplo n.º 17
0
import numpy as np
import pandas as pd
# Matplotlib for visualizing graphs
import matplotlib.pyplot as plt
from matplotlib.pylab import rcParams
# Sklearn for creating a dataset
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split

# Set parameters for plotting
params = {
    'axes.titlesize': 'xx-large',  # Set title size
    'axes.labelsize': 'x-large',  # Set label size
    'figure.figsize': (8, 6)  # Set a figure Size
}
rcParams.update(params)

# Sample size
#M = 200
# No. of input features
#n = 1
# Learning Rate
#l_r = 0.05
# Number of iterations for updates
#epochs = 51


#X, y = make_regression(n_samples=M, n_features=n, n_informative=n, n_targets=1, random_state=42, noise=10)
def plot_graph(X, y):
    # Plot the original set of datapoints
    _ = plt.scatter(X, y, alpha=0.8)
Exemplo n.º 18
0
from parameters import *
from plot import *
from sample import *

import sys, os, glob
from tqdm import tqdm

tqdm.monitor_interval = 0
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
from matplotlib.pylab import rcParams

rcParams.update({'figure.autolayout': True})
rcParams['figure.figsize'] = (15, 8)
plt.style.use('ggplot')
import seaborn as sns

sns.set()

EVENTS = [
    'Goals', 'Attempts', 'Corners', 'Fouls', 'Yellow cards',
    'Second yellow cards', 'Red cards', 'Substitutions', 'Free kicks',
    'Offsides', 'Hand balls', 'Penaltys'
]
NB_SAMPLES = 10

model = load_latest_model()