Example #1
0
def corsika(cos_theta_bin=-1,
            kind='conv nu_mu',
            pmodel=(pm.HillasGaisser2012, 'H3a'),
            hadr='SIBYLL2.3',
            density=('CORSIKA', ('SouthPole', 'December')),
            prpl='ice_allm97_step_1',
            corsika_file='eff_maxmu',
            plot_nuveto_lines=False,
            plot_legacy_veto_lines=False):
    if isinstance(cos_theta_bin, list):
        [
            corsika(cth, kind, pmodel, hadr, density, prpl, corsika_file,
                    plot_nuveto_lines, plot_legacy_veto_lines)
            for cth in cos_theta_bin
        ]
        return

    cfile = pickle.load(open(
        resource_filename('nuVeto',
                          os.path.join('/data/corsika',
                                       corsika_file + '.pkl')), 'rb'),
                        encoding='latin1')
    fraction = 'eff' in corsika_file
    eff, elow, eup, xedges, yedges = cfile[mceq_categ_format(kind)]
    cos_theta = centers(yedges)[cos_theta_bin]
    clean = eff[:, cos_theta_bin] > 0
    xcenters = 10**centers(xedges)[clean]

    pr = plt.errorbar(xcenters,
                      eff[:, cos_theta_bin][clean],
                      xerr=np.asarray(
                          list(
                              zip(xcenters - 10**xedges[:-1][clean],
                                  10**xedges[1:][clean] - xcenters))).T,
                      yerr=np.asarray(
                          list(
                              zip(elow[:, cos_theta_bin][clean],
                                  eup[:, cos_theta_bin][clean]))).T,
                      label='CORSIKA {} {}'.format(tex(kind), tex(cos_theta)),
                      fmt='.')
    if plot_legacy_veto_lines and fraction:
        ens = np.logspace(2, 9, 100)
        emu = extsv.minimum_muon_energy(extsv.overburden(cos_theta))
        plt.plot(ens,
                 exthp.passrates(kind)(ens, emu, cos_theta),
                 'k--',
                 label='Analytic approx. {} {}'.format(tex(kind),
                                                       tex(cos_theta)))
    if plot_nuveto_lines:
        pr_enu(cos_theta,
               kind,
               pmodel=pmodel,
               hadr=hadr,
               prpl=prpl,
               density=density,
               fraction=fraction,
               label='{} {} {}'.format(hadr, tex(kind), tex(cos_theta)),
               color=pr[0].get_color())
    plt.legend()
Example #2
0
def plot_prpl(interp_pkl, include_mean=False, include_cbar=True):
    depth = 1950 * Units.m
    prplfn = pickle.load(open(interp_pkl, 'rb'), encoding='latin1')
    emui_edges = np.logspace(2, 8, 101)
    l_ice_edges = np.linspace(1e3, 4e4, 101)
    emui = centers(emui_edges)
    l_ice = centers(l_ice_edges)
    xx, yy = np.meshgrid(emui, l_ice)
    prpls = prplfn(list(zip(xx.flatten(), yy.flatten())))
    plt.figure()
    plt.pcolormesh(emui_edges,
                   l_ice_edges / 1e3,
                   prpls.reshape(xx.shape),
                   cmap='magma')
    if include_cbar:
        plt.colorbar()
    if include_mean:
        small_ice = l_ice[l_ice < 2.7e4]
        plt.plot(
            extsv.minimum_muon_energy(small_ice),
            small_ice / 1e3,
            'w--',
            label=
            r'$l_{\rm ice,\,median} (E_\mu^{\rm i}, E_\mu^{\rm th} = 1\,{\rm TeV})$'
        )
        leg = plt.legend(frameon=False,
                         prop={'weight': 'bold'},
                         loc='upper left')
        for text in leg.get_texts():
            plt.setp(text, color='w', fontsize='medium')
    plt.xlabel(r'$E_\mu^{\rm i}$ [GeV]')
    plt.ylabel(r'$l_{\rm ice}$ [km]')
    plt.locator_params(axis='y', nbins=8)
    # # plt.yscale('log')
    # # plt.gca().yaxis.set_major_formatter(ScalarFormatter())
    # plt.ticklabel_format(style='plain', axis='y')
    plt.gca().minorticks_off()
    plt.ylim(depth / Units.km, 40)
    # right y-axis with angles
    axr = plt.gca().twinx()
    axr.grid(False)
    geom = Geometry(depth)
    costhetas = geom.overburden_to_cos_theta(np.arange(10, 41, 10) * Units.km)
    axr.set_ylim(depth / Units.km, 40)
    axr.set_yticks(geom.overburden(costhetas) / 1e3)
    axr.set_yticklabels(np.round(costhetas, 2))
    axr.set_ylabel(r'$\cos \theta_z$', rotation=-90)
    axr.set_xscale('log')
    axr.set_xlim(1e2, 1e8)
    axr.minorticks_off()
    xlocmaj = LogLocator(base=10, numticks=12)
    axr.get_xaxis().set_major_locator(xlocmaj)
    return emui_edges, l_ice_edges, prpls.reshape(xx.shape)
