def mean_injection_time(self): inj_time_list = list() for src in self.sources: single_inj_time = 0 for s_name in self._dataset.keys(): s = self._dataset[s_name] tpdf = TimePDF.create(self._inj_dict["injection_sig_time_pdf"], s.get_time_pdf()) single_inj_time += tpdf.raw_injection_time(src) inj_time_list.append(single_inj_time) return np.median(inj_time_list)
def build_time_pdf(self): t_pdf_dict = self.build_time_pdf_dict() time_pdf = TimePDF.create(t_pdf_dict) compatible_time_pdfs = [FixedEndBox, FixedRefBox, DetectorOnOffList] if np.sum([isinstance(time_pdf, x) for x in compatible_time_pdfs]) == 0: raise ValueError( "Attempting to use a time PDF that is not an " "allowed time PDF class. Only {0} are allowed, " " as these PDFs have well-defined start and " "end points. Please prove one of these as a " "background_time_pdf for the simulation.".format(compatible_time_pdfs) ) return time_pdf
def __init__(self, season, sources, **kwargs): kwargs = read_injector_dict(kwargs) self.inj_kwargs = kwargs logger.info("Initialising Injector for {0}".format(season.season_name)) self.injection_band_mask = dict() self.season = season self.season.load_background_model() self.sources = sources if len(sources) > 0: self.weight_scale = calculate_source_weight(self.sources) try: self.sig_time_pdf = TimePDF.create( kwargs["injection_sig_time_pdf"], season.get_time_pdf() ) # self.bkg_time_pdf = TimePDF.create(kwargs["injection_bkg_time_pdf"], # season.get_time_pdf()) self.energy_pdf = EnergyPDF.create(kwargs["injection_energy_pdf"]) self.spatial_pdf = SpatialPDF(kwargs["injection_spatial_pdf"], season) except KeyError: raise Exception( "Injection Arguments missing. \n " "'injection_energy_pdf', 'injection_time_pdf'," "and 'injection_spatial_pdf' are required. \n" "Found: \n {0}".format(kwargs) ) if "poisson_smear_bool" in list(kwargs.keys()): self.poisson_smear = kwargs["poisson_smear_bool"] else: self.poisson_smear = True self.n_exp = np.nan try: self.fixed_n = kwargs["fixed_n"] except KeyError: self.fixed_n = np.nan
def calculate_upper_limits(self): try: ul_dir = os.path.join(self.plot_dir, "upper_limits/") try: os.makedirs(ul_dir) except OSError: pass flux_uls = [] fluence_uls = [] e_per_source_uls = [] energy_flux = [] x_axis = [] for subdir in sorted(os.listdir(self.pickle_dir)): root = os.path.join(self.unblind_dict["background_ts"], subdir) new_path = analysis_pickle_path(name=root) logger.info(f'Opening file {new_path}') with open(new_path, "rb") as f: mh_dict = pickle.load(f) e_pdf_dict = mh_dict["inj_dict"][ "injection_energy_pdf"] self.unblind_dict['name'] = mh_dict['name'] rh = ResultsHandler(self.unblind_dict) logger.debug( f"In calculate_upper_limits, ResultsHandler is {rh}") savepath = ul_dir + subdir + ".pdf" if self.ts < rh.bkg_median: logging.warning( f"Specified TS ({self.ts}) less than the background median ({rh.bkg_median}). " f"There was thus a background n underfluctuation. " f"Using the sensitivity for an upper limit.") ul, extrapolated, err = rh.find_overfluctuations( max(self.ts, rh.bkg_median), savepath) flux_uls.append(ul) # Calculate mean injection time per source n_sources = float(len(self.sources)) inj_time = 0. seasons = mh_dict["dataset"] for (name, season) in seasons.items(): t_pdf = TimePDF.create( mh_dict["inj_dict"]["injection_sig_time_pdf"], season.get_time_pdf()) for src in self.sources: inj_time += t_pdf.raw_injection_time(src) / \ n_sources astro_dict = rh.nu_astronomy(ul, e_pdf_dict) key = "Energy Flux (GeV cm^{-2} s^{-1})" fluence_uls.append(astro_dict[key] * inj_time) e_per_source_uls.append( astro_dict["Mean Luminosity (erg/s)"] * inj_time) energy_flux.append(astro_dict[key]) x_axis.append(float(subdir)) plt.figure() ax = plt.subplot(111) plt.plot(x_axis, flux_uls, marker='o', label="upper limit") if self.mock_unblind: ax.text(0.2, 0.5, "MOCK DATA", color="grey", alpha=0.5, transform=ax.transAxes) ax.set_xlabel('Gamma') ax.set_ylabel('Flux') plt.yscale("log") plt.savefig(self.plot_dir + "upper_limit_flux.pdf") plt.close() plt.figure() ax1 = plt.subplot(111) ax2 = ax1.twinx() ax1.plot(x_axis, fluence_uls, marker='o') ax2.plot(x_axis, e_per_source_uls, marker='o') if self.mock_unblind: ax1.text(0.2, 0.5, "MOCK DATA", color="grey", alpha=0.5, transform=ax1.transAxes) ax2.grid(True, which='both') ax1.set_xlabel('Gamma') ax2.set_xlabel('Gamma') ax1.set_ylabel(r"Total Fluence [GeV cm$^{-2}$ s$^{-1}$]") ax2.set_ylabel( r"Isotropic-Equivalent Luminosity $L_{\nu}$ (erg/s)") ax1.set_yscale("log") ax2.set_yscale("log") for k, ax in enumerate([ax1, ax2]): y = [fluence_uls, e_per_source_uls][k] ax.set_ylim(0.95 * min(y), 1.1 * max(y)) plt.tight_layout() plt.savefig(self.plot_dir + "upper_limit_fluence.pdf") plt.close() try: os.makedirs(os.path.dirname(self.limit_path)) except OSError: pass logger.info("Saving limits to {0}".format(self.limit_path)) res_dict = { "gamma": x_axis, "flux": flux_uls, "energy_flux": energy_flux, "fluence": fluence_uls, "energy": e_per_source_uls } with open(self.limit_path, "wb") as f: pickle.dump(res_dict, f) except AttributeError as e: logger.warning( "Unable to set limits. No TS distributions found.") except ValueError as e: raise OverfluctuationError( "Insufficent pseudotrial values above and below threshold")
for offset in offsets: rh_dict = method_res[offset] try: rh = ResultsHandler(rh_dict) injection_time = rh_dict["inj kwargs"]["Injection Time PDF"] inj_time = 0. cat = np.load(rh_dict["catalogue"]) for season in rh_dict["datasets"]: time = TimePDF.create(injection_time, season) inj_time += np.mean( [time.effective_injection_time(src) for src in cat]) sens.append(rh.sensitivity * inj_time) disc_pots.append(rh.disc_potential * inj_time) ts_median.append(rh.bkg_median) if label == "Zero-bound": frac_over.append(rh.frac_over) except EOFError: sens.append(np.nan) disc_pots.append(np.nan)