예제 #1
0
    def draw_legend(self, dilepton, cumulative, log_x):
        # Legend placement coordinates and sizes depend on factors set
        # elsewhere, too, so this is fragile.
#        if dilepton == 'MuonsPlusMuonsMinus' and cumulative:
        if dilepton == '' and cumulative:
            legend = ROOT.TLegend(0.60, 0.69, 0.86, 0.88)
        elif log_x:
            legend = ROOT.TLegend(0.60, 0.55, 0.86, 0.88)
        else:
            if self.join_dy_and_jets:
                legend = ROOT.TLegend(0.60, 0.50, 0.86, 0.88)
            else:
                legend = ROOT.TLegend(0.60, 0.69, 0.86, 0.88)
                #legend = ROOT.TLegend(0.60, 0.60, 0.86, 0.88)

        legend.SetFillColor(0)
        legend.SetBorderSize(0)

        # Add an entry for the data points.
#        entry = legend.AddEntry('data_marker', 'Data', 'EP')
#        entry.SetMarkerStyle(20)
#        entry.SetMarkerSize(0.8)
#        entry.SetMarkerColor(ROOT.kBlack)

        # Add entries for the MC samples to the legend, respecting
        # join groups (i.e. don't add the same nice-name twice).
        legend_already = set()
        for sample in reversed(self.samples):
            if sample.is_zprime and not self.should_draw_zprime(dilepton):
                continue

            nice_name = sample.nice_name

            join_name = self.get_join_name(sample.name)
            if join_name is not None:
                if join_name in legend_already:
                    continue
                else:
                    legend_already.add(join_name)
                    nice_name = join_name
            legend.AddEntry(sample.histogram, nice_name, 'F') # Gets the color and fill style from the histogram.

        legend.SetTextSize(0.03)
        legend.Draw('same')
        ## "EP" in TLegend::AddEntry doesn't seem to work, so draw the error bar by hand ##for data !
#        ll = ROOT.TLine()
#        if log_x:
#            ll.DrawLineNDC(0.632, 0.845, 0.632, 0.875)
#        else:
#            ll.DrawLineNDC(0.632, 0.835, 0.632, 0.875)

        return legend
예제 #2
0
def doit(fn, mass_name, dir_name, tree_name, cut):
    f = ROOT.TFile(fn)
    t = f.Get(dir_name).Get(tree_name)
    rlem = detree(t, 'run:lumi:event:' + mass_name, cut, lambda x:
                  (int(x[0]), int(x[1]), int(x[2]), float(x[3])))
    me = defaultdict(list)
    for r, l, e, m in rlem:
        me[(r, l, e)].append(m)
    return me
#!/usr/bin/env python

#####run with python GetPrescalesAnalyzer.py zp2mu_histos_prescale.root Mu24eta2p1
import os, sys
from collections import defaultdict
from pprint import pprint
from SUSYBSMAnalysis.Zprime2muAnalysis.roottools import ROOT, detree

print sys.argv

f = ROOT.TFile(sys.argv[1])
t = f.Get('%s/t' % sys.argv[2])
print t.GetEntriesFast(), 'entries in tree'

de = defaultdict(list)
dp = defaultdict(list)

for (run, lumi, event, l1, hlt) in detree(t, 'run:lumi:event:l1:hlt'):
    de[(run, lumi)].append(event)
    dp[(run, lumi)].append((l1, hlt))

for k, v in de.iteritems():
    assert len(v) == len(set(v))

for k, v in dp.iteritems():
    if len(set(v)) != 1:
        print 'run/LS %s with %i events has multiple prescale values: %s' % (
            k, len(de[k]), sorted(set(v)))

lscounts = defaultdict(int)
evcounts = defaultdict(int)
예제 #4
0
#!/usr/bin/env python

import os
from SUSYBSMAnalysis.Zprime2muAnalysis.roottools import ROOT

path = 'data/Run2012MuonsOnly/ana_datamc_data.root'
tmp_fn = 'micro_ntuple.temp.txt'
branch_spec = 'vertex_m'
cut = 'OurSel2012'

f = ROOT.TFile(path)
t = f.SimpleNtupler.Get('t')
t.GetPlayer().SetScanRedirect(True)
t.GetPlayer().SetScanFileName(tmp_fn)
t.Scan(branch_spec, cut)
t.GetPlayer().SetScanRedirect(False)
f.Close()

lines = [
    line.split(' *')[1:] for line in open(tmp_fn).readlines()
    if ' * ' in line and 'Row' not in line
]
lines = ['\t'.join(y.strip() for y in x) for x in lines]
open(tmp_fn, 'wt').write('\n'.join(lines))

f = ROOT.TFile(path.replace('.root', '.microtuple.root'), 'CREATE')
t = ROOT.TTree('t', '')
t.ReadFile(tmp_fn, branch_spec)
f.Write()
f.Close()
예제 #5
0
        h = h.Rebin(len(bins) - 1, h.GetName() + '_rebin', bins)
    if roundto is not None:
        for i in xrange(1, h.GetNbinsX() + 1):
            width = h.GetBinWidth(i)
            if width > roundto:
                h.SetBinContent(i, h.GetBinContent(i) * roundto / width)
    return h


#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#

# First mu+mu-, differential and cumulative.
for cumulative in (False, True):
    histos = {}
    for sample in samples:
        f = ROOT.TFile(mumu_mc_fn_base % sample.name)
        h = f.Histosstartup.Get(mumu_histogram).Clone()
        if mumu_rebin_variable and not cumulative:
            h = variable_rebin_and_normalize(h, mumu_rebin_variable,
                                             mumu_rebin_roundto)
        else:
            h.Rebin(mumu_rebin_factor)
        h.Scale(sample.partial_weight * mumu_scale)
        if cumulative:
            h = cumulative_histogram(h)
            h.SetName(h.GetName().replace('_cumulative_ge', ''))
        histos[sample.name] = h

    f = ROOT.TFile(mumu_data_fn)
    dataHist = f.Histosstartup.Get(mumu_histogram).Clone('data')
    if mumu_rebin_variable and not cumulative:
