Example #1
0
def gethisto(tree, formula, binlo, binhi, additionalcut=None):
    nbins = 50
    h = root.TH1D('h', 'h', nbins, binlo, binhi)
    s = Selector()
    s.read_tree(tree, branches=[formula], cut=additionalcut)
    h = s.draw(formula, hbase=h)
    for ib in xrange(1, h.GetNbinsX() + 1):
        v = h.GetBinContent(ib)
        if v == 0:
            h.SetBinContent(ib, 1)
        else:
            h.SetBinContent(ib, 1. / v)
    return h
def infer(tt, ifile, payload, features, h5):

    nent = int(tt.GetEntries())

    if (0 != tt.FindBranch("dnnoutput")):
        tt.SetBranchStatus("dnnoutput", 0)

    output = ifile + "_tmp"
    ofile = ROOT.TFile(output, "RECREATE")

    otree = tt.CloneTree()
    dnnoutput = array.array('f', [-99.0])
    o_dnnoutput = otree.Branch("dnnoutput", AddressOf(treestruct, 'dnnoutput'),
                               "dnnoutput/F")

    model = load_model(h5)
    s = Selector()
    s.read_tree(tt, branches=features)

    for i in range(int(tt.GetEntries())):

        tt.GetEntry(i)

        treestruct.dnnoutput = -99.

        if (i % (1 * nent / 100) == 0):
            sys.stdout.write("\r[" + "=" * int(20 * i / nent) + " " +
                             str(round(100. * i / nent, 0)) + "% done")
            sys.stdout.flush()

#treestruct.mT = 2*1.5*3*3

        x = np.array([float(s[f][i]) for f in features])
        x = x.reshape((1, x.shape[0]))
        #  print model.predict(x)
        treestruct.dnnoutput = model.predict(x)[0, 0]
        print treestruct.dnnoutput

        o_dnnoutput.Fill()

    ofile.Write()
    ofile.Close()
    os.system("mv -f %s %s" % (output, ifile))
Example #3
0
plot = root.CanvasDrawer()
plot.SetTDRStyle()
plot.SetLumi(40000)
root.gStyle.SetPadRightMargin(0.2)
c = root.TCanvas()
plot.SetCanvas(c)

selectors = {}
files = {}
trees = {}
for p in ['QCD', 'VqqHbb']:
    selectors[p] = {}
    files[p] = root.TFile.Open(basedir + '/' + p + '.root')
    trees[p] = files[p].Get('events')
    for cat in ['pass', 'fail']:
        selectors[p][cat] = Selector()
weight = sel.weights['signal'] % 40000

branches = [weight, 'fjMSD[fjHiggsIdx]', 'fjMSD[fjVIdx]']

for p, cats in selectors.iteritems():
    for cat, s in cats.iteritems():
        logger.info('sensitivity.py', '%s %s' % (p, cat))
        print sel.cuts[cat] % (args.cut, args.cut)
        s.read_tree(trees[p],
                    branches=branches,
                    cut=sel.cuts[cat] % (args.cut, args.cut))

hbase = root.TH2D('h', 'h', 10, 30, 300, 10, 30, 300)

Example #4
0
Load('HistogramDrawer')

plot = root.HistogramDrawer()
plot.SetTDRStyle()
plot.AddSqrtSLabel()
plot.AddCMSLabel()
plot.InitLegend()

#cut = 'genJet0Pt>80 && genJet2Pt>30 && trueGenBosonPt>100 && lheHT>100'
cut = '1==1'
weight = 'normalizedWeight'
pt = '0.001*trueGenBosonPt'

s = {}
for a in ['lo_incl', 'nlo']:
    s[a] = Selector()
    f = root.TFile.Open((basedir + 'WJets_' + a + '.root'))
    t = f.Get('events')
    s[a].read_tree(t, branches=[pt, weight], cut=cut)
    print 'done with', a

print 'done reading'


def draw(num, den, hbase, label, color):
    x = '0.001*trueGenBosonPt'
    hnum = s[num].draw([x], weight=weight, hbase=hbase)
    hden = s[den].draw([x], weight=weight, hbase=hbase)
    hnum.Divide(hden)
    hnum.GetXaxis().SetTitle('V p_{T} [TeV]')
    hnum.GetYaxis().SetTitle('Ratio')
Example #5
0
weight = 'ptweight'
branches = ['gen_pt','clf_IsMatched', 'clf_MSD', 'clf_M', 'clf_Pt', 'clf_Tau32SD', 'clf_Tau32', weight]

