コード例 #1
0
ファイル: doPlotFromWS.py プロジェクト: atpathak/ATLAS
def getBinByBinErrorBand(mc_comps, observables, binWidths, rfr, weights=None):
    if rfr is None:
        return None
    bins = []
    binning = observables[0].getBinning()
    stepsize = binning.averageBinWidth()
    low = binning.lowBound()
    high = binning.highBound()
    real_weights = RooArgList()
    if weights is not None:
        for bw, w in zip(binWidths, weights):
            real_weights.add(RF.RooConst(bw.getVal() * w))
    else:
        for bw in binWidths:
            real_weights.add(RF.RooConst(bw.getVal()))
    m = low
    while m < high - 1e-6:
        rname = "bin" + str(m)
        intes = RooArgList()
        for obs, mc in zip(observables, mc_comps):
            intes.add(mc.createIntegral(RooArgSet(obs), RF.Range(rname)))
        totbin = RooAddition("sumbin", "sumbin", intes, real_weights)
        val = totbin.getVal()
        err = ROOT.RU.getPropagatedError(totbin, rfr)
        bins.append((val, err))
        logging.debug("Found error of {}".format(err))
        m += stepsize
    yvals = []
    xvals = []
    for i, b in enumerate(bins):
        yvals.extend([b[0] + b[1], b[0] + b[1]])
        xvals.extend([binning.binLow(i), binning.binLow(i)])
    xvals.append(high)
    xvals = xvals[1:]
    xvals.extend(reversed(xvals))
    for b in reversed(bins):
        yvals.extend([b[0] - b[1], b[0] - b[1]])
    # # FIXME JWH
    # for x,y in zip(xvals,yvals):
    #     print "(x,y) = ({},{})".format(x,y)
    yvals_a = array('d', yvals)
    xvals_a = array('d', xvals)
    curve = TGraph(len(xvals), xvals_a, yvals_a)
    return curve
コード例 #2
0
ファイル: doPlotFromWS.py プロジェクト: atpathak/ATLAS
def getSumAndError(list_comps, rfr, window=None):
    """ list_comps: list of tuples (obs, bwidth, comp)
    """
    complist = RooArgList()
    widthlist = RooArgList()
    logging.debug("{}".format(list_comps))
    for l in list_comps:
        if window:
            l[0].setRange("myrange", window[0], window[1])
            inte = l[2].createIntegral(RooArgSet(l[0]), RF.Range("myrange"))
        else:
            inte = l[2].createIntegral(RooArgSet(l[0]))
        complist.add(inte)
        widthlist.add(RF.RooConst(l[1]))
    roosum = RooAddition("sum", "sum", complist, widthlist)
    val = roosum.getVal()
    if rfr is not None:
        error = ROOT.RU.getPropagatedError(roosum, rfr)
    else:
        error = -1
    return [val, error]
コード例 #3
0
ファイル: YieldsTable.py プロジェクト: suneetu/2LEP-WH-Limits
def latexfitresults(filename,regionList,sampleList,exactRegionNames=False,dataname='obsData',showSum=False, doAsym=True, blinded=False):
  workspacename = 'w'
  w = Util.GetWorkspaceFromFile(filename,'w')

  if w==None:
    print "ERROR : Cannot open workspace : ", workspacename
    sys.exit(1) 

  resultAfterFit = w.obj('RooExpandedFitResult_afterFit')
  if resultAfterFit==None:
    print "ERROR : Cannot open fit result after fit RooExpandedFitResult_afterFit"
    sys.exit(1)

  resultBeforeFit = w.obj('RooExpandedFitResult_beforeFit')
  if resultBeforeFit==None:
    print "ERROR : Cannot open fit result before fit RooExpandedFitResult_beforeFit"
    sys.exit(1)

  data_set = w.data(dataname)
  if data_set==None:
    print "ERROR : Cannot open dataset : ", "data_set"+suffix
    sys.exit(1)
      
  regionCat = w.obj("channelCat")
  data_set.table(regionCat).Print("v");

  regionFullNameList = [ Util.GetFullRegionName(regionCat, region) for region in regionList]
  print regionFullNameList

  ######

  snapshot =  'snapshot_paramsVals_RooExpandedFitResult_afterFit'
  w.loadSnapshot(snapshot)

  if not w.loadSnapshot(snapshot):
    print "ERROR : Cannot load snapshot : ", snapshot
    sys.exit(1)

  tablenumbers = {}

  # SUM ALL REGIONS
  sumName = ""
  for index, reg in enumerate(regionList):
    if index == 0:
      sumName = reg
    else:
      sumName = sumName + " + " + reg
  
  regionListWithSum = list(regionList)
  if showSum:
    regionListWithSum.append(sumName)

  tablenumbers['names'] = regionListWithSum

  regionCatList = [ 'channelCat==channelCat::' +region.Data() for region in regionFullNameList]
  
  regionDatasetList = [data_set.reduce(regioncat) for regioncat in regionCatList]
  for index, data in enumerate(regionDatasetList):
    data.SetName("data_" + regionList[index])
    data.SetTitle("data_" + regionList[index])
    
  nobs_regionList = [ data.sumEntries() for data in regionDatasetList]
  #SUM
  sumNobs = 0.
  for nobs in nobs_regionList:
    sumNobs += nobs
    ## print " \n XXX nobs = ", nobs, "    sumNobs = ", sumNobs
  if showSum:
    nobs_regionList.append(sumNobs)
  tablenumbers['nobs'] = nobs_regionList
 
  ######
  ######
  ######  FROM HERE ON OUT WE CALCULATE THE FITTED NUMBER OF EVENTS __AFTER__ THE FIT
  ######
  ######

  # total pdf, not splitting in components
  pdfinRegionList = [ Util.GetRegionPdf(w, region)  for region in regionList]
  varinRegionList =  [ Util.GetRegionVar(w, region) for region in regionList]
  rrspdfinRegionList = []
  for index,pdf in enumerate(pdfinRegionList):