예제 #6
0
# cut='dil_chosen==0 && fabs(lep_eta[0])<2.4 && fabs(lep_eta[1])<2.4 && GoodDataRan && GoodVtx && lep_pt[0]>53. && lep_pt[1]>53. && lep_isTrackerMuon[0]==1 && lep_isTrackerMuon[1]==1 && lep_isGlobalMuon[0]==1 && lep_isGlobalMuon[1]==1 && fabs(lep_dB[0]) < 0.2 && fabs(lep_dB[1]) < 0.2 && ( lep_numberOfMatchedStations[0] > 1 || (lep_numberOfMatchedStations[0] == 1 && !(lep_stationMask[0] == 1 || lep_stationMask[0] == 16)) || (lep_numberOfMatchedStations[0] == 1 && (lep_stationMask[0] == 1 || lep_stationMask[0] == 16) && lep_numberOfMatchedRPCLayers[0] > 2))  && (lep_numberOfMatchedStations[1] > 1 || (lep_numberOfMatchedStations[1] == 1 && !(lep_stationMask[1] == 1 || lep_stationMask[1] == 16)) || (lep_numberOfMatchedStations[1] == 1 && (lep_stationMask[1] == 1 || lep_stationMask[1] == 16) && lep_numberOfMatchedRPCLayers[1] > 2)) && lep_glb_numberOfValidMuonHits[0]>0 && lep_glb_numberOfValidMuonHits[1]>0 && lep_glb_numberOfValidPixelHits[0]>=1 && lep_glb_numberOfValidPixelHits[1]>=1 && lep_glb_numberOfValidTrackerLayers[0]>5 && lep_glb_numberOfValidTrackerLayers[1]>5 && lep_sumPt[0]/lep_tk_pt[0]<0.10 && lep_sumPt[1]/lep_tk_pt[1]<0.10 && lep_pt_err[0]/lep_pt[0]<0.3 && lep_pt_err[1]/lep_pt[1]<0.3 && cos_angle>-0.9998 && lep_id[0]*lep_id[1]<0 && (lep_triggerMatchPt[0]>50 || lep_triggerMatchPt[1]>50) && vertex_chi2 < 20 && vertex_m > 120 && vertex_m < 400'
# cut='dil_chosen==0 && fabs(lep_eta[0])<2.4 && fabs(lep_eta[1])<2.4 && GoodDataRan && GoodVtx && lep_pt[0]>53. && lep_pt[1]>53. && lep_isTrackerMuon[0]==1 && lep_isTrackerMuon[1]==1 && lep_isGlobalMuon[0]==1 && lep_isGlobalMuon[1]==1 && fabs(lep_dB[0]) < 0.2 && fabs(lep_dB[1]) < 0.2 && ( lep_numberOfMatchedStations[0] > 1 || (lep_numberOfMatchedStations[0] == 1 && !(lep_stationMask[0] == 1 || lep_stationMask[0] == 16)) || (lep_numberOfMatchedStations[0] == 1 && (lep_stationMask[0] == 1 || lep_stationMask[0] == 16) && lep_numberOfMatchedRPCLayers[0] > 2))  && (lep_numberOfMatchedStations[1] > 1 || (lep_numberOfMatchedStations[1] == 1 && !(lep_stationMask[1] == 1 || lep_stationMask[1] == 16)) || (lep_numberOfMatchedStations[1] == 1 && (lep_stationMask[1] == 1 || lep_stationMask[1] == 16) && lep_numberOfMatchedRPCLayers[1] > 2)) && lep_glb_numberOfValidMuonHits[0]>0 && lep_glb_numberOfValidMuonHits[1]>0 && lep_glb_numberOfValidPixelHits[0]>=1 && lep_glb_numberOfValidPixelHits[1]>=1 && lep_glb_numberOfValidTrackerLayers[0]>5 && lep_glb_numberOfValidTrackerLayers[1]>5 && lep_sumPt[0]/lep_tk_pt[0]<0.10 && lep_sumPt[1]/lep_tk_pt[1]<0.10 && lep_pt_err[0]/lep_pt[0]<0.3 && lep_pt_err[1]/lep_pt[1]<0.3 && cos_angle>-0.9998 && lep_id[0]*lep_id[1]<0 && (lep_triggerMatchPt[0]>50 || lep_triggerMatchPt[1]>50) && vertex_chi2 < 20 && vertex_m > 400 && vertex_m < 600'
# cut='dil_chosen==0 && fabs(lep_eta[0])<2.4 && fabs(lep_eta[1])<2.4 && GoodDataRan && GoodVtx && lep_pt[0]>53. && lep_pt[1]>53. && lep_isTrackerMuon[0]==1 && lep_isTrackerMuon[1]==1 && lep_isGlobalMuon[0]==1 && lep_isGlobalMuon[1]==1 && fabs(lep_dB[0]) < 0.2 && fabs(lep_dB[1]) < 0.2 && ( lep_numberOfMatchedStations[0] > 1 || (lep_numberOfMatchedStations[0] == 1 && !(lep_stationMask[0] == 1 || lep_stationMask[0] == 16)) || (lep_numberOfMatchedStations[0] == 1 && (lep_stationMask[0] == 1 || lep_stationMask[0] == 16) && lep_numberOfMatchedRPCLayers[0] > 2))  && (lep_numberOfMatchedStations[1] > 1 || (lep_numberOfMatchedStations[1] == 1 && !(lep_stationMask[1] == 1 || lep_stationMask[1] == 16)) || (lep_numberOfMatchedStations[1] == 1 && (lep_stationMask[1] == 1 || lep_stationMask[1] == 16) && lep_numberOfMatchedRPCLayers[1] > 2)) && lep_glb_numberOfValidMuonHits[0]>0 && lep_glb_numberOfValidMuonHits[1]>0 && lep_glb_numberOfValidPixelHits[0]>=1 && lep_glb_numberOfValidPixelHits[1]>=1 && lep_glb_numberOfValidTrackerLayers[0]>5 && lep_glb_numberOfValidTrackerLayers[1]>5 && lep_sumPt[0]/lep_tk_pt[0]<0.10 && lep_sumPt[1]/lep_tk_pt[1]<0.10 && lep_pt_err[0]/lep_pt[0]<0.3 && lep_pt_err[1]/lep_pt[1]<0.3 && cos_angle>-0.9998 && lep_id[0]*lep_id[1]<0 && (lep_triggerMatchPt[0]>50 || lep_triggerMatchPt[1]>50) && vertex_chi2 < 20 && vertex_m > 600 && vertex_m < 900'
# cut='dil_chosen==0 && fabs(lep_eta[0])<2.4 && fabs(lep_eta[1])<2.4 && GoodDataRan && GoodVtx && lep_pt[0]>53. && lep_pt[1]>53. && lep_isTrackerMuon[0]==1 && lep_isTrackerMuon[1]==1 && lep_isGlobalMuon[0]==1 && lep_isGlobalMuon[1]==1 && fabs(lep_dB[0]) < 0.2 && fabs(lep_dB[1]) < 0.2 && ( lep_numberOfMatchedStations[0] > 1 || (lep_numberOfMatchedStations[0] == 1 && !(lep_stationMask[0] == 1 || lep_stationMask[0] == 16)) || (lep_numberOfMatchedStations[0] == 1 && (lep_stationMask[0] == 1 || lep_stationMask[0] == 16) && lep_numberOfMatchedRPCLayers[0] > 2))  && (lep_numberOfMatchedStations[1] > 1 || (lep_numberOfMatchedStations[1] == 1 && !(lep_stationMask[1] == 1 || lep_stationMask[1] == 16)) || (lep_numberOfMatchedStations[1] == 1 && (lep_stationMask[1] == 1 || lep_stationMask[1] == 16) && lep_numberOfMatchedRPCLayers[1] > 2)) && lep_glb_numberOfValidMuonHits[0]>0 && lep_glb_numberOfValidMuonHits[1]>0 && lep_glb_numberOfValidPixelHits[0]>=1 && lep_glb_numberOfValidPixelHits[1]>=1 && lep_glb_numberOfValidTrackerLayers[0]>5 && lep_glb_numberOfValidTrackerLayers[1]>5 && lep_sumPt[0]/lep_tk_pt[0]<0.10 && lep_sumPt[1]/lep_tk_pt[1]<0.10 && lep_pt_err[0]/lep_pt[0]<0.3 && lep_pt_err[1]/lep_pt[1]<0.3 && cos_angle>-0.9998 && lep_id[0]*lep_id[1]<0 && (lep_triggerMatchPt[0]>50 || lep_triggerMatchPt[1]>50) && vertex_chi2 < 20 && vertex_m > 900 && vertex_m < 1300'
# cut='dil_chosen==0 && fabs(lep_eta[0])<2.4 && fabs(lep_eta[1])<2.4 && GoodDataRan && GoodVtx && lep_pt[0]>53. && lep_pt[1]>53. && lep_isTrackerMuon[0]==1 && lep_isTrackerMuon[1]==1 && lep_isGlobalMuon[0]==1 && lep_isGlobalMuon[1]==1 && fabs(lep_dB[0]) < 0.2 && fabs(lep_dB[1]) < 0.2 && ( lep_numberOfMatchedStations[0] > 1 || (lep_numberOfMatchedStations[0] == 1 && !(lep_stationMask[0] == 1 || lep_stationMask[0] == 16)) || (lep_numberOfMatchedStations[0] == 1 && (lep_stationMask[0] == 1 || lep_stationMask[0] == 16) && lep_numberOfMatchedRPCLayers[0] > 2))  && (lep_numberOfMatchedStations[1] > 1 || (lep_numberOfMatchedStations[1] == 1 && !(lep_stationMask[1] == 1 || lep_stationMask[1] == 16)) || (lep_numberOfMatchedStations[1] == 1 && (lep_stationMask[1] == 1 || lep_stationMask[1] == 16) && lep_numberOfMatchedRPCLayers[1] > 2)) && lep_glb_numberOfValidMuonHits[0]>0 && lep_glb_numberOfValidMuonHits[1]>0 && lep_glb_numberOfValidPixelHits[0]>=1 && lep_glb_numberOfValidPixelHits[1]>=1 && lep_glb_numberOfValidTrackerLayers[0]>5 && lep_glb_numberOfValidTrackerLayers[1]>5 && lep_sumPt[0]/lep_tk_pt[0]<0.10 && lep_sumPt[1]/lep_tk_pt[1]<0.10 && lep_pt_err[0]/lep_pt[0]<0.3 && lep_pt_err[1]/lep_pt[1]<0.3 && cos_angle>-0.9998 && lep_id[0]*lep_id[1]<0 && (lep_triggerMatchPt[0]>50 || lep_triggerMatchPt[1]>50) && vertex_chi2 < 20 && vertex_m > 1300 && vertex_m < 1800'
# cut='dil_chosen==0 && fabs(lep_eta[0])<2.4 && fabs(lep_eta[1])<2.4 && GoodDataRan && GoodVtx && lep_pt[0]>53. && lep_pt[1]>53. && lep_isTrackerMuon[0]==1 && lep_isTrackerMuon[1]==1 && lep_isGlobalMuon[0]==1 && lep_isGlobalMuon[1]==1 && fabs(lep_dB[0]) < 0.2 && fabs(lep_dB[1]) < 0.2 && ( lep_numberOfMatchedStations[0] > 1 || (lep_numberOfMatchedStations[0] == 1 && !(lep_stationMask[0] == 1 || lep_stationMask[0] == 16)) || (lep_numberOfMatchedStations[0] == 1 && (lep_stationMask[0] == 1 || lep_stationMask[0] == 16) && lep_numberOfMatchedRPCLayers[0] > 2))  && (lep_numberOfMatchedStations[1] > 1 || (lep_numberOfMatchedStations[1] == 1 && !(lep_stationMask[1] == 1 || lep_stationMask[1] == 16)) || (lep_numberOfMatchedStations[1] == 1 && (lep_stationMask[1] == 1 || lep_stationMask[1] == 16) && lep_numberOfMatchedRPCLayers[1] > 2)) && lep_glb_numberOfValidMuonHits[0]>0 && lep_glb_numberOfValidMuonHits[1]>0 && lep_glb_numberOfValidPixelHits[0]>=1 && lep_glb_numberOfValidPixelHits[1]>=1 && lep_glb_numberOfValidTrackerLayers[0]>5 && lep_glb_numberOfValidTrackerLayers[1]>5 && lep_sumPt[0]/lep_tk_pt[0]<0.10 && lep_sumPt[1]/lep_tk_pt[1]<0.10 && lep_pt_err[0]/lep_pt[0]<0.3 && lep_pt_err[1]/lep_pt[1]<0.3 && cos_angle>-0.9998 && lep_id[0]*lep_id[1]<0 && (lep_triggerMatchPt[0]>50 || lep_triggerMatchPt[1]>50) && vertex_chi2 < 20 && vertex_m > 1800 && vertex_m < 8000'
# cut='dil_chosen==0 && fabs(lep_eta[0])<2.4 && fabs(lep_eta[1])<2.4 && GoodDataRan && GoodVtx && lep_pt[0]>53. && lep_pt[1]>53. && lep_isTrackerMuon[0]==1 && lep_isTrackerMuon[1]==1 && lep_isGlobalMuon[0]==1 && lep_isGlobalMuon[1]==1 && fabs(lep_dB[0]) < 0.2 && fabs(lep_dB[1]) < 0.2 && ( lep_numberOfMatchedStations[0] > 1 || (lep_numberOfMatchedStations[0] == 1 && !(lep_stationMask[0] == 1 || lep_stationMask[0] == 16)) || (lep_numberOfMatchedStations[0] == 1 && (lep_stationMask[0] == 1 || lep_stationMask[0] == 16) && lep_numberOfMatchedRPCLayers[0] > 2))  && (lep_numberOfMatchedStations[1] > 1 || (lep_numberOfMatchedStations[1] == 1 && !(lep_stationMask[1] == 1 || lep_stationMask[1] == 16)) || (lep_numberOfMatchedStations[1] == 1 && (lep_stationMask[1] == 1 || lep_stationMask[1] == 16) && lep_numberOfMatchedRPCLayers[1] > 2)) && lep_glb_numberOfValidMuonHits[0]>0 && lep_glb_numberOfValidMuonHits[1]>0 && lep_glb_numberOfValidPixelHits[0]>=1 && lep_glb_numberOfValidPixelHits[1]>=1 && lep_glb_numberOfValidTrackerLayers[0]>5 && lep_glb_numberOfValidTrackerLayers[1]>5 && lep_sumPt[0]/lep_tk_pt[0]<0.10 && lep_sumPt[1]/lep_tk_pt[1]<0.10 && lep_pt_err[0]/lep_pt[0]<0.3 && lep_pt_err[1]/lep_pt[1]<0.3 && cos_angle>-0.9998 && lep_id[0]*lep_id[1]<0 && (lep_triggerMatchPt[0]>50 || lep_triggerMatchPt[1]>50) && vertex_chi2 < 20 && vertex_m > 780 && vertex_m < 785'
cut = 'GoodVtx && fabs(lep_eta[0])<2.4 && fabs(lep_eta[1])<2.4 && lep_pt[0]>53. && lep_pt[1]>53. && lep_isTrackerMuon[0]==1 && lep_isTrackerMuon[1]==1 && lep_isGlobalMuon[0]==1 && lep_isGlobalMuon[1]==1 && fabs(lep_dB[0]) < 0.2 && fabs(lep_dB[1]) < 0.2 && ( lep_numberOfMatchedStations[0] > 1 || (lep_numberOfMatchedStations[0] == 1 && !(lep_stationMask[0] == 1 || lep_stationMask[0] == 16)) || (lep_numberOfMatchedStations[0] == 1 && (lep_stationMask[0] == 1 || lep_stationMask[0] == 16) && lep_numberOfMatchedRPCLayers[0] > 2))  && (lep_numberOfMatchedStations[1] > 1 || (lep_numberOfMatchedStations[1] == 1 && !(lep_stationMask[1] == 1 || lep_stationMask[1] == 16)) || (lep_numberOfMatchedStations[1] == 1 && (lep_stationMask[1] == 1 || lep_stationMask[1] == 16) && lep_numberOfMatchedRPCLayers[1] > 2)) && lep_glb_numberOfValidMuonHits[0]>0 && lep_glb_numberOfValidMuonHits[1]>0 && lep_glb_numberOfValidPixelHits[0]>=1 && lep_glb_numberOfValidPixelHits[1]>=1 && lep_glb_numberOfValidTrackerLayers[0]>5 && lep_glb_numberOfValidTrackerLayers[1]>5 && lep_sumPt[0]/lep_tk_pt[0]<0.10 && lep_sumPt[1]/lep_tk_pt[1]<0.10 && lep_pt_err[0]/lep_pt[0]<0.3 && lep_pt_err[1]/lep_pt[1]<0.3 && cos_angle>-0.9998 && lep_id[0]*lep_id[1]<0 && (lep_triggerMatchPt[0]>50 || lep_triggerMatchPt[1]>50) && vertex_chi2 < 20 && event == 317392 && lumi == 666'  # && vertex_m > 400'# && vertex_m < 900'

