コード例 #1
0
ファイル: rate_w_eff.py プロジェクト: telegraphic/frbpoppy
def plot_w_eff_rate(df):
    """Plot effective pulse width against rate."""
    plot_aa_style(cols=1)

    df = df.sort_values('utc')

    # Groupby repeater
    db = df
    # db = df.groupby(['frb_name']).mean()
    width = db.width
    width_err = (db.width_error_lower, db.width_error_upper)
    n_bursts = db.n_bursts
    rate = db.rate
    exposure = db.exposure.to_numpy()

    # Calculate error bars
    low, high = poisson_interval(n_bursts.to_numpy(), sigma=1)
    rate_err = (low / exposure, high / exposure)

    # Plot values
    plt.errorbar(width,
                 rate,
                 xerr=width_err,
                 yerr=rate_err,
                 marker='x',
                 fmt='o')

    # Print correlation
    _width = width[~np.isnan(rate)]
    _rate = rate[~np.isnan(rate)]
    r = np.corrcoef(_width, _rate)[0, 1]
    print('Pearson correlation coefficient: ', r)
    r = np.corrcoef(np.log10(_width), np.log10(_rate))[0, 1]
    print('Pearson correlation coefficient in log10 space: ', r)

    plt.xlabel(r'Pulse Width (ms)')
    plt.ylabel(r'Rate (/hour)')

    if SCALE == 'log':
        plt.xscale('log')
        plt.yscale('log', nonposy='clip')

    plt.tight_layout()
    plt.savefig(rel_path('./plots/rate_w_eff_chime.pdf'))

    # Save data
    a = np.asarray(
        [width, width_err[0], width_err[1], rate, rate_err[0], rate_err[1]]).T
    np.savetxt(rel_path('./plots/chime_rep_width.csv'),
               a,
               delimiter=",",
               header=','.join([
                   'w_eff', 'w_eff_lower_err', 'w_eff_upper_err', 'rate',
                   'rate_lower_err', 'rate_upper_err'
               ]))
def plot(prob, show=False):
    """Plot the number of bursts seen over a maximum time."""
    plot_aa_style(cols=2)

    days = np.arange(1, N_DAYS, 1)
    m_bursts = np.arange(0, M_BURSTS, 1)

    prob[np.isnan(prob)] = 0

    fig, ax = plt.subplots()
    extent = [min(days) - 0.5, max(days) + 0.5, min(m_bursts), max(m_bursts)]
    plt.imshow(prob,
               norm=LogNorm(),
               origin='lower',
               aspect='auto',
               interpolation='none',
               extent=extent)
    plt.colorbar(orientation='vertical')
    ax.set_title('Probability of M bursts within time')
    ax.set_xlabel('Maximum time (days)')
    ax.set_ylabel('M bursts')
    plt.tight_layout()

    if show:
        plt.show()
    else:
        plt.savefig(rel_path('./plots/prob_m_bursts.pdf'))
コード例 #3
0
    def plot(self):
        plot_aa_style()
        plt.rcParams["figure.figsize"] = (5.75373, 5.75373)
        f, self.axes = plt.subplots(2, 2, sharex='col', sharey='row')

        self.linestyles = ['solid', 'dashed', 'dotted']
        self.colours = plt.rcParams['axes.prop_cycle'].by_key()['color']
        # Matching redshifts to linestyles
        self.zs = self.df.z_max.unique()
        self.lz = dict(zip(self.zs, self.linestyles))

        # Set vertical spacing
        self.internal_survey_spacing = 0.1
        self.external_survey_spacing = 0.2

        for ax in self.axes.flat:
            ax.set_xscale('log')
            ax.set_xlim(1e-6, 1e6)

        self.plot_cosmo()
        self.plot_lum()
        self.plot_si()
        self.plot_w()

        plt.tight_layout()
        p = f'plots/flattening_rates.pdf'
        plt.savefig(rel_path(p))
コード例 #4
0
ファイル: alpha_askap.py プロジェクト: telegraphic/frbpoppy
def plot_rates(rates):
    """Plot detection rates for askap surveys."""
    plot_aa_style()

    fig, (ax1) = plt.subplots(1, 1)
    cmap = plt.get_cmap('tab10')
    ax1.set_xlim((min(ALPHAS) + .1, max(ALPHAS) - .1))
    ax1.set_yscale('log', nonposy='mask')

    # Plot complex versus toy
    for i, surv in enumerate(SURVEYS):
        ax1.plot(ALPHAS,
                 rates[surv],
                 color=cmap(i + 1),
                 label=surv,
                 linestyle='dashed')

    # Plot layout options
    # Set up axes
    ax1.set_xlabel(r'$\alpha_{\text{in}}$')
    ax1.invert_xaxis()
    ax1.set_ylabel('Events / htru')

    plt.legend()
    plt.savefig(rel_path('plots/askap_rates.pdf'), bbox_inches='tight')
