Пример #1
0
def loading(filename):
    prush('<- {0} ...'.format(filename))
    return cache.load(filename)
Пример #2
0
mpl.use('pdf')
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import chi2
from icecube.umdtools import cache,misc
from icecube import icetray, dataclasses, histlite
##Make plots prettier
misc.tex_mpl_rc()
w=4
propsmall = mpl.font_manager.FontProperties (size='small')
propxsmall = mpl.font_manager.FontProperties (size='x-small')

###In this script I'll show some characteristics of the catalogue.###
picklefolder = '/data/user/brelethford/Data/SwiftBAT70m/pickle/'

params=cache.load(picklefolder+'params.pickle')
src_ra, src_dec, redshift, gamma, flux, lum =  params['ra'], params['dec'], params['redshift'], params['gamma'], params['flux'], params['lum']

N = len(src_ra)

arr= np.empty((N, ), dtype=[("ra", np.float), ("dec", np.float),
                                 ("z", np.float), ("gamma", np.float),
                                 ('flux', np.float), ('lum', np.float)])
arr["ra"] = src_ra
arr["dec"] = src_dec
arr["gamma"] = gamma
arr["z"] = redshift
arr["flux"] = flux
arr["lum"] = lum

np.save(picklefolder+'seyferts.npy', arr)
Пример #3
0
parser.add_option(
    '--batchsize',
    dest='batchsize',
    type=int,
    default=1000,
    metavar='BATCHSIZE',
    help='Assigns how many background trials are used in each batch.')

opts, args = parser.parse_args()

batch = opts.batch
batchsize = opts.batchsize
sky = opts.sky

params = cache.load(datafolder + 'SwiftBAT70m/pickle/params.pickle')

## These params contain everything we should need to weight our sources. I've got to select the sources I need to use in this example. ##

src_ra, src_dec, redshift, gamma, flux, lum = params['ra'], params[
    'dec'], params['redshift'], params['gamma'], params['flux'], params['lum']

##Choose the one we're going to use...

if sky == 'onenorth':
    src_ra, src_dec, redshift, flux = [params['ra'][2]], [params['dec'][2]], [
        params['redshift'][2]
    ], [params['flux'][2]]
elif sky == 'twonorth':
    src_ra, src_dec, redshift, flux = [params['ra'][2], params['ra'][6]], [
        params['dec'][2], params['dec'][6]
Пример #4
0
def initMC_79():
  mc = cache.load(filename_pickle+"sirin_IC79/mc.pickle")
  return mc
Пример #5
0
    ra,dec=zip(*points)
    ra=list(ra)
    dec=list(dec)
    redshift=[float(catalog[i][15]) for i in range(len(catalog))]
    lum =[float(catalog[i][16]) for i in range(len(catalog))]
    gamma=[float(catalog[i][11]) for i in range(len(catalog))]
    flux = [float(catalog[i][7]) for i in range(len(catalog))]
    params={'ra':ra,'dec':dec,'redshift':redshift,'gamma':gamma,'flux':flux,'lum':lum}
    return params

params = cache.get (datafolder + 'SwiftBAT70m/pickle/params.pickle', get_SwiftBAT_params)

###Now I'll read in the background TS stuff.###
datafolder='/data/user/brelethford/Output/stacking_sensitivity/SwiftBAT70m/flux/background_trials/'

files = [cache.load(datafolder+file) for file in os.listdir(datafolder) if file.endswith('.array')]
n_inj=[]
nsources=[]
TS=[]
beta=(0.5) #For background ts
TS_beta=[] #Calculated from the total TS median after we get all the TS.
beta_err=[]
gamma=[]

for file in files:
  for item in range(len(file['n_inj'])):
    n_inj.append(file['n_inj'][item])
    nsources.append(file['nsources'][item])
    TS.append(file['TS'][item])
    gamma.append(file['gamma'][item])
Пример #6
0
                  type=int,
                  default=4,
                  metavar='YEARS',
                  help='Number of years of data')

opts, args = parser.parse_args()
batch = opts.batch
batchsize = opts.batchsize
llhweight = opts.llhweight
injweight = opts.injweight
catalog = opts.catalog
years = opts.years

datafolder = '/data/user/brelethford/Data/'