# cut='fabs(lep_eta[0])<1.2 && fabs(lep_eta[1])<1.2 && fabs(lep_eta[0])<2.4 && fabs(lep_eta[1])<2.4 && GoodDataRan && GoodVtx && lep_pt[0]>53. && lep_pt[1]>53. && lep_isTrackerMuon[0]==1 && lep_isTrackerMuon[1]==1 && lep_isGlobalMuon[0]==1 && lep_isGlobalMuon[1]==1 && fabs(lep_dB[0]) < 0.2 && fabs(lep_dB[1]) < 0.2 && ( lep_numberOfMatchedStations[0] > 1 || (lep_numberOfMatchedStations[0] == 1 && !(lep_stationMask[0] == 1 || lep_stationMask[0] == 16)) || (lep_numberOfMatchedStations[0] == 1 && (lep_stationMask[0] == 1 || lep_stationMask[0] == 16) && lep_numberOfMatchedRPCLayers[0] > 2))  && (lep_numberOfMatchedStations[1] > 1 || (lep_numberOfMatchedStations[1] == 1 && !(lep_stationMask[1] == 1 || lep_stationMask[1] == 16)) || (lep_numberOfMatchedStations[1] == 1 && (lep_stationMask[1] == 1 || lep_stationMask[1] == 16) && lep_numberOfMatchedRPCLayers[1] > 2)) && lep_glb_numberOfValidMuonHits[0]>0 && lep_glb_numberOfValidMuonHits[1]>0 && lep_glb_numberOfValidPixelHits[0]>=1 && lep_glb_numberOfValidPixelHits[1]>=1 && lep_glb_numberOfValidTrackerLayers[0]>5 && lep_glb_numberOfValidTrackerLayers[1]>5 && lep_sumPt[0]/lep_tk_pt[0]<0.10 && lep_sumPt[1]/lep_tk_pt[1]<0.10 && lep_pt_err[0]/lep_pt[0]<0.3 && lep_pt_err[1]/lep_pt[1]<0.3 && cos_angle>-0.9998 && lep_id[0]*lep_id[1]<0 && (lep_triggerMatchPt[0]>50 || lep_triggerMatchPt[1]>50) && vertex_chi2 < 20'
#(fabs(lep_eta[0])>1.2 || fabs(lep_eta[1])>1.2)

