Example #1
0
def makePercentReplacedPlot():
    keylist = ['PAT-genLxy', 'DSA-genLxy']
    HISTS = HG.getAddedSignalHistograms(FILE, fs, keylist)
    for key, h in HISTS.iteritems():
        pass
        #h.Rebin(5)
    g = R.TGraphAsymmErrors(HISTS[keylist[0]], HISTS[keylist[1]], 'cp')
    p = Plotter.Plot(g, '', '', 'p')

    p.setTitles(Y='% replaced selected DSA dimuons', X='gen L_{xy} [cm]')
    #RT.addBinWidth(p)

    canvas = Plotter.Canvas(lumi=fs)
    #canvas = Plotter.Canvas(lumi=fs, logy=True)
    canvas.addMainPlot(p)
    canvas.firstPlot.SetMinimum(0.)
    #canvas.firstPlot.SetMinimum(0.0001)
    canvas.firstPlot.SetMaximum(1.)
    canvas.cleanup('pdfs/percentReplacedVSgenLxy_{}.pdf'.format(fs))
Example #2
0
def fillDistributionParameters(MUON, fs, sp, quantity):

    # get histograms and define plots
    h = HistogramGetter.getHistogram(f, (fs, sp), MUON+'_'+quantity+'_Matched').Clone()

    mean  = h.GetMean()
    sigma = h.GetStdDev()
    overflow = h.GetBinContent(h.GetNbinsX()+1)

    if sp not in DATA[fs]: DATA[fs][sp] = {}
    if MUON not in DATA[fs][sp]: DATA[fs][sp][MUON] = {}
    if quantity not in DATA[fs][sp][MUON]: DATA[fs][sp][MUON][quantity] = {
        'mean':0,
        'sigma':0,
        'overflow':0,
    }

    DATA[fs][sp][MUON][quantity]['mean' ] = mean
    DATA[fs][sp][MUON][quantity]['sigma'] = sigma
    DATA[fs][sp][MUON][quantity]['overflow'] = overflow
Example #3
0
def makeLxyPlot():
    hkeys = ['Lxy_{}'.format(tag) for tag in TAGS]
    HISTS = HG.getAddedSignalHistograms(FILES['Signal'], '2Mu2J', hkeys)

    for key in hkeys:
        HISTS[key].Rebin(10)

    for tag in TAGS:
        zz = 'Lxy_{}'.format(tag)
        print zz, HISTS[zz].Integral(
            HISTS[zz].GetXaxis().FindBin(100.),
            HISTS[zz].GetNbinsX() + 1), HISTS['Lxy_00'].Integral(
                HISTS['Lxy_00'].GetXaxis().FindBin(100.),
                HISTS['Lxy_00'].GetNbinsX() + 1)

    g = {}
    for tag in TAGS:
        #g[tag] = R.TGraphAsymmErrors(HISTS['Lxy_{}'.format(tag)], HISTS['Lxy_00'], 'cp')
        g[tag] = HISTS['Lxy_{}'.format(tag)].Clone()
        g[tag].Divide(HISTS['Lxy_00'])

    #p = {tag:Plotter.Plot(g[tag], TAGS[tag]['leg'], 'lp', 'p') for tag in TAGS}
    p = {
        tag: Plotter.Plot(g[tag], TAGS[tag]['leg'], 'lp', 'hist p')
        for tag in TAGS
    }

    c = Plotter.Canvas()
    for tag in ('00', '05', '10', '15'):
        c.addMainPlot(p[tag])
        p[tag].setColor(TAGS[tag]['col'])

    c.makeLegend(lWidth=0.2, pos='bl')

    c.firstPlot.setTitles(X='', Y='', copy=HISTS[hkeys[0]])
    c.firstPlot.SetMinimum(0.8)
    c.firstPlot.SetMaximum(1.01)

    c.firstPlot.GetXaxis().SetRangeUser(0., 400.)

    c.cleanup('Lxy_deltaR_PD.pdf')
Example #4
0
def makeBinnedResPlotBinwise(MUONS, outputTag, quantity, q2, fs, sp):
    defaultColorOrder = (R.kRed, R.kBlue, R.kGreen, R.kMagenta)
    h = {}
    for MUON in MUONS:
        h[MUON] = HistogramGetter.getHistogram(f, (fs, sp), '{M}_{Q}ResVS{Q2}'.format(M=MUON, Q=quantity, Q2=q2)).Clone()

    # leaving space for the bin number
    fname = 'pdfs/SRR_{}_{}_{}-Binned-Bin-{{}}_{}HTo2XTo{}_{}.pdf'.format(outputTag, quantity+'Res', q2, 'Trig-' if TRIGGER else '', fs, SPStr(sp))

    pretty, binranges, values, colors, colors2, legName = getBinningValues(q2)

    for i, key in enumerate(binranges):
        canvas = Plotter.Canvas(lumi=SPLumiStr(fs, *sp))
        projections, plots = {}, {}
        for j, MUON in enumerate(MUONS):
            projections[MUON] = h[MUON].ProjectionY('_'+str(i)+'_'+str(j), key[0], key[1])
            plots[MUON]       = Plotter.Plot(projections[MUON], MUON, 'l', 'hist')
            RT.addFlows(plots[MUON])
            plots[MUON].Rebin(10)
            if plots[MUON].Integral() != 0:
                plots[MUON].Scale(1./plots[MUON].Integral())
            plots[MUON].SetLineColor(defaultColorOrder[j])

            canvas.addMainPlot(plots[MUON])

        canvas.makeLegend(lWidth=.25, pos='tr')
        canvas.legend.resizeHeight()
        canvas.setMaximum(recompute=True)

        canvas.drawText(legName.format(Q2=pretty, V1=values[key][0], V2=values[key][1]), (canvas.legend.GetX1NDC()+.01, canvas.legend.GetY1NDC()-.04))

        for j, MUON in enumerate(MUONS):
            plots[MUON].SetLineColor(defaultColorOrder[j])
            plots[MUON].setTitles(X=plots[MUON].GetXaxis().GetTitle(), Y='Normalized Counts')
            canvas.drawText('#color[{}]{{'.format(defaultColorOrder[j]) + 'RMS = {:.4f}'.format(plots[MUON].GetStdDev()) + '}',
                (canvas.legend.GetX1NDC()+.01, canvas.legend.GetY1NDC()-(j*0.04)-.08)
            )

        RT.addBinWidth(canvas.firstPlot)
        canvas.cleanup(fname.format(i+1))
def makeIntegratedSEQSignal(hkey='SEQ'):
    HISTS = HG.getAddedSignalHistograms(FILES['2Mu2J'], '2Mu2J', hkey)

    h = HISTS[hkey]
    p = Plotter.Plot(h, '', '', 'hist')

    canvas = Plotter.Canvas(lumi='2Mu2J', cWidth=1600)
    canvas.addMainPlot(p)

    p.SetLineColor(R.kBlue)

    setBinLabels(canvas)

    canvas.firstPlot.setTitles(X='Cut', Y='Normalized Counts')
    canvas.firstPlot.SetMaximum(3.e5 if 'DSA' not in hkey else 1.e5)
    canvas.firstPlot.SetMinimum(0.)

    canvas.scaleMargins(.5, 'L')
    canvas.firstPlot.scaleTitleOffsets(.5, 'Y')
    R.TGaxis.SetExponentOffset(0., 0.02, "y")

    canvas.cleanup('pdfs/NM1_{}{}{}_2Mu2J.pdf'.format(hkey, BUMPSTRING,
                                                      IDPHISTRING))