params = cache.load(datafolder + '{}/pickle/params.pickle'.format(catalog))

## These params contain everything we should need to weight our sources. I've made sure the dec and ra are in radians. ##

src_ra, src_dec = params['ra'], params['dec']

## Here's were we put the weights in depending on the catalog. If I do this right, I should only need one version of the script afterwards.

if catalog == 'SwiftBAT70m':
    flux, redshift = params['flux'], params['redshift']
    modelweights = {
        'flux': flux,
        'redshift': np.array(list(np.power(redshift, -2))),
        'uniform': np.array(list(np.ones_like(src_dec)))
    }
elif catalog == '4yr_Starburst':
Пример #7
0
                help = 'spectral index for injection')

parser.add_option ('--llhweight', dest = 'llhweight', type = str,
                default = 'uniform', metavar = 'LLHWEIGHT',
                help = 'Sets the weighting used in the llh model for point source searches.')

parser.add_option ('--longrun', dest = 'longrun',
                default = False, action = 'store_true',
                help = 'Allows longer runtime for sensitivity calculation (>12 hours)')

opts,args = parser.parse_args ()
Gamma=opts.gamma

llhweight = opts.llhweight

params = cache.load (datafolder + '2LAC/pickle/params.pickle')



###Now I'll read in the background TS stuff.###
datafolder='/data/user/brelethford/Output/stacking_sensitivity/2LAC/{}/background_trials/'.format(llhweight)

files = [cache.load(datafolder+file) for file in os.listdir(datafolder) if file.endswith('.array')]
n_inj=[]
nsources=[]
TS=[]
beta=(0.5) #For background ts
TS_beta=[] #Calculated from the total TS median after we get all the TS.
beta_err=[]
gamma=[]
Пример #8
0
def initMC_86I(decorr=False):
    if decorr:
        mc = cache.load(filename_pickle + "IC86I/noMESE/mc.pickle")
    else:
        mc = cache.load(filename_pickle + "IC86I/mc.pickle")
    return mc
Пример #9
0
def initMC_3yr(decorr=False):
    if decorr:
        mc = cache.load(filename_pickle + "epinat_3yr/noMESE/mc.pickle")
    else:
        mc = cache.load(filename_pickle + "epinat_3yr/mc.pickle")
    return mc
Пример #10
0
def loadMC_3yr_nopull():
    mc40 = cache.load(filename_pickle + "nopull/sirin_IC40/mc.pickle")
    mc59 = cache.load(filename_pickle + "nopull/sirin_IC59/mc.pickle")
    mc79 = cache.load(filename_pickle + "nopull/sirin_IC79/mc.pickle")
    MC = {0: mc40, 1: mc59, 2: mc79}
    return MC
Пример #11
0
def initMC_59():
    mc = cache.load(filename_pickle + "IC59/mc.pickle")
    return mc
Пример #12
0
def loadMC_3yr():
    mc40 = cache.load(filename_pickle + "IC40/mc.pickle")
    mc59 = cache.load(filename_pickle + "IC59/mc.pickle")
    mc79 = cache.load(filename_pickle + "IC79/mc.pickle")
    MC = {0: mc40, 1: mc59, 2: mc79}
    return MC
Пример #13
0
from scipy.signal import convolve2d
#Check this out - see if there's a new version specifically for multi / stacking
from bstacking.ps_injector import PointSourceInjector, StackingPointSourceInjector
from bstacking.utils import poisson_weight
from optparse import OptionParser
import argparse

sys.path.append(
    "/home/brelethford/Documents/IceCube_Research/Scripts/AGN_Core")

projfolder = '/home/brelethford/Documents/IceCube_Research/'
datafolder = '/data/user/brelethford/Data/'

filename_plots = projfolder + 'Plots/AGNCore/Stacking/'

params = cache.load(datafolder + 'starburst/pickle/params.pickle')

## These params contain everything we should need to weight our sources. note, these declinations and RAs are in degrees, not radians or sins of either. ##
#I call S60m 'flux' here in order to keep all the things that reference 'flux' the same.

src_ra, src_dec, redshift, flux = params['ra'], params['dec'], params[
    'z'], params['S60m']

#We must switch these to radians in order to correctly calculate background scrambles.
src_dec = np.radians(src_dec)
src_ra = np.radians(src_ra)

