def calc_cum_hist(self, pop): # Bin up parameter in a cumulative bin edges, values = hist(pop.frbs.snr, bin_type='log') if isinstance(edges, float): return np.nan, np.nan n_gt_s = np.cumsum(values[::-1])[::-1] # Normalise to S/N of 10^5 log_diff = (np.log10(edges[0]) - np.log10(1e0)) edges = 10**(np.log10(edges) - log_diff) return edges, n_gt_s
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'))
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'))
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]))
""" mean, std = calc_lognormal_input(mean, std) return np.random.lognormal(mean, std, shape) fig, axes = plt.subplots(1, 1, sharey=True) mean = 2.71**2 std = 5 size = int(1e4) axes.set_xscale('log', basex=2.71) colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] data = lognormal(mean, std, size) xy = hist(data, bin_type='log') label = 'Distribution with input (frbpoppy)' axes.step(*xy, where='mid', color=colors[0], label=label) axes.axvline(mean, color=colors[0], linestyle='dotted') axes.text(mean, 1, mean) axes.axvline(mean + std, color=colors[0], linestyle='dotted') axes.text(mean + std, 1, f'{mean}+{std}') data = np.random.lognormal(mean, std, size) xy = hist(data, bin_type='log') label = 'Underlying normal input (numpy)' axes.step(*xy, where='mid', color=colors[1], label=label) axes.axvline(mean, color=colors[1], linestyle='dotted') axes.text(mean, 1, mean) axes.axvline(mean + std, color=colors[1], linestyle='dotted') axes.text(mean + std, 1, f'{mean}+{std}')
if surv_pop.n_sources() == 0: print(surv_pop.source_rate) print(f'{name} | no FRBs in population') continue names.append(name) ys.append(y) # Dimensions measure plot ax = axes[0] ax.set_xlabel(r'DM ($\textrm{pc}\ \textrm{cm}^{-3}$)') ax.set_ylabel(r'\#') ax.set_yscale('log') bins, values = hist(surv_pop.frbs.dm, bin_type='lin', norm='frac', n_bins=20) values = values.astype(np.float64) values *= float(surv_pop.source_rate.f_area) * 1e6 ax.step(bins, values, where='mid', label=name) # Fluence plot ax = axes[1] ax.set_xlabel('S/N') ax.set_xscale('log') ax.set_ylabel(r'\#(${>}\text{S/N}$)') ax.set_yscale('log') # Update fluence plot bins, values = hist(surv_pop.frbs.snr, bin_type='log',
# Distinguish populations if pop.name.endswith('(1 burst)'): label = '1 burst' linestyle = 'solid' elif pop.name.endswith('(> 1 burst)'): label = '$>$1 burst' linestyle = 'dashed' else: label = 'cosmic' linestyle = 'dashdot' pprint(f'Number of bursts in {label}: {pop.n_bursts()}') # Do stuff with data dm = pop.frbs.dm x, y = hist(dm) x *= 200 # Normalise x-axis z=0.01, z=2 # Plot DM distributions ax1.step(x, y, where='mid', linestyle=linestyle, label=label, color=colors[i]) # Plot fluence distributions snr = pop.frbs.snr if snr is None: continue
time = surv_pop.frbs.time # Set up plot plot_aa_style() if isinstance(rate_dist, np.ndarray): min_rate = np.log10(np.min(rate_dist[rate_dist != 0])) max_rate = np.log10(max(rate_dist)) else: min_rate = np.log10(RATE) - 1 max_rate = np.log10(RATE) + 1 rate_dist = np.array(rate_dist) bins = np.logspace(min_rate, max_rate, 20) # 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)
def plot_dists(surv_pop, telescope): """Plot the fluence and DM distribution of a surveyed population. Args: surv_pop (Population): Population from which to plot telescope (str): Name of the telescope with which to compare the distribution. Necessary for Frbcat. """ plot_aa_style(cols=2) # Plot dm distribution f, (ax1, ax2) = plt.subplots(1, 2, sharey=True) dm_frbpoppy = surv_pop.frbs.dm pprint(f'Number of detected FRBs: {len(dm_frbpoppy)}') ax1.step(*hist(dm_frbpoppy), where='mid', linestyle='dashed') df = Frbcat().df dm_frbcat = df[df.telescope == telescope].dm ax1.step(*hist(dm_frbcat), where='mid') # Compare distributions ks = ks_2samp(dm_frbpoppy, dm_frbcat) text = fr'$p={round(ks[1], 2)}$' anchored_text = AnchoredText(text, loc=1, borderpad=1., frameon=False) ax1.add_artist(anchored_text) ax1.set_xlabel(r'DM ($\textrm{pc}\ \textrm{cm}^{-3}$)') ax1.set_ylabel('Fraction') ax1.set_ylim([0, 1.1]) ax1.set_xlim([0, 3500]) # Plot fluence distributions fluence_frbpoppy = surv_pop.frbs.fluence ax2.step(*hist(fluence_frbpoppy, bin_type='log'), where='mid', label='frbpoppy', linestyle='dashed') fluence_frbcat = df[df.telescope == telescope].fluence ax2.step(*hist(fluence_frbcat, bin_type='log'), where='mid', label='frbcat') # Compare distributions ks = ks_2samp(fluence_frbpoppy, fluence_frbcat) text = fr'$p={round(ks[1], 2)}$' anchored_text = AnchoredText(text, loc=1, borderpad=1., frameon=False) ax2.add_artist(anchored_text) ax2.set_xlabel(r'Fluence (Jy ms)') ax2.set_ylim([0, 1.1]) ax2.set_xlim([5e-1, 1e4]) plt.xscale('log') plt.figlegend(loc='upper center', ncol=2, framealpha=1) plt.tight_layout() plt.savefig(rel_path(f'plots/frbpoppy_{telescope}.pdf')) plt.clf()
def update(*args): """Update plot if widgets change.""" # Which parameter is on the x axis of the rate plot? x_axis = x_para.value_selected ax2.set_xlabel(x_axis) # What values do the parameters have? vars = {s.label.get_text(): s.val for s in sliders} # Update fluence plot for i, line in enumerate(flnc_lines): survey = line.get_label() pop = get_pops(**vars, survey=survey)[0] snr = 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 values = values * pop.source_rate.f_area line.set_xdata(bins) line.set_ydata(values) # Figure out new condition masks = [] for p in parameters: if p != x_axis: masks.append((df[p] == vars[p])) mask = np.bitwise_and.reduce(np.array(masks)) # Scale to which survey scale_survey = scaling.value_selected y_scaling = df[mask][scale_survey].values real_scaling = rates[scale_survey] # Update rate values for i, line in enumerate(rate_lines): survey = line.get_label() x = df[x_axis].unique() y = df[mask][survey] / y_scaling line.set_xdata(x) line.set_ydata(y) # Set up expectation intervals middle = rates[survey] / real_scaling top, bot = poisson_interval(n_frbs[survey], sigma=2) top = (top / n_days[survey]) / real_scaling bot = (bot / n_days[survey]) / real_scaling left = min(x) right = max(x) xy = list(zip([left, right, right, left], [top, top, bot, bot])) intervals[i].set_xy(xy) expects[i].set_xdata([left, right]) expects[i].set_ydata([middle] * 2) # Fluence plot # Rates plot ax2.set_xlim(min(x), max(x)) ax2.set_ylim(1e-2, 1e2) ax2.autoscale_view() fig.canvas.draw_idle()
cosmic_pop.set_lum(model='powerlaw', low=1e40, high=1e45) cosmic_pop.generate() # Setup a survey survey = Survey('perfect') # Observe the FRB population survey_pop = SurveyPopulation(cosmic_pop, survey) plot_aa_style(cols=2) f, axes = plt.subplots(1, 2) s = survey_pop.frbs bins, values = hist(s.snr, bin_type='log') # Cumulative sum values = np.cumsum(values[::-1])[::-1] axes[0].step(bins, values, where='mid') axes[0].set_title('SNR') bins, values = hist(s.fluence, bin_type='log') # Cumulative sum values = np.cumsum(values[::-1])[::-1] axes[1].step(bins, values, where='mid') axes[1].set_title(r'Fluence') # Set axis axes[0].set_xscale('log') axes[0].set_yscale('log') axes[1].set_xscale('log')
from frbpoppy import CosmicPopulation, Survey, SurveyPopulation, hist from tests.convenience import plot_aa_style, rel_path pop = CosmicPopulation.simple(1e4, generate=False) pop.generate() survey = Survey('perfect') survey_pop = SurveyPopulation(pop, survey) plot_aa_style() plt.rcParams["figure.figsize"] = (5.75373, 5.75373) f, axes = plt.subplots(2, 2) s = survey_pop.frbs axes[0, 0].step(*hist(s.snr, bin_type='log'), where='mid') axes[0, 0].set_title('SNR') axes[1, 0].step(*hist(s.T_sys, bin_type='log'), where='mid') axes[1, 0].set_title(r'T$_{\text{sys}}$') axes[0, 1].step(*hist(s.s_peak, bin_type='log'), where='mid') axes[0, 1].set_title(r'S$_{\text{peak}}$') axes[1, 1].step(*hist(s.w_arr, bin_type='log'), where='mid') axes[1, 1].set_title(r'w$_{\text{arr}}$') for x in [0, 1]: for y in [0, 1]: axes[x, y].set_xscale('log') axes[x, y].set_yscale('log')
ax1_elements = [] ax2_elements = [(Line2D([0], [0], color='gray'), 'perfect')] for i, dist_type in enumerate(dist_types): print(f'Distribution type: {dist_type}') color = colors[i] # Plot rates rate = np.array([RATE]) if dist_type == 'mix': rate = np.array([RATE, 0]) bins = np.linspace(0, 0.5, 40) rates, values = hist(rate, bins=bins, norm='prob') if dist_type == 'dist': rate_dist = log10normal(RATE, 2, N_SRCS) rates, values = hist(rate_dist, bins=bins, norm='prob') if dist_type == 'weibull': rate_dist = clustered(n_srcs=N_SRCS, n_days=MAX_DAYS, z=0) rates, values = hist(rate_dist, bins=bins, norm='prob') ax1.step(rates, values, where='mid', label=dist_type, color=color) r = adapt_pop(r_pop, dist_type) surv_pop = SurveyPopulation(r, survey) linestyle = linestyles[0]