def makeIntegratedNM1Signal(hkey='NM1'):

    #HISTS, INDIV = HG.getAddedSignalHistograms(FILES['2Mu2J'], '2Mu2J', 'NM1', getIndividuals=True)

    #totalBin1 = sum([INDIV['NM1'][ref].GetBinContent(1) for ref in SIGNALPOINTS])
    #for ibin in range(1, len(CUTS)+2):
    #    totalBin = sum([INDIV['NM1'][ref].GetBinContent(ibin) for ref in SIGNALPOINTS])
    #    scaleFactor = totalBin1/totalBin
    #    for ref in SIGNALPOINTS:
    #        INDIV['NM1'][ref].SetBinContent(ibin, INDIV['NM1'][ref].GetBinContent(ibin)/totalBin*scaleFactor)

    HISTS = HG.getAddedSignalHistograms(FILES['2Mu2J'], '2Mu2J', hkey)
    totalBin1 = HISTS[hkey].GetBinContent(1)
    for ibin in range(1, len(CUTS) + 2):
        totalBin = HISTS[hkey].GetBinContent(ibin)
        scaleFactor = totalBin1 / totalBin
        HISTS[hkey].SetBinContent(ibin, scaleFactor)

    h = HISTS[hkey]
    p = Plotter.Plot(h, '', '', 'hist')

    canvas = Plotter.Canvas(lumi='2Mu2J', cWidth=1600)
    canvas.addMainPlot(p)

    p.SetLineColor(R.kBlue)

    setBinLabels(canvas)

    canvas.firstPlot.setTitles(X='Cut', Y='n#minus1 Eff.')
    canvas.firstPlot.SetMaximum(1.2)
    canvas.firstPlot.SetMinimum(0.)

    canvas.scaleMargins(.5, 'L')
    canvas.firstPlot.scaleTitleOffsets(.5, 'Y')

    canvas.cleanup('pdfs/NM1_{}{}{}_2Mu2J.pdf'.format(hkey, BUMPSTRING,
                                                      IDPHISTRING))
def makeRepEffectPlots(hkey):
    HISTS, PConfig = HG.getBackgroundHistograms(FILES['MC'], hkey)
    HISTS = HISTS[hkey]
    PConfig = PConfig[hkey]

    PLOTS = {}
    for key in HG.BGORDER + ('stack', ):
        PLOTS[key] = Plotter.Plot(HISTS[key], *PConfig[key])

    canvas = Plotter.Canvas(
        lumi='MC Background, {} PAT association (36.3 fb^{{-1}})'.format(
            hkey.replace('LxySig-', '').replace('Lxy-', '')),
        logy=True,
        cWidth=600 if ARGS.SQUARE else 800)

    for key in HG.BGORDER:
        PLOTS[key].setColor(HG.PLOTCONFIG[key]['COLOR'], which='LF')

    canvas.addMainPlot(PLOTS['stack'])

    canvas.firstPlot.setTitles(X='', copy=PLOTS[HG.BGORDER[0]])
    canvas.firstPlot.setTitles(Y='Event Yield')
    canvas.makeLegend(lWidth=.3, pos='tr', autoOrder=False, fontscale=0.8)
    for ref in reversed(HG.BGORDER):
        canvas.addLegendEntry(PLOTS[ref])
    canvas.legend.resizeHeight()
    RT.addBinWidth(canvas.firstPlot)

    canvas.firstPlot.SetMaximum(10.**7.)
    canvas.firstPlot.SetMinimum(10.**0.)

    if ARGS.SQUARE:
        canvas.firstPlot.scaleTitleOffsets(1.1, 'X')

    z = PLOTS['stack'].plot.GetStack().Last()
    print 'MC', hkey, z.Integral(0, z.GetNbinsX() + 1)
    canvas.cleanup('pdfs/REPEFF_MC_{}.pdf'.format(hkey), mode='LUMI')
Example #8
0
def importHistograms(DISTRIBUTION_SPECS):
    """
    Read and add specified histograms from one or many files.

    Extracts histograms from one or many ROOT files (defined via the argument
    'DISTRIBUTION_SPECS') and adds them to the given HistSpecs objects.

    Parameters
    ----------
    DISTRIBUTION_SPECS : HistSpecs object
        An instance of the HistSpecs class, which defines all the relevant histogram
        properties

    """

    # perform some basic sanity checks
    for el in DISTRIBUTION_SPECS:
        filepath = el.getAttribute("filepath")
        histname_identifier = el.getAttribute("histname_identifier")
        histname_exclude = el.getAttribute("histname_exclude")

        types = ((filepath, str), (histname_identifier, str),
                 (histname_exclude, list))
        for o, t in types:
            if not isinstance(o, t):
                raise Exception(
                    "Invalid type of {}: should be {}, but is {}".format(
                        o, t, type(o)))

        if not os.path.exists(filepath):
            raise Exception("No such file: {}".format(filepath))

    # dictionary structure for collecting the relevant distributions
    hists = {}

    cnt_files = 1
    for el in DISTRIBUTION_SPECS:
        filepath = el.getAttribute("filepath")
        histname_identifier = el.getAttribute("histname_identifier")
        histname_exclude = el.getAttribute("histname_exclude")

        print("[{}/{}] Reading file {}...".format(cnt_files,
                                                  len(DISTRIBUTION_SPECS),
                                                  filepath))

        f_allhists = HistogramGetter.getHistograms(filepath)

        histogram = None

        for dataset in f_allhists:
            selected_hists_names = getHistNames(f_allhists,
                                                dataset,
                                                histname_identifier,
                                                exclude=histname_exclude)
            print("hist names: {}".format(selected_hists_names))

            if len(selected_hists_names) > 1:
                raise Exception(
                    "Ambiguous histogram identifier: {} would select the following {} histograms: {}"
                    .format(histname_identifier, len(selected_hists_names),
                            '\n'.join(selected_hists_names)))

            for key in selected_hists_names:
                if histogram is None:
                    histogram = f_allhists[dataset][key].Clone()
                else:
                    histogram.Add(f_allhists[dataset][key])

        if histogram:
            print("\tImported histogram {}".format(histogram.GetName()))
        else:
            print("\tNo histograms found.")

        # prepare the histogram
        RT.addFlows(histogram)

        if el.getAttribute("histogram") is not None:
            print(
                "Warning: Histogram already exists in the HistSpecs object and will be overwritten"
            )

        # add the actual histrogram to the corresponding HistSpecs object
        el.setAttribute("histogram", histogram)

        cnt_files += 1
        del f_allhists
Example #9
0
import DisplacedDimuons.Analysis.HistogramGetter as HG
import DisplacedDimuons.Analysis.AnalysisTools as AT
import numpy as np
from OptimizerTools import SignalInfo, ScaleFactor, calculateFOM, PARSER

ARGS = PARSER.parse_args()
FIGURE_OF_MERIT = ARGS.FOM

PRETTY_LEG = {'ZBi': 'Z_{Bi}', 'ZPL': 'Z_{PL}'}

FILE = R.TFile.Open(
    '../nMinusOne/roots/NM1Distributions_Trig_HTo2XTo2Mu2J.root')
DFILE = R.TFile.Open('../nMinusOne/roots/NM1Distributions_IDPHI_DATA.root')

HISTS = {
    sp: HG.getHistogram(FILE, ('2Mu2J', sp), 'mass')
    for sp in SIGNALPOINTS
}
SCALED = {sp: HISTS[sp].Clone() for sp in SIGNALPOINTS}
for sp in SIGNALPOINTS:
    integral = SCALED[sp].Integral(0, SCALED[sp].GetNbinsX() + 1)
    SCALED[sp].Scale(1. / (integral if integral != 0. else 1.))