## There are three modelweights I can use, so lets put them in a dictionary for easy access. ##
###Note: for this check there's no reason to check any weight except flux. I'll keep the options open though just in case I want to look at it later.
modelweights = {'flux': flux, 'redshift': list(np.power(redshift, -2))}
Пример #14
0
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import scipy as sp
import os
import sys
from icecube.umdtools import cache, misc
from scipy import optimize as opt
from icecube import icetray, dataclasses, histlite, astro
###This script imports the pickled data from stefan, as well as my data with correct and incorrect pull correction.###

datafolder = '/data/user/brelethford/Data/AGN_Core_Sample/pickle/'
stefanfolder = '/home/brelethford/Documents/IceCube_Research/Scripts/AGN_Core/stefan_c/stefan_data/'

ben_exp = cache.load (datafolder + 'exp.pickle')
ben_mc = cache.load (datafolder + 'MC.pickle')

bad_exp = cache.load (datafolder + 'exp_bad_sigma.pickle')
bad_mc = cache.load (datafolder + 'MC_bad_sigma.pickle')

stefan_exp = np.genfromtxt(stefanfolder+'IC86-I_data.txt',names=True)
stefan_mc = np.genfromtxt(stefanfolder+'IC86-I_MC.txt',names=True)

#extract the sigmas

ben_exp_sigma =ben_exp['sigma']
ben_mc_sigma =ben_mc['sigma']

ben_hist_exp = histlite.hist(ben_exp_sigma,bins=100,log=True)
ben_hist_mc = histlite.hist(ben_mc_sigma,bins=100,log=True)
Пример #15
0
flux1_cut,mu1_cut = plotSensitivity( '/data/user/brelethford/Output/stacking_sensitivity/SwiftBAT70m_mc_cut/onesource/')
flux2_cut,mu2_cut = plotSensitivity( '/data/user/brelethford/Output/stacking_sensitivity/SwiftBAT70m_mc_cut/twosource/')

print ('stacked n_inj = ')
print (mu_stack,flux_stack)

print ('stacked cut n_inj = ')
print (mu_stack_cut,flux_stack_cut)

print ('One Source n_inj = ')
print (mu1,flux1)

print ('Two Source n_inj = ')
print (mu2,flux2)


print ('One Source Cut n_inj = ')
print (mu1_cut,flux1_cut)

print ('Two Source Cut n_inj = ')
print (mu2_cut,flux2_cut)

params = cache.load ( '/data/user/brelethford/Data/SwiftBAT70m/pickle/params.pickle' )

print ( 'First ten sources in catalog: ')
print (params['dec'][0:10])

print ('check if I can staple params together:')
print (params['dec'][0:1]+params['dec'][5:8])

Пример #16
0
def initMC_3yr_no40():
    mc59 = cache.load(filename_pickle + "IC59/mc.pickle")
    mc79 = cache.load(filename_pickle + "IC79/mc.pickle")
    mc86I = cache.load(filename_pickle + "IC86I/mc.pickle")
    MC = {0: mc59, 1: mc79, 2: mc86I}
    return MC
Пример #17
0
    dest='sky',
    type=str,
    default=None,
    metavar='SKY',
    help='tells which sources to use (and which folders to reference)')

opts, args = parser.parse_args()
Gamma = 2

sky = opts.sky

if sky == None:
    raise NameError('Error - did not establish which part of the sky to test.')

#The sources are all going to be loaded in - what changes is which ones I'll use.
params = cache.load(datafolder + 'SwiftBAT70m/pickle/params.pickle')

###Now I'll read in the background TS stuff.###
datafolder = '/data/user/brelethford/Output/stacking_sensitivity/SwiftBAT70m/northsouth/{}/background_trials/'.format(
    sky)

bckg_trials = [
    cache.load(datafolder + file) for file in os.listdir(datafolder)
    if file.endswith('.array')
]

## These params contain everything we should need to weight our sources. Remember to convert src_dec to sindec ##
if sky == 'onenorth':
    src_ra, src_dec, redshift, flux = [params['ra'][2]], [params['dec'][2]], [
        params['redshift'][2]
    ], [params['flux'][2]]
Пример #18
0
parser.add_option('--n',
                  dest='n',
                  type=int,
                  default=4,
                  metavar='N',
                  help='Number of years of data')