コード例 #5
0
ファイル: flattening.py プロジェクト: telegraphic/frbpoppy
    def plot(self, euclidean_lines=True):

        plot_aa_style()
        plt.rcParams["figure.figsize"] = (5.75373, 5.75373)
        f, self.axes = plt.subplots(2, 2, sharex='col', sharey='row')

        self.linestyles = ['solid', 'dashed', 'dotted']
        self.colours = plt.rcParams['axes.prop_cycle'].by_key()['color']
        self.lz = dict(zip(self.zs, self.linestyles))

        for ax in self.axes.flat:
            ax.set_xscale('log')
            ax.set_yscale('log')
            ax.set_xlim(1, 1e6)
            ax.set_ylim(10**-np.log10(self.size), 10**(np.log10(self.size)/2))

            if euclidean_lines:
                xlims = ax.get_xlim()
                xs = np.logspace(np.log10(xlims[0]),
                                 np.log10(xlims[1]),
                                 100)
                for n in range(-10, 10):
                    ys = 10**((np.log10(xs)+n)*-1.5)
                    ax.plot(xs, ys, 'k:', linewidth=0.25)

        self.plot_cosmo()
        self.plot_lum()
        self.plot_si()
        self.plot_w()

        for ax in self.axes.flat:
            ax.legend()
        plt.tight_layout()
        p = f'plots/logn_logs_flattening_{self.survey.name}.pdf'
        plt.savefig(rel_path(p))
コード例 #6
0
ファイル: abc.py プロジェクト: telegraphic/frbpoppy
def plot_logn_logs(data):
    """Plot log N log S data in a cumlative histogram."""
    plot_aa_style()

    fig, (ax1) = plt.subplots(1, 1)

    for key in data:
        x, y = data[key]
        ax1.step(x, y, where='post', label=key)

    plt.xlabel(r'S$_{\text{min}}$ (Jy)')
    plt.ylabel(r'N(${>}\text{S}_{\text{min}}$)')
    plt.xscale('log')
    plt.yscale('log')
    plt.xlim((1e-3, 1e1))
    plt.legend()
    plt.tight_layout()
    plt.savefig(rel_path('plots/logn_logs_abc.pdf'))
コード例 #7
0
ファイル: alpha_complex.py プロジェクト: telegraphic/frbpoppy
def main():
    """Plot expected complex rates."""
    plot_aa_style()

    rates = complex_rates()
    for surv in rates:
        rate = rates[surv]
        plt.plot(ALPHAS, rate, label=surv)

    plt.xlabel(r'$\alpha_{\text{in}}$')
    plt.ylabel(rf'Events / {SURVEYS[0]}')
    plt.yscale('log')
    plt.xlim((min(ALPHAS), max(ALPHAS)))
    plt.legend()
    plt.gca().invert_xaxis()
    plt.tight_layout()
    plt.grid()
    plt.savefig(rel_path('./plots/complex_rates.pdf'))
コード例 #8
0
ファイル: plot.py プロジェクト: telegraphic/frbpoppy
    def __init__(self):
        plot_aa_style()
        plt.rcParams['figure.figsize'] = (5.75373, (5.75373 / 3) * 4)
        plt.rcParams['font.size'] = 9
        # plt.rcParams['xtick.major.pad'] = 10
        # plt.rcParams['ytick.major.pad'] = 10
        # plt.rcParams['axes.titlepad'] = 10
        self.fig, self.axes = plt.subplots(4, 3, sharey='row')
        self.colors = plt.rcParams['axes.prop_cycle'].by_key()['color']
        self.gf = GoodnessOfFit()
        self.df = self.gf.so.df

        # Calculate global maximums
        self.gm = {}
        for run in self.df.run.unique():
            self.gm[run] = self.gf.calc_global_max(run)
        print(self.gm)

        # Plot various subplots
        self.alpha()
        self.si()
        self.li()
        self.li_2()
        self.lum_min()
        self.lum_max()
        self.w_int_mean()
        self.w_int_std()
        self.legend()
        self.dm_igm_slope()
        self.dm_host()
        self.axes[3, 2].set_axis_off()

        # Plot run rectangles
        # self.runs()

        # Save plot
        plt.tight_layout()  # rect=[0, 0, 0.98, 1])
        plt.subplots_adjust(wspace=0.1)
        plt.savefig(rel_path('./plots/mc/mc.pdf'))
