Beispiel #1
0
def initMESE3yr(mode='box', **kwargs):
    arr_exp = cache.load(filename_pickle + "MESE/exp3yr.pickle")
    arr_mc = cache.load(filename_pickle + "MESE/mc.pickle")

    dec_bins = np.unique(
        np.concatenate([
            np.linspace(-1., -0.92, 3 + 1),
            np.linspace(-0.92, hem, 10 + 1),
        ]))
    energy_bins = [
        np.linspace(2., 8.5, 40 + 1),
        np.linspace(-1., hem, 4 + 1),
    ]
    llh_model = EnergyLLH(energy_bins,
                          sinDec_bins=dec_bins,
                          allow_empty=True,
                          kernel=1,
                          seed=2)

    llh = PointSourceLLH(arr_exp,
                         arr_mc,
                         livetime=livetimeMESE3yr,
                         llh_model=llh_model,
                         mode=mode,
                         **kwargs)

    return (llh, arr_exp, arr_mc)
Beispiel #2
0
def init79(decorr=False, mode='box', **kwargs):
    if decorr:
        arr_exp = cache.load(filename_pickle + "IC79/noMESE/exp.pickle")
        arr_mc = cache.load(filename_pickle + "IC79/noMESE/mc.pickle")
    else:
        arr_exp = np.load(filename_pickle + "standard/IC79b_exp.npy")
        arr_mc = np.load(filename_pickle + "standard/IC79b_corrected_MC.npy")

    dec_bins = np.unique(
        np.concatenate([
            np.linspace(-1., -0.75, 10 + 1),
            np.linspace(-0.75, 0.0, 15 + 1),
            np.linspace(0.0, 1., 20 + 1),
        ]))

    energy_bins = [np.linspace(2., 9., 40 + 1), dec_bins]

    llh_model = EnergyLLH(energy_bins,
                          sinDec_bins=dec_bins,
                          allow_empty=True,
                          kernel=1,
                          seed=2)

    llh = PointSourceLLH(arr_exp,
                         arr_mc,
                         livetime=livetime_IC79,
                         llh_model=llh_model,
                         mode=mode,
                         **kwargs)

    return (llh, arr_exp, arr_mc)
Beispiel #3
0
def init3yr(decorr=False, mode='box', **kwargs):
    if decorr:
        arr_exp = cache.load(filename_pickle + "epinat_3yr/noMESE/exp.pickle")
        arr_mc = cache.load(filename_pickle + "epinat_3yr/noMESE/mc.pickle")
    else:
        arr_exp = cache.load(filename_pickle + "epinat_3yr/exp.pickle")
        arr_mc = cache.load(filename_pickle + "epinat_3yr/mc.pickle")
    dec_bins = np.unique(
        np.concatenate([
            np.linspace(-1., -0.93, 4 + 1),
            np.linspace(-0.93, -0.3, 10 + 1),
            np.linspace(-0.3, 0.05, 9 + 1),
            np.linspace(0.05, 1., 18 + 1),
        ]))

    energy_bins = [np.linspace(1., 9.5, 50 + 1), dec_bins]

    llh_model = EnergyLLH(energy_bins,
                          sinDec_bins=dec_bins,
                          allow_empty=True,
                          kernel=1,
                          seed=2)

    llh = PointSourceLLH(arr_exp,
                         arr_mc,
                         livetime=livetime3yr,
                         llh_model=llh_model,
                         mode=mode,
                         **kwargs)

    return (llh, arr_exp, arr_mc)
Beispiel #4
0
def initMESE3yr(energy=True, mode='all', **kwargs):
    arr_exp = cache.load(filename_pickle + "MESE/exp3yr.pickle")
    arr_mc = cache.load(filename_pickle + "MESE/mc.pickle")

    dec_bins = np.unique(
        np.concatenate([
            np.linspace(-1., -0.92, 3 + 1),
            np.linspace(-0.92, hem, 10 + 1),
        ]))
    energy_bins = [
        np.linspace(2., 8.5, 40 + 1),
        np.linspace(-1., hem, 4 + 1),
    ]
    if energy:
        llh_model = EnergyLLH(energy_bins, sinDec_bins=dec_bins)
    else:

        llh_model = ClassicLLH(sinDec_bins=dec_bins, sinDec_range=[-1., 1.])

    llh = PointSourceLLH(arr_exp,
                         arr_mc,
                         livetime=livetimeMESE3yr,
                         llh_model=llh_model,
                         mode=mode,
                         **kwargs)

    return (llh, arr_exp, arr_mc)