opts, args = parser.parse_args()
Gamma = opts.gamma

llhweight = opts.llhweight
injweight = opts.injweight
n = opts.n

params = cache.load(datafolder + '4yr_Starburst/pickle/degparams.pickle')

###Now I'll read in the background TS stuff.###
datafolder = '/data/user/brelethford/Output/stacking_sensitivity/4yr_Starburst/{0}yr/{1}_mhuber_git/background_trials/'.format(
    str(n), llhweight)

files = [
    cache.load(datafolder + file) for file in os.listdir(datafolder)
    if file.endswith('.array')
]
#We only need to get the appropriate chi_fit such that we can get a TSval for weighted sensitivity fcn.

fitfun = delta_chi2

TS = []
Пример #19
0
               help="Catalog used in stacking (default=None)")
p.add_argument(
    "--weight",
    default='equal',
    type=str,
    help=
    "Optional argument for determining the likelihood model weighting scheme.")

args = p.parse_args()
cat = args.cat
batch = args.batch

## These params contain everything we should need to weight our sources. I've made sure the dec and ra are in radians. ##
if cat:
    #Grab the right catalog.
    params = cache.load(
        '/data/user/brelethford/Data/{}/pickle/params.pickle'.format(cat))
    src_ra, src_dec = params['ra'], params['dec']
    try:
        src_ext = params['ext']
    except:
        src_ext = np.zeros_like(src_dec)

else:
    src_ra, src_dec = np.radians(args.ra), np.arcsin(args.sindec)

if cat == 'SwiftBAT70m':
    weight = args.weight
    flux, redshift = params['flux'], params['redshift']
    modelweights = {
        'flux': np.array(flux),
        'redshift': np.array(list(np.power(redshift, -2))),
Пример #20
0
propsmall = mpl.font_manager.FontProperties(size='small')
propxsmall = mpl.font_manager.FontProperties(size='x-small')

#Livetimes (in days)
livetime_IC86I = 332.61
livetime_IC79 = 315.506
livetime_IC59 = 348.138

#Loading Zone#
projfolder = '/home/brelethford/Documents/IceCube_Research/'
datafolder = '/data/user/brelethford/Data/AGN_Core_Sample/'
filename_pickle = datafolder + 'pickle/MESE/'
plotfolder = '/data/user/brelethford/AGN_Core/Plots/data/'

#Those sigmas up there are w/o pull correction - the following is the fix.
mc = cache.load(filename_pickle + 'mc.pickle')
exp = cache.load(filename_pickle + 'exp.pickle')

#Adding in a few params from epinat's 3yr
muex_data = 10**(exp['logE'])
true = mc['trueE']
muex_sim = 10**(mc['logE'])
sindec_data = exp['sinDec']
sindec_sim = mc['sinDec']

sigma_data = exp['sigma']
sigma_sim = mc['sigma']

weight = mc['ow'] * true**(-2)

bins = 80
Пример #21
0
def initMC_40():
  mc = cache.load(filename_pickle+"sirin_IC40/mc.pickle")
  return mc
Пример #22
0
    x = np.linspace(0, 20, 100)
    ax.plot(x,
            chi2_fit.pdf(x),
            linestyle=':',
            color=color,
            label=r'$\tilde{\chi}^2$')  #: df='+str(round(chi2_fit.par[0],2)))
    plt.axvline(np.asscalar(chi2_fit.isf(0.5)), color=color)
#for chi2_fit, weib_fit, color in zip(chi_each, weib_each, colors):
#  ax.plot(x, weib_fit.pdf(x), linestyle='--', color=color, label = 'weibull')
#  plt.axvline(chi2_fit.isf(norm.sf(5)), color = color, linestyle = ':')
#  plt.axvline(weib_fit.isf(norm.sf(5)), color = color, linestyle = '--')

#Now we have to get the TS from the injected trials

inj_uniform = cache.load(
    '/data/user/brelethford/Output/stacking_sensitivity/SwiftBAT70m/bstacking_4yr/uniform/uniform_inj/sensitivity/gamma2.0.array'
)
inj_flux = cache.load(
    '/data/user/brelethford/Output/stacking_sensitivity/SwiftBAT70m/bstacking_4yr/flux/flux_inj/sensitivity/gamma2.0.array'
)
inj_redshift = cache.load(
    '/data/user/brelethford/Output/stacking_sensitivity/SwiftBAT70m/bstacking_4yr/redshift/redshift_inj/sensitivity/gamma2.0.array'
)


def getTSinj(data):
    TS = []
    for trial in data['trials']:
        TS.append(trial[1])
    return TS
Пример #23
0
def initMC_86I():
  mc = cache.load(filename_pickle+"sirin_IC86I/mc.pickle")

  return mc
Пример #24
0
    type=int,
    default=0,
    metavar='DISC',
    help='Toggles calculation of discovery potential instead of sensitivity.')

