Esempio n. 1
0
    def testCombinedResult(self):
        predXSecs, rvalues = {}, {}
        for case in ["T1", "T5", "mixed"]:
            filename = self.createSLHAFile(case=case)
            deco = decompose(filename)
            expRes = database.getExpResults(
                analysisIDs=["CMS-SUS-16-050-agg"])[0]
            # print ( "Experimental result: %s" % expRes )
            tp = theoryPredictionsFor(expRes,
                                      deco,
                                      useBestDataset=False,
                                      combinedResults=True)
            for t in tp:
                predXSecs[case] = t.xsection.value
                rvalues[case] = t.getRValue(expected=True)
            if True:
                os.unlink(filename)
        ## first test: the theory prediction of the mixed scenario should be 25% of the sum
        ## 25%, because the total cross section is a fixed quantity, and half of the mixed scenario
        ## goes into asymmetric branches which we miss out on.
        self.assertAlmostEqual(
            (predXSecs["T1"] + predXSecs["T5"]).asNumber(fb),
            (4 * predXSecs["mixed"]).asNumber(fb), 2)

        ## second test: the r value of the mixed scenario * 2 must be between the r values
        ## of the pure scenarios. The factor of two comes from the fact, that we loose 50%
        ## to asymmetric branches
        self.assertTrue(rvalues["T5"] < 2 * rvalues["mixed"] < rvalues["T1"])
Esempio n. 2
0
    def checkPrediction(self, slhafile, expID, expectedValues, datasetID):

        reducedModel = [
            ptc for ptc in BSMList if abs(ptc.pdg) in [1000011, 1000012]
        ]
        model = Model(reducedModel, SMList)
        model.updateParticles(slhafile)

        self.configureLogger()
        smstoplist = decomposer.decompose(model,
                                          0. * fb,
                                          doCompress=True,
                                          doInvisible=True,
                                          minmassgap=5. * GeV)

        expresults = database.getExpResults(analysisIDs=expID,
                                            datasetIDs=datasetID)
        for expresult in expresults:
            theorypredictions = theoryPredictionsFor(expresult, smstoplist)
            for pred in theorypredictions:
                predval = pred.xsection.value
                expval = expectedValues.pop()
                delta = expval * 0.01
                self.assertAlmostEqual(predval.asNumber(fb),
                                       expval,
                                       delta=delta)

        self.assertTrue(len(expectedValues) == 0)
Esempio n. 3
0
    def runPrinterMain(self, slhafile, mprinter, addTopList=False):
        """
        Main program. Displays basic use case.
    
        """
        runtime.modelFile = 'mssm'
        reload(particlesLoader)

        #Set main options for decomposition:
        sigmacut = 0.03 * fb
        mingap = 5. * GeV
        """ Decompose model  """
        model = Model(BSMList, SMList)
        model.updateParticles(slhafile)
        smstoplist = decomposer.decompose(model,
                                          sigmacut,
                                          doCompress=True,
                                          doInvisible=True,
                                          minmassgap=mingap)

        #Add the decomposition result to the printers
        if addTopList:
            mprinter.addObj(smstoplist)
        listOfExpRes = database.getExpResults(analysisIDs=[
            '*:8*TeV', 'CMS-PAS-SUS-15-002', 'CMS-PAS-SUS-16-024'
        ])
        # Compute the theory predictions for each analysis
        allPredictions = []
        for expResult in listOfExpRes:
            predictions = theoryPredictionsFor(expResult, smstoplist)
            if not predictions:
                continue
            allPredictions += predictions._theoryPredictions

        for theoPred in allPredictions:
            if theoPred.dataType() == 'efficiencyMap' and hasattr(
                    theoPred,
                    'expectedUL') and not theoPred.expectedUL is None:
                theoPred.computeStatistics()

        maxcond = 0.2
        theoryPredictions = TheoryPredictionList(allPredictions, maxcond)
        mprinter.addObj(theoryPredictions)

        #Add coverage information:
        coverageInfo = coverage.Uncovered(smstoplist)
        mprinter.addObj(coverageInfo)

        #Add additional information:
        databaseVersion = database.databaseVersion
        outputStatus = ioObjects.OutputStatus(
            [1, 'Input file ok'], slhafile, {
                'sigmacut': sigmacut.asNumber(fb),
                'minmassgap': mingap.asNumber(GeV),
                'maxcond': maxcond
            }, databaseVersion)
        outputStatus.status = 1
        mprinter.addObj(outputStatus)
        mprinter.flush()
Esempio n. 4
0
    def testGoodFile(self):

        filename = "./testFiles/slha/lightEWinos.slha"
        topolist = slhaDecomposer.decompose(filename,doCompress=True, doInvisible=True, minmassgap = 5*GeV)
        analyses = database.getExpResults (txnames=["TChiWZoff"])
        theoryPrediction = theoryPredictionsFor(analyses[0], topolist)[0]
        conditionViolation = theoryPrediction.conditions
        self.assertEqual(conditionViolation['Cgtr([[[mu+,mu-]],[[l,nu]]],[[[e+,e-]],[[l,nu]]])'],0.)
Esempio n. 5
0
    def runPrinterMain(self, slhafile, mprinter, addTopList=False):
        """
        Main program. Displays basic use case.
    
        """

        runtime.modelFile = 'mssm'
        reload(particlesLoader)

        #Set main options for decomposition:
        sigmacut = 0.03 * fb
        mingap = 5. * GeV
        """ Decompose model (use slhaDecomposer for SLHA input or lheDecomposer
            for LHE input) """
        smstoplist = slhaDecomposer.decompose(slhafile,
                                              sigmacut,
                                              doCompress=True,
                                              doInvisible=True,
                                              minmassgap=mingap)

        #Add the decomposition result to the printers
        if addTopList:
            mprinter.addObj(smstoplist)

        listOfExpRes = database.getExpResults(analysisIDs=[
            '*:8*TeV', 'CMS-PAS-SUS-15-002', 'CMS-PAS-SUS-16-024'
        ])
        # Compute the theory predictions for each analysis
        allPredictions = []
        for expResult in listOfExpRes:
            predictions = theoryPredictionsFor(expResult, smstoplist)
            if not predictions:
                continue
            allPredictions += predictions._theoryPredictions

        maxcond = 0.2
        results = ioObjects.ResultList(allPredictions, maxcond)
        mprinter.addObj(results)

        #Add coverage information:
        coverageInfo = coverage.Uncovered(smstoplist)
        mprinter.addObj(coverageInfo)

        #Add additional information:
        databaseVersion = database.databaseVersion
        outputStatus = ioObjects.OutputStatus(
            [1, 'Input file ok'], slhafile, {
                'sigmacut': sigmacut.asNumber(fb),
                'minmassgap': mingap.asNumber(GeV),
                'maxcond': maxcond
            }, databaseVersion)
        outputStatus.status = 1
        mprinter.addObj(outputStatus)
        mprinter.flush()