plot = root.HistogramDrawer()
#plot.Stack(True)
#plot.Ratio(True)
#plot.FixRatio(0.4)
plot.SetTDRStyle()
plot.InitLegend(.2, .68, .65, .9, 2)
plot.DrawMCErrors(True)

sel = {}
for algo in algos:
    sel[algo] = {}
    for proc in procs:
        sel[algo][proc] = Selector()
        sel[algo][proc].read_files([base[algo] + '/' + proc + '.root'],
                                   branches=branches, cut=cuts[proc])



def draw(field, hbase, xlabel):
    h = {algo:{proc:sel[algo][proc].draw(fields=field, weight=weight, hbase=hbase)
               for proc in procs}
         for algo in algos}

    i = 1
    for ip,proc in enumerate(procs):
        for ia,algo in enumerate(algos):
            h_ = h[algo][proc]
            h_.SetLineStyle(ia+1)
Example #6
0
elif args.cut == 'mjj':
    base_cut = tAND(sel.mjj, sel.cuts['signal'])
    label = 'mjj'
weight = sel.weights['signal'] % lumi

plot = root.HistogramDrawer()
plot.SetRatioStyle()
plot.SetLumi(lumi / 1000.)
plot.DrawEmpty(True)
plot.AddCMSLabel()
plot.AddLumiLabel()
#plot.SetAutoRange(False)
plot.InitLegend()
root.gStyle.SetOptStat(0)

s = Selector()
f = root.TFile.Open(infile)
t = f.Get('events')
branches = [
    'pfmet', 'jot12Mass', '1', 'fabs(genTauEta)', 'fabs(genMuonEta)',
    'fabs(genElectronEta)', 'genTauPt', 'genElectronPt', 'genMuonPt', weight
]
s.read_tree(t, branches=branches, cut=base_cut)

t_mask = ((s['genTauPt'] > 1))
accp = ((s['genTauPt'] > 18) & (s['fabs(genTauEta)'] < 2.3))
t_in_mask = t_mask & accp
t_out_mask = t_mask & (~accp)

e_mask = ((s['genTauPt'] < 1) & (s['genElectronPt'] > 1))
accp = ((s['genElectronPt'] > 10) & (s['fabs(genElectronEta)'] < 2.6))
Example #7
0

nBins = 10

f = root.TFile(args.infile)
t = f.Get('events')

h_effs = {}
h_errs = {}

if args.isfake:
    base_cut = 'fj1MSD>110 && fj1MSD<210'
else:
    base_cut = 'fj1MSD>110 && fj1MSD<210 && fj1IsMatched==1 && fj1GenSize<1.44'

s = Selector()

s.read_tree(t, branches=['fj1Pt', 'normalizedWeight'], cut=base_cut)
h_inc = s.draw('fj1Pt', 'normalizedWeight', fbins=(nBins, 250, 1000))

colors = [root.kRed, root.kRed + 3, root.kBlack]
counter = 10
for c, col in zip([0.45, 0.1, -0.5], colors):
    s.read_tree(t,
                branches=['fj1Pt', 'normalizedWeight'],
                cut=tAND(base_cut, 'top_ecf_bdt>%f' % c))
    h_effs[c] = s.draw('fj1Pt', 'normalizedWeight', fbins=(nBins, 250, 1000))
    h_effs[c].Divide(h_inc)
    h_effs[c].SetMaximum(1.4 * get_max(h_effs[c]))
    h_effs[c].GetXaxis().SetTitle('fatjet p_{T} [GeV]')
    h_effs[c].GetYaxis().SetTitle('Efficiency')
Example #8
0
Load('CanvasDrawer')
c = root.CanvasDrawer(800, 600)
c.SetTDRStyle()
c.InitLegend(.2, .83, .93, .93, 2)
c.GetCanvas().SetRightMargin(0.05)
c.GetCanvas().SetTopMargin(0.05)
c.GetCanvas().SetLeftMargin(0.15)
c.GetCanvas().SetBottomMargin(0.15)
c.cd()

args = parse('--outdir', '--proc')

f = root.TFile.Open(flatdir + '/%s.root' % args.proc)
t = f.Get('events')
sel = Selector()

is_top = not (args.proc == 'QCD')
cut = 'gen_pt>200 && fabs(gen_eta)<2.5 && clf_IsMatched'
if is_top:
    cut = tAND(cut, 'gen_size<1.44 && fabs(gen_pdgid)==6')

