def animate_nearest_neighbour(self, **kwargs):
        # TODO: use custom jointplot
        bw_adjust = kwargs.setdefault("bw_adjust", 0.5)
        g = self.vis.show_nearest_neighbour(**kwargs)
        xlim = g.ax_joint.get_xlim()
        ylim = g.ax_joint.get_ylim()
        color = kwargs.pop("color", "Purple")
        color_rgb = colorConverter.to_rgb(color)
        colors = [
            sns.set_hls_values(color_rgb, l=l) for l in np.linspace(1, 0, 12)  # noqa
        ]
        # Make a colormap based off the plot color
        cmap = sns.blend_palette(colors, as_cmap=True)
        kwargs.setdefault("cmap", cmap)
        kwargs.setdefault("shade", True)
        marginal_kws = kwargs.pop("marginal_kws", dict())
        marginal_kws.update(bw_adjust=bw_adjust)
        marginal_kws.setdefault("color", color)
        marginal_kws.setdefault("shade", True)

        def init():
            g.ax_joint.clear()
            g.ax_marg_x.clear()
            g.ax_marg_y.clear()
            g.fig.suptitle(f"{0:>6.3f}")

        def animate(i):
            g.ax_joint.clear()
            g.ax_marg_x.clear()
            g.ax_marg_y.clear()
            x = self.sn.result.y[:, i]
            y = self.sn.get_nearest_neighbours(t=i)
            # drop nans
            not_na = pd.notnull(x) & pd.notnull(y)
            g.x = x[not_na]
            g.y = y[not_na]
            g.plot_joint(sns_kdeplot, **kwargs)
            g.plot_marginals(sns_kdeplot, **marginal_kws)

            # these are reset after .clear(); so go correct these as in joint_plot
            plt.setp(g.ax_marg_x.get_xticklabels(), visible=False)
            plt.setp(g.ax_marg_y.get_yticklabels(), visible=False)
            plt.setp(g.ax_marg_x.yaxis.get_majorticklines(), visible=False)
            plt.setp(g.ax_marg_x.yaxis.get_minorticklines(), visible=False)
            plt.setp(g.ax_marg_y.xaxis.get_majorticklines(), visible=False)
            plt.setp(g.ax_marg_y.xaxis.get_minorticklines(), visible=False)
            plt.setp(g.ax_marg_x.get_yticklabels(), visible=False)
            plt.setp(g.ax_marg_y.get_xticklabels(), visible=False)
            g.fig.suptitle(f"{self.sn.result.t[i]:>6.3f}", va="bottom")

        self.animations["nearest_neighbour"] = animation.FuncAnimation(
            g.fig,
            animate,
            init_func=init,
            frames=len(self.sn.result.t),
            repeat=False,
        )
Exemple #2
0
 def shade_under_PR_curves(self, ax: Axes):
     """
     Fill area under each PR-curve with a light shade. Plot shades with
     highest AUC at the bottom (i.e. first, most hidden).
     """
     tups = zip(self.threshold_sweeps, self.colors)
     tups = sorted(tups, key=lambda tup: rank_higher_AUC_lower(tup[0]))
     for sweep, color in tups:
         fc = set_hls_values(color, l=0.95)
         ax.fill_between(sweep.recall, sweep.precision, color=fc)
 def plot_mean(x, label, color="#2f2f2f"):
     for i, c in enumerate([column_1, column_2]):
         mean_speedup = data[data[identifier_column] == label][c].mean()
         plt.axvline(x=mean_speedup,
                     lw=1,
                     clip_on=True,
                     zorder=4,
                     linestyle="dotted",
                     ymax=0.25,
                     color=sns.set_hls_values(PALETTE[i], l=0.3))
 def set_hls_values(self_or_cls, h=None, l=None, s=None):
     "Independently manipulate the h, l, or s channels of all scheme colors."
     cls = self_or_cls if isinstance(self_or_cls,
                                     type) else type(self_or_cls)
     return cls(
         **{
             key: Cycle([
                 sns.set_hls_values(c, h=h, l=l, s=s) for c in cycle.values
             ]) if isinstance(cycle, Cycle) else sns.
             set_hls_values(cycle, h=h, l=l, s=s)
             for key, cycle in self_or_cls.iter_names_and_colors()
         })
 def plot_ci(x, label, color="#2f2f2f"):
     ax = plt.gca()
     y_max = 0.25 * ax.get_ylim()[1]
     for i, c in enumerate([column_1, column_2]):
         color = sns.set_hls_values(PALETTE[i], l=0.3)
         fillcolor = matplotlib.colors.to_rgba(
             color, alpha=0.2
         )  # Add alpha to facecolor, while leaving the border opaque;
         upper, lower, _ = get_ci_size(
             data[data[identifier_column] == label][c],
             get_raw_location=True)
         new_patch = Rectangle((lower, 0),
                               upper - lower,
                               y_max,
                               linewidth=1,
                               edgecolor=color,
                               facecolor=fillcolor,
                               zorder=4)
         ax.add_patch(new_patch)
Exemple #6
0
 def shade_under_PR_curves(self, ax):
     tups = zip(get_sweeps(), colors)
     tups = sorted(tups, key=lambda tup: rank_higher_AUC_lower(tup[0]))
     for sweep, color in tups:
         fc = set_hls_values(color, l=0.95)
         ax.fill_between(sweep.recall, sweep.precision, color=fc)