Esempio n. 6
0
    def testGoodFile(self):

        listOfIDs = {'ATLAS-CONF-2013-037': [31, 32, 33, 34, 27, 28, 29, 30], 
                     'ATLAS-SUSY-2013-05' : [26]}
        filename = "./testFiles/slha/higgsinoStop.slha"
        topoList = slhaDecomposer.decompose(filename,doCompress = True, doInvisible=True, minmassgap = 5*GeV)
        resultlist = database.getExpResults(analysisIDs=['*:8*TeV','CMS-PAS-SUS-15-002','CMS-PAS-SUS-16-024'])
        for res in resultlist:
            theorypredictions = theoryPredictionsFor(res, topoList)
            if not theorypredictions: continue
            self.assertEqual(len(theorypredictions),1)
            tpIDs = theorypredictions[0].IDs 
            self.assertEqual(sorted(tpIDs),sorted(listOfIDs[res.globalInfo.id]))
Esempio n. 7
0
    def testGoodFile(self):

        filename = "./testFiles/slha/lightEWinos.slha"
        topolist = slhaDecomposer.decompose(filename,
                                            doCompress=True,
                                            doInvisible=True,
                                            minmassgap=5 * GeV)
        analyses = database.getExpResults(txnames=["TChiWZoff"])
        theoryPrediction = theoryPredictionsFor(analyses[0], topolist)[0]
        conditionViolation = theoryPrediction.conditions
        self.assertEqual(
            conditionViolation[
                'Cgtr([[[mu+,mu-]],[[l,nu]]],[[[e+,e-]],[[l,nu]]])'], 0.)
Esempio n. 8
0
 def checkAnalysis(self,expresult,smstoplist):
     expID = expresult.globalInfo.id
     theorypredictions = theoryPredictionsFor(expresult, smstoplist)
     defpreds=self.predictions()
     if not theorypredictions:
         print ( "no theory predictions for",expresult,"??" )
         sys.exit(-1)
     for pred in theorypredictions:
         predval=pred.xsection.value 
         defpredval = defpreds[expID]
         self.assertAlmostEqual( predval.asNumber(fb), defpredval.asNumber (fb) )
         pred.computeStatistics( marginalize=True, deltas_rel=0. )
         if pred.chi2 != self.predchi2()[expID]:
             self.assertAlmostEqual(pred.chi2/self.predchi2()[expID], 1.0, 1 )
Esempio n. 9
0
 def checkPrediction(self,slhafile,expID,expectedValues):
     self.configureLogger()
     smstoplist = slhaDecomposer.decompose(slhafile, 0.*fb, doCompress=True,
             doInvisible=True, minmassgap=5.*GeV)
     expresults = database.getExpResults(analysisIDs= expID)
     for expresult in expresults:
         theorypredictions = theoryPredictionsFor(expresult, smstoplist)
         for pred in theorypredictions:
             predval=pred.xsection.value 
             expval = expectedValues.pop()
             delta = expval*0.01
             self.assertAlmostEqual(predval.asNumber(fb), expval,delta=delta)
     
     self.assertTrue(len(expectedValues) == 0)
Esempio n. 10
0
    def runPrinterMain(self, slhafile, mprinter,addTopList=False):
        """
        Main program. Displays basic use case.
    
        """
        
        runtime.modelFile = 'mssm'
        reload(particlesLoader)

        #Set main options for decomposition:
        sigmacut = 0.03 * fb
        mingap = 5. * GeV
    
        """ Decompose model (use slhaDecomposer for SLHA input or lheDecomposer
            for LHE input) """
        smstoplist = slhaDecomposer.decompose(slhafile, sigmacut, 
                         doCompress=True, doInvisible=True, minmassgap=mingap )
    
        #Add the decomposition result to the printers
        if addTopList:
            mprinter.addObj(smstoplist)
    
        listOfExpRes = database.getExpResults(analysisIDs=['*:8*TeV','CMS-PAS-SUS-15-002','CMS-PAS-SUS-16-024'])
        # Compute the theory predictions for each analysis
        allPredictions = []
        for expResult in listOfExpRes:
            predictions = theoryPredictionsFor(expResult, smstoplist)
            if not predictions:
                continue
            allPredictions += predictions._theoryPredictions
        
        maxcond = 0.2
        results = ioObjects.ResultList(allPredictions,maxcond)
        mprinter.addObj(results)
        
        #Add coverage information:
        coverageInfo = coverage.Uncovered(smstoplist)
        mprinter.addObj(coverageInfo)
        
        
        #Add additional information:
        databaseVersion = database.databaseVersion
        outputStatus = ioObjects.OutputStatus([1,'Input file ok'], slhafile,
                                               {'sigmacut' : sigmacut.asNumber(fb), 
                                                'minmassgap' : mingap.asNumber(GeV),
                                                'maxcond': maxcond },
                                              databaseVersion)
        outputStatus.status = 1
        mprinter.addObj(outputStatus)
        mprinter.flush()
Esempio n. 11
0
    def testGoodFile(self):

        filename = "./testFiles/slha/lightEWinos.slha"
        model = Model(BSMList, SMList)
        model.updateParticles(filename)

        topolist = decomposer.decompose(model,
                                        sigmacut=0.1 * fb,
                                        doCompress=True,
                                        doInvisible=True,
                                        minmassgap=5 * GeV)
        analyses = database.getExpResults(txnames=["TChiWZoff"],
                                          analysisIDs='ATLAS-SUSY-2013-12')
        theoryPrediction = theoryPredictionsFor(analyses[0], topolist)[0]
        conditionViolation = theoryPrediction.conditions
        self.assertEqual(
            conditionViolation[
                'Cgtr([[[mu+,mu-]],[[l,nu]]],[[[e+,e-]],[[l,nu]]])'], 0.)
Esempio n. 12
0
 def checkAnalysis(self, expresult, smstoplist):
     expID = expresult.globalInfo.id
     theorypredictions = theoryPredictionsFor(expresult, smstoplist)
     defpreds = self.predictions()
     if not theorypredictions:
         print("no theory predictions for", expresult, "??")
         sys.exit(-1)
     for pred in theorypredictions:
         predval = pred.xsection.value
         defpredval = defpreds[expID]
         diff = abs(predval.asNumber(fb) -
                    defpredval.asNumber(fb)) / defpredval.asNumber(fb)
         self.assertTrue(diff < .1)
         #self.assertAlmostEqual( predval.asNumber(fb), defpredval.asNumber(fb), places=4 )
         pred.computeStatistics(marginalize=True, deltas_rel=0.)
         if pred.chi2 != self.predchi2()[expID]:
             diff = abs(pred.chi2 -
                        self.predchi2()[expID]) / self.predchi2()[expID]
             self.assertTrue(diff < .1)
Esempio n. 13
0
 def testPredictionInterface(self):
     """ A simple test to see that the interface in datasetObj
     and TheoryPrediction to the statistics tools is working correctly
     """
     expRes = database.getExpResults( analysisIDs=['CMS-SUS-13-012'] )[0]
     slhafile= "./testFiles/slha/simplyGluino.slha"
     smstoplist = slhaDecomposer.decompose( slhafile )
     prediction = theoryPredictionsFor(expRes, smstoplist,deltas_rel=0.)[0]
     pred_signal_strength = prediction.xsection.value
     prediction.computeStatistics()
     ill = math.log(prediction.likelihood)
     ichi2 = prediction.chi2
     nsig = (pred_signal_strength*expRes.globalInfo.lumi).asNumber()
     m = Data(4, 2.2, 1.1**2, None, nsignal=nsig,deltas_rel=0.2)
     computer = LikelihoodComputer(m)
     dll = math.log(computer.likelihood(nsig, marginalize=False ) )
     self.assertAlmostEqual(ill, dll, places=2)
     dchi2 = computer.chi2( nsig, marginalize=False )
     # print ( "dchi2,ichi2",dchi2,ichi2)
     self.assertAlmostEqual(ichi2, dchi2, places=2)