sel.read_tree(t,
              cut=cut,
              branches=['clf_MSD', 'clf_Tau32', 'clf_Tau32SD', 'ptweight'])

nbins = 5
#hbase = root.TH2D('','',nbins,0,400,50,0.2,1.2)
hbase = root.TH2D('', '', nbins, 0.2, 1, 50, 0, 400)
hbase.GetYaxis().SetTitle('m_{SD} [GeV]')
hbase.GetXaxis().SetTitle('#tau_{32}')
Example #9
0
    payload = json.load(jsonfile)
    weight = payload['weight']
    basedir = payload['base']
    features = payload['features']
    more_features = payload['more_features']
    cut = payload['cut']
    for i, s in enumerate(payload['samples']):
        if s['name'] == args.name:
            samples = s['samples']
            y = i
            break
    else:
        logger.error(sys.argv[0], 'Could not identify process ' + args.name)
        sys.exit(1)

s = Selector()
chain = root.TChain('events')
for sample in samples:
    chain.AddFile(basedir + '/' + sample + '.root')

logger.info(sys.argv[0], 'Reading files for process ' + args.name)
branches = [weight, 'hbbm_dreg']
branches += more_features
branches += [(f, -10, 6) for f in features]
s.read_tree(chain, branches=branches, cut=cut)

N, M = s['hbbjtidx'].shape

hbbidx = np.zeros_like(s[features[0]])
for k in xrange(M):
    hbbidx[np.arange(N), s['hbbjtidx'][:, k]] = 1
Example #10
0
c = root.CanvasDrawer(800, 600)
c.SetTDRStyle()
c.InitLegend(.55,.7,.93,.93)
c.GetCanvas().SetRightMargin(0.05)
c.GetCanvas().SetTopMargin(0.05)
c.GetCanvas().SetLeftMargin(0.15)
c.GetCanvas().SetBottomMargin(0.15)
c.cd()

args = parse('--outdir', '--proc', '--field')

f = {}
f['pf'] = root.TFile.Open(flatdir + '/%s.root'%args.proc)
f['puppi'] = root.TFile.Open(flatdir.replace('nopuppi','ca') + '/%s.root'%args.proc)
t = {k:v.Get('events') for k,v in f.iteritems()}
sel = {k:Selector() for k in f}

is_top = args.proc == 'ZpTT_lo'
cut = 'gen_pt>200 && fabs(gen_eta)<2.5'
if is_top:
    cut = tAND(cut, 'gen_size<1.44 && fabs(gen_pdgid)==6') 

for k,s in sel.iteritems():
    s.read_tree(t[k], cut=cut, 
                branches=['npv', args.field, 'ptweight'])

nbins = 8
if args.field == 'clf_MSD':
    hbase = root.TH2D('','',nbins,1,40,50,0,400)
    hbase.GetYaxis().SetTitle('m_{SD} [GeV]')
else:
Example #11
0
#pt_bins.insert(0, 'Inclusive')

plot = root.HistogramDrawer()
#plot.Stack(True)
#plot.Ratio(True)
#plot.FixRatio(0.4)
plot.SetTDRStyle()
plot.InitLegend(.4, .7, .9, .9, 2)
#plot.InitLegend(.7, .3, .9, .9, 1)
plot.DrawMCErrors(True)
#plot.Logy()
#plot.SetAbsMin(5e-3)

sel = {}
for proc in procs:
    sel[proc] = Selector()
    sel[proc].read_files([flatdir + '/' + proc + '.root'],
                         branches=branches,
                         cut=cuts[proc])

hbase = root.TH1D('', '', 50, 50, 450)


def draw(field, xlabel, proc):
    s = sel[proc]
    inclusive = None
    arg = []
    for i, b in enumerate(pt_bins):
        label = 'p_{T}>%i' % b
        mask = s['gen_pt'] > b
        h = s.draw(fields=field, weight=weight, hbase=hbase, mask=mask)
Example #12
0
from PandaCore.Tools.root_interface import Selector

Load('CanvasDrawer')
c = root.CanvasDrawer(800, 600)
c.SetTDRStyle()
c.GetCanvas().SetRightMargin(0.125)
c.GetCanvas().SetTopMargin(0.05)
c.GetCanvas().SetLeftMargin(0.13)
c.GetCanvas().SetBottomMargin(0.15)
c.cd()

args = parse('--outdir')