opts, args = parser.parse_args()
Gamma = opts.gamma
llhweight = opts.llhweight
injweight = opts.injweight
catalog = opts.catalog
disc = opts.disc

datafolder = '/data/user/coenders/data/MultiYearPointSource/npz'
catfolder = '/data/user/brelethford/stacktest/{}'.format(catalog)

params = cache.load(catfolder + '/pickle/params.pickle')

years = 1  #for now...

## These params contain everything we should need to weight our sources. I've made sure the dec and ra are in radians. ##
src_ra, src_dec = params['ra'], params['dec']


#get TS median, chi2 from background:
def getTSval():
    files = [
        cache.load(backfolder + file) for file in os.listdir(backfolder)
        if file.endswith('.array')
    ]
    fitfun = delta_chi2
    TS = []
Пример #25
0
        'redshift': redshift,
        'gamma': gamma,
        'flux': flux,
        'lum': lum
    }
    return params


params = cache.get(datafolder + 'SwiftBAT70m/pickle/params.pickle',
                   get_SwiftBAT_params)

###Now I'll read in the background TS stuff.###
datafolder = '/data/user/brelethford/Output/stacking_sensitivity/SwiftBAT70m/uniform/background_trials/'

files = [
    cache.load(datafolder + file) for file in os.listdir(datafolder)
    if file.endswith('.array')
]
n_inj = []
nsources = []
TS = []
beta = (0.5)  #For background ts
TS_beta = []  #Calculated from the total TS median after we get all the TS.
beta_err = []
gamma = []

for file in files:
    for item in range(len(file['n_inj'])):
        n_inj.append(file['n_inj'][item])
        nsources.append(file['nsources'][item])
        TS.append(file['TS'][item])