CUM = {sp: SCALED[sp].GetCumulative() for sp in SIGNALPOINTS}
DISTS = {
    sp: Plotter.Plot(HISTS[sp], 'm_{{X}} = {} GeV'.format(sp[1]), 'l', 'hist')
    for sp in SIGNALPOINTS
}
PLOTS = {
    sp: Plotter.Plot(CUM[sp], 'm_{{X}} = {} GeV'.format(sp[1]), 'l', 'hist')
    for sp in SIGNALPOINTS
}
def makeKinkFOMPlot(quantity, masses, sigmaBMode='DEFAULT'):
    points = sorted(
        [sp for sp in SignalInfo if sp[0] == masses[0] and sp[1] == masses[1]],
        key=lambda x: x[2])
    s = {
        points[0]:
        HG.getHistogram(FILES['Signal'], (fs, points[0]),
                        '{}_1'.format(quantity)).Clone(),
        points[1]:
        HG.getHistogram(FILES['Signal'], (fs, points[1]),
                        '{}_10'.format(quantity)).Clone(),
    }

    if sigmaBMode == 'DEFAULT':
        s[points[0]].Scale(ScaleFactor(points[0], 1))
        s[points[1]].Scale(ScaleFactor(points[1], 10))
        extra = ''

    elif sigmaBMode == 'SAME':
        s[points[0]].Scale(ScaleFactor(points[0], 1))
        s[points[1]].Scale(ScaleFactor(points[0], 1))
        extra = '_SAME'

    elif sigmaBMode == 'GLOBAL':
        s[points[0]].Scale(ScaleFactor(points[0], 1, 1.e-2))
        s[points[1]].Scale(ScaleFactor(points[1], 1, 1.e-2))
        extra = '_GLOBAL'

    DHists, DPConfig = HG.getDataHistograms(FILES['Data'],
                                            '{}_1'.format(quantity),
                                            addFlows=False)
    b = DHists['{}_1'.format(quantity)]['data']

    # get cumulatives
    bCum = b.GetCumulative(CONFIG[quantity]['forward'])
    sCum = {p: s[p].GetCumulative(CONFIG[quantity]['forward']) for p in points}
    fom = {p: sCum[p].Clone() for p in points}

    nBins = sCum[points[0]].GetNbinsX()
    xAxis = sCum[points[0]].GetXaxis()

    # dictionaries instead of numbers because we have 2 sets of ZBi curves
    fom_max = {p: 0. for p in points}
    opt_cut = {p: 0. for p in points}
    opt_s = {p: 0. for p in points}
    opt_b = {p: 0. for p in points}

    for ibin in range(1, nBins + 1):
        for p in points:
            S, B, cutVal, FOMs = calculateFOM(s[p], b, sCum[p], bCum, nBins,
                                              ibin, xAxis,
                                              CONFIG[quantity]['forward'])
            if FOMs[FIGURE_OF_MERIT] > fom_max[p]:
                fom_max[p] = FOMs[FIGURE_OF_MERIT]
                opt_cut[p] = cutVal
                opt_s[p] = S
                opt_b[p] = B

            fom[p].SetBinContent(ibin, FOMs[FIGURE_OF_MERIT])

    pl = {
        points[0]:
        Plotter.Plot(fom[points[0]],
                     'c#tau = {} mm, nominal'.format(points[0][2]), 'l',
                     'hist p'),
        points[1]:
        Plotter.Plot(fom[points[1]],
                     'c#tau = {} mm, reweighted'.format(points[0][2]), 'l',
                     'hist p'),
    }

    colors = {
        points[0]: R.kBlue,
        points[1]: R.kRed,
    }

    c = Plotter.Canvas(lumi='({} GeV, {} GeV)'.format(*masses))
    c.addMainPlot(pl[points[0]])
    c.addMainPlot(pl[points[1]])

    for p in points:
        pl[p].setColor(colors[p], which='LM')

    c.makeLegend(lWidth=0.3, pos='tr')
    c.legend.SetMargin(0.1)
    c.legend.resizeHeight()

    lines = {
        p: R.TLine(opt_cut[p], 0., opt_cut[p],
                   max(fom_max.values()) * 1.1)
        for p in points
    }
    for p in points:
        lines[p].SetLineStyle(2)
        lines[p].SetLineColor(colors[p])
        lines[p].Draw()

    for i, p in enumerate(points):
        c.drawText(text='#color[{:d}]{{opt = {:.1f}}}'.format(
            colors[p], opt_cut[p]),
                   pos=(c.legend.GetX2(), c.legend.GetY1() - .04 - i * .04),
                   align='br')

    c.firstPlot.SetMinimum(0.)
    c.firstPlot.SetMaximum(max(fom_max.values()) * 1.1)
    c.firstPlot.setTitles(Y=PRETTY_LEG)
    RT.addBinWidth(c.firstPlot)

    c.cleanup('pdfs/KINK_FOM{}_{}_{}_{}_{}.pdf'.format(extra, quantity,
                                                       masses[0], masses[1],
                                                       FIGURE_OF_MERIT))
Example #11
0
def compareFOMPlot(quantity, sp, sigmaBMode='GLOBAL'):
    keys = FACTORS
    for FACTOR in FACTORS:
        s = HG.getHistogram(FILES['Signal'], (fs, sp),
                            '{}_{}'.format(quantity, FACTOR)).Clone()

        if sigmaBMode == 'GLOBAL':
            s.Scale(ScaleFactor(sp, 1, 1.e-2))
            extra = 'GLOBAL'

        DHists, DPConfig = HG.getDataHistograms(FILES['Data'],
                                                '{}_1'.format(quantity),
                                                addFlows=False)
        b = DHists['{}_1'.format(quantity)]['data']

        # get cumulatives
        bCum = b.GetCumulative(CONFIG[quantity]['forward'])
        sCum = s.GetCumulative(CONFIG[quantity]['forward'])
        fom = {z: sCum.Clone() for z in ('ZBi', 'ZPL')}

        nBins = sCum.GetNbinsX()
        xAxis = sCum.GetXaxis()

        # dictionaries instead of numbers because we have 2 sets of ZBi curves
        fom_max = {z: 0. for z in ('ZBi', 'ZPL')}
        opt_cut = {z: 0. for z in ('ZBi', 'ZPL')}
        opt_s = {z: 0. for z in ('ZBi', 'ZPL')}
        opt_b = {z: 0. for z in ('ZBi', 'ZPL')}

        for ibin in range(1, nBins + 1):
            S, B, cutVal, FOMs = calculateFOM(s, b, sCum, bCum, nBins, ibin,
                                              xAxis,
                                              CONFIG[quantity]['forward'])
            for z in ('ZBi', 'ZPL'):
                if FOMs[z] > fom_max[z]:
                    fom_max[z] = FOMs[z]
                    opt_cut[z] = cutVal
                    opt_s[z] = S
                    opt_b[z] = B

                fom[z].SetBinContent(ibin, FOMs[z])

        p = {
            z: Plotter.Plot(fom[z], PRETTY_LEG[z], 'l', 'hist p')
            for z in fom
        }

        colors = {'ZBi': R.kRed, 'ZPL': R.kBlue}

        c = Plotter.Canvas(lumi='({} GeV, {} GeV, {} mm){}'.format(
            sp[0], sp[1], sp[2], '' if FACTOR ==
            1 else ' #rightarrow {} mm'.format(sp[2] / FACTOR)))
        for z in fom:
            c.addMainPlot(p[z])
            p[z].setColor(colors[z], which='LM')

        c.makeLegend(lWidth=0.1, pos='tr')
        #c.legend.SetMargin(0.1)
        c.legend.resizeHeight()

        lines = {
            z: R.TLine(opt_cut[z], 0., opt_cut[z],
                       max(fom_max.values()) * 1.1)
            for z in fom
        }
        for z in fom:
            lines[z].SetLineStyle(2)
            lines[z].SetLineColor(colors[z])
            lines[z].Draw()

        for i, z in enumerate(fom.keys()):
            c.drawText(text='#color[{:d}]{{opt = {:.1f}}}'.format(
                colors[z], opt_cut[z]),
                       pos=(c.legend.GetX2(),
                            c.legend.GetY1() - .04 - i * .04),
                       align='br')

        c.firstPlot.SetMinimum(0.)
        c.firstPlot.SetMaximum(max(fom_max.values()) * 1.1)
        c.firstPlot.setTitles(Y='Figure of Merit')
        RT.addBinWidth(c.firstPlot)

        c.cleanup('pdfs/COMPARE_FOM-{}_{}_{}_{}_{}_{}.pdf'.format(
            extra, quantity, sp[0], sp[1], sp[2], FACTOR))