f = root.TFile.Open(flatdir + '/Top.root')
t = f.Get('events')
s = Selector()

s.read_tree(t,
            branches=['ptweight', 'gen_pt', 'TMath::Sqrt(gen_size)'],
            cut='fabs(gen_eta)<2.5')

max_x = 500
max_y = 3.14159
hbase = root.TH2D('', '', 50, 50, max_x, 50, 0, max_y)
h = s.draw(fields=['gen_pt', 'TMath::Sqrt(gen_size)'],
           hbase=hbase,
           weight='ptweight')
h.GetXaxis().SetTitle('Top p_{T} [GeV]')
h.GetYaxis().SetTitle("max#DeltaR_{qq}")
h.GetXaxis().SetTitleOffset(1)
h.GetXaxis().SetTitleSize(0.06)
Example #13
0
ptarray = array('f', [30, 50, 80, 120, 160, 200, 250, 300, 500, 1000])
etaarray = array(
    'f',
    [-5, -4, -3, -2.5, -2, -1.5, -1, -0.5, 0, 0.5, 1, 1.5, 2, 2.5, 3, 4, 5])
uncarray = array('f', np.linspace(-30, 30, 200))

f = root.TFile.Open(args.infile)
t = f.Get('events')
ks = t.GetListOfBranches()
pt = args.jet + 'Pt'
rawpt = args.jet + 'RawPt'
eta = 'fabs(' + args.jet + 'Eta)'
corr = '100*(%s-%s)/%s' % (pt, rawpt, rawpt)

s = Selector()
s.read_tree(t, branches=[pt, rawpt, eta, corr], cut='%s>30' % (pt))


def draw(arr, xlabel, xvar, etabins):
    plot.Reset()
    plot.AddLumiLabel()
    plot.GetCanvas().SetLogx('Pt' in xvar)
    plot.cd()

    #  plot.Logy()
    hbase = root.TH2D('', '', len(arr) - 1, arr, len(uncarray) - 1, uncarray)
    h1s = []
    for ie in xrange(len(etabins) - 1):
        mask = np.logical_and(s[eta] > etabins[ie], s[eta] < etabins[ie + 1])
        h2 = s.draw([xvar, corr], hbase=hbase, mask=mask)
Example #14
0
            break
    if (not samples):
        logger.error(sys.argv[0], 'Could not identify process '+args.name)
        sys.exit(1)


print(args.name)
if (y!=0): 
    if ("hadhad" in args.out):  cut+=" && fj_nProngs == 2 && fj_nEles == 0 && fj_nMus == 0"
    elif ("hadel" in args.out): cut+=" && fj_nProngs == 2 && fj_nEles == 1 && fj_nMus == 0"
    elif ("hadmu" in args.out): cut+=" && fj_nProngs == 2 && fj_nEles == 0 && fj_nMus == 1"
elif ("-DYJetsToLL" in args.name):
    cut+=" && fj_nProngs == 2"
print(cut)

s = Selector()
chain = root.TChain('Events')
for sample in samples:
    chain.AddFile(basedir + '/' + sample + "-" + args.tag + '/out.root')
logger.info(sys.argv[0], 'Reading files for process '+args.name)
print("%i total events..."%chain.GetEntries())
for si,slim in enumerate(range(startstep*stepsize,chain.GetEntries(),stepsize)):
    selargs = {"start":slim, "stop":slim+stepsize, "step":1}
    print("\tRunning iteration %i"%(si+startstep))
    #if ("JetHT" in args.name): selargs = {}
    s.read_tree(chain, branches=(features+altfeatures+taufeatures+elecfeatures+muonfeatures+weight+ss), cut=cut, xkwargs=selargs)
    print(s["PF_pt"][:,0])
    X = np.concatenate([np.vstack([s[f].T for f in features]).T,np.vstack([s[f].T for f in altfeatures]).T,np.vstack([s[f].T for f in taufeatures]).T,np.vstack([s[f].T for f in elecfeatures]).T,np.vstack([s[f].T for f in muonfeatures]).T],axis=1)
    W = np.vstack([s[var] for var in weight]).T
    Y = y * np.ones(shape=W.shape[0])
    print(Y)
Example #15
0
plot.AddSqrtSLabel()
plot.SetNormFactor(True)
#plot.SetAutoRange(False)
plot.InitLegend()
root.gStyle.SetOptStat(0)

nBins = 15

f = root.TFile(args.infile)
t = f.Get('events')

