def init(Nexp, NMC, energy=True, **kwargs): Nsrc = kwargs.pop("Nsrc", 0) arr_exp = exp(Nexp - Nsrc) arr_mc = MC(NMC) if Nsrc > 0: inj = PointSourceInjector(2, sinDec_bandwidth=1, seed=0) inj.fill(0., arr_mc, 333.) source = inj.sample(Nsrc, poisson=False).next()[1] arr_exp = np.append(arr_exp, source) if energy: llh_model = PowerLawLLH(["logE"], min(50, Nexp // 50), range=[[0.9 * arr_mc["logE"].min(), 1.1 * arr_mc["logE"].max()]], sinDec_bins=min(50, Nexp // 50), sinDec_range=[-1., 1.], bounds=(0, 5)) else: llh_model = UniformLLH(sinDec_bins=max(3, Nexp // 200), sinDec_range=[-1., 1.]) llh = PointSourceLLH(arr_exp, arr_mc, 365., llh_model=llh_model, mode="all", hemispheres=dict(Full=[-np.inf, np.inf]), nsource=25, scramble=False, nsource_bounds=(-Nexp / 2., Nexp / 2.) if not energy else (0., Nexp / 2.), seed=np.random.randint(2**32), **kwargs) return llh
def initialize_injector(self, e_range=(0., np.inf)): inj = PointSourceInjector( gamma = self.index, E0 = 1000., e_range=e_range) inj.fill( self.dec, self.llh.exp, self.llh.mc, self.llh.livetime, temporal_model=self.llh.temporal_model) self.inj = inj
def init(Nexp, NMC, energy=True, **kwargs): Nsrc = kwargs.pop("Nsrc", 0) arr_exp = exp(Nexp - Nsrc) arr_mc = MC(NMC) if Nsrc > 0: inj = PointSourceInjector(2, sinDec_bandwidth=1, seed=0) inj.fill(0., arr_mc, 333.) source = inj.sample(Nsrc, poisson=False).next()[1] arr_exp = np.append(arr_exp, source) if energy: llh_model = PowerLawLLH( ["logE"], min(50, Nexp // 50), range=[[0.9 * arr_mc["logE"].min(), 1.1 * arr_mc["logE"].max()]], sinDec_bins=min(50, Nexp // 50), sinDec_range=[-1., 1.], bounds=(0, 5)) else: llh_model = UniformLLH(sinDec_bins=max(3, Nexp // 200), sinDec_range=[-1., 1.]) llh = PointSourceLLH(arr_exp, arr_mc, 365., llh_model=llh_model, mode="all", hemispheres=dict(Full=[-np.inf, np.inf]), nsource=25, scramble=False, nsource_bounds=(-Nexp / 2., Nexp / 2.) if not energy else (0., Nexp / 2.), seed=np.random.randint(2**32), **kwargs) return llh
def sensitivity_skylab(Gamma=2, src_dec=0, n_iter=1000, n_bckg=100000): inj = PointSourceInjector(Gamma, sinDec_bandwidth=.1, src_dec=src_dec, seed=0) return PointSourceLLH.weighted_sensitivity(llh, src_ra=0.0, src_dec=src_dec, alpha=.5, beta=.9, inj=inj, mc=mc, n_iter=n_iter)
# create classic likelihood model llh_model = ClassicLLH(sinDec_bins=sinDec_bins, sinDec_range=[sinDec_min, sinDec_max], MCbackground=MCbackground) # specify a point source likelihood based on classicLLH psllh = PointSourceLLH(exp, mc, livetime, scramble=True, seed=args.seed, llh_model=llh_model, mode = "box", delta_ang=numpy.radians(10.*1.0), nside=128) # make an injector to model point sources print "" inj = PointSourceInjector(gamma=args.index,E0=args.E0,seed=args.seed) inj.fill(src_dec, mc, livetime) ################ # SKYLAB SETUP # ################ ############################################################################### ################## # 5 SIGMA SEARCH # ################## print "\nSearching for 5 sigma ... " ns_min = args.ns_bounds[0] ns_max = args.ns_bounds[1]
ax_p.set_xlabel("Sigma / $1^\circ$") ax_p.set_ylabel("Probability Density") fig_E.savefig("figures/energy.pdf") fig_p.savefig("figures/mrs.pdf") plt.show() plt.close("all") ### LLH SCAN ### fig, ax = plt.subplots() for mu, Gamma in zip([20, 40, 30], gamma): print("\tgamma =", Gamma) # init a injector class sampling events at a point source inj = PointSourceInjector(Gamma, sinDec_bandwidth=1., seed=0) inj.fill(0., mc, 333.) n = 25 gamma = np.linspace(*llh.par_bounds[1], num=n) ntrials = 100 T = list() nsources = np.linspace(0.5 * mu, 2. * mu, 2 * n) for i in range(ntrials): # Inject always the same number of events for this plot n_inj, inject = inj.sample(mu, poisson=False).next() TS, xmin = llh.fit_source(np.pi, 0., inject=inject)
def config(seasons, seed=1, scramble=True, e_range=(0, np.inf), verbose=True, gamma=2.0, dec=0., remove=False, src_w=None): r""" Configure multi season point source likelihood and injector. Parameters ---------- seasons : list List of season names seed : int Seed for random number generator Returns ------- multillh : MultiPointSourceLLH Multi year point source likelihood object inj : PointSourceInjector Point source injector object """ print("Scramble is %s" % str(scramble)) # store individual llh as lists to prevent pointer over-writing llh = [] multillh = MultiPointSourceLLH(seed=seed, ncpu=25) # setup likelihoods if verbose: print("\n seasons:") for season in np.atleast_1d(seasons): sample = season[0] name = season[1] exp, mc, livetime = Datasets[sample].season(name) sinDec_bins = Datasets[sample].sinDec_bins(name) energy_bins = Datasets[sample].energy_bins(name) if sample == "GFU" and remove: exp = Datasets['GFU'].remove_ev( exp, 58018.87118560489) # remove EHE 170922A mc = mc[mc["logE"] > 1.] if verbose: print(" - % 15s : % 15s" % (sample, name)) vals = (livetime, exp.size, min(exp['time']), max(exp['time'])) print( " (livetime %7.2f days, %6d events, mjd0 %.2f, mjd1 %.2f)" % vals) llh_model = EnergyLLH(twodim_bins=[energy_bins, sinDec_bins], allow_empty=True, bounds=[1., 4.], seed=2., kernel=1) llh.append( StackingPointSourceLLH(exp, mc, livetime, mode="box", scramble=scramble, llh_model=llh_model, nsource_bounds=(0., 1e3), nsource=15.)) multillh.add_sample(sample + " : " + name, llh[-1]) # save a little RAM by removing items copied into LLHs del exp, mc # END for (season) ####### # LLH # ####### ############################################################################# ############ # INJECTOR # ############ inj = PointSourceInjector(gamma=gamma, E0=1 * TeV, seed=seed, e_range=e_range) inj.fill(dec, multillh.exp, multillh.mc, multillh.livetime, src_w) ############ # INJECTOR # ############ ############################################################################# if verbose: print("\n fitted spectrum:") vals = (inj.E0 / TeV) print(" - dN/dE = A (E / %.1f TeV)^-index TeV^-1cm^-2s^-1" % vals) print(" - index is *fit*") print("\n injected spectrum:") vals = (inj.E0 / TeV, inj.gamma) print(" - dN/dE = A (E / %.1f TeV)^-%.2f TeV^-1cm^-2s^-1" % vals) return (multillh, inj)
elif catalog == 'Milagro17': llh = datascript.init86I(mode='box') else: if years == 7: if mese: llh = datascript.load7yr_mese(mode='box', sirin=sirin) else: llh = datascript.load7yr(mode='box', sirin=sirin) elif years == 4: llh = datascript.load4yr(mode='box', sirin=True, nopull=True) elif years == 1: print("Using IC86") llh = datascript.init86I(mode='box') llhmodel, exp, MC = llh[0], llh[1], llh[2] inj = PointSourceInjector(Gamma, seed=0) inj.fill(src_dec, exp, MC, livetime=llhmodel.livetime) if disc: print("Calculating Discovery Potential...") alpha = norm.sf(5) beta = 0.5 TSval = TSval5sig calctype = "disc" else: print("Calculating Sensitivity...") alpha = 0.5 beta = 0.9 TSval = TSval_median calctype = "sens"
l = "w/" if not energy: l += "o" llh.llh_model = (UniformLLH(sinDec_bins=max( 3, len(llh.exp) // 200), sinDec_range=[-1., 1.]), mc) props = dict() sens = list() disc = list() for j, gamma in enumerate(Gamma): # init a injector class sampling events at a point source inj = PointSourceInjector(gamma, sinDec_bandwidth=1.) # start calculation for dec = 0 result = llh.weighted_sensitivity(0., [0.5, 2.87e-7], [0.9, 0.5], inj, mc, n_bckg=10000, n_iter=1000, eps=1.e-2, **props) props["TSval"] = result["TSval"] sens.append(result["mu"][0]) disc.append(result["mu"][1])
########## # SKYLAB # ########## #llh and inj# import load_j7yr_npz as datascript if n == 7: llh, exp, mc = datascript.load7yr() elif n == 4: llh, exp, mc = datascript.load4yr() elif n == 3: llh, exp, mc = datascript.load3yr() inj = PointSourceInjector(gamma=gamma, E0=1 * TeV, seed=args.seed, e_range=(0, np.inf)) inj.fill(src_dec, exp, mc, llh.livetime, src_w) ########## # SKYLAB # ########## outputfolder = '/data/user/brelethford/Output/npz/' sens_dir = misc.ensure_dir( outputfolder + 'stacking_sensitivity/{0}yr/{1}/{2}/sig/gamma_{3}/{4}/'.format( n, cat, weight, gamma, n_inj)) ###############################################################################
l = "w/" if not energy: l += "o" model = UniformLLH(sinDec_bins=max(3, len(llh.exp) // 200), sinDec_range=[-1., 1.]) llh.set_llh_model(model, mc) ts = None sens = list() disc = list() for j, gamma in enumerate(Gamma): # init a injector class sampling events at a point source inj = PointSourceInjector(gamma, sinDec_bandwidth=1.) inj.fill(0., mc, llh.livetime) # start calculation for dec = 0 result = llh.weighted_sensitivity(np.pi, 0., [0.5, 2.87e-7], [0.9, 0.5], inj, TSval=ts, n_iter=1000, n_bckg=10000, eps=1e-2)[0] ts = result["TS"] sens.append(result["mu"][0]) disc.append(result["mu"][1])
llh = datascript.load7yr() elif years == 4: llh = datascript.load4yr() elif years == 3: llh = datascript.load3yr() elif years == 1: if catalog == 'Milagro17': print("Using IC40") llh = datascript.loadIC40() else: print("Using IC86") llh = datascript.load1yr() #Set up Injector: TeV = 1000 inj = PointSourceInjector(gamma=2., E0=1 * TeV, seed=0) inj.fill(src_dec, llh[0].exp, llh[0].mc, llh[0].livetime) #inj.fill(src_dec, exp, MC, livetime = llhmodel.livetime) if disc: print("Calculating Discovery Potential...") alpha = norm.sf(5) beta = 0.5 TSval = TSval5sig calctype = "disc" else: print("Calculating Sensitivity...") alpha = 0.5 beta = 0.9 TSval = TSval_median
############################################################################### ########## # SKYLAB # ########## import load_j7yr_npz as datascript if n == 7: llh, exp, mc = datascript.load7yr() elif n == 4: llh, exp, mc = datascript.load4yr() elif n == 3: llh, exp, mc = datascript.load3yr() inj = PointSourceInjector(gamma = gamma, E0 = 1*TeV, e_range=(0,np.inf)) inj.fill(src_dec, exp, mc, llh.livetime, src_w) ########## # SKYLAB # ########## outputfolder = '/data/user/brelethford/Output/npz/' sens_dir = misc.ensure_dir (outputfolder+'stacking_sensitivity/{0}yr/{1}/{2}/'.format(n,cat,weight)) bg_dir = sens_dir+'bg/' sig_dir = misc.ensure_dir(sens_dir+'sig/gamma_{}/'.format(gamma)) #For Plots: dir_name = misc.ensure_dir("/data/user/brelethford/AGN_Core/Plots/npz/plots/stacking/{}yr/{}/{}/{}/".format(n,cat,weight,gamma)) subprocess.call(['mkdir', '-p', '{0}'.format(dir_name)])