Ejemplo n.º 1
0
def add_contour(filename, ls, cmap='cool', chop=False):
    f = open(filename, 'rb')
    data = pickle.load(f)
    f.close()
    this_chi = np.array(data["chi2s"])
    temp = np.zeros(shape=(2, len(theta24s), len(theta34s)))
    for t24 in range(len(theta24s)):
        for t34 in range(len(theta34s)):
            temp[0][t24][t34] = this_chi[t24][t34][which_sliver[0]]
            temp[1][t24][t34] = this_chi[t24][t34][which_sliver[1]]
    final_chi = get_closest(ev, [msqs[which_sliver[0]], msqs[which_sliver[1]]],
                            temp)

    if chop:
        # need to chop off the right side :frown:
        for i_x in range(len(scale_x)):
            for i_y in range(len(scale_y[i_x])):
                if scale_x[i_x][i_x] > 6e-2:
                    final_chi[i_x][i_y] = None

    ct = plt.contour(scale_x,
                     scale_y,
                     final_chi.transpose(),
                     levels=chis_l,
                     cmap=cmap,
                     linestyles=ls)
    return ct
Ejemplo n.º 2
0
def get_odds_energy(deposited, reconstructed):
    """
    Takes an energy deposited and energy reconstructed.
    Loads the datafile and reads off the uncertainty from the second column. 
    The data is in %E_depo, so we scale this to be a ratio and then by that deposted energy
    """
    if not isinstance(deposited, (float,int)):
        raise Exception()
    if not isinstance(reconstructed, (float,int)):
        raise Exception()

    if deposited<data[0][0]:
        sigma = data[1][0]*deposited*0.01
    elif deposited>data[0][-1]:
        sigma = data[1][-1]*deposited*0.01
    else:
        sigma = get_closest( deposited, data[0], data[1])*deposited*0.01

    
    s2 = np.log(1+ (sigma/deposited)**2)
    mu = np.log((deposited**2)/np.sqrt(deposited**2  + sigma**2))
    # now, we assume that the uncertainty follows a log normal distribution, and calculate the PDF here

    #prob = rtwo*(1./sigma)*exp(-0.5*((reconstructed - deposited)/sigma)**2)
    prob = rtwo*(1./np.sqrt(s2))*exp(-0.5*((np.log(reconstructed) - mu)**2)/s2)/reconstructed

    return(prob)
Ejemplo n.º 3
0
 def eval(self, rad_error):
     """
     Accesses the stored calculated values for kappa
     """
     if not isinstance(rad_error, (int, float)):
         raise TypeError("Receied invalid datatype for rad error: {}".format(type(rad_error)))
     
     value = get_closest(cos(rad_error), self.czen_range, self.obj)
     return(value)
Ejemplo n.º 4
0
def get_ang_error(energy):
    """
    Returns a best-guess for the angular error - the FIFTYth percentile

    Energy should be a float and in GeV
    """
    if not isinstance(energy, (int,float)):
        raise TypeError("Expected {}, got {}".format(float, type(energy)))
    
    try:
        # we really want to just use the data, so let's try interpolating first 
        error = get_closest( energy, angdata[0], angdata[1] )
    except ValueError: # failing that we use the fit (which isn't as good)
        error = func( log10(energy), popt[0], popt[1], popt[2] )
    return(min(max(error, 0), 180))
Ejemplo n.º 5
0
def add_contour(filename, ls, cmap='cool', chop=False):
    f = open(filename, 'rb')
    data = pickle.load(f)
    f.close()
    this_chi = np.array(data["chi2s"])
    evs = [0.5, 1.0, 3.0, 10.0]

    count = 0
    for ev in evs:

        which_sliver = get_loc(ev, msqs)

        temp = np.zeros(shape=(2, len(theta24s), len(theta34s)))
        for t24 in range(len(theta24s)):
            for t34 in range(len(theta34s)):
                temp[0][t24][t34] = this_chi[t24][t34][which_sliver[0]]
                temp[1][t24][t34] = this_chi[t24][t34][which_sliver[1]]
        final_chi = get_closest(ev,
                                [msqs[which_sliver[0]], msqs[which_sliver[1]]],
                                temp)

        if chop:
            # need to chop off the right side :frown:
            for i_x in range(len(scale_x)):
                for i_y in range(len(scale_y[i_x])):
                    if final_chi[i_x][i_y] < 0 or final_chi[i_x][i_y] > 1000:
                        final_chi[i_x][i_y] = None
                    if scale_x[i_x][i_x] > 6e-2:
                        final_chi[i_x][i_y] = None

        ct = plt.contour(scale_x,
                         scale_y,
                         final_chi.transpose(),
                         levels=chis_l,
                         cmap=cmap,
                         linestyles=ls)
        ct.collections[0].set_color(get_color(count + 1,
                                              len(evs) + 1, "magma"))
        suffix = "Joint" if chop else "Cascades"
        ct.collections[0].set_label("{}, {:.1f}".format(suffix, ev) +
                                    r"eV$^{2}$")
        count += 1
    return ct
