Пример #1
0
def create_table(dir_name):

    particle_defs = [
        pp.particle.MuMinusDef.get(),
        pp.particle.TauMinusDef.get(),
        pp.particle.EMinusDef.get()
    ]

    cuts = [
        pp.EnergyCutSettings(-1, -1),
        pp.EnergyCutSettings(500, -1),
        pp.EnergyCutSettings(-1, 0.05),
        pp.EnergyCutSettings(500, 0.05)
    ]

    mediums = [
        pp.medium.Ice(1.0),
        pp.medium.Hydrogen(1.0),
        pp.medium.Uranium(1.0)
    ]

    initial_energy = np.logspace(4, 13, num=10)  # MeV
    final_energy = initial_energy - 1000

    pp.RandomGenerator.get().set_seed(0)
    np.random.seed(123)

    with open(dir_name + "continous_randomization.txt", "a") as file:

        for particle in particle_defs:
            for medium in mediums:
                for cut in cuts:

                    utility = pp.Utility(particle, medium, cut,
                                         pp.UtilityDefinition(),
                                         pp.InterpolationDef())

                    cont_rand = pp.ContinuousRandomizer(
                        utility, pp.InterpolationDef())

                    buf = [""]

                    for i in range(len(initial_energy)):
                        rnd = np.random.random_sample()
                        rand_energy = cont_rand.randomize(
                            initial_energy[i], final_energy[i], rnd)

                        buf.append(str(rnd))
                        buf.append(particle.name)
                        buf.append(medium.name)
                        buf.append(str(cut.ecut))
                        buf.append(str(cut.vcut))
                        buf.append(str(initial_energy[i]))
                        buf.append(str(final_energy[i]))
                        buf.append(str(rand_energy))
                        buf.append("\n")

                    file.write("\t".join(buf))
Пример #2
0
def create_propagator(
        path_to_inerpolation_tables='~/.local/share/PROPOSAL/tables',
        brems_param_name='BremsKelnerKokoulinPetrukhin',
        epair_param_name='EpairKelnerKokoulinPetrukhin',
        photo_param_name='PhotoAbramowiczLevinLevyMaor97'):
    mu_def = pp.particle.MuMinusDef.get()
    geometry = pp.geometry.Sphere(pp.Vector3D(), 1.e20, 0.0)
    ecut = 500
    vcut = -1

    sector_def = pp.SectorDefinition()
    sector_def.cut_settings = pp.EnergyCutSettings(ecut, vcut)
    sector_def.medium = pp.medium.Ice(1.0)
    sector_def.geometry = geometry
    sector_def.scattering_model = pp.scattering.ScatteringModel.NoScattering
    sector_def.crosssection_defs.brems_def.lpm_effect = True
    sector_def.crosssection_defs.epair_def.lpm_effect = True
    sector_def.do_continuous_randomization = False
    sector_def.do_exact_time_calculation = False
    sector_def.crosssection_defs.brems_def.parametrization = pp.parametrization.bremsstrahlung.BremsFactory.get(
    ).get_enum_from_str(brems_param_name)
    sector_def.crosssection_defs.epair_def.parametrization = pp.parametrization.pairproduction.EpairFactory.get(
    ).get_enum_from_str(epair_param_name)
    sector_def.crosssection_defs.photo_def.parametrization = pp.parametrization.photonuclear.PhotoFactory.get(
    ).get_enum_from_str(photo_param_name)

    detector = geometry

    interpolation_def = pp.InterpolationDef()
    interpolation_def.path_to_tables = path_to_inerpolation_tables
    interpolation_def.path_to_tables_readonly = path_to_inerpolation_tables

    return pp.Propagator(mu_def, [sector_def], detector, interpolation_def)
Пример #3
0
def create_table_scatter(dir_name):

    with open(dir_name + "Scattering_scatter.txt", "a") as file:

        for particle_def in particle_defs:
            for medium in mediums:
                for cut in cuts:
                    for idx, parametrization in enumerate(parametrizations):
                        particle = pp.particle.Particle(particle_def)

                        if scat_names[idx] == "HighlandIntegral":
                            util = pp.Utility(particle_def, medium, cut,
                                              pp.UtilityDefinition(),
                                              pp.InterpolationDef())
                            scattering = parametrization(
                                particle, util, pp.InterpolationDef())
                        else:
                            scattering = parametrization(particle, medium)

                        buf = [""]
                        for jdx, energy in enumerate(energies):
                            # TODO wrap UtilityDecorator
                            particle.energy = energy
                            particle.position = position_init
                            particle.direction = direction_init

                            scattering.scatter(distance, energy,
                                               energies_out[jdx])

                            buf.append(particle_def.name)
                            buf.append(medium.name)
                            buf.append(scat_names[idx])
                            buf.append(str(cut.ecut))
                            buf.append(str(cut.vcut))
                            buf.append(str(energy))
                            buf.append(str(energies_out[jdx]))
                            buf.append(str(distance))
                            buf.append(str(particle.position.x))
                            buf.append(str(particle.position.y))
                            buf.append(str(particle.position.z))
                            buf.append(str(particle.direction.radius))
                            buf.append(str(particle.direction.phi))
                            buf.append(str(particle.direction.theta))
                            buf.append("\n")

                        file.write("\t".join(buf))
Пример #4
0
def create_table_scatter(dir_name):

    with open(dir_name + "Scattering_scatter.txt", "w") as file:

        for particle_def in particle_defs:
            for medium in mediums:
                for cut in cuts:
                    for idx, parametrization in enumerate(parametrizations):

                        if scat_names[idx] == "HighlandIntegral":
                            util = pp.Utility(particle_def, medium, cut, pp.UtilityDefinition(), pp.InterpolationDef())
                            scattering = parametrization(particle_def, util, pp.InterpolationDef())
                        else:
                            scattering = parametrization(particle_def, medium)

                        buf = [""]
                        for jdx, energy in enumerate(energies):
                            # TODO wrap UtilityDecorator

                            rnd1 = pp.RandomGenerator.get().random_double()
                            rnd2 = pp.RandomGenerator.get().random_double()
                            rnd3 = pp.RandomGenerator.get().random_double()
                            rnd4 = pp.RandomGenerator.get().random_double()
                            directions = scattering.scatter(distance,
                                                            energy,
                                                            energies_out[jdx],
                                                            position_init,
                                                            direction_init,
                                                            rnd1, rnd2, rnd3, rnd4)

                            posi = position_init + distance * directions.u
                            dire = directions.n_i

                            buf.append(particle_def.name)
                            buf.append(medium.name)
                            buf.append(scat_names[idx])
                            buf.append(str(cut.ecut))
                            buf.append(str(cut.vcut))
                            buf.append(str(energy))
                            buf.append(str(energies_out[jdx]))
                            buf.append(str(distance))
                            buf.append(str(rnd1))
                            buf.append(str(rnd2))
                            buf.append(str(rnd3))
                            buf.append(str(rnd4))
                            buf.append(str(posi.x))
                            buf.append(str(posi.y))
                            buf.append(str(posi.z))
                            buf.append(str(dire.radius))
                            buf.append(str(dire.phi))
                            buf.append(str(dire.theta))
                            buf.append("\n")

                        file.write("\t".join(buf))