#cut='lep_pt[0]>53. && lep_pt[1]>53. && lep_isTrackerMuon[0]==1 && lep_isTrackerMuon[1]==1 && lep_isGlobalMuon[0]==1 && lep_isGlobalMuon[1]==1 && fabs(lep_dB[0]) < 0.2 && fabs(lep_dB[1]) < 0.2 && lep_numberOfMatchedStations[0] > 1 && lep_numberOfMatchedStations[1] > 1 && lep_glb_numberOfValidMuonHits[0]>0 && lep_glb_numberOfValidMuonHits[1]>0 && lep_glb_numberOfValidPixelHits[0]>=1 && lep_glb_numberOfValidPixelHits[1]>=1 && lep_glb_numberOfValidTrackerLayers[0]>5 && lep_glb_numberOfValidTrackerLayers[1]>5 && lep_sumPt[0]/lep_tk_pt[0]<0.10 && lep_sumPt[1]/lep_tk_pt[1]<0.10 && lep_pt_err[0]/lep_pt[0]<0.3 && lep_pt_err[1]/lep_pt[1]<0.3 && cos_angle>-0.9998 && lep_id[0]*lep_id[1]<0 && (lep_triggerMatchPt[0]>50 || lep_triggerMatchPt[1]>50) && vertex_chi2 < 20 && vertex_m>900'