コード例 #9
0
ファイル: alpha_real.py プロジェクト: telegraphic/frbpoppy
def main():
    """Plot real rate regions per alpha."""
    plot_aa_style()

    rates = real_rates()

    for surv in rates:
        middle, top, bottom = rates[surv]
        left = min(ALPHAS)
        right = max(ALPHAS)
        x = [left, right, right, left]
        y = [top, top, bottom, bottom]
        plt.fill(x, y, alpha=0.25)
        plt.plot([left, right], [middle]*2, label=surv, linestyle='dashed')

    plt.xlabel(r'$\alpha_{\text{in}}$')
    plt.ylabel(rf'Events / {SURVEYS[0]}')
    plt.yscale('log')
    plt.legend()
    plt.gca().invert_xaxis()
    plt.tight_layout()
    plt.savefig(rel_path('./plots/rates_rm.pdf'))
コード例 #10
0
def plot_dm(pops):
    """Plot resulting dispersion measure."""
    plot_aa_style()
    f, (ax1) = plt.subplots(1, 1)

    for i, beam in enumerate(pops):
        pop = pops[beam]
        dm = pop.frbs.dm
        s_peak = pop.frbs.s_peak

        limit = 1e-10
        dm = dm[(s_peak > limit)]

        print(f'{len(dm)} FRBs in graph of {pop.name}')

        n, bin_edges = np.histogram(dm, bins=75)
        n = n / max(n)
        bins = (bin_edges[:-1] + bin_edges[1:]) / 2

        # Add edges to histogram
        bin_diff = np.diff(bins)[-1]
        bins = np.insert(bins, 0, bins[0] - bin_diff)
        bins = np.insert(bins, len(bins), bins[-1] + bin_diff)
        n = np.insert(n, 0, 0)
        n = np.insert(n, len(n), 0)

        ax1.step(bins, n, where='mid', label=beam)

    ax1.set_xlabel(r'DM (pc cm$^{-3}$)')
    ax1.set_xlim([0, 3000])
    ax1.set_ylabel(r'Fraction')
    ax1.set_ylim([0, 1])
    ax1.legend()

    plt.tight_layout()
    plt.savefig(rel_path('./plots/dm_beams.pdf'))
コード例 #11
0
    if SCALE_TO == 'parkes-htru':
        htru_pop = SurveyPopulation(pop, htru, mute=True)
        n_frbs_htru = EXPECTED['parkes-htru'][0]
        n_days_htru = EXPECTED['parkes-htru'][1]
        scaled_n_days = n_days_htru * (htru_pop.source_rate.det / n_frbs_htru)

    if SCALE_TO == 'askap':
        askap_pop = SurveyPopulation(pop, askap, mute=True)
        n_frbs_askap = EXPECTED['askap-fly'][0]
        n_days_askap = EXPECTED['askap-fly'][1]
        scaled_n_days = n_days_askap * (askap_pop.source_rate.det /
                                        n_frbs_askap)

    days_per_frb = scaled_n_days / apertif_pop.source_rate.det
    # print(f'{days_per_frb} days per frb')
    days_per_frbs.append(days_per_frb)

days_per_frbs = np.array(days_per_frbs)
mean = np.mean(days_per_frbs)
std = np.std(days_per_frbs)
poisson_std = poisson_interval(mean)
print(f'Mean rate for apertif is {mean}')
print(f'Standard deviation of {std}')

# Plot
rates, values = hist(days_per_frbs, bin_type='lin')
plot_aa_style()
plt.step(rates, values, where='mid')
plt.xlabel(f'Apertif days per burst scaled to {SCALE_TO}')
plt.savefig(rel_path('./plots/rate_apertif_dist.pdf'))
コード例 #12
0
from tests.convenience import plot_aa_style, rel_path

STEPSIZE = 1e-6
PLOT = True

x_range = np.arange(0, 50, STEPSIZE)
y_range = 4 * (j1(x_range) / x_range)**2
nulls = []

# Find where curve changes direction
ind = np.diff(np.sign(np.diff(y_range)))
x_null = x_range[1:-1][ind > 0]
y_null = y_range[1:-1][ind > 0]

print(x_null)

if PLOT:
    title = r"Bessel function over $\text{x}$"

    plot_aa_style()

    fig = plt.figure()
    ax = fig.add_subplot(111)
    plt.title(title)
    plt.plot(x_range[::10], y_range[::10])
    plt.scatter(x_null, y_null, marker='x')
    plt.yscale('log')
    plt.tight_layout()

    plt.savefig(rel_path('./plots/null_sidelobes.pdf'))
コード例 #13
0
# Plot original distribution
rates, values = hist(rate_dist, bins=bins, norm='max')
plt.step(rates, values, where='mid', label='original')

# Plot the first frac of time
mask = (time < init_surv_time_frac * N_DAYS) & ~np.isnan(time)
half_n_bursts = np.count_nonzero(mask, axis=1)
half_rate = half_n_bursts / (init_surv_time_frac * N_DAYS)
rates, values = hist(half_rate, bins=bins, norm='max')
plt.step(rates,
         values,
         where='mid',
         zorder=2,
         label=fr'{int(init_surv_time_frac*100)}\% of survey time')