Пример #5
0
def muons(energy, statistics, vcut, do_continuous_randomization, dist):

    sec_def = pp.SectorDefinition()
    sec_def.medium = pp.medium.StandardRock(1.0)
    sec_def.geometry = pp.geometry.Sphere(pp.Vector3D(), 1e20, 0)
    sec_def.particle_location = pp.ParticleLocation.inside_detector

    sec_def.scattering_model = pp.scattering.ScatteringModel.Highland
    sec_def.do_continuous_randomization = do_continuous_randomization

    sec_def.cut_settings.ecut = 0
    sec_def.cut_settings.vcut = vcut

    interpolation_def = pp.InterpolationDef()
    interpolation_def.path_to_tables = "~/.local/share/PROPOSAL/tables"
    interpolation_def.path_to_tables_readonly = "~/.local/share/PROPOSAL/tables"

    mu_def = pp.particle.MuMinusDef.get()
    prop = pp.Propagator(
            particle_def=mu_def,
            sector_defs=[sec_def],
            detector=pp.geometry.Sphere(pp.Vector3D(), 1e20, 0),
            interpolation_def=interpolation_def
    )

    mu = pp.particle.DynamicData(mu_def.particle_type)
    mu.position = pp.Vector3D(0, 0, 0)
    mu.direction = pp.Vector3D(0, 0, -1)
    mu.energy = energy
    mu.propagated_distance = 0.
    mu.time = 0.

    mu_energies = []
    pp.RandomGenerator.get().set_seed(1234)

    for i in tqdm(range(statistics)):

        secondaries = prop.propagate(mu, dist * 100)

        mu_energies.append(secondaries.energy[-1])
        # del secondaries

    return mu_energies
Пример #6
0
def muons(energy, statistics, vcut, do_continuous_randomization, dist):

    sec_def = pp.SectorDefinition()
    sec_def.medium = pp.medium.StandardRock(1.0)
    sec_def.geometry = pp.geometry.Sphere(pp.Vector3D(), 1e20, 0)
    sec_def.particle_location = pp.ParticleLocation.inside_detector

    sec_def.scattering_model = pp.scattering.ScatteringModel.Moliere
    sec_def.do_continuous_randomization = do_continuous_randomization

    sec_def.cut_settings.ecut = 0
    sec_def.cut_settings.vcut = vcut

    interpolation_def = pp.InterpolationDef()
    interpolation_def.path_to_tables = "tables/"

    prop = pp.Propagator(particle_def=pp.particle.MuMinusDef.get(),
                         sector_defs=[sec_def],
                         detector=pp.geometry.Sphere(pp.Vector3D(), 1e20, 0),
                         interpolation_def=interpolation_def)

    mu = prop.particle

    mu_energies = []

    start = timer()

    for i in range(statistics):

        mu.position = pp.Vector3D(0, 0, 0)
        mu.direction = pp.Vector3D(0, 0, -1)
        mu.energy = energy
        mu.propagated_distance = 0

        d = prop.propagate(dist * 100)

        mu_energies.append(mu.energy)

    end = timer()

    return (mu_energies, statistics / (end - start))
Пример #7
0
mupair = [
    pp.parametrization.mupairproduction.KelnerKokoulinPetrukhin,
]

mupair_interpol = [
    pp.parametrization.mupairproduction.KelnerKokoulinPetrukhinInterpolant,
]

energies = np.logspace(4, 13, num=10)

vs = np.linspace(
    0.022, 0.98, 10
)  # choose v-range so that v_min < v < v_max is always fulflilled for all E in energies

interpoldef = pp.InterpolationDef()


def create_tables(dir_name, interpolate=False, **kwargs):

    pp.RandomGenerator.get().set_seed(1234)

    if interpolate:
        params = mupair_interpol
    else:
        params = mupair

    buf = {}

    for key in kwargs:
        if key == "dEdx" and kwargs[key] is True:
Пример #8
0
def propagate():
    """ Propagte muon in ice threw a cylindric detector

    Returns:
        (Particle) Particle representing the start position
        (Geometry) Geometry of the detector
        (list)     List of secondarys particles represeint interactions
    """

    medium = pp.medium.Ice(1.0)
    geo_detector = pp.geometry.Cylinder(pp.Vector3D(), 800, 0, 1600)
    geo_outside = pp.geometry.Box(pp.Vector3D(), 500000, 500000, 500000)

    # Infront

    sec_def_infront = pp.SectorDefinition()
    sec_def_infront.medium = medium
    sec_def_infront.geometry = geo_outside
    sec_def_infront.particle_location = pp.ParticleLocation.infront_detector

    sec_def_infront.scattering_model = pp.scattering.ScatteringModel.Moliere

    sec_def_infront.cut_settings.ecut = -1
    sec_def_infront.cut_settings.vcut = 0.05

    # Inside

    sec_def_inside = pp.SectorDefinition()
    sec_def_inside.medium = medium
    sec_def_inside.geometry = geo_outside
    sec_def_inside.particle_location = pp.ParticleLocation.inside_detector

    sec_def_inside.scattering_model = pp.scattering.ScatteringModel.Moliere

    sec_def_inside.cut_settings.ecut = 500
    sec_def_inside.cut_settings.vcut = -1

    # Behind

    sec_def_behind = pp.SectorDefinition()
    sec_def_behind.medium = medium
    sec_def_behind.geometry = geo_outside
    sec_def_behind.particle_location = pp.ParticleLocation.behind_detector

    sec_def_behind.scattering_model = pp.scattering.ScatteringModel.Moliere

    sec_def_behind.cut_settings.ecut = -1
    sec_def_behind.cut_settings.vcut = 0.05

    # Interpolation defintion

    interpolation_def = pp.InterpolationDef()
    interpolation_def.path_to_tables = "~/.local/share/PROPOSAL/tables"

    # Propagator

    prop = pp.Propagator(
        particle_def=pp.particle.MuMinusDef.get(),
        sector_defs=[sec_def_infront, sec_def_inside, sec_def_behind],
        detector=geo_detector,
        interpolation_def=interpolation_def)

    mu = prop.particle

    # Set energy and position of the particle

    mu.energy = 9e6
    mu.direction = pp.Vector3D(0, 0, 1)

    pos = mu.position
    pos.set_cartesian_coordinates(0, 0, -1e5)
    mu.position = pos

    mu_start = pp.particle.Particle(mu)

    secondarys = prop.propagate()

    return mu_start, geo_detector, secondarys