Esempio n. 14
0
 def testPredictionInterface(self):
     """ A simple test to see that the interface in datasetObj
     and TheoryPrediction to the statistics tools is working correctly
     """
     expRes = database.getExpResults(analysisIDs=['CMS-SUS-13-012'])[0]
     slhafile = "./testFiles/slha/simplyGluino.slha"
     smstoplist = slhaDecomposer.decompose(slhafile)
     prediction = theoryPredictionsFor(expRes, smstoplist, deltas_rel=0.)[0]
     pred_signal_strength = prediction.xsection.value
     prediction.computeStatistics()
     ill = math.log(prediction.likelihood)
     ichi2 = prediction.chi2
     nsig = (pred_signal_strength * expRes.globalInfo.lumi).asNumber()
     m = Data(4, 2.2, 1.1**2, None, nsignal=nsig, deltas_rel=0.2)
     computer = LikelihoodComputer(m)
     dll = math.log(computer.likelihood(nsig, marginalize=False))
     self.assertAlmostEqual(ill, dll, places=2)
     dchi2 = computer.chi2(nsig, marginalize=False)
     # print ( "dchi2,ichi2",dchi2,ichi2)
     self.assertAlmostEqual(ichi2, dchi2, places=2)
Esempio n. 15
0
 def testApproxGaussian(self):
     ## turn experimental features on
     from smodels.tools import runtime
     runtime._experimental = True
     expRes = database.getExpResults(analysisIDs=["CMS-PAS-SUS-12-026"])
     self.assertTrue(len(expRes), 1)
     filename = "./testFiles/slha/T1tttt.slha"
     model = Model(BSMList, SMList)
     model.updateParticles(filename)
     smstoplist = decomposer.decompose(model, sigmacut=0)
     prediction = theoryPredictionsFor(expRes[0], smstoplist)[0]
     prediction.computeStatistics()
     import numpy
     tot = 0.
     for i in numpy.arange(0., .2, .02):
         tot += prediction.getLikelihood(i)
     c = 0.
     for i in numpy.arange(0., .2, .02):
         l = prediction.getLikelihood(i)
         c += l
     self.assertAlmostEqual(prediction.likelihood, 1.563288e-35, 3)
Esempio n. 16
0
    def testGoodFile(self):

        listOfIDs = {
            'ATLAS-CONF-2013-037': [31, 32, 33, 34, 27, 28, 29, 30],
            'ATLAS-SUSY-2013-05': [26]
        }
        filename = "./testFiles/slha/higgsinoStop.slha"
        topoList = slhaDecomposer.decompose(filename,
                                            doCompress=True,
                                            doInvisible=True,
                                            minmassgap=5 * GeV)
        resultlist = database.getExpResults(analysisIDs=[
            '*:8*TeV', 'CMS-PAS-SUS-15-002', 'CMS-PAS-SUS-16-024'
        ])
        for res in resultlist:
            theorypredictions = theoryPredictionsFor(res, topoList)
            if not theorypredictions: continue
            self.assertEqual(len(theorypredictions), 1)
            tpIDs = theorypredictions[0].IDs
            self.assertEqual(sorted(tpIDs),
                             sorted(listOfIDs[res.globalInfo.id]))
Esempio n. 17
0
    def testComplexCluster(self):
        """ test the mass clusterer """

        slhafile = 'testFiles/slha/416126634.slha'
        model = Model(BSMparticles=BSMList, SMparticles=SMList)
        model.updateParticles(slhafile)
        sigmacut = 0.03 * fb
        mingap = 5. * GeV
        toplist = decomposer.decompose(model,
                                       sigmacut,
                                       doCompress=True,
                                       doInvisible=True,
                                       minmassgap=mingap)

        #Test clustering for UL results
        expResult = database.getExpResults(analysisIDs='CMS-SUS-16-039',
                                           dataTypes='upperLimit')[0]
        predictions = theoryPredictionsFor(expResult,
                                           toplist,
                                           combinedResults=False,
                                           marginalize=False)
        clusterSizes = sorted([len(p.elements) for p in predictions])
        self.assertEqual(clusterSizes, [1, 16, 24])
Esempio n. 18
0
def main():
    """
    Main program. Displays basic use case.
    """
    model = Model(BSMparticles=BSMList, SMparticles=SMList)
    # Path to input file (either a SLHA or LHE file)
    #     lhefile = 'inputFiles/lhe/gluino_squarks.lhe'
    slhafile = 'inputFiles/slha/lightEWinos.slha'
    #     model.updateParticles(inputFile=lhefile)
    model.updateParticles(inputFile=slhafile)

    # Set main options for decomposition
    sigmacut = 0.01 * fb
    mingap = 5. * GeV

    # Decompose model
    toplist = decomposer.decompose(model,
                                   sigmacut,
                                   doCompress=True,
                                   doInvisible=True,
                                   minmassgap=mingap)

    # Access basic information from decomposition, using the topology list and topology objects:
    print("\n Decomposition Results: ")
    print("\t  Total number of topologies: %i " % len(toplist))
    nel = sum([len(top.elementList) for top in toplist])
    print("\t  Total number of elements = %i " % nel)
    #Print information about the m-th topology:
    m = 2
    if len(toplist) > m:
        top = toplist[m]
        print("\t\t %i-th topology  = " % m, top, "with total cross section =",
              top.getTotalWeight())
        #Print information about the n-th element in the m-th topology:
        n = 0
        el = top.elementList[n]
        print("\t\t %i-th element from %i-th topology  = " % (n, m),
              el,
              end="")
        print("\n\t\t\twith final states =", el.getFinalStates(),
              "\n\t\t\twith cross section =", el.weight,
              "\n\t\t\tand masses = ", el.mass)

    # Load the experimental results to be used.
    # In this case, all results are employed.
    listOfExpRes = database.getExpResults()

    # Print basic information about the results loaded.
    # Count the number of loaded UL and EM experimental results:
    nUL, nEM = 0, 0
    for exp in listOfExpRes:
        expType = exp.datasets[0].dataInfo.dataType
        if expType == 'upperLimit':
            nUL += 1
        elif expType == 'efficiencyMap':
            nEM += 1
    print("\n Loaded Database with %i UL results and %i EM results " %
          (nUL, nEM))

    # Compute the theory predictions for each experimental result and print them:
    print("\n Theory Predictions and Constraints:")
    rmax = 0.
    bestResult = None
    for expResult in listOfExpRes:
        predictions = theoryPredictionsFor(expResult,
                                           toplist,
                                           combinedResults=False,
                                           marginalize=False)
        if not predictions:
            continue  # Skip if there are no constraints from this result
        print('\n %s ' % expResult.globalInfo.id)
        for theoryPrediction in predictions:
            dataset = theoryPrediction.dataset
            datasetID = theoryPrediction.dataId()
            mass = theoryPrediction.mass
            txnames = [str(txname) for txname in theoryPrediction.txnames]
            PIDs = theoryPrediction.PIDs
            print("------------------------")
            print("Dataset = ", datasetID)  #Analysis name
            print("TxNames = ", txnames)
            print(
                "Prediction Mass = ", mass
            )  #Value for average cluster mass (average mass of the elements in cluster)
            print(
                "Prediction PIDs = ", PIDs
            )  #Value for average cluster mass (average mass of the elements in cluster)
            print("Theory Prediction = ",
                  theoryPrediction.xsection)  #Signal cross section
            print("Condition Violation = ",
                  theoryPrediction.conditions)  #Condition violation values

            # Get the corresponding upper limit:
            print("UL for theory prediction = ", theoryPrediction.upperLimit)

            # Compute the r-value
            r = theoryPrediction.getRValue()
            print("r = ", r)
            #Compute likelihhod and chi^2 for EM-type results:
            if dataset.getType() == 'efficiencyMap':
                theoryPrediction.computeStatistics()
                print('Chi2, likelihood=', theoryPrediction.chi2,
                      theoryPrediction.likelihood)
            if r > rmax:
                rmax = r
                bestResult = expResult.globalInfo.id

    # Print the most constraining experimental result
    print("\nThe largest r-value (theory/upper limit ratio) is ", rmax)
    if rmax > 1.:
        print("(The input model is likely excluded by %s)" % bestResult)
    else:
        print(
            "(The input model is not excluded by the simplified model results)"
        )

    #Find out missing topologies for sqrts=8*TeV:
    uncovered = coverage.Uncovered(toplist, sqrts=8. * TeV)
    #First sort coverage groups by label
    groups = sorted(uncovered.groups[:], key=lambda g: g.label)
    #Print uncovered cross-sections:
    for group in groups:
        print("\nTotal cross-section for %s (fb): %10.3E\n" %
              (group.description, group.getTotalXSec()))

    missingTopos = uncovered.getGroup('missing (prompt)')
    #Print some of the missing topologies:
    if missingTopos.generalElements:
        print('Missing topologies (up to 3):')
        for genEl in missingTopos.generalElements[:3]:
            print('Element:', genEl)
            print('\tcross-section (fb):', genEl.missingX)
    else:
        print("No missing topologies found\n")

    missingDisplaced = uncovered.getGroup('missing (displaced)')
    #Print elements with displaced decays:
    if missingDisplaced.generalElements:
        print('\nElements with displaced vertices (up to 2):')
        for genEl in missingDisplaced.generalElements[:2]:
            print('Element:', genEl)
            print('\tcross-section (fb):', genEl.missingX)
    else:
        print("\nNo displaced decays")