base_cut = 'partonPt>300 && partonPt<470 && fabs(partonEta)<2.4 && partonIsReco==1'
if not args.isfake:
    base_cut = tAND(base_cut, 'partonSize<1.44')

s = Selector()

s.read_tree(t, branches=['fj1MSD', '1'], cut=base_cut)
h_inc = s.draw('fj1MSD', '1', fbins=(nBins, 40, 340))

s.read_tree(t,
            branches=['fj1MSD', '1'],
            cut=tAND(base_cut, 'top_ecf_bdt>0.43'))
h_bdt = s.draw('fj1MSD', '1', fbins=(nBins, 40, 340))

s.read_tree(t, branches=['fj1MSD', '1'], cut=tAND(base_cut, 'fj1Tau32SD<0.43'))
h_tau = s.draw('fj1MSD', '1', fbins=(nBins, 40, 340))

v = 'fj1MSD'
label = 'm_{SD} [GeV]'
Example #16
0
    features = payload['features']

f = root.TFile(args.ifile)
t = f.Get('events')

treestruct = TreeStruct()
nent = int(t.GetEntries())

#if t.FindBranch(args.bname):
#  t.SetBranchStatus(args.bname, 0)

output = args.ifile + "_tmp"
ofile = root.TFile(output, "RECREATE")
otree = t.CloneTree()

s = Selector()
s.read_tree(t, branches=features)

model = load_model(args.h5)
print 'Loaded model...'

val = array('f', [-1])
o_val = otree.Branch(args.bname, val, args.bname + '/F')

for i in range(t.GetEntriesFast()):
    val[0] = -1
    x = np.array([float(s[f][i]) for f in features])
    x = x.reshape((1, x.shape[0]))
    #  print model.predict(x)
    val[0] = model.predict(x)[0, 0]
    o_val.Fill()
Example #17
0
root.gROOT.ProcessLine(
    '#include "PandaAnalysis/Utilities/src/PackingHelperStandalone.cc"')

load('PandaTreeObjects')
load('PandaCoreDrawers')
load('PandaAnalysisUtilities')

f = root.TFile.Open(args.infile)
t = f.Get('events')

PFCand = root.panda.PFCand

hbase = root.TH1D('', '', 20, -5, 5)

nmax = root.std.numeric_limits('Short_t').max()
s = Selector()
cut = 'pa::PHS::up(pfCandidates.packedPt)>5'
eta = 'pfCandidates.packedEta * %f / %i' % (6, nmax)
ptype = 'pfCandidates.ptype'
s.read_tree(t, branches=[(eta, -9, 200), (ptype, -100, 200)], cut=cut)
s.flatten()


def get_hist(*ptypes):
    masks = [s.data[ptype] == p for p in ptypes]
    mask = np.zeros_like(s.data[eta]).astype(bool)
    for p in ptypes:
        mask = np.logical_or(mask, s.data[ptype] == p)
    print ptypes
    print s.data[eta][mask].min(), s.data[eta][mask].max()
    h = s.draw(eta, hbase=hbase, mask=mask)
Example #18
0
    plot.InitLegend()
    root.gStyle.SetOptStat(0)

binning = (40, 450, 1200)

n_partons = {
        'Top' : 3,
        'QCD' : 1,
        'Higgs' : 2,
        'W' : 2,
        }

f = root.TFile(basedir + '/' + args.proc + '.root')
t = f.Get('events')

s = Selector()

s.read_tree(t, branches = ['fj1RawPt'], cut = 'fj1RawPt>450 && fj1RawPt<1200')

h = s.draw('fj1RawPt', fbins = binning)

h_inv = h.Clone()
for ib in xrange(1, h_inv.GetNbinsX()+1):
    if h.GetBinContent(ib):
      h_inv.SetBinContent(ib, 1)
      h_inv.SetBinError(ib, 0)

h_inv.Divide(h)

for ib in xrange(1, h_inv.GetNbinsX()+1):
    # print ib, h.GetBinContent(ib), h_inv.GetBinContent(ib)
Example #19
0
nBins = 5

f = root.TFile(args.infile)
t = f.Get('events')

h_effs = {}
h_errs = {}

base_base_cut = 'partonPt>300 && partonPt<470 && fabs(partonEta)<2.4'

if args.isfake:
    base_cut = tAND(base_base_cut, 'partonIsReco==1')
else:
    base_cut = tAND(base_base_cut, 'partonIsReco==1 && partonSize<1.44')

