Example #1
0
else:
    histFile = TFile.Open(os.path.join(histDir, 'initialHists.root'))

    hDataTarg = histFile.Get('FitSinglePhoton')
    hDataBkgNom = histFile.Get('TempBkgdSinglePhoton')
    hDataBkgNear = histFile.Get('TempBkgdSinglePhotonNear')
    hDataBkgFar = histFile.Get('TempBkgdSinglePhotonFar')
    hMCSignalRaw = histFile.Get('TempSignalGJets_raw')
    hMCSBNomRaw = histFile.Get('TempSidebandGJets_raw')
    hMCSignal = histFile.Get('TempSignalGJets')
    hMCSBNom = histFile.Get('TempSidebandGJets')
    hMCSBNear = histFile.Get('TempSidebandGJetsNear')
    hMCSBFar = histFile.Get('TempSidebandGJetsFar')

### plot "estimated" contamination in the sidebands
scanvas = SimpleCanvas(lumi = s.sphLumi)
def plotSigContam(hdata, hmc, name = '', pdir = plotDir):
    scanvas.Clear(full = True)
    scanvas.titlePave.SetX2NDC(0.5)
    scanvas.legend.setPosition(0.7, 0.7, 0.9, 0.9)
    scanvas.legend.add('obs', title = 'Data sideband', opt = 'LP', color = ROOT.kBlack, mstyle = 8)
    scanvas.legend.add('sig', title = '#gamma+jets MC', opt = 'L', lcolor = ROOT.kRed, lwidth = 2, lstyle = ROOT.kDashed)

    scanvas.legend.apply('obs', hdata)
    scanvas.legend.apply('sig', hmc)
    
    hdata.SetTitle('')

    scanvas.addHistogram(hdata, drawOpt = 'EP')
    scanvas.addHistogram(hmc, drawOpt = 'HIST')
Example #2
0
    canvas.addObs(dmet, title = 'Data')

    canvas.xtitle = canvas.obsHistogram().GetXaxis().GetTitle()
    canvas.ytitle = canvas.obsHistogram().GetYaxis().GetTitle()

    canvas.Update(logy = True)

    canvas.printWeb('monophoton/gjetsTFactor', 'distributions'+region)

###########################################
####### Transfer Factors ##################
###########################################

methods = [ ('Data', gmets), ('MC', mcmets) ]
scanvas = SimpleCanvas(lumi = lumi)

tfacts = []

for method, hists in methods:
    tname = 'tfact'+method
    tfact = hists[1].Clone(tname)
    tfact.Divide(hists[0])

    tfact.GetYaxis().SetTitle("")

    tfact.SetMarkerStyle(8)
    tfact.SetMarkerSize(0.8)

    outputFile.cd()
    tfact.Write()
Example #3
0
rawPx = 'probes.scRawPt * TMath::Cos(probes.phi)'
rawPy = 'probes.scRawPt * TMath::Sin(probes.phi)'
rawPz = 'TMath::SinH(probes.eta) * probes.scRawPt'
rawE = 'TMath::CosH(probes.eta) * probes.scRawPt'

rawMass = 'TMath::Sqrt(TMath::Power(' + rawE + ' + tags.pt * TMath::CosH(tags.eta), 2.)'
rawMass += ' - TMath::Power(' + rawPx + ' + tags.pt * TMath::Cos(tags.phi), 2.)'
rawMass += ' - TMath::Power(' + rawPy + ' + tags.pt * TMath::Sin(tags.phi), 2.)'
rawMass += ' - TMath::Power(' + rawPz + ' + tags.pt * TMath::SinH(tags.eta), 2.))'

dataCorr = ROOT.TH1D('dataCorr', '', 60, 60., 120.)
dataRaw = ROOT.TH1D('dataRaw', '', 60, 60., 120.)
dataChain.Draw('tp.mass>>dataCorr', 'probes.pt > 100.', 'goff')
dataChain.Draw(rawMass + '>>dataRaw', 'probes.pt > 100.', 'goff')

canvas = SimpleCanvas()
canvas.legend.setPosition(0.7, 0.7, 0.9, 0.9)
canvas.legend.add('dataCorr', title = 'Corrected', opt = 'LF', color = ROOT.kBlue, fstyle = 3003, lwidth = 2)
canvas.legend.add('dataRaw', title = 'Raw', opt = 'LF', color = ROOT.kRed, fstyle = 3003, lwidth = 2)

canvas.addHistogram(dataCorr)
canvas.addHistogram(dataRaw)

canvas.applyStyles()

canvas.printWeb('rawEScale', 'data', logy = False)

canvas.Clear()

mcCorr = ROOT.TH1D('mcCorr', '', 60, 60., 120.)
mcRaw = ROOT.TH1D('mcRaw', '', 60, 60., 120.)
Example #4
0
        eehist.Add(histSource.Get('mcbkg_ee_' + binName), -1.)
        eghist.Add(histSource.Get('mcbkg_eg_' + binName), -1.)

        ratio = eghist.Integral(61, 120) / eehist.Integral(61, 120)
        mctruth.append(ratio)

outputFile.cd()
frate.Write()
yields['ee'].Write()
yields['eg'].Write()

lumi = 0.
for sname in lumiSamples:
    lumi += allsamples[sname].lumi

canvas = SimpleCanvas(lumi = lumi, sim = (dataType == 'mc'))
canvas.legend.setPosition(0.7, 0.8, 0.9, 0.9)
canvas.legend.add('frate', 'R_{e}', opt = 'LP', color = ROOT.kBlack, mstyle = 8)
canvas.legend.apply('frate', frate)
canvas.ylimits = (0., 0.03)
canvas.addHistogram(frate, drawOpt = 'EP')

canvas.xtitle = binningTitle
canvas.printWeb('efake', 'frate_' + dataType + '_' + binningName, logy = False)

for iBin, (binName, cut) in enumerate(fitBins):
    if dataType == 'mc':
        print '%15s [%.3f +- %.3f (stat.) +- %.3f (syst.)] x 10^{-2} (mc %.3f)' % (binName, contents[iBin] * 100., staterrs[iBin] * 100., systerrs[iBin] * 100., mctruth[iBin] * 100.)
    else:
        print '%15s [%.3f +- %.3f (stat.) +- %.3f (syst.)] x 10^{-2}' % (binName, contents[iBin] * 100., staterrs[iBin] * 100., systerrs[iBin] * 100.)
Example #5
0
File: eff.py Project: yiiyama/MonoX
                hbase.Write()
                eff.Write(vname + '_eff')

        outputFile.Close()

## PLOT GRAPHS

work = ROOT.RooWorkspace('work', 'work')
xvar = work.factory('x[-6500.,6500.]')

if FITEFFICIENCY:
    ROOT.gSystem.Load('libRooFit.so')
    ROOT.gSystem.Load('/home/yiiyama/cms/studies/fittools/libFitTools.so')
    fitter = ROOT.EfficiencyFitter.singleton()

canvas = SimpleCanvas()
canvas.legend.setPosition(0.7, 0.3, 0.9, 0.5)

for omname in omnames:
    oname = omname[0]
    mname = omname[1]
    print oname, mname

    source = ROOT.TFile.Open(outDir + '/trigger_efficiency_%s_%s.root' %
                             (oname, mname))

    snames, region, probeSel, colname = measurements[(oname, mname)]

    canvas.lumi = sum(sample.lumi for sample in allsamples.getmany(snames))

    for tname, (_, _, title, variables) in confs[oname].items():
Example #6
0
    canvas.addObs(dmet, title='Data')

    canvas.xtitle = canvas.obsHistogram().GetXaxis().GetTitle()
    canvas.ytitle = canvas.obsHistogram().GetYaxis().GetTitle()

    canvas.Update(logy=True)

    canvas.printWeb('monophoton/gjetsTFactor', 'distributions' + region)

###########################################
####### Transfer Factors ##################
###########################################

methods = [('Data', gmets), ('MC', mcmets)]
scanvas = SimpleCanvas(lumi=lumi)

tfacts = []

for method, hists in methods:
    tname = 'tfact' + method
    tfact = hists[1].Clone(tname)
    tfact.Divide(hists[0])

    tfact.GetYaxis().SetTitle("")

    tfact.SetMarkerStyle(8)
    tfact.SetMarkerSize(0.8)

    outputFile.cd()
    tfact.Write()
Example #7
0
    fname = config.skimDir + '/' + sample + '_' + region + '.root'
    print fname
    source = r.TFile.Open(fname)
    tree = source.Get('events')
    sources.append(source)
    trees.append((sample, tree))

    branches = tree.GetListOfBranches()
    for branch in branches:
        name = branch.GetName()
        if not name.startswith('weight'):
            continue
        if not name in weights:
            weights.append(name)