Esempio n. 19
0
def testPoint(inputFile, outputDir, parser, databaseVersion, listOfExpRes):
    """
    Test model point defined in input file (running decomposition, check
    results, test coverage)

    :parameter inputFile: path to input file
    :parameter outputDir: path to directory where output is be stored
    :parameter parser: ConfigParser storing information from parameters file
    :parameter databaseVersion: Database version (printed to output file)
    :parameter listOfExpRes: list of ExpResult objects to be considered
    :returns: output of printers
    """
    """Get run parameters and options from the parser"""
    sigmacut = parser.getfloat("parameters", "sigmacut") * fb
    minmassgap = parser.getfloat("parameters", "minmassgap") * GeV
    inputType = parser.get("options", "inputType").lower()
    """Setup output printers"""
    masterPrinter = MPrinter()
    masterPrinter.setPrinterOptions(parser)
    masterPrinter.setOutPutFiles(
        os.path.join(outputDir, os.path.basename(inputFile)))
    """ Add list of analyses loaded to printer"""
    masterPrinter.addObj(ExpResultList(listOfExpRes))
    """Check input file for errors"""
    inputStatus = ioObjects.FileStatus()
    if parser.getboolean("options", "checkInput"):
        inputStatus.checkFile(inputType, inputFile, sigmacut)
    """Initialize output status and exit if there were errors in the input"""
    outputStatus = ioObjects.OutputStatus(inputStatus.status, inputFile,
                                          dict(parser.items("parameters")),
                                          databaseVersion)
    masterPrinter.addObj(outputStatus)
    if outputStatus.status < 0:
        return masterPrinter.flush()
    """
    Decompose input file
    ====================
    """
    try:
        """ Decompose input SLHA file, store the output elements in smstoplist """
        if inputType == 'slha':
            smstoplist = slhaDecomposer.decompose(
                inputFile,
                sigmacut,
                doCompress=parser.getboolean("options", "doCompress"),
                doInvisible=parser.getboolean("options", "doInvisible"),
                minmassgap=minmassgap)
        else:
            smstoplist = lheDecomposer.decompose(
                inputFile,
                doCompress=parser.getboolean("options", "doCompress"),
                doInvisible=parser.getboolean("options", "doInvisible"),
                minmassgap=minmassgap)
    except SModelSError as e:
        print("Exception %s %s" % (e, type(e)))
        """ Update status to fail, print error message and exit """
        outputStatus.updateStatus(-1)
        return masterPrinter.flush()
    """ Print Decomposition output.
        If no topologies with sigma > sigmacut are found, update status, write
        output file, stop running """
    if not smstoplist:
        outputStatus.updateStatus(-3)
        return masterPrinter.flush()

    masterPrinter.addObj(smstoplist)
    """
    Compute theory predictions
    ====================================================
    """
    """ Get theory prediction for each analysis and print basic output """
    allPredictions = []
    for expResult in listOfExpRes:
        theorypredictions = theoryPredictionsFor(expResult, smstoplist)
        if not theorypredictions: continue
        allPredictions += theorypredictions._theoryPredictions
    """Compute chi-square and likelihood"""
    if parser.getboolean("options", "computeStatistics"):
        for theoPred in allPredictions:
            theoPred.computeStatistics()
    """ Define result list that collects all theoryPrediction objects."""
    maxcond = parser.getfloat("parameters", "maxcond")
    results = ioObjects.ResultList(allPredictions, maxcond)

    if not results.isEmpty():
        outputStatus.updateStatus(1)
        masterPrinter.addObj(results)
    else:
        outputStatus.updateStatus(0)  # no results after enforcing maxcond

    if parser.getboolean("options", "testCoverage"):
        """ Testing coverage of model point, add results to the output file """
        uncovered = coverage.Uncovered(smstoplist)
        masterPrinter.addObj(uncovered)

    return masterPrinter.flush()