Пример #26
0
def plot_error(year):
    #The following currently devoted to making energy and angular error plots for a year of data.
    # init likelihood class
    if year == 40:
        llh = data_multi.init40(energy=True)
        mc = cache.load(filename_pickle + "IC40/mc.pickle")
        extra = cache.load(filename_pickle + "IC40/dpsi.pickle")
    if year == 59:
        llh = data_multi.init59(energy=True)
        mc = cache.load(filename_pickle + "IC59/mc.pickle")
        extra = cache.load(filename_pickle + "IC59/dpsi.pickle")
    if year == 79:
        llh = data_multi.init79(energy=True)
        mc = cache.load(filename_pickle + "IC79/mc.pickle")
        extra = cache.load(filename_pickle + "IC79/dpsi.pickle")
    elif year == 86:
        llh = data_multi.init86I(energy=True)
        mc = cache.load(filename_pickle + "IC86I/mc.pickle")
        extra = cache.load(filename_pickle + "IC86I/dpsi.pickle")
    dpsi = extra['dpsi']

    print(llh)

    # datatest
    #Currently don't need to remake these plots. but DONT DELETE

    colors = ['b', 'g', 'y', 'r']
    gamma = np.linspace(1., 2.7, 4)

    # fig_energy, (ax1, ax2) = plt.subplots(ncols=2)
    # ax1.hist([llh.exp["logE"]] + [mc["logE"] for i in gamma],
    #          weights=[np.ones(len(llh.exp))]
    #                   + [mc["ow"] * mc["trueE"]**(-g) for g in gamma],
    #          label=["Pseudo-Data"] + [r"$\gamma={0:.1f}$".format(g) for g in gamma], color= ['k'] + [colors[g] for g in range(len(gamma))],
    #          histtype="step", bins=100, log=True, normed=True, cumulative=-1)
    # ax1.legend(loc="best")
    # ax1.set_title("Reconstructed Energy - IC{}".format(str(year)))
    # ax1.set_xlabel("logE")
    # ax1.set_ylabel("Relative Abundance")
    # ax1.hist([llh.exp["logE"]] + [mc["logE"] for i in gamma],
    #          weights=[np.ones(len(llh.exp))]
    #                   + [mc["ow"] * mc["trueE"]**(-g) for g in gamma],
    #          label=["Data"] + [r"$\gamma={0:.1f}$".format(g) for g in gamma], color= ['k'] + [colors[g] for g in range(len(gamma))],
    #          histtype="step", bins=100, log=True, normed=True, cumulative=-1)
    # ax2.set_title("Zoomed In")
    # ax2.set_xlabel("logE")
    # ax2.set_xlim(4,10)
    # ax2.set_ylim(1e-5,1)
    # ax2.hist([llh.exp["logE"]] + [mc["logE"] for i in gamma],
    #          weights=[np.ones(len(llh.exp))]
    #                   + [mc["ow"] * mc["trueE"]**(-g) for g in gamma],
    #          label=["Pseudo-Data"] + [r"$\gamma={0:.1f}$".format(g) for g in gamma], color= ['k'] + [colors[g] for g in range(len(gamma))],
    #          histtype="step", bins=100, log=True, normed=True, cumulative=-1)
    # fig_energy.savefig(filename_plots + 'energy_hists_IC{}.pdf'.format(str(year)))

    fig_angular_error, (ax1, ax2) = plt.subplots(ncols=2, figsize=(10, 5))
    dec = np.arcsin(mc["sinDec"])
    angdist = np.degrees(dpsi)

    ax1.hist([np.log10(np.degrees(mc["sigma"])) for i in gamma],
             label=[r"$\sigma$ - $\gamma={0:.1f}$".format(g) for g in gamma],
             linestyle='dashed',
             weights=[mc["ow"] * mc["trueE"]**(-g) for g in gamma],
             color=[colors[g] for g in range(len(gamma))],
             histtype="step",
             bins=100,
             normed=True)

    ax1.hist(
        [np.log10(angdist) for i in gamma],
        label=[r"$\Delta \psi$ - $\gamma={0:.1f}$".format(g) for g in gamma],
        weights=[mc["ow"] * mc["trueE"]**(-g) for g in gamma],
        linestyle='solid',
        color=[colors[g] for g in range(len(gamma))],
        histtype="step",
        bins=100,
        normed=True)
    ax1.set_title("Reco MC Angular Error Check - IC{}".format(str(year)))
    ax1.set_xlabel(r"log$\sigma_{ang}$ (degrees)")
    ax1.set_ylabel("Relative Abundance")
    ax1.set_ylim(0, 1.5)

    ax2.hist([(np.degrees(mc["sigma"])) for i in gamma],
             label=[r"$\sigma$ - $\gamma={0:.1f}$".format(g) for g in gamma],
             linestyle='dashed',
             weights=[mc["ow"] * mc["trueE"]**(-g) for g in gamma],
             color=[colors[g] for g in range(len(gamma))],
             histtype="step",
             bins=1000,
             normed=True)

    ax2.hist(
        [(angdist) for i in gamma],
        label=[r"$\Delta \psi$ - $\gamma={0:.1f}$".format(g) for g in gamma],
        weights=[mc["ow"] * mc["trueE"]**(-g) for g in gamma],
        linestyle='solid',
        color=[colors[g] for g in range(len(gamma))],
        histtype="step",
        bins=1000,
        normed=True)
    ax2.legend(loc="upper right")
    ax2.set_xlim(0, 5)
    ax2.set_ylim(0, 3.5)
    ax2.set_xlabel(r"$\sigma_{ang}$ (degrees)")
    fig_angular_error.savefig(filename_plots +
                              'angular_error_hists_IC{}.pdf'.format(str(year)))
Пример #27
0
w = 4
propsmall = mpl.font_manager.FontProperties(size='small')
propxsmall = mpl.font_manager.FontProperties(size='x-small')

#Livetimes (in days)
livetime_IC86I = 332.61
livetime_IC79 = 315.506
livetime_IC59 = 348.138