Пример #9
0
def plot_theory_curve():

    npzfile = np.load(
        "data_sec_dist_MuMinus_standardrock_Emin_10.0_Emax_10.0.npz")

    ioniz_secondary_energy = npzfile['ioniz']
    brems_secondary_energy = npzfile['brems']
    photo_secondary_energy = npzfile['photo']
    epair_secondary_energy = npzfile['epair']

    all_secondary_energy = np.concatenate(
        (ioniz_secondary_energy, brems_secondary_energy,
         photo_secondary_energy, epair_secondary_energy))

    sum_hist = np.sum(all_secondary_energy)
    print(sum_hist)

    list_secondary_energies = [
        ioniz_secondary_energy, brems_secondary_energy, photo_secondary_energy,
        epair_secondary_energy, all_secondary_energy
    ]

    list_secondary_energies_label = [
        'Ionization', 'Photonuclear', 'Bremsstrahlung', 'Pair Production',
        'Sum'
    ]

    statistics = npzfile['statistics'][0]
    E_min_log = npzfile['E_min'][0]
    E_max_log = npzfile['E_max'][0]
    spectral_index = npzfile['spectral_index'][0]
    distance = npzfile['distance'][0]
    medium_name = npzfile['medium_name'][0]
    particle_name = npzfile['particle_name'][0]
    ecut = npzfile['ecut'][0]
    vcut = npzfile['vcut'][0]

    particle_def = pp.particle.MuMinusDef.get()
    medium = pp.medium.StandardRock(1.0)
    energy_cuts = pp.EnergyCutSettings(500, -1)
    multiplier = 1.
    lpm = False
    shadow_effect = pp.parametrization.photonuclear.ShadowButkevichMikhailov()
    add_pertubative = True
    interpolation_def = pp.InterpolationDef()
    interpolation_def.path_to_tables = "~/.local/share/PROPOSAL/tables"

    ioniz = pp.parametrization.Ionization(particle_def=particle_def,
                                          medium=medium,
                                          energy_cuts=energy_cuts,
                                          multiplier=multiplier)

    epair = pp.parametrization.pairproduction.EpairProductionRhoInterpolant(
        particle_def=particle_def,
        medium=medium,
        energy_cuts=energy_cuts,
        multiplier=multiplier,
        lpm_effect=lpm,
        interpolation_def=interpolation_def)

    brems = pp.parametrization.bremsstrahlung.KelnerKokoulinPetrukhin(
        particle_def=particle_def,
        medium=medium,
        energy_cuts=energy_cuts,
        multiplier=multiplier,
        lpm_effect=lpm)

    photo = pp.parametrization.photonuclear.AbramowiczLevinLevyMaor97Interpolant(
        particle_def=particle_def,
        medium=medium,
        energy_cuts=energy_cuts,
        multiplier=multiplier,
        shadow_effect=shadow_effect,
        interpolation_def=interpolation_def)

    photo2 = pp.parametrization.photonuclear.BezrukovBugaev(
        particle_def=particle_def,
        medium=medium,
        energy_cuts=energy_cuts,
        multiplier=multiplier,
        add_pertubative=add_pertubative)

    losses_params = [ioniz, epair, brems, photo2]

    muon_energy = 10**10  # MeV

    inch_to_cm = 2.54
    golden_ratio = 1.61803
    width = 29.7  # cm

    num_bins = 100
    v_bins = np.linspace(np.log10(500), np.log10(muon_energy), num_bins)
    v_bins_log = np.logspace(np.log10(500. / muon_energy), np.log10(1.),
                             num_bins)

    fig = plt.figure(figsize=(width / inch_to_cm,
                              width / inch_to_cm / golden_ratio))
    ax = fig.add_subplot(111)

    for idx, secondary_list in enumerate(list_secondary_energies):
        ax.hist(secondary_list,
                weights=np.ones(len(secondary_list)) / sum_hist,
                histtype='step',
                log=True,
                bins=v_bins,
                label=list_secondary_energies_label[idx])

    all_cross_sections = np.empty((len(losses_params), num_bins))

    for idx, param in enumerate(losses_params):
        all_cross_sections[idx] = np.array([
            param.differential_crosssection(muon_energy, v) * v
            for v in v_bins_log
        ])

    sum_cross_sections = np.sum(all_cross_sections, axis=0)
    print(sum(all_cross_sections[np.isfinite(all_cross_sections)]))
    print(sum(sum_cross_sections[np.isfinite(sum_cross_sections)]))

    for cross_section in np.append(all_cross_sections, [sum_cross_sections],
                                   axis=0):
        ax.plot(v_bins,
                cross_section /
                sum(sum_cross_sections[np.isfinite(sum_cross_sections)]),
                drawstyle="steps-pre")

    # ax.set_xscale("log")
    minor_locator = AutoMinorLocator()
    ax.xaxis.set_minor_locator(minor_locator)
    ax.legend()
    ax.set_xlabel(r'energy loss / log($E$/MeV)')
    ax.set_ylabel(r'$N$')

    ax.set_ylim(ymin=1e-8)
    ax.set_yscale("log")
    ax.legend()
    fig.savefig("theory_curve.pdf")
Пример #10
0
def propagate_muons():

    # start_time = time.time()

    mu_def = pp.particle.MuMinusDef.get()
    geometry = pp.geometry.Sphere(pp.Vector3D(), 1.e20, 0.0)
    ecut = 500
    vcut = 5e-2

    sector_def = pp.SectorDefinition()
    sector_def.cut_settings = pp.EnergyCutSettings(ecut, vcut)
    sector_def.medium = pp.medium.StandardRock(1.0)
    sector_def.geometry = geometry
    sector_def.scattering_model = pp.scattering.ScatteringModel.NoScattering
    sector_def.crosssection_defs.brems_def.lpm_effect = False
    sector_def.crosssection_defs.epair_def.lpm_effect = False
    # sector_def.crosssection_defs.photo_def.parametrization = pp.parametrization.photonuclear.PhotoParametrization.BezrukovBugaev
    # sector_def.do_stochastic_loss_weighting = True
    # sector_def.stochastic_loss_weighting = -0.1

    detector = geometry

    interpolation_def = pp.InterpolationDef()
    interpolation_def.path_to_tables = "~/.local/share/PROPOSAL/tables"

    prop = pp.Propagator(mu_def, [sector_def], detector, interpolation_def)

    statistics_log = 4
    statistics = int(10**statistics_log)
    propagation_length = 1e4  # cm
    E_min_log = 10.0
    E_max_log = 10.0
    spectral_index = 1.0
    pp.RandomGenerator.get().set_seed(1234)

    # muon_energies = np.logspace(E_min_log, E_max_log, statistics)
    # muon_energies = power_law_sampler(spectral_index, 10**E_min_log, 10**E_max_log, statistics)
    muon_energies = np.ones(statistics) * 10**10

    epair_secondary_energy = []
    brems_secondary_energy = []
    ioniz_secondary_energy = []
    photo_secondary_energy = []

    progress = ProgressBar(statistics, pacman=True)
    progress.start()

    for mu_energy in muon_energies:
        progress.update()

        prop.particle.position = pp.Vector3D(0, 0, 0)
        prop.particle.direction = pp.Vector3D(0, 0, -1)
        prop.particle.propagated_distance = 0
        prop.particle.energy = mu_energy

        secondarys = prop.propagate(propagation_length)

        for sec in secondarys:
            log_sec_energy = math.log10(sec.energy)

            if sec.id == pp.particle.Data.Epair:
                epair_secondary_energy.append(log_sec_energy)
            if sec.id == pp.particle.Data.Brems:
                brems_secondary_energy.append(log_sec_energy)
            if sec.id == pp.particle.Data.DeltaE:
                ioniz_secondary_energy.append(log_sec_energy)
            if sec.id == pp.particle.Data.NuclInt:
                photo_secondary_energy.append(log_sec_energy)

    # =========================================================
    #   Write
    # =========================================================

    dir_prefix = ""
    np.savez(os.path.join(
        dir_prefix, 'data_sec_dist_{}_{}_Emin_{}_Emax_{}'.format(
            prop.particle.particle_def.name, sector_def.medium.name.lower(),
            E_min_log, E_max_log, ecut, vcut)),
             brems=brems_secondary_energy,
             epair=epair_secondary_energy,
             photo=photo_secondary_energy,
             ioniz=ioniz_secondary_energy,
             statistics=[statistics],
             E_min=[E_min_log],
             E_max=[E_max_log],
             spectral_index=[spectral_index],
             distance=[prop.particle.propagated_distance / 100],
             medium_name=[sector_def.medium.name.lower()],
             particle_name=[prop.particle.particle_def.name],
             ecut=[ecut],
             vcut=[vcut])