Esempio n. 20
0
def main():
    """
    Main program. Displays basic use case.
    """

    #Define your model (list of rEven and rOdd particles)
    particlesLoader.load('smodels.share.models.mssm'
                         )  #Make sure all the model particles are up-to-date

    # Path to input file (either a SLHA or LHE file)
    slhafile = 'inputFiles/slha/lightEWinos.slha'
    lhefile = 'inputFiles/lhe/gluino_squarks.lhe'

    # Set main options for decomposition
    sigmacut = 0.01 * fb
    mingap = 5. * GeV

    # Decompose model (use slhaDecomposer for SLHA input or lheDecomposer for LHE input)
    slhaInput = True
    if slhaInput:
        toplist = slhaDecomposer.decompose(slhafile,
                                           sigmacut,
                                           doCompress=True,
                                           doInvisible=True,
                                           minmassgap=mingap)
    else:
        toplist = lheDecomposer.decompose(lhefile,
                                          doCompress=True,
                                          doInvisible=True,
                                          minmassgap=mingap)
    # Access basic information from decomposition, using the topology list and topology objects:
    print("\n Decomposition Results: ")
    print("\t  Total number of topologies: %i " % len(toplist))
    nel = sum([len(top.elementList) for top in toplist])
    print("\t  Total number of elements = %i " % nel)
    #Print information about the m-th topology (if it exists):
    m = 2
    if len(toplist) > m:
        top = toplist[m]
        print("\t\t %i-th topology  = " % m, top, "with total cross section =",
              top.getTotalWeight())
        #Print information about the n-th element in the m-th topology:
        n = 0
        el = top.elementList[n]
        print("\t\t %i-th element from %i-th topology  = " % (n, m),
              el,
              end="")
        print("\n\t\t\twith final states =", el.getFinalStates(),
              "\n\t\t\twith cross section =", el.weight,
              "\n\t\t\tand masses = ", el.getMasses())

    # Load the experimental results to be used.
    # In this case, all results are employed.
    listOfExpRes = database.getExpResults()

    # Print basic information about the results loaded.
    # Count the number of loaded UL and EM experimental results:
    nUL, nEM = 0, 0
    for exp in listOfExpRes:
        expType = exp.getValuesFor('dataType')[0]
        if expType == 'upperLimit':
            nUL += 1
        elif expType == 'efficiencyMap':
            nEM += 1
    print("\n Loaded Database with %i UL results and %i EM results " %
          (nUL, nEM))

    # Compute the theory predictions for each experimental result and print them:
    print("\n Theory Predictions and Constraints:")
    rmax = 0.
    bestResult = None
    for expResult in listOfExpRes:
        predictions = theoryPredictionsFor(expResult,
                                           toplist,
                                           combinedResults=False,
                                           marginalize=False)
        if not predictions:
            continue  # Skip if there are no constraints from this result
        print('\n %s ' % expResult.globalInfo.id)
        for theoryPrediction in predictions:
            dataset = theoryPrediction.dataset
            datasetID = dataset.dataInfo.dataId
            mass = theoryPrediction.mass
            txnames = [str(txname) for txname in theoryPrediction.txnames]
            PIDs = theoryPrediction.PIDs
            print("------------------------")
            print("Dataset = ", datasetID)  #Analysis name
            print("TxNames = ", txnames)
            print(
                "Prediction Mass = ", mass
            )  #Value for average cluster mass (average mass of the elements in cluster)
            print(
                "Prediction PIDs = ", PIDs
            )  #Value for average cluster mass (average mass of the elements in cluster)
            print("Theory Prediction = ",
                  theoryPrediction.xsection)  #Signal cross section
            print("Condition Violation = ",
                  theoryPrediction.conditions)  #Condition violation values

            # Get the corresponding upper limit:
            print("UL for theory prediction = ", theoryPrediction.upperLimit)

            # Compute the r-value
            r = theoryPrediction.getRValue()
            print("r = ", r)
            #Compute likelihhod and chi^2 for EM-type results:
            if dataset.dataInfo.dataType == 'efficiencyMap':
                theoryPrediction.computeStatistics()
                print('Chi2, likelihood=', theoryPrediction.chi2,
                      theoryPrediction.likelihood)
            if r > rmax:
                rmax = r
                bestResult = expResult.globalInfo.id

    # Print the most constraining experimental result
    print("\nThe largest r-value (theory/upper limit ratio) is ", rmax)
    if rmax > 1.:
        print("(The input model is likely excluded by %s)" % bestResult)
    else:
        print(
            "(The input model is not excluded by the simplified model results)"
        )

    #Find out missing topologies for sqrts=8*TeV:
    uncovered = coverage.Uncovered(toplist, sqrts=8. * TeV)
    #Print uncovered cross-sections:
    print("\nTotal missing topology cross section (fb): %10.3E\n" %
          (uncovered.getMissingXsec()))
    print(
        "Total cross section where we are outside the mass grid (fb): %10.3E\n"
        % (uncovered.getOutOfGridXsec()))
    print("Total cross section in long cascade decays (fb): %10.3E\n" %
          (uncovered.getLongCascadeXsec()))
    print(
        "Total cross section in decays with asymmetric branches (fb): %10.3E\n"
        % (uncovered.getAsymmetricXsec()))

    #Print some of the missing topologies:
    print('Missing topologies (up to 3):')
    for topo in uncovered.missingTopos.topos[:3]:
        print('Topology:', topo.topo)
        print('Contributing elements (up to 2):')
        for el in topo.contributingElements[:2]:
            print(el, 'cross-section (fb):', el.missingX)

    #Print elements with long cascade decay:
    print('\nElements outside the grid (up to 2):')
    for topo in uncovered.outsideGrid.topos[:2]:
        print('Topology:', topo.topo)
        print('Contributing elements (up to 4):')
        for el in topo.contributingElements[:4]:
            print(el, 'cross-section (fb):', el.missingX)
            print('\tmass:', el.getMasses())
Esempio n. 21
0
 anaIds = ["all"]
 dts = ["all"]
 if args.upper_limits:
     dts = ["upperLimit"]
 if args.efficiencyMaps:
     dts = ["efficiencyMap"]
 listOfExpRes = db.getExpResults(analysisIDs=anaIds,
                                 dataTypes=dts,
                                 onlyWithExpected=True)
 smses = decomposer.decompose(model, .01 * fb)
 #print ( "[combiner] decomposed into %d topos" % len(smses) )
 from smodels.theory.theoryPrediction import theoryPredictionsFor
 combiner = Combiner()
 allps = []
 for expRes in listOfExpRes:
     preds = theoryPredictionsFor(expRes, smses)
     if preds == None:
         continue
     for pred in preds:
         allps.append(pred)
 combo, globalZ, llhd, muhat = combiner.findHighestSignificance(
     allps, "aggressive", expected=args.expected)
 print("[combiner] global Z is %.2f: %s (muhat=%.2f)" %
       (globalZ, combiner.getComboDescription(combo), muhat))
 for expRes in listOfExpRes:
     preds = theoryPredictionsFor(expRes, smses)
     if preds == None:
         continue
     Z, muhat_ = combiner.getSignificance(preds,
                                          expected=args.expected,
                                          mumax=None)
Esempio n. 22
0
    def runSModelS(self, inputFile, sigmacut, allpreds, llhdonly):
        """ run smodels proper.
        :param inputFile: the input slha file
        :param sigmacut: the cut on the topology weights, typically 0.02*fb
        :param allpreds: if true, return all predictions of analyses, else
                         only best signal region
        :param llhdonly: if true, return only results with likelihoods
        """

        if not os.path.exists(inputFile):
            self.pprint("error, cannot find inputFile %s" % inputFile)
            return []
        model = Model(BSMList, SMList)
        model.updateParticles(inputFile=inputFile)

        mingap = 10 * GeV

        # self.log ( "Now decomposing" )
        topos = decomposer.decompose(model, sigmacut, minmassgap=mingap)
        self.log("decomposed model into %d topologies." % len(topos))

        if allpreds:
            bestDataSet = False
            combinedRes = False
        else:
            bestDataSet = True
            combinedRes = self.do_combine

        preds = []
        # self.log ( "start getting preds" )
        from smodels.tools import runtime
        runtime._experimental = True
        for expRes in self.listOfExpRes:
            predictions = theoryPredictionsFor(expRes,
                                               topos,
                                               useBestDataset=bestDataSet,
                                               combinedResults=combinedRes)
            if predictions == None:
                predictions = []
            if allpreds:
                combpreds = theoryPredictionsFor(
                    expRes,
                    topos,
                    useBestDataset=False,
                    combinedResults=self.do_combine)
                if combpreds != None:
                    for c in combpreds:
                        predictions.append(c)
            for prediction in predictions:
                prediction.computeStatistics()
                if (not llhdonly) or (prediction.likelihood != None):
                    preds.append(prediction)
        sap = "best preds"
        if allpreds:
            sap = "all preds"
        sllhd = ""
        if llhdonly:
            sllhd = ", llhds only"
        self.log ( "returning %d predictions, %s%s" % \
                   (len(preds),sap, sllhd ) )
        return preds