# Plot the full rate
n_bursts = np.count_nonzero(~np.isnan(time), axis=1)
rate = n_bursts / N_DAYS
rates, values = hist(rate, bins=bins, norm='max')
plt.step(rates, values, where='mid', zorder=1, label=r'100\% of survey time')

# Set up plot details
plt.xlabel('Rate (per day)')
plt.ylabel('Fraction')
plt.xscale('log')
plt.yscale('log')
plt.legend()
plt.tight_layout()
plt.savefig(rel_path('./plots/rate_intrinsic_vs_observed.pdf'))
コード例 #14
0
ax.set_xlim(extent[0], extent[1])
ax.set_ylim(extent[2], extent[3])

# Add colour bar
cb = plt.colorbar(img)
cb.set_label('Intensity')

# Add legend
# Add line styles
elements = []
for i, dec in enumerate(decs):
    color = colors[i % 9]
    label = str(int(dec)) + r' $^{\circ}$'
    elements.append((Line2D([0], [0],
                            marker='x',
                            color=color,
                            linestyle='None'), label))
lines, labels = zip(*elements)
ax.legend(lines,
          labels,
          loc='upper center',
          ncol=3,
          framealpha=1,
          prop={'size': 8},
          bbox_to_anchor=(0.5, 1.07),
          bbox_transform=ax.transAxes)

# Save figure
plt.tight_layout()
plt.savefig(rel_path('./plots/tracking.pdf'), dpi=600)
コード例 #15
0
f, (ax1) = plt.subplots(1, 1)

for p in SIDELOBES:

    pop = pop_obs[p]
    limit = 1e-9

    s_peak = pop.frbs.s_peak
    dm_igm = pop.frbs.dm_igm

    mini = min(s_peak)
    maxi = max(s_peak)

    bins_s_peak = np.logspace(np.log10(mini), np.log10(maxi), 50)

    dm_igm = dm_igm[(s_peak > limit)]

    print(f'{len(dm_igm)} FRBs in graph of {pop.name}')

    n, bins = np.histogram(dm_igm, bins=50)
    n = n/max(n)
    bincentres = (bins[:-1] + bins[1:]) / 2
    ax1.step(bincentres, n, where='mid', label=p)

ax1.set_xlabel(r'DM$_{\text{IGM}}$')
ax1.set_ylabel(r'Fraction')
ax1.set_ylim([0, 1])
ax1.legend()
plt.tight_layout()
plt.savefig(rel_path('./plots/dm_igm_sidelobes.pdf'))
コード例 #16
0
def plot_data(df):
    """Plot transient properities in a DataFrame."""
    # plot_aa_style(cols=2)
    plt.rcParams["figure.figsize"] = (5.75373, 5.75373*3)
    plt.rcParams["font.family"] = "Times"
    plt.rcParams['pdf.fonttype'] = 42

    fig = plt.figure()
    ax = fig.add_subplot(111, projection=Axes3D.name)

    # Clean data
    df = df[df.bw < 1e10]

    colors = plt.rcParams['axes.prop_cycle'].by_key()['color']
    markers = list(MarkerStyle.markers.keys())
    markers = ['*', '^', 's', '.', 's']

    c = 0
    for obj, mdf in df.groupby(['type']):
        print(f'Plotting {obj}s')
        color = colors[c]
        marker = markers[c]

        c += 1
        alpha = 1
        linewidth = 1
        markersize = 30
        if len(mdf.w_eff) > 5:
            alpha = 0.3
            linewidth = 0.7
            markersize = 10
        if len(mdf.w_eff) > 100:
            alpha = 0.1
            linewidth = 0.2
            markersize = 5

        ax.scatter(np.log10(mdf.w_eff*1e3),
                   np.log10(mdf.bw),
                   np.log10(mdf.pseudo_lum),
                   label=obj,
                   color=color,
                   s=markersize,
                   marker=marker)

        for i in range(len(mdf)):
            ax.plot([np.log10(mdf.w_eff.iloc[i]*1e3) for n in range(2)],
                    [np.log10(mdf.bw.iloc[i]) for n in range(2)],
                    [np.log10(mdf.pseudo_lum.iloc[i]), -4],
                    color=color,
                    alpha=alpha,
                    linewidth=linewidth)

    def power_of_10(n):
        c = 10 ** round(np.log10(n))
        if type(n) == float:
            c = float(c)
        return np.isclose(c, n) or 10 * c == n

    # Set axis properties
    def log_tick_formatter(val, pos=None):
        new_val = 10**val
        return r"$10^{%02d}$" % (val)
        if power_of_10(new_val):
            return "{:.3g}".format(new_val)
        else:
            return ''

    for axis in (ax.xaxis, ax.yaxis, ax.zaxis):
        axis.set_major_formatter(mticker.FuncFormatter(log_tick_formatter))

    # Set labels
    ax.set_xlabel(r'Pulse Width (ms)')
    ax.set_ylabel(r'Bandwidth (MHz)')
    ax.set_zlabel(r'S$_{peak}$D$^2$ (Jy kpc$^2$)')
    plt.legend()

    # Equal figure proportions
    ax.set_xlim(-1, 4)
    ax.set_ylim(1, 6)
    ax.set_zlim(-4, 14)

    # Get rid of colored axes planes
    # First remove fill
    ax.xaxis.pane.fill = False
    ax.yaxis.pane.fill = False
    ax.zaxis.pane.fill = False

    # Now set color to white (or whatever is "invisible")
    ax.xaxis.pane.set_edgecolor('w')
    ax.yaxis.pane.set_edgecolor('w')
    ax.zaxis.pane.set_edgecolor('w')

    # Save figure
    ax.view_init(azim=-52, elev=10)
    plt.tight_layout()

    plt.savefig(rel_path('./plots/transients.pdf'), transparent=True)