Exemple #7
0
def draw_bar(collected):
    fig = plt.figure(figsize=(4, 6), dpi=100)

    PHASES_LABELS = [
        "Generate input",
        "Learn network",
        "Validate solution",
    ]

    bar = plt.axes([0.13, 0.02, 0.15, 0.88])  # left, bottom, width, height
    bar.set_title("Phases of\nthe program", fontsize="large")
    bar.set_xlabel("", fontsize="large")
    bar.set_xlim(0, 1)
    bar.set_xticklabels([])
    bar.set_ylabel("Time (s)", fontsize="large")
    bars = []
    labels = []
    cumsum = collected["main_phases_cumsum"]
    s = collected["main_phases_sum"]
    #bar.set_yticks([0.0, 0.5, 1.0, 1.5, 2.0, 2.5])
    bar.set_ylim(s, 0)
    colors = [
        sns.crayons["Canary"], sns.crayons["Blue"], sns.crayons["Vivid Violet"]
    ]
    hatches = ["/", ".", ""]
    for i, t in enumerate(collected["main_phases"]):
        bars.append(
            bar.bar(0,
                    height=t,
                    bottom=cumsum[i],
                    width=1,
                    color=colors[i],
                    hatch=hatches[i],
                    edgecolor=sns.set_hls_values(colors[i], s=1.0, l=0)))
        labels.append("{} ({:.1%})".format(PHASES_LABELS[i], t / s))
    bar.legend(
        bars,
        labels,
        #loc=(-0.05, -0.15),
        #loc="lower center", bbox_to_anchor=(0.5, -0.15),
        loc=(1.0, 0.0),
        prop={"size": "large"})

    # width = 0.5*4 = 2.0
    # height = 2.0 = 0.33*6
    pie = plt.axes([0.43, 0.54, 0.5, 0.33])  # left, bottom, width, height
    pie.set_title("Time spent\nin transaction\n(in learning phase)",
                  fontsize="large")
    colors = [sns.crayons["Red Orange"], sns.crayons["Silver"]]
    tx = collected["transactional"]
    labels = [
        "Transactional ({:.1%})".format(tx[0] / sum(tx)),
        "Non-transactional ({:.1%})".format(tx[1] / sum(tx))
    ]
    patches, _texts = pie.pie(
        tx,
        #labels=labels,
        #labeldistance=0.1,
        colors=colors,
        startangle=90)
    patches[0].set_hatch("+")
    patches[0].set_edgecolor(sns.set_hls_values(colors[0], s=1.0, l=0))
    patches[1].set_hatch("x")
    patches[1].set_edgecolor(sns.set_hls_values(colors[1], s=0.0, l=0))
    pie.legend(patches,
               labels,
               loc="lower center",
               bbox_to_anchor=(0.5, -0.3),
               prop={"size": "large"})
    plt.savefig("bayes-bar.pdf", bbox_inches="tight")
Exemple #8
0
def main():
    """
    # Script to produce NH distribution plots for dark bursts.
    """
    # Read in burst list
    burst_table = pd.read_csv("../data/Burst list - CSV_master.csv")
    name, z, observed, OA, BAT, XRT, HI = burst_table["GRB"].values, burst_table["Redshift"].values, burst_table["Observed"].values, burst_table["Afterglow"].values, burst_table["BAT Fluence (15-150 keV) [10^-7 erg/cm^2]"].values.astype("float"), burst_table["XRT 11 Hour Flux (0.3-10 keV) [10^-11 erg/cm^2/s]"].values.astype("float"), burst_table["XRT Column Density (NH) [10^21 cm^-2]"].values.astype("float")
    # Bursts that are observed
    name_o = name[observed == "Yes"]
    BAT_o = BAT[observed == "Yes"]
    XRT_o = XRT[observed == "Yes"]
    HI_o = HI[observed == "Yes"]
    # Bursts that are not
    name_c = name[observed == "No"]
    BAT_c = BAT[observed == "No"]
    XRT_c = XRT[observed == "No"]
    HI_c = HI[observed == "No"]
    # Swift catalog
    swift_table = pd.read_table("../data/grb_table_1482495106.txt", delimiter="\t", dtype=None)
    name_s, BAT_s, XRT_s, HI_s = swift_table["GRB"].values, swift_table["BAT Fluence (15-150 keV) [10^-7 erg/cm^2]"].values, swift_table["XRT 11 Hour Flux (0.3-10 keV) [10^-11 erg/cm^2/s]"].values, swift_table["XRT Column Density (NH) [10^21 cm^-2]"].values

    # Greiner Table
    Greiner_table = pd.read_csv("../data/Burst list - Greiner Table.csv")
    name_g, inst, OT = Greiner_table["GRB"].values, Greiner_table["Instrument"].values, Greiner_table["OT"].values

    # Bursts with optical afterglows
    name_g_ot = name_g[(OT == "y") & (inst == "Swift")]
    idx_ot = [ii for ii, kk in enumerate(name_s) if kk in name_g_ot]
    BAT_ot = np.log10(1e-7*filt_nan(BAT_s[idx_ot]))
    XRT_ot = np.log10(1e-11*filt_nan(XRT_s[idx_ot]))
    HI_ot = np.log10(1e21*filt_nan(HI_s[idx_ot]))

    # Bursts without optical afterglows
    name_g_not = name_g[~(OT == "y") & (inst == "Swift")]
    idx_not = [ii for ii, kk in enumerate(name_s) if kk in name_g_not]
    BAT_not = np.log10(1e-7*filt_nan(BAT_s[idx_not]))
    XRT_not = np.log10(1e-11*filt_nan(XRT_s[idx_not]))
    HI_not = np.log10(1e21*filt_nan(HI_s[idx_not]))

    idx = [ii for ii, kk in enumerate(name_g) if kk in name_o]
    name_g_ot = name_g[idx][(OT[idx] == "y") & (inst[idx] == "Swift")]
    name_g_not = name_g[idx][~(OT[idx] == "y") & (inst[idx] == "Swift")]

    # print(idx)

    # print((len(name_g_not))/(len(name_g_ot) + len(name_g_not)))
    # exit()
    print(len(BAT_ot))
    mask_ot = (BAT_ot > -8) & (BAT_ot < -3) & (HI_ot > 19) & (HI_ot < 24)
    g = sns.JointGrid(x=BAT_ot[mask_ot], y=HI_ot[mask_ot], xlim = (-8, -3), ylim = (19, 24), space=0)
    g = g.plot_marginals(sns.distplot, hist=True, kde=False, norm_hist=True)
    # Import directly from Seaborn source to control
    color = sns.color_palette()[0]
    color_rgb = mpl.colors.colorConverter.to_rgb(color)
    colors = [sns.set_hls_values(color_rgb, l=l) for l in np.linspace(1, 0, 12)]
    cmap = sns.blend_palette(colors, as_cmap=True)
    x_bins = _freedman_diaconis_bins(g.x)
    y_bins = _freedman_diaconis_bins(g.y)
    gridsize = int(np.mean([x_bins, y_bins]))
    g = g.plot_joint(pl.hexbin, gridsize=gridsize, cmap=cmap)


    mask_not = (BAT_not > -8) & (BAT_not < -3) & (HI_not > 19) & (HI_not < 24)
    g.x = BAT_not[mask_not]
    g.y = HI_not[mask_not]
    g = g.plot_marginals(sns.distplot, hist=False)
    g = g.plot_joint(sns.kdeplot)

    print(stats.ks_2samp(HI_not[mask_not], HI_ot[mask_ot]))
    print(len(HI_not[mask_not]))
    l, m, h = np.percentile(HI_not[mask_not], [16, 50, 84])
    print(m, m - l, h - m)
    print(len(HI_ot[mask_ot]))
    l, m, h = np.percentile(HI_ot[mask_ot], [16, 50, 84])
    print(m, m - l, h - m)

    print("XRT KS")
    print(stats.ks_2samp(XRT_not[mask_not], XRT_ot[mask_ot]))
    print("BAT KS")
    print(stats.ks_2samp(BAT_not[mask_not], BAT_ot[mask_ot]))

    g.set_axis_labels(r"log(15-150 keV Fluence) [erg/cm$^2$]", r"log(N$_H$) [cm$^2$]")
    pl.tight_layout()


    # Save figure for tex
    pl.legend()
    pl.savefig("../document/figures/NH_dark.pdf", dpi="figure")
    pl.show()