Example #3
0
    def __init__(self,
                 costh,
                 pmodel=(pm.HillasGaisser2012, 'H3a'),
                 hadr='SIBYLL2.3c',
                 barr_mods=(),
                 depth=1950 * Units.m,
                 density=('CORSIKA', ('SouthPole', 'June'))):
        """Initializes the nuVeto object for a particular costheta, CR Flux,
        hadronic model, barr parameters, and depth

        Note:
            A separate MCEq instance needs to be created for each
            combination of __init__'s arguments. To access pmodel and hadr,
            use mceq.pm_params and mceq.yields_params
        Args:
            costh (float): Cos(theta), the cosine of the neutrino zenith at the detector
            pmodel (tuple(CR model class, arguments)): CR Flux
            hadr (str): hadronic interaction model
            barr_mods: barr parameters
            depth (float): the depth at which the veto probability is computed below the ice
        """
        self.costh = costh
        self.pmodel = pmodel
        self.geom = Geometry(depth)
        theta = np.degrees(np.arccos(self.geom.cos_theta_eff(self.costh)))

        MCEq.core.dbg = 0
        MCEq.kernels.dbg = 0
        MCEq.density_profiles.dbg = 0
        MCEq.data.dbg = 0
        self.mceq = MCEqRun(
            # provide the string of the interaction model
            interaction_model=hadr,
            # atmospheric density model
            density_model=density,
            # primary cosmic ray flux model
            # support a tuple (primary model class (not instance!), arguments)
            primary_model=pmodel,
            # zenith angle \theta in degrees, measured positively from vertical direction
            theta_deg=theta,
            enable_muon_energy_loss=False,
            **mceq_config_without(['enable_muon_energy_loss',
                                   'density_model']))

        for barr_mod in barr_mods:
            # Modify proton-air -> mod[0]
            self.mceq.set_mod_pprod(2212, BARR[barr_mod[0]].pdg, barr_unc,
                                    barr_mod)
        # Populate the modifications to the matrices by re-filling the interaction matrix
        self.mceq._init_default_matrices(skip_D_matrix=True)

        X_vec = np.logspace(np.log10(2e-3),
                            np.log10(self.mceq.density_model.max_X), 12)
        self.dX_vec = np.diff(X_vec)
        self.X_vec = 10**centers(np.log10(X_vec))
Example #4
0
    def nbody(fpath, esamp, enu, fn, l_ice):
        with np.load(fpath) as dfile:
            xmus = centers(dfile['xedges'])
            xnus = np.concatenate([xmus, [1]])
            vals = np.nan_to_num(dfile['histograms'])

            ddec = interpolate.RegularGridInterpolator((xnus, xmus),
                                                       vals,
                                                       bounds_error=False,
                                                       fill_value=None)
            emu_mat = xmus[:, None] * esamp[None, :] * Units.GeV
            pmu_mat = ddec(np.stack(np.meshgrid(enu / esamp, xmus), axis=-1))
            reaching = 1 - np.sum(pmu_mat * fn.prpl(
                np.stack([emu_mat, np.ones(emu_mat.shape) * l_ice], axis=-1)),
                                  axis=0)
            reaching[reaching < 0.] = 0.
            return reaching
Example #5
0
File: mu.py Project: vedant8/nuVeto
def hist_preach(infile):
    """ Builds histograms of P_reach based on MMC output text
    """
    Hist = namedtuple('Hist', 'counts edges')
    df = pd.read_csv(infile,
                     delim_whitespace=True,
                     header=None,
                     names='ei l ef'.split())
    # If the muon doesn't reach, MMC saves ef as -distance traveled
    df[df < 0] = 0
    preach = []
    for (ei, l), efs in df.groupby(['ei', 'l']):
        bins = calc_bins(efs['ef'])
        histo = Hist(*np.histogram(efs['ef'], bins=bins, density=True))
        [
            preach.append((ei, l, ef, ew, val)) for ef, ew, val in zip(
                centers(histo.edges), np.ediff1d(histo.edges), histo.counts)
        ]

    return np.asarray(preach)
Example #6
0
def hist_preach(infile, plotdir=None):
    import pandas as pd
    napf = 36
    df = pd.read_csv(infile,
                     delim_whitespace=True,
                     header=None,
                     names='ei l ef'.split())
    # If the muon doesn't reach, MMC saves ef as -distance traveled
    df[df < 0] = 0
    for idx, (ei, sdf) in enumerate(df.groupby('ei')):
        if idx % napf == 0:
            if idx > 0:
                # plt.legend(fontsize=6)
                plt.tight_layout()
                if plotdir is not None:
                    plt.savefig(
                        os.path.join(os.path.expanduser(plotdir),
                                     '{}.png'.format((idx - 1) / napf)))
            fig, axs = plt.subplots(6, 6, figsize=(10, 10))
            # fig.text(0.5, 0.04, r'$E_f$', ha='center', va='center')
            # fig.text(0.06, 0.5, r'$P(E_f|E_i, l)$', ha='center', va='center', rotation='vertical')
            axs = axs.flatten()
        ax = axs[idx % napf]
        ax.set_prop_cycle('color', plt.cm.Blues(np.linspace(0.3, 1, 100)))
        plt.sca(ax)
        plt.title(r'${:.2g}$ GeV'.format(ei), fontdict={'fontsize': 8})
        for l, efs in sdf.groupby('l'):
            bins = calc_bins(efs['ef'])
            counts, edges = np.histogram(efs['ef'], bins=bins, density=True)
            plt.plot(centers(edges), counts, label='{:.3g} km'.format(l / 1e3))
        plt.yscale('log')
        # plt.xlim(sdf['ef'].min(), sdf['ef'].max()*1.1)
    # plt.legend(fontsize=6)
    plt.tight_layout()
    if plotdir is not None:
        plt.savefig(
            os.path.join(os.path.expanduser(plotdir), '{}.png'.format(
                (idx - 1) / napf)))