Пример #11
0
def create_cross_section_calculators(path_to_inerpolation_tables='~/.local/share/PROPOSAL/tables',
                                    brems_param_name='BremsKelnerKokoulinPetrukhin',
                                    epair_param_name='EpairKelnerKokoulinPetrukhin',
                                    photo_param_name='PhotoAbramowiczLevinLevyMaor97'):
    mu = pp.particle.MuMinusDef.get()
    medium = pp.medium.Ice(1.0)
    cuts = pp.EnergyCutSettings(-1, -1)
    multiplier_all = 1.0
    lpm = True
    interpolation_def = pp.InterpolationDef()
    interpolation_def.path_to_tables = path_to_inerpolation_tables
    interpolation_def.path_to_tables_readonly = path_to_inerpolation_tables

    brems_param = pp.parametrization.bremsstrahlung.BremsFactory.get().get_enum_from_str(brems_param_name)
    brems_def = pp.parametrization.bremsstrahlung.BremsDefinition()
    brems_def.parametrization = brems_param
    brems_def.lpm_effect = lpm
    brems_def.multiplier = multiplier_all
    brems = pp.parametrization.bremsstrahlung.BremsFactory.get().create_bremsstrahlung_interpol(
        mu, medium, cuts, brems_def, interpolation_def)
    # brems = pp.crosssection.BremsInterpolant(
    #             pp.parametrization.bremsstrahlung.KelnerKokoulinPetrukhin(
    #                 mu,
    #                 medium,
    #                 cuts,
    #                 multiplier_all,
    #                 lpm),
    #             interpolation_def)

    epair_param = pp.parametrization.pairproduction.EpairFactory.get().get_enum_from_str(epair_param_name)
    epair_def = pp.parametrization.pairproduction.EpairDefinition()
    epair_def.parametrization = epair_param
    epair_def.lpm_effect = lpm
    epair_def.multiplier = multiplier_all
    epair = pp.parametrization.pairproduction.EpairFactory.get().create_pairproduction_interpol(
        mu, medium, cuts, epair_def, interpolation_def)
    # epair = pp.crosssection.EpairInterpolant(
    #             pp.parametrization.pairproduction.KelnerKokoulinPetrukhinInterpolant(
    #                 mu,
    #                 medium,
    #                 cuts,
    #                 multiplier_all,
    #                 lpm,
    #                 interpolation_def),
    #             interpolation_def)

    photo_param = pp.parametrization.photonuclear.PhotoFactory.get().get_enum_from_str(photo_param_name)
    photo_def = pp.parametrization.photonuclear.PhotoDefinition()
    photo_def.parametrization = photo_param
    photo_def.multiplier = multiplier_all
    photo = pp.parametrization.photonuclear.PhotoFactory.get().create_photonuclear_interpol(
        mu, medium, cuts, photo_def, interpolation_def)
    # photo = pp.crosssection.PhotoInterpolant(
    #             pp.parametrization.photonuclear.AbramowiczLevinLevyMaor97Interpolant(
    #                 mu,
    #                 medium,
    #                 cuts,
    #                 multiplier_all,
    #                 pp.parametrization.photonuclear.ShadowButkevichMikhailov(),
    #                 interpolation_def),
    #             interpolation_def)

    ioniz = pp.crosssection.IonizInterpolant(
                pp.parametrization.ionization.Ionization(
                    mu,
                    medium,
                    cuts,
                    lpm),
                interpolation_def)
    return [ioniz, brems, epair, photo]