def main():

    # Calculate initial progenitor seperation from eq 29 from Postnov and Yungelson 2014
    # Time since big bang
    t_constraint = 2970  #Myr
    # t_constraint = 1000 #Myr
    # Neutron star masses
    m1 = 1.4  # Msun
    m2 = 1.4  # Msun
    # Get seperation
    ratio = np.arange(0.5, 2, 0.01)
    masses = np.arange(0.9, 2.1, 0.01)
    xx, yy = np.meshgrid(masses, masses[::-1])
    a0 = calc_sep(t_constraint, xx, yy)

    color = sns.color_palette()[2]
    color_rgb = mpl.colors.colorConverter.to_rgb(color)
    colors = [
        sns.set_hls_values(color_rgb, l=l) for l in np.linspace(1, 0, 12)
    ]
    cmap = sns.blend_palette(colors, as_cmap=True)
    fig, ax = pl.subplots()
    im = ax.imshow(a0,
                   extent=[min(masses),
                           max(masses),
                           min(masses),
                           max(masses)],
                   cmap="viridis_r")
    cbar = pl.colorbar(im)
    cbar.set_label(r'$a_0$ [$R_\odot$]')

    from matplotlib.patches import Ellipse
    ax.scatter(1.33, 1.33, s=10, color="white")
    ax.add_artist(
        Ellipse((1.33, 1.33),
                1.33 - 1.21,
                1.43 - 1.33,
                fill=False,
                linestyle='dashed',
                lw=1,
                alpha=1.0,
                color="white"))
    ax.add_artist(
        Ellipse((1.33, 1.33),
                1.33 - 1.10,
                1.55 - 1.33,
                fill=False,
                linestyle='dashed',
                lw=1,
                alpha=0.7,
                color="white"))

    ax.set_xlabel(r"$M_{\mathrm{NS}}$ [$M_\odot$]")
    ax.set_ylabel(r"$M_{\mathrm{NS}}$ [$M_\odot$]")
    pl.tight_layout()
    pl.savefig("../figures/prog_sep.pdf")
    pl.show()

    a01 = calc_sep(t_constraint, 1.33, 1.33)
    print(a01)
    # 1-sigma
    a0 = calc_sep(t_constraint, 1.21, 1.21)
    print(a01 - a0)
    a0 = calc_sep(t_constraint, 1.43, 1.43)
    print(a0 - a01)
    # 2-sigma
    a0 = calc_sep(t_constraint, 1.10, 1.10)
    print(a01 - a0)
    a0 = calc_sep(t_constraint, 1.55, 1.55)
    print(a0 - a01)
    ##############################
    # Palettes ###################
    ##############################

    # Plot to visualize colors;
    sns.palplot(COLORS.values())

    # Custom color palette ranging from color 1 to color 2, with a neutral tone in the middle, and 20 shades;
    cm = LinearSegmentedColormap.from_list(
        "test", [COLORS["b4"], "#DEDEDE", COLORS["r5"]], N=20)
    # Obtain 10 colors as:
    colors = [cm(x) for x in np.linspace(0, 1, 10)]
    sns.palplot(colors)

    # Manipulate HLS values of color;
    new_color = sns.set_hls_values("#DEDEDE", h=0.2, l=0.3, s=0.4)

    # Obtain the same palette in grayscale;
    grayscale_colors = [hex_color_to_grayscale(c) for c in colors]
    sns.palplot(grayscale_colors)

    #%%

    ##############################
    # Axis ticks and labels ######
    ##############################

    # Add some random data to a plot;
    fig = plt.figure(figsize=(2, 2))
    gs = gridspec.GridSpec(1, 1)
    ax = fig.add_subplot(gs[0, 0])
Exemple #11
0
import seaborn as sns
from matplotlib import pyplot as plt