canvas = SimpleCanvas()
canvas.legend.setPosition(0.6, 0.7, 0.9, 0.9)

for weight in weights:
    print weight
    
    (Xmin, Xmax) = (9999., -1)

    for sample, tree in trees:
        tree.Draw(weight)
        htemp = r.gPad.GetPrimitive("htemp")

        xmin = htemp.GetBinLowEdge(1)
        xmax = htemp.GetBinLowEdge(htemp.GetNbinsX()+1)

        Xmin = min(xmin, Xmin)
Example #8
0
            if int(faken) not in fakens:
                fakens.append(int(faken))

            data[sigs][faken].append(tuple(map(float, words[2:])))

try:
    os.makedirs(config.histDir + '/fakemet')
except OSError:
    pass

fakens.sort()

outputFile = ROOT.TFile.Open(
    config.histDir + '/fakemet/injection_results.root', 'recreate')

canvas = SimpleCanvas()
canvas.legend.setPosition(0.6, 0.6, 0.9, 0.9)
canvas.legend.SetFillStyle(1001)
canvas.legend.SetBorderSize(1)

n = 0
colors = [
    '#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b',
    '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'
]
for faken in fakens:
    canvas.legend.add('n%d' % faken,
                      title='N_{f}=%d' % faken,
                      opt='P',
                      color=ROOT.TColor.GetColor(colors[n]),
                      mstyle=24 + n)
Example #9
0
                            count[1] = float(tmp[-2].strip("(),+-"))
                            count[2] = float(tmp[-1].strip("(),+-"))
                            #print count

                if not match:
                    print "No mc eff found for skim:", dirName
                    yields[loc][pid][ptCut][metCut]['mc'] = (-1., 0.0, 0.0)
                mcFile.close()

                yields[loc][pid][ptCut][metCut]['mc'] = tuple(count)
                    
pprint(yields)


sphLumi = sum(allsamples[s].lumi for s in ['sph-16b-r', 'sph-16c-r', 'sph-16d-r', 'sph-16e-r', 'sph-16f-r', 'sph-16g-r', 'sph-16h'])
canvas = SimpleCanvas(lumi = sphLumi)
rcanvas = SimpleCanvas(lumi = sphLumi)

for loc in s.Locations[:1]:
    for base in bases:
        for metCut in MetSels:
            rcanvas.cd()
            rcanvas.Clear()
            rcanvas.legend.Clear()
            rcanvas.legend.setPosition(0.45, 0.7, 0.8, 0.9)

            for iMod, mod in enumerate(mods):

                dataEff = r.TGraphAsymmErrors()
                dataEff.SetName(loc+'-'+base+mod+'-'+metCut+'-data')
Example #10
0
halos = [allsamples[sname] for sname in halonames]

dataTree = ROOT.TChain('events')
for sample in halos:
    dataTree.Add(config.photonSkimDir + '/' + sample.name + '.root')
dataTree.SetEstimate(dataTree.GetEntries() + 1)

candTree = ROOT.TChain('events')
for sample in targs:
    print config.skimDir + '/' + sample.name + '_monoph.root'
    candTree.Add(config.skimDir + '/' + sample.name + '_monoph.root')
candTree.SetEstimate(candTree.GetEntries() + 1)

# Canvas
from plotstyle import SimpleCanvas
canvas = SimpleCanvas(lumi = sum(t.lumi for t in targs))
plotName = 'fit'

### fit to halo distribution and parametrize

# draw
dataTree.Draw(phimpipi + '>>haloTemp(40,-{pi},{pi})'.format(pi = math.pi), 'photons.mipEnergy > 4.9 && photons.isEB && photons.scRawPt > 175. && t1Met.met > 140. && photons.chWorstIso < 1.37 && photons.nhIso < 1.06', 'goff')

haloTemp = ROOT.gDirectory.Get('haloTemp')
haloTemp.SetLineColor(ROOT.kBlack)
haloTemp.SetLineWidth(2)
haloTemp.SetTitle(';#phi\'')

canvas.addHistogram(haloTemp)
canvas.xtitle = '#phi\''
canvas.printWeb('monophoton/halo', 'haloTemp', logy = False)
Example #11
0
dataTree.Add('/scratch5/ballen/hist/monophoton/phoMet/phi_sph-*.root')
# dataTree.Add('/scratch5/ballen/hist/monophoton/phoMet/phi_sel-*.root')

samples = [('dy-50', r.TColor.GetColor(0x99, 0xee, 0xff)),
           ('gj', r.TColor.GetColor(0xff, 0xaa, 0xcc))]

mcTrees = []
for sample, color in samples:
    mcTree = r.TChain('skim')
    mcTree.Add('/scratch5/ballen/hist/monophoton/phoMet/phi_' + sample +
               '*.root')
    mcTrees.append((sample, color, mcTree))

lumi = allsamples['sph-d3'].lumi + allsamples['sph-d4'].lumi
# canvas = DataMCCanvas(lumi = lumi)
canvas = SimpleCanvas(lumi=lumi)

probeEtaCuts = [('TMath::Abs(probe.eta) < 0.8', 'low'),
                ('TMath::Abs(probe.eta > 0.8)', 'high')]
recoilCuts = [('recoil.pt > %i.' % pt, 'recoil' + str(pt))
              for pt in [170, 200, 250, 300, 400]]
probeObjectCuts = [
    ('probe.isPhoton && probe.pixelVeto && tag.pixelVeto', 'diphoton'),
    ('probe.isPhoton && !probe.pixelVeto && !tag.pixelVeto', 'dielectron'),
    ('tag.pixelVeto && !probe.isPhoton', 'gammajet')
]

njetsCut = 'njets < 2'
tagEtaCut = 'TMath::Abs(tag.eta) < 0.2'

metCut = 't1Met.met > 100.'
Example #12
0
    weight = work.factory('weight[-1000000000., 1000000000.]')
    nbkg = work.factory('nbkg[0., 1000000.]')
    nsignal = work.factory('nsignal[0., 1000000.]')
    if pdf == 'altsig':
        mZ = work.factory('mZ[91.2, 86., 96.]')
        gammaZ = work.factory('gammaZ[2.5, 1., 5.]')
    else:
        mZ = work.factory('mZ[91.2]')
        gammaZ = work.factory('gammaZ[2.5]')

    m0 = work.factory('m0[-10., 10.]')
    sigma = work.factory('sigma[0.001, 5.]')
    alpha = work.factory('alpha[0.01, 5.]')
    n = work.factory('n[1.01, 5.]')

    canvas = SimpleCanvas(lumi = lumi, sim = (dataType == 'mc'))
    canvas.titlePave.SetX2NDC(0.5)
    canvas.legend.setPosition(0.6, 0.7, 0.9, 0.9)
    canvas.legend.add('obs', title = 'Observed', opt = 'LP', color = ROOT.kBlack, mstyle = 8)
    canvas.legend.add('fit', title = 'Fit', opt = 'L', lcolor = ROOT.kBlue, lwidth = 2, lstyle = ROOT.kSolid)
    canvas.legend.add('bkg', title = 'Bkg component', opt = 'L', lcolor = ROOT.kGreen, lwidth = 2, lstyle = ROOT.kDashed)
    if dataType == 'mc':
        canvas.legend.add('mcbkg', title = 'Bkg (MC truth)', opt = 'LF', lcolor = ROOT.kRed, lwidth = 1, fcolor = ROOT.kRed, fstyle = 3003)

random = ROOT.TRandom3(seed)

### Common setup done ###

### Fitting routine ###
def runFit(targ, model, printLevel = 1, vals = None):
    for param, val in initVals.items():
Example #13
0
import config

import ROOT

dma = []
dmv = []

for name in allsamples.names():
    matches = re.match('dm([av])-([0-9]+)-([0-9]+)', name)
    if matches:
        if matches.group(1) == 'a':
            dma.append((float(matches.group(2)), float(matches.group(3))))
        else:
            dmv.append((float(matches.group(2)), float(matches.group(3))))

canvas = SimpleCanvas(cms = False)
canvas.SetGrid(True)

gdma = ROOT.TGraph(len(dma))
for iP, (med, dm) in enumerate(dma):
    gdma.SetPoint(iP, med, dm)

gdma.SetTitle('DMA;M_{med} (GeV);M_{DM} (GeV)')
gdma.SetMarkerStyle(21)