f = ROOT.TFile(path)
t = f.SimpleNtupler.Get('t')
t.GetPlayer().SetScanRedirect(True)
t.GetPlayer().SetScanFileName(tmp_fn)
#- colsize=10 is needed in order not to currupt the event number
t.Scan(branch_spec, cut, "colsize=15 precision=10")
#t.Scan('*', cut)
t.GetPlayer().SetScanRedirect(False)
f.Close()

lines = [
    line.split(' *')[1:] for line in open(tmp_fn).readlines()
    if ' * ' in line and 'Row' not in line
]
#- This loop is to keep only the first (highest-rank) dimuon in an event
prev_run = prev_lumi = prev_event = sum_pt = 0
예제 #7
0
# 	tt_sample = 'NoBinned'
tt_sample = ''

rebin = 1
for mumu_histogram in histogram:
    if 'Pt' in mumu_histogram:
        rebin = 20

    if '_bb' in mumu_histogram:
        Zpeak = 1.0328  #0.9638
    elif '_be' in mumu_histogram:
        Zpeak = 1.0420  #0.9688
    else:
        Zpeak = 1  #1.0386#0.9610

    MC_Stack = ROOT.THStack('MC', '')
    MC_Stack_cum = ROOT.THStack('MC_cum', '')
    dati = ROOT.TH1F()
    h = ROOT.TH1F()
    h_cum = ROOT.TH1F()

    for sample in samples:

        file_dati = ROOT.TFile(mumu_Dati)
        dati = file_dati.Our2016MuonsPlusMuonsMinusHistos.Get(
            mumu_histogram).Clone()
        dati.Rebin(rebin)
        dati.SetMarkerColor(1)
        dati.SetLineColor(1)
        dati.SetLineWidth(2)
예제 #8
0
    def save_histos(self, cutset, dilepton, quantity_to_compare, cumulative):
        if cutset != 'Our2012':
            return
        if dilepton != 'MuonsPlusMuonsMinus':
            return
#        if quantity_to_compare != 'DimuonMassVtxConstrainedLog':
        if quantity_to_compare != 'DimuonMassVertexConstrained':
            return

        zdy_ifois = 0
        prompt_ifois = 0
        for sample in self.samples:
            if sample.is_zprime:
                continue
            if 'dy' in sample.name or sample.name == 'zmumu':
                print 'dy: ',sample.name
                if zdy_ifois == 0:
                    zdy = sample.histogram.Clone('zdy')
                    zdy_ifois = 1
                else:
                    zdy.Add(sample.histogram, 1.)
            if sample.name in ('ttbar', 'ttbar_powheg', 'tW', 'tbarW', 'ztautau', 'ww', 'wz', 'zz'):
                print 'ttbar and others', sample.name
                if prompt_ifois == 0:
                    prompt = sample.histogram.Clone('prompt')
                    prompt_ifois = 1
                else:
                    prompt.Add(sample.histogram, 1.)
        data = self.hdata.Clone('data')
        data_tgraph = poisson_intervalize(self.hdata, True)
        data_tgraph.SetName("data_tgraph")

        file_name = 'dimuon_histos_differential.root'
        if cumulative:
            file_name = 'dimuon_histos_cumulative.root'

        histFile = ROOT.TFile.Open(file_name, 'recreate')
        if not histFile:
            raise RuntimeError, \
                  "Could not open '%s' as an output root file" % output
        data.Write()
        prompt.Write()
        zdy.Write()

        if not cumulative:
            nbins = data.GetNbinsX()
            data_tgraph_per_GeV = ROOT.TGraphAsymmErrors(data_tgraph)
            data_tgraph_per_GeV.SetName("data_tgraph_per_GeV")
            zdy_per_GeV         = zdy.Clone('zdy_per_GeV')
            prompt_per_GeV      = prompt.Clone('prompt_per_GeV')
            for i in xrange(1, nbins):
                c_data = data.GetBinContent(i)/data.GetBinWidth(i)
                e_data = data.GetBinError(i)/data.GetBinWidth(i)
                print i, 'nevents = ', data.GetBinContent(i), ' low edge = ', data.GetBinLowEdge(i), ' width = ', data.GetBinWidth(i), 'events/GeV = ', c_data, '+/-', e_data
                x        = data.GetBinLowEdge(i) + data.GetBinWidth(i)/2.
                err_low  = data_tgraph.GetErrorYlow(i-1)/data.GetBinWidth(i)
                err_high = data_tgraph.GetErrorYhigh(i-1)/data.GetBinWidth(i)
                print '  x = ', x, ' err_low = ', data_tgraph.GetErrorYlow(i-1), err_low, ' err_high = ', data_tgraph.GetErrorYhigh(i-1), err_high
                data_tgraph_per_GeV.SetPoint(i-1, x, c_data)
                data_tgraph_per_GeV.SetPointEYlow(i-1, err_low)
                data_tgraph_per_GeV.SetPointEYhigh(i-1, err_high)

                c_zdy = zdy.GetBinContent(i)/zdy.GetBinWidth(i)
                e_zdy = zdy.GetBinError(i)/zdy.GetBinWidth(i)
                zdy_per_GeV.SetBinContent(i, c_zdy)
                zdy_per_GeV.SetBinError(i, e_zdy)

                c_prompt = prompt.GetBinContent(i)/prompt.GetBinWidth(i)
                e_prompt = prompt.GetBinError(i)/prompt.GetBinWidth(i)
                prompt_per_GeV.SetBinContent(i, c_prompt)
                prompt_per_GeV.SetBinError(i, e_prompt)

            data_tgraph.Write()
            data_tgraph_per_GeV.Write()
            zdy_per_GeV.Write()
            prompt_per_GeV.Write()