Beispiel #5
0
def initMESEfollowup(energy=True, mode='all', **kwargs):
    arr_exp = cache.load(filename_pickle + "MESE/expfollowup.pickle")
    arr_mc = cache.load(filename_pickle + "MESE/mc.pickle")

    dec_bins = np.unique(
        np.concatenate([
            np.linspace(-1., -0.93, 4 + 1),
            np.linspace(-0.93, hem, 12 + 1),
        ]))

    energy_bins = [np.linspace(2., 8.5, 67 + 1), np.linspace(-1., hem, 4 + 1)]

    arr_mc = arr_mc[arr_mc["logE"] > 1.]

    llh_model = EnergyLLH(energy_bins,
                          sinDec_bins=dec_bins,
                          allow_empty=True,
                          kernel=1,
                          seed=2)

    llh = PointSourceLLH(arr_exp,
                         arr_mc,
                         livetime=livetimeMESEfollowup,
                         llh_model=llh_model,
                         mode=mode,
                         **kwargs)

    return (llh, arr_exp, arr_mc)
Beispiel #6
0
def init86I(energy=True, decorr=False, nopull=False, mode='all', **kwargs):
    if decorr:
        arr_exp = cache.load(filename_pickle + "IC86I/noMESE/exp.pickle")
        arr_mc = cache.load(filename_pickle + "IC86I/noMESE/mc.pickle")
    elif nopull:
        arr_exp = cache.load(filename_pickle + "nopull/IC86I/exp.pickle")
        arr_mc = cache.load(filename_pickle + "nopull/IC86I/mc.pickle")
    else:
        arr_exp = cache.load(filename_pickle + "IC86I/exp.pickle")
        arr_mc = cache.load(filename_pickle + "IC86I/mc.pickle")
    dec_bins = np.unique(
        np.concatenate([
            np.linspace(-1., -0.2, 10 + 1),
            np.linspace(-0.2, hem, 4 + 1),
            np.linspace(hem, 0.2, 5 + 1),
            np.linspace(0.2, 1., 10),
        ]))
    #energy_bins = [np.linspace(1., 10., 67 + 1), dec_bins]
    energy_bins = [np.linspace(1.5, 9.5, 64 + 1), dec_bins]

    if energy:
        llh_model = EnergyLLH(energy_bins, sinDec_bins=dec_bins)
    else:
        llh_model = ClassicLLH(sinDec_bins=dec_bins, sinDec_range=[-1., 1.])

    llh = PointSourceLLH(arr_exp,
                         arr_mc,
                         livetime=livetime_IC86I,
                         llh_model=llh_model,
                         mode=mode,
                         **kwargs)

    return (llh, arr_exp, arr_mc)
Beispiel #7
0
def init79(energy=True, decorr=False, mode='all', **kwargs):
    if decorr:
        arr_exp = cache.load(filename_pickle + "IC79/noMESE/exp.pickle")
        arr_mc = cache.load(filename_pickle + "IC79/noMESE/mc.pickle")
    else:
        arr_exp = cache.load(filename_pickle + "IC79/exp.pickle")
        arr_mc = cache.load(filename_pickle + "IC79/mc.pickle")

    dec_bins = np.unique(
        np.concatenate([
            np.linspace(-1., -0.75, 10 + 1),
            np.linspace(-0.75, 0.0, 15 + 1),
            np.linspace(0.0, 1., 20 + 1),
        ]))

    #energy_bins = [np.linspace(2., 9., 67 + 1), dec_bins]
    energy_bins = [np.linspace(2.5, 8.5, 64 + 1), dec_bins]

    if energy:

        llh_model = EnergyLLH(energy_bins, sinDec_bins=dec_bins)
    else:

        llh_model = ClassicLLH(sinDec_bins=dec_bins, sinDec_range=[-1., 1.])

    llh = PointSourceLLH(arr_exp,
                         arr_mc,
                         livetime=livetime_IC79,
                         llh_model=llh_model,
                         mode=mode,
                         **kwargs)

    return (llh, arr_exp, arr_mc)
