elif src not in srcs_seen_twice: # Timedelta at which repeater detected time_rep_seen.append(dt) srcs_seen_twice.append(src) return time_rep_seen if __name__ == '__main__': import matplotlib.pyplot as plt from tests.convenience import plot_aa_style, rel_path import numpy as np from tqdm import tqdm # 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)
"""Plot intensity profile of sidelobes.""" import matplotlib.pyplot as plt import numpy as np from frbpoppy.survey import Survey from tests.convenience import plot_aa_style, rel_path SIDELOBES = [0, 1, 2, 8] SURVEY = 'wsrt-apertif' MIN_Y = 1e-7 n = 50000 plot_aa_style() 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]
def plot(self, run): # Get data # For each requested run df = self.so.df par_set = df[df.run == run].par_set.iloc[0] # For each parameter for main_par in self.run_pars[par_set]: pprint(f'Plotting {main_par}') other_pars = [e for e in self.run_pars[par_set] if e != main_par] for compare_par in ['dm', 'snr']: compare_col = f'{compare_par}_gof' pprint(f' - {compare_col}') for survey, group_surv in df[df.run == run].groupby('survey'): pprint(f' - {survey}') # Set up plot plot_aa_style() plt.rcParams["figure.figsize"] = (5.75373 * 3, 5.75373 * 3) plt.rcParams['figure.max_open_warning'] = 125 n_x = group_surv[other_pars[0]].nunique() if len(other_pars) > 1: n_y = group_surv[other_pars[1]].nunique() else: n_y = 1 fig, ax = plt.subplots(n_x, n_y, sharex='col', sharey='row') groups = group_surv.groupby(other_pars) x = -1 for i, (other_pars_vals, group) in enumerate(groups): bins = group[main_par].values values = group[compare_col].values bins, values = self.add_edges_to_hist(bins, values) if n_y > 1: y = i % n_y if y == 0: x += 1 a = ax[y, x] else: y = i a = ax[y] a.step(bins, values, where='mid') a.set_title = str(other_pars_vals) diff = np.diff(bins) if diff[1] != diff[0]: a.set_xscale('log') # Set axis label if y == n_y - 1: p = other_pars[0] if isinstance(other_pars_vals, float): val = other_pars_vals else: val = other_pars_vals[0] p = p.replace('_', ' ') a.set_xlabel(f'{p} = {val:.2}') if x == 0: p = other_pars[1] val = other_pars_vals[1] p = p.replace('_', ' ') a.set_ylabel(f'{p} = {val:.2}') # Set axis limits subset = df[df.run == run][main_par] y_subset = group_surv[compare_col].copy() try: low = np.nanmin(y_subset) high = np.nanmax(y_subset) except ValueError: low = 0.0001 high = 1 log = False if low > 0 and high > 0: log = True for a in ax.flatten(): a.set_xlim(subset.min(), subset.max()) if log: a.set_yscale('log', nonposy='clip') a.set_ylim(low, high) p = main_par.replace('_', ' ') fig.suptitle(f'{p} - {compare_par} - {survey}') plt.tight_layout() plt.subplots_adjust(top=0.95) # Save to subdirectory path_to_save = rel_path(f'./plots/mc/{main_par}_run{run}/') if not os.path.isdir(path_to_save): os.mkdir(path_to_save) path_to_save += f'{compare_par}_{survey}.pdf' plt.savefig(path_to_save) plt.clf()
else: pop.generate() surv_pop = SurveyPopulation(pop, survey, scale_by_area=False) surv_pop.source_rate.f_area = surv_f_area[name] surv_pop.source_rate.scale_by_area() # surv_pop.save() surv_pops.append(surv_pop) else: surv_pops = [] for name in SURVEYS: surv_pops.append(unpickle(f'optimal_{name}')) # Start plot plot_aa_style(cols=2) plt.rcParams["figure.figsize"] = (3.556 * 3, 3.556) fig, axes = plt.subplots(1, 3) for ax in axes.flatten(): ax.set_aspect('auto') # Get norm pop y = 0 ys = [] names = [] rates = [] norm_sim_rate = surv_pops[0].source_rate.det norm_real_rate = EXPECTED['parkes-htru'][0] / EXPECTED['parkes-htru'][1] norm_rate = norm_sim_rate / norm_real_rate
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()