Ejemplo n.º 6
0
def get_slice(eV: float, chis: np.ndarray):
    """
    Get a slice of the chi-squared arrays at the requested mass squared difference 
    """
    which_sliver = get_loc(eV, msqs)
    print("slivers: {}".format(which_sliver))
    if interpolate:
        chis_final = np.zeros(shape=(2, len(chis), len(chis[0])))
        for t24 in range(len(chis)):
            for t34 in range(len(chis[t24])):
                #print("{} {}".format(t24, t34))
                chis_final[0][t24][t34] = chis[t24][t34][which_sliver[0]]
                chis_final[1][t24][t34] = chis[t24][t34][which_sliver[1]]
        return get_closest(eV, [msqs[which_sliver[0]], msqs[which_sliver[1]]],
                           chis_final)
    else:
        which_sliver = which_sliver[0]
        new_chis = np.zeros(shape=(len(theta24s), len(theta34s)))
        for i24 in range(len(theta24s)):
            for i34 in range(len(theta34s)):
                new_chis[i24][i34] = chis[i24][i34][which_sliver]
        return new_chis
Ejemplo n.º 7
0
deepcore = np.transpose(np.loadtxt("deepcore.dat", delimiter=","))
antares = np.transpose(np.loadtxt("antares.dat", delimiter=","))

color_count = 0
for ev in evs:
    color_count+=1

    which_sliver = get_loc(ev, msqs)
    print(which_sliver)
    if interp:
        chis_f = np.zeros(shape=(2, len(theta24s), len(theta34s)))
        for t24 in range(len(theta24s)):
            for t34 in range(len(theta34s)):
                chis_f[0][t24][t34] = chi2[t24][t34][which_sliver[0]]
                chis_f[1][t24][t34] = chi2[t24][t34][which_sliver[1]]
        chis = get_closest( ev, [msqs[which_sliver[0]], msqs[which_sliver[1]]], chis_f)


    else:
        sliver = which_sliver[0]
        chis = np.zeros(shape=(len(theta24s), len(theta34s)))
        

        for t24 in range(len(theta24s)):
            for t34 in range(len(theta34s)):
                chis[t24][t34] = chi2[t24][t34][sliver]

    #plt.pcolormesh(scale_x,scale_y, chis.transpose(),vmin=0, vmax=10, cmap="PuBu")
    #cbar = plt.colorbar(extend='max')
    
    #plt.title("At {:.2f} eV".format(ev if interp else msqs[which_sliver[0]]) +r"$^{2}$")fs
Ejemplo n.º 8
0
cmap.set_under('0.75')
bounds = chis
norm = matplotlib.colors.BoundaryNorm(bounds, cmap.N)

yellow_left_interp = []
yellow_right_interp = []
green_left_interp = []
green_right_interp = []

for msq in msqs:
    if msq < yellow_left[1][0]:
        left = yellow_left[0][0]
    elif msq > yellow_left[1][-1]:
        left = yellow_left[0][-1]
    else:
        left = get_closest(msq, yellow_left[1], yellow_left[0])
    yellow_left_interp.append(left)

    if msq < yellow_right[1][0]:
        right = yellow_right[0][0]
    elif msq > yellow_right[1][-1]:
        left = yellow_right[0][-1]
    else:
        right = get_closest(msq, yellow_right[1], yellow_right[0])
    yellow_right_interp.append(right)

    if msq < green_left[1][0]:
        left = green_left[0][0]
    elif msq > green_left[1][-1]:
        left = green_left[0][-1]
    else:
Ejemplo n.º 9
0
def get_initial_state(energies, zeniths, n_nu, kwargs):
    """
    This either loads the initial state, or generates it.
    Loading it is waaaay quicker.

    Possible issue! If you run a bunch of jobs and don't already have this flux generated, bad stuff can happen. 
    I'm imagining issues where a bunch of jobs waste time making this, and then all try to write to the same file
    Very bad. Big crash. Very Fail 
    """
    path = os.path.join(config["datapath"], config["mceq_flux"])
    if os.path.exists(path):
        #        print("Loading MCEq Flux")
        f = open(path, 'rb')
        inistate = pickle.load(f)
        f.close()
    else:
        #        print("Generating MCEq Flux")
        inistate = np.zeros(shape=(angular_bins, energy_bins, 2, n_nu))
        mceq = MCEqRun(interaction_model=config["interaction_model"],
                       primary_model=(crf.HillasGaisser2012, 'H3a'),
                       theta_deg=0.)

        r_e = 6.378e6  # meters
        ic_depth = 1.5e3  # meters
        mag = 0.  # power energy is raised to and then used to scale the flux
        for angle_bin in range(angular_bins):
            # get the MCEq angle from the icecube zenith angle
            angle_deg = asin(
                sin(pi - acos(zeniths[angle_bin])) * (r_e - ic_depth) / r_e)
            angle_deg = angle_deg * 180. / pi
            if angle_deg > 180.:
                angle_deg = 180.

            print("Evaluating {} deg Flux".format(angle_deg))
            # for what it's worth, if you try just making a new MCEqRun for each angle, you get a memory leak.
            # so you need to manually set the angle
            mceq.set_theta_deg(angle_deg)
            mceq.solve()

            flux = {}
            flux['e_grid'] = mceq.e_grid

            flux['nue_flux'] = mceq.get_solution(
                'nue', mag) + mceq.get_solution('pr_nue', mag)
            flux['nue_bar_flux'] = mceq.get_solution(
                'antinue', mag) + mceq.get_solution('pr_antinue', mag)
            flux['numu_flux'] = mceq.get_solution(
                'numu', mag) + mceq.get_solution('pr_numu', mag)
            flux['numu_bar_flux'] = mceq.get_solution(
                'antinumu', mag) + mceq.get_solution('pr_antinumu', mag)
            flux['nutau_flux'] = mceq.get_solution(
                'nutau', mag) + mceq.get_solution('pr_nutau', mag)
            flux['nutau_bar_flux'] = mceq.get_solution(
                'antinutau', mag) + mceq.get_solution('pr_antinutau', mag)

            for neut_type in range(2):
                for flavor in range(n_nu):
                    flav_key = get_key(flavor, neut_type)
                    if flav_key == "":
                        continue

                    for energy_bin in range(energy_bins):
                        # (account for the difference in units between mceq and nusquids! )
                        inistate[angle_bin][energy_bin][neut_type][
                            flavor] = get_closest(
                                energies[energy_bin] / un.GeV, flux['e_grid'],
                                flux[flav_key])

        if np.min(inistate) < 0:
            raise ValueError(
                "Found negative value in the input from MCEq {}".format(
                    np.min(inistate)))
        # save it now
        f = open(path, 'wb')
        pickle.dump(inistate, f, -1)
        f.close()

    return (inistate)