コード例 #17
0
# Fluence plot
ax1.set_xlabel('S/N')
ax1.set_xscale('log')
ax1.set_ylabel(r'\#(${>}\text{S/N}$)')
ax1.set_yscale('log')
# ax1.set_xlim(9, 1e5)
# ax1.set_ylim(1e-3, 1e3)

# Update fluence plot
for i, surv_pop in enumerate(surv_pops):
    name = surv_pop.name.split('_')[-1]
    snr = surv_pop.frbs.snr
    try:
        bins, values = hist(snr, bin_type='log', norm=None)
    except ValueError:
        bins, values = np.array([np.nan]), np.array([np.nan])

    # Cumulative sum
    values = np.cumsum(values[::-1])[::-1]

    # Normalise to area on sky
    if not np.isnan(values.all()):
        values = values * surv_pop.source_rate.f_area

    plt.step(bins, values, where='mid', label=name)

plt.legend()
plt.tight_layout()
plt.savefig(rel_path('./plots/logn_logs_local_lum_1e36_w_int.pdf'))
コード例 #18
0
f, (ax1) = plt.subplots(1, 1)

for p in BEAMPATTERNS:

    pop = pop_obs[p]
    limit = 1e-9

    s_peak = pop.frbs.s_peak
    dm_igm = pop.frbs.dm_igm

    mini = min(s_peak)
    maxi = max(s_peak)

    bins_s_peak = np.logspace(np.log10(mini), np.log10(maxi), 50)

    dm_igm = dm_igm[(s_peak > limit)]

    print(f'{len(dm_igm)} FRBs in graph of {pop.name}')

    n, bins = np.histogram(dm_igm, bins=50)
    n = n / max(n)
    bincentres = (bins[:-1] + bins[1:]) / 2
    ax1.step(bincentres, n, where='mid', label=p)

ax1.set_xlabel(r'DM$_{\text{IGM}}$')
ax1.set_ylabel(r'Fraction')
ax1.set_ylim([0, 1])
ax1.legend()
plt.tight_layout()
plt.savefig(rel_path('./plots/dm_igm_beampatterns.pdf'))
コード例 #19
0
    if pattern.startswith('airy'):
        n_sidelobes = int(pattern[-1])
        p = 'airy'
        if n_sidelobes == 0:
            z = 10

    s = Survey(SURVEY)
    s.set_beam(model=p, n_sidelobes=n_sidelobes)
    int_pro, offset = s.calc_beam(shape=n)

    # Sort the values
    sorted_int = np.argsort(offset)
    int_pro = int_pro[sorted_int]
    offset = offset[sorted_int]

    # Clean up lower limit
    offset = offset[int_pro > MIN_Y]
    int_pro = int_pro[int_pro > MIN_Y]

    print(f'Beam size at FWHM: {s.beam_size_at_fwhm}')
    print(f'Beam size with {n_sidelobes} sidelobes: {s.beam_size}')

    plt.plot(offset, int_pro, label=pattern, zorder=z)

plt.xlabel(r'Offset ($^{\circ}$)')
plt.ylabel('Intensity Profile')
plt.yscale('log')
plt.legend(loc='upper right')
plt.tight_layout()
plt.savefig(rel_path('plots/beam_int_theory.pdf'))
コード例 #20
0
ファイル: sidelobes.py プロジェクト: telegraphic/frbpoppy
for sidelobe in reversed(SIDELOBES):

    args = {'sidelobes': sidelobe}

    s = Survey(SURVEY)
    s.set_beam(model='airy', n_sidelobes=sidelobe)
    int_pro, offset = s.calc_beam(shape=n)

    # Sort the values
    sorted_int = np.argsort(offset)
    int_pro = int_pro[sorted_int]
    offset = offset[sorted_int]

    # Clean up lower limit
    offset = offset[int_pro > MIN_Y]
    int_pro = int_pro[int_pro > MIN_Y]

    label = f'{sidelobe} sidelobes'
    if sidelobe == 1:
        label = label[:-1]

    plt.plot(offset, int_pro, label=label)

