tools package¶
Submodules¶
tools.asciiGraph module¶
tools.caching module¶
tools.colors module¶
tools.coverage module¶
-
class
tools.coverage.
GeneralElement
(el, missingX, smFinalStates, bsmFinalStates)[source]¶ Bases:
object
This class represents a simplified (general) element which does only holds information about its even particles and decay type. The even particles are replaced/grouped by the particles defined in smFinalStates.
-
class
tools.coverage.
Uncovered
(topoList, sqrts=None, sigmacut=0.00E+00 [fb], groupFilters={'missing (all)': <function <lambda>>, 'missing (displaced)': <function <lambda>>, 'missing (prompt)': <function <lambda>>, 'outsideGrid (all)': <function <lambda>>}, groupFactors={'missing (all)': <function <lambda>>, 'missing (displaced)': <function <lambda>>, 'missing (prompt)': <function <lambda>>, 'outsideGrid (all)': <function <lambda>>}, groupdDescriptions={'missing (all)': 'missing topologies', 'missing (displaced)': 'missing topologies with displaced decays', 'missing (prompt)': 'missing topologies with prompt decays', 'outsideGrid (all)': 'topologies outside the grid'}, smFinalStates=None, bsmFinalSates=None)[source]¶ Bases:
object
Wrapper object for defining and holding a list of coverage groups (UncoveredGroup objects).
The class builds a series of UncoveredGroup objects and stores them.
Inititalize the object.
Parameters: - topoList – TopologyList object used to select elements from.
- sqrts – Value (with units) for the center of mass energy used to compute the missing cross sections. If not specified the largest value available will be used.
- sigmacut – Minimum cross-section/weight value (after applying the reweight factor) for an element to be included. The value should in fb (unitless)
- groupFilters – Dictionary containing the groups’ labels and the method for selecting elements.
- groupFactors – Dictionary containing the groups’ labels and the method for reweighting cross sections.
- groupdDescriptions – Dictionary containing the groups’ labels and strings describing the group (used for printout)
- smFinalStates – List of (inclusive) Particle or MultiParticle objects used for grouping Z2-even particles when creating GeneralElements.
- bsmFinalSates – List of (inclusive) Particle or MultiParticle objects used for grouping Z2-odd particles when creating GeneralElements.
-
class
tools.coverage.
UncoveredGroup
(label, elementFilter, reweightFactor, smFinalStates, bsmFinalStates, sqrts, sigmacut=0.0)[source]¶ Bases:
object
Holds information about a single coverage group: criteria for selecting and grouping elements, function for reweighting cross sections, etc.
Parameters: - label – Group label
- elementFilter – Function which takes an element as argument and returns True (False) if the element should (not) be selected.
- reweightFactor – Function which takes an element as argument and returns the reweighting factor to be applied to the element weight.
- smFinalStates – List of Particle/MultiParticle objects used to group Z2-even particles appearing in the final state
- bsmFinalStates – List of Particle/MultiParticle objects used to group Z2-odd particles appearing in the final state
- sqrts – Value (with units) for the center of mass energy used to compute the missing cross sections. If not specified the largest value available will be used.
- sigmacut – Minimum cross-section/weight value (after applying the reweight factor) for an element to be included. The value should in fb (unitless)
-
addToGeneralElements
(el, missingX)[source]¶ Adds an element to the list of missing topologies = general elements. If the element contributes to a missing topology that is already in the list, add element and weight to topology. :parameter el: element to be added :parameter missingX: missing cross-section for the element (in fb)
-
getMissingX
(element)[source]¶ Calculate total missing cross section of an element, by recursively checking if its mothers already appear in the list. :param element: Element object
Returns: missing cross section without units (in fb)
tools.crashReport module¶
-
class
tools.crashReport.
CrashReport
[source]¶ Bases:
object
Class that handles all crash report information.
-
createCrashReportFile
(inputFileName, parameterFileName)[source]¶ Create a new SModelS crash report file.
A SModelS crash report file contains:
- a timestamp
- SModelS version
- platform information (CPU architecture, operating system, …)
- Python version
- stack trace
- input file name
- input file content
- parameter file name
- parameter file content
Parameters: - inputFileName – relative location of the input file
- parameterFileName – relative location of the parameter file
-
tools.databaseBrowser module¶
-
class
tools.databaseBrowser.
Browser
(database, force_txt=False)[source]¶ Bases:
object
Browses the database, exits if given path does not point to a valid smodels-database. Browser can be restricted to specified run or experiment.
Parameters: - force_txt – If True forces loading the text database.
- database – Path to the database or Database object
-
getAttributes
(showPrivate=False)[source]¶ Checks for all the fields/attributes it contains as well as the attributes of its objects if they belong to smodels.experiment.
Parameters: showPrivate – if True, also returns the protected fields (_field) Returns: list of field names (strings)
-
getEfficiencyFor
(expid, dataset, txname, massarray)[source]¶ Get an efficiency for the given experimental id, the dataset name, the txname, and the massarray. Can only be used for EfficiencyMap-type experimental results. Interpolation is done, if necessary.
Parameters: - expid – experimental id (string)
- dataset – dataset name (string)
- txname – txname (string).
- massarray – list of masses with units, e.g. [[ 400.*GeV, 100.*GeV],[400.*GeV, 100.*GeV]]
Returns: efficiency
-
getULFor
(expid, txname, massarray, expected=False)[source]¶ Get an upper limit for the given experimental id, the txname, and the massarray. Can only be used for UL experimental results. Interpolation is done, if necessary.
Parameters: - expid – experimental id (string)
- txname – txname (string). ONLY required for upper limit results
- massarray – list of masses with units, e.g. [[ 400.*GeV, 100.*GeV],[400.*GeV, 100.*GeV]]
- expected – If true, return expected upper limit, otherwise return observed upper limit.
Returns: upper limit [fb]
-
getULForSR
(expid, datasetID)[source]¶ Get an upper limit for the given experimental id and dataset (signal region). Can only be used for efficiency-map results. :param expid: experimental id (string) :param datasetID: string defining the dataset id, e.g. ANA5-CUT3. :return: upper limit [fb]
-
getValuesFor
(attribute, expResult=None)[source]¶ Returns a list for the possible values appearing in the database for the required attribute (sqrts,id,constraint,…).
Parameters: - attribute – name of a field in the database (string).
- expResult – if defined, restricts the list to the corresponding expResult. Must be an ExpResult object.
Returns: list of values
-
loadAllResults
()[source]¶ Saves all the results from database to the _selectedExpResults. Can be used to restore all results to _selectedExpResults.
-
selectExpResultsWith
(**restrDict)[source]¶ Loads the list of the experimental results (pair of InfoFile and DataFile) satisfying the restrictions to the _selectedExpResults. The restrictions specified as a dictionary.
Parameters: restrDict – selection fields and their allowed values. E.g. lumi = [19.4/fb, 20.3/fb], txName = ‘T1’,….} The values can be single entries or a list of values. For the fields not listed, all values are assumed to be allowed.
tools.databaseClient module¶
-
class
tools.databaseClient.
DatabaseClient
(servername=None, port=None, verbose='info', rundir='./', logfile='@@rundir@@/dbclient.log', clientid=-1)[source]¶ Bases:
object
-
query
(msg)[source]¶ query a certain result, msg is eg. obs:ATLAS-SUSY-2016-07:ul:T1:[[5.5000E+02,4.5000E+02],[5.5000E+02,4.5000E+02]]
-
tools.databaseServer module¶
tools.externalPythonTools module¶
-
class
tools.externalPythonTools.
ExternalPythonTool
(importname, optional=False)[source]¶ Bases:
object
An instance of this class represents the installation of a python package. As it is python-only, we need this only for installation, not for running (contrary to nllfast or pythia).
Initializes the ExternalPythonTool object. Useful for installation. :params optional: optional package, not needed for core SModelS.
tools.inclusiveObjects module¶
tools.interactivePlots module¶
-
class
tools.interactivePlots.
Plotter
(smodelsFolder, slhaFolder, parameterFile, modelFile=None)[source]¶ Bases:
object
A class to store the required data and produce the interactive plots
Initializes the class.
Parameters: - smodelsFolder – path to the folder or tarball containing the smodels (python) output files
- slhaFolder – path to the folder or tarball containing the SLHA input files
- parameterFile – path to the file containing the plotting definitions
- modelFile – path to the model file, e.g smodels/share/models/mssm.py
-
editSlhaInformation
()[source]¶ Edits slha_hover_information,ctau_hover_information,BR_hover_information,variable_x,variable_y if they are defined as a list. The function transforms it in a dict whose keys are the object names
-
fillWith
(smodelsOutput, slhaData)[source]¶ Fill the dictionary (data_dict) with the desired data from the smodels output dictionary (smodelsDict) and the pyslha.Doc object slhaData
-
loadData
(npoints=-1)[source]¶ Reads the data from the smodels and SLHA folders. If npoints > 0, it will limit the number of points in the plot to npoints.
Parameters: npoints – Number of points to be plotted (int). If < 0, all points will be used.
-
tools.interactivePlots.
main
(args, indexfile='index.html')[source]¶ Create the interactive plots using the input from argparse
Parameters: args – argparser.Namespace object containing the options for the plotter Main interface for the interactive-plots.
Parameters: - smodelsFolder – Path to the folder or tarball containing the SModelS python output
- slhaFolder – Path to the folder or tarball containing the SLHA files corresponding to the SModelS output
- parameters – Path to the parameter file setting the options for the interactive plots
- npoints – Number of points used to produce the plot. If -1, all points will be used.
- verbosity – Verbosity of the output (debug,info,warning,error)
- indexfile – name of the starting web page (index.html)
Returns: True if the plot creation was successfull
tools.interactivePlotsHelpers module¶
-
class
tools.interactivePlotsHelpers.
Filler
(plotter, smodelsOutput, slhaData)[source]¶ Bases:
object
A class with the functions required to fill the data dictionary to produce the plots
-
getBR
()[source]¶ Gets the requested branching ratios from the slha file, that will go into de hover.
-
getExpres
()[source]¶ Extracts the Expres info from the .py output. If requested, the data will be appended on each corresponding list
-
getMaxMissingTopologyXsection
()[source]¶ Extracts the cross section of the missing topology with the largest cross section
-
getOutsideGrid
()[source]¶ Extracts the outside grid info from the .py output. If requested, the data will be appended on each corresponding list.
-
-
class
tools.interactivePlotsHelpers.
PlotlyBackend
(master, path_to_plots)[source]¶ Bases:
object
-
DataFrameExcludedNonexcluded
()[source]¶ Generate sub data frames for excluded and non-excluded points
-
SeparateContDiscPlots
()[source]¶ Generate sub lists of plots with discrete and conitnuous z axis variables.
-
makeContinuousPlots
(data_frame, data_selection)[source]¶ Generate plots with continuous z axis variables, using all data points
-
makeDiscretePlots
(data_frame, data_selection)[source]¶ Generate plots with discrete z axis variables, using all data points
-
-
tools.interactivePlotsHelpers.
getEntry
(inputDict, *keys)[source]¶ Get entry key in dictionary inputDict. If a list of keys is provided, it will assumed nested dictionaries (e.g. key1,key2 will return inputDict[key1][key2]).
-
tools.interactivePlotsHelpers.
getSlhaData
(slhaFile)[source]¶ Uses pyslha to read the SLHA file. Return a pyslha.Doc objec, if successful.
-
tools.interactivePlotsHelpers.
getSlhaFile
(smodelsOutput)[source]¶ Returns the file name of the SLHA file corresponding to the output in smodelsDict
tools.ioObjects module¶
-
class
tools.ioObjects.
FileStatus
[source]¶ Bases:
object
Object to run several checks on the input file. It holds an LheStatus (SlhaStatus) object if inputType = lhe (slha)
-
class
tools.ioObjects.
LheStatus
(filename)[source]¶ Bases:
object
Object to check if input lhe file contains errors.
Variables: filename – path to input LHE file
-
class
tools.ioObjects.
OutputStatus
(status, inputFile, parameters, databaseVersion)[source]¶ Bases:
object
Object that holds all status information and has a predefined printout.
Initialize output. If one of the checks failed, exit.
Parameters: - status – status of input file
- inputFile – input file name
- parameters – input parameters
- databaseVersion – database version (string)
-
class
tools.ioObjects.
SlhaStatus
(filename, findMissingDecayBlocks=True, findIllegalDecays=False, checkXsec=True)[source]¶ Bases:
object
An instance of this class represents the status of an SLHA file. The output status is: = 0 : the file is not checked, = 1: the check is ok = -1: case of a physical problem, e.g. charged LSP, = -2: case of formal problems, e.g. no cross sections
Parameters: - filename – path to input SLHA file
- findMissingDecayBlocks – if True add a warning for missing decay blocks
- findIllegalDecays – if True check if all decays are kinematically allowed
- checkXsec – if True check if SLHA file contains cross sections
- findLonglived – if True find stable charged particles and displaced vertices
-
emptyDecay
(pid)[source]¶ Check if any decay is missing for the particle with pid
Parameters: pid – PID number of particle to be checked Returns: True if the decay block is missing or if it is empty, None otherwise
-
evaluateStatus
()[source]¶ Get status summary from all performed checks.
Returns: a status flag and a message for explanation
-
findIllegalDecay
(findIllegal)[source]¶ Find decays for which the sum of daughter masses excels the mother mass
Parameters: findIllegal – True if check should be run Returns: status flag and message
-
findMissingDecayBlocks
(findMissingBlocks)[source]¶ For all non-SMpdgs particles listed in mass block, check if decay block is written
Returns: status flag and message
tools.modelTester module¶
-
tools.modelTester.
getAllInputFiles
(inFile)[source]¶ Given inFile, return list of all input files
Parameters: inFile – Path to input file or directory containing input files Returns: List of all input files, and the directory name
-
tools.modelTester.
getParameters
(parameterFile)[source]¶ Read parameter file, exit in case of errors
Parameters: parameterFile – Path to parameter File Returns: ConfigParser read from parameterFile
-
tools.modelTester.
loadDatabase
(parser, db)[source]¶ Load database
Parameters: - parser – ConfigParser with path to database
- db – binary database object. If None, then database is loaded, according to databasePath. If True, then database is loaded, and text mode is forced.
Returns: database object, database version
-
tools.modelTester.
loadDatabaseResults
(parser, database)[source]¶ Load database entries specified in parser
Parameters: - parser – ConfigParser, containing analysis and txnames selection
- database – Database object
Returns: List of experimental results
-
tools.modelTester.
runSetOfFiles
(inputFiles, outputDir, parser, databaseVersion, listOfExpRes, timeout, development, parameterFile)[source]¶ Loop over all input files in inputFiles with testPoint
Parameters: - inputFiles – list of input files to be tested
- outputDir – path to directory where output is be stored
- parser – ConfigParser storing information from parameter.ini file
- databaseVersion – Database version (printed to output file)
- listOfExpRes – list of ExpResult objects to be considered
- development – turn on development mode (e.g. no crash report)
- parameterFile – parameter file, for crash reports
Returns: printers output
-
tools.modelTester.
runSingleFile
(inputFile, outputDir, parser, databaseVersion, listOfExpRes, timeout, development, parameterFile)[source]¶ Call testPoint on inputFile, write crash report in case of problems
Parameters: - inputFile – path to input file
- outputDir – path to directory where output is be stored
- parser – ConfigParser storing information from parameter.ini file
- databaseVersion – Database version (printed to output file)
- listOfExpRes – list of ExpResult objects to be considered
- crashReport – if True, write crash report in case of problems
- timeout – set a timeout for one model point (0 means no timeout)
Returns: output of printers
-
tools.modelTester.
setExperimentalFlag
(parser)[source]¶ set the experimental flag, if options:experimental = True
-
tools.modelTester.
testPoint
(inputFile, outputDir, parser, databaseVersion, listOfExpRes)[source]¶ Test model point defined in input file (running decomposition, check results, test coverage)
Parameters: - inputFile – path to input file
- outputDir – path to directory where output is be stored
- parser – ConfigParser storing information from parameters file
- databaseVersion – Database version (printed to output file)
- listOfExpRes – list of ExpResult objects to be considered
Returns: output of printers
-
tools.modelTester.
testPoints
(fileList, inDir, outputDir, parser, databaseVersion, listOfExpRes, timeout, development, parameterFile)[source]¶ Loop over all input files in fileList with testPoint, using ncpus CPUs defined in parser
Parameters: - fileList – list of input files to be tested
- inDir – path to directory where input files are stored
- outputDir – path to directory where output is stored
- parser – ConfigParser storing information from parameter.ini file
- databaseVersion – Database version (printed to output files)
- listOfExpRes – list of ExpResult objects to be considered
- timeout – set a timeout for one model point (0 means no timeout)
- development – turn on development mode (e.g. no crash report)
- parameterFile – parameter file, for crash reports
Returns: printer(s) output, if not run in parallel mode
tools.nllFastWrapper module¶
-
class
tools.nllFastWrapper.
NllFastWrapper
(sqrts, nllfastVersion, testParams, testCondition)[source]¶ Bases:
smodels.tools.wrapperBase.WrapperBase
An instance of this class represents the installation of nllfast.
Parameters: - sqrts – sqrt of s, in TeV, as an integer,
- nllfastVersion – version of the nllfast tool
- testParams – what are the test params we need to run things with?
- testCondition – the line that should be the last output line when running executable
SrcPath: the path of the source code, for compilation
-
class
tools.nllFastWrapper.
NllFastWrapper13
[source]¶ Bases:
tools.nllFastWrapper.NllFastWrapper
An instance of this class represents the installation of nllfast 8.
-
class
tools.nllFastWrapper.
NllFastWrapper7
[source]¶ Bases:
tools.nllFastWrapper.NllFastWrapper
An instance of this class represents the installation of nllfast 7.
-
class
tools.nllFastWrapper.
NllFastWrapper8
[source]¶ Bases:
tools.nllFastWrapper.NllFastWrapper
An instance of this class represents the installation of nllfast 8.
tools.physicsUnits module¶
tools.printer module¶
-
class
tools.printer.
BasicPrinter
(output, filename)[source]¶ Bases:
object
Super class to handle the basic printing methods
-
addObj
(obj)[source]¶ Adds object to the Printer.
Parameters: obj – A object to be printed. Must match one of the types defined in formatObj Returns: True if the object has been added to the output. If the object does not belong to the pre-defined printing list toPrint, returns False.
-
filename
¶
-
-
class
tools.printer.
MPrinter
[source]¶ Bases:
object
Master Printer class to handle the Printers (one printer/output type)
-
addObj
(obj)[source]¶ Adds the object to all its Printers:
Parameters: obj – An object which can be handled by the Printers.
-
flush
()[source]¶ Ask all printers to write the output and clear their cache. If the printers return anything other than None, we pass it on.
-
setOutPutFiles
(filename, silent=False)[source]¶ Set the basename for the output files. Each printer will use this file name appended of the respective extension (i.e. .py for a python printer, .smodels for a summary printer,…)
Parameters: - filename – Input file name
- silent – dont comment removing old files
-
-
class
tools.printer.
PyPrinter
(output='stdout', filename=None)[source]¶ Bases:
tools.printer.BasicPrinter
Printer class to handle the printing of one single pythonic output
-
class
tools.printer.
SLHAPrinter
(output='file', filename=None)[source]¶ Bases:
tools.printer.TxTPrinter
Printer class to handle the printing of slha format summary output. It uses the facilities of the TxTPrinter.
-
setOutPutFile
(filename, overwrite=True, silent=False)[source]¶ Set the basename for the text printer. The output filename will be filename.smodels. :param filename: Base filename :param overwrite: If True and the file already exists, it will be removed. :param silent: dont comment removing old files
-
-
class
tools.printer.
SummaryPrinter
(output='stdout', filename=None)[source]¶ Bases:
tools.printer.TxTPrinter
Printer class to handle the printing of one single summary output. It uses the facilities of the TxTPrinter.
-
setOutPutFile
(filename, overwrite=True, silent=False)[source]¶ Set the basename for the text printer. The output filename will be filename.smodels. :param filename: Base filename :param overwrite: If True and the file already exists, it will be removed. :param silent: dont comment removing old files
-
-
class
tools.printer.
TxTPrinter
(output='stdout', filename=None)[source]¶ Bases:
tools.printer.BasicPrinter
Printer class to handle the printing of one single text output
-
class
tools.printer.
XmlPrinter
(output='stdout', filename=None)[source]¶ Bases:
tools.printer.PyPrinter
Printer class to handle the printing of one single XML output
-
convertToElement
(pyObj, parent, tag='')[source]¶ Convert a python object (list,dict,string,…) to a nested XML element tree. :param pyObj: python object (list,dict,string…) :param parent: XML Element parent :param tag: tag for the daughter element
-
-
tools.printer.
getInfoFromPython
(output)[source]¶ Retrieves information from the python output
Parameters: output – output (dictionary) Returns: list of r-values,r-expected and analysis IDs. None if no results are found.
-
tools.printer.
getInfoFromSLHA
(output)[source]¶ Retrieves information from the SLHA output
Parameters: output – output (string) Returns: list of r-values,r-expected and analysis IDs. None if no results are found.
-
tools.printer.
getInfoFromSummary
(output)[source]¶ Retrieves information from the summary output
Parameters: output – output (string) Returns: list of r-values,r-expected and analysis IDs. None if no results are found.
-
tools.printer.
getSummaryFrom
(output, ptype)[source]¶ Retrieves information about the output according to the printer type (slha,python or summary)
Parameters: - output – output (dictionary for ptype=python or string for ptype=slha/summary)
- ptype – Printer type (slha, python or summary)
Returns: Dictionary with the output information
-
tools.printer.
printScanSummary
(outputDict, outputFile)[source]¶ Method for creating a simple summary of the results when running SModelS over multiple files.
Parameters: - outputDict – A dictionary with filenames as keys and the master printer flush dictionary as values.
- outputFile – Path to the summary file to be written.
tools.proxyDBCreator module¶
tools.pyhfInterface module¶
-
class
tools.pyhfInterface.
PyhfData
(nsignals, inputJsons)[source]¶ Bases:
object
Holds data for use in pyhf :ivar nsignals: signal predictions list divided into sublists, one for each json file :ivar inputJsons: list of json instances :ivar nWS: number of workspaces = number of json files
-
checkConsistency
()[source]¶ Check various inconsistencies of the PyhfData attributes
Parameters: zeroSignalsFlag – boolean identifying if all SRs of a single json are empty
-
getWSInfo
()[source]¶ Getting informations from the json files
Variables: channelsInfo – list of dictionaries (one dictionary for each json file) containing useful information about the json files - :key signalRegions: list of dictonaries with ‘json path’ and ‘size’ (number of bins) of the ‘signal regions’ channels in the json files - :key otherRegions: list of strings indicating the path to the control and validation region channels
-
-
class
tools.pyhfInterface.
PyhfUpperLimitComputer
(data, cl=0.95)[source]¶ Bases:
object
Class that computes the upper limit using the jsons files and signal informations in the data instance of PyhfData
Parameters: - data – instance of PyhfData holding the signals information
- cl – confdence level at which the upper limit is desired to be computed
Variables: - data – created from :param data:
- nsignals – signal predictions list divided into sublists, one for each json file
- inputJsons – list of input json files as python json instances
- channelsInfo – list of channels information for the json files
- zeroSignalsFlag – list boolean flags in case all signals are zero for a specific json
- nWS – number of workspaces = number of json files
- patches – list of patches to be applied to the inputJsons as python dictionary instances
- workspaces – list of workspaces resulting from the patched inputJsons
- cl – created from :param cl:
- scale – scale that is applied to the signal predictions, dynamically changes throughout the upper limit calculation
- alreadyBeenThere – boolean flag that identifies when the :ivar nsignals: accidentally passes twice at two identical values
-
likelihood
(workspace_index=None)[source]¶ Returns the value of the likelihood. Inspired by the pyhf.infer.mle module but for non-log likelihood
-
patchMaker
()[source]¶ Method that creates the list of patches to be applied to the self.inputJsons workspaces, one for each region given the self.nsignals and the informations available in self.channelsInfo and the content of the self.inputJsons NB: It seems we need to include the change of the “modifiers” in the patches as well
Returns: the list of patches, one for each workspace
-
rescale
(factor)[source]¶ Rescales the signal predictions (self.nsignals) and processes again the patches and workspaces
Returns: updated list of patches and workspaces (self.patches and self.workspaces)
-
ulSigma
(expected=False, workspace_index=None)[source]¶ - Compute the upper limit on the signal strength modifier with:
- by default, the combination of the workspaces contained into self.workspaces
- if workspace_index is specified, self.workspace[workspace_index] (useful for computation of the best upper limit)
Parameters: - expected –
- if set to True: uses expected SM backgrounds as signals
- else: uses self.nsignals
- workspace_index –
- if different from None: index of the workspace to use for upper limit
- else: all workspaces are combined
Returns: the upper limit at self.cl level (0.95 by default)
tools.pythia6Wrapper module¶
-
class
tools.pythia6Wrapper.
Pythia6Wrapper
(configFile='<install>/smodels/etc/pythia.card', executablePath='<install>/smodels/lib/pythia6/pythia_lhe', srcPath='<install>/smodels/lib/pythia6/')[source]¶ Bases:
smodels.tools.wrapperBase.WrapperBase
An instance of this class represents the installation of pythia6. nevents keeps track of how many events we run. For each event we only allow a certain computation time: if self.secondsPerEvent * self.nevents > CPU time, we terminate Pythia.
Parameters: - configFile – Location of the config file, full path; copy this file and provide tools to change its content and to provide a template
- executablePath – Location of executable, full path (pythia_lhe)
- srcPath – Location of source code
-
checkFileExists
(inputFile)[source]¶ Check if file exists, raise an IOError if it does not.
Returns: absolute file name if file exists.
-
replaceInCfgFile
(replacements={'NEVENTS': 10000, 'SQRTS': 8000})[source]¶ Replace strings in the config file by other strings, similar to setParameter.
This is introduced as a simple mechanism to make changes to the parameter file.
Parameters: replacements – dictionary of strings and values; the strings will be replaced with the values; the dictionary keys must be strings present in the config file
-
run
(slhafile, lhefile=None, unlink=True)[source]¶ Execute pythia_lhe with n events, at sqrt(s)=sqrts.
Parameters: - slhafile – input SLHA file
- lhefile – option to write LHE output to file; if None, do not write output to disk. If lhe file exists, use its events for xsecs calculation.
- unlink – Clean up temp directory after running pythia
Returns: List of cross sections
tools.pythia8Wrapper module¶
-
class
tools.pythia8Wrapper.
Pythia8Wrapper
(configFile='<install>/smodels/etc/pythia8.cfg', executablePath='<install>/smodels/lib/pythia8/pythia8.exe', srcPath='<install>/smodels/lib/pythia8/')[source]¶ Bases:
smodels.tools.wrapperBase.WrapperBase
An instance of this class represents the installation of pythia8.
Parameters: - configFile – Location of the config file, full path; copy this file and provide tools to change its content and to provide a template
- executablePath – Location of executable, full path (pythia8.exe)
- srcPath – Location of source code
-
checkFileExists
(inputFile)[source]¶ Check if file exists, raise an IOError if it does not.
Returns: absolute file name if file exists.
-
run
(slhaFile, lhefile=None, unlink=True)[source]¶ Run pythia8.
Parameters: - slhaFile – SLHA file
- lhefile – option to write LHE output to file; if None, do not write output to disk. If lhe file exists, use its events for xsecs calculation.
- unlink – clean up temporary files after run?
Returns: List of cross sections
tools.pythia8particles module¶
tools.reweighting module¶
-
tools.reweighting.
calculateProbabilities
(width, Leff_inner, Leff_outer)[source]¶ The fraction of prompt and displaced decays are defined as:
F_long = exp(-totalwidth*l_outer/gb_outer) F_prompt = 1 - exp(-totaltotalwidth*l_inner/gb_inner) F_displaced = 1 - F_prompt - F_long
Parameters: - Leff_inner – is the effective inner radius of the detector, given in meters
- Leff_outer – is the effective outer radius of the detector, given in meters
- width – particle width for which probabilities should be calculated (in GeV)
Returns: Dictionary with the probabilities for the particle not to decay (in the detector), to decay promptly or displaced.
-
tools.reweighting.
defaultEffReweight
(element, Leff_inner=None, Leff_outer=None, minWeight=1e-10)[source]¶ Computes the lifetime reweighting factor for the element efficiency based on the lifetimes of all intermediate particles and the last stable odd-particle appearing in the element. The fraction corresponds to the fraction of decays corresponding to prompt decays to all intermediate BSM particles and to a long-lived decay (outside the detector) to the final BSM state.
Parameters: - element – Element object or nested list of widths
- minWeight – Lower cut for the reweighting factor. Any value below this will be taken to be zero.
- Leff_inner – is the effective inner radius of the detector, given in meters. If None, use default value.
- Leff_outer – is the effective outer radius of the detector, given in meters. If None, use default value.
Returns: Reweight factor (float)
-
tools.reweighting.
defaultULReweight
(element, Leff_inner=None, Leff_outer=None)[source]¶ Computes the lifetime reweighting factor for the element upper limit based on the lifetimes of all intermediate particles and the last stable odd-particle appearing in the element. The fraction corresponds to the fraction of decays corresponding to prompt decays to all intermediate BSM particles and to a long-lived decay (outside the detector) to the final BSM state.
Parameters: - element – Element object
- Leff_inner – is the effective inner radius of the detector, given in meters. If None, use default value.
- Leff_outer – is the effective outer radius of the detector, given in meters. If None, use default value.
Returns: Reweight factor (float)
-
tools.reweighting.
reweightFactorFor
(element, resType='prompt', Leff_inner=None, Leff_outer=None)[source]¶ Computer the reweighting factor for the element according to the experimental result type. Currently only two result types are supported: ‘prompt’ and ‘displaced’. If resultType = ‘prompt’, returns the reweighting factor for all decays in the element to be prompt and the last odd particle to be stable. If resultType = ‘displaced’, returns the reweighting factor for ANY decay in the element to be displaced and no long-lived decays and the last odd particle to be stable. Not that the fraction of “long-lived (meta-stable) decays” is usually included in topologies where the meta-stable particle appears in the final state. Hence it should not be included in the prompt or displaced fractions.
Parameters: - element – Element object
- resType – Type of result to compute the reweight factor for (either ‘prompt’ or ‘displaced’)
- Leff_inner – is the effective inner radius of the detector, given in meters. If None, use default value.
- Leff_outer – is the effective outer radius of the detector, given in meters. If None, use default value.
Returns: probabilities (depending on types of decay within branch), branches (with different labels depending on type of decay)
tools.runSModelS module¶
-
tools.runSModelS.
run
(inFile, parameterFile, outputDir, db, timeout, development)[source]¶ Provides a command line interface to basic SModelS functionalities.
Parameters: - inFile – input file name (either a SLHA or LHE file) or directory name (path to directory containing input files)
- parameterFile – File containing the input parameters (default = smodels/etc/parameters_default.ini)
- outputDir – Output directory to write a summary of results to
- db – supply a smodels.experiment.databaseObj.Database object, so the database doesn’t have to be loaded anymore. Will render a few parameters in the parameter file irrelevant. If None, load the database as described in parameterFile, If True, force loading the text database.
- timeout – set a timeout for one model point (0 means no timeout)
- development – turn on development mode (e.g. no crash report)
tools.runtime module¶
-
tools.runtime.
experimentalFeatures
()[source]¶ a simple boolean flag to turn experimental features on/off, can be turned on and off via options:experimental in parameters.ini.
tools.simplifiedLikelihoods module¶
-
class
tools.simplifiedLikelihoods.
Data
(observed, backgrounds, covariance, third_moment=None, nsignal=None, name='model', deltas_rel=0.2)[source]¶ Bases:
object
A very simple observed container to collect all the data needed to fully define a specific statistical model
Parameters: - observed – number of observed events per dataset
- backgrounds – expected bg per dataset
- covariance – uncertainty in background, as a covariance matrix
- nsignal – number of signal events in each dataset
- name – give the model a name, just for convenience
- deltas_rel – the assumed relative error on the signal hypotheses. The default is 20%.
-
convert
(obj)[source]¶ Convert object to numpy arrays. If object is a float or int, it is converted to a one element array.
-
signals
(mu)[source]¶ Returns the number of expected signal events, for all datasets, given total signal strength mu.
Parameters: mu – Total number of signal events summed over all datasets.
-
totalCovariance
(nsig)[source]¶ get the total covariance matrix, taking into account also signal uncertainty for the signal hypothesis <nsig>. If nsig is None, the predefined signal hypothesis is taken.
-
class
tools.simplifiedLikelihoods.
LikelihoodComputer
(data, ntoys=30000)[source]¶ Bases:
object
Parameters: - data – a Data object.
- ntoys – number of toys when marginalizing
-
chi2
(nsig, marginalize=False)[source]¶ Computes the chi2 for a given number of observed events nobs given the predicted background nb, error on this background deltab, expected number of signal events nsig and the relative error on signal (deltas_rel). :param marginalize: if true, marginalize, if false, profile :param nsig: number of signal events :return: chi2 (float)
-
dLdMu
(mu, signal_rel, theta_hat)[source]¶ d (ln L)/d mu, if L is the likelihood. The function whose root gives us muhat, i.e. the mu that maximizes the likelihood.
Parameters: - mu – total number of signal events
- signal_rel – array with the relative signal strengths for each dataset (signal region)
- theta_hat – array with nuisance parameters
-
debug_mode
= False¶
-
findMuHat
(signal_rel)[source]¶ Find the most likely signal strength mu given the relative signal strengths in each dataset (signal region).
Parameters: signal_rel – array with relative signal strengths Returns: mu_hat, the maximum likelihood estimate of mu
-
findThetaHat
(nsig)[source]¶ Compute nuisance parameter theta that maximizes our likelihood (poisson*gauss).
-
getSigmaMu
(signal_rel)[source]¶ Get a rough estimate for the variance of mu around mu_max.
Parameters: signal_rel – array with relative signal strengths in each dataset (signal region)
-
getThetaHat
(nobs, nb, nsig, covb, max_iterations)[source]¶ Compute nuisance parameter theta that maximizes our likelihood (poisson*gauss).
-
likelihood
(nsig, marginalize=False, nll=False)[source]¶ compute likelihood for nsig, profiling the nuisances :param marginalize: if true, marginalize, if false, profile :param nll: return nll instead of likelihood
-
marginalizedLLHD1D
(nsig, nll)[source]¶ Return the likelihood (of 1 signal region) to observe nobs events given the predicted background nb, error on this background (deltab), expected number of signal events nsig and the relative error on the signal (deltas_rel).
Parameters: - nsig – predicted signal (float)
- nobs – number of observed events (float)
- nb – predicted background (float)
- deltab – uncertainty on background (float)
Returns: likelihood to observe nobs events (float)
-
marginalizedLikelihood
(nsig, nll)[source]¶ compute the marginalized likelihood of observing nsig signal event
-
nllHess
(theta)[source]¶ the Hessian of nll as a function of the thetas. Makes it easier to find the maximum likelihood.
-
nllprime
(theta)[source]¶ the derivative of nll as a function of the thetas. Makes it easier to find the maximum likelihood.
-
class
tools.simplifiedLikelihoods.
UpperLimitComputer
(ntoys=30000, cl=0.95)[source]¶ Bases:
object
Parameters: - ntoys – number of toys when marginalizing
- cl – desired quantile for limits
-
debug_mode
= False¶
-
ulSigma
(model, marginalize=False, toys=None, expected=False, trylasttime=False)[source]¶ - upper limit obtained from the defined Data (using the signal prediction
- for each signal regio/dataset), by using the q_mu test statistic from the CCGV paper (arXiv:1007.1727).
Params marginalize: if true, marginalize nuisances, else profile them Params toys: specify number of toys. Use default is none Params expected: compute the expected value, not the observed. Params trylasttime: if True, then dont try extra Returns: upper limit on production xsec (efficiencies unfolded)
tools.smodelsLogging module¶
-
class
tools.smodelsLogging.
ColorizedStreamHandler
(stream=None)[source]¶ Bases:
logging.StreamHandler
tools.statistics module¶
-
tools.statistics.
chi2FromLimits
(likelihood, expectedUpperLimit)[source]¶ compute the chi2 value from a likelihood (convenience function).
-
tools.statistics.
deltaChi2FromLlhd
(likelihood)[source]¶ compute the delta chi2 value from a likelihood (convenience function)
-
tools.statistics.
likelihoodFromLimits
(upperLimit, expectedUpperLimit, nsig, nll=False)[source]¶ computes the likelihood from an expected and an observed upper limit. :param upperLimit: observed upper limit, as a yield (i.e. unitless) :param expectedUpperLimit: expected upper limit, also as a yield :param nSig: number of signal events :param nll: if True, return negative log likelihood
Returns: likelihood (float)
-
tools.statistics.
rvsFromLimits
(upperLimit, expectedUpperLimit, n=1)[source]¶ Generates a sample of random variates, given expected and observed likelihoods. The likelihood is modelled as a truncated Gaussian.
Parameters: - upperLimit – observed upper limit, as a yield (i.e. unitless)
- expectedUpperLimit – expected upper limit, also as a yield
- n – sample size
Returns: sample of random variates
tools.stringTools module¶
tools.timeOut module¶
tools.toolBox module¶
-
class
tools.toolBox.
ToolBox
[source]¶ Bases:
object
A singleton-like class that keeps track of all external tools. Intended to make installation and deployment easier.
Constructor creates the singleton.
tools.wrapperBase module¶
-
class
tools.wrapperBase.
WrapperBase
[source]¶ Bases:
object
An instance of this class represents the installation of an external tool.
An external tool encapsulates a tool that is executed via commands.getoutput. The wrapper defines how the tool is tested for proper installation and how the tool is executed.
-
absPath
(path)[source]¶ Get the absolute path of <path>, replacing <install> with the installation directory.
-
checkInstallation
(compile=True)[source]¶ Checks if installation of tool is correct by looking for executable and executing it. If check is False and compile is True, then try and compile it.
Returns: True, if everything is ok
-
defaulttempdir
= '/tmp/'¶
-
tools.xsecComputer module¶
-
class
tools.xsecComputer.
ArgsStandardizer
[source]¶ Bases:
object
simple class to collect all argument manipulators
-
class
tools.xsecComputer.
XSecComputer
(maxOrder, nevents, pythiaVersion, maycompile=True)[source]¶ Bases:
object
cross section computer class, what else?
Parameters: - maxOrder – maximum order to compute the cross section, given as an integer if maxOrder == LO, compute only LO pythia xsecs if maxOrder == NLO, apply NLO K-factors from NLLfast (if available) if maxOrder == NLL, apply NLO+NLL K-factors from NLLfast (if available)
- nevents – number of events for pythia run
- pythiaVersion – pythia6 or pythia8 (integer)
- maycompile – if True, then tools can get compiled on-the-fly
-
addMultipliersToFile
(ssmultipliers, slhaFile)[source]¶ add the signal strength multipliers to the SLHA file
-
addXSecToFile
(xsecs, slhafile, comment=None, complain=True)[source]¶ Write cross sections to an SLHA file.
Parameters: - xsecs – a XSectionList object containing the cross sections
- slhafile – target file for writing the cross sections in SLHA format
- comment – optional comment to be added to each cross section block
- complain – complain if there are already cross sections in file
-
compute
(sqrts, slhafile, lhefile=None, unlink=True, loFromSlha=None, pythiacard=None, ssmultipliers=None)[source]¶ Run pythia and compute SUSY cross sections for the input SLHA file.
Parameters: - sqrts – sqrt{s} to run Pythia, given as a unum (e.g. 7.*TeV)
- slhafile – SLHA file
- lhefile – LHE file. If None, do not write pythia output to file. If file does not exist, write pythia output to this file name. If file exists, read LO xsecs from this file (does not run pythia).
- unlink – Clean up temp directory after running pythia
- loFromSlha – If True, uses the LO xsecs from the SLHA file to compute the higher order xsecs
- pythiaCard – Optional path to pythia.card. If None, uses smodels/etc/pythia.card
- ssmultipliers – optionally supply signal strengh multipliers, given as dictionary of the tuple of the mothers’ pids as keys and multipliers as values, e.g { (1000001,1000021):1.1 }.
Returns: XSectionList object
-
computeForBunch
(sqrtses, inputFiles, unlink, lOfromSLHA, tofile, pythiacard=None, ssmultipliers=None)[source]¶ compute xsecs for a bunch of slha files
-
computeForOneFile
(sqrtses, inputFile, unlink, lOfromSLHA, tofile, pythiacard=None, ssmultipliers=None, comment=None)[source]¶ Compute the cross sections for one file.
Parameters: - sqrtses – list of sqrt{s} tu run pythia, as a unum (e.g. [7*TeV])
- inputFile – input SLHA file to compute xsecs for
- unlink – if False, keep temporary files
- lofromSLHA – try to obtain LO xsecs from SLHA file itself
- tofile – False, True, “all”: write results to file, if “all” also write lower xsecs to file.
- pythiacard – optionally supply your own runcard
- ssmultipliers – optionally supply signal strengh multipliers, given as dictionary of the tuple of the mothers’ pids as keys and multipliers as values, e.g { (1000001,1000021):1.1 }.
- comment – an optional comment that gets added to the slha file.
Returns: number of xsections that have been computed
-
xsecToBlock
(xsec, inPDGs=(2212, 2212), comment=None, xsecUnit=1.00E+00 [pb])[source]¶ Generate a string for a XSECTION block in the SLHA format from a XSection object.
Parameters: - inPDGs – defines the PDGs of the incoming states (default = 2212,2212)
- comment – is added at the end of the header as a comment
- xsecUnit – unit of cross sections to be written (default is pb). Must be a Unum unit.