Example #12
0
keyList = {
    'Prompt': [
        'hLessLxySig',
        'hMoreLxySig',
        'hLessDeltaPhi',
        'hMoreDeltaPhi',
    ],
    'Full': ['LxySig_IDPHI', 'LxySig_DPHI'],
}

DHists = {'Prompt': {}, 'Full': {}}
for which in keyList:
    if which == 'Prompt':
        for key in keyList[which]:
            DHists[which][key] = HG.getHistogram(FILES[which], 'Data',
                                                 key).Clone()
    else:
        D, P = HG.getDataHistograms(FILES[which],
                                    keyList[which],
                                    addFlows=False)
        DHists[which] = {key: D[key]['data'] for key in D}

#### Correction factors from "inverted PAT" CR and SR ####

# these are 0.5 bins

#DHists['Prompt']['hLessLxySig'].GetXaxis().SetRange(1, 12)
#DHists['Prompt']['hMoreLxySig'].GetXaxis().SetRange(1, 12)

# now they're 1 bins
DHists['Prompt']['hLessLxySig'].Rebin(2)
else:
    FILE = R.TFile.Open(ARGS.FILE)
    if not FILE:
        raise Exception('{}: No such file'.format(ARGS.FILE))

MCONLY = ARGS.MCONLY
HKEY = ARGS.HKEY
TOTAL = ARGS.TOTAL

# some constants
BGSAMPLES = ['WJets', 'WW', 'WZ', 'ZZ', 'tW', 'tbarW', 'ttbar', 'QCD20toInf-ME', 'DY10to50', 'DY50toInf']
DATASAMPLES = ['DoubleMuonRun2016{}-07Aug17{}'.format(era, '' if era != 'B' else '-v2') for era in ('B', 'C', 'D', 'E', 'F', 'G', 'H')]

# get the stacked MC
h = {}
MCStack = HistogramGetter.getHistogram(FILE, BGSAMPLES[0], HKEY)
if not MCStack:
    raise Exception('{}: No such MC key'.format(HKEY))
MCStack = MCStack.Clone()
MCStack.Scale(HistogramGetter.PLOTCONFIG[BGSAMPLES[0]]['WEIGHT'])
for SAMPLE in BGSAMPLES:
    h[SAMPLE] = HistogramGetter.getHistogram(FILE, SAMPLE, HKEY).Clone()
    h[SAMPLE].Scale(HistogramGetter.PLOTCONFIG[SAMPLE]['WEIGHT'])
for SAMPLE in BGSAMPLES[1:]:
    MCStack.Add(h[SAMPLE])

# get the added data
if not MCONLY:
    DataStack = HistogramGetter.getHistogram(FILE, DATASAMPLES[0], HKEY)
    if not DataStack:
        raise Exception('{}: No such data key'.format(HKEY))
def makeResPlots(metric, quantity, sp=None):
    PRETTY = {
        'pTRes_hits_less': {
            'mnice': 'p_{T} res.',
            'qnice': 'N(hits)',
            'leg': 'N(hits) #leq 12',
            'col': R.kRed
        },
        'pTRes_hits_more': {
            'mnice': 'p_{T} res.',
            'qnice': 'N(hits)',
            'leg': 'N(hits) > 12',
            'col': R.kBlue
        },
        'pTRes_fpte_less': {
            'mnice': 'p_{T} res.',
            'qnice': '#sigma_{p_{T}}/p_{T}',
            'leg': '#sigma_{p_{T}}/p_{T} < 1',
            'col': R.kBlue
        },
        'pTRes_fpte_more': {
            'mnice': 'p_{T} res.',
            'qnice': '#sigma_{p_{T}}/p_{T}',
            'leg': '#sigma_{p_{T}}/p_{T} #geq 1',
            'col': R.kRed
        },
        'qdiff_hits_less': {
            'mnice': 'charge diff.',
            'qnice': 'N(hits)',
            'leg': 'N(hits) #leq 12',
            'col': R.kRed
        },
        'qdiff_hits_more': {
            'mnice': 'charge diff.',
            'qnice': 'N(hits)',
            'leg': 'N(hits) > 12',
            'col': R.kBlue
        },
        'qdiff_fpte_less': {
            'mnice': 'charge diff.',
            'qnice': '#sigma_{p_{T}}/p_{T}',
            'leg': '#sigma_{p_{T}}/p_{T} < 1',
            'col': R.kBlue
        },
        'qdiff_fpte_more': {
            'mnice': 'charge diff.',
            'qnice': '#sigma_{p_{T}}/p_{T}',
            'leg': '#sigma_{p_{T}}/p_{T} #geq 1',
            'col': R.kRed
        },
    }
    witches = ('less', 'more') if quantity == 'fpte' else ('more', 'less')
    hkeys = ['{}_{}_{}'.format(metric, quantity, which) for which in witches]

    if sp is None:
        HISTS = HG.getAddedSignalHistograms(FILES['Signal'], '2Mu2J', hkeys)
    else:
        HISTS = {}
        for key in hkeys:
            HISTS[key] = HG.getHistogram(FILES['Signal'], ('2Mu2J', sp),
                                         key).Clone()

    PLOTS = {}
    for key in hkeys:
        HISTS[key].Scale(1. /
                         HISTS[key].Integral(0, HISTS[key].GetNbinsX() + 1))
        #RT.addFlows(HISTS[key])
        PLOTS[key] = Plotter.Plot(HISTS[key], PRETTY[key]['leg'], 'l', 'hist')

    #canvas = Plotter.Canvas(lumi='{} by {}'.format(PRETTY[hkeys[0]]['mnice'], PRETTY[hkeys[0]]['qnice']))
    lumi = 'H#rightarrow2X#rightarrow2#mu'
    if sp is None:
        lumi += ', all samples combined'
    else:
        lumi += ' ({} GeV, {} GeV, {} mm)'.format(*sp)
    canvas = Plotter.Canvas(lumi=lumi, cWidth=600 if ARGS.SQUARE else 800)

    for key in hkeys:
        canvas.addMainPlot(PLOTS[key])
        PLOTS[key].setColor(PRETTY[key]['col'], which='L')

    canvas.firstPlot.SetMinimum(0.)
    canvas.setMaximum()
    if metric == 'qdiff':
        canvas.firstPlot.SetMaximum(1.)

    canvas.firstPlot.setTitles(Y='Density')
    if 'qdiff' in hkeys[0]:
        canvas.firstPlot.SetNdivisions(3)

    canvas.makeLegend(lWidth=0.27, pos='tr')
    canvas.legend.resizeHeight()

    RT.addBinWidth(canvas.firstPlot)

    if ARGS.SQUARE:
        canvas.firstPlot.scaleTitleOffsets(1.1, 'X')
        if metric == 'pTRes':
            canvas.firstPlot.scaleTitleOffsets(1.3, 'Y')
    canvas.cleanup('pdfs/QCUTRES_Sig_{}_{}_{}.pdf'.format(
        metric, quantity, 'Global' if sp is None else SPStr(sp)),
                   mode='LUMI')