greys = sns.color_palette('Greys', n_colors=8)
greens = sns.color_palette('Greens', n_colors=8)
blue_greens = sns.color_palette("GnBu_d", n_colors=12)
blues = sns.color_palette('Blues', n_colors=8)
oranges = sns.color_palette('Oranges', desat=0.8)
purples = sns.color_palette('Purples', n_colors=8)
reds = sns.color_palette('Reds', n_colors=8)
reddish_purple = sns.set_hls_values(sns.xkcd_rgb['reddish purple'], 0.9, 0.3,
                                    1)
reddish = sns.xkcd_rgb['raspberry']

rcParams = plt.rcParams
rcParams['font.family'] = 'sans-serif'
rcParams['font.sans-serif'] = [
    'Myriad Pro', 'Roboto', 'Tahoma', 'DejaVu Sans', 'Lucida Grande', 'Verdana'
]

sns.set_style('white')
Exemple #12
0
def main():
    """
    # Script to produce Eiso vs. z
    """

    Eiso_111117A = 3.38 * (cosmo.luminosity_distance(2.211)**2/cosmo.luminosity_distance(1.3)**2)*(2.3 / 3.211)*1e51


    # Read in long GRBs from Turpin et al. 2015, https://arxiv.org/abs/1503.02760
    burst_table = pd.read_csv("../data/Comparison sample - Long Eiso.csv")
    name, z_long, Eiso_long = burst_table["GRB"].values, burst_table["z"].values, burst_table["Eiso"].values

    Eiso_long = np.log10(10*filt_nan(Eiso_long, fill_value=np.nan)*1e51)
    z_long = filt_nan(z_long, fill_value=np.nan)

    # Read in short GRBs from D'Avanzo et al. 2014
    burst_table = pd.read_csv("../data/Comparison sample - Short.csv")
    name, z_short, Eiso_short = burst_table["GRB"].values, burst_table["z"].values, burst_table["Eiso"].values

    # Remove GRB090426
    idx = np.where(name == "090426")[0]
    name, z_short, Eiso_short = np.delete(name, idx), np.delete(z_short, idx), np.delete(Eiso_short, idx)

    Eiso_short = np.log10(filt_nan(Eiso_short, fill_value=np.nan)*1e51)




    # Plot values from Turpin et al. 2015
    g = sns.JointGrid(x=z_long, y=Eiso_long, xlim=(0, 4), ylim=(49, 55), space=0)
    color = sns.color_palette()[2]
    color_rgb = mpl.colors.colorConverter.to_rgb(color)
    colors = [sns.set_hls_values(color_rgb, l=l) for l in np.linspace(1, 0, 12)]
    cmap = sns.blend_palette(colors, as_cmap=True)
    g = g.plot_marginals(sns.distplot, hist=False, color=color)
    g = g.plot_joint(sns.kdeplot, cmap=cmap, label="Turpin et al. 2015", zorder=1)

    color = sns.color_palette()[1]
    g.x = np.array([2.211])
    g.y = np.array([np.log10(Eiso_111117A)])
    g = g.plot_joint(pl.scatter, facecolors='none', marker = "*", s = 150, lw=1.5, color=sns.color_palette()[1], label="GRB111117A")
    g = g.plot_marginals(sns.rugplot, color=color, height = 1.0, lw = 4.0)

    # Plot values D'Avanzo et al. 2014
    color = sns.color_palette()[0]
    g.x = z_short
    g.y = Eiso_short
    g = g.plot_marginals(sns.distplot, hist=False, rug=True, kde=False, color=color, rug_kws={"height": 0.7, "lw": 2.0})
    g = g.plot_joint(pl.scatter, color=color, label="D'Avanzo et al. 2014")


    g.x = -1
    g.y = 1
    g = g.plot_joint(pl.plot, color=sns.color_palette()[2], label="Turpin et al. 2015")





    ax = pl.gca()
    # ax.axhline(0.5, color="black", linestyle="dashed", alpha=0.5)
    # ax.annotate(r"$\beta_{OX} = 0.5$", (19.6, 0.45))
    g.set_axis_labels(r"z", r"log(E$_{iso}$) [erg]")
    pl.tight_layout()



    # Save figure for tex
    pl.legend(loc=4)
    pl.savefig("../figures/Eiso_z.pdf", dpi="figure")
    pl.show()
