def plot_ra_distribution(sin_dec, n_sources): filename = plot_output_dir( f"{raw}{sin_dec:.4f}/{int(n_sources)}sources/ra_distribution.pdf") title = rf"sin($\delta$)={sin_dec:.2f} \n n={n_sources:.0f}" catalogue_filename = fs_sources(str(int(n_sources)), sin_dec) c = np.load(catalogue_filename) ra = c["ra_rad"] f, a = plt.subplots() a.hist(ra) a.set_xlabel("right ascensions") a.set_title(title) f.savefig(filename) plt.close()
from __future__ import print_function import numpy as np from flarestack.shared import catalogue_dir, plot_output_dir import matplotlib.pyplot as plt cats = ["jetted", "gold", "obscured", "silver"] for j, cat in enumerate(cats): cat_path = catalogue_dir + "TDEs/TDE_" + cat + "_catalogue.npy" catalogue = np.load(cat_path) times = catalogue["End Time (MJD)"] - catalogue["Start Time (MJD)"] print(cat, "Livetime", np.sum(times)) savepath = plot_output_dir("analyses/tde/") + cat + "_hist.pdf" plt.figure() plt.hist(times, range=(0, max(times)), bins=20) plt.xlabel("Search Window (Days)") plt.title(cat + " TDEs") plt.savefig(savepath) plt.close()
def agn_cores_output_dir(name="foldername"): return plot_output_dir("analyses/agn_cores/" + name + "/")
sens_ratios, yerr=sens_ratio_errs, color="red", marker="o") ax2.scatter(sindecs, disc_ratios, color="k") ax2.plot(sindecs, disc_ratios, color="k", linestyle="--") ax2.set_ylabel(r"ratio", fontsize=12) ax2.set_xlabel(r"sin($\delta$)", fontsize=12) # ax1.set_xlim(xmin=-1.0, xmax=1.0) # ax2.set_ylim(ymin=0.5, ymax=1.5) ax2.grid(True) xticklabels = ax1.get_xticklabels() plt.setp(xticklabels, visible=False) plt.subplots_adjust(hspace=0.001) # ratio_interp = interp1d(sindecs, sens_ratios) # # interp_range = np.linspace(np.min(sindecs), # np.max(sindecs), 1000) # ax1.plot( # interp_range, # reference_sensitivity(interp_range)*ratio_interp(interp_range), # color='red', linestyle="--", label="Ratio Interpolation") ax1.legend(loc="upper right", fancybox=True, framealpha=1.0) plt.savefig(plot_output_dir(name) + "/7yearPS.pdf") plt.close()
ratio_sens.append(astro_sens[key] / int_xray) # fluence ratio_disc.append(astro_disc[key] / int_xray) ratio_sens_100GeV10PeV.append(astro_sens_100GeV10PeV[key] / int_xray) # fluence ratio_disc_100GeV10PeV.append(astro_disc_100GeV10PeV[key] / int_xray) n_src.append(nr_srcs) except OSError: pass # # Save arrays to file np.savetxt( plot_output_dir(base_dir) + "data.out", ( np.array(n_src), np.array(int_xray_flux_erg), np.array(e_min_gev), np.array(e_max_gev), np.array(sens), np.array(sens_err_low), np.array(sens_err_upp), np.array(disc_pot), np.array(disc_ts_threshold), np.array(sens_livetime), np.array(disc_pots_livetime), np.array(ratio_sens), np.array(ratio_disc), np.array(ratio_sens) / saturate_ratio,
logging.debug("y: " + str(y)) # ax.set_ylim(0.95 * min(y), # 1.1 * max(y)) plt.title( "Stacked " + ["Sensitivity", "Discovery Potential"][j] + " for " + cat_name + " SNe" ) plt.tight_layout() plt.savefig( plot_output_dir(name) + "/spectral_index_" + ["sens", "disc"][j] + "_" + cat_name + ".pdf" ) plt.close() # ======================== save calculated sensitivities ======================== # with open(limit_sens(mh_name, pdf_type), "wb") as f: pickle.dump(stacked_sens_flux, f) # ======================== make final plots =============================== #
fluence[i], label=labels[i], linestyle=linestyle, color=cols[i]) ax2.plot(f, energy[i], linestyle=linestyle, color=cols[i]) ax1.grid(True, which="both") ax1.set_ylabel(r"Time-Integrated Flux[ GeV$^{-1}$ cm$^{-2}$]", fontsize=12) ax2.set_ylabel(r"Mean Isotropic-Equivalent $E_{\nu}$ (erg)") ax1.set_xlabel(r"Flare Length (days)") ax1.set_yscale("log") ax2.set_yscale("log") for k, ax in enumerate([ax1, ax2]): y = [fluence, energy][k] ax.set_ylim( 0.95 * min([min(x) for x in y if len(x) > 0]), 1.1 * max([max(x) for x in y if len(x) > 0]), ) plt.title("Flare in " + str(int(search_window)) + " day window") ax1.legend(loc="upper left", fancybox=True, framealpha=0.0) plt.tight_layout() plt.savefig( plot_output_dir(name) + "/flare_vs_box_" + catalogue["source_name"][0].decode() + "_" + ["sens", "disc"][j] + ".pdf") plt.close()
analyse(mh_dict, cluster=False, n_cpu=23) sky_dict[n_cat] = mh_dict sn_dict[sky] = sky_dict res_dict[sn] = sn_dict # raw_input("prompt") wait_for_cluster() # dem = AsimovEstimator(ps_7_year.get_seasons("IC86_1"), inj_kwargs) for (sn, sn_dict) in res_dict.items(): savedir_sn = plot_output_dir(name_root) + sn + "/" for (sky, sky_dict) in sn_dict.items(): if sky == "Northern": # if True: savedir = savedir_sn + sky + "/" sens = [] sens_e = [] disc = [] disc_e = [] disc_25 = [] disc_25_e = [] guess_disc = [] guess_disc_e = []
ax1.set_ylabel(r"Total Fluence [GeV cm$^{-2}$]", fontsize=12) ax2.set_ylabel(r"Mean Isotropic-Equivalent $E_{\nu}$ (erg)") ax1.set_xlabel(r"Flare Length (Days)") ax1.set_yscale("log") ax2.set_yscale("log") # Set limits and save for k, ax in enumerate([ax1, ax2]): try: y = [fluence, energy][k] ax.set_ylim(0.7 * min([min(x) for x in y if len(x) > 0]), 1.5 * max([max(x) for x in y if len(x) > 0])) except ValueError: pass plt.title(["Sensitivity", "Discovery Potential"][j] + " for " + cat) ax1.legend(loc='upper left', fancybox=True) plt.tight_layout() path = plot_output_dir(name) + "/flare_vs_box_" + ["sens", "disc"][j] + ".pdf" logging.info(f"Saving to {path}") plt.savefig(path) plt.close()
def agn_cores_output_dir(name='foldername'): return plot_output_dir('analyses/agn_cores/'+name+'/')
def __init__(self, unblind_dict, seed=None, scan_2d=False, **kwargs): self.unblind_dict = unblind_dict unblind_dict["unblind_bool"] = True unblind_dict["mock_unblind_bool"] = mock_unblind unblind_dict["inj_dict"] = {} if np.logical_and(not mock_unblind, not disable_warning): self.check_unblind() if mock_unblind is False: self.mock_unblind = False else: self.mock_unblind = True ParentMiminisationHandler.__init__(self, unblind_dict) try: if self.mock_unblind: self.limit_path = limit_output_path( self.unblind_dict["name"] + "mock_unblind/") self.unblind_res_path = unblinding_output_path( self.unblind_dict["name"] + "mock_unblind/") else: self.limit_path = limit_output_path( self.unblind_dict["name"] + "real_unblind/") self.unblind_res_path = unblinding_output_path( self.unblind_dict["name"] + "real_unblind/") except KeyError: self.limit_path = np.nan self.unblind_res_path = np.nan if self.name != " /": if self.mock_unblind: self.name += "mock_unblind/" else: self.name += "real_unblind/" self.plot_dir = plot_output_dir(self.name) try: os.makedirs(os.path.dirname(self.unblind_res_path)) except OSError: pass # Avoid redoing unblinding if not reunblind: try: logger.info( "Not re-unblinding, loading results from {0}".format( self.unblind_res_path)) with open(self.unblind_res_path, "rb") as f: self.res_dict = pickle.load(f) except FileNotFoundError: logger.warning( "No pickle files containing unblinding results found. " "Re-unblinding now.") # Otherwise unblind if not hasattr(self, "res_dict"): logger.info("Unblinding catalogue") # Minimise likelihood and produce likelihood scans self.res_dict = self.simulate_and_run(0, seed) logger.info(self.res_dict) # Quantify the TS value significance self.ts = np.array([self.res_dict["TS"]])[0] self.ts_type = unblind_dict.get('ts_type', 'Standard') self.sigma = np.nan logger.info("Test Statistic of: {0}".format(self.ts)) ub_res_dict = { "Parameters": self.res_dict['Parameters'], "TS": self.res_dict['TS'], "Flag": self.res_dict['Flag'] } logger.info("Saving unblinding results to {0}".format( self.unblind_res_path)) with open(self.unblind_res_path, "wb") as f: pickle.dump(ub_res_dict, f) try: path = self.unblind_dict["background_ts"] self.pickle_dir = name_pickle_output_dir(path) self.output_file = self.plot_dir + "TS.pdf" self.compare_to_background_TS() except KeyError: logger.warning("No Background TS Distribution specified. " "Cannot assess significance of TS value.") if full_plots: self.calculate_upper_limits() if isinstance(self, FlareMinimisationHandler): self.neutrino_lightcurve() else: self.scan_likelihood(scan_2d=scan_2d)
zs = [Distance(Distance(dl * u.Mpc)).compute_z() for dl in dist_mpc[mask]] print(zs) x = np.log(zs) y = np.log(np.array(e_per_source)[mask]) [m, c] = np.polyfit(x, y, 1) def f(x): return np.exp(m * np.log(x) + c) name_root = "analyses/ztf/depth/" save_dir = plot_output_dir(name_root) print(save_dir) plt.figure() # plt.scatter(zs, np.array(e_per_source)[mask]) # plt.scatter(zs, np.array(e_per_source)[mask]) # plt.plot([0.001, 0.1], f([0.001, 0.1])) x = np.linspace(0.001, 0.1, 1e3) plt.plot(x, f(x), color="orange") plt.yscale("log") # plt.xscale("log") plt.xlabel("Redshift") plt.ylabel(r"$E_{\nu}$ per source") # plt.plot(np.array(dist_mpc)[mask], np.array(disc)[mask])
from flarestack.analyses.ccsn import get_sn_color from flarestack.cosmo.neutrino_cosmology import get_diffuse_flux_at_1GeV from flarestack.cosmo import get_diffuse_flux_contour from flarestack.cosmo.icecube_diffuse_flux.joint_15 import contour_95, e_range, units # from flarestack.misc.convert_diffuse_flux_contour import contour_95, lower_contour, upper_contour, e_range import pickle import matplotlib.pyplot as plt import os import logging mh_name = "fit_weights" energy_range_gev = np.linspace(10**3, 10**7, 10) linestyles = ["--", "-.", ":", "-"] plot_out_dir = plot_output_dir( f"{raw_output_dir}/sensitivity_fluxes/{mh_name}") if not os.path.isdir(plot_out_dir): os.makedirs(plot_out_dir) best_f, upper_f, lower_f, e_range = get_diffuse_flux_contour(contour_name=95) def plot_diffuse_flux_measurement(axes, **kwargs): logging.debug("plotting diffuse flux measurement") label = kwargs.get("label", "measured diffuse flux, 95% contour") patch = axes.fill_between( e_range, y1=lower_f(e_range) * e_range**2, y2=upper_f(e_range) * e_range**2, label=label, color="k",
y_label = [ r"Total Fluence [GeV cm$^{-2}$]", r"Mean Isotropic-Equivalent $E_{\nu}$ (erg)", ] ax2.grid(True, which="both") ax1.set_ylabel(r"Total Fluence [GeV cm$^{-2}$]", fontsize=12) ax2.set_ylabel(r"Mean Isotropic-Equivalent $E_{\nu}$ (erg)") ax1.set_xlabel(r"Spectral Index ($\gamma$)") ax1.set_yscale("log") ax2.set_yscale("log") for k, ax in enumerate([ax1, ax2]): y = [fluence, energy][k] ax.set_ylim( 0.95 * min([min(x) for x in y if len(x) > 0]), 1.1 * max([max(x) for x in y if len(x) > 0]), ) plt.title("Stacked " + ["Sensitivity", "Discovery Potential"][j] + " for " + cat_name + " TDEs") ax1.legend(loc="upper left", fancybox=True, framealpha=0.0) plt.tight_layout() plt.savefig( plot_output_dir(name) + "/spectral_index_" + "Emin=" + str(e_min) + ["sens", "disc"][j] + "_" + cat_name + ".pdf") plt.close()
ax1.plot(f, fluence[i], label=labels[i], linestyle=linestyle, color=cols[i]) ax2.plot(f, energy[i], linestyle=linestyle, color=cols[i]) ax1.grid(True, which="both") ax1.set_ylabel(r"Time-Integrated Flux[ GeV$^{-1}$ cm$^{-2}$]", fontsize=12) ax2.set_ylabel(r"Mean Isotropic-Equivalent $E_{\nu}$ (erg)") ax1.set_xlabel(r"Flare Length (days)") ax1.set_yscale("log") ax2.set_yscale("log") for k, ax in enumerate([ax1, ax2]): y = [fluence, energy][k] ax.set_ylim( 0.95 * min([min(x) for x in y if len(x) > 0]), 1.1 * max([max(x) for x in y if len(x) > 0]), ) plt.title("Flare in " + str(int(max_window)) + " day window") ax1.legend(loc="upper left", fancybox=True, framealpha=0.0) plt.tight_layout() plt.savefig( plot_output_dir(name) + "/flare_vs_box_" + catalogue["Name"][0] + "_" + ["sens", "disc"][j] + ".pdf") plt.close()
import matplotlib, os matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np from flarestack.analyses.ccsn.necker_2019.ccsn_helpers import ( updated_sn_catalogue_name, sn_cats, sn_times, pdf_names, raw_output_dir, ) import logging from flarestack.shared import plot_output_dir plot_dir = plot_output_dir(raw_output_dir + "/catalogue_visualization/difference_stasik/") if not os.path.isdir(plot_dir): os.makedirs(plot_dir) def autolabel(rects, axis): """Attach a text label above each bar in *rects*, displaying its height.""" for rect in rects: height = rect.get_height() axis.annotate( "{}".format(height), xy=(rect.get_x() + rect.get_width() / 2, height), xytext=(0, 2), # 3 points vertical offset textcoords="offset points", ha="center",
plt.figure() ax = plt.subplot(111) cols = ["r", "g", "b", "orange"] for i, (sindec_key, src_res) in enumerate(cat_res.items()): name = name_root + sindec_key + "/" sens = [] lengths = [] for (t, rh_dict) in sorted(src_res.items()): rh = ResultsHandler(rh_dict) sens.append(rh.sensitivity) lengths.append(t) ax.plot(lengths, sens, label=sindec_key, color=cols[i]) ax.set_ylabel(r"Flux [GeV$^{-1}$ cm$^{-2}$ s$^{-1}$]", fontsize=12) ax.set_xlabel("Time-Integration Window (days)") ax.set_yscale("log") # plt.legend() plt.title("Sensitivity for 100 day emission") ax.legend(loc='upper right', fancybox=True, framealpha=1.) plt.tight_layout() plt.savefig(plot_output_dir(name_root) + "scaling_sens.pdf") plt.close()
ax2.grid(True) xticklabels = ax1.get_xticklabels() plt.setp(xticklabels, visible=False) plt.subplots_adjust(hspace=0.001) plt.suptitle('Point Source Discovery Potential') # ratio_interp = interp1d(sindecs, sens_ratios) # # interp_range = np.linspace(np.min(sindecs), # np.max(sindecs), 1000) # ax1.plot( # interp_range, # reference_sensitivity(interp_range)*ratio_interp(interp_range), # color='red', linestyle="--", label="Ratio Interpolation") ax1.legend(loc='upper right', fancybox=True, framealpha=1.) save_dir = plot_output_dir(name) try: os.makedirs(save_dir) except OSError: pass title = ["/PSDisc.pdf", "/IC86_1.pdf"][i] plt.savefig(save_dir + title) plt.close()
# Set up plot ax2.grid(True, which='both') ax1.set_ylabel(r"Total Fluence [GeV cm$^{-2}$]", fontsize=12) ax2.set_ylabel(r"Mean Isotropic-Equivalent $E_{\nu}$ (erg)") ax1.set_xlabel(r"Flare Length (Days)") ax1.set_yscale("log") ax2.set_yscale("log") # Set limits and save for k, ax in enumerate([ax1, ax2]): try: y = [fluence, energy][k] ax.set_ylim(0.7 * min([min(x) for x in y if len(x) > 0]), 1.5 * max([max(x) for x in y if len(x) > 0])) except ValueError: pass plt.title(["Sensitivity", "Discovery Potential"][j] + " for " + cat + " TDEs") ax1.legend(loc='upper left', fancybox=True) plt.tight_layout() plt.savefig(plot_output_dir(name) + "/flare_vs_box_" + cat + "_" + ["sens", "disc"][j] + ".pdf") plt.close()
ax1.set_xlabel(r"Spectral Index ($\gamma$)") ax1.set_yscale("log") ax2.set_yscale("log") for k, ax in enumerate([ax1, ax2]): y = [fluence, energy][k] logging.debug('y: ' + str(y)) # ax.set_ylim(0.95 * min(y), # 1.1 * max(y)) plt.title("Stacked " + ["Sensitivity", "Discovery Potential"][j] + " for " + cat_name + " SNe") plt.tight_layout() plt.savefig(plot_output_dir(name) + "/spectral_index_" + ["sens", "disc"][j] + "_" + cat_name + ".pdf") plt.close() # ================================ save sensitivities ============================== # with open(limit_sens(mh_name, pdf_type), 'wb') as f: pickle.dump(stacked_sens_flux, f) # ================================= make final plots =============================== # # loop over gammas to make a plots for each spectral indice for gamma in gammas: # ------------- plot sensitivity against box length ------------------- # flux_fig, flux_ax = plt.subplots()
sens_ratios = np.array(sens) / reference_sensitivity(sindecs, sample="10yr") sens_ratio_errs = sens_err / reference_sensitivity(sindecs, sample="10yr") disc_ratios = np.array(disc_pots) / reference_discovery_potential( sindecs, sample="10yr" ) ax2.errorbar(sindecs, sens_ratios, yerr=sens_ratio_errs, color="red", marker="o") ax2.scatter(sindecs, disc_ratios, color="k") ax2.plot(sindecs, disc_ratios, color="k", linestyle="--") ax2.set_ylabel(r"ratio", fontsize=12) ax2.set_xlabel(r"sin($\delta$)", fontsize=12) plt.suptitle("Point Source Sensitivity (10 year)") # ax1.set_xlim(xmin=-1.0, xmax=1.0) xticklabels = ax1.get_xticklabels() plt.setp(xticklabels, visible=False) plt.subplots_adjust(hspace=0.001) ax1.legend(loc="upper right", fancybox=True, framealpha=1.0) savefile = plot_output_dir(name) + "/PS10yr.pdf" logging.info(f"Saving to {savefile}") plt.savefig(savefile) plt.close()
# analyse(mh_dict, cluster=False, n_cpu=36) sky_dict[n_cat] = mh_dict season_dict[sky] = sky_dict sn_dict[j+1] = season_dict res_dict[sn] = sn_dict wait_for_cluster() all_res = dict() for (sn, sn_dict) in res_dict.items(): savedir_sn = plot_output_dir(name_root) + sn + "/" sn_res = dict() for (years, season_dict) in sn_dict.items(): season_res = dict() season_savedir = savedir_sn + str(years) + "/" for (sky, sky_dict) in season_dict.items(): if sky == "Northern": sky_res = dict() # if True:
label="skylab", ) else: logging.info("no skylab results") ax.set_xlabel("$N$") ax.set_ylabel(r"$F \, \cdot \, F_{\mathrm{point \, source}}^{-1}$") ax.set_xscale("log") ax.set_title("stacked sensitivity \n" + r"$\sin(\delta)=${:.2f}".format(sindec)) ax.legend() plt.tight_layout() fig.savefig( plot_output_dir(raw + "/{:.4f}/".format(sindec)) + f"sens_nsources_gamma={gamma}_" f"sindec{sindec:.2f}.pdf") plt.close() fig2, ax2 = plt.subplots() Nsqrt = 1 / np.sqrt(sens[0]) Nrez = 1 / np.array(sens[0]) ax2.plot(sens[0], Nsqrt, "k--", label=r"$F \sim \sqrt{N}$") ax2.plot(sens[0], Nrez, "k-.", label=r"$F = const$") ax2.errorbar( sens[0], # np.array(sens[1]) / sens[1][0] / np.array(sens[0]), np.array(sens[1]) / norm_to / np.array(sens[0]),
ax2 = plt.subplot2grid((4, 1), (3, 0), colspan=3, rowspan=1, sharex=ax1) # sens_ratios = np.array(all_sens[1]) / np.array(all_sens[0]) # disc_ratios = np.array(all_disc[1]) / np.array(all_disc[0]) # ax2.scatter(sindecs, sens_ratios, color="red") ax2.plot(sindecs, sens_ratios, color="red") ax2.scatter(sindecs, disc_ratios, color="k") ax2.plot(sindecs, disc_ratios, color="k", linestyle="--") ax2.set_ylabel(r"ratio", fontsize=12) ax2.set_xlabel(r"sin($\delta$)", fontsize=12) ax2.grid(True) xticklabels = ax1.get_xticklabels() plt.setp(xticklabels, visible=False) plt.subplots_adjust(hspace=0.001) ax1.legend(loc="upper right", fancybox=True, framealpha=1.0) savepath = plot_output_dir(base_name) + "/PS_comparison.pdf" try: os.makedirs(os.path.dirname(savepath)) except OSError: pass plt.savefig(savepath) plt.close()
ax1.plot(sin_decs, vals, label=config) ax2.plot(sin_decs, vals / plot_dict["Base Case (No floor)"]) ax2.set_xlabel(r"sin($\delta$)") ax2.set_ylabel("Ratio") ax1.set_xlim(xmin=-1.0, xmax=1.0) ax2.grid(True) xticklabels = ax1.get_xticklabels() plt.setp(xticklabels, visible=False) plt.subplots_adjust(hspace=0.001) ax1.legend() name = ["Sensitivity", "Discovery Potential"][i] savepath = plot_output_dir(gamma_name) + "comparison " + name + ".pdf" print("Saving to", savepath) plt.savefig(savepath) plt.close() for i, bias_dict in enumerate([med_bias_dict, mean_bias_dict]): name = ["Median Bias", "Mean Bias"][i] plt.figure() for (config, biases) in bias_dict.items(): plt.plot(sin_decs, biases, label=config) plt.axhline(1.0, linestyle=":") plt.xlabel(r"sin($\delta$)") plt.ylabel(name + r" in $n_{s}$") plt.legend()
sens_livetime.append(astro_sens[key]) disc_pots_livetime.append(astro_disc[key]) # fluence normalized over tot xray flux ratio_sens.append(astro_sens[key] / int_xray) ratio_disc.append(astro_disc[key] / int_xray) n_src.append(nr_srcs) except OSError: pass # Save arrays to file np.savetxt( plot_output_dir(base_dir) + "data.out", (np.array(n_src), np.array(int_xray_flux_erg), np.array(sens), np.array(sens_err_low), np.array(sens_err_upp), np.array(disc_pot), np.array(disc_ts_threshold), np.array(sens_livetime), np.array(disc_pots_livetime), np.array(ratio_sens), np.array(ratio_disc), np.array(ratio_sens) / saturate_ratio, np.array(ratio_disc) / saturate_ratio, np.array(sens_n), np.array(disc_pot_n)), header="n_src, int_xray_flux_erg," "sensitivity, sensitivity_err_lower, sensitivity_err_upper," "dp, disc_ts_threshold," "int_sensitivity, int_dp," "ratio_sens, ratio_dp," "ratio_sens_saturate, ratio_dp_saturate," "sensitivity_nr_neutrinos, dp_nr_neutrinos")
mh_dict = res_dict[i] # Creates a Results Handler to analyse the results, and calculate the # sensitivity. This is the flux that needs to arrive at Earth, in order for # IceCube to see an overfluctuation 90% of the time. Prints this information. rh = ResultsHandler(mh_dict) sens.append(rh.sensitivity) disc.append(rh.disc_potential) for i, vals in enumerate([sens, disc]): label = ["Sensitivity", "Discovery Potential"][i] plt.figure() plt.plot(n_range, vals) plt.ylabel("Ratio to Model") plt.xlabel("Model Number") plt.title(label + " during TXS Neutrino Flare") savepath = plot_output_dir(base_dir) + label + ".pdf" try: os.makedirs(os.path.dirname(savepath)) except OSError: pass print("Saving to", savepath) plt.savefig(savepath) plt.close()
ax2 = plt.subplot2grid((4, 1), (3, 0), colspan=3, rowspan=1, sharex=ax1) ratios = np.array(all_sens[1]) / np.array(all_sens[0]) ax2.scatter(sindecs, ratios, color="black") ax2.plot(sindecs, ratios, linestyle="--", color="red") ax2.set_ylabel(r"ratio", fontsize=12) ax2.set_xlabel(r"sin($\delta$)", fontsize=12) # ax1.set_xlim(xmin=-1.0, xmax=1.0) # ax2.set_ylim(ymin=0.5, ymax=1.5) ax2.grid(True) xticklabels = ax1.get_xticklabels() plt.setp(xticklabels, visible=False) plt.subplots_adjust(hspace=0.001) # ax1.set_xscale("log") # ax1.set_xlim(0, 1.0) ax1.legend(loc='upper right', fancybox=True, framealpha=1.) savename = plot_output_dir(name) + "ratio.pdf" try: os.makedirs(os.path.dirname(savename)) except OSError: pass plt.savefig(savename) plt.close()
from __future__ import division from builtins import str from builtins import range import os import numpy as np import matplotlib.pyplot as plt from flarestack.data.icecube.ps_tracks.ps_v002_p01 import IC86_1_dict from flarestack.data.icecube.ps_tracks.ps_v003_p01 import IC86_234567_dict from flarestack.shared import plot_output_dir from flarestack.icecube_utils.dataset_loader import data_loader from flarestack.core.astro import angular_distance from numpy.lib.recfunctions import append_fields basedir = plot_output_dir( "analyses/angular_error_floor/dynamic_pull_corrections/") try: os.makedirs(basedir) except OSError: pass energy_bins = np.linspace(1.0, 10.0, 20 + 1) # def get_data(season): # mc = data_loader(season["mc_path"], floor=False) # x = np.degrees(angular_distance( # mc["ra"], mc["dec"], mc["trueRa"], mc["trueDec"])) # y = np.degrees(mc["sigma"]) * 1.177 # return mc, x, y
disc_pots_livetime_100GeV10PeV.append(astro_disc_100GeV10PeV[key]) # normalized over tot xray flux ratio_sens.append(astro_sens[key] / int_xray) # fluence ratio_disc.append(astro_disc[key] / int_xray) ratio_sens_100GeV10PeV.append(astro_sens_100GeV10PeV[key] / int_xray) # fluence ratio_disc_100GeV10PeV.append(astro_disc_100GeV10PeV[key] / int_xray) n_src.append(nr_srcs) except OSError: pass # # Save arrays to file np.savetxt(plot_output_dir(base_dir) + "data.out", (np.array(n_src), np.array(int_xray_flux_erg), np.array(e_min_gev), np.array(e_max_gev), np.array(sens), np.array(sens_err_low), np.array(sens_err_upp), np.array(disc_pot), np.array(disc_ts_threshold), np.array(sens_livetime), np.array(disc_pots_livetime), np.array(ratio_sens), np.array(ratio_disc), np.array(ratio_sens)/saturate_ratio, np.array(ratio_disc)/saturate_ratio, np.array(sens_livetime_100GeV10PeV), np.array(disc_pots_livetime_100GeV10PeV), np.array(ratio_sens_100GeV10PeV), np.array(ratio_disc_100GeV10PeV), np.array(ratio_sens_100GeV10PeV)/saturate_ratio, np.array(ratio_disc_100GeV10PeV)/saturate_ratio, np.array(sens_n), np.array(disc_pot_n)), header="n_src, int_xray_flux_erg, " "e_min_gev, e_max_gev" "sensitivity, sensitivity_err_lower, sensitivity_err_upper," "dp, disc_ts_threshold,"