Esempio n. 23
0
def testPoint(inputFile, outputDir, parser, databaseVersion, listOfExpRes):
    """
    Test model point defined in input file (running decomposition, check
    results, test coverage)

    :parameter inputFile: path to input file
    :parameter outputDir: path to directory where output is be stored
    :parameter parser: ConfigParser storing information from parameters file
    :parameter databaseVersion: Database version (printed to output file)
    :parameter listOfExpRes: list of ExpResult objects to be considered
    :returns: output of printers
    """
    """Get run parameters and options from the parser"""
    sigmacut = parser.getfloat("parameters", "sigmacut") * fb
    minmassgap = parser.getfloat("parameters", "minmassgap") * GeV
    """Setup output printers"""
    masterPrinter = MPrinter()
    masterPrinter.setPrinterOptions(parser)
    masterPrinter.setOutPutFiles(
        os.path.join(outputDir, os.path.basename(inputFile)))
    """ Add list of analyses loaded to printer"""
    masterPrinter.addObj(ExpResultList(listOfExpRes))
    """Check input file for errors"""
    inputStatus = ioObjects.FileStatus()
    if parser.getboolean("options", "checkInput"):
        inputStatus.checkFile(inputFile)
    """Initialize output status and exit if there were errors in the input"""
    outputStatus = ioObjects.OutputStatus(inputStatus.status, inputFile,
                                          dict(parser.items("parameters")),
                                          databaseVersion)
    masterPrinter.addObj(outputStatus)
    if outputStatus.status < 0:
        return masterPrinter.flush()
    """
    Load the input model
    ====================
    """
    try:
        """
        Load the input model and  update it with the information from the input file
        """
        from smodels.particlesLoader import BSMList
        model = Model(BSMparticles=BSMList, SMparticles=SMList)
        promptWidth = None
        stableWidth = None
        if parser.has_option("particles", "promptWidth"):
            promptWidth = parser.getfloat("particles", "promptWidth") * GeV
        if parser.has_option("particles", "stableWidth"):
            stableWidth = parser.getfloat("particles", "stableWidth") * GeV
        model.updateParticles(inputFile=inputFile,
                              promptWidth=promptWidth,
                              stableWidth=stableWidth)
    except SModelSError as e:
        print("Exception %s %s" % (e, type(e)))
        """ Update status to fail, print error message and exit """
        outputStatus.updateStatus(-1)
        return masterPrinter.flush()
    """
    Decompose input model
    =====================
    """

    try:
        """ Decompose the input model, store the output elements in smstoplist """
        sigmacut = parser.getfloat("parameters", "sigmacut") * fb
        smstoplist = decomposer.decompose(
            model,
            sigmacut,
            doCompress=parser.getboolean("options", "doCompress"),
            doInvisible=parser.getboolean("options", "doInvisible"),
            minmassgap=minmassgap)
    except SModelSError as e:
        print("Exception %s %s" % (e, type(e)))
        """ Update status to fail, print error message and exit """
        outputStatus.updateStatus(-1)
        return masterPrinter.flush()
    """ Print Decomposition output.
        If no topologies with sigma > sigmacut are found, update status, write
        output file, stop running """
    if not smstoplist:
        outputStatus.updateStatus(-3)
        return masterPrinter.flush()

    masterPrinter.addObj(smstoplist)
    """
    Compute theory predictions
    ====================================================
    """
    """ Get theory prediction for each analysis and print basic output """
    allPredictions = []
    combineResults = False
    try:
        combineResults = parser.getboolean("options", "combineSRs")
    except (NoSectionError, NoOptionError) as e:
        pass
    for expResult in listOfExpRes:
        theorypredictions = theoryPredictionsFor(
            expResult,
            smstoplist,
            useBestDataset=True,
            combinedResults=combineResults,
            marginalize=False)
        if not theorypredictions:
            continue
        allPredictions += theorypredictions._theoryPredictions
    """Compute chi-square and likelihood"""
    if parser.getboolean("options", "computeStatistics"):
        for theoPred in allPredictions:
            theoPred.computeStatistics()
    """ Define theory predictions list that collects all theoryPrediction objects which satisfy max condition."""
    maxcond = parser.getfloat("parameters", "maxcond")
    theoryPredictions = theoryPrediction.TheoryPredictionList(
        allPredictions, maxcond)

    if len(theoryPredictions) != 0:
        outputStatus.updateStatus(1)
        masterPrinter.addObj(theoryPredictions)
    else:
        outputStatus.updateStatus(0)  # no results after enforcing maxcond

    if parser.getboolean("options", "testCoverage"):
        """ Testing coverage of model point, add results to the output file """
        if parser.has_option("options", "coverageSqrts"):
            sqrts = parser.getfloat("options", "coverageSqrts") * TeV
        else:
            sqrts = None
        uncovered = coverage.Uncovered(smstoplist,
                                       sigmacut=sigmacut,
                                       sqrts=sqrts)
        masterPrinter.addObj(uncovered)

    return masterPrinter.flush()
Esempio n. 24
0
#Define the SLHA input file name
filename = "%s/inputFiles/slha/gluino_squarks.slha" % installDirectory()

# In[4]:

#Load the database, do the decomposition and compute theory predictions:
#(Look at the theory predictions HowTo to learn how to compute theory predictions)
databasepath = os.path.join(os.getenv("HOME"), "smodels-database/")
database = Database(databasepath)
expResults = database.getExpResults()
topList = slhaDecomposer.decompose(filename,
                                   sigcut=0.03 * fb,
                                   doCompress=True,
                                   doInvisible=True,
                                   minmassgap=5 * GeV)
allThPredictions = [theoryPredictionsFor(exp, topList) for exp in expResults]

# In[5]:

#Print the value of each theory prediction for each experimental
#result and the corresponding upper limit (see the obtain experimental upper limits HowTo to learn how
#to compute the upper limits).
#Also print the expected upper limit, if available
for thPreds in allThPredictions:
    if not thPreds: continue  #skip results with no predictions
    for theoryPred in thPreds:
        expID = theoryPred.expResult.globalInfo.id
        dataType = theoryPred.dataset.dataInfo.dataType
        print "\nExperimental Result: %s (%s-type)" % (expID, dataType
                                                       )  #Result ID and type
        print "Theory prediction xsec = ", theoryPred.xsection.value  #Signal xsection*efficiency*BR