Beispiel #8
0
def init86I(decorr=False, nopull=False, mode='box', **kwargs):
    if decorr:
        arr_exp = cache.load(filename_pickle + "IC86I/noMESE/exp.pickle")
        arr_mc = cache.load(filename_pickle + "IC86I/noMESE/mc.pickle")
    elif nopull:
        arr_exp = np.load(filename_pickle + "nopull/IC86_exp.npy")
        arr_mc = np.load(filename_pickle + "nopull/IC86_corrected_MC.npy")
    else:
        arr_exp = np.load(filename_pickle + "standard/IC86_exp.npy")
        arr_mc = np.load(filename_pickle + "standard/IC86_corrected_MC.npy")
    dec_bins = np.unique(
        np.concatenate([
            np.linspace(-1., -0.2, 10 + 1),
            np.linspace(-0.2, hem, 4 + 1),
            np.linspace(hem, 0.2, 5 + 1),
            np.linspace(0.2, 1., 10),
        ]))
    energy_bins = [np.linspace(1., 10., 40 + 1), dec_bins]

    llh_model = EnergyLLH(energy_bins,
                          sinDec_bins=dec_bins,
                          allow_empty=True,
                          kernel=1,
                          seed=2)

    llh = PointSourceLLH(arr_exp,
                         arr_mc,
                         livetime=livetime_IC86I,
                         llh_model=llh_model,
                         mode=mode,
                         **kwargs)

    return (llh, arr_exp, arr_mc)
Beispiel #9
0
    def initialize_llh(self, skipped=None, scramble=False):
        '''
        Grab data and format it all into a skylab llh object
        '''
        if self.exp is None:
            self.get_data()

        if self._verbose:
            print("Initializing Point Source LLH in Skylab")

        assert self._fix_index != self._float_index,\
            'Must choose to either float or fix the index'

        if self._fix_index:
            llh_model = EnergyLLH(
                twodim_bins=[self.energy_bins, self.sinDec_bins],
                allow_empty=True,
                spectrum=PowerLaw(A=1, gamma=self.index, E0=1000.)) 
        elif self._float_index:
            llh_model = EnergyLLH(
                twodim_bins=[self.energy_bins, self.sinDec_bins],
                allow_empty=True,
                bounds=self._index_range,
                seed = self.index)
        
        box = TemporalModel(
            grl=self.grl,
            poisson_llh=True,
            days=self._nb_days,
            signal=BoxProfile(self.start, self.stop))
        
        if skipped is not None:
            self.exp = self.remove_event(self.exp, self.dset, skipped)

        if self.extension is not None:
            src_extension = float(self.extension)
            self.save_items['extension'] = src_extension
        else:
            src_extension = None

        llh = PointSourceLLH(
            self.exp,                      # array with data events
            self.mc,                       # array with Monte Carlo events
            self.livetime,                 # total livetime of the data events
            ncpu=5,                        # use 10 CPUs when computing trials
            scramble=scramble,             # set to False for unblinding
            timescramble=True,             # not just RA scrambling
            llh_model=llh_model,           # likelihood model
            temporal_model=box,            # use box for temporal model
            nsource_bounds=(0., 1e3),      # bounds on fitted ns
            src_extension = src_extension, # Model symmetric extended source
            nsource=1.,                    # seed for nsignal fit
            seed=self.llh_seed)           

        return llh