Exemple #13
0
def main():
    """
    # Script to produce N_H vs. z
    """
    # Read in long GRBs
    burst_table = pd.read_csv("../data/Comparison sample - Long NH.csv")
    name, z_long, NH_long = burst_table["GRB"].values, burst_table[
        "z"].values, burst_table["Nnew(z)"].values

    NH_long_dec = np.log10(1e21 * filt_nan(NH_long, fill_value=np.nan))
    z_long_dec = filt_nan(z_long, fill_value=np.nan)
    print(len(z_long_dec), len(z_long_dec[np.isnan(z_long_dec)]))

    for ii, kk in enumerate(z_long):
        print(kk, NH_long[ii], NH_long_dec[ii])

    # Get lower limits
    NH_long_lowlim = np.log10(1e21 * np.array([
        (kk, float(ii[1:]))
        for kk, ii in enumerate(NH_long[np.isnan(NH_long_dec)]) if ii[0] == ">"
    ]))
    z_long_lowlim, NH_long_lowlim = z_long[np.isnan(NH_long_dec)][(
        (10**NH_long_lowlim[:, 0]) / 1e21).astype("int")], NH_long_lowlim[:, 1]
    z_long_lowlim = filt_nan(z_long_lowlim, fill_value=np.nan)
    print(z_long_lowlim)

    # Get upper limits
    NH_long_uplim = np.array([
        (kk, float(ii[1:]))
        for kk, ii in enumerate(NH_long[np.isnan(NH_long_dec)]) if ii[0] == "<"
    ])
    z_long_uplim, NH_long_uplim = z_long[np.isnan(NH_long_dec)][
        NH_long_uplim[:,
                      0].astype("int")], np.log10(1e21 * NH_long_uplim[:, 1])

    # Read in short GRBs
    burst_table = pd.read_csv("../data/Comparison sample - Short.csv")
    name, z_short, NH_short = burst_table["GRB"].values, burst_table[
        "z"].values, burst_table["NH(z)"].values

    # Remove GRB090426
    idx = np.where(name == "090426")[0]
    name, z_short, NH_short = np.delete(name, idx), np.delete(
        z_short, idx), np.delete(NH_short, idx)

    NH_short_dec = np.log10(1e21 * filt_nan(NH_short, fill_value=np.nan))
    NH_short_lim = np.log10(
        1e21 *
        np.array([float(ii[1:]) for ii in NH_short[np.isnan(NH_short_dec)]]))

    z_short_dec = filt_nan(z_short, fill_value=np.nan)
    z_short_lim = z_short[np.isnan(NH_short_dec)]

    # Plot values from Arcodia et al. 2016
    g = sns.JointGrid(x=z_long_dec,
                      y=NH_long_dec,
                      xlim=(0, 4),
                      ylim=(20.5, 23.5),
                      space=0)
    color = sns.color_palette()[2]
    color_rgb = mpl.colors.colorConverter.to_rgb(color)
    colors = [
        sns.set_hls_values(color_rgb, l=l) for l in np.linspace(1, 0, 12)
    ]
    cmap = sns.blend_palette(colors, as_cmap=True)
    g = g.plot_marginals(sns.distplot, hist=False, color=color)
    g = g.plot_joint(sns.kdeplot,
                     cmap=cmap,
                     label="Arcodia et al. 2016",
                     zorder=1,
                     lw=0.7,
                     alpha=0.6)
    # g = g.plot_joint(pl.scatter, cmap=cmap, label="Arcodia et al. 2016", zorder=1)
    # g = g.plot_marginals(sns.distplot, hist=False, rug=True, kde=False, color=color, rug_kws={"height": 0.7, "lw": 2.0})
    g = g.plot_joint(pl.scatter,
                     color=color,
                     marker="h",
                     s=20,
                     lw=1.0,
                     alpha=0.8)
    print(z_long_uplim, NH_long_uplim)
    g.x = z_long_uplim
    g.y = NH_long_uplim
    g = g.plot_marginals(sns.distplot,
                         hist=False,
                         rug=True,
                         kde=False,
                         color=color,
                         rug_kws={
                             "height": 0.7,
                             "lw": 2.0,
                             "alpha": 0.5
                         })
    g = g.plot_joint(pl.scatter,
                     color=color,
                     marker=u'$\u2193$',
                     s=100,
                     lw=1.0)

    g.x = z_long_lowlim
    g.y = NH_long_lowlim
    g = g.plot_marginals(sns.distplot,
                         hist=False,
                         rug=True,
                         kde=False,
                         color=color,
                         rug_kws={
                             "height": 0.7,
                             "lw": 2.0,
                             "alpha": 0.5
                         })
    g = g.plot_joint(pl.scatter,
                     color=color,
                     marker=u'$\u2191$',
                     s=100,
                     lw=1.0)

    # Plot values D'Avanzo et al. 2014
    color = sns.color_palette()[0]
    g.x = z_short_dec
    g.y = NH_short_dec
    g = g.plot_marginals(sns.distplot,
                         hist=False,
                         rug=True,
                         kde=False,
                         color=color,
                         rug_kws={
                             "height": 0.7,
                             "lw": 2.0
                         })
    g = g.plot_joint(pl.scatter, color=color, label="D'Avanzo et al. 2014")
    g.x = z_short_lim
    g.y = NH_short_lim
    g = g.plot_marginals(sns.distplot,
                         hist=False,
                         rug=True,
                         kde=False,
                         color=color,
                         rug_kws={
                             "height": 0.7,
                             "lw": 2.0,
                             "alpha": 0.5
                         })
    g = g.plot_joint(pl.scatter,
                     color=color,
                     marker=u'$\u2193$',
                     s=100,
                     lw=1.0)

    g.x = -1
    g.y = 1
    g = g.plot_joint(pl.plot,
                     color=sns.color_palette()[2],
                     label="Arcodia et al. 2016")

    color = sns.color_palette()[1]
    g.x = np.array([2.211])
    g.y = np.array([np.log10(2.4e22)])
    # g.y = np.array([np.log10(2.4e22+2.4e22)])
    gyupperr = np.log10(2.4e22) / np.log10(
        2.4e22)  # np.log10(2.4e22) - np.log10(1.6e22)
    gylowerr = np.log10(1.6e22) / np.log10(
        2.4e22)  #  np.log10(4.8e22) - np.log10(2.4e22)
    g = g.plot_joint(pl.scatter,
                     marker="*",
                     s=150,
                     color=sns.color_palette()[1],
                     label="GRB 111117A")

    g = g.plot_marginals(sns.rugplot, color=color, height=1.0, lw=4.0)
    g.x = np.array([2.211, 2.211])
    g.y = np.array([np.log10(2.4e22 - 1.6e22), np.log10(2.4e22 + 2.4e22)])
    g = g.plot_joint(pl.plot, color=sns.color_palette()[1])

    ax = pl.gca()
    g.set_axis_labels(r"z", r"log($N_\mathrm{H,X}$) [cm$^{-2}$]")
    pl.tight_layout()

    # Save figure for tex
    pl.xlim((0, 6))
    pl.legend(loc=1, markerfirst=False)
    pl.savefig("../figures/NH_z.pdf", dpi="figure")
    pl.show()