import ROOT as R
import DisplacedDimuons.Analysis.HistogramGetter as HG
from DisplacedDimuons.Common.Constants import SIGNALPOINTS

# see commit from Mar 5 2019 for the patch required to run studyPTCut.py

f = R.TFile.Open('roots/PTCutPlots_2Mu2J.root')

for sp in SIGNALPOINTS:
    h = HG.getHistogram(f, ('2Mu2J', sp), 'nMatches')
    maxMatched = max(
        [h.GetBinContent(i) for i in xrange(1,
                                            h.GetNbinsX() + 1)])
    ibin = h.GetMaximumBin()

    print '{:4d} {:3d} {:4d} : '.format(*sp),
    print 'the maximum {:5d} occurs @ pT > {:2d}'.format(
        int(maxMatched), int(ibin - 1)),
    if ibin != 11:
        if int(maxMatched - h.GetBinContent(11)) != 0:
            print ', but 10 GeV would only cause a loss of {:2d} events ({:.2%})'.format(
                int(maxMatched - h.GetBinContent(11)),
                1. - (h.GetBinContent(11) / maxMatched))
        else:
            print ' -- but 10 GeV is an equivalently optimal cut'
    else:
        print ' -- this is the optimal cut'
DATA = initializeData()
with open('text/replaceSignal.txt') as f:
    for line in f:
        if '%' in line or '---' in line: continue
        cols = line.strip('\n').split()
        fs = cols[0]
        sp = tuple(map(int, cols[1:4]))
        #DATA[fs][sp]['den'] = int(cols[4])
        #DATA[fs][sp]['num'] = int(cols[5])
        DATA[fs][sp]['repPct'] = float(cols[6])

f = R.TFile.Open('roots/PATMuonStudyPlots_Trig_Combined_BS8_2Mu2J.root')
fs = '2Mu2J'
for sp in SIGNALPOINTS:
    h = HG.getHistogram(f, (fs, sp), 'DSA-LxySig')
    DATA[fs][sp]['DSA-LxySig'] = h.GetMean()
    DATA[fs][sp]['DSA-LxySig-Overflow'] = h.GetBinContent(h.GetNbinsX() + 1)

    h = HG.getHistogram(f, (fs, sp), 'PAT-LxySig')
    DATA[fs][sp]['PAT-LxySig'] = h.GetMean()
    DATA[fs][sp]['PAT-LxySig-Overflow'] = h.GetBinContent(h.GetNbinsX() + 1)

    DATA[fs][sp]['Frac-LxySig-Overflow'] = h.GetBinContent(
        h.GetNbinsX() + 1) / h.Integral(0,
                                        h.GetNbinsX() + 1) * 100.

    h = HG.getHistogram(f, (fs, sp), 'PAT-vtxChi2')
    DATA[fs][sp]['PAT-vtxChi2'] = h.GetMean()
    DATA[fs][sp]['PAT-vtxChi2-Overflow'] = h.GetBinContent(h.GetNbinsX() + 1)
    "pTdiff": (-1.1, 10.0),
    "d0": (0.0, 200),
    "L1pTres": (-1.0, 8.0),
    "L2pTres": (-1.0, 8.0),
    "dimVtxChi2": (0.0, 60.0),
    "dimLxySig": (0.0, 230.0),
    "chi2": (0.0, 30.0),
    "pTSig": (0.0, 2.0),
    "nStations": (0.0, 10.0),
    "nCSCDTHits": (10.0, 60.0),
    "chargeprod": (-1.0, 2.0),
    "charge": (-1.0, 2.0),
}

HISTS = HistogramGetter.getHistograms(
    "/afs/cern.ch/work/s/stempl/private/DDM/cosmics-studies/simulation-validation/Cosmics2016_UGMT-bottomOnly_HLT-ppSeed.root"
)


def makePerSamplePlots(selection=None):
    rebinning_exceptions = ("pTdiff", "nCSCDTHits")

    h = {}
    p = {}
    for dataset in HISTS:
        if selection is not None:
            selected_hists_names = getHistNames(dataset, *selection)
        else:
            selected_hists_names = HISTS[dataset]

        for key in selected_hists_names:
PP.PARSER.add_argument('--thesis', dest='THESIS', action='store_true')
ARGS = PP.PARSER.parse_args()

##################################
#### Get histograms and scale ####
##################################

FILES = {
    'DataNom' : R.TFile.Open('roots/MyDataPileupHistogram.root'),
    'DataLow' : R.TFile.Open('roots/MyDataPileupHistogram_Low.root'),
    'DataHigh': R.TFile.Open('roots/MyDataPileupHistogram_High.root'),
    'Signal'  : R.TFile.Open('roots/pileup_HTo2XTo2Mu2J.root'),
}

HISTS, INDIV = HG.getAddedSignalHistograms(FILES['Signal'], '2Mu2J', 'pileup', True)
HISTS, INDIV = HISTS['pileup'], INDIV['pileup']

KEYS = ('Nom', 'Low', 'High')

DATA = {key:FILES['Data'+key].Get('pileup').Clone() for key in KEYS}

for key in DATA:
    DATA[key].Scale(1./DATA[key].Integral())

for sp in INDIV:
    INDIV[sp].Scale(1./INDIV[sp].Integral())

HISTS.Scale(1./HISTS.Integral())

# saves the weight for a printing pass afterwards
Example #19
0
import ROOT as R
import DisplacedDimuons.Analysis.HistogramGetter as HG
import DisplacedDimuons.Analysis.Plotter as Plotter

FILES = {'_PATOnly':0, '_NoRep':0, '':0}
HISTS = {}
for key in FILES:
    FILES[key] = R.TFile.Open('roots/ZephyrPlots_Trig_Combined_BS9{}_2Mu2J.root'.format(key))
    HISTS[key] = HG.getAddedSignalHistograms(FILES[key], '2Mu2J', ('GEN-Lxy', 'GEN-Lxy-PAT', 'GEN-Lxy-HYB', 'GEN-Lxy-DSA'))

# relative signal match eff
h = {}
h['PAT'] = HISTS['_PATOnly']['GEN-Lxy'].Clone()
h['HYB'] = HISTS[''        ]['GEN-Lxy'].Clone()
h['DSA'] = HISTS['_NoRep'  ]['GEN-Lxy'].Clone()
for key in h:
    h[key].Rebin(5)

h['PAT'].Divide(h['DSA'])
h['HYB'].Divide(h['DSA'])

h.pop('DSA')

p = {}
config = {'PAT' : ('DSA-DSA or PAT-PAT only', R.kRed), 'HYB' : ('DSA-DSA, PAT-PAT, or DSA-PAT', R.kBlue)}
for key in h:
    p[key] = Plotter.Plot(h[key], config[key][0], 'lp', 'p')

canvas = Plotter.Canvas(lumi='2Mu2J')
for key in ('PAT', 'HYB'):
    canvas.addMainPlot(p[key])