#Loading Zone#
projfolder = '/home/brelethford/Documents/IceCube_Research/'
datafolder = '/data/user/brelethford/Data/AGN_Core_Sample/'
filename_pickle = datafolder + 'pickle/'
plotfolder = '/data/user/brelethford/AGN_Core/Plots/data/'

ra86I_sim, sindec86I_sim, ra86I_data, sindec86I_data, ra86I_true, sindec86I_true, energy86I_true, muex86I_sim, muex86I_data, sigma86I_sim, sigma86I_data, OneWeight_IC86I, dpsi_IC86I = cache.load(
    filename_pickle + "IC86I/coords.pickle")

ra79_sim, sindec79_sim, ra79_data, sindec79_data, ra79_true, sindec79_true, energy79_true, muex79_sim, muex79_data, sigma79_sim, sigma79_data, OneWeight_IC79, dpsi_IC79 = cache.load(
    filename_pickle + "IC79/coords.pickle")

nch79_sim, nch79_data = cache.load(filename_pickle + "IC79/NCh.pickle")

ra59_sim, sindec59_sim, ra59_data, sindec59_data, ra59_true, sindec59_true, energy59_true, mue59_sim, mue59_data, sigma59_sim, sigma59_data, OneWeight_IC59, dpsi_IC59 = cache.load(
    filename_pickle + "IC59/coords.pickle")

nch59_sim, nch59_data = cache.load(filename_pickle + "IC59/NCh.pickle")

ra40_sim, sindec40_sim, ra40_data, sindec40_data, ra40_true, sindec40_true, energy40_true, mue40_sim, mue40_data, sigma40_sim, sigma40_data, OneWeight_IC40, dpsi_IC40 = cache.load(
    filename_pickle + "IC40/coords.pickle")

nch40_sim, nch40_data = cache.load(filename_pickle + "IC40/NCh.pickle")
Пример #28
0
def printflux(datafolder):
    files = cache.load(datafolder + 'gamma2.0.array')
    flux = files['flux']
    mu = files['mu']
    TSval = files['TSval']
    return (flux, mu, TSval)
Пример #29
0
                  metavar='YEARS',
                  help='Number of years of data')

parser.add_option(
    '--longrun',
    dest='longrun',
    default=False,
    action='store_true',
    help='Allows longer runtime for sensitivity calculation (>12 hours)')

opts, args = parser.parse_args()
Gamma = opts.gamma
years = opts.years
llhweight = opts.llhweight

params = cache.load(datafolder + '2LAC/pickle/params.pickle')

###Now I'll read in the background TS stuff.###
datafolder = '/data/user/brelethford/Output/stacking_sensitivity/2LAC/flux_{0}yr/background_trials/'.format(
    str(years))