s = Selector()

s.read_tree(t, branches=['partonPt', 'npv', '1'], cut=base_base_cut)
h_inc = {
    'partonPt': s.draw('partonPt', '1', fbins=(nBins, 300, 470)),
    'npv': s.draw('npv', '1', fbins=(nBins, 1, 41))
}

s.read_tree(t,
            branches=['partonPt', 'npv', '1'],
            cut=tAND(base_cut, 'top_ecf_bdt>0.43 && fj1MSD>110 && fj1MSD<210'))
h_bdt = {
    'partonPt': s.draw('partonPt', '1', fbins=(nBins, 300, 470)),
    'npv': s.draw('npv', '1', fbins=(nBins, 1, 41))
}
Example #20
0
plot = root.CanvasDrawer()
plot.SetTDRStyle()
plot.AddPlotLabel(
    args.f.replace('_', ' ').replace('AllEras', 'Run2016*'), .18, .85, False,
    42, .04)
if args.vbf:
    plot.AddPlotLabel('#Delta#phi_{jj}<1.5, #Delta#eta_{jj}>1', .18, .72,
                      False, 42, .04)
elif args.spike:
    plot.AddPlotLabel('|#phi-2.01|>0.4 or |#eta+2.81|>0.4', .18, .78, False,
                      42, .04)
root.gStyle.SetPadRightMargin(0.2)
c = root.TCanvas()
plot.SetCanvas(c)

s = Selector()

infile = basedir + args.f + '.root'
f = root.TFile.Open(infile)
t = f.Get('events')


def fn(hbase, branch_tmpl, xtitle, ytitle, postfix, save=False):
    hnum = hbase.Clone()
    hden = hbase.Clone()
    for iJ in xrange(3):
        branches = [x.format(iJ) for x in branch_tmpl]
        s.read_tree(t, branches=branches, cut=cut.format(iJ))
        hden.Add(s.draw(branches, hbase=hbase))
        s.read_tree(t, branches=branches, cut=tAND(cut, sigcut).format(iJ))
        hnum.Add(s.draw(branches, hbase=hbase))
Example #21
0
  base_cut = sel.cuts['dimuon']
  metnomu = 'pfUZmag'
base_cut = tAND(base_cut, '(trigger&8)!=0')
# base_cut = remove_cut(base_cut, 'pfUWmag')
# base_cut = tAND(base_cut, 'pfUWmag>180')
base_cut = base_cut.replace('pfUWmag>250', 'pfUWmag>200')

plot = root.GraphAsymmErrDrawer()
plot.SetTDRStyle()
plot.SetLumi(lumi/1000.)
plot.DrawEmpty(True)
#plot.SetAutoRange(False)
root.gStyle.SetOptStat(0)


s = Selector()
f = root.TFile.Open(infile); t = f.Get('events')
branches = [metnomu, 'jot12Mass', 'jetPt[0]', 'jetPt[0]+jetPt[1]', 'fabs(jotEta[0])', 'trigger&1', 'fabs(jotEta[1])', 'barrelHT', 'barrelHTMiss']
s.read_tree(t, branches = branches, cut = base_cut)

triggered = ( s['trigger&1'] != 0 )