def makeSignalPlot(key):
    h = HG.getAddedSignalHistograms(FILES['2Mu2J'], '2Mu2J', key)
    h = h[key]

    p = Plotter.Plot(h, '', '', 'hist')

    RT.addBinWidth(p)

    c = Plotter.Canvas(lumi='H#rightarrow2X#rightarrow2#mu, {}'.format(
        CUTS[key]['lumi']),
                       cWidth=600 if key != 'deltaPhi' else 800,
                       logy=CUTS[key]['logy'])
    c.addMainPlot(p)
    c.firstPlot.setColor(R.kBlue)
    c.firstPlot.scaleTitleOffsets(1.1, 'Y')

    if key == 'deltaPhi':
        axis = c.firstPlot.GetXaxis()
        labeldict = {
            1: '0',
            25: '#pi/4',
            50: '#pi/2',
            75: '3#pi/4',
            100: '#pi'
        }
        for i in xrange(1, 101):
            val = labeldict.get(i)
            if val is None: val = ''
            axis.SetBinLabel(i, val)
        axis.SetNdivisions(216, False)
        axis.SetLabelSize(.06)
        axis.SetTickLength(0.03)
        axis.SetTickSize(0.03)
        axis.LabelsOption('h')

        c.mainPad.Update()
        ymin = c.mainPad.GetUymin()
        ymax = c.mainPad.GetUymax()
        if c.logy:
            ymax = 10.**ymax

        xB = R.TGaxis(0., ymin,
                      R.TMath.Pi() - .07, ymin, 0., R.TMath.Pi(), 216, "+B",
                      .03)
        xB.SetLabelSize(0)
        xB.Draw('same')

        xT = R.TGaxis(0., ymax,
                      R.TMath.Pi() - .07, ymax, 0., R.TMath.Pi(), 216, "-B",
                      .03)
        xT.SetLabelSize(0)
        xT.Draw('same')

    if key == 'pT':
        c.firstPlot.GetXaxis().SetRangeUser(0., 600.)

    eff = getEff(p, key)
    c.drawText('{:.1%} efficient'.format(eff),
               align='tr',
               pos=(1. - c.margins['r'] - .03, 1. - c.margins['t'] - .03))

    c.mainPad.Update()
    ymax = c.mainPad.GetUymax()
    line = R.TLine(CUTS[key]['val'], 0., CUTS[key]['val'],
                   ymax if not c.logy else 10.**ymax)
    line.SetLineStyle(2)
    line.Draw()

    if key == 'trkChi2': c.firstPlot.GetXaxis().SetTitle('trk. #chi^{2}/dof')

    c.cleanup('pdfs/NM1_2Mu2J_{}.pdf'.format(key), mode='LUMI')
Example #21
0
#fOld = R.TFile.Open('roots/ZephyrPlots_Trig_Combined_NS_NH_FPTE_HLT_REP_PQ1_PT_PC_LXYE_MASS_CHI2_DSAPROXMATCH_HTo2XTo2Mu2J.root')
#fNew = R.TFile.Open('roots/ZephyrPlots_Trig_Combined_NS_NH_FPTE_HLT_REP_PQ1_PT_PC_LXYE_MASS_CHI2_DPT_HTo2XTo2Mu2J.root')

fOld = R.TFile.Open(
    'roots/ZephyrPlots_Trig_Combined_NS_NH_FPTE_HLT_REP_PT_PC_LXYE_MASS_CHI2_VTX_COSA_SFPTE_HTo2XTo2Mu2J.root'
)
fNew = R.TFile.Open(
    'roots/ZephyrPlots_Trig_Combined_NS_NH_FPTE_HLT_REP_PT_PC_LXYE_MASS_CHI2_VTX_COSA_SFPTE_PROXTHRESH_HTo2XTo2Mu2J.root'
)


def deleteHistogram(HIST):
    R.gROOT.ProcessLine('delete gROOT->FindObject("' + HIST.GetName() + '")')


hOld = HG.getAddedSignalHistograms(fOld, '2Mu2J', 'GEN-Lxy-DSA')
g = hOld['GEN-Lxy-DSA'].Clone()
g.SetName('new')
deleteHistogram(hOld['GEN-Lxy-DSA'])

HybOld = HG.getAddedSignalHistograms(fOld, '2Mu2J', 'GEN-Lxy-HYB')
g.Add(HybOld['GEN-Lxy-HYB'])
deleteHistogram(HybOld['GEN-Lxy-HYB'])

hNew = HG.getAddedSignalHistograms(fNew, '2Mu2J', 'GEN-Lxy-DSA')
h = hNew['GEN-Lxy-DSA'].Clone()
h.SetName('old')
deleteHistogram(hNew['GEN-Lxy-DSA'])

HybNew = HG.getAddedSignalHistograms(fNew, '2Mu2J', 'GEN-Lxy-HYB')
h.Add(HybNew['GEN-Lxy-HYB'])
Example #22
0
PARSER.add_argument('--quantity' , dest='QUANTITY' , default='vtxChi2')
PARSER.add_argument('--cutstring', dest='CUTSTRING', default='Combined_NS_NH_FPTE_HLT_REP_PQ1_PT_PC_LXYE_MASS')
PARSER.add_argument('--cut'      , dest='CUT'      , default=50., type=float)
PARSER.add_argument('--rtypes'   , dest='RTYPES'   , default='DPH')
ARGS = PARSER.parse_args()

f = R.TFile.Open('roots/ZephyrPlots_Trig_{}_HTo2XTo2Mu2J.root'.format(ARGS.CUTSTRING))

RTYPES = []
if 'D' in ARGS.RTYPES: RTYPES.append('DSA')
if 'P' in ARGS.RTYPES: RTYPES.append('PAT')
if 'H' in ARGS.RTYPES: RTYPES.append('HYB')

print '{:4s} {:3s} {:4s} {:>10s} {:>6s} {:>6s} {:>6s}'.format('mH', 'mX', 'cTau', 'Mean', 'OFlow', 'OFlow%', '%>{}'.format(ARGS.CUT))
for sp in SIGNALPOINTS:
    for i, key in enumerate(RTYPES):
        if i == 0:
            h = HG.getHistogram(f, ('2Mu2J', sp), key+'-'+ARGS.QUANTITY)
        else:
            h.Add(HG.getHistogram(f, ('2Mu2J', sp), key+'-'+ARGS.QUANTITY))
    c = h.GetCumulative()
    ibin = c.FindBin(float(ARGS.CUT))
    print '{:4d} {:3d} {:4d} {:10.2f} {:6.0f} {:6.2f} {:6.2f}'.format(
        sp[0], sp[1], sp[2],
        h.GetMean(),
        h.GetBinContent(h.GetNbinsX()+1),
        h.GetBinContent(h.GetNbinsX()+1)/h.Integral(0, h.GetNbinsX()+1)*100.,
        100.-c.GetBinContent(ibin)      /h.Integral(0, h.GetNbinsX()+1)*100.
    )

