Core functionality¶
MCEq.core
- core module¶
This module contains the main program features. Instantiating MCEq.core.MCEqRun
will initialize the data structures and particle tables, create and fill the
interaction and decay matrix and check if all information for the calculation
of inclusive fluxes in the atmosphere is available.
The preferred way to instantiate MCEq.core.MCEqRun
is:
from mceq_config import config
from MCEq.core import MCEqRun
import CRFluxModels as pm
mceq_run = MCEqRun(interaction_model='SIBYLL2.3c',
primary_model=(pm.HillasGaisser2012, "H3a"),
**config)
mceq_run.set_theta_deg(60.)
mceq_run.solve()
-
class
MCEq.core.
MCEqRun
(interaction_model, density_model, primary_model, theta_deg, adv_set, obs_ids, *args, **kwargs)[source]¶ Main class for handling the calculation.
This class is the main user interface for the caclulation. It will handle initialization and various error/configuration checks. The setup has to be accomplished before invoking the integration routine is
MCeqRun.solve()
. Changes of configuration, such as:- interaction model in
MCEqRun.set_interaction_model()
, - primary flux in
MCEqRun.set_primary_model()
, - zenith angle in
MCEqRun.set_theta_deg()
, - density profile in
MCEqRun.set_density_model()
, - member particles of the special
obs_
group inMCEqRun.set_obs_particles()
,
can be made on an active instance of this class, while calling
MCEqRun.solve()
subsequently to calculate the solution corresponding to the settings.The result can be retrieved by calling
MCEqRun.get_solution()
.Parameters: - interaction_model (string) – PDG ID of the particle
- density_model (string,sting,string) – model type, location, season
- primary_model (class, param_tuple) – classes derived from
CRFluxModels.PrimaryFlux
and its parameters as tuple - theta_deg (float) – zenith angle in degrees, measured positively from vertical direction
- adv_set (dict) – advanced settings, see
mceq_config
- obs_ids (list) – list of particle name strings. Those lepton decay
products will be scored in the special
obs_
categories
-
get_solution
(particle_name, mag=0.0, grid_idx=None, integrate=False)[source]¶ Retrieves solution of the calculation on the energy grid.
Some special prefixes are accepted for lepton names:
- the total flux of muons, muon neutrinos etc. from all sources/mothers
can be retrieved by the prefix
total_
, i.e.total_numu
- the conventional flux of muons, muon neutrinos etc. from all sources
can be retrieved by the prefix
conv_
, i.e.conv_numu
- correspondigly, the flux of leptons which originated from the decay
of a charged pion carries the prefix
pi_
and from a kaonk_
- conventional leptons originating neither from pion nor from kaon
decay are collected in a category without any prefix, e.g.
numu
ormu+
Parameters: - particle_name (str) – The name of the particle such, e.g.
total_mu+
for the total flux spectrum of positive muons orpr_antinumu
for the flux spectrum of prompt anti muon neutrinos - mag (float, optional) – ‘magnification factor’: the solution is
multiplied by
sol
- grid_idx (int, optional) – if the integrator has been configured to save
intermediate solutions on a depth grid, then
grid_idx
specifies the index of the depth grid for which the solution is retrieved. If not specified the flux at the surface is returned - integrate (bool, optional) – return averge particle number instead of
- flux (multiply by bin width) –
Returns: flux of particles on energy grid
e_grid
Return type: - the total flux of muons, muon neutrinos etc. from all sources/mothers
can be retrieved by the prefix
-
set_density_model
(density_config)[source]¶ Sets model of the atmosphere.
To choose, for example, a CORSIKA parametrization for the Southpole in January, do the following:
mceq_instance.set_density_model(('CORSIKA', 'PL_SouthPole', 'January'))
More details about the choices can be found in
MCEq.density_profiles
. Calling this method will issue a recalculation of the interpolation and the integration path.Parameters: density_config (tuple of strings) – (parametrization type, arguments)
-
set_interaction_model
(interaction_model, charm_model=None, force=False)[source]¶ Sets interaction model and/or an external charm model for calculation.
Decay and interaction matrix will be regenerated automatically after performing this call.
Parameters:
-
set_mod_pprod
(prim_pdg, sec_pdg, x_func, x_func_args, delay_init=False)[source]¶ Sets combination of projectile/secondary for error propagation.
The production spectrum of
sec_pdg
in interactions ofprim_pdg
is modified according to the function passed toInteractionYields.init_mod_matrix()
Parameters:
-
set_obs_particles
(obs_ids)[source]¶ Adds a list of mother particle strings which decay products should be scored in the special
obs_
category.Decay and interaction matrix will be regenerated automatically after performing this call.
Parameters: obs_ids (list of strings) – mother particle names
-
set_primary_model
(mclass, tag)[source]¶ Sets primary flux model.
This functions is quick and does not require re-generation of matrices.
Parameters: - interaction_model (
CRFluxModel.PrimaryFlux
) – reference - primary model class (to) –
- tag (tuple) – positional argument list for model class
- interaction_model (
-
set_single_primary_particle
(E, corsika_id)[source]¶ Set type and energy of a single primary nucleus to calculation of particle yields.
The functions uses the superposition theorem, where the flux of a nucleus with mass A and charge Z is modeled by using Z protons and A-Z neutrons at energy The nucleus type is defined via . For example iron has the CORSIKA ID 5226.
A continuous input energy range is allowed between .
Parameters:
-
set_theta_deg
(theta_deg)[source]¶ Sets zenith angle as seen from a detector.
Currently only ‘down-going’ angles (0-90 degrees) are supported.
Parameters: atm_config (tuple of strings) – (parametrization type, location string, season string)
-
solve
(**kwargs)[source]¶ Launches the solver.
The setting integrator in the config file decides which solver to launch, either the simple but accelerated explicit Euler solvers,
MCEqRun._forward_euler()
or, solvers from ODEPACKMCEqRun._odepack()
.Parameters: kwargs (dict) – Arguments are passed directly to the solver methods.
-
unset_mod_pprod
()[source]¶ Removes modifications from
MCEqRun.set_mod_pprod()
.
-
cs
= None¶ handler for cross-section data of type
MCEq.data.HadAirCrossSections
-
d
= None¶ (int) dimension of energy grid
-
ds
= None¶ handler for decay yield data of type
MCEq.data.DecayYields
-
e_grid
= None¶ (np.array) energy grid (bin centers)
-
modtab
= None¶ instance of
ParticleDataTool.SibyllParticleTable
– access to properties lists of particles, index translation etc.
-
pd
= None¶ instance of
ParticleDataTool.PYTHIAParticleData
– access to properties of particles, like mass and charge
-
y
= None¶ handler for decay yield data of type
MCEq.data.InteractionYields
- interaction model in
MCEq.data
— data management¶
This module includes code for bookkeeping, interfacing and validating data structures:
InteractionYields
manages particle interactions, obtained from sampling of various interaction modelsDecayYields
manages particle decays, obtained from sampling PYTHIA8 Monte CarloHadAirCrossSections
keeps information about the inelastic, cross-section of hadrons with air. Typically obtained from Monte Carlo.MCEqParticle
bundles different particle properties for simpler usage inMCEqRun
EdepZFactos
calculates energy-dependent spectrum weighted moments (Z-Factors)
-
class
MCEq.data.
DecayYields
(mother_list=None, fname=None)[source]¶ Class for managing the dictionary of decay yield matrices.
The class un-pickles a dictionary, which contains spectra of decay products/daughters, sampled from PYTHIA 8 Monte Carlo.
Parameters: mother_list (list, optional) – list of particle mothers from interaction model -
assign_d_idx
(mother, moidx, daughter, dtridx, dmat)[source]¶ Copies a subset, defined in tuples
moidx
anddtridx
from thedecay_matrix(mother,daughter)
intodmat
Parameters: - mother (int) – PDG ID of mother particle
- moidx (int,int) – tuple containing index range relative to the mothers’s energy grid
- daughter (int) – PDG ID of final state daughter/secondary particle
- dtridx (int,int) – tuple containing index range relative to the daughters’s energy grid
- dmat (numpy.array) – array reference to the decay matrix
-
daughters
(mother)[source]¶ Checks if
mother
decays and returns the list of daughter particles.Parameters: mother (int) – PDG ID of projectile particle Returns: PDG IDs of daughter particles Return type: list
-
get_d_matrix
(mother, daughter)[source]¶ Returns a
DIM x DIM
decay matrix.Parameters: Returns: decay matrix
Return type: Note
In the current version, the matrices have to be multiplied by the bin widths. In later versions they will be stored with the multiplication carried out.
-
is_daughter
(mother, daughter)[source]¶ Checks if
daughter
is a decay daughter ofmother
.Parameters: Returns: True
ifdaughter
is daughter ofmother
Return type:
-
particle_list
= None¶ (list) List of particles in the decay matrices
-
-
class
MCEq.data.
HadAirCrossSections
(interaction_model)[source]¶ Class for managing the dictionary of hadron-air cross-sections.
The class unpickles a dictionary, which contains proton-air, pion-air and kaon-air cross-sections tabulated on the common energy grid.
Parameters: interaction_model (str) – name of the interaction model -
get_cs
(projectile, mbarn=False)[source]¶ Returns inelastic
projectile
-air cross-section as vector spanned over the energy grid.Parameters: Returns: cross-section in or
Return type:
-
set_interaction_model
(interaction_model)[source]¶ Selects an interaction model and prepares all internal variables.
Parameters: interaction_model (str) – interaction model name Raises: Exception
– if invalid name specified in argumentinteraction_model
-
GeV2mbarn
= 0.38937930376300284¶ unit -
-
GeVcm
= 1.9732696312541852e-14¶ unit -
-
GeVfm
= 0.19732696312541853¶ unit -
-
egrid
= None¶ current energy grid
-
iam
= None¶ current interaction model name
-
mbarn2cm2
= 9.999999999999999e-28¶ unit conversion -
-
-
class
MCEq.data.
InteractionYields
(interaction_model, charm_model=None)[source]¶ Class for managing the dictionary of interaction yield matrices.
The class unpickles a dictionary, which contains the energy grid and spectra, sampled from hadronic interaction models.
A list of available interaction model keys can be printed by:
$ print yield_obj
Parameters: -
assign_yield_idx
(projectile, projidx, daughter, dtridx, cmat)[source]¶ Copies a subset, defined in tuples
projidx
anddtridx
from theyield_matrix(projectile,daughter)
intocmat
Parameters: - projectile (int) – PDG ID of projectile particle
- projidx (int,int) – tuple containing index range relative to the projectile’s energy grid
- daughter (int) – PDG ID of final state daughter/secondary particle
- dtridx (int,int) – tuple containing index range relative to the daughters’s energy grid
- cmat (numpy.array) – array reference to the interaction matrix
-
get_y_matrix
(projectile, daughter)[source]¶ Returns a
DIM x DIM
yield matrix.Parameters: Returns: yield matrix
Return type: Note
In the current version, the matrices have to be multiplied by the bin widths. In later versions they will be stored with the multiplication carried out.
-
is_yield
(projectile, daughter)[source]¶ Checks if a non-zero yield matrix exist for
projectile
-daughter
combination (deprecated)Parameters: Returns: True
if non-zero interaction matrix exists elseFalse
Return type:
-
set_interaction_model
(interaction_model, force=False)[source]¶ Selects an interaction model and prepares all internal variables.
Parameters: Raises: Exception
– if invalid name specified in argumentinteraction_model
-
set_xf_band
(xl_low_idx, xl_up_idx)[source]¶ Limits interactions to certain range in .
Limit particle production to a range in given by lower index, below which no particles are produced and an upper index, respectively. (Needs more clarification).
Parameters:
-
band
= None¶ (tuple) selection of a band of coeffictients (in xf)
-
charm_model
= None¶ (str) charm model name
-
dim
= None¶ (int) dimension of grid
-
e_bins
= None¶ (numpy.array) energy grid bin endges
-
e_grid
= None¶ (numpy.array) energy grid bin centers
-
iam
= None¶ (str) InterAction Model name
-
mod_pprod
= None¶ (tuple) modified particle combination for error prop.
-
particle_list
= None¶ (list) List of particles supported by interaction model
-
weights
= None¶ (numpy.array) energy grid bin widths
-
xmat
= None¶ (numpy.array) Matrix of x_lab values
-
-
class
MCEq.data.
MCEqParticle
(pdgid, particle_db, pythia_db, cs_db, d, max_density=0.00124)[source]¶ Bundles different particle properties for simplified availability of particle properties in
MCEq.core.MCEqRun
.Parameters: - pdgid (int) – PDG ID of the particle
- particle_db (object) – handle to an instance of
ParticleDataTool.SibyllParticleTable
- pythia_db (object) – handle to an instance of
ParticleDataTool.PYTHIAParticleData
- cs_db (object) – handle to an instance of
InteractionYields
- d (int) – dimension of the energy grid
-
calculate_mixing_energy
(e_grid, no_mix=False, max_density=0.00124)[source]¶ Calculates interaction/decay length in Air and decides if the particle has resonance and/or hadron behavior.
Class attributes
is_mixed
,E_mix
,mix_idx
,is_resonance
are calculated here.Parameters: - e_grid (numpy.array) – energy grid of size
d
- no_mix (bool) – if True, mixing is disabled and all particles have either hadron or resonances behavior.
- max_density (float) – maximum density on the integration path (largest decay length)
- e_grid (numpy.array) – energy grid of size
-
critical_energy
()[source]¶ Returns critical energy where decay and interaction are balanced.
Approximate value in Air.
Returns: in GeV Return type: (float)
-
hadridx
()[source]¶ Returns index range where particle behaves as hadron.
Returns: range on energy grid Return type: tuple()
(int,int)
-
inverse_decay_length
(E, cut=True)[source]¶ Returns inverse decay length (or infinity (np.inf), if particle is stable), where the air density is factorized out.
Parameters: Returns: in 1/cm
Return type: (float)
-
inverse_interaction_length
(cs=None)[source]¶ Returns inverse interaction length for A_target given by config.
Returns: in cm**2/g Return type: (float)
-
lidx
()[source]¶ Returns lower index of particle range in state vector.
Returns: lower index in state vector MCEqRun.phi
Return type: (int)
-
residx
()[source]¶ Returns index range where particle behaves as resonance.
Returns: range on energy grid Return type: tuple()
(int,int)
-
uidx
()[source]¶ Returns upper index of particle range in state vector.
Returns: upper index in state vector MCEqRun.phi
Return type: (int)
-
E_crit
= None¶ (float) critical energy in air at the surface
-
E_mix
= None¶ (float) mixing energy, transition between hadron and resonance behavior
-
is_alias
= None¶ (bool) particle is an alias (PDG ID encodes special scoring behavior)
-
is_baryon
= None¶ (bool) particle is a baryon
-
is_hadron
= None¶ (bool) particle is a hadron (meson or baryon)
-
is_lepton
= None¶ (bool) particle is a lepton
-
is_meson
= None¶ (bool) particle is a meson
-
is_mixed
= None¶ (bool) particle has both, hadron and resonance properties
-
is_projectile
= None¶ (bool) particle is interacting projectile
-
is_resonance
= None¶ (bool) if particle has just resonance behavior
-
mix_idx
= None¶ (int) energy grid index, where transition between hadron and resonance occurs
-
nceidx
= None¶ (int) MCEq ID
-
pdgid
= None¶ (int) Particle Data Group Monte Carlo particle ID
MCEq.data_utils
— file operations on MCEq databases¶
This module contains function to convert data files used by MCEq.
convert_to_compact()
converts an interaction model file into “compact” modeextend_to_low_energies()
extends an interaction model file with an low energy interaction model using interpolation
-
MCEq.data_utils.
convert_to_compact
(fname)[source]¶ Converts an interaction model dictionary to “compact” mode.
This function takes a compressed yield file, where all secondary particle types known to the particular model are expected to be final state particles (set stable in the MC), and converts it to a new compressed yield file which contains only production channels to the most important particles (for air-shower and inclusive lepton calculations).
The production of short lived particles and resonances is taken into account by executing the convolution with their decay distributions into more stable particles, until only final state particles are left. The list of “important” particles is defined in the standard_particles variable below. This results in a feed-down corretion, for example the process (chain) becomes simply . The new interaction yield file obtains the suffix _compact and it contains only those final state secondary particles:
The compact mode has the advantage, that the production spectra stored in this dictionary are directly comparable to what accelerators consider as stable particles, defined by a minimal life-time requirement. Using the compact mode is recommended for most applications, which use
MCEq.core.MCEqRun.set_mod_pprod()
to modify the spectrum of secondary hadrons.For some interaction models, the performance advantage can be around 50%. The precision loss is negligible at energies below 100 TeV, but can increase up to a few % at higher energies where prompt leptons dominate. This is because also very short-lived charmed mesons and baryons with small branching ratios into leptons can interact with the atmosphere and lose energy before decay.
For QGSJET, compact and normal mode are identical, since the model does not produce resonances or rare mesons by design.
Parameters: fname (str) – name of compressed yield (.bz2) file
-
MCEq.data_utils.
extend_to_low_energies
(he_di=None, le_di=None, fname=None)[source]¶ Interpolates between a high-energy and a low-energy interaction model.
Theis function takes either two yield dictionaries or a file name of the high energy model and interpolates the matrices at the energy specified in :mod:mceq_config in the low_energy_extension section. The interpolation is linear in energy grid index.
In ‘compact’ mode all particles should be supported by the low energy model. However if you don’t use compact mode, some rare or exotic secondaries might be not supported by the low energy model. In this case the config option “use_unknown_cs” decides if only the high energy part is used or if to raise an excption.
Parameters:
MCEq.kernels
— calculation kernels for the forward-euler integrator¶
The module contains functions which are called by the forward-euler
integration routine MCEq.core.MCEqRun.forward_euler()
.
The integration is part of these functions. The single step
with
(1)¶
and
(2)¶
The functions use different libraries for sparse and dense linear algebra (BLAS):
- The default for dense or sparse matrix representations is the function
kern_numpy()
. It uses the dot-product implementation ofnumpy
. Depending on the details, yournumpy
installation can be already linked to some BLAS library like as ATLAS or MKL, what typically accelerates the calculation significantly. - The fastest version,
kern_MKL_sparse()
, directly interfaces to the sparse BLAS routines from Intel MKL viactypes
. If you have the MKL runtime installed, this function is recommended for most purposes. - The GPU accelerated versions
kern_CUDA_dense()
andkern_CUDA_sparse()
are implemented using the cuBLAS or cuSPARSE libraries, respectively. They should be considered as experimental or implementation examples if you need extremely high performance. To keep Python as the main programming language, these interfaces are accessed via the modulenumbapro
, which is part of the Anaconda Accelerate package. It is free for academic use.
-
MCEq.kernels.
kern_CUDA_dense
(nsteps, dX, rho_inv, int_m, dec_m, phi, grid_idcs, mu_egrid=None, mu_dEdX=None, mu_lidx_nsp=None, prog_bar=None)[source]¶ NVIDIA CUDA cuBLAS implementation of forward-euler integration.
Function requires a working
numbapro
installation. It is typically slower compared tokern_MKL_sparse()
but it depends on your hardware.Parameters: - nsteps (int) – number of integration steps
- dX (numpy.array[nsteps]) – vector of step-sizes in g/cm**2
- rho_inv (numpy.array[nsteps]) – vector of density values
- int_m (numpy.array) – interaction matrix (1) in dense or sparse representation
- dec_m (numpy.array) – decay matrix (2) in dense or sparse representation
- phi (numpy.array) – initial state vector
- prog_bar (object,optional) – handle to
ProgressBar
object
Returns: state vector after integration
Return type:
-
MCEq.kernels.
kern_CUDA_sparse
(nsteps, dX, rho_inv, context, phi, grid_idcs, mu_egrid=None, mu_dEdX=None, mu_lidx_nsp=None, prog_bar=None)[source]¶ NVIDIA CUDA cuSPARSE implementation of forward-euler integration.
Function requires a working
accelerate
installation.Parameters: - nsteps (int) – number of integration steps
- dX (numpy.array[nsteps]) – vector of step-sizes in g/cm**2
- rho_inv (numpy.array[nsteps]) – vector of density values
- int_m (numpy.array) – interaction matrix (1) in dense or sparse representation
- dec_m (numpy.array) – decay matrix (2) in dense or sparse representation
- phi (numpy.array) – initial state vector
- prog_bar (object,optional) – handle to
ProgressBar
object
Returns: state vector after integration
Return type:
-
MCEq.kernels.
kern_MKL_sparse
(nsteps, dX, rho_inv, int_m, dec_m, phi, grid_idcs, mu_egrid=None, mu_dEdX=None, mu_lidx_nsp=None, prog_bar=None)[source]¶ Intel MKL sparse BLAS implementation of forward-euler integration.
Function requires that the path to the MKL runtime library
libmkl_rt.[so/dylib]
defined in the config file.Parameters: - nsteps (int) – number of integration steps
- dX (numpy.array[nsteps]) – vector of step-sizes in g/cm**2
- rho_inv (numpy.array[nsteps]) – vector of density values
- int_m (numpy.array) – interaction matrix (1) in dense or sparse representation
- dec_m (numpy.array) – decay matrix (2) in dense or sparse representation
- phi (numpy.array) – initial state vector
- grid_idcs (list) – indices at which longitudinal solutions have to be saved.
- prog_bar (object,optional) – handle to
ProgressBar
object
Returns: state vector after integration
Return type:
-
MCEq.kernels.
kern_XeonPHI_sparse
(nsteps, dX, rho_inv, int_m, dec_m, phi, grid_idcs, mu_egrid=None, mu_dEdX=None, mu_lidx_nsp=None, prog_bar=None)[source]¶ Experimental Xeon Phi support using pyMIC library.
-
MCEq.kernels.
kern_numpy
(nsteps, dX, rho_inv, int_m, dec_m, phi, grid_idcs, mu_egrid=None, mu_dEdX=None, mu_lidx_nsp=None, prog_bar=None, fa_vars=None)[source]¶ :mod;`numpy` implementation of forward-euler integration.
Parameters: - nsteps (int) – number of integration steps
- dX (numpy.array[nsteps]) – vector of step-sizes in g/cm**2
- rho_inv (numpy.array[nsteps]) – vector of density values
- int_m (numpy.array) – interaction matrix (1) in dense or sparse representation
- dec_m (numpy.array) – decay matrix (2) in dense or sparse representation
- phi (numpy.array) – initial state vector
- prog_bar (object,optional) – handle to
ProgressBar
object - fa_vars (dict,optional) – contains variables for first interaction mode
Returns: state vector after integration
Return type:
MCEq.misc
- other useful things¶
Some helper functions and plotting features are collected in this module.
-
class
MCEq.misc.
EdepZFactors
(interaction_model, primary_flux_model)[source]¶ Handles calculation of energy dependent Z factors.
Was not recently checked and results could be wrong.
-
MCEq.misc.
cornertext
(text, loc=2, color=None, frameon=False, axes=None, **kwargs)[source]¶ Conveniently places text in a corner of a plot.
Parameters: - text (string or tuple of strings) – Text to be placed in the plot. May be a tuple of strings to get several lines of text.
- loc (integer or string) – Location of text, same as in legend(...).
- frameon (boolean (optional)) – Whether to draw a border around the text. Default is False.
- axes (Axes (optional, default: None)) – Axes object which houses the text (defaults to the current axes).
- fontproperties (matplotlib.font_manager.FontProperties object) – Change the font style.
- keyword arguments are forwarded to the text instance. (Other) –
- Authors –
- ------- –
- Dembinski <hans.dembinski@kit.edu> (Hans) –
-
MCEq.misc.
get_bins_and_width_from_centers
(vector)[source]¶ Returns bins and bin widths given given bin centers.
-
MCEq.misc.
normalize_hadronic_model_name
(name)[source]¶ Converts hadronic model name into standard form
-
MCEq.misc.
plot_hist
(xedges, ws, axes=None, facecolor=None, **kwargs)[source]¶ Plots histogram data in ROOT style.
Parameters: - xedge (lower bin boundaries + upper boundary of last bin) –
- w (content of the bins) –
-
MCEq.misc.
print_in_rows
(str_list, n_cols=8)[source]¶ Prints contents of a list in rows n_cols entries per row.