Пример #12
0
def propagate_muons():

    mu_def = pp.particle.MuMinusDef.get()
    geometry = pp.geometry.Sphere(pp.Vector3D(), 1.e20, 0.0)
    ecut = 500
    vcut = -1

    sector_def = pp.SectorDefinition()
    sector_def.cut_settings = pp.EnergyCutSettings(ecut, vcut)
    sector_def.medium = pp.medium.Ice(1.0)
    sector_def.geometry = geometry
    sector_def.scattering_model = pp.scattering.ScatteringModel.NoScattering
    sector_def.crosssection_defs.brems_def.lpm_effect = True
    sector_def.crosssection_defs.epair_def.lpm_effect = True

    detector = geometry

    interpolation_def = pp.InterpolationDef()
    interpolation_def.path_to_tables = "tables/"

    #initialize propagator without mupairproduction
    prop_nomupair = pp.Propagator(mu_def, [sector_def], detector, interpolation_def)

    #initialize propagator with mupairproduction
    sector_def.crosssection_defs.mupair_def.parametrization = pp.parametrization.mupairproduction.MupairParametrization.KelnerKokoulinPetrukhin
    sector_def.crosssection_defs.mupair_def.particle_output = False
    prop = pp.Propagator(mu_def, [sector_def], detector, interpolation_def)


    # for rho sampling
    param_defs_mupair = [mu_def, sector_def.medium, sector_def.cut_settings, 1.0, True, interpolation_def]
    param_mupair = pp.parametrization.mupairproduction.KelnerKokoulinPetrukhinInterpolant(*param_defs_mupair)

    statistics_log = 5
    statistics = int(10**statistics_log)
    propagation_length = 1e20 # cm
    E_log = 8.0
    pp.RandomGenerator.get().set_seed(1234)

    ### PRIMARY MUON PROPAGATION ###

    muon_energies = np.ones(statistics)*10**E_log
    epair_secondary_energy = []
    brems_secondary_energy = []
    ioniz_secondary_energy = []
    photo_secondary_energy = []

    mpair_secondary_energy = []
    mpair_primary_energy = []

    print("Propagate primary muons...")
    progress = ProgressBar(statistics, pacman=True)
    progress.start()

    for mu_energy in muon_energies:
        progress.update()

        prop.particle.position = pp.Vector3D(0, 0, 0)
        prop.particle.direction = pp.Vector3D(0, 0, -1)
        prop.particle.propagated_distance = 0
        prop.particle.energy = mu_energy

        secondarys = prop.propagate(propagation_length)

        for sec in secondarys:
            sec_energy = sec.energy

            if sec.id == pp.particle.Data.Epair:
                epair_secondary_energy.append(sec_energy)
            elif sec.id == pp.particle.Data.Brems:
                brems_secondary_energy.append(sec_energy)
            elif sec.id == pp.particle.Data.DeltaE:
                ioniz_secondary_energy.append(sec_energy)
            elif sec.id == pp.particle.Data.NuclInt:
                photo_secondary_energy.append(sec_energy)
            elif sec.id == pp.particle.Data.MuPair:
                mpair_secondary_energy.append(sec_energy)
                mpair_primary_energy.append(sec.parent_particle_energy)
    #statistics:
    num_all = len(brems_secondary_energy) + len(epair_secondary_energy) + len(photo_secondary_energy) + len(ioniz_secondary_energy) + len(mpair_secondary_energy)
    ene_all = sum(brems_secondary_energy) + sum(epair_secondary_energy) + sum(photo_secondary_energy) + sum(ioniz_secondary_energy) + sum(mpair_secondary_energy)

    print("Number:")
    print("Brems: ", len(brems_secondary_energy), len(brems_secondary_energy)/num_all)
    print("Epair: ", len(epair_secondary_energy), len(epair_secondary_energy)/num_all)
    print("photo: ", len(photo_secondary_energy), len(photo_secondary_energy)/num_all)
    print("Ioniz: ", len(ioniz_secondary_energy), len(ioniz_secondary_energy)/num_all)
    print("MPair: ", len(mpair_secondary_energy), len(mpair_secondary_energy)/num_all)
    print("Energies:")

    print("Brems ", sum(brems_secondary_energy), sum(brems_secondary_energy)/ene_all)
    print("Epair: ", sum(epair_secondary_energy), sum(epair_secondary_energy)/ene_all)
    print("photo: ", sum(photo_secondary_energy), sum(photo_secondary_energy)/ene_all)
    print("Ioniz: ", sum(ioniz_secondary_energy), sum(ioniz_secondary_energy)/ene_all)
    print("MPair: ", sum(mpair_secondary_energy), sum(mpair_secondary_energy)/ene_all)

    plt.rcParams.update(params)

    fig_all = plt.figure(
        figsize=(width, 4)
    )

    x_space = np.logspace(min(np.log10(np.concatenate((ioniz_secondary_energy,brems_secondary_energy,photo_secondary_energy,epair_secondary_energy,mpair_secondary_energy)))), E_log, 100)

    ax_all = fig_all.add_subplot(111)
    ax_all.hist(
        [
            ioniz_secondary_energy,
            photo_secondary_energy,
            brems_secondary_energy,
            epair_secondary_energy,
            mpair_secondary_energy,
            np.concatenate((
                ioniz_secondary_energy,
                brems_secondary_energy,
                photo_secondary_energy,
                epair_secondary_energy,
                mpair_secondary_energy)
            )
        ],
        histtype='step',
        log=True,
        bins=x_space,
        label=['Ionization', 'Photonuclear', 'Bremsstrahlung', r'$e$ pair production', r'$\mu$ pair production', 'Sum'],
        color = ['C3', 'C2', 'C1', 'C0', 'C4', 'C7'],
        zorder = 3
    )

    plt.xscale('log')
    #minor_locator = AutoMinorLocator()
    #ax_all.xaxis.set_minor_locator(minor_locator)
    ax_all.legend(loc='best')
    ax_all.set_xlabel(r'$ E \cdot v \,/\, \mathrm{MeV} $')
    ax_all.set_ylabel(r'Frequency')
    #plt.xlim(left=2.5)
    plt.grid(grid_conf)
    fig_all.tight_layout()
    fig_all.savefig("build/spectrum_mupair.pdf",bbox_inches='tight')
    plt.clf()

    epair_old = epair_secondary_energy
    brems_old = brems_secondary_energy
    ioniz_old = ioniz_secondary_energy
    photo_old = photo_secondary_energy
    mpair_old = mpair_secondary_energy

    ### SECONDARY MUON PROPAGATION ###
    secondary_muon_energy = []

    for E, nu in zip(mpair_primary_energy, mpair_secondary_energy):
        rho = param_mupair.Calculaterho(E, nu/E, np.random.rand(), np.random.rand())
        secondary_muon_energy.append( 0.5 * nu * (1. + rho) )
        secondary_muon_energy.append( 0.5 * nu * (1. - rho) )


    epair_secondary_energy = []
    brems_secondary_energy = []
    ioniz_secondary_energy = []
    photo_secondary_energy = []
    mpair_secondary_energy = []

    print("Propagate secondary muons...")
    progress = ProgressBar(len(secondary_muon_energy), pacman=True)
    progress.start()

    for mu_energy in secondary_muon_energy:
        progress.update()

        prop.particle.position = pp.Vector3D(0, 0, 0)
        prop.particle.direction = pp.Vector3D(0, 0, -1)
        prop.particle.propagated_distance = 0
        prop.particle.energy = mu_energy

        secondarys = prop.propagate(propagation_length)

        for sec in secondarys:
            sec_energy = sec.energy

            if sec.id == pp.particle.Data.Epair:
                epair_secondary_energy.append(sec_energy)
            elif sec.id == pp.particle.Data.Brems:
                brems_secondary_energy.append(sec_energy)
            elif sec.id == pp.particle.Data.DeltaE:
                ioniz_secondary_energy.append(sec_energy)
            elif sec.id == pp.particle.Data.NuclInt:
                photo_secondary_energy.append(sec_energy)
            elif sec.id == pp.particle.Data.MuPair:
                mpair_secondary_energy.append(sec_energy)

    print("Number:")
    print("Brems: ", len(brems_secondary_energy), len(brems_secondary_energy)/num_all)
    print("Epair: ", len(epair_secondary_energy), len(epair_secondary_energy)/num_all)
    print("photo: ", len(photo_secondary_energy), len(photo_secondary_energy)/num_all)
    print("Ioniz: ", len(ioniz_secondary_energy), len(ioniz_secondary_energy)/num_all)
    print("MPair: ", len(mpair_secondary_energy), len(mpair_secondary_energy)/num_all)
    print("Energies:")

    print("Brems ", sum(brems_secondary_energy), sum(brems_secondary_energy)/ene_all)
    print("Epair: ", sum(epair_secondary_energy), sum(epair_secondary_energy)/ene_all)
    print("photo: ", sum(photo_secondary_energy), sum(photo_secondary_energy)/ene_all)
    print("Ioniz: ", sum(ioniz_secondary_energy), sum(ioniz_secondary_energy)/ene_all)
    print("MPair: ", sum(mpair_secondary_energy), sum(mpair_secondary_energy)/ene_all)


    ### PROPAGATION WITHOUT MUPAIRPRODUCTION

    muon_energies = np.ones(statistics)*10**E_log
    epair_secondary_energy_nomupair = []
    brems_secondary_energy_nomupair = []
    ioniz_secondary_energy_nomupair = []
    photo_secondary_energy_nomupair = []

    print("Propagate muons without MuPairProduction...")
    progress = ProgressBar(statistics, pacman=True)
    progress.start()

    for mu_energy in muon_energies:
        progress.update()

        prop_nomupair.particle.position = pp.Vector3D(0, 0, 0)
        prop_nomupair.particle.direction = pp.Vector3D(0, 0, -1)
        prop_nomupair.particle.propagated_distance = 0
        prop_nomupair.particle.energy = mu_energy

        secondarys = prop_nomupair.propagate(propagation_length)

        for sec in secondarys:
            sec_energy = sec.energy

            if sec.id == pp.particle.Data.Epair:
                epair_secondary_energy_nomupair.append(sec_energy)
            elif sec.id == pp.particle.Data.Brems:
                brems_secondary_energy_nomupair.append(sec_energy)
            elif sec.id == pp.particle.Data.DeltaE:
                ioniz_secondary_energy_nomupair.append(sec_energy)
            elif sec.id == pp.particle.Data.NuclInt:
                photo_secondary_energy_nomupair.append(sec_energy)
            elif sec.id == pp.particle.Data.MuPair:
                print("Something went wrong")


    # Comparison plot

    plt.rcParams.update(params)

    fig_all = plt.figure(
        figsize=(width, 4)
    )

    gs = matplotlib.gridspec.GridSpec(2, 1, height_ratios=[4, 1], hspace=0.1)


    x_space = np.logspace(min(np.log10(np.concatenate((ioniz_secondary_energy_nomupair,photo_secondary_energy_nomupair,brems_secondary_energy_nomupair,epair_secondary_energy_nomupair)))), E_log, 100)
    
    ax_all = fig_all.add_subplot(gs[0])
    ax_all.hist(
        [
            ioniz_secondary_energy,
            photo_secondary_energy,
            brems_secondary_energy,
            epair_secondary_energy,
            mpair_secondary_energy
        ],
        histtype='step',
        color = ['C3', 'C2', 'C1', 'C0', 'C4'],
        log=True,
        bins=x_space,
        zorder = 3,
        linestyle = 'dashed',
    )

    ax_all.hist(
        [
            ioniz_secondary_energy_nomupair,
            photo_secondary_energy_nomupair,
            brems_secondary_energy_nomupair,
            epair_secondary_energy_nomupair,
            np.concatenate((
                ioniz_secondary_energy_nomupair,
                brems_secondary_energy_nomupair,
                photo_secondary_energy_nomupair,
                epair_secondary_energy_nomupair)
            )
        ],
        color = ['C3', 'C2', 'C1', 'C0', 'C7'],
        label=['Ionization', 'Photonuclear', 'Bremsstrahlung', r'$e$ pair production', 'Sum'],
        histtype='step',
        log=True,
        bins=x_space,
        zorder = 4,
    )    

    ax_all.hist(
        [
            np.array([0])      
        ],
        color = ['C4'],
        label=[r'$\mu$ pair production'],
        histtype='step',
        log=True,
        bins=x_space,
        zorder = 0,
    )   

    plt.xscale('log')
    #minor_locator = AutoMinorLocator()
    #ax_all.xaxis.set_minor_locator(minor_locator)
    ax_all.legend(loc='best')
    ax_all.set_ylabel(r'Frequency')
    #plt.xlim(left=2.5)
    plt.grid(grid_conf)
    plt.setp(ax_all.get_xticklabels(), visible=False)
    plt.tick_params(
        axis='x',          # changes apply to the x-axis
        which='both',      # both major and minor ticks are affected
        bottom=False,      # ticks along the bottom edge are off
        top=False,         # ticks along the top edge are off
        labelbottom=False
    ) # labels along the bottom edge are off

    ax_all = fig_all.add_subplot(gs[1], sharex=ax_all)

    hist_1, bin_edges_1 = np.histogram(np.concatenate((ioniz_secondary_energy_nomupair,brems_secondary_energy_nomupair,photo_secondary_energy_nomupair,epair_secondary_energy_nomupair)),
                                        bins = x_space)

    hist_2, bin_edges_2 = np.histogram(np.concatenate((epair_old, ioniz_old, brems_old, photo_old, ioniz_secondary_energy,photo_secondary_energy,brems_secondary_energy,epair_secondary_energy,mpair_secondary_energy)),
                                        bins = x_space)    

    print(np.shape(x_space))

    print(np.shape(hist_1))

    ax_all.step(x_space[1:], hist_1/hist_2, where='pre', color='C4')
    #ax_all.bar(x_space[:-1], hist_1/hist_2, width=np.diff(x_space), align='edge', fill=False)

    ax_all.set_xlabel(r'$ E \cdot v \,/\, \mathrm{MeV} $')
    ax_all.set_ylabel(r'ratio')
    plt.ylim(0.9, 1.1)
    plt.grid(grid_conf)
    ax_all.axhline(y=1, linewidth=0.5, zorder=0, C = 'C7')

    fig_all.tight_layout()
    fig_all.savefig("build/spectrum_mupair_secondary_comparison.pdf",bbox_inches='tight')
    plt.clf()


    # Plot particles from secondary spectrum

    plt.rcParams.update(params)

    fig_all = plt.figure(
        figsize=(width, 4)
    )

    x_space = np.logspace(min(np.log10(np.concatenate((ioniz_secondary_energy,brems_secondary_energy,photo_secondary_energy,epair_secondary_energy,mpair_secondary_energy)))), E_log, 100)

    ax_all = fig_all.add_subplot(111)
    ax_all.hist(
        [
            ioniz_secondary_energy,
            photo_secondary_energy,
            brems_secondary_energy,
            epair_secondary_energy,
            mpair_secondary_energy,
            np.concatenate((
                ioniz_secondary_energy,
                brems_secondary_energy,
                photo_secondary_energy,
                epair_secondary_energy,
                mpair_secondary_energy)
            )
        ],
        histtype='step',
        log=True,
        bins=x_space,
        label=['Ionization', 'Photonuclear', 'Bremsstrahlung', r'$e$ pair production', r'$\mu$ pair production', 'Sum'],
        color = ['C3', 'C2', 'C1', 'C0', 'C4', 'C7'],
        zorder = 3
    )

    plt.xscale('log')
    #minor_locator = AutoMinorLocator()
    #ax_all.xaxis.set_minor_locator(minor_locator)
    ax_all.legend(loc='best')
    ax_all.set_xlabel(r'$ E \cdot v \,/\, \mathrm{MeV} $')
    ax_all.set_ylabel(r'Frequency')
    #plt.xlim(left=2.5)
    plt.grid(grid_conf)
    fig_all.tight_layout()
    fig_all.savefig("build/spectrum_mupair_secondary.pdf",bbox_inches='tight')
    plt.clf()