Exemple #14
0
def main():
    """
    # Script to produce beta OX.
    """
    # Read in burst list
    burst_table = pd.read_csv("../data/Burst list - observed.csv")
    name, sample, dt, acqmag, X_Fnu = burst_table["GRB"].values, burst_table[
        "In Sample"].values, burst_table["Follow-up delay"].values, burst_table[
            "Acquisition mag"].values, burst_table["XRT flux density"].values
    name = np.array([ii[3:] for ii in name])
    # print(name)
    acqmag = filt_nan(acqmag, fill_value=24)
    idx_limit = (acqmag == 24)

    X_Fnu = filt_nan(X_Fnu)
    # Optical flux in microjansky
    O_Fnu = 10**((23.9 - acqmag) / 2.5)

    O_nu0 = 3e8 / 658e-9  # Convert R-band rest to Hertz
    E_Xrt = ((10. - 0.3) / 2.) * 1e3  # Middle energy of XRT in eV
    X_nu0 = E_Xrt / 4.135667516e-15  # Convert eV to Hertz
    # Calculate betaOX
    betaOX = np.log10(O_Fnu / X_Fnu) / np.log10(X_nu0 / O_nu0)
    # Mask bad values and reverse order
    mask = np.isnan(betaOX) | (sample == "No")
    betaOX = betaOX[~mask][::-1]
    name = name[~mask][::-1]
    idx_limit = idx_limit[~mask][::-1]

    # for ii, kk in enumerate(betaOX):
    #     print(name[ii], kk)
    # exit()
    fynbo_table = np.genfromtxt("../data/Fynbo2009betaOX.dat", dtype=None)
    f_name = fynbo_table[:, 0]
    fynbo_table[:, 1] = [ii.replace('<', '') for ii in fynbo_table[:, 1]]
    f_betaOX = filt_nan(fynbo_table[:, 1])
    f_name = f_name[~np.isnan(f_betaOX)]
    f_betaOX = f_betaOX[~np.isnan(f_betaOX)]

    # Get Swift HI values
    swift_table = pd.read_table("../data/allSwiftGRBs_NH.txt",
                                delimiter="\t",
                                dtype=None)
    name_s, z_s, HI_s, HI_sh, HI_sl = swift_table["#GRB"].values, swift_table[
        "Redshift"].values, swift_table["Ave_NH_PC"].values, swift_table[
            "Ave_dNH_PC+"].values, -1 * swift_table["Ave_dNH_PC-"].values
    # print(HI_s)

    # # Read in Buchner catalog
    # grbcat = fits.open("../data/grbcat-annotated.fits")
    # # print(grbcat[1].data.field)
    # name_s = np.array(["".join(kk.split(" "))[3:] for kk in grbcat[1].data.field("Name")])
    # HI_s, HI_sl, HI_sh, nH_std, z_s = grbcat[1].data.field("NH_sphere_mean"), grbcat[1].data.field("NH_sphere_hi"), grbcat[1].data.field("NH_sphere_lo"), grbcat[1].data.field("NH_sphere_std"), grbcat[1].data.field("z")

    # Find values with betaOX
    idx = [
        ii for ii, kk in enumerate(name_s) if kk in name and ~np.isnan(z_s[ii])
    ]
    idx_2 = [ii for ii, kk in enumerate(name) if kk in name_s[idx]]
    f_idx = [
        ii for ii, kk in enumerate(name_s)
        if kk in f_name and ~np.isnan(z_s[ii])
    ]
    f_idx_2 = [ii for ii, kk in enumerate(f_name) if kk in name_s[f_idx]]

    # HI = filt_nan(HI_s[idx], fill_value=0)
    # HIh = filt_nan(HI_sh[idx], fill_value=0)
    # HIl = filt_nan(HI_sl[idx], fill_value=0)
    # f_HI = filt_nan(HI_s[f_idx], fill_value=0)
    # f_HI[np.isnan(f_HI)] = 0

    HI = np.log10(1e22 * filt_nan(HI_s[idx], fill_value=0))
    HIh = np.log10(1e22 * filt_nan(HI_s[idx] + HI_sh[idx], fill_value=0))
    HIl = np.log10(1e22 * filt_nan(HI_s[idx] - HI_sl[idx], fill_value=0))
    f_HI = np.log10(1e22 * filt_nan(HI_s[f_idx], fill_value=0))
    f_HI[np.isnan(f_HI)] = 0

    # Plot new values

    print(stats.pearsonr(HI, betaOX[idx_2]))
    print(stats.spearmanr(HI, betaOX[idx_2]))
    print(stats.pointbiserialr(HI, betaOX[idx_2]))
    print(stats.kendalltau(HI, betaOX[idx_2]))

    # exit()

    g = sns.JointGrid(x=HI,
                      y=betaOX[idx_2],
                      xlim=(19.5, 23),
                      ylim=(0, 1.3),
                      space=0)
    color = sns.color_palette()[0]
    g = g.plot_marginals(sns.distplot,
                         hist=True,
                         kde=False,
                         norm_hist=True,
                         color=color)
    idx_limit = idx_limit[idx_2]
    g.x = HI[~idx_limit]
    g.y = betaOX[idx_2][~idx_limit]

    np.savetxt("betaOX.dat",
               list(
                   zip(name_s[idx][~idx_limit], HI[~idx_limit],
                       betaOX[idx_2][~idx_limit])),
               fmt='%s %s %s')
    # exit()

    g = g.plot_joint(pl.scatter, color=color, label="This work")

    g.x = HI[idx_limit]
    g.y = betaOX[idx_2][idx_limit]
    g = g.plot_joint(pl.scatter,
                     color=color,
                     marker=r'$\downarrow$',
                     s=150,
                     lw=1.0)

    for ii, kk in enumerate(HI):
        g.y = np.array([betaOX[idx_2][ii], betaOX[idx_2][ii]])

        g.x = np.array([HIl[ii], HIh[ii]])
        g = g.plot_joint(pl.plot, color=color, lw=0.75)

    # Plot values from Fynbo et al. 2009
    color = sns.color_palette()[2]
    color_rgb = mpl.colors.colorConverter.to_rgb(color)
    colors = [
        sns.set_hls_values(color_rgb, l=l) for l in np.linspace(1, 0, 12)
    ]
    cmap = sns.blend_palette(colors, as_cmap=True)

    g.x = f_HI
    g.y = f_betaOX[f_idx_2]

    # print(f_betaOX[f_idx_2], f_HI)

    g = g.plot_marginals(sns.distplot, hist=False, color=color)
    g = g.plot_joint(sns.kdeplot, cmap=cmap, label="Fynbo et al. 2009")
    g.x = 1
    g.y = 1
    g = g.plot_joint(pl.plot, color=color, label="Fynbo et al. 2009")
    ax = pl.gca()
    ax.axhline(0.5, color="black", linestyle="dashed", alpha=0.5)
    ax.annotate(r"$\beta_{OX} = 0.5$", (19.6, 0.42))
    g.set_axis_labels(r"$\log(N_{\mathrm{H, X}}/\mathrm{cm}^{-2})$",
                      r"$\beta_{OX}$")
    pl.tight_layout()

    # print(stats.ks_2samp(betaOX[idx_2], f_betaOX[f_idx_2]))
    # print(len(betaOX[idx_2]))
    # l, m, h = np.percentile(betaOX[idx_2], [16, 50, 84])
    # print(m, m - l, h - m)
    # print(len(f_betaOX[f_idx_2]))
    # l, m, h = np.percentile(f_betaOX[f_idx_2], [16, 50, 84])
    # print(m, m - l, h - m)

    # print(stats.ks_2samp(HI, f_HI))
    # print(len(HI))

    print("Above 0.5")
    l, m, h = np.percentile(HI[betaOX[idx_2] >= 0.5], [16, 50, 84])
    print(HI[betaOX[idx_2] >= 0.5])
    print(m, m - l, h - m)
    print("Below 0.5")
    l, m, h = np.percentile(HI[betaOX[idx_2] < 0.5], [16, 50, 84])
    print(HI[betaOX[idx_2] >= 0.5])
    print(m, m - l, h - m)

    #Fraction of dark bursts
    print(
        len(HI[betaOX[idx_2] < 0.5]) /
        (len(HI[betaOX[idx_2] < 0.5]) + len(HI[betaOX[idx_2] >= 0.5])))
    print(stats.ks_2samp(HI[betaOX[idx_2] < 0.5], HI[betaOX[idx_2] >= 0.5]))
    print(len(HI))
    # exit()
    # print(len(f_HI))
    # l, m, h = np.percentile(f_HI, [16, 50, 84])
    # print(m, m - l, h - m)

    # Save figure for tex
    pl.legend(loc=1)
    pl.savefig("../document/figures/betaOX.pdf", dpi="figure")
    pl.show()