예제 #9
0
    def __init__(self, options):
        self.histo_dir = options.histo_dir
        self.print_table = options.print_table
        self.save_plots = options.save_plots
        self.rescale_lumi = options.rescale_lumi
        self.lumi_syst_frac = options.lumi_syst_frac
        self.draw_zprime = options.draw_zprime
        self.use_poisson_intervals = options.use_poisson_intervals
        self.put_overflow_in_last_bin = options.put_overflow_in_last_bin
        self.do_joins = options.do_joins
        self.join_ttbar_and_other_prompt_leptons = options.join_ttbar_and_other_prompt_leptons
        self.join_dy_and_jets = options.join_dy_and_jets
        self.qcd_from_data = options.qcd_from_data
        self.guess_yrange = options.guess_yrange

        if not os.path.isdir(self.histo_dir):
            raise ValueError('histo_dir %s is not a directory' % self.histo_dir)

        self.data_fn = os.path.join(self.histo_dir, 'ana_datamc_data.root')
        if not os.path.isfile(self.data_fn):
            raise ValueError('data_fn %s is not a file' % self.data_fn)
        self.data_f = ROOT.TFile(self.data_fn)
        if not self.data_f.IsOpen() or self.data_f.IsZombie():
            raise ValueError('data_fn %s is not a ROOT file' % self.data_fn)
        
        # We look for a separate mc dir in our histo_dir first, for
        # the case where we want to use a specific set of MC files for
        # a given histo_dir. If none there, check if there is one
        # specified in options.  Else, use the general mc dir from the
        # current directory.
        self.mc_dir = os.path.join(self.histo_dir, 'mc')
        if not os.path.isdir(self.mc_dir):
            if hasattr(options, 'mc_dir'):
                self.mc_dir = options.mc_dir
            else:
                self.mc_dir = 'mc'
        if not os.path.isdir(self.mc_dir):
            raise ValueError('mc_dir %s is not a directory' % self.mc_dir)

        # If the options override the int_lumi, take that; otherwise
        # try to get the int_lumi from the file corresponding to
        # data_fn.
        if type(options.override_int_lumi) == float:
            self.int_lumi = options.override_int_lumi
            print self.int_lumi
        else:
            lumi_fn = self.data_fn.replace('.root', '.lumi')
            self.int_lumi = self.parse_lumi_from_log(lumi_fn)
            if self.int_lumi is None:
                raise ValueError('int_lumi could not be parsed from file %s' % lumi_fn)
        if self.int_lumi < 0:
            raise ValueError('int_lumi %f makes no sense' % self.int_lumi)

        # Use all samples specified in MCSamples that are not
        # requested to be dropped in the options. The sample objects
        # already-set values (like color, partial_weight) we won't
        # change, but the objects themselves may be modified. In
        # particular, we will use them as storage containers for
        # things like ROOT histograms and calculated things like scale
        # factors and event counts.
        self.samples = [s for s in MCSamples.samples if options.exclude_samples is None or s.name not in options.exclude_samples]
        self.hdata = None

        # Defaults for the dileptons, cutsets, and mass ranges for the
        # ASCII table.
        self.quantities_to_compare = ['DileptonMass', 'DimuonMassVertexConstrained','DileptonPt', 'LeptonPt','LeptonPhi', 'LeptonEta','NVertices']
        self.dileptons = ['MuonsPlusMuonsMinus', 'MuonsSameSign', 'MuonsAllSigns', 'MuonsElectronsOppSign', 'MuonsElectronsSameSign', 'MuonsElectronsAllSigns']
        #        self.dileptons = ['MuonsPlusMuonsMinus', 'MuonsSameSign', 'MuonsAllSigns', 'MuonsElectronsOppSign', 'MuonsElectronsSameSign', 'MuonsElectronsAllSigns'] ########
        self.dileptons = ['']
        #        self.cutsets = ['Our2012', 'Simple', 'OurMuPrescaled']  #################
        self.cutsets = ['Histosinner', 'Histostunepnew', 'Histosstartup']
        self.mass_ranges_for_table = [(50,),(60,120)]
        #self.mass_ranges_for_table = [(60,120), (120,200), (200,400), (400,600), (120,), (200,), (400,), (600,)]