Beispiel #10
0
def init59(energy=True, mode='all', nopull=False, **kwargs):
    if nopull:
        arr_exp = cache.load(filename_pickle + "nopull/IC59/exp.pickle")
        arr_mc = cache.load(filename_pickle + "nopull/IC59/mc.pickle")
    else:
        arr_exp = cache.load(filename_pickle + "IC59/exp.pickle")
        arr_mc = cache.load(filename_pickle + "IC59/mc.pickle")

    dec_bins = np.unique(
        np.concatenate([
            np.linspace(-1., -0.95, 2 + 1),
            np.linspace(-0.95, -0.25, 25 + 1),
            np.linspace(-0.25, 0.05, 15 + 1),
            np.linspace(0.05, 1., 10 + 1),
        ]))

    dec_bins_logE = np.unique(
        np.concatenate([
            np.linspace(-1., -0.05, 20 + 1),
            np.linspace(0.05, 1., 10 + 1),
        ]))

    #energy_bins = [np.linspace(2., 9.5, 67 + 1), dec_bins_logE]
    energy_bins = [np.linspace(2.5, 8.5, 64 + 1), dec_bins_logE]

    if energy:

        llh_model = EnergyLLH(energy_bins, sinDec_bins=dec_bins)
    else:

        llh_model = ClassicLLH(sinDec_bins=dec_bins, sinDec_range=[-1., 1.])
    llh = PointSourceLLH(arr_exp,
                         arr_mc,
                         livetime=livetime_IC59,
                         llh_model=llh_model,
                         mode=mode,
                         **kwargs)

    return (llh, arr_exp, arr_mc)
Beispiel #11
0
def init40(energy=True, mode='all', nopull=False, **kwargs):
    if nopull:
        arr_exp = cache.load(filename_pickle + "nopull/IC40/exp.pickle")
        arr_mc = cache.load(filename_pickle + "nopull/IC40/mc.pickle")
    else:
        arr_exp = cache.load(filename_pickle + "IC40/exp.pickle")
        arr_mc = cache.load(filename_pickle + "IC40/mc.pickle")

    dec_bins = np.unique(
        np.concatenate([
            np.linspace(-1., -0.25, 10 + 1),
            np.linspace(-0.25, 0.0, 5 + 1),
            np.linspace(0.0, 1., 10 + 1),
        ]))

    dec_bins_logE = np.unique(
        np.concatenate([
            np.linspace(-1., -0.25, 10 + 1),
            np.linspace(-0.25, 0.0, 10 + 1),
            np.linspace(0.0, 1., 10 + 1),
        ]))
    #These binnings are done, year specifically, in load.py from stefan.
    #energy_bins = [np.linspace(2., 9., 75 + 1), dec_bins_logE]
    energy_bins = [np.linspace(2.6, 8.4, 64 + 1), dec_bins_logE]
    if energy:

        llh_model = EnergyLLH(energy_bins, sinDec_bins=dec_bins)
    else:

        llh_model = ClassicLLH(sinDec_bins=dec_bins, sinDec_range=[-1., 1.])
    llh = PointSourceLLH(arr_exp,
                         arr_mc,
                         livetime=livetime_IC40,
                         llh_model=llh_model,
                         mode=mode,
                         **kwargs)

    return (llh, arr_exp, arr_mc)
Beispiel #12
0
def init59(mode='box', nopull=False, **kwargs):
    if nopull:
        arr_exp = np.load(filename_pickle + "nopull/IC59_exp.npy")
        arr_mc = np.load(filename_pickle + "nopull/IC59_corrected_MC.npy")
    else:
        arr_exp = np.load(filename_pickle + "standard/IC59_exp.npy")
        arr_mc = np.load(filename_pickle + "standard/IC59_corrected_MC.npy")

    dec_bins = np.unique(
        np.concatenate([
            np.linspace(-1., -0.95, 2 + 1),
            np.linspace(-0.95, -0.25, 25 + 1),
            np.linspace(-0.25, 0.05, 15 + 1),
            np.linspace(0.05, 1., 10 + 1),
        ]))

    dec_bins_logE = np.unique(
        np.concatenate([
            np.linspace(-1., -0.05, 20 + 1),
            np.linspace(0.05, 1., 10 + 1),
        ]))

    energy_bins = [np.linspace(2., 9.5, 50 + 1), dec_bins_logE]

    llh_model = EnergyLLH(energy_bins,
                          sinDec_bins=dec_bins,
                          allow_empty=True,
                          kernel=1,
                          seed=2)

    llh = PointSourceLLH(arr_exp,
                         arr_mc,
                         livetime=livetime_IC59,
                         llh_model=llh_model,
                         mode=mode,
                         **kwargs)

    return (llh, arr_exp, arr_mc)