plt.xlabel(r'Offset ($^{\circ}$)')
plt.ylabel('Intensity Profile')
plt.yscale('log')
plt.legend()
plt.tight_layout()
plt.savefig(rel_path('./plots/beam_int_sidelobes.pdf'))
コード例 #21
0
# Fluence plot
ax1.set_xlabel('S/N')
ax1.set_xscale('log')
ax1.set_ylabel(r'\#(${>}\text{S/N}$)')
ax1.set_yscale('log')

# Update fluence plot
for i, surv_pop in enumerate(surv_pops):
    name = surv_pop.name.split('_')[-1]
    snr = surv_pop.frbs.snr

    if snr.size == 0:
        pprint(f'No FRBs in {name} population')
        continue

    bins, values = hist(snr, bin_type='log', norm=None)

    # Cumulative sum
    values = np.cumsum(values[::-1])[::-1]

    # Normalise to area on sky
    if not np.isnan(values.all()):
        values = values * surv_pop.source_rate.f_area

    plt.step(bins, values, where='mid', label=name)

plt.legend()
plt.tight_layout()
plt.savefig(rel_path('./plots/logn_logs_future_surveys.pdf'))
コード例 #22
0
ax.set_yticks(ys)
ax.set_yticklabels(names)
colors = plt.rcParams['axes.prop_cycle'].by_key()['color']
for i, y in enumerate(ax.get_yticklabels()):
    y.set_color(colors[i])
ax.invert_yaxis()  # labels read top-to-bottom

# Add thin grey horizontal lines
x_lim = ax.get_xlim()
ax.set_xlim(x_lim)
for i, y in enumerate(ys):
    ax.plot((x_lim[0], rates[i]), (y, y), color='k', lw=0.5, zorder=0, ls='--')

for e in list(zip(SURVEYS, rates)):
    pprint(e)

euclidean_lines = True
if euclidean_lines:
    xlims = axes[1].get_xlim()
    ylims = axes[1].get_ylim()
    axes[1].set_xlim(xlims)
    axes[1].set_ylim(ylims)
    xs = np.logspace(np.log10(xlims[0]), np.log10(xlims[1]), 100)
    for n in range(-10, 15):
        ys = 10**((np.log10(xs) + n) * -1.5)
        axes[1].plot(xs, ys, 'k:', linewidth=0.25)

# plt.legend()
plt.tight_layout()
plt.savefig(rel_path('./plots/future_surveys.pdf'))
コード例 #23
0
ファイル: obs_rep_frac.py プロジェクト: telegraphic/frbpoppy
    # Set up plot style
    plot_aa_style(cols=1)
    f, ax1 = plt.subplots(1, 1)

    # See how the real fraction changes over time
    chime_fracs = []
    dts = calc_rep_frac()
    days = [d for d in range(301)]
    for day in tqdm(days, desc='frbcat'):
        n_rep = sum([dt <= day for dt in dts])
        n_one_offs = 2 * day
        try:
            frac = n_rep / (n_rep + n_one_offs)
        except ZeroDivisionError:
            frac = np.nan
        chime_fracs.append(frac)

    ax1.plot(days, chime_fracs, label='chime-frb')

    # Further plot details
    ax1.set_xlabel(r'Time (days)')
    ax1.set_ylabel(r'$f_{\textrm{rep}}$')
    # Equal to $N_{\textrm{repeaters}}/N_{\textrm{detections}}$
    ax1.set_xlim(0, max(days))
    ax1.set_yscale('log')

    # Save figure
    plt.tight_layout()
    plt.savefig(rel_path('plots/obs_rep_frac_chime.pdf'))
    plt.clf()
コード例 #24
0
ファイル: burstiness.py プロジェクト: telegraphic/frbpoppy
chime_dms = np.array(chime_dms)
chime_n_bursts = np.array(chime_n_bursts)
chime_n_days = (max(group.timestamp) - min(group.timestamp)).days

ax2 = ax1.twinx()

if CHIME_HIST:
    n_bursts = []
    for bin in zip(bins[:-1], bins[1:]):
        low, high = bin
        ii = np.where((chime_dms >= low) & (chime_dms < high))
        n_burst_per_src = chime_n_bursts[ii]
        n_bursts.append(np.mean(n_burst_per_src))

    ax2.step(bins[:-1], np.array(n_bursts), where='mid', label='chime-frb',
             color=colors[len(lum_funcs)])