Ejemplo n.º 10
0
def make_plots():
    Emin = 1 * un.GeV
    Emax = 10 * un.PeV

    energies = nsq.logspace(Emin, Emax, 100)
    angles = nsq.linspace(-0.99, -0.98, 2)

    # just look at straight up/down
    # get MCEq flux there

    mag = 0.
    angle = 0.  #degrees

    mceq = MCEqRun(interaction_model='SIBYLL23C',
                   primary_model=(crf.HillasGaisser2012, 'H3a'),
                   theta_deg=0.)

    mceq.solve()

    n_nu = 3
    inistate = np.zeros(shape=(2, len(energies), 2, n_nu))
    flux = {}

    flux['e_grid'] = mceq.e_grid
    flux['nue_flux'] = mceq.get_solution('nue', mag) + mceq.get_solution(
        'pr_nue', mag)
    flux['nue_bar_flux'] = mceq.get_solution(
        'antinue', mag) + mceq.get_solution('pr_antinue', mag)
    flux['numu_flux'] = mceq.get_solution('numu', mag) + mceq.get_solution(
        'pr_numu', mag)
    flux['numu_bar_flux'] = mceq.get_solution(
        'antinumu', mag) + mceq.get_solution('pr_antinumu', mag)
    flux['nutau_flux'] = mceq.get_solution('nutau', mag) + mceq.get_solution(
        'pr_nutau', mag)
    flux['nutau_bar_flux'] = mceq.get_solution(
        'antinutau', mag) + mceq.get_solution('pr_antinutau', mag)

    # propagate it with nusquids
    for neut_type in range(2):
        for flavor in range(n_nu):
            flav_key = get_key(flavor, neut_type)
            if flav_key == "":
                continue
            for energy_bin in range(len(energies)):
                inistate[0][energy_bin][neut_type][flavor] = get_closest(
                    energies[energy_bin] / un.GeV, flux['e_grid'],
                    flux[flav_key])

                inistate[1][energy_bin][neut_type][flavor] = get_closest(
                    energies[energy_bin] / un.GeV, flux['e_grid'],
                    flux[flav_key])

    nus_atm = nsq.nuSQUIDSAtm(angles, energies, n_nu, nsq.NeutrinoType.both,
                              True)

    nus_atm.Set_MixingAngle(0, 1, 0.563942)
    nus_atm.Set_MixingAngle(0, 2, 0.154085)
    nus_atm.Set_MixingAngle(1, 2, 0.785398)

    nus_atm.Set_SquareMassDifference(1, 7.65e-05)
    nus_atm.Set_SquareMassDifference(2, 0.00247)

    nus_atm.SetNeutrinoCrossSections(xs)

    #settting some zenith angle stuff
    nus_atm.Set_rel_error(1.0e-6)
    nus_atm.Set_abs_error(1.0e-6)
    #nus_atm.Set_GSL_step(gsl_odeiv2_step_rk4)
    nus_atm.Set_GSL_step(nsq.GSL_STEP_FUNCTIONS.GSL_STEP_RK4)

    # we load in the initial state. Generating or Loading from a file
    nus_atm.Set_initial_state(inistate, nsq.Basis.flavor)
    print("Done setting initial state")

    # we turn off the progress bar for jobs run on the cobalts
    nus_atm.Set_ProgressBar(False)
    nus_atm.Set_IncludeOscillations(True)

    print("Evolving State")
    nus_atm.EvolveState()

    # Evaluate the flux at the energies, flavors, and shit we care about

    eval_flux = {}
    for flavor in range(3):
        for nute in range(2):
            key = get_key(flavor, nute)
            if key == "":
                continue
            eval_flux[key] = np.zeros(len(energies))

            for energy in range(len(energies)):
                powed = energies[energy]

                eval_flux[key][energy] = nus_atm.EvalFlavor(
                    flavor, -0.985, powed, nute)

    # multiply the fluxes with total cross sections at that energy

    conv_flux = {}
    for flavor in flavors.keys():
        if flavor == "electron":
            i_flav = 0
        elif flavor == "muon":
            i_flav = 1
        else:
            i_flav = 2
        for neut_type in neut_types.keys():
            if neut_type == "neutrino":
                i_neut = 0
            else:
                i_neut = 1

            eval_key = get_key(i_flav, i_neut)
            for current in currents.keys():
                conv_key = "_".join([flavor, neut_type, current])
                conv_flux[conv_key] = np.zeros(len(energies))
                for energy in range(len(energies)):
                    powed = energies[energy]

                    conv_flux[conv_key][
                        energy] = eval_flux[eval_key][energy] * get_total_flux(
                            powed, flavors[flavor], neut_types[neut_type],
                            currents[current])

    # sum up the cascades and compare them with the cross sections

    casc_fluxes = np.zeros(len(energies))
    track_fluxes = np.zeros(len(energies))
    for key in conv_flux:
        if is_cascade(key):
            casc_fluxes += conv_flux[key]
        else:
            track_fluxes += conv_flux[key]

    plt.plot(energies / un.GeV, casc_fluxes, label="Cascades")
    plt.plot(energies / un.GeV, track_fluxes, label="Tracks")
    plt.xscale('log')
    plt.xlim([10**2, 10**7])
    plt.yscale('log')
    plt.legend()
    plt.xlabel("Energy [GeV]", size=14)
    plt.ylabel(r"Flux$\cdot\sigma_{total}$ [s GeV sr]$^{-1}$", size=14)
    plt.show()