def __init__(self): self.f_name = gen_filename( config["datapath"] + "/expected_fluxes_reco/", "expected_flux.dat", SterileParams()) self.use_mc = False _generic_LLHMachine.__init__(self, SterileParams(), use_syst=True, flatten=True)
def __init__(self, expectation=SterileParams(), use_syst=True, flatten=False, smearmode=False, special_mode=False): if not isinstance(expectation, SterileParams): raise TypeError("Expected {}, got {}".format( SterileParams, type(expectation))) if not isinstance(use_syst, bool): raise TypeError("Expected {}, got {}".format(bool, type(use_syst))) if not isinstance(flatten, bool): raise TypeError("Expected {}, got {}".format(bool, type(flatten))) self._use_systematics = use_syst self._flatten = flatten self._smearmode = smearmode if not os.path.exists(self.f_name): print("Generating binned event rate at {}".format(expectation)) make_meta_flux(expectation, self.use_mc, smearmode) if special_mode: print("Likelihooder made in special mode!") # the angle edges weren't saved right for some of the expected rates # so we manually put it in # but we also only want to go over (-1 -> 0.2) since we don't account for the backgrounds that would appear at south-sky angles self._special = special_mode self.a_edges = np.linspace(-1, 1, 11) #[:7] self._lt_scale = 1.0 #2.0 self._stat_scale = sqrt(self._lt_scale) self._configure() print("Likelihood machine built with expectation at {}".format( self.f_name))
def __init__(self, *args): for arg in args: if not isinstance(arg, doLLH): raise TypeError() self.doLLHs = list(args) self._meta_skip = all(entry.skip_missing for entry in self.doLLHs) self._options = [part.options for part in self.doLLHs] self._skipped = 0 self._done = 0 # get the edges fn = gen_filename( data_folder, self.doLLHs[-1]._filenames, SterileParams() ) #just use the null for this, we're only looking at the bin edges obj = open(fn, 'rb') data = pickle.load(obj) obj.close() self._e_edges = data["e_edges"] n_e = len(self._e_edges) - 1 self._a_edges = data["a_edges"] n_a = len(self._a_edges) - 1 self._reco_obj = DataReco(self._e_edges * (1e9), self._a_edges, self._e_edges * (1e9), self._a_edges) self._reco_tensor = [[[[ self._reco_obj.get_energy_reco_odds(j, l) * self._reco_obj.get_czenith_reco_odds(k, i, l) for i in range(n_a) ] for j in range(n_e)] for k in range(n_a)] for l in range(n_e)]
def reload_null(self): """ This function reloads the null flux """ sp = SterileParams(0., 0., 0., 0.) if self.ui.recoBox.isChecked(): which = config["recon_flux"] + ".dat" else: which = config["nu_flux_downsize"] + ".dat" f = open(gen_filename(config["datapath"], which, sp), 'rb') all_data = pickle.load(f) f.close() if self.ui.recoBox.isChecked(): self.e_reco = np.array(bhist([all_data["e_reco"]]).centers) self.a_reco = np.array(bhist([all_data["a_reco"]]).centers) else: self.e_reco = np.array(all_data["e_true"]) self.a_reco = np.array(all_data["a_true"]) all_data = all_data["flux"] self.flux_null = np.zeros(shape=(len(self.e_reco), len(self.a_reco))) for key in all_data.keys(): if self.check_key(key): self.flux_null += np.array( all_data[key]) if self.ui.recoBox.isChecked( ) else self.apply_xs(np.array(all_data[key]), key)
def astro_norm_unc(use_mc=False, smearmode=False, special=False): """ Calculates the expected astrophysical neutrino spectrum, then returns the expected gains/losses in each bin by perturbing the overall spectram index (dgamma) and normalization (dnorm) down/up Returns a tuple containing np.ndarrays The first is the event change from a negative perturbation The second is the event change from a positive perturbation """ null = SterileParams() norm_p = 0.21 shift_p = 0.19 # unperturbed = generate_astr_flux(null) prefix = "astr_perturb" + ("_frommc" if use_mc else "") prefix += ("_smear" if smearmode else "") if special: prefix += "_smearedwell" # for each of these... # generate the flux # load it in as a data object # parse it through the effective area integrator # yay now we have fluxes in reconstruction space! if special: flux_func = lambda *objs: build_flux_sad(*objs, good_angles=True) else: if smearmode: flux_func = build_flux_sad else: flux_func = build_mc_flux if use_mc else build_flux filename = os.path.join(perturb_folder, prefix + "_central.dat") if os.path.exists(filename): central = pickle_load(filename) else: central = flux_func(generate_astr_flux(null, as_data=True)) pickle_save(central, filename) filename = os.path.join(perturb_folder, prefix + "_norm_minus.dat") if os.path.exists(filename): norm_minus = pickle_load(filename) else: norm_minus = flux_func( generate_astr_flux(null, norm=-1 * norm_p, as_data=True)) pickle_save(norm_minus, filename) filename = os.path.join(perturb_folder, prefix + "_norm_plus.dat") if os.path.exists(filename): norm_plus = pickle_load(filename) else: norm_plus = flux_func( generate_astr_flux(null, norm=norm_p, as_data=True)) pickle_save(norm_plus, filename) return _flipper(central["event_rate"], (norm_minus["event_rate"], norm_plus["event_rate"]))
def __init__(self, expectation=SterileParams(), use_syst=True, flatten=False): self.f_name = gen_filename( config["datapath"] + "/expected_fluxes_reco/", "expected_flux_from_mc.dat", expectation) self.use_mc = True _generic_LLHMachine.__init__(self, expectation, use_syst, flatten)
def astro_shift_unc(use_mc=False, smearmode=False, special=False, shift_p=0.19): null = SterileParams() norm_p = 0.21 # unperturbed = generate_astr_flux(null) prefix = "astr_perturb" + ("_frommc" if use_mc else "") if smearmode: prefix += "_smear" if special: prefix += "_smearedwell" flux_func = build_mc_flux if use_mc else build_flux if special: flux_func = lambda *objs: build_flux_sad(*objs, good_angles=True) elif smearmode: flux_func = build_flux_sad # for each of these... # generate the flux # load it in as a data object # parse it through the effective area integrator # now we have fluxes in reconstruction space! filename = os.path.join(perturb_folder, prefix + "_central.dat") if os.path.exists(filename): central = pickle_load(filename) else: central = flux_func(generate_astr_flux(null, as_data=True)) pickle_save(central, filename) filename = os.path.join(perturb_folder, prefix + "_gamma_minus.dat") if os.path.exists(filename): norm_minus = pickle_load(filename) else: norm_minus = flux_func( generate_astr_flux(null, dgamma=-1 * shift_p, as_data=True)) pickle_save(norm_minus, filename) filename = os.path.join(perturb_folder, prefix + "_gamma_plus.dat") if os.path.exists(filename): norm_plus = pickle_load(filename) else: norm_plus = flux_func( generate_astr_flux(null, dgamma=shift_p, as_data=True)) pickle_save(norm_plus, filename) return _flipper(central["event_rate"], (norm_minus["event_rate"], norm_plus["event_rate"]))
def load(null_bool): filename = "null_exp.dat" if null_bool else "ster_exp.dat" if False: #os.path.exists(filename): f = open(filename,'rb') data = pickle.load(f) f.close() return data else: if null_bool: params = SterileParams() else: params = SterileParams(0.0, 0.1609, 0.0, 4.7) # load the fluxes fu_filename = gen_filename(config["datapath"], "raw_det_flux.dat", params) flux = Data(fu_filename) data = build_mc_flux(flux) f = open(filename, 'wb') pickle.dump(data, f, -1) f.close() return data
def get_interp_flux(self): """ This creates the interpolated flux by accessing the currently set angles, finding the four neighboring fluxes, and then performing a bilinear interpolation """ # this gets the indices of the two mixing angle values neighboring the intermediate one we hav enow i_x1, i_x2 = get_loc(self.electron_angle, self.theta03s) i_y1, i_y2 = get_loc(self.tau_angle, self.theta23s) # now let's build the parameter objects using those neighboring points we have param_11 = SterileParams(self.theta03s[i_x1], self.thetamu, self.theta23s[i_y1], self.msq) param_12 = SterileParams(self.theta03s[i_x1], self.thetamu, self.theta23s[i_y2], self.msq) param_21 = SterileParams(self.theta03s[i_x2], self.thetamu, self.theta23s[i_y1], self.msq) param_22 = SterileParams(self.theta03s[i_x2], self.thetamu, self.theta23s[i_y2], self.msq) which = (config["recon_flux"] if self.ui.recoBox.isChecked() else config["nu_flux_downsize"]) + ".dat" # using those indices, we generate the names of the flux files and load flux_11 = self._load_flux_file( gen_filename(config["datapath"], which, param_11)) flux_12 = self._load_flux_file( gen_filename(config["datapath"], which, param_12)) flux_21 = self._load_flux_file( gen_filename(config["datapath"], which, param_21)) flux_22 = self._load_flux_file( gen_filename(config["datapath"], which, param_22)) # these are useful intermediates used for my bilinear interpolation function p0 = (self.electron_angle, self.tau_angle) p1 = (self.theta03s[i_x1], self.theta23s[i_y1]) p2 = (self.theta03s[i_x2], self.theta23s[i_y2]) return bilinear_interp(p0, p1, p2, flux_11, flux_12, flux_21, flux_22)
def update_plot(self): self.update_labels() null = SterileParams() this_s = SterileParams(theta13=self.muon_a, theta23=self.tau_a, msq2=self.msq) null_dat = self.load(null) ster_dat = self.load(this_s) self.ui.figure.clear() ax = self.ui.figure.add_subplot(111) pmesh = ax.pcolormesh(self.an, self.en, ster_dat["event_rate"]/null_dat["event_rate"], vmin=1.0-self.width, vmax=1.0+self.width, cmap="coolwarm") ax.set_yscale('log') ax.set_ylim([1e2,1e6]) ax.set_xlim([-1,0.2]) self.cbar = self.ui.figure.colorbar(pmesh, ax=ax) self.cbar.set_label("Difference") plt.vlines(self.core_b,ymin=10**2, ymax=10**6, colors="white", ls="-") plt.vlines(self.mantle_b,ymin=10**2, ymax=10**6, colors="white", ls="--") self.ui.canvas.draw()
def __init__(self, expectation=SterileParams(), use_syst=True, flatten=False, smearmode=False, special=False): suffix = "_smeared" if smearmode else "" suffix = "_smearedwell" if special else "" self.f_name = gen_filename( config["datapath"] + "/expected_fluxes_reco/", "expected_flux{}.dat".format(suffix), expectation) self.use_mc = False _generic_LLHMachine.__init__(self, expectation, use_syst, flatten, smearmode, special)
def __init__(self, parent=None): QWidget.__init__(self, parent) # set up the UI self.ui = base_gui() self.ui.setupUi(self) self.folder = "/home/bsmithers/software/data/hg_sib/expected_fluxes_reco" self.filenames = "expected_flux_smearedwell.dat" # whenever the sliders value change, we update the plots # may want to change this to (mouse released) if this takes a while self.ui.tau_slider.valueChanged.connect(self.update_plot) self.ui.muon_slider.valueChanged.connect(self.update_plot) self.ui.msq_slider.valueChanged.connect(self.update_plot) self.ui.width_slider.valueChanged.connect(self.update_width) self.core_b = -0.98 self.mantle_b = -0.83 self.tau_a = 0.0 self.muon_a = 0.0 self.msq = 0.0 # copied from the make_dag python script # this just ensures that the names are all right n_grid = 90 self.theta13s = app_zero(np.arcsin(np.sqrt(np.logspace(-3,0, n_grid)))/2) self.theta23s = app_zero(np.arcsin(np.sqrt(np.logspace(-3,0, n_grid)))/2) self.msqs = app_zero(np.logspace(-2,2,40)) self._n_fluxes = len(self.theta13s)*len(self.msqs)*len(self.theta23s) # load the null flux! null_dict = self.load(SterileParams()) self.en = null_dict["e_edges"] self.an = np.linspace(-1,1,11) self.width = 0.50 self.update_plot()
th14s = np.arcsin(np.sqrt(np.logspace(-3, 0, n_th)))/2.0 th14s = np.concatenate((np.array([0]) , th14s)) if n_th==1: th14s = th14s[:1] print(th14s) th24 = float(sys.argv[1]) th34 = float(sys.argv[2]) msq = float(sys.argv[3]) mc_mode = int(sys.argv[4])==1 # msq = 1.0 for th14 in th14s: pm = SterileParams(theta03=th14, theta13=th24, theta23=th34, msq2=msq) make_meta_flux( pm, do_mc=mc_mode) else: # n_m = 1 n_m = 40 msqs = np.concatenate(( np.array([0.0]), np.logspace(-2,2,n_m) )) if n_m==1: msqs=msqs[:1] th24 = float(sys.argv[1]) th34 = float(sys.argv[2]) if len(sys.argv)==4: mc_mode = int(sys.argv[3])==1 else:
import nuSQUIDSpy as nsq import nuSQUIDSpy as nsq from cascade.raw_fluxes import raw_flux import os import numpy as np from matplotlib import pyplot as plt import pickle plt.style.use( os.path.join(os.path.dirname(__file__), "..", "..", "cascade.mplstyle")) bestMode = False if bestMode: params = SterileParams(theta03=0.3555, theta13=0.1609, theta23=0.05, msq2=3.3) else: params = SterileParams(theta13=0.1609, theta23=0.2245, msq2=4.5) #params=SterileParams(theta13=0.1609, theta23=0.0, msq2=4.64) #params= SterileParams() colorscale = 'PuBu' def state_setter(energies, zeniths, n_nu, kwargs): """ This function prepares our initial flux. We set all the muon ones so we can easily extract P(nu_mu -> nu_? ) P(nu_mu_bar -> nu_?_bar )
""" Defines some stuff to do the likelihood calculations """ import pickle import numpy as np import os from scipy.optimize import minimize from cascade.utils import get_closest, SterileParams, gen_filename, config, Data from cascade.sensitivity.eff_area_reader import build_flux null = SterileParams() #null_flux = Data(gen_filename(config["datapath"], config["nu_flux"]+".dat", null)) null_flux = "" from cascade.sensitivity.systematic_unc import astro_norm_unc from cascade.sensitivity.systematic_unc import astro_shift_unc, cr_perturb from cascade.sensitivity.systematic_unc import ice_grad_0, ice_grad_1 from cascade.sensitivity.generate_all_integrated_fluxes import make_meta_flux from cascade.sensitivity.load_expectation import load as loade from math import sqrt, pi, exp, log from math import lgamma twopi = sqrt(2 / pi) def llh_func(exp, cts, sigma):
add_contour("/home/bsmithers/software/data/hg_sib/0.1609e0/best_llh_1_00eV_smearing_0.0_0.1609e0_0.0_1.0000e0.dat", r"1.0eV$^{2}$, $\theta_{24}=0.1609$", '-') add_contour("/home/bsmithers/software/data/hg_sib/0.1609e0/best_llh_3_30eV_smearing_0.0_0.1609e0_0.0_3.3000e0.dat", r"3.3eV$^{2}$, $\theta_{24}=0.1609$", '-') add_contour("/home/bsmithers/software/data/hg_sib/0.1609e0/best_llh_4_64eV_smearing_0.0_0.1609e0_0.0_4.6400e0.dat", r"4.64eV$^{2}$, $\theta_{24}=0.1609$", '-') add_contour("/home/bsmithers/software/data/hg_sib/0.3826e0/best_llh_1_00eV_smearing_0.0_0.3826e0_0.0_1.0000e0.dat", r"1.0eV$^{2}$, $\theta_{24}=0.3826$", '--') add_contour("/home/bsmithers/software/data/hg_sib/0.3826e0/best_llh_3_30eV_smearing_0.0_0.3826e0_0.0_3.3000e0.dat", r"3.3eV$^{2}$, $\theta_{24}=0.3826$", '--') add_contour("/home/bsmithers/software/data/hg_sib/0.3826e0/best_llh_4_64eV_smearing_0.0_0.3826e0_0.0_4.6400e0.dat", r"4.64eV$^{2}$, $\theta_{24}=0.3826$", '--') """ msqs = [1.0, 3.3, 4.64] th24s = [0.1609, 3.826] th34s = [0.0] thetas = np.concatenate(([0], np.arcsin(np.sqrt(np.logspace(-3, 0, 90))) / 2)) systematics = True smearing = True central = SterileParams() options = { "is_mc": False, "use_syst": systematics, "skip_missing": True, "smear": smearing } mc_options = { "is_mc": True, "use_syst": systematics, "skip_missing": True, "smear": False } llhood = doLLH("best_expected_flux.dat", central_exp=central, options=options)
import matplotlib matplotlib.use('Qt5Agg') import matplotlib.pyplot as plt plt.style.use(os.path.join(os.path.dirname(__file__), "..", ".." , "cascade.mplstyle")) interp = True #f = open("../cummulative_probs.dat",'rb') #f = open("/home/benito/software/data/cascade/hg_sib//expectations/0.0/scaled_cummulative_probsnonorm_special_nosys_0.0_0.0_0.0_0.0.dat",'rb') #f = open("/home/benito/software/data/cascade/hg_sib//expectations/0.0/scaled_cummulative_probsnonorm_special_0.0_0.0_0.0_0.0.dat",'rb') #/home/benito/software/data/cascade/hg_sib/0.0/newSense_result_float_0.0_0.0_0.0_0.0.dat # /home/benito/software/data/cascade/hg_sib/0.0/joint_likelihood_nosys_0.0_0.0_0.0_0.0.dat <- no sys fname = gen_filename(config["datapath"], "joint_likelihood_smearing.dat" , SterileParams(theta13=0.1652, theta23=0.2293, msq2=4.6416)) f = open(fname, 'rb') obj = pickle.load(f) f.close() theta24s = obj["theta24s"] theta34s = obj["theta34s"] msqs = obj["msqs"] chi2 = np.array(obj["chi2s"]) deg = 180./3.1415926 ps = [0.10] #, 0.01]
def __init__(self, filenames, central_exp=SterileParams(), options={}): self._is_mc = False self._flatten = False self._upgoing = True self._skip_missing = False self._use_syst = True self._fix_norm = -1 self._fixing_norm = False self._use_sideband_err = False self._smear = False if not isinstance(filenames, str): raise TypeError("Filename should be {}, not {}".format( str, type(filenames))) self._filenames = filenames self._parse_options(options) self._options = options if self._smear: # get the edges fn = gen_filename(data_folder, self._filenames, central_exp) obj = open(fn, 'rb') data = pickle.load(obj) obj.close() self._e_edges = data["e_edges"] n_e = len(self._e_edges) - 1 self._a_edges = data["a_edges"] n_a = len(self._a_edges) - 1 self._reco_obj = DataReco(self._e_edges * (1e9), self._a_edges, self._e_edges * (1e9), self._a_edges) self._reco_tensor = [[[[ self._reco_obj.get_energy_reco_odds(j, l) * self._reco_obj.get_czenith_reco_odds(k, i, l) for i in range(n_a) ] for j in range(n_e)] for k in range(n_a)] for l in range(n_e)] # do the initial configuration self.set_central(central_exp) self._net_error_m_sys = np.zeros( shape=np.shape(self._net_error_m_stat)) self._net_error_p_sys = np.zeros( shape=np.shape(self._net_error_p_stat)) if self._use_syst: fn = gen_filename(data_folder, self._filenames, central_exp) f = open(fn, 'rb') expectation = pickle.load(f) f.close() ice_grad_0 = unc_wrapper(expectation, Syst.icegrad0, options) ice_grad_1 = unc_wrapper(expectation, Syst.icegrad1, options) astro_grad = unc_wrapper(expectation, Syst.astrogam, options) cr_grad = unc_wrapper(expectation, Syst.crgam, options) self._net_error_m_sys = astro_grad[0]**2 self._net_error_m_sys = self._net_error_m_sys + cr_grad[ 0]**2 + ice_grad_0[0]**2 + ice_grad_1[0]**2 self._net_error_m_sys = np.sqrt(self._net_error_m_sys) self._net_error_p_sys = astro_grad[1]**2 self._net_error_p_sys = self._net_error_p_sys + cr_grad[ 1]**2 + ice_grad_0[1]**2 + ice_grad_1[1]**2 self._net_error_p_sys = np.sqrt(self._net_error_p_sys)
def scan(self): """ Scan over all the data files. This might take a while! """ if len(self.theta14s) == 1: chi2 = np.zeros(shape=(len(self.theta24s), len(self.theta34s), len(self.msqs))) else: chi2 = np.zeros(shape=(len(self.theta14s), len(self.theta24s), len(self.theta34s), len(self.msqs))) n_todo = len(self.theta24s) * len(self.theta34s) * len( self.msqs) * len(self.theta14s) counter = 0 pcent_i = 0 pcents = np.concatenate((np.linspace(0, 95, 20), np.linspace(96, 100, 5))) prediction_made = False how_long = "might take a while" if n_todo > 20000 else "should be quick" print("Starting the scan! This " + how_long) start = datetime.now() for i14 in range(len(self.theta14s)): for i24 in range(len(self.theta24s)): for i34 in range(len(self.theta34s)): for jm in range(len(self.msqs)): counter += 1 if 100 * (counter / n_todo) > pcents[pcent_i]: print("...{}%".format(pcents[pcent_i])) pcent_i += 1 if (not prediction_made) and (pcent_i != 1): end = datetime.now() t_total = ((end - start) * n_todo) / counter print( "Estimated time of completion: {}".format( start + t_total)) prediction_made = True pam = SterileParams(theta03=self.theta14s[i14], theta13=self.theta24s[i24], theta23=self.theta34s[i34], msq2=self.msqs[jm]) if self._compare: # if we _expect_ the sterile point, what's the llh of measuring what we measure? self.llh._set_central(pam) llh = self.llh.get_llh(self._central) else: # what are the odds of measuring PAM if we expect whatever the llh'er was configured to expect llh = self.llh.get_llh(pam) if len(self.theta14s) == 1: chi2[i24][i34][jm] = -2 * llh else: chi2[i14][i24][i34][jm] = -2 * llh if self._compare: chi2 = chi2 - np.min(chi2) return { "theta14s": self.theta14s, "theta24s": self.theta24s, "theta34s": self.theta34s, "th14_mode": self.th14_mode, "msqs": self.msqs, "chi2s": chi2, "options": self.llh.options }
if __name__ == "__main__": import pickle from cascade.utils import get_color do_fudge = False flavors = ["e", "mu", "tau"] if do_fudge: core_b = -0.98 mantle_b = -0.83 # let's see how the new predicted event rate looks! null = SterileParams() not_null = SterileParams(theta13=0.1609, theta23=0.2249, msq2=4.47) kwargs = {} kwargs["as_data"] = True atmo_data = raw_flux(null, kwargs=kwargs) astr_data = generate_astr_flux(null, as_data=True) n_e = 20 n_a = 10 raw_data = get_expectation(atmo_data, astr_data) e_bins = raw_data["e_edges"] a_bins = raw_data["a_edges"] events = raw_data["event_rate"] plt.pcolormesh(a_bins, e_bins, events)
add_contour("/home/bsmithers/software/data/hg_sib/0.1609e0/best_llh_1_00eV_smearing_0.0_0.1609e0_0.0_1.0000e0.dat", r"1.0eV$^{2}$, $\theta_{24}=0.1609$", '-') add_contour("/home/bsmithers/software/data/hg_sib/0.1609e0/best_llh_3_30eV_smearing_0.0_0.1609e0_0.0_3.3000e0.dat", r"3.3eV$^{2}$, $\theta_{24}=0.1609$", '-') add_contour("/home/bsmithers/software/data/hg_sib/0.1609e0/best_llh_4_64eV_smearing_0.0_0.1609e0_0.0_4.6400e0.dat", r"4.64eV$^{2}$, $\theta_{24}=0.1609$", '-') add_contour("/home/bsmithers/software/data/hg_sib/0.3826e0/best_llh_1_00eV_smearing_0.0_0.3826e0_0.0_1.0000e0.dat", r"1.0eV$^{2}$, $\theta_{24}=0.3826$", '--') add_contour("/home/bsmithers/software/data/hg_sib/0.3826e0/best_llh_3_30eV_smearing_0.0_0.3826e0_0.0_3.3000e0.dat", r"3.3eV$^{2}$, $\theta_{24}=0.3826$", '--') add_contour("/home/bsmithers/software/data/hg_sib/0.3826e0/best_llh_4_64eV_smearing_0.0_0.3826e0_0.0_4.6400e0.dat", r"4.64eV$^{2}$, $\theta_{24}=0.3826$", '--') """ msqs = [1.0, 3.3, 4.64] th24s = [0.1609, 3.826] th34s = [0.0] thetas = np.concatenate(([0], np.arcsin(np.sqrt(np.logspace(-3, 0, 90))) / 2)) filename = gen_filename(config["datapath"], "newllh_1d_scan.dat", params=SterileParams()) f = open(filename, 'rb') data_dict = pickle.load(f) f.close() msqs = data_dict["msqs"] th14s = data_dict["theta14s"] th24s = data_dict["theta24s"] th34s = data_dict["theta34s"] chis = data_dict["chi2s"] # chis = chis - np.nanmin(chis) print("Chi Shape: {}".format(np.shape(chis))) cl = 4 * 1.9 color_number = 0
from cascade.utils import SterileParams, gen_filename, config from cascade.deporeco import DataReco from cascade.sensitivity.generate_all_integrated_fluxes import make_meta_flux def ldata(fname): print("Loading {}".format(fname)) f = open(fname, 'rb') data = pickle.load(f) f.close() return data ratios = False central_s = SterileParams() #sterile_s = SterileParams(theta13=0.1652, theta23=0.2293, msq2=4.6416) sterile_s = SterileParams(theta13=0.1652, theta23=0.2293, msq2=4.5) use_params = central_s cascade_name_root = "best_expected_flux.dat" track_name_root = "expected_flux_from_mc_smearedwell.dat" datadir = os.path.join(config["datapath"], "expected_fluxes_reco") # datadir = "/home/benito/software/data/cascade/hg_sib/expected_fluxes_reco/" sterile_casc_fname = gen_filename(datadir, cascade_name_root, sterile_s) sterile_track_fname = gen_filename(datadir, track_name_root, sterile_s) cascade_fname = gen_filename(datadir, cascade_name_root, central_s) track_fname = gen_filename(datadir, track_name_root, central_s)
def _load_flux(name): f = open(name,'rb') all_data = pickle.load(f) f.close() e_reco = all_data["e_reco"] a_reco = all_data["a_reco"] flux = all_data["flux"] return( e_reco, a_reco, flux ) #null_pt = gen_filename(config["datapath"], config["nu_flux"], 0.,0.,0.) null = SterileParams(0.,0.,0.,0.) mud = SterileParams(0., 0.1609, 0.2205, 4.47) eld = SterileParams(0.13, 0., 0.0, 1.3) e_reco, a_reco, flux_null = _load_flux(gen_filename(config["datapath"], config["recon_flux"]+".dat", null)) e_reco, a_reco, flux_sterile = _load_flux(gen_filename(config["datapath"], config["recon_flux"]+".dat", mud)) ex = list(flux_null.keys())[0] null_total = np.zeros(shape = np.shape(flux_null[ex])) sterile_total = np.zeros(shape = np.shape(flux_null[ex])) just_nubar = False keep_key = "Tau" for key in flux_null.keys():
def cr_perturb(dgamma=0.0, dnorm=0.0, use_mc=False, smearmode=False, special=False): """ Calculates the expected cosmic ray spectrum, then returns the expected gains/losses in each bin by perturbing the overall spectram index (dgamma) and normalization (dnorm) down/up Returns a tuple containing np.ndarrays The first is the event change from a negative perturbation The second is the event change from a positive perturbation """ perturb_gamma = dgamma != 0.0 perturb_norm = dnorm != 0.0 if perturb_gamma == perturb_norm: raise ValueError( "Cannot perturb both norm and gamma simultaneously. Also need to perturb at least one." ) filename = os.path.join(perturb_folder, "cr_central.dat") null = SterileParams() if special: flux_func = lambda *objs: build_flux_sad(*objs, good_angles=True) else: if smearmode: flux_func = build_flux_sad else: flux_func = build_mc_flux if use_mc else build_flux if True: #not os.path.exists(filename): kwargs = {'as_data': True} flux_data = flux_func(raw_flux(null, kwargs)) pickle_save(flux_data, filename) else: flux_data = pickle_load(filename) p_plus = np.zeros(shape=np.shape(flux_data["stat_err"])) p_minus = np.zeros(shape=np.shape(flux_data["stat_err"])) if perturb_norm: mean_norm = 1.19 return _flipper(flux_data["event_rate"], ((mean_norm - dnorm) * flux_data["event_rate"], (mean_norm + dnorm) * flux_data["event_rate"])) if perturb_gamma: # scale with #phi(e) * (E/(2.2TeV))^deltagamma e_edges = flux_data["e_edges"] for i_e in range(len(e_edges) - 1): for i_a in range(len(flux_data["a_edges"]) - 1): # we have the energies at the bin edges... # sooo mean_dgamma = 0.068 effective_e = 0.5 * (e_edges[i_e] + e_edges[i_e + 1]) p_plus[i_e][i_a] = flux_data["event_rate"][i_e][i_a] * pow( effective_e / (2.2e3), -mean_dgamma - dgamma) p_minus[i_e][i_a] = flux_data["event_rate"][i_e][i_a] * pow( effective_e / (2.2e3), -mean_dgamma + dgamma) return _flipper(flux_data["event_rate"], (p_minus, p_plus))
def _load_flux(name): f = open(name, 'rb') all_data = pickle.load(f) f.close() e_reco = all_data["e_true"] a_reco = all_data["a_true"] flux = all_data["flux"] return (e_reco, a_reco, flux) e_reco, a_reco, flux = _load_flux( gen_filename(config["datapath"], config["nu_flux_downsize"] + ".dat", SterileParams())) energies = bhist([e_reco]).centers a_widths = bhist([a_reco]).widths angles = bhist([a_reco]).centers keys = list(flux.keys()) def is_track(key): curr = key.split("_")[2].lower() if "nc" == curr: return (False) elif "cc" == curr: flavor = key.split("_")[0].lower()
from cascade.utils import Data, SterileParams, gen_filename, config from cascade.sensitivity.make_from_mc import build_mc_flux from cascade.sensitivity.eff_area_reader import quickload import numpy as np import matplotlib matplotlib.use('Qt5Agg') import matplotlib.pyplot as plt import os # load the fluxes null_f = gen_filename(config["datapath"], "raw_det_flux.dat", SterileParams()) ster_f = gen_filename(config["datapath"], "raw_det_flux.dat", SterileParams(0.0, 0.1609, 0.0, 4.7)) null = Data(null_f) ster = Data(ster_f) # get the binning information filename = "effective_area.nu_mu.txt" area_data = quickload( os.path.join( os.path.join(config["datapath"], "charm_search_supplemental/"), filename)) e_edges = np.array(area_data["e_reco"]) a_edges = np.array(area_data["cos_th"]) e_centers = 0.5 * (e_edges[:-1] + e_edges[1:]) a_centers = 0.5 * (a_edges[:-1] + a_edges[1:]) # get the flux in the centers of each of the bins null_flux = np.zeros(shape=(len(e_centers), len(a_centers)))
data = pickle.load(f) f.close() return data else: # only import these if we need to from cascade.sensitivity.make_from_mc import build_mc_flux from cascade.sensitivity.generate_all_integrated_fluxes import make_meta_flux data = make_meta_flux(param, do_mc=False, smeary=True, good_angles=True) return data sp = SterileParams(theta13=0.1609e0, theta23=0.2247e0, msq2=4.47e0) null_flux_d = load(SterileParams()) ster_flux_d = load(sp) null_flux = null_flux_d["event_rate"] ster_flux = ster_flux_d["event_rate"] print(np.shape(null_flux)) print(np.shape(ster_flux)) e_edges = null_flux_d["e_edges"] a_edges = np.linspace(-1, 1, 11) # null_flux_d["a_edges"] print("E bins {}".format(len(e_edges))) print(e_edges)
import matplotlib matplotlib.use('Qt5Agg') import matplotlib.pyplot as plt import matplotlib.cm as cm import numpy as np from math import pi, cos, sqrt from cascade.oscillations.core import Oscillator from cascade.utils import SterileParams, sci ster_p = SterileParams(0.0,0.160875,0.0, 4.47) osc = Oscillator(SterileParams()) #osc = Oscillator(ster_p) energy = 5e1 # GeV positions = np.logspace(5,8, 300) flavors = 3 values = [[osc.p_trans(energy, pos, 1, flavor) for pos in positions] for flavor in range(flavors)] names = ["e", r"$\mu$", r"$\tau$", "s"] for flavor in range(flavors): plt.plot(positions, values[flavor], label=r"$\nu$"+names[flavor]) earth_r = 6.36e6 if min(positions)<(2*earth_r):
Then we plot each one individually Then we plot their ratio Then I added a few other debugging plots """ import numpy as np import matplotlib matplotlib.use('Qt5Agg') import matplotlib.pyplot as plt import matplotlib.cm as cm # these are like the MOST important things, damn from cascade.utils import bhist, SterileParams, gen_filename, config from cascade.deposit import generate_singly_diff_fluxes null = SterileParams(0., 0., 0., 0.) #ster = SterileParams(0., 0.1609, 0, 4.47) ster = SterileParams(0., 0.1609, 0.2205, 4.47) raw_null = gen_filename(config["datapath"], config["nu_flux"] + ".dat", null) raw_ster = gen_filename(config["datapath"], config["nu_flux"] + ".dat", ster) n_bins = 40 true_e_edges, depo_e_edges, null_flux, czenith_edges, errs = generate_singly_diff_fluxes( n_bins, datafile=raw_null) true_e_edges, depo_e_edges, ster_flux, czenith_edges, errs = generate_singly_diff_fluxes( n_bins, datafile=raw_ster) true_e_widths = np.array(bhist([true_e_edges]).widths)
import os import matplotlib matplotlib.use('Qt5Agg') import matplotlib.pyplot as plt plt.style.use(os.path.join(os.path.dirname(__file__), "..", ".." , "cascade.mplstyle")) from cascade.deporeco import DataReco import os exist_masses = np.concatenate((np.array([0]), np.logspace(-2,2,40))) fn = "best_expected_flux.dat" data_folder = os.path.join(config["datapath"], "expected_fluxes_reco") f_name = gen_filename(data_folder, fn, SterileParams()) sterile_fname = gen_filename(data_folder, fn, SterileParams(theta13=0.1652, theta23=0.2293, msq2=4.6416)) #sterile_string = r"$\sin^{2}(2\theta_{24})=0.1, \sin^{2}(2\theta_{34})=0.20, \Delta m_{41}^{2}=4.64$" sterile_string = r"Sterile Neutrino" def loadit(filename): f = open(filename, 'rb') tdata = pickle.load(f) f.close() return tdata data = loadit(f_name) sdata = loadit(sterile_fname)