canvas.addHistogram(gdma, drawOpt = 'P')
canvas.printWeb('signal_points', 'dma', logx = True)

canvas.Clear()
canvas.SetGrid(True)
Example #14
0
                    print "No mc eff file found for skim:", dirName
                    yields[loc][pid][ptCut][metCut]['mc'] = (-1., 0.0)

                if gjMatch and wjMatch:
                    count[0] = gjCount[0] + wjCount[0]
                    count[1] = math.sqrt(gjCount[1]**2 + wjCount[1]**2)

                    yields[loc][pid][ptCut][metCut]['mc'] = tuple(count)

                else:
                    print "No mc yields file found for skim:", dirName
                    yields[loc][pid][ptCut][metCut]['mc'] = (-1., 0.0)

pprint(yields)

canvas = SimpleCanvas(lumi=s.sphLumi)
rcanvas = SimpleCanvas(lumi=s.sphLumi, name='effs')

scalefactors = {}

passes = base + mods[2]
totals = base + mods[0]

for loc in s.Locations[:1]:
    scalefactors[loc] = {}
    for base in bases:
        scalefactors[loc][base] = {}
        print '\n' + base
        for metCut in MetSels:
            scalefactors[loc][base][metCut] = {}
Example #15
0
            pass

    ratio = yields['eg'].GetBinContent(iBin + 1) / yields['ee'].GetBinContent(iBin + 1)
    frate.SetBinContent(iBin + 1, ratio)
    frate.SetBinError(iBin + 1, ratio * math.sqrt(stat2 + syst2))

    contents.append(ratio)
    staterrs.append(ratio * math.sqrt(stat2))
    systerrs.append(ratio * math.sqrt(syst2))

outputFile.cd()
frate.Write()
yields['ee'].Write()
yields['eg'].Write()

canvas = SimpleCanvas(lumi = allsamples['sel-d3'].lumi + allsamples['sel-d4'].lumi, sim = (dataType == 'mc'))
canvas.legend.setPosition(0.7, 0.8, 0.9, 0.9)
canvas.legend.add('frate', 'R_{e}', opt = 'LP', color = ROOT.kBlack, mstyle = 8)
canvas.legend.apply('frate', frate)
canvas.ylimits = (0., 0.03)
canvas.addHistogram(frate, drawOpt = 'EP')

canvas.xtitle = binningTitle
canvas.printWeb('efake', 'frate_' + dataType + '_' + binningName, logy = False)

for iBin, (binName, cut) in enumerate(fitBins):
    print '%15s [%.3f +- %.3f (stat.) +- %.3f (syst.)] x 10^{-2}' % (binName, contents[iBin] * 100., staterrs[iBin] * 100., systerrs[iBin] * 100.)

if toyUncert and binningName == 'pt':
    binName = 'pt_100_6500'
    for conf in ['ee', 'eg']:
Example #16
0
    green = (1.0, 0.0)
    blue = (1.0, 1.0)

    s = array.array('d', stops)
    r = array.array('d', red)
    g = array.array('d', green)
    b = array.array('d', blue)

    npoints = len(s)
    ROOT.TColor.CreateGradientColorTable(npoints, s, r, g, b, ncontours)
    ROOT.gStyle.SetNumberContours(ncontours)
    ROOT.gStyle.SetPaintTextFormat(".0f")


lumi = allsamples['sph-d3'].lumi + allsamples['sph-d4'].lumi
canvas = SimpleCanvas(lumi=lumi, xmax=0.90)

samples = ['monoph', 'efake', 'hfake', 'halo', 'haloUp', 'haloDown']

for sample in samples:
    dataTree = ROOT.TChain('events')
    dataTree.Add('/scratch5/ballen/hist/monophoton/skim/sph-d*_' + sample +
                 '.root')

    xString = "t1Met.photonDPhi"
    yString = "( ( (photons.e55[0] / TMath::CosH(photons.eta[0])) - photons.pt[0] ) / t1Met.met )"

    dataHist = ROOT.TH2D(sample, "", 30, 0., math.pi, 10, -1.0, 1.0)
    dataHist.GetXaxis().SetTitle('#Delta#phi(#gamma, E_{T}^{miss})')
    dataHist.GetYaxis().SetTitle(
        '(E_{55}^{#gamma} - E_{T}^{#gamma}) / E_{T}^{miss}')
Example #17
0
import math
import array

thisdir = os.path.dirname(os.path.realpath(__file__))
basedir = os.path.dirname(thisdir)
sys.path.append(basedir)
from datasets import allsamples
import config
from main.plotconfig import getConfig
from plotstyle import SimpleCanvas

import ROOT
ROOT.gROOT.SetBatch(True)

lumi = allsamples['sph-d3'].lumi + allsamples['sph-d4'].lumi
canvas = SimpleCanvas(lumi=lumi)

samples = {
    'sph-*': ['monoph', 'efake', 'hfake', 'halo', 'gjets'],
    'gj-*': ['gjets'],
    'qcd-*': ['gjets'],
    'wlnu-*': ['wenu'],
    'wlnu': ['wenu']
}

for sample in samples:
    for region in samples[sample]:
        canvas.Clear()
        canvas.legend.Clear()
        canvas.legend.setPosition(0.6, 0.7, 0.9, 0.9)
Example #18
0
import sys
import os
import array
import math
import ROOT

basedir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(basedir)
from plotstyle import SimpleCanvas, RatioCanvas
from datasets import allsamples
import config

lumi = sphLumi = sum(allsamples[s].lumi for s in ['sph-16b-r', 'sph-16c-r', 'sph-16d-r', 'sph-16e-r', 'sph-16f-r', 'sph-16g-r', 'sph-16h'])
canvas = SimpleCanvas(lumi = lumi)
rcanvas = RatioCanvas(lumi = lumi)

binning = array.array('d', [175., 180., 185., 190., 200., 210., 230., 250., 300., 350., 400.])
pid = 'medium'

inputFile = ROOT.TFile.Open(basedir+'/data/impurity.root')
# impurityHist = inputFile.Get("barrel-loose-pixel-Met0to60")
impurityGraph = inputFile.Get("barrel-" + pid + "-pixel-Met0to60")

outputFile = ROOT.TFile.Open(basedir+'/data/hadronTFactor.root', 'recreate')

isos = [ ('', '') ] # ('Worst', '') ] # , ('JetPt', 'JetPt') ] # [ ( '', 'pv'), ('Worst', '') ]

baseSel = 'jets.pt[0] > 100. && t1Met.met < 60. && photons.size == 1 && photons.pixelVeto[0]'