Beispiel #13
0
def init40(mode='box', nopull=False, **kwargs):
    if nopull:
        arr_exp = np.load(filename_pickle + "nopull/IC40_exp.npy")
        arr_mc = np.load(filename_pickle + "nopull/IC40_corrected_MC.npy")
    else:
        arr_exp = np.load(filename_pickle + "standard/IC40_exp.npy")
        arr_mc = np.load(filename_pickle + "standard/IC40_corrected_MC.npy")

    dec_bins = np.unique(
        np.concatenate([
            np.linspace(-1., -0.25, 10 + 1),
            np.linspace(-0.25, 0.0, 5 + 1),
            np.linspace(0.0, 1., 10 + 1),
        ]))

    dec_bins_logE = np.unique(
        np.concatenate([
            np.linspace(-1., -0.25, 10 + 1),
            np.linspace(-0.25, 0.0, 10 + 1),
            np.linspace(0.0, 1., 10 + 1),
        ]))
    #These binnings are done, year specifically, in load.py from stefan.
    energy_bins = [np.linspace(1., 10., 35 + 1), dec_bins_logE]
    llh_model = EnergyLLH(energy_bins,
                          sinDec_bins=dec_bins,
                          allow_empty=True,
                          kernel=1,
                          seed=2)
    llh = PointSourceLLH(arr_exp,
                         arr_mc,
                         livetime=livetime_IC40,
                         llh_model=llh_model,
                         mode=mode,
                         **kwargs)

    return (llh, arr_exp, arr_mc)
Beispiel #14
0
            llh = datascript.load4yr(mode='box', sirin=True, nopull=True)
    elif catalog == 'Milagro17':
        llh = datascript.init86I(mode='box')
    else:
        if years == 3:
            if catalog == '2LAC':
                llh = datascript.load3yr_no40(mode='all')
            else:
                llh = datascript.load3yr(mode='all')
        elif years == 4:
            llh = datascript.load4yr(mode='all')

if years == 1:
    bckg_trials = PointSourceLLH.do_trials(
        llh[0],
        n_iter=batchsize,
        src_ra=src_ra,
        src_dec=src_dec,
        src_w=modelweights['{}'.format(llhweight)])
else:
    bckg_trials = FastMultiPointSourceLLH.do_trials(
        llh[0],
        n_iter=batchsize,
        src_ra=src_ra,
        src_dec=src_dec,
        src_w=modelweights['{}'.format(llhweight)])

#choose an output dir, and make sure it exists
this_dir = os.path.dirname(os.path.abspath(__file__))