#        self.mass_ranges_for_table = [(60,120), (120,200), (120,400), (400,600), (600,900,), (900,1300), (1300,1800), (1800,), (120,), (200,), (400,), (600,)]

        if options.include_quantities is not None:
            self.quantities_to_compare = options.include_quantities
        if options.include_dileptons is not None:
            self.dileptons = options.include_dileptons
        if options.include_cutsets is not None:
            self.cutsets = options.include_cutsets
        if options.include_mass_ranges_for_table is not None:
            self.mass_ranges_for_table = options.include_mass_ranges_for_table
        
        if options.for_rescale_factors:
            self.save_plots = False
            self.rescale_lumi = False
            self.mass_ranges_for_table = [(60,120)]
            #            self.dileptons = ['MuonsPlusMuonsMinus']
            self.dileptons = ['']
        
        self.setup_root()
        base = 'plots/mc'
        if options.plot_dir_tag is not None:
            base += '_' + options.plot_dir_tag
        self.plot_dir_base = os.path.join(base, os.path.basename(self.histo_dir))
        os.system('mkdir -p %s' % self.plot_dir_base)
        width,height = options.plot_size.split(',')
        self.ps = plot_saver(self.plot_dir_base, size=(int(width), int(height)), pdf_log=True, pdf=True)

        self.table_sections = []
        self.table_rows = []
예제 #10
0
    def draw_data_on_mc(self, cutset, dilepton, quantity_to_compare, cumulative):
        # Make a Stack for the MC histograms. We draw it first so the
        # data points will be drawn on top later.  We assume that in
        # the list of samples, the join groups are contiguous already
        # so that like-colored histograms will be next to each other.
        
        s = ROOT.THStack('s', '')
        for sample in self.samples:
            # Don't stack the Z' samples.
            if sample.is_zprime:
                continue
            s.Add(sample.histogram) # Assumes they've already been prepared.

        # Figure out its titles.
        xtitle = self.titleize(quantity_to_compare) % (self.subtitleize(dilepton), self.unitize(quantity_to_compare))
        if cumulative:
            # E.g. Events >= m(mu+mu-).
            ytitle = 'Events #geq %s' % (self.titleize(quantity_to_compare) % (self.subtitleize(dilepton), ''))
        else:
            # E.g. Events/5 GeV.
            ytitle = 'Events / %i%s' % (self.get_rebin_factor(dilepton, quantity_to_compare), self.unitize(quantity_to_compare).translate(None, '()[]')) # Events/5 GeV. JMTBAD assumes original histogram had 1 GeV bins and was rebinned simply -- ignores rebin_histogram ability to have arb. bins
            if quantity_to_compare == 'DileptonRap':
                ytitle = 'Events / 0.5'
            elif quantity_to_compare == 'RelIsoSumPt':
                ytitle = 'Events / 0.02'
            elif quantity_to_compare == 'RelCombIso':
                ytitle = 'Events / 0.05'
            elif quantity_to_compare == 'DimuonMassVtxConstrainedLog':
                ytitle = 'Events / bin'
        s.SetTitle(';%s;%s' % (xtitle, ytitle))

        s.Draw('hist')

        # Must call Draw first or the THStack doesn't have a histogram/axes.
        s.GetXaxis().SetTitleOffset(0.9)
        s.GetXaxis().SetTitleSize(0.047)
        if 'MuonsSameSign' in dilepton:
            s.GetYaxis().SetTitleOffset(0.9)
        else:
            s.GetYaxis().SetTitleOffset(1.0)
        s.GetYaxis().SetTitleSize(0.047)

        # Set the x-axis range as specified. Then determine what
        # the real extrema of the data histogram and the MC stack are
        # over the xrange specified.
        xrange = self.get_x_axis_range(cutset, dilepton, quantity_to_compare)
        mymin, mymax = None, None
        if xrange is not None:
            s.GetXaxis().SetRangeUser(*xrange)
#            self.hdata.GetXaxis().SetRangeUser(*xrange)
            mymin = real_hist_min(s.GetStack().Last(), user_range=xrange) * 0.7
            mymax = real_hist_max(s.GetStack().Last(), user_range=xrange, use_error_bars=False) * 1.05
#            if self.hdata.GetEntries() > 0:
#                rhm = real_hist_max(self.hdata, user_range=xrange)
#                mymax = max(mymax, rhm)
#
#        if self.guess_yrange:
#            mymin = 0
#            mymax = real_hist_max(self.hdata, user_range=xrange)

        # Can override the above fussing.
#        yrange = self.get_y_axis_range(dilepton, cumulative)
#        if yrange is not None:
#            if yrange[0] is not None:
#                mymin = yrange[0]
#            if yrange[1] is not None:
#                mymax = yrange[1]

        mymin = 0.005

        if mymin is not None: s.SetMinimum(mymin)
        if mymax is not None: s.SetMaximum(mymax)

        # Calculate (data-bckg)/bckg.  Do it before TH1 gets converted
        # to TGraphAsymmErrors by poisson_intervalize.
#        if not cumulative:
#            ifois = 0
#            for sample in self.samples:
#                # Don't add the Z' samples.
#                if sample.is_zprime:
#                    continue
#                if ifois == 0:
#                    mc_sum = sample.histogram.Clone()
#                    ifois = 1
#                else:
#                    mc_sum.Add(sample.histogram, 1.)
#
#            data_mc_diff = self.hdata.Clone()
#            data_mc_diff.Divide(mc_sum)
#            nbins = data_mc_diff.GetNbinsX()
#            for ibin in range(1, nbins):
#                f_bin = data_mc_diff.GetBinContent(ibin)
#                data_mc_diff.SetBinContent(ibin, f_bin-1.)

        # Now draw the data on top of the stack.