Exemple #15
0
def main():
    """
    # Script to produce N_H vs. z
    """
    # Read in SDSS line-fluxes
    sdss = fits.open(
        '/Users/jselsing/Work/spectral_libraries/sdss_catalogs/portsmouth_emlinekin_full-DR12.fits'
    )
    # mask = np.logical_and((sdss[1].data.field('Z') >= 0.5),(sdss[1].data.field('Z') <= 2.0))

    mask = (sdss[1].data.field('Z') <= 0.1)

    Hb_sdss = sdss[1].data.field('FLUX')[:, 15]
    OIII_sdss = sdss[1].data.field('FLUX')[:, 17]

    Ha_sdss = sdss[1].data.field('FLUX')[:, 24]
    NII_sdss = sdss[1].data.field('FLUX')[:, 25]

    x = np.log10(NII_sdss[mask] / Ha_sdss[mask])
    y = np.log10(OIII_sdss[mask] / Hb_sdss[mask])

    # Plot values from Arcodia et al. 2016
    g = sns.JointGrid(x=x, y=y, xlim=(-2, 1), ylim=(-1.5, 1.5), space=0)
    color = sns.color_palette()[0]
    color_rgb = mpl.colors.colorConverter.to_rgb(color)
    colors = [
        sns.set_hls_values(color_rgb, l=l) for l in np.linspace(1, 0, 12)
    ]
    cmap = sns.blend_palette(colors, as_cmap=True)

    g = g.plot_joint(pl.hexbin,
                     cmap=cmap,
                     bins='log',
                     extent=[-2, 1, -1.5, 1.5],
                     alpha=0.3,
                     edgecolors="NAAone")

    color = sns.color_palette()[1]

    nii = 4.5e-18
    niie = 9.9e-18
    ha = 1.1e-16
    hae = 1.2e-17

    niiha, niihae = propagate_uncertainties(fraction, [nii, ha], [niie, hae],
                                            1000000)

    hb = 1.3e-17
    hbe = 3.5e-18
    oiii = 4.3e-17
    oiiie = 9.9e-18

    hboiii, hboiiie = propagate_uncertainties(fraction, [oiii, hb],
                                              [oiiie, hbe], 1000000)

    g.x = np.log10(3 * niie / ha)
    g.y = np.log10(oiii / (3 * hbe))
    g = g.plot_joint(pl.errorbar,
                     yerr=0.2,
                     xerr=0.2,
                     xuplims=True,
                     uplims=True,
                     lw=1.5,
                     color=sns.color_palette()[2],
                     label="GRB111117A")

    g.x = niiha
    g.y = hboiii
    g = g.plot_joint(pl.scatter,
                     facecolors='none',
                     marker="*",
                     s=150,
                     lw=1.5,
                     color=sns.color_palette()[2],
                     label="GRB111117A")
    ax = pl.gca()
    from matplotlib.patches import Ellipse
    for j in np.arange(1, 4):
        ax.add_artist(
            Ellipse((g.x, g.y),
                    j * niihae,
                    j * hboiiie,
                    fill=False,
                    linestyle='dashed',
                    lw=2,
                    alpha=1.0 / (2.0 * j)))

    ax = pl.gca()
    # ax.axhline(0.5, color="black", linestyle="dashed", alpha=0.5)
    # ax.annotate(r"$\beta_{OX} = 0.5$", (19.6, 0.45))
    g.set_axis_labels(r"log([N II]$\lambda$6584/H$\alpha$)",
                      r"log([O III]$\lambda$5007/H$\beta$)")
    pl.tight_layout()

    # Save figure for tex
    pl.legend()
    pl.savefig("../figures/BPT.pdf", dpi="figure")
    pl.show()
 def get_color(c):  # Make the color darker, to use it for text;
     hue, saturation, brightness = colors.rgb_to_hsv(colors.to_rgb(c))
     return sns.set_hls_values(c, l=brightness * 0.6, s=saturation * 0.7)