Esempio n. 25
0
    def RunSModelS(self,SLHAFilePath,SummaryFilePath):
        # Set the path to the database
        database = Database("/home/oo1m20/softwares/smodels-1.2.2/smodels-database")

        self.SummaryFilePath = os.path.abspath(SummaryFilePath)

        #Define your model (list of rEven and rOdd particles)
        particlesLoader.load( 'smodels.share.models.secumssm' ) #Make sure all the model particles are up-to-date
    
        # Path to input file (either a SLHA or LHE file)
        self.SLHAFilePath = SLHAFilePath
        slhafile = self.SLHAFilePath
        #lhefile = 'inputFiles/lhe/gluino_squarks.lhe'

        # Set main options for decomposition
        sigmacut = 0.01 * fb
        mingap = 5. * GeV

    
        # Decompose model (use slhaDecomposer for SLHA input or lheDecomposer for LHE input)
        slhaInput = True
        if slhaInput:
            toplist = slhaDecomposer.decompose(slhafile, sigmacut, doCompress=True, doInvisible=True, minmassgap=mingap)
        else:
            toplist = lheDecomposer.decompose(lhefile, doCompress=True,doInvisible=True, minmassgap=mingap)
        # Access basic information from decomposition, using the topology list and topology objects:
        f= open(self.SummaryFilePath,"a+")
        print( "\n Decomposition Results: ", file=f )
        print( "\t  Total number of topologies: %i " %len(toplist), file=f )
        nel = sum([len(top.elementList) for top in toplist])
        print( "\t  Total number of elements = %i " %nel , file=f)
        #Print information about the m-th topology (if it exists):
        m = 2
        if len(toplist) > m:
            top = toplist[m]
            print( "\t\t %i-th topology  = " %m,top,"with total cross section =",top.getTotalWeight(), file=f )
            #Print information about the n-th element in the m-th topology:
            n = 0
            el = top.elementList[n]
            print( "\t\t %i-th element from %i-th topology  = " %(n,m),el, end="", file=f )
            print( "\n\t\t\twith final states =",el.getFinalStates(),"\n\t\t\twith cross section =",el.weight,"\n\t\t\tand masses = ",el.getMasses(), file=f )
            
        # Load the experimental results to be used.
        # In this case, all results are employed.
        listOfExpRes = database.getExpResults()

        # Print basic information about the results loaded.
        # Count the number of loaded UL and EM experimental results:
        nUL, nEM = 0, 0
        for exp in listOfExpRes:
            expType = exp.getValuesFor('dataType')[0]
            if expType == 'upperLimit':
                nUL += 1
            elif  expType == 'efficiencyMap':
                nEM += 1
        print( "\n Loaded Database with %i UL results and %i EM results " %(nUL,nEM), file=f )

        # Compute the theory predictions for each experimental result and print them:
        print("\n Theory Predictions and Constraints:", file=f)
        rmax = 0.
        bestResult = None
        for expResult in listOfExpRes:
            predictions = theoryPredictionsFor(expResult, toplist, combinedResults=False, marginalize=False)
            if not predictions: continue # Skip if there are no constraints from this result
            print('\n %s ' %expResult.globalInfo.id, file=f)
            for theoryPrediction in predictions:
                dataset = theoryPrediction.dataset
                datasetID = dataset.dataInfo.dataId            
                mass = theoryPrediction.mass
                txnames = [str(txname) for txname in theoryPrediction.txnames]
                PIDs =  theoryPrediction.PIDs         
                print( "------------------------", file=f )
                print( "Dataset = ", datasetID, file=f )   #Analysis name
                print( "TxNames = ", txnames, file=f )  
                print( "Prediction Mass = ",mass, file=f )   #Value for average cluster mass (average mass of the elements in cluster)
                print( "Prediction PIDs = ",PIDs, file=f )   #Value for average cluster mass (average mass of the elements in cluster)
                print( "Theory Prediction = ",theoryPrediction.xsection, file=f )  #Signal cross section
                print( "Condition Violation = ",theoryPrediction.conditions, file=f ) #Condition violation values
              
                # Get the corresponding upper limit:
                print( "UL for theory prediction = ",theoryPrediction.upperLimit, file=f )

                # Compute the r-value
                r = theoryPrediction.getRValue()
                print( "r = ",r , file=f)
                #Compute likelihhod and chi^2 for EM-type results:
                if dataset.dataInfo.dataType == 'efficiencyMap':
                    theoryPrediction.computeStatistics()
                    print( 'Chi2, likelihood=', theoryPrediction.chi2, theoryPrediction.likelihood, file=f )
                if r > rmax:
                    rmax = r
                    bestResult = expResult.globalInfo.id

        # Print the most constraining experimental result
        print( "\nThe largest r-value (theory/upper limit ratio) is ",rmax, file=f )
        if rmax > 1.:
            print( "(The input model is likely excluded by %s)" %bestResult, file=f )
        else:
            print( "(The input model is not excluded by the simplified model results)", file=f )

        f.close()