#        self.hdata.SetStats(0)
#        data_draw_cmd = 'same p e'
#        if self.use_poisson_intervals:
#            self.hdata = poisson_intervalize(self.hdata, True)
#            data_draw_cmd += ' z'
#        if mymin is not None: self.hdata.SetMinimum(mymin)
#        if mymax is not None: self.hdata.SetMaximum(mymax)
#        self.hdata.SetMarkerStyle(20)
#        self.hdata.SetMarkerSize(0.8)
#        self.hdata.Draw(data_draw_cmd)

        # Draw the Z' curve separately. It is overlaid, not stacked
        # with the rest of the MC expectation.
        zp = self.get_zprime_histogram()
        if self.should_draw_zprime(dilepton) and zp:
            # JMTBAD Extend to the rest of the Z' samples when there are any.
            zp.SetTitle('')
            zp.SetLineWidth(2)
            if xrange is not None:
                zp.GetXaxis().SetRangeUser(*xrange)
                zp.SetMinimum(mymin)
                zp.SetMaximum(mymax)
            zp.SetStats(0)
            zp.Draw('hist same')

        # Use log(x) whenever needed
        log_x = self.get_log_x(cutset, dilepton, quantity_to_compare)
        if log_x:
            self.ps.c.SetLogx()

        # Adorn the plot with legend and labels.
        l = self.draw_legend(dilepton, cumulative, log_x)
#        t = ROOT.TPaveLabel(0.20, 0.89, 0.86, 0.99, 'CMS Preliminary   #sqrt{s} = 8 TeV    #int L dt = %.f pb^{-1}' % round(self.int_lumi), 'brNDC')
        t = ROOT.TPaveLabel(0.30, 0.89, 0.96, 0.99, 'CMS Preliminary   #sqrt{s} = 13 TeV   #int L dt = 5 fb^{-1}', 'brNDC')
        t.SetTextSize(0.35)
        t.SetBorderSize(0)
        t.SetFillColor(0)
        t.SetFillStyle(0)
        t.Draw()

        # Done; save it!
        plot_fn = dilepton + 'plot'
        if cumulative:
            plot_fn += '_cumulative'
        self.ps.save(plot_fn)

        if log_x:
            self.ps.c.SetLogx(0)
예제 #11
0
    def prepare_mc_histograms(self, cutset, dilepton, quantity_to_compare, cumulative):
        # For each sample in the list of MC samples, we get the
        # specified histogram from the appropriate input file, clone
        # it, rebin/scale/otherwise manipulate it as necessary, and
        # store the result as The Histogram in the sample object.
        for sample in self.samples:
            if (self.qcd_from_data and 'MuPrescaled' not in cutset and 'Electron' not in dilepton and sample.name == 'inclmu15' and quantity_to_compare in ['DileptonMass', 'DimuonMassVertexConstrained', 'DimuonMassVtxConstrainedLog']):
                # Replace QCD MC prediction by that obtained from data.
                mc_fn = os.path.join('./', 'qcd_from_data.root')
                f = ROOT.TFile(mc_fn)
                if 'MuonsSameSign' in dilepton:
                    sample.histogram = f.Get('ss').Clone()
                elif 'MuonsPlusMuonsMinus' in dilepton:
                    sample.histogram = f.Get('os').Clone()
                elif 'MuonsAllSigns' in dilepton:
                    sample.histogram = f.Get('ss').Clone()
                    sample.histogram.Add(f.Get('os'), 1.)
                else:
                    print "+++ Unknown dilepton type! +++"

                if (quantity_to_compare == 'DimuonMassVtxConstrainedLog'):
                    # Re-pack fixed-bin-width histogram into a variable-bin-width one
                    mc_fn = os.path.join(self.mc_dir, 'ana_datamc_%s.root' % sample.name)
                    f = ROOT.TFile(mc_fn)
                    varbin_histogram = getattr(f, self.get_dir_name(cutset, dilepton)).Get(quantity_to_compare).Clone()

                    nbins_var = varbin_histogram.GetNbinsX()
                    nbins_fix = sample.histogram.GetNbinsX()
                    for ibin_var in range(1, nbins_var+1):
                        xlow_var = varbin_histogram.GetBinLowEdge(ibin_var)
                        xupp_var = xlow_var + varbin_histogram.GetBinWidth(ibin_var)
                        # print ibin_var, xlow_var, xupp_var
                        cbin = 0
                        for ibin_fix in range(1, nbins_fix+1):
                            bin_center = sample.histogram.GetBinCenter(ibin_fix)
                            if (bin_center > xlow_var and bin_center < xupp_var):
                                # print "     ", ibin_fix, bin_center, sample.histogram.GetBinContent(ibin_fix)
                                cbin = cbin + sample.histogram.GetBinContent(ibin_fix)
                        # print "  ", ibin_var, cbin
                        varbin_histogram.SetBinContent(ibin_var, cbin)

                    sample.histogram = varbin_histogram.Clone()

                sample.scaled_by = 1. # Assume that the histogram is appropriately normalized.
            else:
                mc_fn = os.path.join(self.mc_dir, 'ana_datamc_%s.root' % sample.name)
                f = ROOT.TFile(mc_fn)
                sample.histogram = getattr(f, self.get_dir_name(cutset, dilepton)).Get(quantity_to_compare).Clone()
                sample.scaled_by = self.int_lumi * self.get_lumi_rescale_factor(cutset, dilepton) * sample.partial_weight
                #print sample.name,' ',self.int_lumi,' ',self.get_lumi_rescale_factor(cutset, dilepton),' ',sample.partial_weight #NEW TO CHECK#
                if 'MuPrescaled' in cutset:
                    sample.scaled_by = sample.scaled_by / overall_prescale

            # Assume that the QCD histogram includes W+jets as well.
            if (self.qcd_from_data and 'MuPrescaled' not in cutset and 'Electron' not in dilepton and sample.name in ('wmunu', 'wjets') and quantity_to_compare in ['DileptonMass', 'DimuonMassVertexConstrained', 'DimuonMassVtxConstrainedLog']):
                nbins = sample.histogram.GetNbinsX()
                for ibin in range(1, nbins+1):
                    sample.histogram.SetBinContent(ibin, 0.)
                    sample.histogram.SetBinError(ibin, 0.)

            self.rebin_histogram(sample.histogram, cutset, dilepton, quantity_to_compare)
            sample.histogram.Scale(sample.scaled_by)

            if cumulative:
                sample.histogram = cumulative_histogram(sample.histogram)
            else:
                self.handle_overflows(sample.histogram, self.get_x_axis_range(cutset, dilepton, quantity_to_compare))

            sample.histogram.SetMarkerStyle(0)
            color = self.get_color(sample)
            sample.histogram.SetLineColor(color)
            if not sample.is_zprime:
                sample.histogram.SetFillColor(color)
                sample.histogram.SetLineColor(1) #NEW#