def main():
    """
    Small script to plot delay time vs acqmag
    """

    # Read in burst list
    burst_table = pd.read_csv("../data/Burst list - observed.csv")
    name, z, delay, mag = burst_table["GRB"].values, burst_table[
        "z"].values, burst_table["Follow-up delay"].values, burst_table[
            "Acquisition mag"].values

    # for kk, ll in list(zip(name, z)):
    #     print(kk, cosmo.luminosity_distance(ll).to(u.cm))
    # exit()

    for ii, ll in enumerate(mag):
        print(name[ii], ll)
        if "R" in str(ll):
            print(ll)
            mag[ii] = float(ll.split("=")[1]) + 0.21
    # print(mag)
    # exit()
    idx_limits = ~(mag == ">24")
    magnondet = 24 * (~idx_limits).astype("int")

    delay_sort = np.argsort(delay)
    sorted_delay = delay[delay_sort]
    sorted_z = z[delay_sort]
    print(len(sorted_z))
    print(sorted_z)
    # exit()
    fractional_completeness = (
        1 - np.cumsum(np.isnan(sorted_z).astype("int")) / len(sorted_z)) * 100
    # print(len(sorted_z), np.sum(np.isnan(sorted_z).astype("int")))
    # print(fractional_completeness[-1])
    # exit()
    idx_hasz = ~np.isnan(z)

    # Plot
    fig, ax1 = pl.subplots()

    color = sns.color_palette("muted")[0]
    color_rgb = mpl.colors.colorConverter.to_rgb(color)
    colors = [
        sns.set_hls_values(color_rgb, l=l) for l in np.linspace(1, 0, 12)
    ]
    cmap = sns.blend_palette(colors, as_cmap=True)
    # cmap = pl.get_cmap("plasma")
    # With redshift and acq mag
    sc = ax1.scatter(delay[idx_hasz & idx_limits],
                     mag[idx_hasz & idx_limits],
                     c=z[idx_hasz & idx_limits],
                     cmap=cmap,
                     s=35)

    # Without redshift and with acq mag
    ax1.scatter(delay[~idx_hasz & idx_limits],
                mag[~idx_hasz & idx_limits],
                color=sns.color_palette("muted")[2],
                s=45,
                marker="x")
    # With redshift, but without acq mag
    ax1.scatter(delay[idx_hasz & ~idx_limits],
                magnondet[idx_hasz & ~idx_limits],
                c=z[idx_hasz & ~idx_limits],
                cmap=cmap,
                s=175,
                marker=r'$\downarrow$')
    # No redshift and without acq mag
    ax1.scatter(delay[~idx_hasz & ~idx_limits],
                magnondet[~idx_hasz & ~idx_limits],
                color=sns.color_palette("muted")[2],
                s=175,
                marker=r'$\downarrow$')
    ax2 = pl.twinx()
    ax2.plot(sorted_delay,
             fractional_completeness,
             color=sns.color_palette("muted")[2])

    ax1.spines['top'].set_visible(False)
    ax2.spines['top'].set_visible(False)
    ax2.spines['right'].set_visible(False)
    ax2.spines['left'].set_visible(False)
    ax2.spines['bottom'].set_visible(False)
    ax1.get_xaxis().tick_bottom()
    ax1.get_yaxis().tick_left()
    ax1.tick_params(axis='x', direction='out')
    ax1.tick_params(axis='y', direction='out')
    ax2.tick_params(axis='y', direction='out')
    # offset the spines
    for spine in ax1.spines.values():
        spine.set_position(('outward', 3))
    for spine in ax2.spines.values():
        spine.set_position(('outward', 3))
    # put the grid behind
    ax1.set_axisbelow(True)
    ax2.set_axisbelow(True)

    # ax.set_xlim((19.5, 23))
    ax1.set_xlim((0.05, 110))
    # ax1.set_ylim((15.5, 24.5))
    # ax2.set_yticks([75, 80, 85, 90, 95, 100])
    ax2.set_ylim((70, 105))
    ax2.set_yticks([75, 80, 85, 90, 95, 100])
    ax1.set_xlabel(r"Follow-up delay (hours)")
    ax1.set_ylabel(r"Acquisition camera magnitude ($R, i$-band)")
    ax2.set_ylabel(r"Redshift completeness (\%)")

    ax1.invert_yaxis()
    ax1.semilogx()
    # pl.tight_layout()
    ax1.xaxis.set_major_formatter(FormatStrFormatter('%.1f'))
    #create a colorbar axis

    from mpl_toolkits.axes_grid1 import make_axes_locatable
    divider = make_axes_locatable(ax1)
    cax = divider.append_axes('top', size='5%', pad=0.05)
    cbar = fig.colorbar(sc, cax=cax, orientation='horizontal')

    # cbar.ax.tick_params(direction='out')
    cax.xaxis.set_ticks_position("top")
    cax.xaxis.set_label_position("top")
    # cbar.make_axes(location="top")
    cbar.set_label("Redshift")

    pl.tight_layout()
    pl.savefig("../document/figures/timing.pdf", dpi="figure")
    pl.show()