Example #23
0
def makeOverlaidResPlot(MUONS, fs, sp, quantity, outputTag=None):
    # whether the plot is dif or res makes a difference wrt binning, fit range, and stats box positions
    # only pT is a res type; the others are all dif types
    ISDIF = quantity != 'pT'

    # what to name the plot. if MUONS is length 1, no sense to pass it twice, so get it automatically
    if outputTag is None:
        outputTag = MUONS[0]

    # colors, in order of MUONS, and also hashed
    defaultColorOrder = (R.kBlue, R.kRed, R.kGreen)
    colorDict = dict(zip(MUONS, defaultColorOrder))

    # get histograms and define plots
    h = {}
    for MUON in MUONS:
        h[MUON] = HistogramGetter.getHistogram(f, (fs, sp), MUON+'_'+quantity+'Res').Clone()
    p = {}
    for MUON in MUONS:
        RT.addFlows(h[MUON])
        if not ISDIF:
            h[MUON].Rebin(5)
        else:
            h[MUON].Rebin(10)
        p[MUON] = Plotter.Plot(h[MUON], 'Signal MC ({})'.format(MUON[:3]), 'l', 'hist')

    # define and fit gaussians to everything. Set FITRANGE to be something useful.
    funcs = {}
    fplots = {}
    for MUON in MUONS:
        if quantity == 'pT':
            FITRANGE = (-0.4, 0.3)
        elif quantity == 'eta':
            FITRANGE = (-0.1, 0.1)
        else:
            FITRANGE = (-20., 20.)
        funcs[MUON] = R.TF1('f'+MUON, 'gaus', *FITRANGE)
        h[MUON].Fit('f'+MUON, 'R')
        fplots[MUON] = Plotter.Plot(funcs[MUON], 'Gaussian fit ({})'.format(MUON[:3]), 'l', '')

    # define canvas, add plots. addS is so that statsbox will be drawn later.
    # these all should be pretty obvious until...
    canvas = Plotter.Canvas(lumi=SPLumiStr(fs, *sp))
    for i, MUON in enumerate(MUONS):
        canvas.addMainPlot(p[MUON], addS=True if i!=0 else False)
        canvas.addMainPlot(fplots[MUON])

    if len(MUONS) > 1:
        canvas.firstPlot.setTitles(X=canvas.firstPlot.GetXaxis().GetTitle().replace(MUONS[0],'Reco'))

    canvas.makeLegend(lWidth=.25, pos='tl')
    canvas.legend.resizeHeight()

    for MUON in MUONS:
        p     [MUON].SetLineColor(colorDict[MUON]  )
        fplots[MUON].SetLineColor(colorDict[MUON]+1)

    RT.addBinWidth(canvas.firstPlot)

    # dif type: fit boxes go down the left side
    # res type: fit boxes go down the middle
    # stats boxes are on the right
    paves = []
    for i, MUON in enumerate(MUONS):
        paves.append(canvas.makeStatsBox(p[MUON], color=colorDict[MUON]))
        Plotter.MOVE_OBJECT(paves[-1], Y=-.2*i)

        if not ISDIF:
            canvas.setFitBoxStyle(h[MUON], lWidth=0.275, pos='tr')
        else:
            canvas.setFitBoxStyle(h[MUON], lWidth=0.275, pos='tl')

        sbox = p[MUON].FindObject('stats')
        sbox.SetTextColor(colorDict[MUON]+1)

        if not ISDIF:
            Plotter.MOVE_OBJECT(sbox, Y=-.15*i, X=-.18, NDC=True)
        else:
            Plotter.MOVE_OBJECT(sbox, Y=-.15*i-0.04*4.1, NDC=True)

    fname = 'pdfs/SRR_{}_{}_{}HTo2XTo{}_{}.pdf'.format(outputTag, quantity+'Res', 'Trig-' if TRIGGER else '', fs, SPStr(sp))
    canvas.cleanup(fname)
Example #24
0
def optimizeCut(fs, sp, quantity):
    # get histograms
    s = HG.getHistogram(FILES['Signal'], (fs, sp), quantity)
    DHists, DPConfig = HG.getDataHistograms(FILES['Data'], quantity)
    b = DHists[quantity]['data']

    n = s.Integral(0, s.GetNbinsX()+1)
    s.Scale(ScaleFactor(sp, sigmaB=1.e-2))

    # get cumulatives
    sCum = s.GetCumulative(CONFIG[quantity]['forward'])
    bCum = b.GetCumulative(CONFIG[quantity]['forward'])
    fom  = sCum.Clone()

    print '**** Data (|DeltaPhi| > Pi/2) vs. HTo2XTo{} ({} GeV, {} GeV, {} mm) (|DeltaPhi| < Pi/2)'.format(fs, *sp)
    print '**** Quantity = {:s} ::: Passing (N-1) = {:.0f} ::: N_gen = {:.0f} ::: Sigma*B = {:.3f} pb ::: 2016 ILumi = 35922 /pb'.format(
            CONFIG[quantity]['pretty'], n, SignalInfo[sp]['sumWeights'][1], SignalInfo[sp]['sigmaBLimit'])
    print '{:>8s} {:>7s} {:>7s} {:>7s} {:>6s} {:>6s}'.format('CutVal', 'S', 'B=nOff', 'S+B=nOn', 'ZBi', 'ZPL')

    # fill f.o.m. histogram, and keep track of max f.o.m. and cut value
    nBins = sCum.GetNbinsX()
    xAxis = sCum.GetXaxis()

    fom_max = 0.
    opt_cut = 0.
    opt_s   = 0.
    opt_b   = 0.

    for ibin in range(1,nBins+1):
        S, B, cutVal, FOMs = calculateFOM(s, b, sCum, bCum, nBins, ibin, xAxis, CONFIG[quantity]['forward'])
        print '{:8.3f} {:7.3f} {:7.3f} {:7.3f} {:6.3f} {:6.3f}'.format(cutVal, S, B, S+B, FOMs['ZBi'], FOMs['ZPL'])

        if FOMs[FIGURE_OF_MERIT] > fom_max:
            fom_max = FOMs[FIGURE_OF_MERIT]
            opt_cut = cutVal
            opt_s   = S
            opt_b   = B

        fom.SetBinContent(ibin, FOMs[FIGURE_OF_MERIT])

    # make plots
    p = {}
    p['sig'] = Plotter.Plot(sCum, 'signal'   , 'l', 'hist')
    p['bg' ] = Plotter.Plot(bCum, 'data'     , 'l', 'hist')
    p['fom'] = Plotter.Plot(fom , PRETTY_LEG , 'l', 'hist')

    # make canvas, colors, maximum
    canvas = Plotter.Canvas(lumi=SPLumiStr(fs, *sp))
    canvas.addMainPlot(p['sig'])
    canvas.addMainPlot(p['bg' ])
    canvas.addMainPlot(p['fom'])

    p['sig'].SetLineColor(R.kBlue )
    p['bg' ].SetLineColor(R.kRed  )
    p['fom'].SetLineColor(R.kGreen)

    canvas.setMaximum()
    canvas.firstPlot.SetMinimum(0.)

    # scale f.o.m. and make new axis
    fom.Scale(canvas.firstPlot.GetMaximum()/fom_max/1.05)
    axis = R.TGaxis(xAxis.GetXmax(), 0., xAxis.GetXmax(), canvas.firstPlot.GetMaximum(), 0., fom_max*1.05, 510, '+L')
    for attr in ('LabelFont', 'LabelOffset', 'TitleFont', 'TitleOffset', 'TitleSize'):
        getattr(axis, 'Set'+attr)(getattr(xAxis, 'Get'+attr)())
    axis.SetTitle('Figure of Merit')
    axis.CenterTitle()
    axis.Draw()
    canvas.scaleMargins(1.1, edges='R')

    # make the legend after
    canvas.makeLegend(lWidth=.2, pos='br')
    canvas.legend.resizeHeight()
    canvas.legend.moveLegend(X=-.2, Y=.1)

    # draw optimum text and line
    x, y = canvas.legend.GetX1(), canvas.legend.GetY2()
    canvas.drawText(text='#color[{:d}]{{opt. cut = {:.2f}}}'.format(R.kBlack, opt_cut), pos=(x, y+0.05), align='bl')

    line = R.TLine(opt_cut, 0., opt_cut, canvas.firstPlot.GetMaximum())
    line.SetLineStyle(2)
    line.Draw()

    # save
    canvas.cleanup('pdfs/OPT_{}_{}_HTo2XTo{}_{}.pdf'.format(quantity, FIGURE_OF_MERIT, fs, SPStr(sp)))
import re
import ROOT as R
import DisplacedDimuons.Analysis.Plotter as Plotter
import DisplacedDimuons.Analysis.RootTools as RT
from DisplacedDimuons.Common.Utilities import SPStr, SPLumiStr
import DisplacedDimuons.Analysis.HistogramGetter as HistogramGetter
import DisplacedDimuons.Analysis.PlotterParser as PlotterParser

ARGS = PlotterParser.PARSER.parse_args()

TRIGGER = ARGS.TRIGGER
CUTSTRING = ARGS.CUTSTRING
MCONLY = ARGS.MCONLY

# get histograms
HISTS = HistogramGetter.getHistograms(
    '../analyzers/roots/Main/RecoMuonPlots.root')
f = R.TFile.Open('../analyzers/roots/Main/RecoMuonPlots.root')