else:
    ax2.scatter(chime_dms, chime_n_bursts, label='chime-frb', marker='x',
                color=colors[len(lum_funcs)])


ax2.set_ylabel(r'$n_{\text{obs.~bursts, chime}}$', color=colors[len(lum_funcs)])
ax2.tick_params(axis='y', labelcolor=colors[len(lum_funcs)])

ax1.set_xlabel(r'DM$_{\textrm{ex}}$ ($\textrm{pc}\ \textrm{cm}^{-3}$)')

plt.tight_layout()
plt.savefig(rel_path('plots/burstiness.pdf'))
plt.clf()
コード例 #25
0
    s.set_beam(model=pattern)
    int_pro, offset = s.calc_beam(shape=n)

    # Sort the values
    sorted_int = np.argsort(offset)
    int_pro = int_pro[sorted_int]
    offset = offset[sorted_int]

    bins = 1e2

    bin_means, bin_edges, bin_numbers = bstat(offset,
                                              int_pro,
                                              statistic='mean',
                                              bins=bins)

    bin_mins, _, _ = bstat(offset, int_pro, statistic='min', bins=bins)
    bin_maxs, _, _ = bstat(offset, int_pro, statistic='max', bins=bins)

    center = (bin_edges[:-1] + bin_edges[1:]) / 2

    plt.plot(center, bin_means, label=pattern)
    plt.fill_between(center, bin_mins, bin_maxs, alpha=0.2)


plt.xlabel(r'Offset ($^{\circ}$)')
plt.ylabel('Intensity Profile')
plt.yscale('log')
plt.legend()
plt.tight_layout()
plt.savefig(rel_path('plots/beam_int_patterns.pdf'))
コード例 #26
0
                   27.7, 18.9, 17.84, 10.2, 14.84, 10.25]
snrs['fast-crafts'] = [19]
# Start plot
plot_aa_style()
fig, ax1 = plt.subplots(1, 1)

# Fluence plot
ax1.set_xlabel('S/N')
ax1.set_xscale('log')
ax1.set_ylabel(r'\#(${>}\text{S/N}$)')
ax1.set_yscale('log')

# Update fluence plot
for survey in SURVEYS:
    name = survey
    snr = snrs[survey]

    try:
        bins, values = hist(snr, bin_type='log', norm=None)

        # Cumulative sum
        values = np.cumsum(values[::-1])[::-1]

        plt.step(bins, values, where='mid', label=name)
    except ValueError:
        continue

plt.legend()
plt.tight_layout()
plt.savefig(rel_path('./plots/logn_logs_current.pdf'))
コード例 #27
0
        ns[s] = ns[s][1:]
        bins = bins[1:]

        bincentres = (bins[:-1] + bins[1:]) / 2

        title = titles[i]
        plt.step(bincentres, ns[s], where='mid', label=title)

        i += 1

    plt.xlabel('$z$')
    plt.ylabel(r'$\text{d}n_{\text{FRB}}/\text{d}z$')
    plt.yscale('log')
    plt.legend()
    plt.tight_layout()
    plt.savefig(rel_path('plots/number_frbs.pdf'))
    plt.clf()

if DENSITY_FRBS:
    plot_aa_style()

    fig = plt.figure()
    ax = fig.add_subplot(111)

    # Get dV
    import frbpoppy.precalc as pc
    d = pc.DistanceTable().lookup(z=bincentres)
    dvols = d[3]
    dens = {}
    i = 0
    for s in pop_types:
コード例 #28
0
n_gt_s = np.cumsum(hist[::-1])[::-1]

# Calculate alpha
alpha, alpha_err, norm = surv_pop.frbs.calc_logn_logs(parameter='fluence',
                                                      min_p=min_p,
                                                      max_p=max_p)

print(alpha, alpha_err, norm)
xs = 10**((np.log10(edges[:-1]) + np.log10(edges[1:])) / 2)
xs = xs[xs >= min_p]
xs = xs[xs <= max_p]
ys = [norm * x**(alpha) for x in xs]

plot_aa_style()
fig = plt.figure()
ax = fig.add_subplot(111)

plt.step(edges[:-1], n_gt_s, where='post')
plt.plot(xs,
         ys,
         linestyle='--',
         label=rf'$\alpha$ = {alpha:.3} $\pm$ {round(abs(alpha_err), 2)}')