#    pdf.Print("t")
    prodList = pdf.pdfList()
    foundRRS = 0
    for idx in range(prodList.getSize()):
      #      if "BG" in prodList[idx].GetName():
      #        prodList[idx].Print("t")
      if prodList[idx].InheritsFrom("RooRealSumPdf"):
        rrspdfInt =  prodList[idx].createIntegral(RooArgSet(varinRegionList[index]));
        rrspdfinRegionList.append(rrspdfInt)
        foundRRS += 1
    if foundRRS >1 or foundRRS==0:
      print " \n\n WARNING: ", pdf.GetName(), " has ", foundRRS, " instances of RooRealSumPdf"
      print pdf.GetName(), " component list:", prodList.Print("v")
    
  nFittedInRegionList =  [ pdf.getVal() for index, pdf in enumerate(rrspdfinRegionList)]
  pdfFittedErrInRegionList = [ Util.GetPropagatedError(pdf, resultAfterFit, doAsym) for pdf in rrspdfinRegionList]

  if showSum:
    pdfInAllRegions = RooArgSet()
    for index, pdf in enumerate(rrspdfinRegionList):
      pdfInAllRegions.add(pdf)
    pdfSumInAllRegions = RooAddition( "pdf_AllRegions_AFTER", "pdf_AllRegions_AFTER", RooArgList(pdfInAllRegions))
    pdfSumInAllRegions.Print()
    nPdfSumVal = pdfSumInAllRegions.getVal()
    nPdfSumError = Util.GetPropagatedError(pdfSumInAllRegions, resultAfterFit, doAsym)
    nFittedInRegionList.append(nPdfSumVal)
    pdfFittedErrInRegionList.append(nPdfSumError)
  
  tablenumbers['TOTAL_FITTED_bkg_events']    =  nFittedInRegionList
  tablenumbers['TOTAL_FITTED_bkg_events_err']    =  pdfFittedErrInRegionList
 
  if blinded: 
    nobs_regionList = [ data.sumEntries() for data in regionDatasetList]
    nobs_regionList[-1] = -1
    tablenumbers['nobs'] = nobs_regionList

  # components
  for isam, sample in enumerate(sampleList):
    sampleName=getName(sample)
    nSampleInRegionVal = []
    nSampleInRegionError = []
    sampleInAllRegions = RooArgSet()
    for ireg, region in enumerate(regionList):
      sampleInRegion=getPdfInRegions(w,sample,region)
      #sampleInRegion = Util.GetComponent(w,sample,region,exactRegionNames)
      sampleInRegionVal = 0.
      sampleInRegionError = 0.
      if not sampleInRegion==None:
        sampleInRegion.Print()
        sampleInRegionVal = sampleInRegion.getVal()
        sampleInRegionError = Util.GetPropagatedError(sampleInRegion, resultAfterFit, doAsym) 
        sampleInAllRegions.add(sampleInRegion)
      else:
        print " \n YieldsTable.py: WARNING: sample =", sampleName, " non-existent (empty) in region =",region, "\n"
      nSampleInRegionVal.append(sampleInRegionVal)
      nSampleInRegionError.append(sampleInRegionError)
    if showSum:
      sampleSumInAllRegions = RooAddition( (sampleName+"_AllRegions_FITTED"), (sampleName+"_AllRegions_FITTED"), RooArgList(sampleInAllRegions))
      sampleSumInAllRegions.Print()
      nSampleSumVal = sampleSumInAllRegions.getVal()
      nSampleSumError = Util.GetPropagatedError(sampleSumInAllRegions, resultAfterFit, doAsym)
      nSampleInRegionVal.append(nSampleSumVal)
      nSampleInRegionError.append(nSampleSumError)
    tablenumbers['Fitted_events_'+sampleName]   = nSampleInRegionVal
    tablenumbers['Fitted_err_'+sampleName]   = nSampleInRegionError

  print tablenumbers

  ######
  ######
  ######  FROM HERE ON OUT WE CALCULATE THE EXPECTED NUMBER OF EVENTS __BEFORE__ THE FIT
  ######
  ######

  #  FROM HERE ON OUT WE CALCULATE THE EXPECTED NUMBER OF EVENTS BEFORE THE FIT
  w.loadSnapshot('snapshot_paramsVals_RooExpandedFitResult_beforeFit')

  # check if any of the initial scaling factors is != 1
  _result = w.obj('RooExpandedFitResult_beforeFit')
  _muFacs = _result.floatParsFinal()

  for i in range(len(_muFacs)):
    if "mu_" in _muFacs[i].GetName() and _muFacs[i].getVal() != 1.0:
      print  " \n WARNING: scaling factor %s != 1.0 (%g) expected MC yield WILL BE WRONG!" % (_muFacs[i].GetName(), _muFacs[i].getVal())
  
  pdfinRegionList = [ Util.GetRegionPdf(w, region)  for region in regionList]
  varinRegionList =  [ Util.GetRegionVar(w, region) for region in regionList]
  rrspdfinRegionList = []
  for index,pdf in enumerate(pdfinRegionList):
    prodList = pdf.pdfList()
    foundRRS = 0
    for idx in range(prodList.getSize()):
      if prodList[idx].InheritsFrom("RooRealSumPdf"):
        prodList[idx].Print()
        rrspdfInt =  prodList[idx].createIntegral(RooArgSet(varinRegionList[index]))
        rrspdfinRegionList.append(rrspdfInt)
        foundRRS += 1
    if foundRRS >1 or foundRRS==0:
      print " \n\n WARNING: ", pdf.GetName(), " has ", foundRRS, " instances of RooRealSumPdf"
      print pdf.GetName(), " component list:", prodList.Print("v")

  nExpInRegionList =  [ pdf.getVal() for index, pdf in enumerate(rrspdfinRegionList)]
  pdfExpErrInRegionList = [ Util.GetPropagatedError(pdf, resultBeforeFit, doAsym)  for pdf in rrspdfinRegionList]
  
  if showSum:
    pdfInAllRegions = RooArgSet()
    for index, pdf in enumerate(rrspdfinRegionList):
      pdfInAllRegions.add(pdf)
    pdfSumInAllRegions = RooAddition( "pdf_AllRegions_BEFORE", "pdf_AllRegions_BEFORE", RooArgList(pdfInAllRegions))
    nPdfSumVal = pdfSumInAllRegions.getVal()
    nPdfSumError = Util.GetPropagatedError(pdfSumInAllRegions, resultBeforeFit, doAsym)
    nExpInRegionList.append(nPdfSumVal)
    pdfExpErrInRegionList.append(nPdfSumError)
  
  tablenumbers['TOTAL_MC_EXP_BKG_events']    =  nExpInRegionList
  tablenumbers['TOTAL_MC_EXP_BKG_err']    =  pdfExpErrInRegionList
  
  for isam, sample in enumerate(sampleList):
    sampleName=getName(sample)
    nMCSampleInRegionVal = []
    nMCSampleInRegionError = []
    MCSampleInAllRegions = RooArgSet()
    for ireg, region in enumerate(regionList):
      MCSampleInRegion = getPdfInRegions(w,sample,region)
      #MCSampleInRegion = Util.GetComponent(w,sample,region,exactRegionNames)
      MCSampleInRegionVal = 0.
      MCSampleInRegionError = 0.
      if not MCSampleInRegion==None:
        MCSampleInRegionVal = MCSampleInRegion.getVal()
        MCSampleInRegionError = Util.GetPropagatedError(MCSampleInRegion, resultBeforeFit, doAsym) 
        MCSampleInAllRegions.add(MCSampleInRegion)
      else:
        print " \n WARNING: sample=", sampleName, " non-existent (empty) in region=",region
      nMCSampleInRegionVal.append(MCSampleInRegionVal)
      nMCSampleInRegionError.append(MCSampleInRegionError)
    if showSum:
      MCSampleSumInAllRegions = RooAddition( (sampleName+"_AllRegions_MC"), (sampleName+"_AllRegions_MC"), RooArgList(MCSampleInAllRegions))
      nMCSampleSumVal = MCSampleSumInAllRegions.getVal()
      nMCSampleSumError = Util.GetPropagatedError(MCSampleSumInAllRegions, resultBeforeFit, doAsym)
      nMCSampleInRegionVal.append(nMCSampleSumVal)
      nMCSampleInRegionError.append(nMCSampleSumError)
    tablenumbers['MC_exp_events_'+sampleName] = nMCSampleInRegionVal
    tablenumbers['MC_exp_err_'+sampleName] = nMCSampleInRegionError

    #  sorted(tablenumbers, key=lambda sample: sample[1])   # sort by age
  map_listofkeys = tablenumbers.keys()
  map_listofkeys.sort()
  
  for name in map_listofkeys:
    if tablenumbers.has_key(name) :
      print name, ": ", tablenumbers[name]
      
  ###
  return tablenumbers
