Python API
Basic Classes
EOS provides its basic functionality via the main eos module.
- class eos.Constraint
Represents a named experimental or theoretical constraint known to EOS.
A constraint bundles one or more observables with the log-likelihood blocks that constrain them. New objects are created using the
makestatic method. See also the complete list of constraints.- blocks((Constraint)arg1) object
Returns an iterator over the log-likelihood blocks that make up the constraint.
- static make((QualifiedName)name, (Options)options) Constraint
Makes a new
Constraintobject from the internal database of constraints.- Parameters:
name (eos.QualifiedName) –
The name of the constraint. See the complete list of constraints.
options (eos.Options) – The set of options passed to the observables entering the constraint.
- Returns:
The new constraint object.
- Return type:
- name((Constraint)self) QualifiedName
Returns the name of the constraint.
- Return type:
- class eos.ConstraintEntry
Describes a single constraint known to EOS and acts as its factory.
A constraint entry records a constraint’s name, type, the observables it constrains, and the references it originates from. Entries are obtained by iterating or indexing
eos.Constraints, and can create the correspondingeos.Constraint(viamake) or an equivalenteos.LogPrior(viamake_prior).- static deserialize((QualifiedName)name, (str)yaml) ConstraintEntry
Creates a new
ConstraintEntryby deserializing its YAML representation.- Parameters:
name (eos.QualifiedName) – The name of the constraint.
yaml (str) – The YAML representation of the constraint entry.
- Returns:
The new constraint entry object.
- Return type:
- make((ConstraintEntry)self, (QualifiedName)name, (Options)options) Constraint
Makes a new
Constraintobject from this entry.- Parameters:
name (eos.QualifiedName) – The name of the constraint.
options (eos.Options) – The set of options passed to the observables entering the constraint.
- Returns:
The new constraint object.
- Return type:
- make_prior((ConstraintEntry)self, (_Parameters)parameters, (Options)options) LogPrior
Makes a new
LogPriorobject from this entry.- Parameters:
parameters (eos.Parameters) – The set of parameters to which the prior is bound.
options (eos.Options) – The set of options passed to the observables entering the constraint.
- Returns:
The new log(prior) object.
- Return type:
- name((ConstraintEntry)self) QualifiedName
Returns the name of the constraint.
- Return type:
- observables((ConstraintEntry)arg1) object
Returns an iterator over the names of the observables entering the constraint.
- references((ConstraintEntry)arg1) object
Returns an iterator over the names of the references from which the constraint originates.
- class eos.Constraints(prefix=None, name=None, suffix=None)
Represents the complete list of constraints known to EOS.
Objects of this class are visualized as tables in Jupyter notebooks for easy overview. Filters can be applied through keyword arguments to the initialization.
- Parameters:
prefix (str) – Only show constraints whose qualified names contain the provided
prefixin their prefix part.name (str) – Only show constraints whose qualified names contain the provided
namein their name part.suffix (str) – Only show constraints whose qualified names contain the provided
suffixin their suffix part.
See also the complete list of constraints in this documentation.
- insert((_Constraints)self, (QualifiedName)name, (str)entry) ConstraintEntry
Inserts a new constraint into EOS at run time by parsing its YAML representation.
- Parameters:
name (eos.QualifiedName) – The name of the new constraint.
entry (str) – The YAML representation of the constraint entry.
- Returns:
The newly inserted constraint entry.
- Return type:
- class eos.Kinematics
Represents the set of kinematic variables relevant to an
observable.Initialize a new set of kinematic variables. The inital set of variables and their initial set of values can be provided through keyword arguments, e.g. using
k = eos.Kinematics(q2=0.4, k2=0.0) # default keyword arguments k = eos.Kinematics({'q2': 0.4, 'cos(theta_l)': -1.0}) # use a dictionary if variable names are not # valid python identifiers
- declare((Kinematics)self, (str)name, (float)value) KinematicVariable
Declares a new kinematic variable.
- class eos.KinematicVariable
Represents a single kinematic variable within a
Kinematicsobject.Users cannot directly create new objects of this class. They are obtained from a
Kinematicsobject by name, by iteration, or as the result ofKinematics.declare.An object of this class is a handle to the variable rather than a copy of its value:
setchanges the value seen by the owningKinematicsobject and by everything bound to it.
- class eos.LogLikelihood
Represents the log(likelihood) of a Bayesian analysis undertaken with the
Analysisclass.- add((LogLikelihood)self, (Constraint)constraint) None
Adds a constraint from the internal database to the likelihood.
- param constraint:
The constraint to add.
- type constraint:
eos.Constraint
add( (LogLikelihood)self, (LogLikelihoodBlock)block) -> None :
Adds a single log-likelihood block to the likelihood.
- param block:
The log-likelihood block to add.
- type block:
eos.LogLikelihoodBlock
- evaluate((LogLikelihood)self) float
Evaluates the log(likelihood) for the current parameter point.
- Return type:
- observable_cache((LogLikelihood)self) ObservableCache
Returns the observable cache shared by the likelihood’s blocks.
- Return type:
- class eos.LogLikelihoodBlock
Represents a single block (term) of a
LogLikelihood.A block encapsulates the likelihood contribution of one or more observables, such as a (multivariate) Gaussian constraint or a user-provided external likelihood. New blocks are created using the static factory methods, e.g.
ExternalandUnbinned1D, and added to a likelihood viaLogLikelihood.add.- static External((ObservableCache)cache, (object)factory) LogLikelihoodBlock
Create a new external log-likelihood block.
- Parameters:
cache (eos.ObservableCache) – The observable cache used by the total log-likelihood.
factory (collections.abc.Callable) – The factory method used to initialize the external log-likelihood block.
- Returns:
The new block.
- Return type:
- static Unbinned1D(cache, pdf_name, kinematics, options, resolution, observations)
Create a new unbinned log-likelihood block with a resolution function.
The named SignalPDF is evaluated on the supplied grid and convolved with the resolution function via a discrete Fourier transform, yielding the resolution-smeared PDF sampled on the grid. The log-likelihood is then the sum over the observed events of the logarithm of the smeared PDF, evaluated at each observation by linear interpolation from the surrounding grid points.
- Parameters:
cache (eos.ObservableCache) – The observable cache used by the total log-likelihood.
pdf_name (eos.QualifiedName) – The name of the SignalPDF to evaluate at each grid point.
kinematics (list of eos.Kinematics) – One Kinematics object per grid point.
options (eos.Options) – Options forwarded to the SignalPDF constructor.
resolution (list of float) – Discretised resolution function on the same grid, in natural (centred) order, i.e. the zero offset (the peak of a symmetric kernel) sits at the centre of the array. The kernel is converted to the wrap-around order expected by the underlying circular convolution via
numpy.fft.ifftshift()before the block is constructed.observations (list of eos.Kinematics) – The observed events, expressed as kinematic variables.
- Returns:
The new block.
- Return type:
Note
The convolution underlying the unbinned likelihood is circular. The grid must therefore be padded with a sufficiently large region in which both the PDF and the resolution function are negligible, so that no appreciable density wraps across the boundary.
- class eos.LogPrior
Represents a Bayesian prior on the log scale.
New LogPrior objects can only be created using the capitalized static methods:
LogPrior.Uniform(),LogPrior.Flat(),LogPrior.Gaussian(),LogPrior.CurtailedGauss(),LogPrior.Poisson(),LogPrior.Scale(), andLogPrior.Transform().- static CurtailedGauss((_Parameters)parameters, (str)name, (float)min, (float)max, (float)lower, (float)central, (float)upper) LogPrior
Returns a new (curtailed) Gaussian prior as a LogPrior.
The prior’s support is provided by the pair of
minandmaxparameters, with the approximate 68% probability interval [lower,upper] and the mode provided by the parametercentral.- Parameters:
parameters (eos.Parameters) – The parameters to which this LogPrior is bound.
name (str) – The name of the parameter for which the LogPrior is defined.
min (float) – The minimum value that the parameter is allowed to take.
max (float) – The maximum value that the parameter is allowed to take.
lower (float) – The lower boundary of the 68% probability interval.
central (float) – The mode and median of the prior.
upper (float) – The upper boundary of the 68% probability interval.
- static External((_Parameters)parameters, (object)factory) LogPrior
Returns a new external prior as a LogPrior.
The prior’s behaviour is provided by a user-supplied Python object created by the
factorycallable. The factory is invoked with a singleParametersargument and must return an object that exposes:a callable
evaluate()returning the logarithm of the prior’s probability density;a callable
sample()that sets the varied parameters from their generator values;a callable
compute_cdf()that sets the varied parameters’ generator values from their current values;an iterable
varied_parametersof the names of the parameters varied by this prior; anda boolean
informativeattribute.
- Parameters:
parameters (eos.Parameters) – The parameters to which this LogPrior is bound.
factory (collections.abc.Callable) – The factory callable used to initialize the external prior.
- static Flat((_Parameters)parameters, (str)name, (float)min, (float)max) LogPrior
Alias for
LogPrior.Uniform().
- static Gaussian((_Parameters)parameters, (QualifiedName)name, (float)mu, (float)sigma) LogPrior
Returns a new Gaussian prior as a LogPrior.
The priors support is infinite. The mode is provided by the parameter
muand the standard deviation by the parametersigma.- Parameters:
parameters (eos.Parameters) – The parameters to which this LogPrior is bound.
name (str) – The name of the parameter for which the LogPrior is defined.
mu (float) – The mode of the prior.
sigma (float) – The standard deviation of the prior, which must be strictly positive.
- static Poisson((_Parameters)parameters, (str)name, (float)k) LogPrior
Returns a new Poisson prior as a LogPrior.
The priors support is infinite. The mode is provided by the parameter
k.- Parameters:
parameters (eos.Parameters) – The parameters to which this LogPrior is bound.
name (str) – The name of the parameter for which the LogPrior is defined.
k (float) – The mode of the prior, which must be strictly positive.
- static Scale((_Parameters)parameters, (str)name, (float)min, (float)max, (float)mu_0, (float)scale) LogPrior
Returns a new Scale prior as a LogPrior.
The prior’s support is provided by the pair of
minandmaxparameters, which should coincide with [mu_0 / scale,mu_0 * scale]. The PDF is chosen such that a renormalization scale is varied in this range and with central value mu_0 such that \(\ln x / \mu_0\) is uniformly distributed in the interval \([-\ln \lambda, +\ln \lambda]\).- Parameters:
parameters (eos.Parameters) – The parameters to which this LogPrior is bound.
name (str) – The name of the parameter for which the LogPrior is defined.
min (float) – The minimum value that the parameter is allowed to take.
max (float) – The maximum value that the parameter is allowed to take.
mu_0 (float) – The central value of the parameter, which must be strictly positive.
scale (float) – The scale factor, which must be strictly positive.
- static Transform((_Parameters)parameters, (object)name, (object)shift, (object)transform, (object)min, (object)max) LogPrior
Returns a new transformed uniform prior from original uniform priors as a LogPrior.
The prior’s support is infinite.
- Parameters:
parameters (eos.Parameters) – The parameters to which this LogPrior is bound.
name (str) – The name of the parameters for which the LogPrior is defined.
shift (collections.abc.Sequence of float) – The shift vector to the original set of parameters
transform (numpy.ndarray) – The matrix that transforms the original set of parameters
min (collections.abc.Sequence of float) – The vector of minimum values that the parameters are allowed to take.
max (collections.abc.Sequence of float) – The vector of maximum values that the parameters are allowed to take.
- static Uniform((_Parameters)parameters, (str)name, (float)min, (float)max) LogPrior
Returns a new uniform prior as a LogPrior.
The prior’s support is provided by the range parameter.
- Parameters:
parameters (eos.Parameters) – The parameters to which this LogPrior is bound.
name (str) – The name of the parameter for which the LogPrior is defined.
min (float) – The minimum value that the parameter is allowed to take.
max (float) – The maximum value that the parameter is allowed to take.
- compute_cdf((LogPrior)self) None
Returns the cumulative probabilities \(p\) assigned to each parameter via its
Parameter.evaluate_generator()method.
- evaluate((LogPrior)self) float
Returns the logarithm of the prior’s probability density at the current parameter values.
- Return type:
- sample((LogPrior)self) None
Sets its parameters’ values corresponding to the cumulative propability \(p\) assigned to each parameter via its
Parameter.set_generator()method.
- class eos.LogPosterior
Represents a Bayesian posterior on the log scale.
- add((LogPosterior)self, (LogPrior)prior, (bool)nuisance) bool
Adds a new prior object to the posterior.
- Parameters:
prior (eos.LogPrior) – The prior to add to the posterior.
nuisance (bool) – Whether the prior’s parameters shall be treated as nuisance parameters.
- Returns:
Whether the prior was added successfully.
- Return type:
- log_likelihood((LogPosterior)self) LogLikelihood
Returns the likelihood object used as part of the posterior.
- Return type:
- class eos.Model
Represents a physics model, providing access to the CKM matrix elements, quark masses in various renormalization schemes, the strong coupling, and Wilson coefficients.
New objects are created using the
makestatic method.- alpha_s((Model)self, (float)mu) float
Returns the strong coupling \(\alpha_s(\mu)\) at the renormalization scale
mu.
- m_b_kin((Model)self, (float)mu_kin) float
Returns the bottom-quark kinetic mass \(m_b^{\text{kin}}(\mu_{\text{kin}})\) in GeV.
- m_b_msbar((Model)self, (float)mu) float
Returns the bottom-quark \(\overline{\text{MS}}\) mass \(\overline{m}_b(\mu)\) in GeV.
- m_b_pole((Model)self, (int)loop_order) float
Returns the bottom-quark pole mass in GeV.
- param loop_order:
The loop order of the conversion from the \(\overline{\text{MS}}\) mass. Defaults to 3.
- type loop_order:
int
- rtype:
float
m_b_pole( (Model)self) -> float :
Returns the bottom-quark pole mass in GeV at the default loop order.
- rtype:
float
- m_c_kin((Model)self, (float)mu_kin) float
Returns the charm-quark kinetic mass \(m_c^{\text{kin}}(\mu_{\text{kin}})\) in GeV.
- m_c_msbar((Model)self, (float)mu) float
Returns the charm-quark \(\overline{\text{MS}}\) mass \(\overline{m}_c(\mu)\) in GeV.
- m_s_msbar((Model)self, (float)mu) float
Returns the strange-quark \(\overline{\text{MS}}\) mass \(\overline{m}_s(\mu)\) in GeV.
- m_t_msbar((Model)self, (float)mu) float
Returns the top-quark \(\overline{\text{MS}}\) mass \(\overline{m}_t(\mu)\) in GeV.
- m_ud_msbar((Model)self, (float)mu) float
Returns the averaged up-/down-quark \(\overline{\text{MS}}\) mass \(\overline{m}_{ud}(\mu)\) in GeV.
- static make((str)name, (_Parameters)parameters, (Options)options) Model
Makes a new
Modelobject.- Parameters:
name (str) – The name of the model, e.g.
SMorWET.parameters (eos.Parameters) – The set of parameters to which the model is bound.
options (eos.Options) – The set of options relevant to the model.
- Returns:
The new model object.
- Return type:
- wilson_coefficients_b_to_s((Model)self, (float)mu, (object)lepton_flavor, (bool)cp_conjugate) BToSWilsonCoefficients
Returns the Wilson coefficients of the \(b \to s\) effective Hamiltonian.
- class eos.Observable
Represents an observable or pseudo observable known to EOS.
New observable objects are created using the
makestatic method. See also the complete list of observables.- evaluate((Observable)self) float
Evaluates the observable for the present values of its bound set of parameters and set of kinematic variables.
- Returns:
The value of the observable.
- Return type:
- kinematics((Observable)self) Kinematics
Returns the set of kinematic variables bound to this observable.
- Return type:
- static make((QualifiedName)name, (_Parameters)parameters, (Kinematics)kinematics, (Options)options) Observable
Makes a new
Observableobject.- Parameters:
name (eos.QualifiedName) –
The name of the observable. See the complete list of observables.
parameters (eos.Parameters) – The set of parameters to which this observable is bound.
kinematics (eos.Kinematics) – The set of kinematic variables to which this observable is bound.
options (eos.Options) – The set of options relevant to this observable.
- Returns:
The new observable object.
- Return type:
- name((Observable)self) QualifiedName
Returns the name of the observable.
- Return type:
- options((Observable)self) Options
Returns the set of options used when creating the observable.
- Return type:
- parameters((Observable)self) eos.Parameters
Returns the set of parameters bound to this observable.
- Return type:
- class eos.ObservableEntry
Describes a single observable known to EOS.
An observable entry records an observable’s name, its LaTeX representation, its unit, and the kinematic variables and options it accepts. Entries are obtained by iterating or indexing
eos.Observables.- kinematic_variables((ObservableEntry)arg1) object
Returns an iterator over the names of the kinematic variables accepted by the observable.
- name((ObservableEntry)self) QualifiedName
Returns the name of the observable.
- Return type:
- class eos.ObservableId
Represents an opaque handle to an observable within an
ObservableCache.Users cannot directly create new objects of this class. New handles are obtained from
ObservableCache.add.
- class eos.Observables(prefix=None, name=None, suffix=None, showall=False)
Represents the complete list of observables known to EOS.
Objects of this class are visualized as tables in Jupyter notebooks for easy overview. Filters can be applied through keyword arguments to the initialization.
- Parameters:
prefix (str) – Only show observables whose qualified names contain the provided
prefixin their prefix part.name (str) – Only show observables whose qualified names contain the provided
namein their name part.suffix (str) – Only show observables whose qualified names contain the provided
suffixin their suffix part.
See also the complete list of observables in this documentation.
- insert((_Observables)self, (QualifiedName)name, (str)latex, (Unit)unit, (Options)options, (str)expression) None
Insert a new observable to EOS by parsing the input string.
- Parameters:
name (eos.QualifiedName) – The name of the new observable.
latex (str) – The latex representation of the new observable.
unit (eos.Unit) – The unit of the new observable.
options (eos.Options) – The set of options relevant to this new observable. These options apply to all the observables in the expression.
expression (str) – The expression to be parsed.
- class eos.Options
Represents the set of options provided to an observable.
Options are pairs of (key, value) pairs. The list of valid keys and their respective valid options are specific to each observable. The initialization accepts keyword arguments, e.g.:
o = eos.Options(model='WET') # default keyword arguments o = eos.Options({'form-factors': 'BSZ2015'}) # use a dictionary if option keys are not # valid python identifiers
- class eos.Parameter
Represents a single real-valued scalar parameter in EOS.
Users cannot directly create new objects of this class. However, new named sets of parameters can be created, via the
eos.Parametersclass, from which the parameter of interest can be extracted, inspected, and altered.- evaluate_generator((Parameter)self) float
Return the current generator value of a parameter.
- Return type:
- max((Parameter)self) float
Returns the maximum value that the parameter is allowed to take.
- Return type:
- min((Parameter)self) float
Returns the minimum value that the parameter is allowed to take.
- Return type:
- set((Parameter)self, (float)value) None
Set the value of a parameter.
- Parameters:
value (float) – The value to set the parameter to.
- set_generator((Parameter)self, (float)value) None
Set the generator value of a parameter.
- Parameters:
value (float) – The value to set the parameter’s generator to.
- set_max((Parameter)self, (float)value) None
Set the maximum value that the parameter is allowed to take.
- Parameters:
value (float) – The maximum value to set.
- class eos.Parameters(*args, **kwargs)
Represents the set of parameters known to EOS.
Objects of this class are visualized as tables in Jupyter notebooks for easy overview. Filters can be applied through keyword arguments to the initialization. An independent instance of the default parameters is obtained by each call to the constructor.
- Parameters:
prefix (str) – Only show parameters whose qualified names contain the provided
prefixin their prefix part.name (str) – Only show parameters whose qualified names contain the provided
namein their name part.suffix (str) – Only show parameters whose qualified names contain the provided
suffixin their suffix part.
See also the complete list of parameters.
- static Defaults() eos.Parameters
Returns an independent instance of the default set of parameters known to EOS.
- Return type:
- static FromWCxf(w)
Imports Wilson coefficients into an eos.Parameters object from a wilson.Wilson object.
- Parameters:
w (wilson.Wilson) – WET Wilson coefficients in the EOS basis.
- by_id((_Parameters)self, (int)id) Parameter
Returns the parameter with the given internal id.
- Parameters:
id (int) – The internal id of the parameter.
- Return type:
- static declare((QualifiedName)name, (str)latex, (Unit)unit, (float)value, (float)min, (float)max) int
Declare a new parameter as part of the default parameter set.
- Parameters:
name (eos.QualifiedName) – The name of the parameter to declare.
latex (str) – The LaTeX representation for the parameter.
unit (eos.Unit) – The unit in which the parameter is expressed.
value (float) – The initial value for the parameter.
min (float) – The minimum value that the parameter can attain.
max (float) – The maximum value that the parameter can attain.
- declare_and_insert((_Parameters)self, (QualifiedName)name, (str)latex, (Unit)unit, (float)value, (float)min, (float)max) Parameter
Declare a new parameter as part of the default parameter set and insert it into this parameter set.
- Parameters:
name (eos.QualifiedName) – The name of the parameter to declare.
latex (str) – The LaTeX representation for the parameter.
unit (eos.Unit) – The unit in which the parameter is expressed.
value (float) – The initial value for the parameter.
min (float) – The minimum value that the parameter can attain.
max (float) – The maximum value that the parameter can attain.
- Returns:
The newly inserted parameter.
- Return type:
- dump(file, **kwargs)
Dumps an eos.Parameters object to a YAML file.
- Parameters:
file (str) – Name of the file to which the parameters shall be written.
names (collections.abc.Collection of str, optional) – Names of the parameters that shall be converted.
- property generation
The current generation of this set of parameters.
The generation changes whenever any of the parameters is written to. It is invariant under reading any of the parameters.
The value is an opaque
_ParametersGenerationobject. Two values compare equal if and only if no parameter has been written to in between.
- has((_Parameters)self, (QualifiedName)name) bool
Returns whether a parameter of the given name is part of this set.
- Parameters:
name (eos.QualifiedName) – The name of the parameter to look up.
- Return type:
- override_from_file((_Parameters)self, (str)file) None
Overrides parameter values from a YAML file.
- Parameters:
file (str) – The path to the YAML file with the parameter values.
- static redirect((QualifiedName)name, (int)id) None
Redirect a parameter name to a different parameter id in the default set of parameters.
The internal mapping of the parameter name will be redirected to the new id. If the the parameter’s previous id is not already aliased, it will become inaccessible. This is useful for example to alias a parameter name to a different parameter object.
- Parameters:
name (eos.QualifiedName) – The name of the parameter to be redirected.
id (int) – The id of the parameter to which the name shall be redirected.
- sections((_Parameters)arg1) object
Returns an iterator over the sections into which the known parameters are grouped.
- to_yaml(names=None)
Converts an eos.Parameters object to a YAML representation.
- Parameters:
names (collections.abc.Collection of str, optional) – Names of the parameters that shall be converted.
- class eos.QualifiedName
Represent a qualified (i.e. complete and syntactically correct) name.
EOS uses qualified names when naming any observable or constraint. The composition is approximately:
PREFIX::NAME@SUFFIX;OPTIONS
- name_part((QualifiedName)self) qnpName
Returns the name part of the name, i.e., the part following the ‘::’ and preceding any optional ‘@’.
- options_part((QualifiedName)self) Options
Returns the optional options part of the name, i.e., the part following the optional ‘;’.
- class eos.qnpName
Represents the name part of a
QualifiedName, i.e. the part following the ‘::’ and preceding any optional ‘@’.Objects of this class are returned by
QualifiedName.name_partand can be created from astr.
- class eos.qnpOptionKey
Represents the key of a single option within the options part of a
QualifiedName, i.e. the part of an option preceding the ‘=’.Objects of this class occur when iterating
QualifiedName.options_partand can be created from astr.
- class eos.qnpOptionValue
Represents the value of a single option within the options part of a
QualifiedName, i.e. the part of an option following the ‘=’.Objects of this class occur when iterating
QualifiedName.options_partand can be created from astr.
- class eos.qnpPrefix
Represents the prefix part of a
QualifiedName, i.e. the part preceding the ‘::’.Objects of this class are returned by
QualifiedName.prefix_partand can be created from astr.
- class eos.qnpSuffix
Represents the suffix part of a
QualifiedName, i.e. the part following the optional ‘@’.Objects of this class are returned by
QualifiedName.suffix_partand can be created from astr.
- class eos.Reference
Represents a single bibliographic reference known to EOS.
A reference records the bibliographic details (authors, title, e-print, INSPIRE identifier, and URL) of a publication underlying part of EOS, be it an experimental constraint or a theoretical work such as the implementation of an observable, a form factor parametrization, or a theory prediction. References are obtained by iterating or indexing
eos.References.- eprint_archive((Reference)self) str
Returns the e-print archive of the reference, e.g.
arXiv.- Return type:
- eprint_id((Reference)self) str
Returns the e-print identifier of the reference, e.g. the arXiv number.
- Return type:
- name((Reference)self) ReferenceName
Returns the name (handle) of the reference.
- class eos.ReferenceName
Represents the name of a reference in the EOS bibliography.
A reference name is composed of a name part, a year part, and an index part, as in
BSZ:2015A. Objects of this class can be created from astrand are used to look up aReferenceinReferences.- index_part((ReferenceName)self) rnpIndex
Returns the index part of the reference name, i.e., the letters following the year part.
- class eos.rnpIndex
Represents the index part of a
ReferenceName, i.e. the letters following the year part.Objects of this class are returned by
ReferenceName.index_partand can be created from astr.
- class eos.rnpName
Represents the name part of a
ReferenceName, i.e. the part preceding the ‘:’.Objects of this class are returned by
ReferenceName.name_partand can be created from astr.
- class eos.rnpYear
Represents the year part of a
ReferenceName, i.e. the four digits following the ‘:’.Objects of this class are returned by
ReferenceName.year_partand can be created from astr.
- class eos.References(year=None, index=None)
Represents the complete list of references known to EOS.
Objects of this class are visualized as tables in Jupyter notebooks for easy overview. Filters can be applied through keyword arguments to the initialization.
- Parameters:
See also the complete list of references in this documentation.
- class eos.SignalPDF
- evaluate((_SignalPDF)self) float
Evaluates the (unnormalized) PDF for the present values of the sets of parameters and kinematic variables that it is bound to.
- Returns:
The value of the PDF.
- Return type:
- kinematics((_SignalPDF)self) Kinematics
Returns the set of kinematic variables bound to this PDF.
- Return type:
- log_pdf(x)
Adapter for use with external optimization software (e.g. pypmc) to aid when sampling from the log(PDF).
- Parameters:
x (collections.abc.Iterable of float) – Phase space point, with the elements corresponding to the sorted list of variables in lexicographical order; inspect self.variables.
- static make(name, parameters, kinematics, options)
Makes a new
SignalPDFobject.- Parameters:
name (eos.QualifiedName) – The name of the probability density function (PDF). See the complete list of PDFs.
parameters (eos.Parameters) – The set of parameters to which this PDF is bound.
kinematics (eos.Kinematics) – The set of kinematic variables to which this PDF is bound.
options (eos.Options) – The set of options relevant to this PDF.
- Returns:
The new PDF object.
- Return type:
- name((_SignalPDF)self) QualifiedName
Returns the name of the PDF.
- Return type:
- normalization((_SignalPDF)self) float
Evaluates the normalization of the PDF.
To speed up sampling from the PDF, the
evaluatereturns values of an unnormalized function proportional to the actual PDF. To ensure that the integral over the PDF is normalized to 1, the values returned by evaluate need to be divided by the return value of this method.- Return type:
- options((_SignalPDF)self) Options
Returns the set of options used when creating the PDF.
- Return type:
- parameters((_SignalPDF)self) eos.Parameters
Returns the set of parameters bound to this PDF.
- Return type:
- sample_mcmc(N, stride, pre_N, preruns, cov_scale=0.1, start_point=None, rng=None)
Return samples of the kinematic variables and the log(PDF).
Obtains random samples of the log(PDF) using an adaptive Markov Chain Monte Carlo with PyPMC. A prerun with adaptations is carried out first and its samples are discarded.
- Parameters:
N – Number of samples that shall be returned
stride – Stride, i.e., the number by which the actual amount of samples shall be thinned to return N samples.
pre_N – Number of samples in each prerun.
preruns – Number of preruns.
cov_scale – Scale factor for the initial guess of the covariance matrix.
start_point (collections.abc.Sequence, optional) – Optional starting point for the chain
rng – Optional random number generator (must be compatible with the requirements of pypmc.sampler.markov_chain.MarkovChain)
- Returns:
A tuple of the kinematic variables as array of size N and the log(PDF) as array of size N.
Note
This method requires the PyPMC python module, which can be installed from PyPI.
- class eos.SignalPDFEntry
Describes a single signal PDF known to EOS.
A signal-PDF entry records the PDF’s name and a human-readable description. Entries are obtained by iterating or indexing
eos.SignalPDFs.- denominator_kinematic_variables((SignalPDFEntry)arg1) object
Returns an iterator over the names of the kinematic variables in the PDF’s denominator.
- description((SignalPDFEntry)self) str
Returns the human-readable description of the signal PDF.
- Return type:
- name((SignalPDFEntry)self) QualifiedName
Returns the name of the signal PDF.
- Return type:
- class eos.SignalPDFs(prefix=None, name=None, suffix=None, showall=False)
Represents the complete list of probability density functions (PDFs) known to EOS.
Objects of this class are visualized as tables in Jupyter notebooks for easy overview. Filters can be applied through keyword arguments to the initialization.
- Parameters:
prefix (str) – Only show observables whose qualified names contain the provided
prefixin their prefix part.name (str) – Only show observables whose qualified names contain the provided
namein their name part.suffix (str) – Only show observables whose qualified names contain the provided
suffixin their suffix part.
See also the complete list of signal PDFs in this documentation.
- insert((_SignalPDFs)self, (QualifiedName)name, (str)description, (Options)options, (QualifiedName)numerator, (object)numerator_kinematic_variables, (QualifiedName)normalization, (object)normalization_kinematic_variables) None
Insert a new signal PDF to EOS, built at run time from two existing observables.
- Parameters:
name (eos.QualifiedName) – The name of the new signal PDF.
description (str) – A human-readable description of the new signal PDF.
options (eos.Options) – The set of options relevant to this new signal PDF. These options apply to both backing observables.
numerator (eos.QualifiedName) – The name of the observable that provides the unnormalized PDF.
numerator_kinematic_variables (list of str) – The kinematic variables of the unnormalized PDF; these are the PDF’s sampling variables.
normalization (eos.QualifiedName) – The name of the observable that provides the normalization.
normalization_kinematic_variables (list of str) – The kinematic variables of the normalization; for each sampling variable
vthis should contain the boundsv_minandv_max.
- class eos.Unit
Represents the unit of the observables.
- Thirteen possible entries are currently implemented in EOS:
Undefined
Unity
GeV
GeV2
GeV3
InverseGeV
InverseGeV2
InverseGeV4
Second
InverseSecond
InversePicoSecond
GeVSecond
Femtometer2
- static Undefined() Unit
Returns the undefined unit, which is used wherever no unit has been assigned. It is printed as
undefined.- Return type:
Common Classes
EOS provides common classes for use in statistical analyses via the main eos module.
- class eos.Analysis(priors, likelihood, external_likelihood=None, global_options=None, manual_constraints=None, fixed_parameters=None, parameters=None)
Represents a statistical analysis.
Describes a Bayesian analysis in terms of a set of parameters, a log(likelihood), and a set containing one or more log(prior)s.
- Parameters:
global_options (dict, optional) – The options as (key, value) pairs that shall be forwarded to all theory predictions.
priors (collections.abc.Sequence) – The priors for this analysis as a list of prior descriptions. See below for what consitutes a valid prior description.
likelihood (collections.abc.Sequence) –
The likelihood as a list of individual constraints from the internal data base of experimental and theoretical constraints; cf. the complete list of constraints.
external_likelihood (collections.abc.Sequence of
eos.LogLikelihoodBlock.) – The external likelihood blocks as a list or iterable of objects returned byeos.LogLikelihoodBlock.External().manual_constraints (dict, optional) – Additional manually-specified constraints that shall be added to the log(likelihood).
fixed_parameters (dict, optional) – Values of parameters that are set when the analysis is defined.
parameters (
eos.Parametersor None, optional) – The optional set of parameters that shall be used for this analysis. Defaults to None which means that a new instance ofeos.Parametersis created.
Each prior description is a dictionary with the following mandatory elements:
type (str) – The type specification of the prior. Must be one of
uniform,flat, orgaussian.parameter (str) – The name of the parameter for which the prior shall apply.
min (float) – The lower boundary of the prior’s support.
max (float) – The upper boundary of the prior’s support.
A
uniformorflatprior does not require any further description. Agaussianprior requires in addition providing the following two elements:central (float) – The median value of the parameter.
sigma (float, or list, tuple of float) – The width of the 68% probability interval. If a list or tuple of two numbers is provided, the prior will by a asymmetric but continuous. The two values are then taken to be the distance to the lower and upper end of the 68% probability interval.
- clone()
Return an independent copy of this analysis.
The clone is constructed from the same arguments as the original, so it has its own parameter set and can be modified without affecting this instance.
- Returns:
A new analysis equivalent to this one.
- Return type:
- goodness_of_fit()
Summarize the quality of the fit at the current parameter point.
- Returns:
A goodness-of-fit summary (e.g. test statistic, degrees of freedom, and p-value) evaluated at the analysis’ current parameter values.
- Return type:
- log_likelihood(p, *args)
Adapter for use with external sampling software (e.g. dynesty) to aid when sampling from the log(likelihood).
- Parameters:
p (collections.abc.Iterable) – Parameter point, with the elements in the same order as in eos.Analysis.varied_parameters.
args (optional) – Dummy parameter (ignored)
- log_pdf(u, *args)
Adapter for use with external optimization software (e.g. pypmc) to aid when optimizing the log(posterior).
- Parameters:
u (collections.abc.Iterable) – Parameter point in u space, with the elements in the same order as in eos.Analysis.varied_parameters.
args (optional) – Dummy parameter (ignored)
- negative_log_pdf(u, *args)
Adapter for use with external optimization software (e.g. scipy.optimize.minimize) to aid when optimizing the log(posterior).
- Parameters:
u (collections.abc.Iterable) – Parameter point in u space, with the elements in the same order as in eos.Analysis.varied_parameters.
args (optional) – Dummy parameter (ignored)
- optimize(start_point=None, rng=None, **kwargs)
Optimize the log(posterior) and returns a best-fit-point summary. Optimization is performed using the scipy SLSQP method by default since the varied parameters are usually bounded. However, other bounded algorithms (such as Nelder-Mead, L-BFGS-B, TNC, SLSQP, Powell or trust-constr) sometimes perform better. The most significant performance improvement is usually achieved by selecting an appropriate initial point, for example, one taken from importance samples.
- Parameters:
start_point (collections.abc.Iterable, optional) – Parameter point from which to start the optimization, with the elements in the same order as in eos.Analysis.varied_parameters. If set to “random”, optimization starts at the random point in the space of the priors. If not specified, optimization starts at the current parameter point.
rng – Optional random number generator
**kwargs – Are passed to scipy.optimize.minimize
- parameters
The set of parameters used for this analysis.
- reset_parameters()
Reset this analysis’ parameters to their EOS default values.
Each parameter of the analysis is set back to the default value of the corresponding EOS parameter, discarding any modifications made since the analysis was created.
- sample(N=1000, stride=5, pre_N=150, preruns=3, cov_scale=0.1, observables=None, start_point=None, rng=None, return_uspace=False)
Return samples of the parameters, log(weights), and optionally posterior-predictive samples for a sequence of observables.
Obtains random samples of the log(posterior) using an adaptive Markov Chain Monte Carlo with PyPMC. A prerun with adaptations is carried out first and its samples are discarded.
- Parameters:
N – Number of samples that shall be returned
stride – Stride, i.e., the number by which the actual amount of samples shall be thinned to return N samples.
pre_N – Number of samples in each prerun.
preruns – Number of preruns.
cov_scale – Scale factor for the initial guess of the covariance matrix.
observables (collections.abc.Sequence, optional) – Observables for which posterior-predictive samples shall be obtained.
start_point (collections.abc.Sequence, optional) – Optional starting point for the chain
rng – Optional random number generator (must be compatible with the requirements of pypmc.sampler.markov_chain.MarkovChain)
- Returns:
A tuple of the parameters as array of size N, the logarithmic weights as array of size N, and optionally the posterior-predictive samples of the observables as array of size N x len(observables).
Note
This method requiries the PyPMC python module, which can be installed from PyPI.
- sample_nested(bound='multi', nlive=250, dlogz=1.0, maxiter=None, miniter=0, min_ess=0, print_progress=True, print_function=None, seed=10, sample='auto')
Return samples of the parameters.
Obtains random samples of log(likelihood) using dynamic nested sampling with dynesty.
- Parameters:
bound (str, optional) – The option for bounding the target distribution. For valid values, see the dynesty documentation. Defaults to ‘multi’.
nlive (int, optional) – The number of live points.
dlogz (float, optional) – The relative tolerance for the remaining evidence. Defaults to 1.0.
maxiter (int, optional) – The maximum number of iterations. Iterations may stop earlier if the termination condition is reached.
miniter (int, optional) – The minimum number of iterations. Defaults to 0. Samples will be added until miniter is reached, even if the termination condition is reached earlier.
min_ess (int, optional) – The minimum effective sample size (ESS). Defaults to 0. Samples will be added until the estimated ESS reaches min_ess, even if the termination condition is reached earlier. If 0, dynesty’s default ESS target is used.
print_progress (bool, optional) – Whether to print progress messages during sampling. Defaults to True.
print_function (collections.abc.Callable, optional) – The function used to print progress messages. Defaults to using a dynesty-based function.
seed (None or int or collections.abc.Sequence of int or numpy.random.SeedSequence, optional) – The seed used to initialize the Mersenne Twister pseudo-random number generator.
sample (str, optional) – The method used for sampling within the likelihood constraints. For valid values, see dynesty documentation. Defaults to ‘auto’.
Note
This method requires the dynesty python module, which can be installed from PyPI.
- sample_pmc(log_proposal, step_N=1000, steps=10, final_N=5000, rng=None, return_final_only=True, final_perplexity_threshold=1.0, weight_threshold=1e-10, pmc_iterations=1, pmc_rel_tol=1e-10, pmc_abs_tol=1e-05, pmc_lookback=1)
Return samples of the parameters and log(weights), and a mixture density adapted to the posterior.
Obtains random samples of the log(posterior) using adaptive importance sampling following the Population Monte Carlo approach with PyPMC.
- Parameters:
log_proposal (pypmc.density.mixture.MixtureDensity) – Initial gaussian mixture density that shall be adapted to the posterior density.
step_N (int) – Number of samples that shall be drawn in each adaptation step.
steps (int) – Number of adaptation steps.
final_N (int) – Number of samples that shall be drawn after all adaptation steps.
rng – Optional random number generator (must be compatible with the requirements of pypmc.sampler.importance_sampler.ImportanceSampler)
return_final_only – If set to True, only returns the samples and weights of the final sampling step, after all adaptations have finished.
final_perplexity_threshold – Adaptations are stopped if the perplexity of the last adaptation step is above this threshold value.
weight_threshold – Mixture components with a weight smaller than this threshold are pruned.
pmc_iterations – (advanced) Maximum number of update of the PMC, changing this value may make the update unstable.
pmc_rel_tol – (advanced) Relative tolerance of the PMC. If two consecutive values of the current density log-likelihood are relatively smaller than this value, the convergence is declared.
pmc_abs_tol – (advanced) Absolute tolerance of the PMC. If two consecutive values of the current density log-likelihood are smaller than this value, the convergence is declared.
pmc_lookback – (advanced) Use reweighted samples from the previous update steps when adjusting the mixture density. The parameter determines the number of update steps to “look back”. The default value of 1 disables this feature, a value of 0 means that all previous steps are used.
- Returns:
A tuple of the parameters as array of length N = step_N * steps + final_N, the (linear) weights as array of length N, the posterior values as array of length N, and the final proposal function as pypmc.density.mixture.MixtureDensity.
This method should be called after obtaining approximate samples of the log(posterior) by other means, e.g., by using
eos.Analysis.sample(). A possible (incomplete) example could look as follows:from pypmc.mix_adapt.r_value import make_r_gaussmix chains = [] for i in range(10): # run Markov Chains for your problem chain, _ = analysis.sample(...) chains.append(chain) # please consult the pypmc documentation for details on the call below proposal_density = make_r_gaussmix(chains, K_g=3, critical_r=1.1) # adapt the proposal to the posterior and obtain high-quality samples analysis.sample_pmc(proposal_density, ...)
Note
This method requires the PyPMC python module, which can be installed from PyPI.
- sample_prior(N=1000, rng=None)
Return prior samples of the parameters.
Obtains random samples of the parameters based on their prior distributions. The code uses inverse transform sampling.
- Parameters:
N (int) – Number of samples that shall be returned
rng – Optional random number generator
- Returns:
An iterable of the parameter samples of size N.
- varied_parameters: list
The parameters varied by this analysis, as a list of
eos.Parameterobjects.
- class eos.AnalysisFile(analysis_file)
Represents a collection of statistical analyses and their building blocks.
- Parameters:
analysis_file (str) – The path to the file to be parsed.
- analysis(_posterior, base_directory='./')
Create an eos.Analysis object for the named posterior.
- Parameters:
base_directory (str) – The base directory against which declared constraints’ relative filenames (see the ‘constraints’ top-level section) are resolved. Defaults to the current working directory.
- dump()
Dumps the contents of the analysis file in YAML format.
- property likelihoods
Returns a list of all likelihoods recorded in the analysis file.
- property masks
Returns a list of all masks recorded in the analysis file.
- observable(_posterior, observable_name, analysis_parameters)
Creates an eos.Observable for the named posterior with the given parameter set.
- observables(_posterior, _prediction, parameters)
Creates a list of eos.Observable objects for the named set of posterior and predictions.
- property posteriors
Returns a list of all posteriors recorded in the analysis file.
- property predictions
Returns a list of all predictions recorded in the analysis file.
- property priors
Returns a list of all priors recorded in the analysis file.
- validate(deep: bool = True, base_directory: str = './')
Validates the analysis file semantically and, by default, deeply.
The deep phase instantiates every posterior and every prediction set, which catches errors that the semantic phase cannot see: invalid options, malformed manual-constraint bodies, inconsistent prior ranges, and unreadable pyhf workspaces. It is enabled by default.
- Parameters:
- Returns:
The diagnostics found, most-structural first.
- Return type:
- class eos.BestFitPoint(analysis, point)
Represents the best-fit point of a Bayesian analysis undertaken with the
Analysisclass.Typically obtained as the return value of
Analysis.optimize(). It bundles the analysis with the parameter point that maximizes its log-posterior and renders as a parameter/value table in IPython.- Parameters:
analysis (eos.Analysis) – The analysis whose best-fit point is represented.
point (collections.abc.Iterable of float) – The values of the varied parameters at the best-fit point, in the same order as
eos.Analysis.varied_parameters.
- Variables:
analysis – The analysis whose best-fit point is represented.
point – The values of the varied parameters at the best-fit point.
- class eos.GoodnessOfFit
Represents the goodness of fit characteristics of the log(posterior).
- class eos.ObservableCache
Provides a cache for the efficient evaluation of observables.
- add((ObservableCache)self, (Observable)observable) ObservableId
Add an existing observable to the cache.
- Parameters:
observable (eos.Observable) – The observable to add to the cache.
- Returns:
An internal handle to the cached observable. The observable’s value can be retrieved using
cache[handle].- Return type:
- parameters((ObservableCache)self) eos.Parameters
Retrieve the set of parameters bound to this cache.
- Return type:
- class eos.PyhfLogLikelihood(cache, workspace, parameter_map=None)
Wraps a HistFactory likelihood, specified as a pyhf workspace, for use within EOS.
On construction, the pyhf model’s modifiers (its parameters) are mapped onto EOS observables or parameters: each pyhf parameter is associated with the EOS observable or parameter named by
parameter_map, defaulting to a parameterpyhf::<name>that is declared if it does not yet exist. The corresponding observables are registered with the supplied observable cache, so thatevaluate()can compute the main term of the pyhf log-likelihood from the current EOS parameter values. The constraint terms of the pyhf likelihood are not evaluated here; they are instead exposed as EOS priors viapriors().Using this class requires the optional
pyhfmodule.- Parameters:
cache (eos.ObservableCache) – The EOS observable cache to which the observables backing the pyhf parameters are added.
workspace (pyhf.workspace.Workspace | str) – A pyhf workspace, or the path to a JSON file specifying one.
parameter_map (dict | None) – An optional mapping from pyhf parameter names to EOS observables or parameters. Each value is either the qualified name of an EOS observable/parameter, or a dictionary with a
namekey and optionalkinematicsandoptionskeys. Parameters not listed default to an EOS parameter namedpyhf::<name>.
- Raises:
RuntimeError – If the
pyhfmodule is not installed.ValueError – If
workspaceis neither a pyhf workspace nor a path to a valid JSON file, or if aparameter_mapvalue is neither a string nor a dictionary.
- evaluate()
Evaluate the main term of the pyhf log-likelihood at the current parameter values.
The pyhf parameters are read from their associated EOS observables/parameters, and the main (non-constraint) term of the HistFactory log-likelihood is returned. Constraint terms are handled separately within EOS via the priors returned by
priors().- Returns:
The value of the main log-likelihood term.
- Return type:
- static factory(cache, workspace, parameter_map=None)
Construct a
PyhfLogLikelihood.Convenience factory with the same signature as the constructor; see the class documentation for a description of the arguments.
- Returns:
The constructed likelihood.
- Return type:
- priors()
Return the EOS prior descriptions corresponding to the pyhf constraint terms.
Each modifier (parameter) of the pyhf model is translated into an EOS prior description: unconstrained parameters yield a uniform prior over their suggested bounds, while parameters with a normal or Poisson constraint yield Gaussian or Poisson priors, respectively. Parameters mapped to an EOS observable (a dictionary entry in
parameter_map) are skipped, since they are not free parameters.
Common Tasks
In addition to the basic classes, EOS provides functions to carry out often-repeated tasks,
such as finding the mode of a posterior, sampling from a posterior, and similar.
Tasks require a description of the statistical analysis (see eos.Analysis) by means
of an analysis file. For a documentation of its format, see eos.AnalysisFile.
Tasks store their results in a hierarchy for directories below a user-provided base directory. This ensures that tasks can readily use results produced by another task.
- eos.create_constraint(analysis_file: str, posterior: str, constraint_name: str, base_directory: str = './', source: str = 'samples', parameters: list = None, tests: list = None, goodness_of_fit_threshold: float = 0.03, strict: bool = True)
Creates a MultivariateGaussian(Covariance) constraint from previously computed samples of a named posterior.
The fit is the closed-form weighted maximum-likelihood estimate: the weighted sample mean and weighted sample covariance of the selected columns. One or more named goodness-of-fit tests are then run on the fit; see tests and strict below for how a failing test is handled.
The input files are expected in EOS_BASE_DIRECTORY/data/POSTERIOR/SOURCE. The output file will be stored in EOS_BASE_DIRECTORY/constraints/CONSTRAINT_NAME/constraint.yaml.
- Parameters:
analysis_file (str or eos.AnalysisFile) – The name of the analysis file that describes the named posterior, or an object of class eos.AnalysisFile.
posterior (str) – The name of the posterior PDF from which to draw the samples.
constraint_name (str) – The qualified name under which the constraint is registered; also used verbatim as the output subdirectory name.
base_directory (str, optional) – The base directory for the storage of data files. Can also be set via the EOS_BASE_DIRECTORY environment variable.
source (str, optional) – The name of the data file inside the posterior’s data directory to fit. Defaults to ‘samples’ (the posterior’s own importance samples). A value starting with ‘pred-’ selects the posterior-predictive importance samples of that name, previously written by the predict-observables task.
parameters (list of str, optional) – The list of column names to constrain, matched against the loaded data’s lookup table (bare parameter names for source=’samples’; composite observable identifiers for a ‘pred-’ source). If None, every column of the loaded data is used.
tests (list of str, optional) – The names of the goodness-of-fit tests that must be run before the constraint is accepted. Defaults to [‘KS-test’]. Each name must be a key of goodness_of_fit_tests; call one of those functions directly (e.g. eos.ks_test) on your own reloaded samples to diagnose why a test failed.
goodness_of_fit_threshold (float or dict[str, float], optional) – The p-value threshold below which a test counts as failed. Either a single float applied to every test in tests, or a dict mapping each test name in tests to its own threshold.
strict (bool, optional) – If True (the default), a failed test logs an error and aborts the task – no constraint file is written. If False, a failed test only logs a warning, and the constraint is written regardless.
- eos.create_mask(analysis_file: str, posterior: str, mask_name: str, base_directory: str = './')
Creates a sample mask for a named posterior from a mask description in the analysis file.
The named mask’s description is a logical combination (
andoror) of observables and/or other masks. Each observable contributes the subset of samples for which it evaluates positive, and nested masks are created recursively. The combined mask is stored as aneos.data.SampleMaskin EOS_BASE_DIRECTORY/data/POSTERIOR/mask-MASK_NAME, and is also returned as a boolean array.- Parameters:
analysis_file (str or eos.AnalysisFile) – The name of the analysis file that describes the named posterior and mask, or an object of class eos.AnalysisFile.
posterior (str) – The name of the posterior whose samples are masked.
mask_name (str) – The name of the mask to create, as defined in the analysis file.
base_directory (str, optional) – The base directory for the storage of data files. Can also be set via the EOS_BASE_DIRECTORY environment variable.
- Returns:
The combined boolean mask, with one entry per posterior sample.
- Return type:
- eos.draw_figure(analysis_file: str, figure_name: str, base_directory: str = './', format: str | list[str] = 'pdf')
Draws figures from the analysis file.
The output files will be stored in EOS_BASE_DIRECTORY/figures/. If more than one format is requested, the figure is drawn once and stored once per format, since drawing the same figure repeatedly would stack its elements on top of each other.
- Parameters:
analysis_file (str or eos.AnalysisFile) – The name of the analysis file that describes the named posterior, or an object of class eos.AnalysisFile.
figure_name (str) – The name of the figure to draw.
base_directory (str, optional) – The base directory for the storage of data files. Can also be set via the EOS_BASE_DIRECTORY environment variable.
format (str or list of str, optional) – The file extension of the figure files. Can also be a list of file extensions.
- eos.find_clusters(posterior: str, base_directory: str = './', threshold: float = 2.0, K_g: int = 1, analysis_file: str = None)
Finds clusters among posterior MCMC samples, grouped by Gelman-Rubin R value, and creates a Gaussian mixture density.
Finding clusters and creating a Gaussian mixture density is a necessary intermediate step before using the sample-pmc subcommand. The input files are expected in EOS_BASE_DIRECTORY/data/POSTERIOR/mcmc-*. All MCMC input files present will be used in the clustering. The output files will be stored in EOS_BASE_DIRECTORY/data/POSTERIOR/clusters.
- Parameters:
posterior (str) – The name of the posterior.
base_directory (str, optional) – The base directory for the storage of data files. Can also be set via the EOS_BASE_DIRECTORY environment variable.
threshold (float, optional) – The R value threshold, which must be larger than 1.0. If two sample subsets have an R value larger than this threshold, they will be treated as two distinct clusters. Defaults to 2.0.
K_g (int, optional) – The number of mixture components per cluster, which must be at least 1. Default to 1.
- eos.find_mode(analysis_file: str, posterior: str, base_directory: str = './', optimizations: int = 3, start_point: list = None, chain: int = None, importance_samples: bool = None, seed: int = None, label: str = 'default', mask_name: str = None)
Finds the mode of the named posterior using scipy SLSQP method by default.
The optimization process can be initialized either with a random point, a provided parameter point, or by extracting the point with the largest posterior from among previously obtained MCMC or importance samples. The latter possibility usually gives the better performence. The optimization can also be iterated to increase the accuracy of the result.
The output file will be stored in EOS_BASE_DIRECTORY/data/POSTERIOR/mode-LABEL.
- Parameters:
analysis_file (str or eos.AnalysisFile) – The name of the analysis file that describes the named posterior, or an object of class eos.AnalysisFile.
posterior (str) – The name of the posterior PDF from which to draw the samples.
base_directory (str, optional) – The base directory for the storage of data files. Can also be set via the EOS_BASE_DIRECTORY environment variable.
optimizations (int, optional) – The number of calls to the optimization algorithm.
start_point (numpy.ndarray, optional) – If provided, the optimization will start at this point.
chain (int, optional) – If provided, the optimization will start at the point with the largest posterior of previously computed MCMC samples. The samples are expected to be stored in the mcmc-XXXX subdirectories of the base_directory, where ‘XXXX’ is the provided int.
importance_samples (bool, optional) – If set to True, the optimization will start at the point with the largest posterior of previously computed importance samples.
seed (int, optional) – If provided, the optimization will start from a random point and the random number generator will be seeded with this value.
- eos.list_figures(analysis_file: str)
Lists all figures that can be created from the analysis file.
- Parameters:
analysis_file (str or
eos.AnalysisFile) – The name of the analysis file, or an object of class eos.AnalysisFile.
- eos.list_step_dependencies(analysis_file: str, id: str)
Lists all steps required to be completed before the given step can be executed.
- Parameters:
analysis_file (str or
eos.AnalysisFile) – The name of the analysis file that shall be inspected`.id (str) – The id of the step to inspect.
- eos.list_steps(analysis_file: str)
Lists the steps in the analysis file.
- Parameters:
analysis_file (str or
eos.AnalysisFile) – The name of the analysis file that shall be inspected`.
- eos.mixture_product(posterior: str, posteriors: list, base_directory: str = './', analysis_file: str = None)
Compute the cartesian product of the densities listed in posteriors. Note that this product is not commutative.
The input densities are read from EOS_BASE_DIRECTORY/data/POSTERIOR_i/pmc, where POSTERIOR_i is listed in posteriors. The output density will be stored in EOS_BASE_DIRECTORY/data/POSTERIOR/product.
- Parameters:
posterior (str) – The name of the posterior.
posteriors (collections.abc.Iterable of str) – The list of names of the posteriors whose mixture densities will be concatenated.
base_directory (str, optional) – The base directory for the storage of data files. Can also be set via the EOS_BASE_DIRECTORY environment variable.
- eos.predict_observables(analysis_file: str, posterior: str, prediction: str, base_directory: str = './', begin: int = 0, end: int = None, mask_name: str = None)
Predicts a set of observables based on previously obtained importance samples.
The input files are expected in EOS_BASE_DIRECTORY/data/POSTERIOR/samples. The output files will be stored in EOS_BASE_DIRECTORY/data/POSTERIOR/pred-PREDICTION.
- Parameters:
analysis_file (str or eos.AnalysisFile) – The name of the analysis file that describes the named posterior, or an object of class eos.AnalysisFile.
posterior (str) – The name of the posterior.
prediction (str) – The name of the set of observables to predict.
base_directory (str, optional) – The base directory for the storage of data files. Can also be set via the EOS_BASE_DIRECTORY environment variable.
begin (int) – The index of the first sample to use for the predictions. Defaults to 0.
end – The index beyond the last sample to use for the predictions. Defaults to None.
mask_name (str, optional) – The label of the mask to apply to the observables. Defaults to None.
- eos.report(analysis_file: str, template_file: str, base_directory: str = './', generate_pdf: bool = True)
Generates a report from an analysis file and a Jinja2 template file.
The processed file will be stored in the same directory as the template file, with the the extension ‘.jinja’ or ‘.jinja2’ stripped from the file name. If generate_pdf is set to True, the intermediate file will be converted to PDF using Pandoc and XeLaTeX. This requires a working installation of both programs.
- Parameters:
analysis_file (str or eos.AnalysisFile) – The name of the analysis file that shall be used for the report.
template_file (str) – The name of the Jinja2 template file that shall be used for the report.
base_directory (str, optional) – The base directory for the storage of data files. Can also be set via the EOS_BASE_DIRECTORY environment variable.
generate_pdf (bool, optional) – The flag that enables the conversion of the intermediate file to PDF. Defaults to True.
- eos.run(analysis_file: str, id: str, base_directory: str = './', dry_run: bool = False)
Runs one out of a list of predefined steps recorded in the analysis file.
- Each step corresponds to a call to one or more of the common tasks, e.g.,
sample-mcmc
find-cluster
sample-pmc
predict-observables
- Parameters:
analysis_file (str or eos.AnalysisFile) – The name of the analysis file that describes the named posterior, or an object of class eos.AnalysisFile.
id (str) – The id of the step to run.
base_directory (str, optional) – The base directory for the storage of data files. Can also be set via the EOS_BASE_DIRECTORY environment variable.
dry_run (bool, optional) – The flag that disables execution and instead prints the full information on the tasks that would be run to standard output. Defaults to False.
- eos.sample_mcmc(analysis_file: str, posterior: str, chain: int, base_directory: str = './', pre_N: int = 150, preruns: int = 3, N: int = 1000, stride: int = 5, cov_scale: float = 0.1, start_point: list = None)
Samples from a named posterior PDF using Markov Chain Monte Carlo (MCMC) methods.
The output file will be stored in EOS_BASE_DIRECTORY/data/POSTERIOR/mcmc-CHAIN.
- Parameters:
analysis_file (str or eos.AnalysisFile) – The name of the analysis file that describes the named posterior, or an object of class eos.AnalysisFile.
posterior (str) – The name of the posterior PDF from which to draw the samples.
chain (int) – The index assigned to the Markov chain, which must be non-negative. This value is used to seed the RNG for a reproducible analysis.
base_directory (str, optional) – The base directory for the storage of data files. Can also be set via the EOS_BASE_DIRECTORY environment variable.
pre_N (int, optional) – The number of samples to be used for an adaptation in each prerun steps. These samples will be discarded.
preruns (int, optional) – The number of prerun steps, which are used to adapt the MCMC proposal to the posterior.
N (int, optional) – The number of samples to be stored in the output file. Defaults to 1000.
stride (int, optional) – The ratio of samples drawn over samples stored. For every S samples, S - 1 will be discarded. Defaults to 5.
cov_scale (float, optional) – Scale factor for the initial guess of the covariance matrix.
start_point (collections.abc.Sequence, optional) – Optional starting point for the chain
- eos.sample_nested(analysis_file: str, posterior: str, base_directory: str = './', bound: str = 'multi', nlive: int = 250, dlogz: float = 1.0, maxiter: int = None, miniter: int = 0, min_ess: int = 0, seed: int = 10, sample: str = 'auto')
Samples from a likelihood associated with a named posterior using dynamic nested sampling.
The output will be stored in EOS_BASE_DIRECTORY/data/POSTERIOR/nested. In addition, an ImportanceSamples object is exported to EOS_BASE_DIRECTORY/data/POSTERIOR/samples.
- Parameters:
analysis_file (str or eos.AnalysisFile) – The name of the analysis file that describes the named posterior, or an object of class eos.AnalysisFile.
posterior (str) – The name of the posterior.
base_directory (str, optional) – The base directory for the storage of data files. Can also be set via the EOS_BASE_DIRECTORY environment variable.
bound (str, optional) – The option for bounding the target distribution. For valid values, see the dynesty documentation. Defaults to ‘multi’.
nlive (int, optional) – The number of live points.
dlogz (float, optional) – The relative tolerance for the remaining evidence. Defaults to 1.0.
maxiter (int, optional) – The maximum number of iterations. Iterations may stop earlier if the termination condition is reached.
miniter (int, optional) – The minimum number of iterations. If not provided, the sampler will run until the termination condition is reached. Defaults to 0.
min_ess (int, optional) – The minimum effective sample size (ESS). Samples will be added until the estimated ESS reaches min_ess, even if the termination condition is reached earlier. If 0 (default), dynesty’s default ESS target is used.
seed (int, optional) – The seed used to initialize the Mersenne Twister pseudo-random number generator.
sample (str, optional) – The method used for sampling within the likelihood constraints. For valid values, see dynesty documentation. Defaults to ‘auto’.
- eos.sample_pmc(analysis_file: str, posterior: str, base_directory: str = './', step_N: int = 500, steps: int = 10, final_N: int = 5000, perplexity_threshold: float = 1.0, weight_threshold: float = 1e-10, sigma_test_stat: list = None, initial_proposal: str = 'clusters', pmc_iterations: int = 1, pmc_rel_tol: float = 1e-10, pmc_abs_tol: float = 1e-05, pmc_lookback: int = 1)
Samples from a named posterior using the Population Monte Carlo (PMC) methods.
The results of the find-cluster command are expected in EOS_BASE_DIRECTORY/data/POSTERIOR/clusters. The output will be stored in EOS_BASE_DIRECTORY/data/POSTERIOR/pmc. In addition, an ImportanceSamples object is exported to EOS_BASE_DIRECTORY/data/POSTERIOR/samples.
- Parameters:
analysis_file (str or eos.AnalysisFile) – The name of the analysis file that describes the named posterior, or an object of class eos.AnalysisFile.
posterior (str) – The name of the posterior.
base_directory (str, optional) – The base directory for the storage of data files. Can also be set via the EOS_BASE_DIRECTORY environment variable.
step_N (int, optional) – The number of samples to be used in each adaptation step, which must be positive. These samples will be discarded. Defaults to 500.
steps (int, optional) – The number of adaptation steps, which must be positive, and which are used to adapt the PMC proposal to the posterior. Defaults to 10.
final_N (int, optional) – The number of samples to be stored in the output file, which must be positive. Defaults to 5000,
perplexity_threshold (float, optional) – The threshold for the perplexity in the last step after which further adaptation steps are to be skipped. Must be larger than 0.0 and at most 1.0. Defaults to 1.0.
weight_threshold (float, optional) – Mixture components with a weight smaller than this threshold are pruned. Must be larger than 0.0 and at most 1.0.
sigma_test_stat (list or collections.abc.Iterable) – If provided, the inverse CDF of -2*log(PDF) will be evaluated, using the provided values as the respective significance.
initial_proposal (str, optional) –
Specify where the initial proposal should be taken from:
clusters: use the proposal obtained using find-clusters (default)product: use the proposal obtained from mixture_productpmc: continue sampling from the previous sample-pmc results.
pmc_iterations (int, optional) – Maximum number of update of the PMC, which must be positive. This is an advanced option; changing this value may make the update unstable.
pmc_rel_tol (float, optional) – Relative tolerance of the PMC, which must be positive. This is an advanced option. If two consecutive values of the current density log-likelihood are relatively smaller than this value, the convergence is declared.
pmc_abs_tol (float, optional) – Absolute tolerance of the PMC, which must be positive. This is an advanced option. If two consecutive values of the current density log-likelihood are smaller than this value, the convergence is declared.
pmc_lookback (int, optional) – Use reweighted samples from the previous update steps when adjusting the mixture density. The parameter determines the number of update steps to “look back”, and must be non-negative. The default value of 1 disables this feature, a value of 0 means that all previous steps are used.
- eos.sample_prior(analysis_file: str, posterior: str, base_directory: str = './', N: int = 1000, seed: int = 1701)
Samples from a named posterior PDF w/o likelihood information, an effective prior PDF.
The output file will be stored in EOS_BASE_DIRECTORY/data/POSTERIOR/samples.
- Parameters:
analysis_file (str or eos.AnalysisFile) – The name of the analysis file that describes the named prior, or an object of class eos.AnalysisFile.
posterior (str) – The name of the posterior PDF (w/o any likelihood information) from which to draw the samples.
base_directory (str, optional) – The base directory for the storage of data files. Can also be set via the EOS_BASE_DIRECTORY environment variable.
N (int, optional) – The number of samples to be stored in the output file. Defaults to 1000.
seed (int, optional) – The seed used to initialize the Mersenne Twister pseudo-random number generator.
- eos.validate(analysis_file: str, deep: bool = True)
Validates the analysis file structurally and semantically, then by default checks that all posteriors and prediction sets can be created. The deep phase inserts declarations into the process-wide EOS registries; once it has run, those registries are contaminated for the remainder of the process. Use
deep=Falsefor idempotent, side-effect-free validation.
Accessing Data
EOS provides access to save and load the various (intermediate) results of analyses via the eos.data module.
- class eos.data.ImportanceSamples(path)
Represents a set of weighted importance samples stored on disk.
Bundles samples in parameter space with their importance weights and, optionally, the values of the posterior density at each sample. Instances are created either by reading an existing data set from disk (passing its
pathto the constructor) or by writing a new data set withcreate().- Variables:
type – The type identifier of the data object, always
'ImportanceSamples'.varied_parameters – The descriptions (name, min, max) of the varied parameters.
lookup_table – A mapping from each parameter name to its column index in
samples.weights – The importance weights on a linear scale as a 1D array of shape (N, ).
posterior_values – The posterior density values at each sample as a 1D array of shape (N, ), or
Noneif not stored.
- static create(path, parameters, samples, weights, posterior_values=None)
Write a new ImportanceSamples object to disk.
- Parameters:
path (str) – Path to the storage location, which will be created as a directory.
parameters (collections.abc.Sequence of eos.Parameter) – Parameter descriptions as a 1D array of shape (P, ).
samples (numpy.ndarray) – Samples as a 2D array of shape (N, P).
weights (numpy.ndarray, optional) – Weights on a linear scale as a 1D array of shape (N, ).
- class eos.data.MarkovChain(path)
Represents the parameter samples of a single Markov chain stored on disk.
A Markov chain bundles samples drawn in parameter space together with their counterparts in the unit-hypercube
uspace and, optionally, importance weights. Instances are created either by reading an existing chain from disk (passing itspathto the constructor) or by writing a new chain withcreate().- Variables:
type – The type identifier of the data object, always
'MarkovChain'.varied_parameters – The descriptions (name, min, max) of the varied parameters.
lookup_table – A mapping from each parameter name to its column index in
samples.usamples – The samples in unit-hypercube
uspace as a 2D array of shape (N, P).weights – The importance weights on a linear scale as a 1D array of shape (N, ), or
Noneif the chain is unweighted.
- static create(path, parameters, samples, usamples, weights=None)
Write a new MarkovChain object to disk.
- Parameters:
path (str) – Path to the storage location, which will be created as a directory.
parameters (collections.abc.Sequence of eos.Parameter) – Parameter descriptions as a 1D array of shape (N, ).
samples (numpy.ndarray) – Samples in parameter space as a 2D array of shape (N, P).
usamples (numpy.ndarray) – Samples in u space as a 2D array of shape (N, P).
weights (numpy.ndarray, optional) – Weights on a linear scale as a 1D array of shape (N, ).
- class eos.data.MixtureDensity(path)
Represents a mixture density (e.g. a PMC proposal or a fit to a posterior) stored on disk.
Stores the components and weights of a mixture of (Gaussian) densities together with the descriptions of the varied parameters and, optionally, precomputed test statistics. Instances are created either by reading an existing density from disk (passing its
pathto the constructor) or by writing a new density withcreate(). Usedensity()to obtain the correspondingpypmc.density.mixture.MixtureDensity.- Variables:
type – The type identifier of the data object, always
'MixtureDensity'.format_version – The on-disk format version the density was read from (1 for legacy files).
components – The descriptions of the mixture components.
weights – The component weights of the mixture.
lookup_table – A mapping from each parameter name to its index in
varied_parameters.test_statistics – The precomputed test statistics, or
Noneif not stored.
- static cartesian_product(densities)
Construct the cartesian product of a list of mixture densities. The means and covariances of the components are copied and concatenated and the weights are multiplied. Note that this product is not commutative, the order of densities affects the order of parameters in the output density. Only Gaussian mixtures are supported.
- Parameters:
densities (collections.abc.Sequence of pypmc.density.MixtureDensity) – List of mixture densities.
- static create(path, density, parameters, sigma_test_stat=None, samples=None, weights=None)
Write a new MixtureDensity object to disk.
- Parameters:
path (str) – Path to the storage location, which will be created as a directory.
density (pypmc.density.MixtureDensity) – Mixture density.
parameters (list or collections.abc.Iterable of eos.Parameter) – Parameter descriptions as a 1D array of shape (P, ).
sigma_test_stat (list or collections.abc.Iterable) – (optional) If provided, the inverse CDF of -2*log(PDF) will be evaluated, using the provided values as the respective significance.
samples (numpy.ndarray, optional) – Samples as a 2D array of shape (N, P). Needed to generate the test statistic.
weights (numpy.ndarray, optional) – Weights on a linear scale as a 2D array of shape (N, 1). Needed to generate the test statistic.
- density()
Construct the corresponding PyPMC mixture density.
- Returns:
A Gaussian mixture density built from the stored components and weights.
- Return type:
pypmc.density.mixture.MixtureDensity
- Raises:
ImportError – If the optional PyPMC module is not installed.
- class eos.data.Mode(path)
Represents a (local) mode of a posterior density stored on disk.
Stores the location of the mode in parameter space together with goodness-of-fit information. Instances are created either by reading an existing mode from disk (passing its
pathto the constructor) or by writing a new mode withcreate()(low-level) orfrom_bfp_and_gof()(from an optimization result).- Variables:
type – The type identifier of the data object, always
'Mode'.format_version – The on-disk format version the mode was read from (1 for legacy files).
varied_parameters – The descriptions (name, min, max) of the varied parameters.
mode – The location of the mode in parameter space.
pvalue – The global p-value at the mode.
local_pvalues – A mapping from each element’s name to its local p-value, derived from
test_statistics.global_chi2 – The global \(\chi^2\) value at the mode, or
Noneif not stored.dof – The number of degrees of freedom, or
Noneif not stored.
- static create(path, parameters, mode, pvalue, test_statistics, global_chi2, dof)
Write a new Mode object to disk.
This is the low-level serializer. To record a mode obtained from an optimization, prefer
from_bfp_and_gof(), which derives the arguments below from the best-fit point and the goodness-of-fit object.- Parameters:
path (str) – Path to the storage location, which will be created as a directory.
parameters (list or collections.abc.Iterable of eos.Parameter) – Parameter descriptions as a 1D array of shape (N, ).
mode (numpy.ndarray) – The mode to be stored.
pvalue (float) – The global p-value of the mode.
test_statistics (list of dict) – The per-element test statistics, each a mapping with the keys
name,local_pvalueand, optionally,type(default'chi^2') andvalue.global_chi2 (float) – The global chi2 value of the mode.
dof (float) – The degrees of freedom of the mode.
- static from_bfp_and_gof(path, bfp, gof)
Write a new Mode object to disk from an optimization result.
Derives the varied parameters and the mode from the best-fit point
bfpand the global and per-element test statistics (chi^2 values, degrees of freedom, and p-values) from the goodness-of-fit objectgof, then delegates tocreate().- Parameters:
path (str) – Path to the storage location, which will be created as a directory.
bfp (eos.BestFitPoint) – The best-fit point, as returned by
eos.Analysis.optimize().gof (eos.GoodnessOfFit) – The goodness-of-fit at the best-fit point.
- class eos.data.PMCSampler(path)
Represents the proposal density of a population Monte Carlo (PMC) sampler stored on disk.
Stores the Gaussian components and weights of the PMC proposal mixture together with the descriptions of the varied parameters. Instances are created either by reading an existing sampler from disk (passing its
pathto the constructor) or by writing a new sampler withcreate(). Usedensity()to obtain the correspondingpypmc.density.mixture.MixtureDensity. Reading requires the optional PyPMC module.- Variables:
type – The type identifier of the data object, always
'PMCSampler'.lookup_table – A mapping from each parameter name to its index in
varied_parameters.components – The Gaussian components of the proposal mixture.
component_weights – The weights of the proposal mixture components.
test_statistics – The precomputed test statistics.
- static create(path, parameters, proposal, sigma_test_stat=None, samples=None, weights=None)
Write a new PMCSampler object to disk.
- Parameters:
path (str) – Path to the storage location, which will be created as a directory.
parameters (list or collections.abc.Iterable of eos.Parameter) – Parameter descriptions as a 1D array of shape (P, ).
sigma_test_stat (list or collections.abc.Iterable) – (optional) If provided, the inverse CDF of -2*log(PDF) will be evaluated, using the provided values as the respective significance.
samples (numpy.ndarray, optional) – Samples as a 2D array of shape (N, P). Needed to generate the test statistic.
weights (numpy.ndarray, optional) – Weights on a linear scale as a 1D array of shape (N, ). Needed to generate the test statistic.
- density()
Construct the corresponding PyPMC mixture density.
- Returns:
A Gaussian mixture density built from the stored proposal components and weights.
- Return type:
pypmc.density.mixture.MixtureDensity
- Raises:
ImportError – If the optional PyPMC module is not installed.
- class eos.data.Prediction(path)
Represents weighted samples of theory predictions for one or more observables, stored on disk.
Bundles the predictive samples of a set of observables with their importance weights. Instances are created either by reading an existing data set from disk (passing its
pathto the constructor) or by writing a new data set withcreate().Each column is either a genuine observable or a parameter clothed as an observable; the two are distinguished by the
kindkey of the corresponding entry invaried_parameters.- Variables:
type – The type identifier of the data object, always
'Prediction'.format – The on-disk format version the prediction was read from (1 for legacy files).
lookup_table – A mapping from each column’s qualified name (including options and kinematics) to its column index in
samples.weights – The importance weights on a linear scale as a 1D array of shape (N, ).
- static create(path, observables, samples, weights)
Write a new Prediction object to disk.
- Parameters:
path (str) – Path to the storage location, which will be created as a directory.
observables (collections.abc.Sequence of eos.Observable) – Observables as a 1D array of shape (O, ).
samples (numpy.ndarray) – Samples as a 2D array of shape (N, O).
weights (numpy.ndarray) – Weights on a linear scale as a 1D array of shape (N, ).
- class eos.data.SampleMask(path)
Represents a boolean mask over a set of observables, stored on disk.
A mask selects a subset of samples (e.g. to remove unphysical points) and records the observables it applies to. Instances are created either by reading an existing mask from disk (passing its
pathto the constructor) or by writing a new mask withcreate().- Variables:
type – The type identifier of the data object, always
'SampleMask'.observables – The observables to which the mask applies.
mask – The boolean mask as a 1D array.
- static create(path, mask, observables)
Write a new SampleMask object to disk.
- Parameters:
path (str) – Path to the storage location, which will be created as a directory.
mask (collections.abc.Sequence of bool) – Mask as a 1D boolean array
observables – Observables as a 1D array
Plotting Classes
The eos.figure submodule provides means to produce publication-quality figures.
A figure contains one or more plots, each of which is a set of axis that can be thought of as a ‘canvas’ to draw on. A plot further contains items for display, for example a constraint in the form of data points with error bars or an observable as a function of a kinematic variable in the form or a line graph.
Note
Import eos.figure before you do something like import matplotlib.pyplot as plt,
because the eos.figure module modified the default plot style and the matplotlib backend.
All options (except the backend) can be overwritten by updating matplotlib.rcParams[...];
see also the matplotlib documentation.
Note that the default settings use LaTeX to create labels and math expressions,
so for this to work latex needs to be available on your system.
EOS also provides a new plotting framework with a different interface, which will replace
the existing framework as soon as it is feature complete. Within the new framework, Figures
are created using the eos.figure.FigureFactory class, which returns an object
of a class descended by eos.figure.Figure. The figure is responsible for creating
and managing the matplotlib figure object. It also creates the
plot or plots that are contained in the figure as objects of classes descended from
eos.figure.plot.Plot. These objects manage the axes of the figure and
the individual plot items that are contained in the plot. The actual contents are created using
the eos.figure.item.ItemFactory class, which returns an object of a class descended from
eos.figure.item.Item. The item is responsible for creating the actual
plot item, such as the curve of an EOS observable, a scatter plot of parameters, a histogram
or a kernel density estimate, to name some of the options.
A figure is rendered by its draw method, and the rendered figure
is stored to one or more output files by its save method. A figure
must only be drawn once; drawing it repeatedly stacks its elements on top of each other, which distorts
the colors of elements with an opacity < 1.
Utility Classes
- class eos.analysis_file_context.AnalysisFileContext(*, base_directory: str = './')
Auxiliary class used to resolve paths relative to an analysis file’s base directory.
Instances are passed to consumers of an analysis file (e.g. figures and tasks) so that relative data paths can be resolved against a common base directory.
- Parameters:
base_directory (str) – The base directory against which relative paths are resolved. Defaults to the current working directory.
- data_path(relative_path: str)
Resolve a path relative to
base_directoryinto an absolute path.
- class eos.diagnostic.Diagnostic(path: tuple, severity: eos.diagnostic.Severity, message: str, line: int | None = None)
- class eos.diagnostic.Severity(*values)
- class eos.figure.DataFile(*, path: str, label: str, color: str = None, kde: bool = False)
Collects the relevant information to load a data file, to extract data, variables, and labels from it.
- Parameters:
path (str) – Path to the data file (either in eos.Prediction or eos.ImportanceSample format) that will be used.
label (str) – Title to appear in a figure’s legend in association with this data file.
color (str (optional)) – Color to be used in the plot.
kde (bool) – A boolean determining whether to use kernel density estimates (KDE) to visualize the distributions. Defaults to False, in which case histograms are used.
- property empirical_range
An empirically determined plotting range for each variable in the data file.
For each variable, the range is centered on the weighted median and extends to 1.3 times the distance from the median to the weighted 1% and 99% quantiles, respectively.
- Returns:
A tuple
(min, max)of arrays holding the lower and upper bound for each variable.- Return type:
- labels(variables)
Return LaTeX labels for the given variables.
For parameter samples, the labels are taken from the corresponding EOS parameters; for predictions, they are taken from the corresponding EOS observables, falling back to the parameter label if the name does not identify an observable.
- Parameters:
variables (list[str]) – The names of the variables for which labels are requested.
- Returns:
The LaTeX label for each requested variable, in the same order.
- Return type:
- Raises:
NotImplementedError – If the data file has an unsupported format.
- prepare(context: AnalysisFileContext = None)
Load the underlying data file and cache it for subsequent access.
Resolves
pathagainst the given context, opens the file as eithereos.data.ImportanceSamples(a file namedsamples) oreos.data.Prediction(a file whose name starts withpred-), and records the available variable names. The result is cached, so repeated calls return the already-loaded data file without reloading.- Parameters:
context (AnalysisFileContext | None) – The analysis file context used to resolve the relative
path. IfNone, a default context rooted at the current working directory is used.- Returns:
The loaded data file.
- Return type:
- Raises:
ValueError – If the data file does not exist.
NotImplementedError – If the data file has an unsupported format.
- class eos.figure.Watermark(*, position: str = 'upper right', preliminary: bool = False, xy: tuple[float, float] | None = None, offset: float | tuple[float, float] | None = None)
Inserts an EOS watermark into a figure.
- Parameters:
position (str) – The position of the watermark as
'<vpos> <hpos>'. The vertical position can be any of'right','left'and'center'. The horizontal position can be any of'upper','lower', and'center'.preliminary (bool) – If true, marks the figure as a preliminary version.
xy (tuple[float, float] | None) – An explicit anchor point in axes fraction. If given, it overrides the coordinates derived from
position, while the text alignment is still taken fromposition. Defaults to None (use thepositionpreset).offset (float | tuple[float, float] | None) – The offset from the edges for the
positionpresets, given as a single fraction (used for both axes) or as a(xdelta, ydelta)pair. Defaults to None (i.e. 0.04 on both axes).
- draw(ax)
Draw the EOS watermark on the provided axes.
Renders the EOS version (or the word
Preliminary) as a semi-transparent label at the configured corner of the axes.- Parameters:
ax (matplotlib.axes.Axes) – The matplotlib axes onto which the watermark is drawn.
Analysis File Description Classes
The classes in the eos.analysis_file_description module describe the individual elements of an
analysis file. Each class corresponds to a key, or a type of entry, of the
analysis file format; its fields correspond to the keys of the respective YAML object.
The metadata of an analysis is described by:
- class eos.analysis_file_description.MetadataDescription(title: str = '', id: str = '', authors: list[MetadataAuthorDescription] = <factory>, description: str = '')
Describes the metadata of an analysis file.
- Parameters:
title (str) – A human-readable title for the analysis. Optional.
description (str) – A human-readable description of the analysis. Optional.
id (str) – A unique identifier for the analysis. Optional.
authors (list[MetadataAuthorDescription]) – The list of authors of the analysis. Optional.
- static from_dict(**kwargs)
Create a
MetadataDescriptionfrom its keyword description.Deserializes the nested
authorslist intoMetadataAuthorDescriptioninstances.- Returns:
The instantiated metadata description.
- Return type:
- class eos.analysis_file_description.MetadataAuthorDescription(name: str, affiliation: str = '', email: str = '')
Describes a single author in an analysis file’s metadata.
A named prior, and the prior densities it comprises, are described by:
- class eos.analysis_file_description.PriorDescription
Polymorphic description of a single prior on one or more parameters.
This is a dispatcher rather than a concrete description:
from_dict()selects the concrete type from thetypekey. The recognized types areconstraint(ConstraintPriorDescription),uniform/flat(UniformPriorDescription),scale(ScalePriorDescription),gauss/gaussian(GaussianPriorDescription, orCurtailedGaussianDescriptionifmin/maxare given),poisson(PoissonPriorDescription), andtransform(TransformPriorDescription).For backwards compatibility, a description that omits the
typekey but provides aconstraintkey is still interpreted as aConstraintPriorDescription; this form is deprecated.- static from_dict(**kwargs)
Create the concrete prior description matching the given keyword description.
- Returns:
An instance of the concrete
PriorDescriptionsubtype selected fromtype.
- class eos.analysis_file_description.PriorComponent(name: str, descriptions: list)
Describes a single named prior, i.e. one entry of an analysis file’s
priorslist.A named prior bundles one or more prior descriptions: a single description for a univariate prior, or several for an (uncorrelated) multivariate prior.
- Parameters:
name (str) – The unique name of the prior, by which posteriors refer to it.
descriptions (list[PriorDescription]) – The list of prior descriptions that make up this prior.
- classmethod from_dict(**kwargs)
Create a
PriorComponentfrom its keyword description.Deserializes each entry of
descriptionsviaPriorDescription.from_dict(). The deprecatedparameterskey is still accepted as a fall-back alias fordescriptions.- Returns:
The instantiated prior component.
- Return type:
- class eos.analysis_file_description.ConstraintPriorDescription(constraint: str)
Describes a (possibly correlated, multivariate) prior taken from a built-in EOS constraint.
- Parameters:
constraint (str) – The qualified name of the EOS constraint used as the prior.
- class eos.analysis_file_description.UniformPriorDescription(parameter: str, min: float, max: float)
Describes a uniform (flat) prior on a single parameter.
- class eos.analysis_file_description.ScalePriorDescription(parameter: str, min: float, max: float, mu_0: float, lambda_scale: float)
Describes a prior on a renormalization scale parameter.
- Parameters:
parameter (str) – The qualified name of the scale parameter.
min (float) – The lower bound of the scale variation.
max (float) – The upper bound of the scale variation.
mu_0 (float) – The default (central) scale.
lambda_scale (float) – The multiplicative factor that controls the width of the log-uniform variation.
- class eos.analysis_file_description.GaussianPriorDescription(parameter: str, central: float, sigma: float)
Describes a Gaussian prior on a single parameter.
- class eos.analysis_file_description.CurtailedGaussianDescription(parameter: str, central: float, sigma: float, min: float, max: float)
Describes a Gaussian prior truncated to a finite interval (
type: gausswithmin/max).Deprecated since version 1.0.21: The curtailed Gaussian prior description is deprecated and will be removed in a future version of EOS; use
type: gaussianwithout themin/maxkeys instead.- Parameters:
- class eos.analysis_file_description.PoissonPriorDescription(parameter: str, k: float)
Describes a Poisson prior on a single parameter.
- class eos.analysis_file_description.TransformPriorDescription(parameters: list[str], shift: list[float], transform: list[list[float]], min: list[float], max: list[float])
Describes a prior on a linear transformation of several parameters.
- Parameters:
parameters (list[str]) – The qualified names of the parameters that enter the transformation.
shift (list[float]) – The constant shift applied to the parameters before the transformation.
transform (list[list[float]]) – The transformation matrix applied to the (shifted) parameters.
min (list[float]) – The lower bounds of the transformed parameters’ support.
max (list[float]) – The upper bounds of the transformed parameters’ support.
A named likelihood, and the constraints it comprises, are described by:
- class eos.analysis_file_description.LikelihoodComponent(name: str, constraints: list = <factory>, manual_constraints: list = <factory>, pyhf: PyHFConstraintDescription | None = None)
Describes a single named likelihood, i.e. one entry of an analysis file’s
likelihoodslist.A named likelihood may combine any number of built-in constraints, inline (manual) constraints, and pyhf-based contributions; at least one of the three must be present.
- Parameters:
name (str) – The unique name of the likelihood, by which posteriors refer to it.
constraints (list[ConstraintLikelihoodDescription]) – The built-in EOS constraints contributing to the likelihood. Optional.
manual_constraints (list[ManualConstraintDescription]) – The inline constraint definitions contributing to the likelihood. Optional.
pyhf (PyHFConstraintDescription | None) – The pyhf-based contribution to the likelihood, or None if there is none. Optional.
- classmethod from_dict(**kwargs)
Create a
LikelihoodComponentfrom its keyword description.Deserializes the
constraints,manual_constraints, andpyhfentries into their respective description types.- Returns:
The instantiated likelihood component.
- Return type:
- class eos.analysis_file_description.ConstraintLikelihoodDescription(constraint: QualifiedName)
Describes a likelihood contribution taken from a built-in EOS constraint.
- Parameters:
constraint (eos.QualifiedName) – The qualified name of the EOS constraint.
- class eos.analysis_file_description.ManualConstraintDescription(name: QualifiedName, info: dict)
Describes a likelihood contribution from a constraint defined inline in the analysis file.
- Parameters:
name (eos.QualifiedName) – The qualified name under which the manual constraint is registered.
info (dict) – The constraint definition, in the same format as a built-in EOS constraint entry.
- class eos.analysis_file_description.PyHFConstraintDescription(file: str, parameter_map: dict = <factory>)
Describes a likelihood contribution imported from a pyhf workspace.
- Parameters:
file (str) – The path to the JSON file specifying the pyhf workspace.
parameter_map (dict) – An optional mapping from pyhf parameter names to EOS observables or parameters; see
eos.PyhfLogLikelihood.
A named posterior is described by:
- class eos.analysis_file_description.PosteriorDescription(name: str, prior: list, likelihood: list, global_options: dict = <factory>, fixed_parameters: dict = <factory>)
Describes a single named posterior, i.e. one entry of an analysis file’s
posteriorslist.A posterior combines one or more named priors with one or more named likelihoods, optionally fixing parameters and setting global options for all of its theory predictions.
- Parameters:
name (str) – The unique name of the posterior.
prior (list[str]) – The names of the priors that make up the posterior.
likelihood (list[str]) – The names of the likelihoods that make up the posterior.
global_options (dict) – Options forwarded to all theory predictions of the posterior. Optional.
fixed_parameters (dict) – Parameters to fix, given as a mapping from qualified name to value. Optional.
A custom observable is described by:
- class eos.analysis_file_description.ObservableComponent(name: str, latex: str, unit: str, expression: str, options: dict = <factory>)
Describes a custom observable defined in an analysis file’s
observablessection.- Parameters:
name (str) – The qualified name under which the new observable is registered.
latex (str) – The LaTeX representation of the observable, used in figures and tables.
unit (str) – The unit of the observable.
expression (str) – The EOS expression that defines the observable.
options (dict) – Default options applied when evaluating the observable. Optional.
A custom parameter is described by:
- class eos.analysis_file_description.ParameterComponent(name: str, latex: str, unit: str, central: float, min: float, max: float, alias_of: list = <factory>)
Describes a custom parameter defined in an analysis file’s
parameterssection.- Parameters:
name (str) – The new EOS qualified name of the parameter.
latex (str) – The LaTeX representation of the parameter, used in figures and tables.
unit (str) – The unit of the parameter.
central (float) – The default (central) value of the parameter.
min (float) – The lower end of the parameter’s allowed range.
max (float) – The upper end of the parameter’s allowed range.
alias_of (list[str]) – The qualified names of existing parameters for which this parameter is an alias. Optional.
A prediction, and the observables it comprises, are described by:
- class eos.analysis_file_description.PredictionDescription(name: str, observables: list, global_options: dict = <factory>, fixed_parameters: dict = <factory>)
Describes a single named prediction, i.e. one entry of an analysis file’s
predictionslist.A prediction lists the observables to be evaluated on previously obtained importance samples, optionally fixing parameters and setting global options.
- Parameters:
name (str) – The unique name of the prediction.
observables (list[PredictionObservableComponent]) – The observables to be predicted.
global_options (dict) – Options forwarded to all observables of the prediction. Optional.
fixed_parameters (dict) – Parameters to fix, given as a mapping from qualified name to value. Optional.
- classmethod from_dict(**kwargs)
Create a
PredictionDescriptionfrom its keyword description.Deserializes each entry of
observablesinto aPredictionObservableComponent.- Returns:
The instantiated prediction description.
- Return type:
- class eos.analysis_file_description.PredictionObservableComponent(name: str, kinematics: dict = <factory>, options: dict = <factory>)
Describes a single observable to be predicted, i.e. one entry of a prediction’s
observableslist.
A step, and the tasks it comprises, are described by:
- class eos.analysis_file_description.StepComponent(title: str, id: str, tasks: list, depends_on: list = <factory>, default_arguments: defaultdict = <factory>)
Describes a single step of a reproducible analysis, i.e. one entry of an analysis file’s
stepslist.A step bundles one or more task invocations, may declare dependencies on other steps, and may supply default arguments shared by its tasks.
- Parameters:
title (str) – A human-readable title for the step.
id (str) – The unique identifier of the step. Must not contain
/or whitespace.tasks (list[TaskComponent]) – The tasks executed by the step.
depends_on (list[str]) – The ids of steps that must complete before this step runs. Optional.
default_arguments (dict) – Default arguments per task name, applied to this step’s task invocations. Optional.
- classmethod from_dict(**kwargs)
Create a
StepComponentfrom its keyword description.Deserializes each entry of
tasksinto aTaskComponentand normalizes thedefault_argumentskeys against the per-task command-line argument map.- Returns:
The instantiated step component.
- Return type:
- class eos.analysis_file_description.TaskComponent(task: str, arguments: dict = <factory>)
Describes a single task invocation within a step, i.e. one entry of a step’s
taskslist.
A named mask, and the entries it comprises, are described by:
- class eos.analysis_file_description.MaskDescription
Polymorphic description of a single entry in a mask’s
descriptionlist.This is a dispatcher rather than a concrete description:
from_dict()inspects the keys of an entry and returns the matching concrete type. An entry containing anexpressionkey yields aMaskExpressionComponent, one containing amask_namekey yields aMaskNamedComponent, and otherwise the entry yields aMaskObservableComponent.- static from_dict(**kwargs)
Create the concrete mask-description entry matching the given keyword description.
- Returns:
An instance of the concrete
MaskDescriptionsubtype selected from the keys.- Return type:
MaskExpressionComponent | MaskNamedComponent | MaskObservableComponent
- class eos.analysis_file_description.MaskComponent(name: str, description: list, logical_combination: str = 'and')
Describes a single named mask, i.e. one entry of an analysis file’s
maskslist.A mask selects a subset of posterior samples by combining one or more (pseudo-)observables and/or other masks, keeping samples for which all (
and) or any (or) of them evaluate positive.- Parameters:
name (str) – The unique name of the mask.
description (list[MaskDescription]) – The entries that make up the mask.
logical_combination (str) – How the entries are combined, either
'and'or'or'. Defaults to'and'.
- classmethod from_dict(**kwargs)
Create a
MaskComponentfrom its keyword description.Deserializes each entry of
descriptionviaMaskDescription.from_dict().- Returns:
The instantiated mask component.
- Return type:
- class eos.analysis_file_description.MaskObservableComponent(name: str)
Describes a mask entry given by the name of an existing EOS observable.
- Parameters:
name (str) – The qualified name of the observable used for masking.