Пример #13
0
def propagate_muons():

    # start_time = time.time()

    mu_def = pp.particle.EPlusDef.get()
    geometry = pp.geometry.Sphere(pp.Vector3D(), 1.e20, 0.0)
    ecut = 500
    vcut = -1

    sector_def = pp.SectorDefinition()
    sector_def.do_continuous_randomization = False
    sector_def.cut_settings = pp.EnergyCutSettings(ecut, vcut)
    sector_def.medium = pp.medium.StandardRock(1.0)
    sector_def.geometry = geometry
    sector_def.scattering_model = pp.scattering.ScatteringModel.NoScattering
    #sector_def.crosssection_defs.brems_def.lpm_effect = True
    #sector_def.crosssection_defs.epair_def.lpm_effect = False
    sector_def.crosssection_defs.annihilation_def.parametrization = pp.parametrization.annihilation.AnnihilationParametrization.Heitler
    sector_def.crosssection_defs.ioniz_def.parametrization = pp.parametrization.ionization.IonizParametrization.IonizBergerSeltzerBhabha
    sector_def.crosssection_defs.brems_def.parametrization = pp.parametrization.bremsstrahlung.BremsParametrization.ElectronScreening
    # sector_def.do_stochastic_loss_weighting = True
    # sector_def.stochastic_loss_weighting = -0.1

    detector = geometry

    interpolation_def = pp.InterpolationDef()
    interpolation_def.path_to_tables = "~/.local/share/PROPOSAL/tables"

    prop = pp.Propagator(mu_def, [sector_def], detector, interpolation_def)

    statistics_log = 5
    statistics = int(10**statistics_log)
    propagation_length = 1e10  # cm
    E_min_log = 8.0
    E_max_log = 8.0
    spectral_index = 1
    pp.RandomGenerator.get().set_seed(1000)

    #muon_energies = np.logspace(E_min_log, E_max_log, statistics)
    muon_energies = power_law_sampler(spectral_index, 10**E_min_log,
                                      10**E_max_log, statistics)
    #muon_energies = np.ones(statistics)*10**10
    epair_secondary_energy = []
    brems_secondary_energy = []
    ioniz_secondary_energy = []
    photo_secondary_energy = []
    annihilation_secondary_energy = []

    plot_energy_histogram(
        np.log10(muon_energies), 'energyhist_{}_{}_Emin_{}_Emax_{}.pdf'.format(
            prop.particle.particle_def.name, sector_def.medium.name.lower(),
            E_min_log, E_max_log, ecut, vcut))

    progress = ProgressBar(statistics, pacman=True)
    progress.start()

    for mu_energy in muon_energies:
        progress.update()

        prop.particle.position = pp.Vector3D(0, 0, 0)
        prop.particle.direction = pp.Vector3D(0, 0, -1)
        prop.particle.propagated_distance = 0
        prop.particle.energy = mu_energy

        secondarys = prop.propagate(propagation_length)

        skip_next = False

        for sec in secondarys:
            if (skip_next):
                skip_next = False
                continue

            if (sec.energy > 0):
                log_sec_energy = math.log10(sec.energy)
            else:
                print(sec.energy)
                print(sec.id)
            if sec.id == pp.particle.Data.Epair:
                epair_secondary_energy.append(log_sec_energy)
            elif sec.id == pp.particle.Data.Brems:
                brems_secondary_energy.append(log_sec_energy)
            elif sec.id == pp.particle.Data.DeltaE:
                ioniz_secondary_energy.append(log_sec_energy)
            elif sec.id == pp.particle.Data.NuclInt:
                photo_secondary_energy.append(log_sec_energy)
            else:
                annihilation_secondary_energy.append(
                    math.log10(sec.parent_particle_energy))
                skip_next = True  # do not include the second photon as well...

    # =========================================================
    #   Write
    # =========================================================

    dir_prefix = ""
    np.savez(os.path.join(
        dir_prefix, 'data_sec_dist_{}_{}_Emin_{}_Emax_{}'.format(
            prop.particle.particle_def.name, sector_def.medium.name.lower(),
            E_min_log, E_max_log, ecut, vcut)),
             brems=brems_secondary_energy,
             epair=epair_secondary_energy,
             photo=photo_secondary_energy,
             ioniz=ioniz_secondary_energy,
             annihilation=annihilation_secondary_energy,
             statistics=[statistics],
             statistics_log=[statistics_log],
             E_min=[E_min_log],
             E_max=[E_max_log],
             spectral_index=[spectral_index],
             distance=[prop.particle.propagated_distance / 100],
             medium_name=[sector_def.medium.name.lower()],
             particle_name=[prop.particle.particle_def.name],
             ecut=[ecut],
             vcut=[vcut])

    #statistics:
    sum_all = np.sum(brems_secondary_energy) + np.sum(
        epair_secondary_energy) + np.sum(photo_secondary_energy) + np.sum(
            ioniz_secondary_energy)
    num_all = len(brems_secondary_energy) + len(epair_secondary_energy) + len(
        photo_secondary_energy) + len(ioniz_secondary_energy)
    print(num_all)
    print("Brem: ", len(brems_secondary_energy),
          len(brems_secondary_energy) / num_all)
    print("Epair: ", len(epair_secondary_energy),
          len(epair_secondary_energy) / num_all)
    print("photo: ", len(photo_secondary_energy),
          len(photo_secondary_energy) / num_all)
    print("Ioniz: ", len(ioniz_secondary_energy),
          len(ioniz_secondary_energy) / num_all)

    plot_secondary_spectrum('data_sec_dist_{}_{}_Emin_{}_Emax_{}.npz'.format(
        prop.particle.particle_def.name, sector_def.medium.name.lower(),
        E_min_log, E_max_log, ecut, vcut))