samples = [ ('',  baseSel+' && (( photons.sieie[0] < 0.015 && photons.sieie[0] > 0.012) || ( photons.chIso[0] < 11.0 && photons.chIso[0] > 1.37))')
            ,('Down', baseSel)
Example #19
0
import os
import sys
import ROOT

thisdir = os.path.dirname(os.path.realpath(__file__))
basedir = os.path.dirname(thisdir)
sys.path.append(basedir)
from plotstyle import SimpleCanvas

ROOT.gStyle.SetTitleOffset(1.6, 'Y')

source = ROOT.TFile.Open(basedir + '/data/kfactor.root')

canvas = SimpleCanvas(sim=True)
canvas.legend.setPosition(0.8, 0.7, 0.9, 0.9)
canvas.legend.add('znng-130-o',
                  'Z#gamma',
                  opt='LFP',
                  color=ROOT.kBlue,
                  fstyle=3003,
                  lwidth=2,
                  mstyle=8)
canvas.legend.add('wnlg-130-o',
                  'W#gamma',
                  opt='LFP',
                  color=ROOT.kMagenta,
                  fstyle=3003,
                  lwidth=2,
                  mstyle=8)

for hname in ['znng-130-o', 'wnlg-130-o']:
Example #20
0
noniso += ' && photons.chIsoMaxX[0][%d] < %f' % (itune, ROOT.cutvalue)
ROOT.gROOT.ProcessLine("cutvalue = panda::XPhoton::nhIsoCuts[%s][0][2];" %
                       tune)
noniso += ' && (photons.nhIsoX[0][%d] > %f' % (itune, ROOT.cutvalue)
ROOT.gROOT.ProcessLine("cutvalue = panda::XPhoton::phIsoCuts[%s][0][2];" %
                       tune)
noniso += ' || photons.phIsoX[0][%d] > %f)' % (itune, ROOT.cutvalue)

outputFile.cd()

addPlot(
    haloPlotter, 'phiHalo',
    'photons.sieie[0] > 0.015 && photons.mipEnergy[0] > 4.9 && metFilters.globalHalo16'
)
addPlot(emjetPlotter, 'phiCand', noniso)
addPlot(mcPlotter, 'phiZnng')

haloPlotter.fillPlots()
emjetPlotter.fillPlots()
mcPlotter.fillPlots()

canvas = SimpleCanvas()
canvas.legend.setPosition(0.4, 0.7, 0.92, 0.92)
canvas.legend.SetTextSize(0.03)

for plot in plots:
    canvas.Clear()
    canvas.ylimits = (0., plot.GetMaximum() * 1.5)
    canvas.addHistogram(plot)
    canvas.printWeb('monophoton/halo', plot.GetName(), logy=False)
Example #21
0
import sys
import os
import array
import math
import ROOT

basedir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(basedir)
from plotstyle import SimpleCanvas
import config

canvas = SimpleCanvas(lumi = 2239.9)

binning = array.array('d', [175., 180., 185., 190., 200., 210., 230., 250., 300., 350., 400.])

inputFile = ROOT.TFile.Open(basedir+'/data/impurity.root')
impurityHist = inputFile.Get("ChIso50to80imp")

outputFile = ROOT.TFile.Open(basedir+'/data/hadronTFactor.root', 'recreate')

isos = [ ('Worst', '') ] # , ('JetPt', 'JetPt') ] # [ ( '', 'pv'), ('Worst', '') ]

baseSel = 't1Met.met < 60. && photons.size == 1 && photons.pixelVeto[0]'

samples = [ ('',  baseSel+' && (photons.sieie[0] > 0.012 || photons.chIso[0] > 1.37)')
            ,('Down', baseSel)
            ,('Up', baseSel)
            ]

for iso in isos:
    gtree = ROOT.TChain('events')
Example #22
0
tree = ROOT.TChain('events')

tree.Add('/scratch5/yiiyama/hist/triggertree/t2mit/filefi/042/' + allsamples['sph-d3'].directory + '/l1t_*.root')
tree.Add('/scratch5/yiiyama/hist/triggertree/t2mit/filefi/042/' + allsamples['sph-d4'].directory + '/l1t_*.root')

binning = array.array('d', [30. + 5. * x for x in range(14)] + [100. + 10. * x for x in range(10)] + [200. + 20. * x for x in range(5)])

passing = ROOT.TH1D('passing', ';p_{T}^{#gamma} (GeV)', len(binning) - 1, binning)
denom = ROOT.TH1D('denom', ';p_{T}^{#gamma} (GeV)', len(binning) - 1, binning)

tree.Draw('pt>>denom')
tree.Draw('pt>>passing', 'l1dr2 < 0.25')

eff = ROOT.TGraphAsymmErrors(passing, denom)

canvas = SimpleCanvas(lumi = allsamples['sph-d3'].lumi + allsamples['sph-d4'].lumi)
canvas.legend.setPosition(0.7, 0.3, 0.9, 0.5)
canvas.legend.add('eff', title = 'L1 seed', opt = 'LP', color = ROOT.kBlack, mstyle = 8)

canvas.SetGrid()

canvas.legend.apply('eff', eff)

canvas.addHistogram(eff, drawOpt = 'EP')
canvas.addLine(0., 1., 300., 1.)
eff.GetXaxis().SetLimits(0., 300.)

canvas.xtitle = 'p_{T}^{#gamma} (GeV)'
canvas.ytitle = 'L1 seed eff.'

canvas.ylimits = (0., 1.2)
Example #23
0
from plotstyle import SimpleCanvas, RatioCanvas
from datasets import allsamples
import purity.selections as selections
import config
import utils

ROOT.gROOT.SetBatch(True)

###########################
# Setup and configuration #
###########################

snames = ['sph-16*-m']

lumi = sum(s.lumi for s in allsamples.getmany(snames))
canvas = SimpleCanvas(lumi=lumi)
rcanvas = RatioCanvas(lumi=lumi)

binning = array.array('d', map(float, selections.photonPtBinning))
pid = 'medium'
tune = 'Spring16'  # 'GJetsCWIso'
extras = 'pixel-chargedpf'  # -monoph'
suffix = '_Spring16'  # '_GJetsCWIso'

itune = selections.Tunes.index(tune)

inputFile = ROOT.TFile.Open(basedir + '/data/impurity_' + tune + '.root')
impurityGraph = inputFile.Get("barrel-" + pid + "-" + extras + "-Met0to60")

outputFile = ROOT.TFile.Open(
    basedir + '/data/hadronTFactor' + suffix + '.root', 'recreate')
Example #24
0
def makeFoldedPlot(tree, name, sel):
    plot = ROOT.TH1D(name, ";#phi''", 15, 0.0, math.pi * 0.5)
    plot.Sumw2()
    plot.SetLineColor(ROOT.kBlack)
    plot.SetLineWidth(2)
    tree.Draw(
        "TMath::Abs(TMath::Abs(TVector2::Phi_mpi_pi(TVector2::Phi_mpi_pi(photons.phi + 0.005) - 1.570796)) - 1.570796)>>"
        + name,
        selection.format(sel=sel),
        "goff",
    )

    return plot


canvas = SimpleCanvas()
canvas.legend.setPosition(0.4, 0.7, 0.92, 0.92)
canvas.legend.SetTextSize(0.03)

outputFile = ROOT.TFile.Open(config.histDir + "/halo/phidistributions.root", "recreate")

sphnames = ["sph-16b2", "sph-16b2s"]

sphs = [allsamples[sname] for sname in sphnames]
znng = allsamples["znng-130"]

dataTree = ROOT.TChain("events")
for sample in sphs:
    dataTree.Add(config.photonSkimDir + "/" + sample.name + ".root")

dataTreeAll = ROOT.TChain("events")
Example #25
0
            if int(faken) not in fakens:
                fakens.append(int(faken))

            data[sigs][faken].append(tuple(map(float, words[2:])))

try:
    os.makedirs(config.histDir + '/fakemet')
except OSError:
    pass

fakens.sort()

outputFile = ROOT.TFile.Open(
    config.histDir + '/fakemet/injection_results.root', 'recreate')

canvas = SimpleCanvas()
canvas.legend.setPosition(0.8, 0.7, 0.9, 0.9)
canvas.legend.SetFillStyle(1001)
canvas.legend.SetBorderSize(1)

n = 0
colors = [
    '#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b',
    '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'
]
for faken in fakens:
    canvas.legend.add('n%d' % faken,
                      title='N_{f}=%d' % faken,
                      opt='P',
                      color=ROOT.TColor.GetColor(colors[n]),
                      mstyle=24 + n)
Example #26
0
def printCanvas(canvas, plotdef, plotConfig, plotDir):
    """
    Print the canvas content as pdf and png.
    """

    eil = ROOT.gErrorIgnoreLevel
    ROOT.gErrorIgnoreLevel = ROOT.kWarning

    canvas.xtitle = plotdef.xtitle()
    canvas.ytitle = plotdef.ytitle(binNorm=True)

    canvas.selection = plotdef.cutName

    if plotdef.logy is None:
        logy = True
        addLinear = True
    else:
        logy = plotdef.logy
        addLinear = False

    canvas.ylimits = (plotdef.ymin, plotdef.ymax)
    canvas.rlimits = (plotdef.rmin, plotdef.rmax)
    canvas.Update(logy=logy)

    if plotdef.fullyBlinded():
        # remove ratio pad. Hack to use SimpleCanvas interface
        simple = SimpleCanvas(lumi=canvas.lumi)

        garbage = []
        cnv = ROOT.TCanvas('tmp', 'tmp', 600, 600)
        cnv.cd()

        plotPad = canvas.plotPad.DrawClone()
        garbage.append(plotPad)
        plotPad.SetTopMargin(simple.canvas.GetTopMargin())
        plotPad.SetRightMargin(simple.canvas.GetRightMargin())
        plotPad.SetBottomMargin(simple.canvas.GetBottomMargin())
        plotPad.SetLeftMargin(simple.canvas.GetLeftMargin())

        xaxis = canvas.xaxis.DrawClone()
        garbage.append(xaxis)
        xaxis.SetX1(simple.canvas.GetLeftMargin())
        xaxis.SetX2(1. - simple.canvas.GetRightMargin())
        xaxis.SetY1(simple.canvas.GetBottomMargin())
        xaxis.SetY2(simple.canvas.GetBottomMargin())

        yaxis = canvas.yaxis.DrawClone()
        garbage.append(yaxis)
        yaxis.SetX1(simple.canvas.GetLeftMargin())
        yaxis.SetX2(simple.canvas.GetLeftMargin())
        yaxis.SetY1(simple.canvas.GetBottomMargin())
        yaxis.SetY2(1. - simple.canvas.GetTopMargin())

        simple.canvas.IsA().Destructor(simple.canvas)
        simple.canvas = cnv
        simple._needUpdate = False
        simple.printWeb(plotDir, plotdef.name)

        sys.stdout.write('    main')
        if logy:
            sys.stdout.write(' (log)')
        else:
            sys.stdout.write(' (lin)')

        if addLinear:
            plotPad.SetLogy(False)
            plotPad.Update()
            yaxis.SetOption('')
            yaxis.SetWmin(plotPad.GetUymin())
            yaxis.SetWmax(plotPad.GetUymax())
            simple.printWeb(plotDir, plotdef.name + 'Linear', logy=False)

            sys.stdout.write(' (lin)')

        sys.stdout.write('\n')
        sys.stdout.flush()

        # cleanup the mess
        for obj in garbage:
            obj.IsA().Destructor(obj)

        cnv.IsA().Destructor(cnv)

    else:
        # normal, (partially) unblinded distributions
        canvas.printWeb(plotDir, plotdef.name, drawLegend=False)

        sys.stdout.write('    main')
        if logy:
            sys.stdout.write(' (log)')
        else:
            sys.stdout.write(' (lin)')

        if addLinear:
            canvas.ylimits = (0., -1.)
            canvas.minimum = -1.
            plotdef.ymax = -1.
            plotdef.ymin = 0.
            canvas._needUpdate = True
            canvas.printWeb(plotDir, plotdef.name + 'Linear', logy=False)

            sys.stdout.write(' (lin)')

        sys.stdout.write('\n')
        sys.stdout.flush()

    ROOT.gErrorIgnoreLevel = eil
Example #27
0
dataMumug.Add(config.skimDir + '/smu-16*-m_tpmmg.root')

# MC mumug tree
mcMumug = ROOT.TChain('events')
mcMumug.Add(config.skimDir + '/zllg_tpmmg.root')
mcMumug.Add(config.skimDir + '/tt_tpmmg.root')
mcMumug.Add(config.skimDir + '/ww_tpmmg.root')
mcMumug.Add(config.skimDir + '/wz_tpmmg.root')
mcMumug.Add(config.skimDir + '/zz_tpmmg.root')

# MC znng tree
mcMonoph = ROOT.TChain('events')
mcMonoph.Add(config.skimDir + '/znng-130-o_monophNoLVeto.root')

# canvases
distCanvas = SimpleCanvas('cdist')
distCanvas.legend.add('data',
                      title='2#mu data',
                      opt='L',
                      color=ROOT.kBlack,
                      fstyle=0)
distCanvas.legend.add('mumug',
                      title='2#mu MC',
                      opt='L',
                      color=ROOT.kRed,
                      fstyle=0)
distCanvas.legend.add('monoph',
                      title='Z#gamma MC',
                      opt='L',
                      color=ROOT.kBlue,
                      fstyle=0)
Example #28
0
from datasets import allsamples
from plotstyle import SimpleCanvas
import config
import utils

ROOT.RooMsgService.instance().setGlobalKillBelow(ROOT.RooFit.ERROR)
ROOT.gROOT.LoadMacro(basedir + '/../common/MultiDraw.cc+')

#targs = allsamples.getmany(['sph-16b-m', 'sph-16c-m', 'sph-16d-m'])
targs = allsamples.getmany(['sph-16*-m'])
dataLumi = sum(s.lumi for s in targs)

### Canvas
from plotstyle import SimpleCanvas
canvas = SimpleCanvas()
canvas.lumi = dataLumi


### Make templates
# Visualization
def plotHist(hist):
    canvas.addHistogram(hist)
    canvas.xtitle = '#phi\''
    canvas.printWeb('monophoton/halo', hist.GetName(), logy=False)
    canvas.Clear()


outputFile = ROOT.TFile.Open(config.histDir + '/halo/phifit.root', 'recreate')

templates = {}
Example #29
0
                    pdfout = pdflatex.communicate()
                    if not pdfout[1] == "":
                        print pdfout[1]


                    convert = Popen( ["convert",purityFilePath.replace(".tex",".pdf")
                                      ,purityFilePath.replace(".tex",".png") ]
                                     ,stdout=PIPE,stderr=PIPE,cwd=outDir)
                    conout = convert.communicate()
                    if not conout[1] == "":
                        print conout[1]
                    """
                       
pprint(purities)

canvas = SimpleCanvas(lumi = config.jsonLumi)

for source in sources:
    for loc in Locations[:1]:
        for pid in PhotonIds:
            for metCut in MetSels[1:2]:
                canvas.cd()
                canvas.Clear()
                canvas.legend.Clear()
                canvas.legend.setPosition(0.525,0.65,0.875,0.85)

                purityFileName = "purity_data_"+loc+"_"+pid+"_ptbinned_table.tex"
                purityFilePath = os.path.join(outDir,purityFileName)
                purityFile = open(purityFilePath, "w")

                purityFile.write(r"\documentclass{article}")
Example #30
0
import math
import array

thisdir = os.path.dirname(os.path.realpath(__file__))
basedir = os.path.dirname(thisdir)
sys.path.append(basedir)
from datasets import allsamples
import config
from main.plotconfig import getConfig
from plotstyle import SimpleCanvas

import ROOT
ROOT.gROOT.SetBatch(True)

lumi = allsamples['sph-d3'].lumi + allsamples['sph-d4'].lumi
canvas =  SimpleCanvas(lumi = lumi)



samples = {'sph' : [ 'monoph', 'efake', 'hfake', 'halo', 'gjets'],
           'gj' : [ 'gjets' ],
           'qcd' : [ 'gjets' ], 
           'wlnu' : [ 'withel' ]
           }


for sample in samples:
    for region in samples[sample]:
        canvas.Clear()
        canvas.legend.Clear()
        canvas.legend.setPosition(0.6, 0.7, 0.9, 0.9)
Example #31
0
                    purities[loc][pid][ptCut][metCut] = tuple(purity)

                    if not match:
                        print "No purity found for skim:", dirName
                        purities[loc][pid][ptCut][metCut] = (102.5, 0.0, 0.0,
                                                             0.0, 0.0, 0.0)

                    condorFile.close()
                except:
                    print "No purity file found for skim:", dirName
                    purities[loc][pid][ptCut][metCut] = (102.5, 0.0, 0.0, 0.0,
                                                         0.0, 0.0)

pprint(purities)

canvas = SimpleCanvas(lumi=s.sphLumi)

for loc in s.Locations[:1]:
    for base in bases:
        for metCut in MetSels:
            canvas.cd()
            canvas.Clear()
            canvas.legend.Clear()
            canvas.legend.setPosition(0.45, 0.7, 0.8, 0.9)

            for iMod, mod in enumerate(mods):

                pGraph = r.TGraphAsymmErrors()
                pGraph.SetName(loc + '-' + base + mod + '-' + metCut)

                for iB, ptCut in enumerate(PhotonPtSels):
Example #32
0
    mass = work.factory('mass[60., 120.]')
    mass.setUnit('GeV')
    mass.setBinning(fitBinning, 'fitWindow')
    mass.setBinning(compBinning, 'compWindow')
    massset = ROOT.RooArgSet(mass) # for convenience
    masslist = ROOT.RooArgList(mass) # for convenience
    weight = work.factory('weight[-1000000000., 1000000000.]')
    nbkg = work.factory('nbkg[0., 1000000.]')
    nsignal = work.factory('nsignal[0., 1000000.]')
    if dataType == 'data':
        m0 = work.factory('m0[-10., 10.]')
        sigma = work.factory('sigma[0.001, 5.]')
        alpha = work.factory('alpha[0.01, 5.]')
        n = work.factory('n[1.01, 5.]')

    canvas = SimpleCanvas(lumi = allsamples['sel-d3'].lumi + allsamples['sel-d4'].lumi, sim = (dataType == 'mc'))
    canvas.titlePave.SetX2NDC(0.5)
    canvas.legend.setPosition(0.6, 0.7, 0.9, 0.9)
    canvas.legend.add('obs', title = 'Observed', opt = 'LP', color = ROOT.kBlack, mstyle = 8)
    canvas.legend.add('fit', title = 'Fit', opt = 'L', lcolor = ROOT.kBlue, lwidth = 2, lstyle = ROOT.kSolid)
    canvas.legend.add('bkg', title = 'Bkg component', opt = 'L', lcolor = ROOT.kGreen, lwidth = 2, lstyle = ROOT.kDashed)
    if dataType == 'mc':
        canvas.legend.add('mcbkg', title = 'Bkg (MC truth)', opt = 'LF', lcolor = ROOT.kRed, lwidth = 1, fcolor = ROOT.kRed, fstyle = 3003)

random = ROOT.TRandom3(seed)

### Common setup done ###

### Fitting routine ###
def runFit(targ, model, printLevel = 1, vals = None):
    for param, val in initVals.items():
Example #33
0
dataTree.Add('/scratch5/ballen/hist/monophoton/phoMet/phi_sph-*.root')
# dataTree.Add('/scratch5/ballen/hist/monophoton/phoMet/phi_sel-*.root')

samples = [ ('dy-50', r.TColor.GetColor(0x99, 0xee, 0xff)), 
            ('gj', r.TColor.GetColor(0xff, 0xaa, 0xcc))
            ]

mcTrees = []
for sample, color in samples:
    mcTree = r.TChain('skim')
    mcTree.Add('/scratch5/ballen/hist/monophoton/phoMet/phi_'+sample+'*.root')
    mcTrees.append( (sample, color, mcTree) )

lumi = allsamples['sph-d3'].lumi + allsamples['sph-d4'].lumi
# canvas = DataMCCanvas(lumi = lumi)
canvas = SimpleCanvas(lumi = lumi)

probeEtaCuts = [ ('TMath::Abs(probe.eta) < 0.8', 'low'), ('TMath::Abs(probe.eta > 0.8)', 'high') ] 
recoilCuts = [ ('recoil.pt > %i.' % pt, 'recoil'+str(pt)) for pt in [170, 200, 250, 300, 400] ]
probeObjectCuts = [ ('probe.isPhoton && probe.pixelVeto && tag.pixelVeto', 'diphoton'), 
                    ('probe.isPhoton && !probe.pixelVeto && !tag.pixelVeto', 'dielectron'), 
                    ('tag.pixelVeto && !probe.isPhoton', 'gammajet') ]

njetsCut = 'njets < 2'
tagEtaCut = 'TMath::Abs(tag.eta) < 0.2'

metCut = 't1Met.met > 100.'
dPhiCut = 'TMath::Abs(TVector2::Phi_mpi_pi(tag.phi - probe.phi)) > 3.'
unbalancedCut = 'TMath::Abs(probe.pt - tag.pt) > 150'
probeLooseCut = 'probe.loose == 1'
probeNhIsoCut = 'probe.nhIso < 1.06'
Example #34
0
import math
from argparse import ArgumentParser

plotDir = 'monophoton/workspace'

thisdir = os.path.dirname(os.path.realpath(__file__))
basedir = os.path.dirname(thisdir)
sys.path.append(basedir)
from plotstyle import SimpleCanvas, RatioCanvas

import fit.parameters as parameters

import ROOT
ROOT.gROOT.SetBatch(True) 

canvas1 = SimpleCanvas(name = 'canvas1')
canvas1.legend.setPosition(0.7, 0.7, 0.9, 0.9)
# a very ugly hack - somehow cannot plot two types (with and without uncertainty) of plots..
canvas2 = SimpleCanvas(name = 'canvas2')

canvas1.legend.add('total', 'stat. + syst.', opt = 'F', color = ROOT.kOrange + 1, fstyle = 1001)
canvas1.legend.add('stat', 'stat.', opt = 'L', color = ROOT.kBlack, mstyle = 8)

source = ROOT.TFile.Open(parameters.plotsOutname)

tfList = ['tf_' + target[0] + '_' + target[1] + '_' + base[0] + '_' + base[1]  for (target, base) in parameters.links]
print tfList
procList = parameters.processes + parameters.signals + tfList

for region in parameters.regions:
    for proc in procList:
Example #35
0
ROOT.gROOT.SetBatch(True)

dataMumug = ROOT.TChain('skim')
dataMumug.Add(config.histDir + '/veto_eff/mumug_smu*.root')

mcMumug = ROOT.TChain('skim')
mcMumug.Add(config.histDir + '/veto_eff/mumug_zllg-130.root')
mcMumug.Add(config.histDir + '/veto_eff/mumug_tt.root')
mcMumug.Add(config.histDir + '/veto_eff/mumug_ww.root')
mcMumug.Add(config.histDir + '/veto_eff/mumug_wz.root')
mcMumug.Add(config.histDir + '/veto_eff/mumug_zz.root')

mcMonoph = ROOT.TChain('skim')
mcMonoph.Add(config.histDir + '/veto_eff/monoph_znng-130.root')

distCanvas = SimpleCanvas('cdist')
distCanvas.legend.add('data', title = '2#mu data', opt = 'L', color = ROOT.kBlack, fstyle = 0)
distCanvas.legend.add('mumug', title = '2#mu MC', opt = 'L', color = ROOT.kRed, fstyle = 0)
distCanvas.legend.add('monoph', title = 'Z#gamma MC', opt = 'L', color = ROOT.kBlue, fstyle = 0)
distCanvas.legend.setPosition(0.7, 0.7, 0.9, 0.9)

effCanvas = SimpleCanvas('ceff')
effCanvas.legend.add('data', title = '2#mu data', opt = 'LP', color = ROOT.kBlack, mstyle = 8)
effCanvas.legend.add('mumug', title = '2#mu MC', opt = 'LP', color = ROOT.kRed, mstyle = 8)
effCanvas.legend.add('monoph', title = 'Z#gamma MC', opt = 'LP', color = ROOT.kBlue, mstyle = 4)
effCanvas.legend.add('sf', title = '2#mu data/MC', opt = 'LP', color = ROOT.kBlack, mstyle = 25, lwidth = 2)
effCanvas.legend.setPosition(0.7, 0.7, 0.9, 0.9)
effCanvas.ylimits = (0.9, 1.05)
effCanvas.SetGrid(True)

configs = {
Example #36
0
import os
import sys

thisdir = os.path.dirname(os.path.realpath(__file__))
basedir = os.path.dirname(thisdir)
sys.path.append(basedir)
from datasets import allsamples
from plotstyle import SimpleCanvas
import config
import utils

import ROOT

canvas = SimpleCanvas()
canvas.legend.setPosition(0.7, 0.3, 0.9, 0.5)

#source = ROOT.TFile(config.histDir + '/trigger/scalefactor_photon_selBCD_dy.root')
#source = ROOT.TFile(config.histDir + '/trigger/scalefactor_photon_ph75_mcph75.root')
source = ROOT.TFile(config.histDir +
                    '/trigger/scalefactor_vbf_selBCD_wlnu.root')

#graph = source.Get('ph75r9iso_ptwide')
graph = source.Get('vbf_mjj')

#func = ROOT.TF1('line', '[0] + [1] * x', 80., 600.)
func = ROOT.TF1('line', '[0]', 550., 1000.)
#func.SetParameters(0.98, 0.)
func.SetParameters(0.98)

graph.Fit(func)
Example #37
0
sfTruth.Divide(mcTruthEff)

outputFile.cd()
scaleFactor.Write()
sfTruth.Write()
dataEff.Write('dataEff')
mcEff.Write('mcEff')
mcTruthEff.Write('mcTruthEff')

### Visualize

lumi = sum(allsamples[s].lumi for s in lumiSamples)

# scaleFactor.SetMaximum(1.05)

canvas = SimpleCanvas(lumi = lumi)
canvas.SetGrid(False, True)
canvas.legend.setPosition(0.7, 0.8, 0.9, 0.9)

canvas.legend.add('sf', 'Scale Factor', opt = 'LP', color = ROOT.kBlack, mstyle = 8)
canvas.legend.add('sf_truth', 'MC truth', opt = 'LP', color = ROOT.kGreen, mstyle = 4)
canvas.ylimits = (0.9, 1.10)

canvas.legend.apply('sf_truth', sfTruth)
canvas.addHistogram(sfTruth, drawOpt = 'EP')

canvas.legend.apply('sf', scaleFactor)
canvas.addHistogram(scaleFactor, drawOpt = 'EP')

if ADDFIT:
    flat = ROOT.TF1('flat', '[0]', scaleFactor.GetXaxis().GetXmin(), scaleFactor.GetXaxis().GetXmax())
Example #38
0
                        if tmp:
                            match = True
                            # pprint(tmp)
                            purity[5] = float(tmp[-1].strip("(),")) * 100
                            #print purity
                purities[loc][pid][ptCut][metCut] = tuple(purity)

                if not match:
                    print "No purity found for skim:", dirName
                    purities[loc][pid][ptCut][metCut] = (102.5, 0.0)
                condorFile.close()
                       
pprint(purities)

sphLumi = sum(allsamples[s].lumi for s in ['sph-16b-r', 'sph-16c-r', 'sph-16d-r', 'sph-16e-r', 'sph-16f-r', 'sph-16g-r', 'sph-16h'])
canvas = SimpleCanvas(lumi = sphLumi)

for loc in s.Locations[:1]:
    for base in bases:
        for metCut in MetSels:
            canvas.cd()
            canvas.Clear()
            canvas.legend.Clear()
            canvas.legend.setPosition(0.45, 0.7, 0.8, 0.9)

            for iMod, mod in enumerate(mods):
                
                pGraph = r.TGraphAsymmErrors()
                pGraph.SetName(loc+'-'+base+mod+'-'+metCut)

                for iB, ptCut in enumerate(PhotonPtSels):
Example #39
0
                                pprint(tmp)
                                count[0] = float(tmp[-3].strip("(),+-"))
                                count[1] = float(tmp[-2].strip("(),+-"))
                                count[2] = float(tmp[-1].strip("(),+-"))
                                #print count

                    if not match:
                        print "No yield found for skim:", source, dirName
                        yields[source][loc][pid][ptCut[0]][metCut[0]] = (-1., 0.0, 0.0)
                    condorFile.close()

                    yields[source][loc][pid][ptCut[0]][metCut[0]] = count
                    
pprint(yields)

canvas = SimpleCanvas(lumi = config.jsonLumi)
rcanvas = RatioCanvas(lumi = config.jsonLumi)

for loc in s.Locations[:1]:
    for pid in PhotonIds:
        for metCut in s.MetSels[1:2]:
            rcanvas.cd()
            rcanvas.Clear()
            rcanvas.legend.Clear()
            rcanvas.legend.setPosition(0.7, 0.3, 0.9, 0.5)

            dataEff = r.TGraphAsymmErrors()
            dataEff.SetName(loc+'-'+pid+'-'+metCut[0]+'-data')
            
            mcEff = r.TGraphAsymmErrors()
            mcEff.SetName(loc+'-'+pid+'-'+metCut[0]+'-mc')
Example #40
0
import ROOT

ROOT.gROOT.SetBatch(True)

fitDiagnostics = sys.argv[1]
plots = sys.argv[2]  # plots with random fakemet
name = sys.argv[3]
sigScale = float(sys.argv[4])
fakeNorm = float(sys.argv[5])

originalMu = 0.1
dist = 'mtPhoMet'
signal = 'dph-nlo-125'
region = 'gghg'

canvas = SimpleCanvas()

source = ROOT.TFile.Open(fitDiagnostics)

bkg = source.Get('shapes_fit_s/gghg/total_background')
fake = source.Get('shapes_fit_s/gghg/fakemet')
sig = source.Get('shapes_fit_s/gghg/total_signal')
data = source.Get('shapes_fit_s/gghg/data')

bkg.Add(fake, -1.)

plotsSource = ROOT.TFile.Open(plots)
bkgTrue = plotsSource.Get(dist + '/bkgtotal')
fakeTrue = plotsSource.Get(dist + '/fakemet')
sigTrue = plotsSource.Get(dist + '/samples/' + signal + '_' + region)
Example #41
0
            canvas.ytitle = obshist.GetYaxis().GetTitle()

            canvas.selection = vardef.formSelection(plotConfig)

            if vardef.logy is None:
                logy = True
                addLinear = True
            else:
                logy = vardef.logy
                addLinear = False

            canvas.Update(logy = logy, ymax = vardef.ymax)

            if vardef.fullyBlinded():
                # remove ratio pad. Hack to use SimpleCanvas interface
                simple = SimpleCanvas(lumi = canvas.lumi)

                garbage = []
                cnv = ROOT.TCanvas('tmp', 'tmp', 600, 600)
                cnv.cd()

                plotPad = canvas.plotPad.DrawClone()
                garbage.append(plotPad)
                plotPad.SetTopMargin(simple.canvas.GetTopMargin())
                plotPad.SetRightMargin(simple.canvas.GetRightMargin())
                plotPad.SetBottomMargin(simple.canvas.GetBottomMargin())
                plotPad.SetLeftMargin(simple.canvas.GetLeftMargin())

                xaxis = canvas.xaxis.DrawClone()
                garbage.append(xaxis)
                xaxis.SetX1(simple.canvas.GetLeftMargin())
Example #42
0
    fname = config.skimDir + '/' + sample + '_' + region + '.root'
    print fname
    source = r.TFile.Open(fname)
    tree = source.Get('events')
    sources.append(source)
    trees.append((sample, tree))

    branches = tree.GetListOfBranches()
    for branch in branches:
        name = branch.GetName()
        if not name.startswith('weight'):
            continue
        if not name in weights:
            weights.append(name)

canvas = SimpleCanvas()
canvas.legend.setPosition(0.6, 0.7, 0.9, 0.9)

for weight in weights:
    print weight

    (Xmin, Xmax) = (9999., -1)

    for sample, tree in trees:
        tree.Draw(weight)
        htemp = r.gPad.GetPrimitive("htemp")

        xmin = htemp.GetBinLowEdge(1)
        xmax = htemp.GetBinLowEdge(htemp.GetNbinsX() + 1)

        Xmin = min(xmin, Xmin)
Example #43
0
    reweighted += efficiency.GetBinContent(iX) * nproxy

    tpDist.SetBinContent(iX, ntp)

original /= tpDist.GetSumOfWeights() # should in principle match the nominal pT > 40 GeV efficiency
reweighted /= proxyDist.GetSumOfWeights()

print 'Original fake rate =', 1. / original - 1.
print 'Reweighted fake rate =', 1. / reweighted - 1.

proxyDist.Scale(1., 'width')
tpDist.Scale(1., 'width')
proxyDist.Scale(8. / proxyDist.GetSumOfWeights())
tpDist.Scale(8. / tpDist.GetSumOfWeights())

canvas = SimpleCanvas()
canvas.legend.setPosition(0.6, 0.7, 0.9, 0.9)
canvas.legend.add('inefficiency', title = '1 - #epsilon_{e}', opt = 'LP', mstyle = 8, color = ROOT.kBlack)
canvas.legend.add('tp', title = 'T&P sample', opt = 'LF', color = ROOT.kRed - 7, fstyle = 3003, lwidth = 2)
canvas.legend.add('proxy', title = 'W#rightarrowe#nu', opt = 'LF', color = ROOT.kBlue - 7, fstyle = 3003, lwidth = 2)

canvas.addHistogram(inefficiency, drawOpt = 'EP')
canvas.addHistogram(tpDist)
canvas.addHistogram(proxyDist)
canvas.applyStyles()

canvas.ytitle = '1 - #epsilon (%)'
canvas.xtitle = title

canvas.printWeb('efake', 'convolution_' + variable, logy = False)
Example #44
0
if len(sys.argv) > 4:
    fit_targ = sys.argv[4]
    formula = sys.argv[5]
    fit_range = tuple(map(float, sys.argv[6].split(',')))
    params = tuple(map(float, sys.argv[7].split(',')))
else:
    fit_targ = None

outName = 'trigger'
outDir = config.histDir + '/trigger'

if (oname, mname1) not in measurements or (oname, mname2) not in measurements:
    print 'Invalid object or measurement name'
    sys.exit(1)

canvas = SimpleCanvas()
canvas.legend.setPosition(0.7, 0.3, 0.9, 0.5)

numerSource = ROOT.TFile.Open(outDir + '/trigger_efficiency_%s_%s.root' %
                              (oname, mname1))
denomSource = ROOT.TFile.Open(outDir + '/trigger_efficiency_%s_%s.root' %
                              (oname, mname2))

outputFile = ROOT.TFile.Open(
    outDir + '/scalefactor_%s_%s_%s.root' % (oname, mname1, mname2),
    'recreate')

for tname, (_, _, title, variables) in confs[oname].items():
    for vname, (vtitle, _, _, binning) in variables.items():
        npass = numerSource.Get(tname + '/' + vname + '_pass')
        nbase = numerSource.Get(tname + '/' + vname + '_base')
Example #45
0
ROOT.gROOT.SetBatch(True)

dataDimu = ROOT.TChain("skim")
dataDimu.Add(config.histDir + "/veto_eff/dimu_smu*.root")

mcDimu = ROOT.TChain("skim")
mcDimu.Add(config.histDir + "/veto_eff/dimu_dy-50.root")
mcDimu.Add(config.histDir + "/veto_eff/dimu_tt.root")
mcDimu.Add(config.histDir + "/veto_eff/dimu_ww.root")
mcDimu.Add(config.histDir + "/veto_eff/dimu_wz.root")
mcDimu.Add(config.histDir + "/veto_eff/dimu_zz.root")

mcMonoph = ROOT.TChain("skim")
mcMonoph.Add(config.histDir + "/veto_eff/monoph_znng-130.root")

distCanvas = SimpleCanvas("cdist")
distCanvas.legend.add("data", title="2#mu data", opt="L", color=ROOT.kBlack, fstyle=0)
distCanvas.legend.add("dimu", title="2#mu MC", opt="L", color=ROOT.kRed, fstyle=0)
distCanvas.legend.add("monoph", title="Z#gamma MC", opt="L", color=ROOT.kBlue, fstyle=0)
distCanvas.legend.setPosition(0.7, 0.7, 0.9, 0.9)

effCanvas = SimpleCanvas("ceff")
effCanvas.legend.add("data", title="2#mu data", opt="LP", color=ROOT.kBlack, mstyle=8)
effCanvas.legend.add("dimu", title="2#mu MC", opt="LP", color=ROOT.kRed, mstyle=8)
effCanvas.legend.add("monoph", title="Z#gamma MC", opt="LP", color=ROOT.kBlue, mstyle=4)
effCanvas.legend.add("sf", title="2#mu data/MC", opt="LP", color=ROOT.kBlack, mstyle=25, lwidth=2)
effCanvas.legend.setPosition(0.7, 0.7, 0.9, 0.9)
effCanvas.ylimits = (0.9, 1.05)
effCanvas.SetGrid(True)

configs = {
Example #46
0
                math.pow(esmaller / smaller, 2.)))

outputFile.cd()
result.Write()
yields[meas[0]].Write()
yields[meas[1]].Write()
if dataType == 'mc':
    trueResult.Write()
    trueYields[meas[0]].Write()
    trueYields[meas[1]].Write()

### Visualize

lumi = sum(allsamples[s].lumi for s in lumiSamples)

canvas = SimpleCanvas(lumi=lumi, sim=(dataType == 'mc'))
canvas.SetGrid(False, True)
canvas.legend.setPosition(0.7, 0.8, 0.9, 0.9)
if PRODUCT == 'frate':
    result.SetMaximum(0.05)
    canvas.legend.add(PRODUCT, 'R_{e}', opt='LP', color=ROOT.kBlack, mstyle=8)
    canvas.ylimits = (0., 0.05)
else:
    canvas.legend.add(PRODUCT,
                      '#epsilon_{e}',
                      opt='LP',
                      color=ROOT.kBlack,
                      mstyle=8)
    canvas.ylimits = (0.75, 1.)

if dataType == 'mc':
Example #47
0
passdef, denomdef, title = tconf[tname]

if sname == 'jht' and vname == 'pt' and (tname == 'l1' or tname == 'l1hlt'):
    binning = array.array('d', [30. + 5. * x for x in range(14)] + [100. + 10. * x for x in range(10)] + [200. + 20. * x for x in range(5)] + [300. + 50. * x for x in range(14)])

## OBJECT DEFS

lumi = 0.
for sample in allsamples:
    if not sample.data:
        continue
    if not sname+'-16' in sample.name:
        continue
    lumi += sample.lumi

canvas = SimpleCanvas(lumi = lumi)
canvas.legend.setPosition(0.7, 0.3, 0.9, 0.5)

# matchL1[2] -> SEG34IorSEG40IorSJet200
# matchHLT[2] -> Ph165HE10

work = ROOT.RooWorkspace('work', 'work')
xvar = work.factory('x[-6500.,6500.]')

# fitter = ROOT.EfficiencyFitter.singleton()
tmpfile = ROOT.TFile.Open('/tmp/trigeff_tmp.root', 'recreate')

canvas.Clear()

tree = ROOT.TChain('triggerTree')
for fname in os.listdir(workDir):
Example #48
0
                math.pow(esmaller / smaller, 2.)))

outputFile.cd()
result.Write()
yields[meas[0]].Write()
yields[meas[1]].Write()
if dataType == 'mc':
    trueResult.Write()
    trueYields[meas[0]].Write()
    trueYields[meas[1]].Write()

### Visualize

lumi = sum(allsamples[s].lumi for s in lumiSamples)

canvas = SimpleCanvas(lumi=lumi, sim=(dataType == 'mc'))
canvas.SetGrid(False, True)
canvas.legend.setPosition(0.7, 0.8, 0.9, 0.9)
if PRODUCT == 'frate':
    result.SetMaximum(0.05)
    canvas.legend.add(PRODUCT, 'R_{e}', opt='LP', color=ROOT.kBlack, mstyle=8)
    canvas.ylimits = (0., 0.05)
else:
    canvas.legend.add(PRODUCT,
                      '#epsilon_{e}',
                      opt='LP',
                      color=ROOT.kBlack,
                      mstyle=8)
    canvas.ylimits = (0.75, 1.)

if dataType == 'mc':
Example #49
0
    red   = (1.0,0.0)
    green = (1.0,0.0)
    blue  = (1.0,1.0)
    
    s = array.array('d', stops)
    r = array.array('d', red)
    g = array.array('d', green)
    b = array.array('d', blue)

    npoints = len(s)
    ROOT.TColor.CreateGradientColorTable(npoints, s, r, g, b, ncontours)
    ROOT.gStyle.SetNumberContours(ncontours)
    ROOT.gStyle.SetPaintTextFormat(".0f")

lumi = allsamples['sph-d3'].lumi + allsamples['sph-d4'].lumi
canvas =  SimpleCanvas(lumi = lumi, xmax = 0.90)

samples = [ 'monoph', 'efake', 'hfake', 'halo', 'haloUp', 'haloDown']

for sample in samples:
    dataTree = ROOT.TChain('events')
    dataTree.Add('/scratch5/ballen/hist/monophoton/skim/sph-d*_'+sample+'.root')

    xString = "t1Met.photonDPhi"
    yString = "( ( (photons.e55[0] / TMath::CosH(photons.eta[0])) - photons.pt[0] ) / t1Met.met )"

    dataHist = ROOT.TH2D(sample, "", 30, 0., math.pi, 10, -1.0, 1.0)
    dataHist.GetXaxis().SetTitle('#Delta#phi(#gamma, E_{T}^{miss})')
    dataHist.GetYaxis().SetTitle('(E_{55}^{#gamma} - E_{T}^{#gamma}) / E_{T}^{miss}')
    dataHist.Sumw2()
    dataTree.Draw(yString+":"+xString+">>"+sample, '(photons.pt[0] > 175. && t1Met.minJetDPhi > 0.5 && t1Met.met > 170.)', 'goff')
Example #50
0
rawPx = 'probes.scRawPt * TMath::Cos(probes.phi)'
rawPy = 'probes.scRawPt * TMath::Sin(probes.phi)'
rawPz = 'TMath::SinH(probes.eta) * probes.scRawPt'
rawE = 'TMath::CosH(probes.eta) * probes.scRawPt'

rawMass = 'TMath::Sqrt(TMath::Power(' + rawE + ' + tags.pt * TMath::CosH(tags.eta), 2.)'
rawMass += ' - TMath::Power(' + rawPx + ' + tags.pt * TMath::Cos(tags.phi), 2.)'
rawMass += ' - TMath::Power(' + rawPy + ' + tags.pt * TMath::Sin(tags.phi), 2.)'
rawMass += ' - TMath::Power(' + rawPz + ' + tags.pt * TMath::SinH(tags.eta), 2.))'

dataCorr = ROOT.TH1D('dataCorr', '', 60, 60., 120.)
dataRaw = ROOT.TH1D('dataRaw', '', 60, 60., 120.)
dataChain.Draw('tp.mass>>dataCorr', 'probes.pt > 100.', 'goff')
dataChain.Draw(rawMass + '>>dataRaw', 'probes.pt > 100.', 'goff')

canvas = SimpleCanvas()
canvas.legend.setPosition(0.7, 0.7, 0.9, 0.9)
canvas.legend.add('dataCorr',
                  title='Corrected',
                  opt='LF',
                  color=ROOT.kBlue,
                  fstyle=3003,
                  lwidth=2)
canvas.legend.add('dataRaw',
                  title='Raw',
                  opt='LF',
                  color=ROOT.kRed,
                  fstyle=3003,
                  lwidth=2)

canvas.addHistogram(dataCorr)