Esempio n. 26
0
def main():
    """
    Main program. Displays basic use case.
    """
    
    #Define your model (list of rEven and rOdd particles)
    particlesLoader.load( 'smodels.share.models.mssm' ) #Make sure all the model particles are up-to-date
    
    # Path to input file (either a SLHA or LHE file)
    slhafile = 'inputFiles/slha/lightEWinos.slha'
    lhefile = 'inputFiles/lhe/gluino_squarks.lhe'

    # Set main options for decomposition
    sigmacut = 0.01 * fb
    mingap = 5. * GeV

    
    # Decompose model (use slhaDecomposer for SLHA input or lheDecomposer for LHE input)
    slhaInput = True
    if slhaInput:
        toplist = slhaDecomposer.decompose(slhafile, sigmacut, doCompress=True, doInvisible=True, minmassgap=mingap)
    else:
        toplist = lheDecomposer.decompose(lhefile, doCompress=True,doInvisible=True, minmassgap=mingap)
    # Access basic information from decomposition, using the topology list and topology objects:
    print( "\n Decomposition Results: " )
    print( "\t  Total number of topologies: %i " %len(toplist) )
    nel = sum([len(top.elementList) for top in toplist])
    print( "\t  Total number of elements = %i " %nel )
    #Print information about the m-th topology (if it exists):
    m = 2
    if len(toplist) > m:
        top = toplist[m]
        print( "\t\t %i-th topology  = " %m,top,"with total cross section =",top.getTotalWeight() )
        #Print information about the n-th element in the m-th topology:
        n = 0
        el = top.elementList[n]
        print( "\t\t %i-th element from %i-th topology  = " %(n,m),el, end="" )
        print( "\n\t\t\twith final states =",el.getFinalStates(),"\n\t\t\twith cross section =",el.weight,"\n\t\t\tand masses = ",el.getMasses() )
            
    # Load the experimental results to be used.
    # In this case, all results are employed.
    listOfExpRes = database.getExpResults()

    # Print basic information about the results loaded.
    # Count the number of loaded UL and EM experimental results:
    nUL, nEM = 0, 0
    for exp in listOfExpRes:
        expType = exp.getValuesFor('dataType')[0]
        if expType == 'upperLimit':
            nUL += 1
        elif  expType == 'efficiencyMap':
            nEM += 1
    print( "\n Loaded Database with %i UL results and %i EM results " %(nUL,nEM) )

    # Compute the theory predictions for each experimental result and print them:
    print("\n Theory Predictions and Constraints:")
    rmax = 0.
    bestResult = None
    for expResult in listOfExpRes:
        predictions = theoryPredictionsFor(expResult, toplist, combinedResults=False, marginalize=False)
        if not predictions: continue # Skip if there are no constraints from this result
        print('\n %s ' %expResult.globalInfo.id)
        for theoryPrediction in predictions:
            dataset = theoryPrediction.dataset
            datasetID = dataset.dataInfo.dataId            
            mass = theoryPrediction.mass
            txnames = [str(txname) for txname in theoryPrediction.txnames]
            PIDs =  theoryPrediction.PIDs         
            print( "------------------------" )
            print( "Dataset = ",datasetID )   #Analysis name
            print( "TxNames = ",txnames )  
            print( "Prediction Mass = ",mass )   #Value for average cluster mass (average mass of the elements in cluster)
            print( "Prediction PIDs = ",PIDs )   #Value for average cluster mass (average mass of the elements in cluster)
            print( "Theory Prediction = ",theoryPrediction.xsection )  #Signal cross section
            print( "Condition Violation = ",theoryPrediction.conditions ) #Condition violation values
              
            # Get the corresponding upper limit:
            print( "UL for theory prediction = ",theoryPrediction.upperLimit )

            # Compute the r-value
            r = theoryPrediction.getRValue()
            print( "r = ",r )
            #Compute likelihhod and chi^2 for EM-type results:
            if dataset.dataInfo.dataType == 'efficiencyMap':
                theoryPrediction.computeStatistics()
                print( 'Chi2, likelihood=', theoryPrediction.chi2, theoryPrediction.likelihood )
            if r > rmax:
                rmax = r
                bestResult = expResult.globalInfo.id
            
    # Print the most constraining experimental result
    print( "\nThe largest r-value (theory/upper limit ratio) is ",rmax )
    if rmax > 1.:
        print( "(The input model is likely excluded by %s)" %bestResult )
    else:
        print( "(The input model is not excluded by the simplified model results)" )
      
    #Find out missing topologies for sqrts=8*TeV:
    uncovered = coverage.Uncovered(toplist,sqrts=8.*TeV)
    #Print uncovered cross-sections:
    print( "\nTotal missing topology cross section (fb): %10.3E\n" %(uncovered.getMissingXsec()) )
    print( "Total cross section where we are outside the mass grid (fb): %10.3E\n" %(uncovered.getOutOfGridXsec()) )
    print( "Total cross section in long cascade decays (fb): %10.3E\n" %(uncovered.getLongCascadeXsec()) )
    print( "Total cross section in decays with asymmetric branches (fb): %10.3E\n" %(uncovered.getAsymmetricXsec()) )
    
    #Print some of the missing topologies:
    print( 'Missing topologies (up to 3):' )
    for topo in uncovered.missingTopos.topos[:3]:
        print( 'Topology:',topo.topo )
        print( 'Contributing elements (up to 2):' )
        for el in topo.contributingElements[:2]:
            print( el,'cross-section (fb):', el.missingX )
    
    #Print elements with long cascade decay:
    print( '\nElements outside the grid (up to 2):' )
    for topo in uncovered.outsideGrid.topos[:2]:
        print( 'Topology:',topo.topo )
        print( 'Contributing elements (up to 4):' )
        for el in topo.contributingElements[:4]:
            print( el,'cross-section (fb):', el.missingX )
            print( '\tmass:',el.getMasses() )
Esempio n. 27
0
def main():
    """
    Main program. Displays basic use case.

    """

    # Path to input file (either a SLHA or LHE file)
    slhafile = 'inputFiles/slha/lightEWinos.slha'
    # lhefile = 'inputFiles/lhe/gluino_squarks.lhe'

    # Set main options for decomposition
    sigmacut = 0.3 * fb
    mingap = 5. * GeV

    # Decompose model (use slhaDecomposer for SLHA input or lheDecomposer for LHE input)
    toplist = slhaDecomposer.decompose(slhafile,
                                       sigmacut,
                                       doCompress=True,
                                       doInvisible=True,
                                       minmassgap=mingap)
    # toplist = lheDecomposer.decompose(lhefile, doCompress=True,doInvisible=True, minmassgap=mingap)

    # Access basic information from decomposition, using the topology list and topology objects:
    print "\n Decomposition Results: "
    print "\t  Total number of topologies: %i " % len(toplist)
    nel = sum([len(top.elementList) for top in toplist])
    print "\t  Total number of elements = %i " % nel
    #Print information about the m-th topology:
    m = 3
    top = toplist[m]
    print "\t\t %i-th topology  = " % m, top, "with total cross section =", top.getTotalWeight(
    )
    #Print information about the n-th element in the m-th topology:
    n = 0
    el = top.elementList[n]
    print "\t\t %i-th element from %i-th topology  = " % (n, m), el,
    print "\n\t\t\twith cross section =", el.weight, "\n\t\t\tand masses = ", el.getMasses(
    )

    # Load the experimental results to be used.
    # In this case, all results are employed.
    listOfExpRes = database.getExpResults()

    # Print basic information about the results loaded.
    # Count the number of loaded UL and EM experimental results:
    nUL, nEM = 0, 0
    for exp in listOfExpRes:
        expType = exp.getValuesFor('dataType')[0]
        if expType == 'upperLimit':
            nUL += 1
        elif expType == 'efficiencyMap':
            nEM += 1
    print "\n Loaded Database with %i UL results and %i EM results " % (nUL,
                                                                        nEM)

    # Compute the theory predictions for each experimental result and print them:
    print("\n Theory Predictions and Constraints:")
    rmax = 0.
    bestResult = None
    for expResult in listOfExpRes:
        predictions = theoryPredictionsFor(expResult, toplist)
        if not predictions:
            continue  # Skip if there are no constraints from this result
        print('\n %s ' % expResult.globalInfo.id)
        for theoryPrediction in predictions:
            dataset = theoryPrediction.dataset
            datasetID = dataset.dataInfo.dataId
            mass = theoryPrediction.mass
            txnames = [str(txname) for txname in theoryPrediction.txnames]
            PIDs = theoryPrediction.PIDs
            print "------------------------"
            print "Dataset = ", datasetID  #Analysis name
            print "TxNames = ", txnames
            print "Prediction Mass = ", mass  #Value for average cluster mass (average mass of the elements in cluster)
            print "Prediction PIDs = ", PIDs  #Value for average cluster mass (average mass of the elements in cluster)
            print "Theory Prediction = ", theoryPrediction.xsection  #Signal cross section
            print "Condition Violation = ", theoryPrediction.conditions  #Condition violation values

            # Get the corresponding upper limit:
            ul = expResult.getUpperLimitFor(txname=txnames[0],
                                            mass=mass,
                                            dataID=datasetID)
            print "UL for theory prediction = ", ul

            # Compute the r-value
            r = theoryPrediction.xsection.value / ul
            print "r = ", r
            if r > rmax:
                rmax = r
                bestResult = expResult.globalInfo.id

    # Print the most constraining experimental result
    print "\nThe largest r-value (theory/upper limit ratio) is ", rmax
    if rmax > 1.:
        print "(The input model is likely excluded by %s)" % bestResult
    else:
        print "(The input model is not excluded by the simplified model results)"