コード例 #4
0
def latexfitresults(filename,
                    regionList,
                    sampleList,
                    dataname='obsData',
                    showSum=False,
                    doAsym=True,
                    blinded=False,
                    splitBins=False):
    """
  Calculate before/after-fit yields in all channels given
  
  @param filename The filename containing afterFit workspace
  @param regionList A list of regions to be considered
  @param sampleList A list of samples to be considered
  @param dataname The name of dataset (default='obsData')
  @param showSum Calculates sum of all regions if set to true (default=False)
  @param doAsym Calculates asymmetric errors taken from MINOS (default=True)
  @param blinded Observed event count will not be shown if set to True (default=False)
  @param splitBins Calculates bin-by-bin yields for all regions if set to True (default=False)
  """
    """
  pick up workspace from file
  """
    workspacename = 'w'
    w = Util.GetWorkspaceFromFile(filename, 'w')
    if w == None:
        print "ERROR : Cannot open workspace : ", workspacename
        sys.exit(1)
    """
  pick up after-fit RooExpandedFitResult from workspace
  """
    resultAfterFit = w.obj('RooExpandedFitResult_afterFit')
    if resultAfterFit == None:
        print "ERROR : Cannot open fit result after fit RooExpandedFitResult_afterFit"
        sys.exit(1)
    """
  pick up before-fit RooExpandedFitResult from workspace
  """
    resultBeforeFit = w.obj('RooExpandedFitResult_beforeFit')
    if resultBeforeFit == None:
        print "ERROR : Cannot open fit result before fit RooExpandedFitResult_beforeFit"
        sys.exit(1)
    """
  pick up dataset from workspace
  """
    data_set = w.data(dataname)
    if data_set == None:
        print "ERROR : Cannot open dataset : ", "data_set" + suffix
        sys.exit(1)
    """
  pick up channel category (RooCategory) from workspace
  """
    regionCat = w.obj("channelCat")
    if not blinded:
        data_set.table(regionCat).Print("v")
    """
  find full (long) name list of regions (i.e. short=SR3J, long=SR3J_meffInc30_JVF25pt50)
  """
    regionFullNameList = [
        Util.GetFullRegionName(regionCat, region) for region in regionList
    ]
    """
  load afterFit workspace snapshot (=set all parameters to values after fit)
  """
    snapshot = 'snapshot_paramsVals_RooExpandedFitResult_afterFit'
    w.loadSnapshot(snapshot)

    if not w.loadSnapshot(snapshot):
        print "ERROR : Cannot load snapshot : ", snapshot
        sys.exit(1)
    """
  define set, for all names/yields to be saved in
  """
    tablenumbers = {}
    """
  if showSum=True define names for sum of all regions and add to regionList
  """
    sumName = ""
    for index, reg in enumerate(regionList):
        if index == 0:
            sumName = reg
        else:
            sumName = sumName + " + " + reg

    regionListWithSum = list(regionList)
    if showSum:
        regionListWithSum.append(sumName)

    tablenumbers['names'] = regionListWithSum
    """
  make a list of channelCat calls for every region
  """
    regionCatList = [
        'channelCat==channelCat::' + region.Data()
        for region in regionFullNameList
    ]
    """
  retrieve number of observed (=data) events per region
  """
    regionDatasetList = [
        data_set.reduce(regioncat) for regioncat in regionCatList
    ]
    for index, data in enumerate(regionDatasetList):
        data.SetName("data_" + regionList[index])
        data.SetTitle("data_" + regionList[index])

    nobs_regionList = [data.sumEntries() for data in regionDatasetList]
    """
  if showSum=True calculate the total number of observed events in all regions  
  """
    sumNobs = 0.
    for nobs in nobs_regionList:
        sumNobs += nobs
    if showSum:
        nobs_regionList.append(sumNobs)
    tablenumbers['nobs'] = nobs_regionList
    """
  FROM HERE ON OUT WE CALCULATE THE FITTED NUMBER OF EVENTS __AFTER__ THE FIT
  """
    """
  get a list of pdf's and variables per region
  """
    pdfinRegionList = [Util.GetRegionPdf(w, region) for region in regionList]
    varinRegionList = [Util.GetRegionVar(w, region) for region in regionList]
    """
  if splitBins=True get the list of Nbins, binMax and binMin; make a list of new region names for each bin
  """
    varNbinsInRegionList = []
    varBinLowInRegionList = []
    varBinHighInRegionList = []
    rangeNameBinsInRegionList = []
    if splitBins:
        varNbinsInRegionList = [
            Util.GetRegionVar(w, region).getBinning().numBins()
            for region in regionList
        ]
        varBinLowInRegionList = [[
            Util.GetRegionVar(w, region).getBinning(
                (region + "binning")).binLow(ibin)
            for ibin in range(0, varNbinsInRegionList[idx])
        ] for idx, region in enumerate(regionList)]
        varBinHighInRegionList = [[
            Util.GetRegionVar(w, region).getBinning(
                (region + "binning")).binHigh(ibin)
            for ibin in range(0, varNbinsInRegionList[idx])
        ] for idx, region in enumerate(regionList)]
        rangeNameBinsInRegionList = [[
            regionList[idx] + "_bin" + str(ibin)
            for ibin in range(0, varNbinsInRegionList[idx])
        ] for idx, region in enumerate(regionList)]
        for index, region in enumerate(regionList):
            if varNbinsInRegionList[index] == 1:
                print " \n YieldsTable.py: WARNING: you have called -P (= per-bin yields) but this region ", region, " has only 1 bin \n"
    """
  if splitBins=True reshuffle the regionName list; each region name is followed by names of each bin (i.e. regionNameList=['SR3J','SR3J_bin1','SR3j_bin2','SR4J','SR4J_bin1'])
  """
    regionListWithBins = []
    if splitBins:
        for index, region in enumerate(regionList):
            regionListWithBins.append(region)
            for ibin in range(0, varNbinsInRegionList[index]):
                regionListWithBins.append(
                    rangeNameBinsInRegionList[index][ibin])
        tablenumbers['names'] = regionListWithBins
    """
  calculate number of observed(=data) events per bin
  """
    nobs_regionListWithBins = []
    if splitBins:
        binFuncInRegionList = [
            RooBinningCategory("bin_" + region, "bin_" + region,
                               varinRegionList[index])
            for index, region in enumerate(regionList)
        ]
        for index, data in enumerate(regionDatasetList):
            data.addColumn(binFuncInRegionList[index])
            if not blinded:
                data.table(binFuncInRegionList[index]).Print("v")
            nobs_regionListWithBins.append(data.sumEntries())
            for ibin in range(0, varNbinsInRegionList[index]):
                nobs_regionListWithBins.append(
                    (data.reduce(binFuncInRegionList[index].GetName() + "==" +
                                 binFuncInRegionList[index].GetName() + "::" +
                                 varinRegionList[index].GetName() + "_bin" +
                                 str(ibin))).sumEntries())

        tablenumbers['nobs'] = nobs_regionListWithBins
    """
  if blinded=True, set all numbers of observed events to -1
  """
    if blinded:
        for index, nobs in enumerate(nobs_regionListWithBins):
            nobs_regionListWithBins[index] = -1
        tablenumbers['nobs'] = nobs_regionListWithBins
    """
  get a list of RooRealSumPdf per region (RooRealSumPdf is the top-pdf per region containing all samples)
  """
    rrspdfinRegionList = []
    for index, pdf in enumerate(pdfinRegionList):
        prodList = pdf.pdfList()
        foundRRS = 0
        for idx in range(prodList.getSize()):
            if prodList[idx].InheritsFrom("RooRealSumPdf"):
                rrspdfInt = prodList[idx].createIntegral(
                    RooArgSet(varinRegionList[index]))
                rrspdfinRegionList.append(rrspdfInt)
                if splitBins:
                    origMin = varinRegionList[index].getMin()
                    origMax = varinRegionList[index].getMax()
                    for ibin in range(0, varNbinsInRegionList[index]):
                        rangeName = rangeNameBinsInRegionList[index][ibin]
                        varinRegionList[index].setRange(
                            rangeName, varBinLowInRegionList[index][ibin],
                            varBinHighInRegionList[index][ibin])
                        rrspdfInt = prodList[idx].createIntegral(
                            RooArgSet(varinRegionList[index]), rangeName)
                        rrspdfinRegionList.append(rrspdfInt)
                    varinRegionList[index].setRange(origMin, origMax)
                foundRRS += 1
        if foundRRS > 1 or foundRRS == 0:
            print " \n\n WARNING: ", pdf.GetName(
            ), " has ", foundRRS, " instances of RooRealSumPdf"
            print pdf.GetName(), " component list:", prodList.Print("v")
    """
  calculate total pdf number of fitted events and error
  """
    nFittedInRegionList = [
        pdf.getVal() for index, pdf in enumerate(rrspdfinRegionList)
    ]
    pdfFittedErrInRegionList = [
        Util.GetPropagatedError(pdf, resultAfterFit, doAsym)
        for pdf in rrspdfinRegionList
    ]
    """
  if showSum=True calculate the total number of fitted events in all regions  
  """
    if showSum:
        pdfInAllRegions = RooArgSet()
        for index, pdf in enumerate(rrspdfinRegionList):
            pdfInAllRegions.add(pdf)
        pdfSumInAllRegions = RooAddition("pdf_AllRegions_AFTER",
                                         "pdf_AllRegions_AFTER",
                                         RooArgList(pdfInAllRegions))
        nPdfSumVal = pdfSumInAllRegions.getVal()
        nPdfSumError = Util.GetPropagatedError(pdfSumInAllRegions,
                                               resultAfterFit, doAsym)
        nFittedInRegionList.append(nPdfSumVal)
        pdfFittedErrInRegionList.append(nPdfSumError)

    tablenumbers['TOTAL_FITTED_bkg_events'] = nFittedInRegionList
    tablenumbers['TOTAL_FITTED_bkg_events_err'] = pdfFittedErrInRegionList
    """
  calculate the fitted number of events and propagated error for each requested sample, by splitting off each sample pdf
  """
    for isam, sample in enumerate(sampleList):
        sampleName = getName(sample)
        nSampleInRegionVal = []
        nSampleInRegionError = []
        sampleInAllRegions = RooArgSet()
        for ireg, region in enumerate(regionList):
            sampleInRegion = getPdfInRegions(w, sample, region)
            sampleInRegionVal = 0.
            sampleInRegionError = 0.
            if not sampleInRegion == None:
                sampleInRegionVal = sampleInRegion.getVal()
                sampleInRegionError = Util.GetPropagatedError(
                    sampleInRegion, resultAfterFit, doAsym)
                sampleInAllRegions.add(sampleInRegion)
            else:
                print " \n YieldsTable.py: WARNING: sample =", sampleName, " non-existent (empty) in region =", region, "\n"
            nSampleInRegionVal.append(sampleInRegionVal)
            nSampleInRegionError.append(sampleInRegionError)
            """
      if splitBins=True calculate numbers of fitted events plus error per bin      
      """
            if splitBins:
                origMin = varinRegionList[ireg].getMin()
                origMax = varinRegionList[ireg].getMax()
                for ibin in range(0, varNbinsInRegionList[ireg]):
                    rangeName = rangeNameBinsInRegionList[ireg][ibin]
                    sampleInRegion = getPdfInRegionsWithRangeName(
                        w, sample, region, rangeName)
                    sampleInRegionVal = 0.
                    sampleInRegionError = 0.
                    if not sampleInRegion == None:
                        varinRegionList[ireg].setRange(
                            rangeName, varBinLowInRegionList[ireg][ibin],
                            varBinHighInRegionList[ireg][ibin])
                        sampleInRegionVal = sampleInRegion.getVal()
                        sampleInRegionError = Util.GetPropagatedError(
                            sampleInRegion, resultAfterFit, doAsym)
                    else:
                        print " \n YieldsTable.py: WARNING: sample =", sampleName, " non-existent (empty) in region=", region, " bin=", ibin, " \n"
                    nSampleInRegionVal.append(sampleInRegionVal)
                    nSampleInRegionError.append(sampleInRegionError)

                varinRegionList[ireg].setRange(origMin, origMax)
        """
    if showSum=True calculate the total number of fitted events in all regions  
    """
        if showSum:
            sampleSumInAllRegions = RooAddition(
                (sampleName + "_AllRegions_FITTED"),
                (sampleName + "_AllRegions_FITTED"),
                RooArgList(sampleInAllRegions))
            nSampleSumVal = sampleSumInAllRegions.getVal()
            nSampleSumError = Util.GetPropagatedError(sampleSumInAllRegions,
                                                      resultAfterFit, doAsym)
            nSampleInRegionVal.append(nSampleSumVal)
            nSampleInRegionError.append(nSampleSumError)
        tablenumbers['Fitted_events_' + sampleName] = nSampleInRegionVal
        tablenumbers['Fitted_err_' + sampleName] = nSampleInRegionError

    print "\n starting BEFORE-FIT calculations \n"
    """
  FROM HERE ON OUT WE CALCULATE THE EXPECTED NUMBER OF EVENTS __BEFORRE__ THE FIT
  """
    """
  load beforeFit workspace snapshot (=set all parameters to values before fit)
  """
    w.loadSnapshot('snapshot_paramsVals_RooExpandedFitResult_beforeFit')
    """
  check if any of the initial scaling factors is != 1
  """
    _result = w.obj('RooExpandedFitResult_beforeFit')
    _muFacs = _result.floatParsFinal()

    for i in range(len(_muFacs)):
        if "mu_" in _muFacs[i].GetName() and _muFacs[i].getVal() != 1.0:
            print " \n WARNING: scaling factor %s != 1.0 (%g) expected MC yield WILL BE WRONG!" % (
                _muFacs[i].GetName(), _muFacs[i].getVal())
    """
  get a list of pdf's and variables per region
  """
    pdfinRegionList = [Util.GetRegionPdf(w, region) for region in regionList]
    varinRegionList = [Util.GetRegionVar(w, region) for region in regionList]
    """
  get a list of RooRealSumPdf per region (RooRealSumPdf is the top-pdf per region containing all samples)
  """
    rrspdfinRegionList = []
    for index, pdf in enumerate(pdfinRegionList):
        prodList = pdf.pdfList()
        foundRRS = 0
        for idx in range(prodList.getSize()):
            if prodList[idx].InheritsFrom("RooRealSumPdf"):
                rrspdfInt = prodList[idx].createIntegral(
                    RooArgSet(varinRegionList[index]))
                rrspdfinRegionList.append(rrspdfInt)
                if splitBins:
                    origMin = varinRegionList[index].getMin()
                    origMax = varinRegionList[index].getMax()
                    for ibin in range(0, varNbinsInRegionList[index]):
                        rangeName = rangeNameBinsInRegionList[index][ibin]
                        varinRegionList[index].setRange(
                            rangeName, varBinLowInRegionList[index][ibin],
                            varBinHighInRegionList[index][ibin])
                        rrspdfInt = prodList[idx].createIntegral(
                            RooArgSet(varinRegionList[index]), rangeName)
                        rrspdfinRegionList.append(rrspdfInt)
                    varinRegionList[index].setRange(origMin, origMax)
                foundRRS += 1
        if foundRRS > 1 or foundRRS == 0:
            print " \n\n WARNING: ", pdf.GetName(
            ), " has ", foundRRS, " instances of RooRealSumPdf"
            print pdf.GetName(), " component list:", prodList.Print("v")
    """
  calculate total pdf number of expected events and error
  """
    nExpInRegionList = [
        pdf.getVal() for index, pdf in enumerate(rrspdfinRegionList)
    ]
    pdfExpErrInRegionList = [
        Util.GetPropagatedError(pdf, resultBeforeFit, doAsym)
        for pdf in rrspdfinRegionList
    ]
    """
  if showSum=True calculate the total number of expected events in all regions  
  """
    if showSum:
        pdfInAllRegions = RooArgSet()
        for index, pdf in enumerate(rrspdfinRegionList):
            pdfInAllRegions.add(pdf)
        pdfSumInAllRegions = RooAddition("pdf_AllRegions_BEFORE",
                                         "pdf_AllRegions_BEFORE",
                                         RooArgList(pdfInAllRegions))
        nPdfSumVal = pdfSumInAllRegions.getVal()
        nPdfSumError = Util.GetPropagatedError(pdfSumInAllRegions,
                                               resultBeforeFit, doAsym)
        nExpInRegionList.append(nPdfSumVal)
        pdfExpErrInRegionList.append(nPdfSumError)

    tablenumbers['TOTAL_MC_EXP_BKG_events'] = nExpInRegionList
    tablenumbers['TOTAL_MC_EXP_BKG_err'] = pdfExpErrInRegionList
    """
  calculate the fitted number of events and propagated error for each requested sample, by splitting off each sample pdf
  """
    for isam, sample in enumerate(sampleList):
        sampleName = getName(sample)
        nMCSampleInRegionVal = []
        nMCSampleInRegionError = []
        MCSampleInAllRegions = RooArgSet()
        for ireg, region in enumerate(regionList):
            MCSampleInRegion = getPdfInRegions(w, sample, region)
            MCSampleInRegionVal = 0.
            MCSampleInRegionError = 0.
            if not MCSampleInRegion == None:
                MCSampleInRegionVal = MCSampleInRegion.getVal()
                MCSampleInRegionError = Util.GetPropagatedError(
                    MCSampleInRegion, resultBeforeFit, doAsym)
                MCSampleInAllRegions.add(MCSampleInRegion)
            else:
                print " \n WARNING: sample=", sampleName, " non-existent (empty) in region=", region
            nMCSampleInRegionVal.append(MCSampleInRegionVal)
            nMCSampleInRegionError.append(MCSampleInRegionError)
            """
      if splitBins=True calculate numbers of fitted events plus error per bin      
      """
            if splitBins:
                origMin = varinRegionList[ireg].getMin()
                origMax = varinRegionList[ireg].getMax()
                for ibin in range(0, varNbinsInRegionList[ireg]):
                    rangeName = rangeNameBinsInRegionList[ireg][ibin]
                    MCSampleInRegion = getPdfInRegionsWithRangeName(
                        w, sample, region, rangeName)
                    MCSampleInRegionVal = 0.
                    MCSampleInRegionError = 0.
                    if not MCSampleInRegion == None:
                        varinRegionList[ireg].setRange(
                            rangeName, varBinLowInRegionList[ireg][ibin],
                            varBinHighInRegionList[ireg][ibin])
                        MCSampleInRegionVal = MCSampleInRegion.getVal()
                        MCSampleInRegionError = Util.GetPropagatedError(
                            MCSampleInRegion, resultBeforeFit, doAsym)
                    else:
                        print " \n YieldsTable.py: WARNING: sample =", sampleName, " non-existent (empty) in region=", region, " bin=", ibin, " \n"
                    nMCSampleInRegionVal.append(MCSampleInRegionVal)
                    nMCSampleInRegionError.append(MCSampleInRegionError)

                varinRegionList[ireg].setRange(origMin, origMax)
        """
    if showSum=True calculate the total number of fitted events in all regions  
    """
        if showSum:
            MCSampleSumInAllRegions = RooAddition(
                (sampleName + "_AllRegions_MC"),
                (sampleName + "_AllRegions_MC"),
                RooArgList(MCSampleInAllRegions))
            nMCSampleSumVal = MCSampleSumInAllRegions.getVal()
            nMCSampleSumError = Util.GetPropagatedError(
                MCSampleSumInAllRegions, resultBeforeFit, doAsym)
            nMCSampleInRegionVal.append(nMCSampleSumVal)
            nMCSampleInRegionError.append(nMCSampleSumError)
        tablenumbers['MC_exp_events_' + sampleName] = nMCSampleInRegionVal
        tablenumbers['MC_exp_err_' + sampleName] = nMCSampleInRegionError
    """
  sort the tablenumbers set
  """
    map_listofkeys = tablenumbers.keys()
    map_listofkeys.sort()
    """
  print the sorted tablenumbers set
  """
    for name in map_listofkeys:
        if tablenumbers.has_key(name):
            print name, ": ", tablenumbers[name]

    return tablenumbers