Пример #14
0
def plot_brems(medium, plotname, energy):

    eminus = pp.particle.EMinusDef.get()
    cuts = pp.EnergyCutSettings(-1, -1)  # ecut, vcut
    cuts_total = pp.EnergyCutSettings(1, -1)  # ecut, vcut

    dEdx_photo = []
    dNdx_photo = []

    interpolation_def = pp.InterpolationDef()

    # =========================================================
    # 	Constructor args for parametrizations
    #
    #   - particle
    #   - medium
    #   - cut
    #   - multiplier
    #   - lpm effect
    #   - interpolation definition
    # =========================================================

    param_defs = [
        eminus,
        medium,
        cuts,
        1.0,
        False,
    ]

    param_defs_total = [
        eminus,
        medium,
        cuts_total,
        1.0,
        False,
    ]

    # =========================================================
    #   Selection of cross sections
    # =========================================================

    params = []
    params_total = []

    def wrapper(func):
        params.append(func(*param_defs))
        params_total.append(func(*param_defs_total))

    wrapper(parametrization.bremsstrahlung.ElectronScreening)
    wrapper(parametrization.bremsstrahlung.CompleteScreening)
    #wrapper(parametrization.bremsstrahlung.KelnerKokoulinPetrukhin)
    #wrapper(parametrization.bremsstrahlung.PetrukhinShestakov)
    wrapper(parametrization.bremsstrahlung.AndreevBezrukovBugaev)
    wrapper(parametrization.bremsstrahlung.SandrockSoedingreksoRhode)

    # =========================================================
    # 	Create x sections out of their parametrizations
    # =========================================================

    crosssections = []
    crosssections_total = []

    for param in params:
        crosssections.append(pp.crosssection.BremsIntegral(param, ))

    for param in params_total:
        crosssections_total.append(pp.crosssection.BremsIntegral(param, ))

    # print(crosssections[0])

    # =========================================================
    # 	Calculate DE/dx at the given energies
    # =========================================================

    for cross, cross_total in zip(crosssections, crosssections_total):
        dEdx = []
        dNdx = []
        for E in energy:
            dEdx.append(cross.calculate_dEdx(E) / E)
            dNdx.append(cross_total.calculate_dNdx(E))

        dEdx_photo.append(dEdx)
        dNdx_photo.append(dNdx)
        # print(dEdx)

    # =========================================================
    # 	Plot dEdx
    # =========================================================

    colors = np.array(
        ['C0', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9'])

    fig = plt.figure()
    gs = mpl.gridspec.GridSpec(2, 1, height_ratios=[1, 1])

    ax = fig.add_subplot(gs[0])

    for dEdx, param in zip(dEdx_photo, params):
        ax.loglog(energy, dEdx, linestyle='-', label="".join([param.name[5:]]))

    ax.axvline(50, color='r', lw=0.5, ls='-.')
    #ax.axvline(0.5, color='b', lw=0.5, ls='-.')
    ax.set_ylabel(r'-1/E dEdx / $\rm{g}^{-1} \rm{cm}^2$')

    ax.legend(loc='best')

    # ====[ ratio ]============================================

    ax = fig.add_subplot(gs[1], sharex=ax)

    start = 0
    for i in np.linspace(1,
                         len(crosssections) - 1,
                         len(crosssections) - 1,
                         dtype=int):
        ax.semilogx(
            energy[start:],
            np.array(dEdx_photo[i][start:]) / np.array(dEdx_photo[0][start:]),
            linestyle='-',
            color=colors[i],
            label="{} / {}".format(
                "".join([c for c in params[i].name[1:] if c.isupper()]),
                "".join([c for c in params[0].name[1:] if c.isupper()])))

    ax.xaxis.grid(which='major', ls=":")
    ax.yaxis.grid(which='minor', ls=":")
    #ax.set_ylim(top=1.1, bottom=0.7)
    #ax.set_xlim(left=1e1, right=1e9)

    ax.set_xlabel(r'$E$ / MeV')
    ax.set_ylabel(r'ratio')

    ax.axhline(1.0, color='k', lw=0.5, ls='-.')

    ax.axvline(50, color='r', lw=0.5, ls='-.')

    ax.legend(loc='best')
    fig.tight_layout()
    fig.savefig('brems_dEdx_' + plotname + '.pdf')
    plt.show()

    plt.clf()

    # =========================================================
    # 	Plot dNdx
    # =========================================================

    colors = np.array(
        ['C0', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9'])

    fig = plt.figure()
    gs = mpl.gridspec.GridSpec(2, 1, height_ratios=[1, 1])

    ax = fig.add_subplot(gs[0])

    for dNdx, param in zip(dNdx_photo, params_total):
        ax.loglog(energy, dNdx, linestyle='-', label="".join([param.name[5:]]))

    ax.axvline(50, color='r', lw=0.5, ls='-.')
    ax.set_ylabel(r'dNdx / $\rm{g}^{-1} \rm{cm}^2$')

    ax.legend(loc='best')

    # ====[ ratio ]============================================

    ax = fig.add_subplot(gs[1], sharex=ax)

    start = 0
    for i in np.linspace(1,
                         len(crosssections_total) - 1,
                         len(crosssections_total) - 1,
                         dtype=int):
        ax.semilogx(
            energy[start:],
            np.array(dNdx_photo[i][start:]) / np.array(dNdx_photo[0][start:]),
            linestyle='-',
            color=colors[i],
            label="{} / {}".format(
                "".join([c for c in params[i].name[1:] if c.isupper()]),
                "".join([c for c in params[0].name[1:] if c.isupper()])))

    ax.xaxis.grid(which='major', ls=":")
    ax.yaxis.grid(which='minor', ls=":")
    #ax.set_ylim(top=1.1, bottom=0.7)
    #ax.set_xlim(left=1e1, right=1e9)

    ax.set_xlabel(r'$E$ / MeV')
    ax.set_ylabel(r'ratio')

    ax.axhline(1.0, color='k', lw=0.5, ls='-.')

    ax.axvline(50, color='r', lw=0.5, ls='-.')

    ax.legend(loc='best')
    fig.tight_layout()
    fig.savefig('brems_dNdx_' + plotname + '.pdf')
    plt.show()
Пример #15
0
def propagate_muons():

    mu_def = pp.particle.MuMinusDef.get()
    geometry = pp.geometry.Sphere(pp.Vector3D(), 1.e20, 0.0)
    ecut = 500
    vcut = 5e-2

    sector_def = pp.SectorDefinition()
    sector_def.cut_settings = pp.EnergyCutSettings(ecut, vcut)
    sector_def.medium = pp.medium.Ice(1.0)
    sector_def.geometry = geometry
    sector_def.scattering_model = pp.scattering.ScatteringModel.NoScattering
    sector_def.crosssection_defs.brems_def.lpm_effect = True
    sector_def.crosssection_defs.epair_def.lpm_effect = True

    detector = geometry

    interpolation_def = pp.InterpolationDef()
    interpolation_def.path_to_tables = "tables/"

    prop = pp.Propagator(mu_def, [sector_def], detector, interpolation_def)

    statistics = int(1e4)
    propagation_length = 1e20  # cm
    E_log = 8.0
    pp.RandomGenerator.get().set_seed(1234)

    muon_energies = np.ones(statistics) * 10**E_log
    epair_secondary_energy = []
    brems_secondary_energy = []
    ioniz_secondary_energy = []
    photo_secondary_energy = []

    progress = ProgressBar(statistics, pacman=True)
    progress.start()

    for mu_energy in muon_energies:
        progress.update()

        prop.particle.position = pp.Vector3D(0, 0, 0)
        prop.particle.direction = pp.Vector3D(0, 0, -1)
        prop.particle.propagated_distance = 0
        prop.particle.energy = mu_energy

        secondarys = prop.propagate(propagation_length)

        for sec in secondarys:
            sec_energy = sec.energy

            if sec.id == pp.particle.Data.Epair:
                epair_secondary_energy.append(sec_energy)
            elif sec.id == pp.particle.Data.Brems:
                brems_secondary_energy.append(sec_energy)
            elif sec.id == pp.particle.Data.DeltaE:
                ioniz_secondary_energy.append(sec_energy)
            elif sec.id == pp.particle.Data.NuclInt:
                photo_secondary_energy.append(sec_energy)

    #statistics:
    num_all = len(brems_secondary_energy) + len(epair_secondary_energy) + len(
        photo_secondary_energy) + len(ioniz_secondary_energy)
    ene_all = sum(brems_secondary_energy) + sum(epair_secondary_energy) + sum(
        photo_secondary_energy) + sum(ioniz_secondary_energy)

    print("Anzahl:")
    print("Brems: ", len(brems_secondary_energy),
          len(brems_secondary_energy) / num_all)
    print("Epair: ", len(epair_secondary_energy),
          len(epair_secondary_energy) / num_all)
    print("photo: ", len(photo_secondary_energy),
          len(photo_secondary_energy) / num_all)
    print("Ioniz: ", len(ioniz_secondary_energy),
          len(ioniz_secondary_energy) / num_all)
    print("Energie:")

    print("Brems ", sum(brems_secondary_energy),
          sum(brems_secondary_energy) / ene_all)
    print("Epair: ", sum(epair_secondary_energy),
          sum(epair_secondary_energy) / ene_all)
    print("photo: ", sum(photo_secondary_energy),
          sum(photo_secondary_energy) / ene_all)
    print("Ioniz: ", sum(ioniz_secondary_energy),
          sum(ioniz_secondary_energy) / ene_all)

    plt.rcParams.update(params)

    fig_all = plt.figure(figsize=(width, 4))

    tmp = np.concatenate((ioniz_secondary_energy, brems_secondary_energy,
                          photo_secondary_energy, epair_secondary_energy))
    tmp = tmp[tmp > 0]  # remove zero elements
    x_space = np.logspace(min(np.log10(tmp)), E_log, 100)

    ax_all = fig_all.add_subplot(111)
    ax_all.hist([
        ioniz_secondary_energy, photo_secondary_energy, brems_secondary_energy,
        epair_secondary_energy,
        np.concatenate((ioniz_secondary_energy, brems_secondary_energy,
                        photo_secondary_energy, epair_secondary_energy))
    ],
                histtype='step',
                log=True,
                bins=x_space,
                label=[
                    'Ionization', 'Photonuclear', 'Bremsstrahlung',
                    r'$e$ pair production', 'Sum'
                ],
                color=['C3', 'C2', 'C1', 'C0', 'C7'],
                zorder=3)

    plt.xscale('log')
    #minor_locator = AutoMinorLocator()
    #ax_all.xaxis.set_minor_locator(minor_locator)
    ax_all.legend(loc='best')
    ax_all.set_xlabel(r'$ E \cdot v \,/\, \mathrm{MeV} $')
    ax_all.set_ylabel(r'Frequency')
    #plt.xlim(left=2.5)
    plt.grid(grid_conf)
    fig_all.tight_layout()
    fig_all.savefig("build/spectrum.pdf", bbox_inches='tight')