j1 = (s['fabs(jotEta[0])'] < 3)
j2 = (s['fabs(jotEta[1])'] < 3)
bb = (j1 & j2).flatten()
bf = (j1 ^ j2).flatten()
ff = ~(j1 | j2).flatten()
bins = [200, 225, 250, 275, 350, 400, 450, 500, 550, 600, 650,  750]
ratios_to_plot = {
  metnomu : (bins,'U [GeV]'),
  'jot12Mass' : ([200, 400, 600, 800, 1000, 1250, 1500, 1750, 2000, 2500, 3500, 5000],'m_{jj} [GeV]'),
Example #22
0
etaarray = array(
    'f',
    [-5, -4, -3, -2.5, -2, -1.5, -1, -0.5, 0, 0.5, 1, 1.5, 2, 2.5, 3, 4, 5])
uncarray = array('f', np.linspace(0, 0.1, 200))

f = root.TFile.Open(args.infile)
t = f.Get('events')
ks = t.GetListOfBranches()
pt = args.jet + 'Pt'
pt_ = pt + '_'
uncs = []
for k in ks:
    if k.GetName().startswith(pt_) and k.GetName().endswith('Up'):
        uncs.append(k.GetName().replace(pt_, '')[:-2])

s = Selector()
branches = {u: 'fabs(%s-%s%sUp)/%s' % (pt, pt_, u, pt) for u in uncs}
all_branches = [pt, args.jet + 'Eta'] + branches.values()
s.read_tree(t, branches=all_branches, cut='%s>30' % (pt))

c2 = root.TCanvas()

majors = [
    'Absolute', 'Relative', 'PileUp', 'SinglePion', 'Flavor', 'Fragmentation',
    'Time', 'Total'
]


def draw(arr, xlabel, xvar):
    plot.Reset()
    plot.AddLumiLabel()
Example #23
0
#!/usr/bin/env python

from PandaCore.Tools.script import * 
import numpy as np
from PandaCore.Tools.root_interface import Selector 

baseDir = getenv('PANDA_FLATDIR')+'/' 
args = parse('--outdir', ('--cut', {'default':'1==1'}))

Load('PandaCoreDrawers')
plot = root.HistogramDrawer()
plot.SetTDRStyle()
plot.InitLegend()
# plot.Logy(True)

s = Selector()
f = root.TFile.Open(baseDir + '/ZtoNuNu.root')
t = f.Get('events')
s.read_tree(t, 
            branches=['trueGenBosonPt', 
                      'normalizedWeight',
                      'normalizedWeight*sf_qcdV', 
                      'normalizedWeight*sf_qcdV*sf_ewkV'], 
            cut='trueGenBosonPt>160')

ptbins = (10,160,1600) 
hlo = s.draw('trueGenBosonPt', weight='normalizedWeight', fbins=ptbins)
hqcd = s.draw('trueGenBosonPt', weight='normalizedWeight*sf_qcdV', fbins=ptbins)
hewk = s.draw('trueGenBosonPt', weight='normalizedWeight*sf_qcdV*sf_ewkV', fbins=ptbins)

for h in [hewk, hqcd, hlo]:
Example #24
0
from PandaCore.Tools.root_interface import Selector
from math import sqrt
Load('CanvasDrawer')
root.gROOT.SetBatch()
root.gStyle.SetNumberContours(999)
root.gStyle.SetPalette(root.kCool)

SMOOTH = True

plot = root.CanvasDrawer()
plot.SetTDRStyle()
root.gStyle.SetPadRightMargin(0.2)
c = root.TCanvas()
plot.SetCanvas(c)

s = Selector()
s_nlo = Selector()

cut = 'trueGenBosonPt>50 && lheHT>100'
if args.proc == 'WJets':
    cut = tAND(cut, 'genBosonMass>70 && genBosonMass<90')
else:
    cut = tAND(cut, 'genBosonMass>80 && genBosonMass<100')

branches = ['normalizedWeight', '0.001*trueGenBosonPt', '0.001*lheHT']

infile = basedir + args.proc + '.root'
f = root.TFile.Open(infile)
t = f.Get('events')
print 'LO'
s.read_tree(t, branches=branches, cut=cut)
Example #25
0
#!/usr/bin/env python

from PandaCore.Tools.script import *
from PandaCore.Tools.root_interface import Selector
import numpy as np
from array import array

Load('PandaCoreTools')
args = parse('--infile')

bins = array('f', np.linspace(250, 1200, 50))
h = root.TH1D('h', 'h', len(bins) - 1, bins)
s = Selector()
f = root.TFile.Open(args.infile, 'update')
t = f.Get('events')
s.read_tree(t, branches=['gen_pt'], cut='clf_IsMatched==1')
h = s.draw(['gen_pt'], hbase=h)

norm = h.Integral() / (len(bins) - 1)
for ib in xrange(1, h.GetNbinsX() + 1):
    val = h.GetBinContent(ib)
    if val > 0:
        h.SetBinContent(ib, norm / val)

ba = root.H1BranchAdder()
ba.setH(h)
ba.formulaX = 'gen_pt'
ba.newBranchName = 'weight'

ba.addBranch(t)
Example #26
0
    payload = json.load(jsonfile)
    weight = payload['weight']
    basedir = payload['base']
    features = payload['features']
    cut = payload['cut']
    substructure_vars = payload['substructure_vars']
    for i,s in enumerate(payload['samples']):
        if s['name'] == args.name:
            samples = s['samples']
            y = i
            break
    else:
        logger.error(sys.argv[0], 'Could not identify process '+args.name)
        sys.exit(1)

s = Selector()
chain = root.TChain('Events')
for sample in samples:
    chain.AddFile(basedir + '/' + sample + '.root')

logger.info(sys.argv[0], 'Reading files for process '+args.name)
s.read_tree(chain, branches=(features+substructure_vars+[weight]), cut=cut)
#s.read_tree(chain, branches=(features+[weight]), cut=cut)
#print s['fj_cpf_pt'].T[0:30,:].shape
sortinds = s['fj_cpf_pt'].T[0:30,:].argsort(axis=0)
print s['fj_cpf_pt'].T[0:30,:][:,sortinds[::-1]]
print sortinds	
X = np.vstack([s[f].T[0:30,:] for f in features]).T 
W = s[weight]
#W *= 1000 / W.sum()
Y = y * np.ones(shape=W.shape)
Example #27
0
argv=[]

import ROOT as root
from PandaCore.Tools.Load import Load
from PandaCore.Tools.Misc import *
from PandaCore.Tools.root_interface import Selector
Load('HistogramDrawer')

lumi=35900
import PandaAnalysis.VBF.PandaSelection as sel 
cut = 'jot1Eta*jot2Eta<0 && jot1Pt>80 && jot2Pt>40 && fabs(jot1Eta)<4.7 && fabs(jot2Eta)<4.7 && nTau==0 && jetNMBtags==0 && jot1VBFID==1 && dphipfmet>0.5'
weight = 'normalizedWeight'



s = Selector()
f = root.TFile.Open(infile); t = f.Get('events')
branches = ['pfmet', 'jot12Mass', 
            weight]
s.read_tree(t, branches = branches, cut = cut)

met_bins = array('f',[50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 220, 240, 260, 280, 300, 340, 380, 420, 460, 500, 550, 600, 650, 700, 750, 800, 900, 1000])
mjj_bins = array('f',[200, 400, 600, 900, 1200, 1500, 2000, 2750, 3500, 5000])
h = root.TH2F('h','h',len(mjj_bins)-1, mjj_bins, len(met_bins)-1, met_bins)
h.GetXaxis().SetTitle('m_{jj} [GeV]')
h.GetYaxis().SetTitle('E_{T}^{miss} [GeV]')
h = s.draw(fields=['jot12Mass', 'pfmet'], weight=weight, hbase=h)

plot = root.CanvasDrawer()
plot.SetTDRStyle()
root.gStyle.SetPadRightMargin(0.15)
binning = (40, 450, 1200)

n_partons = {
    'Top_lo': 3,
    'Top': 3,
    'QCD': 1,
    'Higgs': 2,
    'W': 2,
}
n_parton = n_partons[args.proc]

f = root.TFile(basedir + '/' + args.proc + '.root')
t = f.Get('events')

s = Selector()

s.read_tree(t,
            branches=['genFatJetPt'],
            cut='genFatJetPt>450 && genFatJetPt<1200 && genFatJetNProngs==%i' %
            n_parton)

h = s.draw('genFatJetPt', fbins=binning)

h_inv = h.Clone()
for ib in xrange(1, h_inv.GetNbinsX() + 1):
    if h.GetBinContent(ib):
        h_inv.SetBinContent(ib, 1)
        h_inv.SetBinError(ib, 0)

h_inv.Divide(h)
Example #29
0
Load('CanvasDrawer')
root.gROOT.SetBatch()
root.gStyle.SetNumberContours(999)
root.gStyle.SetPalette(root.kCool)

SMOOTH = True

plot = root.CanvasDrawer()
plot.SetTDRStyle()
plot.SetLumi(40000)
root.gStyle.SetPadRightMargin(0.2)
c = root.TCanvas()
c.SetLogz()
plot.SetCanvas(c)

s = Selector()
f = root.TFile.Open(basedir + '/' + 'VqqHbb' + '.root')
t = f.Get('events')
weight = sel.weights['signal'] % 40000

branches = [weight]
for b in ['Eta', 'Phi']:
    for i, j in [('fjHiggsIdx', 'H'), ('fjVIdx', 'V')]:
        branches.append('fjQ[%s]' % i)
        branches.append('fj%s[%s]' % (b, i))
        branches.append('gen%s%s' % (j, b))
        branches.append('fj%s[%s] - gen%s%s' % (b, i, j, b))

s.read_tree(t, branches=branches, cut=tAND(sel.cuts['signal'], args.cut))

hbase = root.TH2D('h', 'h', 20, -2.5, 2.5, 20, -3.14159, 3.14159)