if catalog == 'WHSP_Blazars':
    out_dir = misc.ensure_dir(
Beispiel #15
0
def config(seasons, seed=1, scramble=True, verbose=True, dec=0.):
    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
  """

    # store individual llh as lists to prevent pointer over-writing
    llh = []

    multillh = FastMultiPointSourceLLH(seed=seed, ncpu=25)

    # setup likelihoods
    if verbose: print("\n seasons:")
    for season in np.atleast_1d(seasons):

        #sample = 'PointSourceTracks7yr_galactic_plane'
        #sample = 'PointSourceTracks7yr'
        #sample = 'PointSourceTracks_v002p01b'
        sample = 'PointSourceTracks'

        exp, mc, livetime = Datasets[sample].season(season)
        sinDec_bins = Datasets[sample].sinDec_bins(season)
        energy_bins = Datasets[sample].energy_bins(season)

        mc = mc[mc["logE"] > 1.]

        if verbose:
            print("   - %-15s (livetime %7.2f days, %6d events)" %
                  (season, livetime, exp.size))

        llh_model = EnergyLLH(twodim_bins=[energy_bins, sinDec_bins],
                              allow_empty=True,
                              bounds=[1., 4.],
                              seed=2.,
                              kernel=1)

        llh.append(
            PointSourceLLH(exp,
                           mc,
                           livetime,
                           mode="box",
                           seed=seed,
                           scramble=scramble,
                           llh_model=llh_model,
                           nsource_bounds=(0., 1e3),
                           delta_ang=np.deg2rad(1.),
                           nsource=15.))

        multillh.add_sample(season, llh[-1])

        # save a little RAM by removing items copied into LLHs
        del exp, mc

    # END for (season)

    #######
    # LLH #
    #######

    #############################################################################

    ############
    # INJECTOR #
    ############
    '''
  inj = PointSourceInjector(gamma = 2., E0 = 1*TeV, seed = seed)
  inj.fill(dec, multillh.exp, multillh.mc, multillh.livetime)
  '''
    inj = None
    ############
    # 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)
Beispiel #16
0
    calctype = "disc"
else:
    print("Calculating Sensitivity...")
    alpha = 0.5
    beta = 0.9
    TSval = TSval_median
    calctype = "sens"

if catalog:
    if years == 1:
        sensitivity = PointSourceLLH.weighted_sensitivity(
            llhmodel,
            src_ra=src_ra,
            src_dec=src_dec,
            alpha=alpha,
            beta=beta,
            inj=inj,
            TSval=TSval,
            src_w=modelweights['{}'.format(injweight)],
            eps=0.04,
            n_iter=100)
    else:
        sensitivity = MultiPointSourceLLH.weighted_sensitivity(
            llhmodel,
            src_ra=src_ra,
            src_dec=src_dec,
            alpha=alpha,
            beta=beta,
            inj=inj,
            TSval=TSval,
            src_w=modelweights['{}'.format(injweight)],
Beispiel #17
0
def config(alert_ind,
           seed=1,
           scramble=True,
           e_range=(0, np.inf),
           g_range=[1., 5.],
           gamma=2.0,
           E0=1 * TeV,
           remove=False,
           ncpu=20,
           nside=256,
           poisson=False,
           injector=True,
           verbose=True,
           smear=True):
    r""" Configure point source likelihood and injector. 

    Parameters
    ----------
    alert_ind: int
    index of IceCube alert event

    seed : int
    Seed for random number generator

    Returns
    -------
    llh : PointSourceLLH
    Point source likelihood object
    inj : PriorInjector
     Point source injector object
    """
    seasons = [("GFUOnline_v001p02", "IC86, 2011-2018"),
               ("GFUOnline_v001p02", "IC86, 2019")]
    #skymaps_path = '/data/user/steinrob/millipede_scan_archive/fits_v3_prob_map/'
    #files = glob(skymaps_path + '*.fits')
    #skymap_fits = fits.open(files[alert_ind])[0].data

    #Turn this into a function read_alert_event()
    #skymap_files = glob('/data/ana/realtime/alert_catalog_v2/2yr_prelim/fits_files/Run13*.fits.gz')
    skymap_files = glob(
        '/data/ana/realtime/alert_catalog_v2/fits_files/Run1*.fits.gz')
    #skymap_f = fits.open(skymap_files[alert_ind])
    #skymap_fits = skymap_f[1].data
    #skymap_header = skymap_f[1].header
    skymap_fits, skymap_header = hp.read_map(skymap_files[alert_ind],
                                             h=True,
                                             verbose=False)
    skymap_header = {name: val for name, val in skymap_header}
    run_id, ev_id = skymap_header['RUNID'], skymap_header['EVENTID']
    ev_mjd = skymap_header['EVENTMJD']
    ev_iso = skymap_header['START']
    signalness = skymap_header['SIGNAL']
    ev_en = skymap_header['ENERGY']
    ev_ra, ev_dec = np.radians(skymap_header['RA']), np.radians(
        skymap_header['DEC'])
    ev_stream = skymap_header['I3TYPE']
    skymap_llh = skymap_fits.copy()
    skymap_fits = np.exp(-1. * skymap_fits /
                         2.)  #Convert from 2LLH to unnormalized probability
    skymap_fits = np.where(skymap_fits > 1e-12, skymap_fits, 0.0)
    skymap_fits = skymap_fits / np.sum(skymap_fits)
    if smear:
        ninety_msk = skymap_llh < 64.2
        init_nside = hp.get_nside(skymap_llh)
        cdf = np.cumsum(np.sort(skymap_fits[ninety_msk][::-1]))
        pixs_above_ninety = np.count_nonzero(cdf > 0.1)
        original_ninety_area = hp.nside2pixarea(init_nside) * pixs_above_ninety
        new_ninety_area = hp.nside2pixarea(init_nside) * np.count_nonzero(
            skymap_fits[ninety_msk])
        original_ninety_radius = np.sqrt(original_ninety_area / np.pi)
        new_ninety_radius = np.sqrt(new_ninety_area / np.pi)
        scaled_probs = scale_2d_gauss(skymap_fits, original_ninety_radius,
                                      new_ninety_radius)
        skymap_fits = scaled_probs

    if hp.pixelfunc.get_nside(skymap_fits) != nside:
        skymap_fits = hp.pixelfunc.ud_grade(skymap_fits, nside)
    skymap_fits = skymap_fits / skymap_fits.sum()
    #print(hp.pixelfunc.get_nside(skymap_fits))
    spatial_prior = SpatialPrior(skymap_fits, containment=0.99)

    llh = []  # store individual llh as lists to prevent pointer over-writing
    multillh = MultiPointSourceLLH(ncpu=1)

    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,
                                                    floor=np.radians(0.2))
        sinDec_bins = Datasets[sample].sinDec_bins(name)
        energy_bins = Datasets[sample].energy_bins(name)

        msg = "   - % 15s (" % season
        msg += "livetime %7.2f days, %6d events" % (livetime, exp.size)
        msg += ", mjd0 %.2f" % min(exp['time'])
        msg += ", mjd1 %.2f)" % max(exp['time'])
        if verbose:
            print(msg)

        llh_model = EnergyLLH(twodim_bins=[energy_bins, sinDec_bins],
                              allow_empty=True,
                              bounds=g_range,
                              seed=gamma,
                              kernel=1,
                              ncpu=ncpu)

        llh.append(
            PointSourceLLH(exp,
                           mc,
                           livetime,
                           mode="box",
                           scramble=scramble,
                           llh_model=llh_model,
                           nsource_bounds=(0., 1e3),
                           nsource=1.))

        multillh.add_sample(sample + " : " + name, llh[-1])

        # save a little RAM by removing items copied into LLHs
        del exp, mc

        # END for (season)

    ######################### REMOVE EVENT

    if injector is False:
        return multillh, spatial_prior
    else:
        inj = PriorInjector(spatial_prior,
                            seed=seed,
                            gamma=gamma,
                            E0=1 * TeV,
                            bunchsize=10)
        inj.fill(multillh.exp, multillh.mc, multillh.livetime)

        if verbose:
            print("\n injected spectrum:")
            print("   - %s" % str(inj.spectrum))

    return multillh, spatial_prior, inj
Beispiel #18
0
rnd_seed = 1
multillh = MultiPointSourceLLH(seed=rnd_seed, ncpu=40)

livetimes = _loader.livetime_loader()
for name, livetime in sorted(livetimes.items()):
    print("\n# Setting up LLH for sample '{}'".format(name))
    # Get exp data and MC
    exp = _loader.exp_data_loader(name)[name]
    mc = _loader.mc_loader(name)[name]

    # Setup the energy LLH model with fixed index, only ns is fitted
    settings = _loader.settings_loader(name, skylab_bins=use_skylab_bins)[name]
    llh_model = EnergyLLH(**settings["llh_model_opts"])
    llh = PointSourceLLH(exp,
                         mc,
                         livetime,
                         llh_model,
                         scramble=scramble,
                         **settings["llh_opts"])

    multillh.add_sample(name, llh)

    del exp
    del mc
    gc.collect()

# Load the BG only distribution
with gzip.open(pdf_path) as fp:
    bg_ts_dist = ExpTailEmpiricalDist.from_json(fp)
    print("Loaded BG only TS distribution from:\n    {}".format(pdf_path))

# ##############################################################################
Beispiel #19
0
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(
            PointSourceLLH(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)