files = [
    cache.load(datafolder + file) for file in os.listdir(datafolder)
    if file.endswith('.array')
]
n_inj = []
nsources = []
TS = []
beta = (0.5)  #For background ts
TS_beta = []  #Calculated from the total TS median after we get all the TS.
beta_err = []
def plot_ratio(year):
    #The following currently devoted to making energy and angular error plots for a year of data.
    # init likelihood class
    if year == 40:
        mc = cache.load(filename_pickle + "sirin_IC40/mc.pickle")
        extra = cache.load(filename_pickle + "sirin_IC40/dpsi.pickle")
    if year == 59:
        mc = cache.load(filename_pickle + "sirin_IC59/mc.pickle")
        extra = cache.load(filename_pickle + "sirin_IC59/dpsi.pickle")
    if year == 79:
        mc = cache.load(filename_pickle + "sirin_IC79/mc.pickle")
        extra = cache.load(filename_pickle + "sirin_IC79/dpsi.pickle")
    elif year == 86:
        mc = cache.load(filename_pickle + "sirin_IC86I/mc.pickle")
        extra = cache.load(filename_pickle + "sirin_IC86I/dpsi.pickle")
    dpsi = extra['dpsi']

    # datatest
    #Currently don't need to remake these plots. but DONT DELETE

    colors = ['b', 'g', 'y', 'r']
    gamma = np.linspace(1., 2.7, 4)

    # fig_energy, (ax1, ax2) = plt.subplots(ncols=2)
    # ax1.hist([llh.exp["logE"]] + [mc["logE"] for i in gamma],
    #          weights=[np.ones(len(llh.exp))]
    #                   + [mc["ow"] * mc["trueE"]**(-g) for g in gamma],
    #          label=["Pseudo-Data"] + [r"$\gamma={0:.1f}$".format(g) for g in gamma], color= ['k'] + [colors[g] for g in range(len(gamma))],
    #          histtype="step", bins=100, log=True, normed=True, cumulative=-1)
    # ax1.legend(loc="best")
    # ax1.set_title("Reconstructed Energy - IC{}".format(str(year)))
    # ax1.set_xlabel("logE")
    # ax1.set_ylabel("Relative Abundance")
    # ax1.hist([llh.exp["logE"]] + [mc["logE"] for i in gamma],
    #          weights=[np.ones(len(llh.exp))]
    #                   + [mc["ow"] * mc["trueE"]**(-g) for g in gamma],
    #          label=["Data"] + [r"$\gamma={0:.1f}$".format(g) for g in gamma], color= ['k'] + [colors[g] for g in range(len(gamma))],
    #          histtype="step", bins=100, log=True, normed=True, cumulative=-1)
    # ax2.set_title("Zoomed In")
    # ax2.set_xlabel("logE")
    # ax2.set_xlim(4,10)
    # ax2.set_ylim(1e-5,1)
    # ax2.hist([llh.exp["logE"]] + [mc["logE"] for i in gamma],
    #          weights=[np.ones(len(llh.exp))]
    #                   + [mc["ow"] * mc["trueE"]**(-g) for g in gamma],
    #          label=["Pseudo-Data"] + [r"$\gamma={0:.1f}$".format(g) for g in gamma], color= ['k'] + [colors[g] for g in range(len(gamma))],
    #          histtype="step", bins=100, log=True, normed=True, cumulative=-1)
    # fig_energy.savefig(filename_plots + 'energy_hists_IC{}.pdf'.format(str(year)))

    fig_ratio, (ax1, ax2) = plt.subplots(ncols=2, figsize=(10, 5))
    dec = np.arcsin(mc["sinDec"])
    angdist = np.degrees(dpsi)

    ax1.hist([np.log10(np.degrees(mc["sigma"]) / (angdist)) for i in gamma],
             label=[
                 r"$\Delta \psi / \sigma$ - $\gamma={0:.1f}$".format(g)
                 for g in gamma
             ],
             linestyle='solid',
             weights=[mc["ow"] * mc["trueE"]**(-g) for g in gamma],
             color=[colors[g] for g in range(len(gamma))],
             histtype="step",
             bins=100,
             normed=True)

    medians = [
        misc.weighted_median(np.log10(np.degrees(mc["sigma"]) / (angdist)),
                             mc["ow"] * mc["trueE"]**(-g)) for g in gamma
    ]

    for g in range(len(gamma)):
        ax1.axvline(medians[g], color=colors[g], alpha=0.3)

    ax1.set_title(r"Reco MC $\Delta \psi / \sigma$ Check - IC{}".format(
        str(year)))
    ax1.set_xlabel(r"log$\Delta \psi / \sigma_{ang}$")
    ax1.set_ylabel("Relative Abundance")
    ax1.set_ylim(0, 1.5)
    ax1.set_xlim(-2.5, 2.5)
    ax1.axvline(x=0, color='k')
    ax1.axvline(x=np.log10(1.1774), color='k')
    ax2.set_xlim(-5, 5)

    ax2.hist([(np.degrees(mc["sigma"])) / (angdist) for i in gamma],
             label=[
                 r"$\Delta \psi / \sigma$ - $\gamma={0:.1f}$".format(g)
                 for g in gamma
             ],
             linestyle='solid',
             weights=[mc["ow"] * mc["trueE"]**(-g) for g in gamma],
             color=[colors[g] for g in range(len(gamma))],
             histtype="step",
             bins=1000,
             range=(0, 5),
             normed=True)

    ax2.legend(loc="upper right")
    ax2.set_xlim(0, 5)
    ax2.set_ylim(0, 3.5)
    ax2.set_xlabel(r"$\Delta \psi / \sigma_{ang}$")
    fig_ratio.savefig(filename_plots +
                      'dpsi_sigma_ratio_IC{}_sirin.pdf'.format(str(year)))