# make plots that are per sample
def makePerSamplePlots():
    for ref in HISTS:
        if not type(ref) == tuple: continue
        for key in HISTS[ref]:
            if 'deltaRGR' in key: continue
            if 'VS' in key: continue
            if type(ref) == tuple:
                if ref[0] == '4Mu':
                    name = 'HTo2XTo4Mu_'
                    latexFS = '4#mu'
                elif ref[0] == '2Mu2J':
def makeKinkDistPlot(quantity, masses):
    points = sorted(
        [sp for sp in SignalInfo if sp[0] == masses[0] and sp[1] == masses[1]],
        key=lambda x: x[2])
    s = {
        points[0]:
        HG.getHistogram(FILES['Signal'], (fs, points[0]),
                        '{}_1'.format(quantity)).Clone(),
        points[1]:
        HG.getHistogram(FILES['Signal'], (fs, points[1]),
                        '{}_10'.format(quantity)).Clone(),
    }

    s[points[0]].Scale(1. /
                       s[points[0]].Integral(0, s[points[0]].GetNbinsX() + 1))
    s[points[1]].Scale(1. /
                       s[points[1]].Integral(0, s[points[1]].GetNbinsX() + 1))

    #RT.addFlows(s[points[0]])
    #RT.addFlows(s[points[1]])

    s[points[0]].Rebin(2)
    s[points[1]].Rebin(2)

    pl = {
        points[0]:
        Plotter.Plot(s[points[0]],
                     'c#tau = {} mm, nominal'.format(points[0][2]), 'l',
                     'hist'),
        points[1]:
        Plotter.Plot(s[points[1]],
                     'c#tau = {} mm, reweighted'.format(points[0][2]), 'l',
                     'hist'),
    }

    colors = {
        points[0]: R.kBlue,
        points[1]: R.kRed,
    }

    c = Plotter.Canvas(lumi='({} GeV, {} GeV)'.format(*masses))
    c.addMainPlot(pl[points[0]])
    c.addMainPlot(pl[points[1]])

    for p in points:
        pl[p].setColor(colors[p], which='LM')

    c.makeLegend(lWidth=0.3, pos='tr')
    c.legend.SetMargin(0.1)
    c.legend.resizeHeight()

    c.drawText(text='lol',
               pos=(c.legend.GetX1(), c.legend.GetY1() + .4),
               NDC=False)

    c.setMaximum()
    RT.addBinWidth(c.firstPlot)

    c.cleanup('pdfs/KINK_Dist_{}_{}_{}_{}.pdf'.format(quantity, masses[0],
                                                      masses[1],
                                                      FIGURE_OF_MERIT))
Example #27
0
    (125, 20, 1300): (R.kGreen + 0, 10),
}

for SPLIT, DO2MU, DO4MU in OPTIONS:
    for quantity, isGreater, RESIZE in CONFIG:
        LOGY = quantity in ('DSA_d0Sig', 'REF_d0Sig', 'LxySig')
        if RESIZE:
            LOGY = False
        if TAG == 'Dimuon':
            qkeyname = 'Dim_{}'.format(quantity)
        elif TAG == 'RecoMuon':
            qkeyname = quantity

        h = {}

        h['MC'] = HG.getHistogram(FILES['MC_Prompt'], BGORDER[0], qkeyname)

        for key in BGORDER:
            for fkey in ('MC_Prompt', 'MC_NoPrompt'):
                if key == BGORDER[0] and fkey == 'MC_Prompt':
                    h['MC'].Scale(PC[key]['WEIGHT'])
                else:
                    hTemp = HG.getHistogram(FILES[fkey], key, qkeyname)
                    hTemp.Scale(PC[key]['WEIGHT'])
                    h['MC'].Add(hTemp)

        if not SPLIT:
            h['2Mu'] = HG.getHistogram(FILES['Signal_Prompt'],
                                       ('2Mu2J', SPLIST[0]), qkeyname)
            h['4Mu'] = HG.getHistogram(FILES['Signal_Prompt'],
                                       ('4Mu', SPLIST[0]), qkeyname)
Example #28
0
import ROOT as R
import DisplacedDimuons.Analysis.HistogramGetter as HG
import DisplacedDimuons.Analysis.Plotter as Plotter

# the input histogram here is just two histograms with LxySig < 6 and DeltaPhi < pi/4 and > 3pi/4 separately
# the script to make it is validateBackground which is in oldscripts now
# this script makes a little less sense now, also it is superseded by smallLxySigConsistency,
# but I'm leaving it here in case you want to see how to to the KS probability

f = R.TFile.Open('roots/ValidationPlots_DATA.root')

D, P = HG.getDataHistograms(f, ('LxySig_DPHI', 'LxySig_IDPHI'), addFlows=False)

h = {k: D[k]['data'] for k in D}

c = {k: h[k].GetCumulative(False) for k in h}

cumRatio = c['LxySig_IDPHI'].Clone()
cumRatio.Divide(c['LxySig_DPHI'])

for k in h:
    h[k].Rebin(5)

distRatio = h['LxySig_IDPHI'].Clone()
distRatio.Divide(h['LxySig_DPHI'])

pDist = {
    k: Plotter.Plot(h[k],
                    '#Delta#Phi {} #pi/2'.format('<' if '_DPHI' in k else '>'),
                    'lp', 'hist e')
    for k in h
import re
import ROOT as R
import DisplacedDimuons.Analysis.Plotter as Plotter
import DisplacedDimuons.Analysis.RootTools as RT
import DisplacedDimuons.Analysis.Selections as Selections
from DisplacedDimuons.Common.Utilities import SPStr, SPLumiStr
import DisplacedDimuons.Analysis.HistogramGetter as HistogramGetter

TRIGGER = False

# get histograms
HISTS = HistogramGetter.getHistograms(
    '../analyzers/roots/Main/nMinusOnePlots.root')
f = R.TFile.Open('../analyzers/roots/Main/nMinusOnePlots.root')


# make per sample plots
def makePerSamplePlots():
    for ref in HISTS:
        for key in HISTS[ref]:
            if type(ref) == tuple:
                if ref[0] == '4Mu': name = 'HTo2XTo4Mu_'
                elif ref[0] == '2Mu2J': name = 'HTo2XTo2Mu2J_'
                name += SPStr(ref[1])
                if TRIGGER:
                    name = 'Trig-' + name
                lumi = SPLumiStr(ref[0], *ref[1])
                legName = HistogramGetter.PLOTCONFIG['HTo2XTo' +
                                                     ref[0]]['LATEX']
            else:
                name = ref
Example #30
0
import re
import ROOT as R
import DisplacedDimuons.Analysis.Plotter as Plotter
import DisplacedDimuons.Analysis.RootTools as RT
from DisplacedDimuons.Common.Constants import SIGNALPOINTS
from DisplacedDimuons.Common.Utilities import SPStr, SPLumiStr
import DisplacedDimuons.Analysis.HistogramGetter as HistogramGetter
import DisplacedDimuons.Analysis.PlotterParser as PlotterParser

ARGS = PlotterParser.PARSER.parse_args()

TRIGGER = ARGS.TRIGGER
CUTSTRING = ARGS.CUTSTRING

# get histograms
HISTS = HistogramGetter.getHistograms(
    '../analyzers/roots/Main/SignalVertexFitEffPlots.root')
f = R.TFile.Open('../analyzers/roots/Main/SignalVertexFitEffPlots.root')


# make overlaid plots that combine all signal points
def makeEffPlots(quantity, fs, SP=None):
    HKeys = {
        'Eff': '{}Eff',
        'Den': '{}Den',
    }
    for key in HKeys:
        HKeys[key] = HKeys[key].format(quantity)

    h = {}
    p = {}
    g = {}