plt.xlabel('Fluence (Jy ms)')
plt.ylabel(r'N(${>}Fluence$)')
plt.xscale('log')
plt.yscale('log')
plt.legend()
plt.tight_layout()
plt.savefig(rel_path('plots/logn_logf_local.pdf'))
コード例 #29
0
def plot(frbcat, frbpop):
    """Plot distributions."""
    # Change working directory
    plot_aa_style(cols=2)

    f, axes = plt.subplots(2, 2, sharex='col', sharey='row')

    axes[1, 0].set_xlabel(r'DM ($\textrm{pc}\ \textrm{cm}^{-3}$)')
    axes[1, 1].set_xlabel(r'S/N')
    axes[1, 1].set_xscale('log')

    axes[1, 0].set_ylabel('Fraction')
    axes[1, 0].set_yscale('log')
    axes[1, 0].set_ylim(3e-2, 1.2e0)
    axes[0, 0].set_ylabel('Fraction')
    axes[0, 0].set_yscale('log')
    axes[0, 0].set_ylim(3e-2, 1.2e0)

    # Set colours
    cmap = plt.get_cmap('tab10')([0, 1])

    # Plot dm distribution
    for i, p in enumerate((frbcat, frbpop)):
        for t in ['r', 'o']:

            # Line style
            linestyle = 'solid'
            label = 'one-offs'
            alpha = 1
            a = 0
            if t == 'r':
                linestyle = 'dashed'
                label = 'repeaters'
                a = 1

            n_bins = 40
            if len(p[t]['dm']) < 20:
                n_bins = 10

            bins = np.linspace(0, 2000, n_bins)
            axes[a, 0].step(*hist(p[t]['dm'], norm='max', bins=bins),
                            where='mid', linestyle=linestyle, label=label,
                            color=cmap[i], alpha=alpha)

            # Plot SNR distribution
            bins = np.logspace(0.8, 3.5, n_bins)
            axes[a, 1].step(*hist(p[t]['snr'], norm='max', bins=bins),
                            where='mid', linestyle=linestyle, label=label,
                            color=cmap[i], alpha=alpha)

    for t in ['r', 'o']:
        for p in ('dm', 'snr'):
            row = 0
            col = 0
            if p == 'snr':
                col = 1
            if t == 'r':
                row = 1

            ks = ks_2samp(frbpop[t][p], frbcat[t][p])
            print(t, p, ks)

            text = fr'$p={round(ks[1], 2)}$'
            if ks[1] < 0.01:
                # text = r'$p < 0.01$'
                text = fr'$p={round(ks[1], 3)}$'
            anchored_text = AnchoredText(text, loc='upper right',
                                         borderpad=0.5, frameon=False)
            axes[row, col].add_artist(anchored_text)

    # Set up layout options
    f.subplots_adjust(hspace=0)
    f.subplots_adjust(wspace=0.07)

    # Add legend elements
    elements = []

    def patch(color):
        return Patch(facecolor=color, edgecolor=color)

    elements.append((patch(cmap[0]), 'Frbcat'))
    elements.append((patch(cmap[1]), 'Frbpoppy'))

    # Add line styles
    elements.append((Line2D([0], [0], color='gray'), 'One-offs'))
    elements.append((Line2D([0], [0], color='gray', linestyle='dashed'),
                     'Repeaters'))

    lines, labels = zip(*elements)

    lgd = plt.figlegend(lines, labels, loc='upper center', ncol=4,
                        framealpha=1,  bbox_to_anchor=(0.485, 1.04),
                        columnspacing=1.1, handletextpad=0.3)

    path = rel_path('./plots/frbpoppy_chime.pdf')
    plt.savefig(path, bbox_extra_artists=(lgd,), bbox_inches='tight')

    # Check p-value above S/N 15
    for t in ['r', 'o']:
        mask_frbpop = (frbpop[t]['snr'] > 15)
        mask_frbcat = (frbcat[t]['snr'] > 15)
        for par in ['dm', 'snr']:
            ks = ks_2samp(frbpop[t][par][mask_frbpop],
                          frbcat[t][par][mask_frbcat])
            print(t, par, ks, len(frbpop[t][par][mask_frbpop]),
                  len(frbcat[t][par][mask_frbcat]))
コード例 #30
0
    ax.xaxis.pane.set_edgecolor('w')
    ax.yaxis.pane.set_edgecolor('w')
    ax.zaxis.pane.set_edgecolor('w')

    # Save figure
    ax.view_init(azim=-52, elev=10)
    plt.tight_layout()

    plt.savefig(rel_path('./plots/transients.pdf'), transparent=True)
    # plt.show()


if __name__ == '__main__':

    RELOAD = False
    csv_path = rel_path('./plots/transients.csv')

    if RELOAD:
        test = pd.DataFrame({'obj': ['a', 'a', 'b'],
                             'pseudo_lum': [1e40, 1e41, 1e40],
                             'w_eff': [1, 100, 0.1],
                             'bw': [800, 1400, 1000]})

        pulsars = import_pulsars(use_epn=True)
        frbs = import_frbcat()
        magnetars = import_magnetars()
        giants = import_crab_giants()

        tot_df = pd.concat([frbs, pulsars, magnetars, giants], sort=False)

        tot_df.to_csv(csv_path)