コード例 #5
0
def latexfitresults(filename,regionList,sampleList,dataname='obsData',showSum=False, doAsym=True, blinded=False, splitBins=False):
  """
  Calculate before/after-fit yields in all channels given

  @param filename The filename containing afterFit workspace
  @param regionList A list of regions to be considered
  @param sampleList A list of samples to be considered
  @param dataname The name of dataset (default='obsData')
  @param showSum Calculates sum of all regions if set to true (default=False)
  @param doAsym Calculates asymmetric errors taken from MINOS (default=True)
  @param blinded Observed event count will not be shown if set to True (default=False)
  @param splitBins Calculates bin-by-bin yields for all regions if set to True (default=False)
  """

  """
  pick up workspace from file
  """
  workspacename = 'w'
  w = Util.GetWorkspaceFromFile(filename,'w')
  if w==None:
    print "ERROR : Cannot open workspace : ", workspacename
    sys.exit(1)

  """
  pick up after-fit RooExpandedFitResult from workspace
  """
  resultAfterFit = w.obj('RooExpandedFitResult_afterFit')
  if resultAfterFit==None:
    print "ERROR : Cannot open fit result after fit RooExpandedFitResult_afterFit"
    sys.exit(1)

  """
  pick up before-fit RooExpandedFitResult from workspace
  """
  resultBeforeFit = w.obj('RooExpandedFitResult_beforeFit')
  if resultBeforeFit==None:
    print "ERROR : Cannot open fit result before fit RooExpandedFitResult_beforeFit"
    sys.exit(1)

  """
  pick up dataset from workspace
  """
  data_set = w.data(dataname)
  if data_set==None:
    print "ERROR : Cannot open dataset : ", "data_set"+suffix
    sys.exit(1)

  """
  pick up channel category (RooCategory) from workspace
  """
  regionCat = w.obj("channelCat")
  if not blinded:
    data_set.table(regionCat).Print("v")

  """
  find full (long) name list of regions (i.e. short=SR3J, long=SR3J_meffInc30_JVF25pt50)
  """
  regionFullNameList = [ Util.GetFullRegionName(regionCat, region) for region in regionList]


  """
  load afterFit workspace snapshot (=set all parameters to values after fit)
  """
  snapshot =  'snapshot_paramsVals_RooExpandedFitResult_afterFit'
  w.loadSnapshot(snapshot)

  if not w.loadSnapshot(snapshot):
    print "ERROR : Cannot load snapshot : ", snapshot
    sys.exit(1)

  """
  define set, for all names/yields to be saved in
  """
  tablenumbers = {}

  """
  if showSum=True define names for sum of all regions and add to regionList
  """
  sumName = ""
  for index, reg in enumerate(regionList):
    if index == 0:
      sumName = reg
    else:
      sumName = sumName + " + " + reg

  regionListWithSum = list(regionList)
  if showSum:
    regionListWithSum.append(sumName)

  tablenumbers['names'] = regionListWithSum

  """
  make a list of channelCat calls for every region
  """
  regionCatList = [ 'channelCat==channelCat::' +region.Data() for region in regionFullNameList]

  """
  retrieve number of observed (=data) events per region
  """
  print regionCatList
  srindex = regionFullNameList.index("SR_cuts")
  regionDatasetList = [data_set.reduce(regioncat) for regioncat in regionCatList]

  for index, data in enumerate(regionDatasetList):
    print "data," , data, data.GetName()
    data.SetName("data_" + regionList[index])
    data.SetTitle("data_" + regionList[index])

  nobs_regionList = [ data.sumEntries() for data in regionDatasetList]
  if blinded :  nobs_regionList[srindex] = -1
  """
  if showSum=True calculate the total number of observed events in all regions
  """
  sumNobs = 0.
  for nobs in nobs_regionList:
    sumNobs += nobs
  if showSum:
    nobs_regionList.append(sumNobs)
  tablenumbers['nobs'] = nobs_regionList


  """
  FROM HERE ON OUT WE CALCULATE THE FITTED NUMBER OF EVENTS __AFTER__ THE FIT
  """

  """
  get a list of pdf's and variables per region
  """
  pdfinRegionList = [ Util.GetRegionPdf(w, region)  for region in regionList]
  varinRegionList =  [ Util.GetRegionVar(w, region) for region in regionList]

  """
  if splitBins=True get the list of Nbins, binMax and binMin; make a list of new region names for each bin
  """
  varNbinsInRegionList =  []
  varBinLowInRegionList = []
  varBinHighInRegionList =  []
  rangeNameBinsInRegionList = []
  if splitBins:
    varNbinsInRegionList = [Util.GetRegionVar(w, region).getBinning().numBins() for region in regionList]
    varBinLowInRegionList = [[Util.GetRegionVar(w, region).getBinning((region+"binning")).binLow(ibin) for ibin in range(0, varNbinsInRegionList[idx]) ] for idx,region in enumerate(regionList)]
    varBinHighInRegionList = [[Util.GetRegionVar(w, region).getBinning((region+"binning")).binHigh(ibin) for ibin in range(0, varNbinsInRegionList[idx]) ] for idx,region in enumerate(regionList)]
    rangeNameBinsInRegionList = [[regionList[idx]+"_bin"+str(ibin) for ibin in range(0, varNbinsInRegionList[idx]) ] for idx,region in enumerate(regionList)]
    for index,region in enumerate(regionList):
      if varNbinsInRegionList[index]==1:
        print " \n YieldsTable.py: WARNING: you have called -P (= per-bin yields) but this region ", region, " has only 1 bin \n"



  """
  if splitBins=True reshuffle the regionName list; each region name is followed by names of each bin (i.e. regionNameList=['SR3J','SR3J_bin1','SR3j_bin2','SR4J','SR4J_bin1'])
  """
  regionListWithBins = []
  if splitBins:
    for index,region in enumerate(regionList):
      regionListWithBins.append(region)
      for ibin in range(0,varNbinsInRegionList[index]):
        regionListWithBins.append(rangeNameBinsInRegionList[index][ibin])
    tablenumbers['names'] = regionListWithBins


  """
  calculate number of observed(=data) events per bin
  """
  nobs_regionListWithBins = []
  if splitBins:
    binFuncInRegionList = [RooBinningCategory("bin_"+region,"bin_"+region,varinRegionList[index]) for index,region in enumerate(regionList)]
    for index, data in enumerate(regionDatasetList):
      data.addColumn(binFuncInRegionList[index])
      if not blinded:
        data.table(binFuncInRegionList[index]).Print("v")
      nobs_regionListWithBins.append(data.sumEntries())
      for ibin in range(0,varNbinsInRegionList[index]):
        nobs_regionListWithBins.append((data.reduce(binFuncInRegionList[index].GetName()+"=="+binFuncInRegionList[index].GetName()+"::"+varinRegionList[index].GetName()+"_bin"+str(ibin))).sumEntries())

    tablenumbers['nobs'] = nobs_regionListWithBins

  """
  if blinded=True, set all numbers of observed events to -1
  """
  if blinded and splitBins:
    for index, nobs in enumerate(nobs_regionListWithBins):
      nobs_regionListWithBins[index] = -1
    tablenumbers['nobs'] = nobs_regionListWithBins


  """
  get a list of RooRealSumPdf per region (RooRealSumPdf is the top-pdf per region containing all samples)
  """
  rrspdfinRegionList = []
  for index,pdf in enumerate(pdfinRegionList):
    prodList = pdf.pdfList()
    foundRRS = 0
    for idx in range(prodList.getSize()):
      if prodList[idx].InheritsFrom("RooRealSumPdf"):
        rrspdfInt =  prodList[idx].createIntegral(RooArgSet(varinRegionList[index]))
        rrspdfinRegionList.append(rrspdfInt)
        if splitBins:
          origMin = varinRegionList[index].getMin()
          origMax = varinRegionList[index].getMax()
          for ibin in range(0,varNbinsInRegionList[index]):
            rangeName = rangeNameBinsInRegionList[index][ibin]
            varinRegionList[index].setRange(rangeName,varBinLowInRegionList[index][ibin],varBinHighInRegionList[index][ibin])
            rrspdfInt =  prodList[idx].createIntegral(RooArgSet(varinRegionList[index]),rangeName)
            rrspdfinRegionList.append(rrspdfInt)
          varinRegionList[index].setRange(origMin,origMax)
        foundRRS += 1
    if foundRRS >1 or foundRRS==0:
      print " \n\n WARNING: ", pdf.GetName(), " has ", foundRRS, " instances of RooRealSumPdf"
      print pdf.GetName(), " component list:", prodList.Print("v")

  """
  calculate total pdf number of fitted events and error
  """
  nFittedInRegionList =  [ pdf.getVal() for index, pdf in enumerate(rrspdfinRegionList)]
  pdfFittedErrInRegionList = [ Util.GetPropagatedError(pdf, resultAfterFit, doAsym) for pdf in rrspdfinRegionList]


  """
  if showSum=True calculate the total number of fitted events in all regions
  """
  if showSum:
    pdfInAllRegions = RooArgSet()
    for index, pdf in enumerate(rrspdfinRegionList):
      pdfInAllRegions.add(pdf)
    pdfSumInAllRegions = RooAddition( "pdf_AllRegions_AFTER", "pdf_AllRegions_AFTER", RooArgList(pdfInAllRegions))
    nPdfSumVal = pdfSumInAllRegions.getVal()
    nPdfSumError = Util.GetPropagatedError(pdfSumInAllRegions, resultAfterFit, doAsym)
    nFittedInRegionList.append(nPdfSumVal)
    pdfFittedErrInRegionList.append(nPdfSumError)

  tablenumbers['TOTAL_FITTED_bkg_events']    =  nFittedInRegionList
  tablenumbers['TOTAL_FITTED_bkg_events_err']    =  pdfFittedErrInRegionList

  """
  calculate the fitted number of events and propagated error for each requested sample, by splitting off each sample pdf
  """
  for isam, sample in enumerate(sampleList):
    sampleName=getName(sample)
    nSampleInRegionVal = []
    nSampleInRegionError = []
    sampleInAllRegions = RooArgSet()
    for ireg, region in enumerate(regionList):
      sampleInRegion=getPdfInRegions(w,sample,region)
      sampleInRegionVal = 0.
      sampleInRegionError = 0.
      if not sampleInRegion==None:
        sampleInRegionVal = sampleInRegion.getVal()
        sampleInRegionError = Util.GetPropagatedError(sampleInRegion, resultAfterFit, doAsym)
        sampleInAllRegions.add(sampleInRegion)
      else:
        print " \n YieldsTable.py: WARNING: sample =", sampleName, " non-existent (empty) in region =",region, "\n"
      nSampleInRegionVal.append(sampleInRegionVal)
      nSampleInRegionError.append(sampleInRegionError)

      """
      if splitBins=True calculate numbers of fitted events plus error per bin
      """
      if splitBins:
        origMin = varinRegionList[ireg].getMin()
        origMax = varinRegionList[ireg].getMax()
        for ibin in range(0,varNbinsInRegionList[ireg]):
          rangeName = rangeNameBinsInRegionList[ireg][ibin]
          sampleInRegion=getPdfInRegionsWithRangeName(w,sample,region,rangeName)
          sampleInRegionVal = 0.
          sampleInRegionError = 0.
          if not sampleInRegion==None:
            varinRegionList[ireg].setRange(rangeName,varBinLowInRegionList[ireg][ibin],varBinHighInRegionList[ireg][ibin])
            sampleInRegionVal = sampleInRegion.getVal()
            sampleInRegionError = Util.GetPropagatedError(sampleInRegion, resultAfterFit, doAsym)
          else:
            print " \n YieldsTable.py: WARNING: sample =", sampleName, " non-existent (empty) in region=",region, " bin=",ibin, " \n"
          nSampleInRegionVal.append(sampleInRegionVal)
          nSampleInRegionError.append(sampleInRegionError)

        varinRegionList[ireg].setRange(origMin,origMax)

    """
    if showSum=True calculate the total number of fitted events in all regions
    """
    if showSum:
      sampleSumInAllRegions = RooAddition( (sampleName+"_AllRegions_FITTED"), (sampleName+"_AllRegions_FITTED"), RooArgList(sampleInAllRegions))
      nSampleSumVal = sampleSumInAllRegions.getVal()
      nSampleSumError = Util.GetPropagatedError(sampleSumInAllRegions, resultAfterFit, doAsym)
      nSampleInRegionVal.append(nSampleSumVal)
      nSampleInRegionError.append(nSampleSumError)
    tablenumbers['Fitted_events_'+sampleName]   = nSampleInRegionVal
    tablenumbers['Fitted_err_'+sampleName]   = nSampleInRegionError



  print "\n starting BEFORE-FIT calculations \n"
  """
  FROM HERE ON OUT WE CALCULATE THE EXPECTED NUMBER OF EVENTS __BEFORRE__ THE FIT
  """

  """
  load beforeFit workspace snapshot (=set all parameters to values before fit)
  """
  w.loadSnapshot('snapshot_paramsVals_RooExpandedFitResult_beforeFit')

  """
  check if any of the initial scaling factors is != 1
  """
  _result = w.obj('RooExpandedFitResult_beforeFit')
  _muFacs = _result.floatParsFinal()

  for i in range(len(_muFacs)):
    if "mu_" in _muFacs[i].GetName() and _muFacs[i].getVal() != 1.0:
      print  " \n WARNING: scaling factor %s != 1.0 (%g) expected MC yield WILL BE WRONG!" % (_muFacs[i].GetName(), _muFacs[i].getVal())

  """
  get a list of pdf's and variables per region
  """
  pdfinRegionList = [ Util.GetRegionPdf(w, region)  for region in regionList]
  varinRegionList =  [ Util.GetRegionVar(w, region) for region in regionList]

  """
  get a list of RooRealSumPdf per region (RooRealSumPdf is the top-pdf per region containing all samples)
  """
  rrspdfinRegionList = []
  for index,pdf in enumerate(pdfinRegionList):
    prodList = pdf.pdfList()
    foundRRS = 0
    for idx in range(prodList.getSize()):
      if prodList[idx].InheritsFrom("RooRealSumPdf"):
        rrspdfInt =  prodList[idx].createIntegral(RooArgSet(varinRegionList[index]))
        rrspdfinRegionList.append(rrspdfInt)
        if splitBins:
          origMin = varinRegionList[index].getMin()
          origMax = varinRegionList[index].getMax()
          for ibin in range(0,varNbinsInRegionList[index]):
            rangeName = rangeNameBinsInRegionList[index][ibin]
            varinRegionList[index].setRange(rangeName,varBinLowInRegionList[index][ibin],varBinHighInRegionList[index][ibin])
            rrspdfInt =  prodList[idx].createIntegral(RooArgSet(varinRegionList[index]),rangeName)
            rrspdfinRegionList.append(rrspdfInt)
          varinRegionList[index].setRange(origMin,origMax)
        foundRRS += 1
    if foundRRS >1 or foundRRS==0:
      print " \n\n WARNING: ", pdf.GetName(), " has ", foundRRS, " instances of RooRealSumPdf"
      print pdf.GetName(), " component list:", prodList.Print("v")

  """
  calculate total pdf number of expected events and error
  """
  nExpInRegionList =  [ pdf.getVal() for index, pdf in enumerate(rrspdfinRegionList)]
  pdfExpErrInRegionList = [ Util.GetPropagatedError(pdf, resultBeforeFit, doAsym)  for pdf in rrspdfinRegionList]

  """
  if showSum=True calculate the total number of expected events in all regions
  """
  if showSum:
    pdfInAllRegions = RooArgSet()
    for index, pdf in enumerate(rrspdfinRegionList):
      pdfInAllRegions.add(pdf)
    pdfSumInAllRegions = RooAddition( "pdf_AllRegions_BEFORE", "pdf_AllRegions_BEFORE", RooArgList(pdfInAllRegions))
    nPdfSumVal = pdfSumInAllRegions.getVal()
    nPdfSumError = Util.GetPropagatedError(pdfSumInAllRegions, resultBeforeFit, doAsym)
    nExpInRegionList.append(nPdfSumVal)
    pdfExpErrInRegionList.append(nPdfSumError)

  tablenumbers['TOTAL_MC_EXP_BKG_events']    =  nExpInRegionList
  tablenumbers['TOTAL_MC_EXP_BKG_err']    =  pdfExpErrInRegionList

  """
  calculate the fitted number of events and propagated error for each requested sample, by splitting off each sample pdf
  """
  for isam, sample in enumerate(sampleList):
    sampleName=getName(sample)
    nMCSampleInRegionVal = []
    nMCSampleInRegionError = []
    MCSampleInAllRegions = RooArgSet()
    for ireg, region in enumerate(regionList):
      MCSampleInRegion = getPdfInRegions(w,sample,region)
      MCSampleInRegionVal = 0.
      MCSampleInRegionError = 0.
      if not MCSampleInRegion==None:
        MCSampleInRegionVal = MCSampleInRegion.getVal()
        MCSampleInRegionError = Util.GetPropagatedError(MCSampleInRegion, resultBeforeFit, doAsym)
        MCSampleInAllRegions.add(MCSampleInRegion)
      else:
        print " \n WARNING: sample=", sampleName, " non-existent (empty) in region=",region
      nMCSampleInRegionVal.append(MCSampleInRegionVal)
      nMCSampleInRegionError.append(MCSampleInRegionError)

      """
      if splitBins=True calculate numbers of fitted events plus error per bin
      """
      if splitBins:
        origMin = varinRegionList[ireg].getMin()
        origMax = varinRegionList[ireg].getMax()
        for ibin in range(0,varNbinsInRegionList[ireg]):
          rangeName = rangeNameBinsInRegionList[ireg][ibin]
          MCSampleInRegion=getPdfInRegionsWithRangeName(w,sample,region,rangeName)
          MCSampleInRegionVal = 0.
          MCSampleInRegionError = 0.
          if not MCSampleInRegion==None:
            varinRegionList[ireg].setRange(rangeName,varBinLowInRegionList[ireg][ibin],varBinHighInRegionList[ireg][ibin])
            MCSampleInRegionVal = MCSampleInRegion.getVal()
            MCSampleInRegionError = Util.GetPropagatedError(MCSampleInRegion, resultBeforeFit, doAsym)
          else:
            print " \n YieldsTable.py: WARNING: sample =", sampleName, " non-existent (empty) in region=",region, " bin=",ibin, " \n"
          nMCSampleInRegionVal.append(MCSampleInRegionVal)
          nMCSampleInRegionError.append(MCSampleInRegionError)

        varinRegionList[ireg].setRange(origMin,origMax)

    """
    if showSum=True calculate the total number of fitted events in all regions
    """
    if showSum:
      MCSampleSumInAllRegions = RooAddition( (sampleName+"_AllRegions_MC"), (sampleName+"_AllRegions_MC"), RooArgList(MCSampleInAllRegions))
      nMCSampleSumVal = MCSampleSumInAllRegions.getVal()
      nMCSampleSumError = Util.GetPropagatedError(MCSampleSumInAllRegions, resultBeforeFit, doAsym)
      nMCSampleInRegionVal.append(nMCSampleSumVal)
      nMCSampleInRegionError.append(nMCSampleSumError)
    tablenumbers['MC_exp_events_'+sampleName] = nMCSampleInRegionVal
    tablenumbers['MC_exp_err_'+sampleName] = nMCSampleInRegionError

  """
  sort the tablenumbers set
  """
  map_listofkeys = tablenumbers.keys()
  map_listofkeys.sort()

  """
  print the sorted tablenumbers set
  """
  for name in map_listofkeys:
    if tablenumbers.has_key(name) :
      print name, ": ", tablenumbers[name]

  return tablenumbers
コード例 #6
0
def latexfitresults(filename,
                    regionList,
                    sampleList,
                    dataname='obsData',
                    showSum=False):

    w = Util.GetWorkspaceFromFile(filename, 'w')

    if w == None:
        print "ERROR : Cannot open workspace : ", workspacename
        sys.exit(1)

    resultAfterFit = w.obj('RooExpandedFitResult_afterFit')
    if resultAfterFit == None:
        print "ERROR : Cannot open fit result after fit RooExpandedFitResult_afterFit"
        sys.exit(1)

    resultBeforeFit = w.obj('RooExpandedFitResult_beforeFit')
    if resultBeforeFit == None:
        print "ERROR : Cannot open fit result before fit RooExpandedFitResult_beforeFit"
        sys.exit(1)

    data_set = w.data(dataname)
    if data_set == None:
        print "ERROR : Cannot open dataset : ", "data_set" + suffix
        sys.exit(1)

    regionCat = w.obj("channelCat")
    data_set.table(regionCat).Print("v")

    regionFullNameList = [
        Util.GetFullRegionName(regionCat, region) for region in regionList
    ]
    print regionFullNameList

    ###

    snapshot = 'snapshot_paramsVals_RooExpandedFitResult_afterFit'
    w.loadSnapshot(snapshot)

    if not w.loadSnapshot(snapshot):
        print "ERROR : Cannot load snapshot : ", snapshot
        sys.exit(1)

    tablenumbers = {}

    # SUM ALL REGIONS
    sumName = ""
    for index, reg in enumerate(regionList):
        if index == 0:
            sumName = reg
        else:
            sumName = sumName + " + " + reg

    regionListWithSum = list(regionList)
    if showSum:
        regionListWithSum.append(sumName)

    tablenumbers['names'] = regionListWithSum

    regionCatList = [
        'channelCat==channelCat::' + region.Data()
        for region in regionFullNameList
    ]

    regionDatasetList = [
        data_set.reduce(regioncat) for regioncat in regionCatList
    ]
    for index, data in enumerate(regionDatasetList):
        data.SetName("data_" + regionList[index])
        data.SetTitle("data_" + regionList[index])

    nobs_regionList = [data.sumEntries() for data in regionDatasetList]
    #SUM
    sumNobs = 0.
    for nobs in nobs_regionList:
        sumNobs += nobs
        print " \n XXX nobs = ", nobs, "    sumNobs = ", sumNobs
    if showSum:
        nobs_regionList.append(sumNobs)
    tablenumbers['nobs'] = nobs_regionList

    ######
    ######
    ######  FROM HERE ON OUT WE CALCULATE THE FITTED NUMBER OF EVENTS __AFTER__ THE FIT
    ######
    ######

    # total pdf, not splitting in components
    pdfinRegionList = [Util.GetRegionPdf(w, region) for region in regionList]
    varinRegionList = [Util.GetRegionVar(w, region) for region in regionList]
    rrspdfinRegionList = []
    for index, pdf in enumerate(pdfinRegionList):
        #    pdf.Print("t")
        prodList = pdf.pdfList()
        foundRRS = 0
        for idx in range(prodList.getSize()):
            #      if "BG" in prodList[idx].GetName():
            #        prodList[idx].Print("t")
            if prodList[idx].InheritsFrom("RooRealSumPdf"):
                rrspdfInt = prodList[idx].createIntegral(
                    RooArgSet(varinRegionList[index]))
                rrspdfinRegionList.append(rrspdfInt)
                foundRRS += 1
        if foundRRS > 1 or foundRRS == 0:
            print " \n\n WARNING: ", pdf.GetName(
            ), " has ", foundRRS, " instances of RooRealSumPdf"
            print pdf.GetName(), " component list:", prodList.Print("v")

    nFittedInRegionList = [
        pdf.getVal() for index, pdf in enumerate(rrspdfinRegionList)
    ]
    pdfFittedErrInRegionList = [
        Util.GetPropagatedError(pdf, resultAfterFit)
        for pdf in rrspdfinRegionList
    ]

    if showSum:
        pdfInAllRegions = RooArgSet()
        for index, pdf in enumerate(rrspdfinRegionList):
            pdfInAllRegions.add(pdf)
        pdfSumInAllRegions = RooAddition("pdf_AllRegions_AFTER",
                                         "pdf_AllRegions_AFTER",
                                         pdfInAllRegions)
        pdfSumInAllRegions.Print()
        nPdfSumVal = pdfSumInAllRegions.getVal()
        nPdfSumError = Util.GetPropagatedError(pdfSumInAllRegions,
                                               resultAfterFit)
        nFittedInRegionList.append(nPdfSumVal)
        pdfFittedErrInRegionList.append(nPdfSumError)

    tablenumbers['TOTAL_FITTED_bkg_events'] = nFittedInRegionList
    tablenumbers['TOTAL_FITTED_bkg_events_err'] = pdfFittedErrInRegionList

    # components
    for isam, sample in enumerate(sampleList):
        nSampleInRegionVal = []
        nSampleInRegionError = []
        sampleInAllRegions = RooArgSet()
        for ireg, region in enumerate(regionList):
            sampleInRegion = Util.GetComponent(w, sample, region)
            sampleInRegionVal = 0.
            sampleInRegionError = 0.
            if not sampleInRegion == None:
                sampleInRegion.Print()
                sampleInRegionVal = sampleInRegion.getVal()
                sampleInRegionError = Util.GetPropagatedError(
                    sampleInRegion, resultAfterFit)
                sampleInAllRegions.add(sampleInRegion)
            else:
                print " \n YieldsTable.py: WARNING: sample =", sample, " non-existent (empty) in region =", region, "\n"
            nSampleInRegionVal.append(sampleInRegionVal)
            nSampleInRegionError.append(sampleInRegionError)
        # print " \n\n  XXX-AFTER sample = ", sample
        if showSum:
            sampleSumInAllRegions = RooAddition(
                (sample + "_AllRegions_FITTED"),
                (sample + "_AllRegions_FITTED"), sampleInAllRegions)
            sampleSumInAllRegions.Print()
            nSampleSumVal = sampleSumInAllRegions.getVal()
            nSampleSumError = Util.GetPropagatedError(sampleSumInAllRegions,
                                                      resultAfterFit)
            nSampleInRegionVal.append(nSampleSumVal)
            nSampleInRegionError.append(nSampleSumError)
        tablenumbers['Fitted_events_' + sample] = nSampleInRegionVal
        tablenumbers['Fitted_err_' + sample] = nSampleInRegionError

    ######
    ######
    ######  FROM HERE ON OUT WE CALCULATE THE EXPECTED NUMBER OF EVENTS __BEFORE__ THE FIT
    ######
    ######

    #  FROM HERE ON OUT WE CALCULATE THE EXPECTED NUMBER OF EVENTS BEFORE THE FIT
    w.loadSnapshot('snapshot_paramsVals_RooExpandedFitResult_beforeFit')

    pdfinRegionList = [Util.GetRegionPdf(w, region) for region in regionList]
    varinRegionList = [Util.GetRegionVar(w, region) for region in regionList]
    rrspdfinRegionList = []
    for index, pdf in enumerate(pdfinRegionList):
        prodList = pdf.pdfList()
        foundRRS = 0
        for idx in range(prodList.getSize()):
            if prodList[idx].InheritsFrom("RooRealSumPdf"):
                #      print " \n\n  XXX-BEFORE  prodList[idx] = ", prodList[idx].GetName()
                prodList[idx].Print()
                rrspdfInt = prodList[idx].createIntegral(
                    RooArgSet(varinRegionList[index]))
                rrspdfinRegionList.append(rrspdfInt)
                foundRRS += 1
        if foundRRS > 1 or foundRRS == 0:
            print " \n\n WARNING: ", pdf.GetName(
            ), " has ", foundRRS, " instances of RooRealSumPdf"
            print pdf.GetName(), " component list:", prodList.Print("v")

    nExpInRegionList = [
        pdf.getVal() for index, pdf in enumerate(rrspdfinRegionList)
    ]
    pdfExpErrInRegionList = [
        Util.GetPropagatedError(pdf, resultBeforeFit)
        for pdf in rrspdfinRegionList
    ]

    if showSum:
        pdfInAllRegions = RooArgSet()
        for index, pdf in enumerate(rrspdfinRegionList):
            pdfInAllRegions.add(pdf)
        pdfSumInAllRegions = RooAddition("pdf_AllRegions_BEFORE",
                                         "pdf_AllRegions_BEFORE",
                                         pdfInAllRegions)
        nPdfSumVal = pdfSumInAllRegions.getVal()
        nPdfSumError = Util.GetPropagatedError(pdfSumInAllRegions,
                                               resultAfterFit)
        nExpInRegionList.append(nPdfSumVal)
        pdfExpErrInRegionList.append(nPdfSumError)

    tablenumbers['TOTAL_MC_EXP_BKG_events'] = nExpInRegionList
    tablenumbers['TOTAL_MC_EXP_BKG_err'] = pdfExpErrInRegionList

    for isam, sample in enumerate(sampleList):
        nMCSampleInRegionVal = []
        nMCSampleInRegionError = []
        sampleInAllRegions = RooArgSet()
        for ireg, region in enumerate(regionList):
            MCSampleInRegion = Util.GetComponent(w, sample, region)
            MCSampleInRegionVal = 0.
            MCSampleInRegionError = 0.
            if not MCSampleInRegion == None:
                MCSampleInRegionVal = MCSampleInRegion.getVal()
                MCSampleInRegionError = Util.GetPropagatedError(
                    MCSampleInRegion, resultBeforeFit)
                sampleInAllRegions.add(sampleInRegion)
            else:
                print " \n WARNING: sample=", sample, " non-existent (empty) in region=", region
            nMCSampleInRegionVal.append(MCSampleInRegionVal)
            nMCSampleInRegionError.append(MCSampleInRegionError)
        #print " \n\n  XXX-BEFORE  sample = ", sample
        if showSum:
            sampleSumInAllRegions = RooAddition((sample + "_AllRegions_MC"),
                                                (sample + "_AllRegions_MC"),
                                                sampleInAllRegions)
            nSampleSumVal = sampleSumInAllRegions.getVal()
            nSampleSumError = Util.GetPropagatedError(sampleSumInAllRegions,
                                                      resultBeforeFit)
            nMCSampleInRegionVal.append(nSampleSumVal)
            nMCSampleInRegionError.append(nSampleSumError)
        tablenumbers['MC_exp_events_' + sample] = nMCSampleInRegionVal
        tablenumbers['MC_exp_err_' + sample] = nMCSampleInRegionError

        #  sorted(tablenumbers, key=lambda sample: sample[1])   # sort by age
    map_listofkeys = tablenumbers.keys()
    map_listofkeys.sort()

    for name in map_listofkeys:
        if tablenumbers.has_key(name):
            print name, ": ", tablenumbers[name]

    ###
    return tablenumbers