Beispiel #1
0
def get_uncertainty_graph(hnom, curve_uncert):
    """
    Convert an histogram and a RooCurve
    into a TGraphAsymmError

    Parameters
    ----------
    hnom: TH1F, TH1D, ...
        The histogram of nominal values
    curve_uncert: RooCurve
        The uncertainty band around the nominal value

    TODO: Improve the handling of the underflow and overflow bins
    """
    graph = Graph(hnom.GetNbinsX())
    for ibin in xrange(1, hnom.GetNbinsX() + 1):
        uncerts = []
        for ip in xrange(3, curve_uncert.GetN() - 3):
            x, y = ROOT.Double(0.), ROOT.Double(0.)
            curve_uncert.GetPoint(ip, x, y)
            if hnom.GetBinLowEdge(ibin) <= x < hnom.GetBinLowEdge(ibin + 1):
                uncerts.append(y)
        log.debug('{0}, bin {1}: {2}'.format(hnom.name, ibin, uncerts))
        low, high = min(uncerts), max(uncerts)
        bin_center = 0.5 * (hnom.GetBinLowEdge(ibin + 1) +
                            hnom.GetBinLowEdge(ibin))
        e_x_low = bin_center - hnom.GetBinLowEdge(ibin)
        e_x_high = hnom.GetBinLowEdge(ibin + 1) - bin_center
        bin_content = hnom.GetBinContent(ibin)
        e_y_low = hnom.GetBinContent(ibin) - low
        e_y_high = high - hnom.GetBinContent(ibin)
        graph.SetPoint(ibin - 1, bin_center, bin_content)
        graph.SetPointError(ibin - 1, e_x_low, e_x_high, e_y_low, e_y_high)
    return graph
Beispiel #2
0
def test_ROOT():

    a = ROOT.TH1F("a", "a", 10, 0, 1)
    assert_true(isinstance(a, _Hist))

    b = ROOT.Hist(10, 0, 1, type='F')
    assert_equal(a.TYPE, b.TYPE)
Beispiel #3
0
def HGCAL_label(text='HGCAL Simulation', pad=None):
    """Add label to the current Pad."""
    if pad is None:
        pad = ROOT.gPad.func()
    with preserve_current_canvas():
        pad.cd()
        left_margin = pad.GetLeftMargin()
        top_margin = pad.GetTopMargin()
        # Offset labels by 14% of the top margin
        ypos = 1 - 0.86 * top_margin
        label_cms = ROOT.TLatex(left_margin, ypos, "CMS")
        label_cms.SetTextFont(61)  # Helvetica bold
        label_cms.SetTextAlign(11)  # left-bottom
        label_cms.SetNDC()
        # The text is 75% as tall as the margin it lives in.
        label_cms.SetTextSize(0.75 * top_margin)
        label_cms.Draw()
        keepalive(pad, label_cms)
        # Draw additional text if desired
        label_add = None
        if text:
            label_add = ROOT.TLatex(left_margin + 0.09, ypos, text)
            label_add.SetTextFont(52)  # Helvetica italic
            label_add.SetTextAlign(11)  # left-bottom
            label_add.SetNDC()
            # The text is 75% as tall as the margin it lives in.
            label_add.SetTextSize(0.60 * top_margin)
            label_add.Draw()
            keepalive(pad, label_add)
        pad.Modified()
        pad.Update()
    return label_cms, label_add
Beispiel #4
0
    def __make_overlay(self, pileup, threshold, hists, fits, labels, header):
        with preserve_current_style():
            name = self.filename_format.format(pileup=pileup,
                                               threshold=threshold)

            xmin = hists[0].GetTotalHistogram().GetBinLowEdge(1)
            xmax = hists[0].GetTotalHistogram().GetBinLowEdge(
                hists[0].GetTotalHistogram().GetNbinsX() + 1)

            # Draw each efficiency (with fit)
            draw_args = {
                "xtitle": self.offline_title,
                "ytitle": "Efficiency",
                "xlimits": [xmin, xmax]
            }

            canvas = draw(hists, draw_args=draw_args)
            if len(fits) > 0:
                for fit, hist in zip(fits, hists):
                    fit["asymmetric"].linecolor = hist.GetLineColor()
                    fit["asymmetric"].Draw("same")

            # Add labels
            label_canvas()

            # Add a legend
            legend = Legend(
                len(hists),
                header=self.legend_title,
                topmargin=0.35,
                rightmargin=0.3,
                leftmargin=0.7,
                textsize=0.025,
                entryheight=0.028,
            )

            for hist, label in zip(hists, labels):
                legend.AddEntry(hist, label)

            legend.SetBorderSize(0)
            legend.Draw()

            for val in [0.25, 0.5, 0.75, 0.95, 1.]:
                line = ROOT.TLine(xmin, val, xmax, val)
                line.SetLineStyle("dashed")
                line.SetLineColor(15)
                line.Draw()

            for thresh in self.thresholds.bins:
                line = ROOT.TLine(thresh, 0., thresh, 1.)
                line.SetLineStyle("dashed")
                line.SetLineColor(15)
                line.Draw()

            # Save canvas to file
            self.save_canvas(canvas, name)
def draw_lines(params):
    lines = []
    line_100 = ROOT.TLine(params.xmin, 1, params.xmax, 1)
    line_95 = ROOT.TLine(params.xmin, 0.95, params.xmax, 0.95)
    line_100.SetLineWidth(2)
    line_95.SetLineWidth(2)
    line_95.SetLineStyle(2)
    line_100.Draw()
    line_95.Draw()
    lines.append(line_100)
    lines.append(line_95)
    return lines
 def make_efficiency(labels):
     this_name = "efficiency" + name.format(**labels)
     this_title = title.format(**labels)
     '''Checking type of 'low' to see whether it's int (x-range minimum)
             or array (bin edges) for constructing TEfficiency'''
     if isinstance(low, np.ndarray):
         eff = asrootpy(
             ROOT.TEfficiency(this_name, this_title, n_bins, low))
     else:
         eff = asrootpy(
             ROOT.TEfficiency(this_name, this_title, n_bins, low, high))
     eff.drawstyle = EfficiencyPlot.drawstyle
     return eff
    def _dynamic_bin(self, eff):
        """
        Re-build efficiency plots so that there are no bins with < min_ entries
        """

        min_ = 16
        total = []
        passed = []
        bins = []
        bins.append(eff.GetTotalHistogram().GetBinLowEdge(1))
        nbins = eff.GetTotalHistogram().GetNbinsX()

        merge_total = 0
        merge_passed = 0

        for bin in range(1, nbins + 1):

            next_bin_total = eff.GetTotalHistogram().GetBinContent(bin + 1)
            merge_total += eff.GetTotalHistogram().GetBinContent(bin)
            merge_passed += eff.GetPassedHistogram().GetBinContent(bin)
            if bin == nbins:
                merge_total += eff.GetTotalHistogram().GetBinContent(bin + 1)
                merge_passed += eff.GetPassedHistogram().GetBinContent(bin + 1)

            if (next_bin_total > min_ and merge_total > min_) or bin == nbins:
                bins.append(eff.GetTotalHistogram().GetBinLowEdge(bin + 1))
                total.append(merge_total)
                passed.append(merge_passed)
                merge_total = 0
                merge_passed = 0

        npbins = np.asarray(bins)

        hist_total = asrootpy(
            ROOT.TH1I("total", "total",
                      len(bins) - 1, npbins))
        hist_passed = asrootpy(
            ROOT.TH1I("passed", "passed",
                      len(bins) - 1, npbins))

        for bin in range(1, len(bins)):
            hist_total.SetBinContent(bin, total[bin - 1])
            hist_passed.SetBinContent(bin, passed[bin - 1])

        hist_total.Sumw2(False)
        hist_passed.Sumw2(False)

        eff.SetTotalHistogram(hist_total, "f")
        eff.SetPassedHistogram(hist_passed, "f")
Beispiel #8
0
def mergeHistsFromMapping(hists, mapping, fillcolors=None):
    """
    merge histograms from mappping.
    e.g.
    - hists {'a_1': Hist(), 'a_2': Hist(), ... , 'b_1': Hist(),  'b_2': Hist()}
    - mapping {'a': ['a_1', 'a_2',], 'b': ['b_1', 'b_2']}
    - fillcolors [optional] {'a': 'green', 'b': 'red'}
    - returns OrderedDict('a': Hist(), 'b': Hist()) sorted by Integral()
    """

    from collections import OrderedDict
    CatHists = {}
    for cat, ds in mapping.items():
        output = None
        for d in ds:
            if output is None:
                output = hists[d].Clone()
                ROOT.SetOwnership(output, False)
            else:
                output.Add(hists[d])
        if fillcolors:
            output.fillcolor = fillcolors[cat]
        output.SetTitle(cat)
        CatHists[cat] = output
    return OrderedDict(sorted(CatHists.items(), key=lambda x: x[1].Integral()))
Beispiel #9
0
def UncertGraph(hnom, curve_uncert):
    """
    Convert an histogram and a RooCurve
    into a TGraphAsymmError

    Parameters
    ----------
    hnom: TH1F, TH1D,...
        The histogram of nominal values
    curve_uncert: RooCurve
        The uncertainty band around the nominal value
    curve_uncert: RooCurve
    TODO: Improve the handling of the underflow and overflow bins
    """

    graph = Graph(hnom.GetNbinsX())
    # ---------------------------------------------
    for ibin in xrange(1, hnom.GetNbinsX() + 1):
        uncerts = []
        for ip in xrange(3, curve_uncert.GetN() - 3):
            x, y = ROOT.Double(0.), ROOT.Double(0.)
            curve_uncert.GetPoint(ip, x, y)
            if int(x) == int(hnom.GetBinLowEdge(ibin)):
                uncerts.append(y)
        uncerts.sort()
        log.info('{0}: {1}'.format(hnom.name, uncerts))
        if len(uncerts) != 2:
            for val in uncerts:
                if val in uncerts:
                    uncerts.remove(val)
        if len(uncerts) != 2:
            raise RuntimeError(
                'Need exactly two error values and got {0}'.format(uncerts))

        bin_center = 0.5 * (hnom.GetBinLowEdge(ibin + 1) +
                            hnom.GetBinLowEdge(ibin))
        e_x_low = bin_center - hnom.GetBinLowEdge(ibin)
        e_x_high = hnom.GetBinLowEdge(ibin + 1) - bin_center
        bin_content = hnom.GetBinContent(ibin)
        e_y_low = hnom.GetBinContent(ibin) - uncerts[0]
        e_y_high = uncerts[1] - hnom.GetBinContent(ibin)
        graph.SetPoint(ibin - 1, bin_center, bin_content)
        graph.SetPointError(ibin - 1, e_x_low, e_x_high, e_y_low, e_y_high)
    # ---------------------------------------------
    return graph
Beispiel #10
0
def test_file_open():
    fname = 'test_file_open.root'
    with File.open(fname, 'w'):
        pass
    with root_open(fname, 'r'):
        pass
    with root_open(fname):
        pass
    with ROOT.TFile(fname, 'recreate') as f:
        assert_true(isinstance(f, File))
    os.unlink(fname)
Beispiel #11
0
def digitize(path, file, tree):
    """"""
    output = R.TFile.Open(str(Path(path).stem + ".digi.root"), "RECREATE")
    output.cd()
    digitized = digitize_tree(output, path, copytree(file, tree), tree.GetName())
    digitized.Write()
    for (key, name) in map(lambda k: (k, k.GetName()), file.GetListOfKeys()):
        if name != tree.GetName():
            file.cd()
            obj = key.ReadObj()
            output.cd()
            obj.Write()
    output.cd()
    digitize_tag = R.TNamed("DIGITIZED", "TRUE")
    digitize_tag.Write()
    output.Close()
    def __make_overlay(self, hists, fits, labels, ytitle, suffix=""):
        with preserve_current_style():
            # Draw each resolution (with fit)
            # TODO: this feels like it does not belong here
            for hist in hists:
                hist.GetYaxis().SetRangeUser(0, 0.1)
                hist.GetYaxis().SetTitleOffset(1.4)

            xtitle = self.resolution_method.label.format(
                on=self.online_title, off=self.offline_title)
            canvas = draw(hists,
                          draw_args={
                              "xtitle": xtitle,
                              "ytitle": ytitle
                          })
            if fits:
                for fit, hist in zip(fits, hists):
                    fit["asymmetric"].linecolor = hist.GetLineColor()
                    fit["asymmetric"].Draw("same")

            # Add labels
            label_canvas()

            # Add a legend
            legend = Legend(
                len(hists),
                header=self.legend_title,
                topmargin=0.35,
                rightmargin=0.3,
                leftmargin=0.7,
                textsize=0.03,
                entryheight=0.03,
            )

            for hist, label in zip(hists, labels):
                legend.AddEntry(hist, label)
            legend.SetBorderSize(0)
            legend.Draw()

            ymax = 1.2 * max([hist.GetMaximum() for hist in hists])
            line = ROOT.TLine(0., 0., 0., ymax)
            line.SetLineColor(15)

            # Save canvas to file
            name = self.filename_format.format(pileup="all")
            self.save_canvas(canvas, name + suffix)
Beispiel #13
0
def TitleAsLatex(s):
    """Add a title as TLatex on top left"""

    # label = ROOT.TLatex(ROOT.gStyle.GetPadLeftMargin(), 0.9+ROOT.gStyle.GetPadTopMargin()*0.01, s)
    label = ROOT.TPaveText(ROOT.gStyle.GetPadLeftMargin() - 0.02,
                           0.95 + ROOT.gStyle.GetPadTopMargin() * 0.03,
                           ROOT.gStyle.GetPadLeftMargin() + 0.58,
                           0.95 + ROOT.gStyle.GetPadTopMargin() * 0.85,
                           'NB NDC')
    label.AddText(s)
    label.SetTextFont(42)
    label.SetTextAlign(12)
    # label.SetTextSize(22)
    # label.SetNDC()
    label.SetFillStyle(0)
    label.SetFillColor(0)
    label.SetBorderSize(0)
    return label
Beispiel #14
0
def ErrorBandFromHistStack(hstack, **kwargs):
    """
    possion error band (TGraphAsymmError) from sum of `hstack`
    kwargs are forwarded for TGraphAsymmError property setting
    """
    _sumStack = sumHistStack(hstack)

    stackError = asrootpy(_sumStack)  #.poisson_errors()
    ROOT.SetOwnership(stackError, False)
    kwDefaults = {
        'fillstyle': 3244,
        'fillcolor': 'gray',
        'drawstyle': 'e2',
        'markersize': 0,
        'legendstyle': 'F',
        'title': 'stat. unc',
    }
    kwDefaults.update(kwargs)
    for k, v in kwDefaults.items():
        setattr(stackError, k, v)

    return stackError
Beispiel #15
0
 def write_meta(self, key, value):
     self.__t_file_out.cd()
     ROOT.TNamed(key, value).Write()
Beispiel #16
0
def computeCosAlpha(p4_1, p4_2):
    vec_1 = ROOT.TVector3(p4_1.px(), p4_1.py(), p4_1.pz())
    vec_2 = ROOT.TVector3(p4_2.px(), p4_2.py(), p4_2.pz())

    return vec_1.Dot(vec_2) / vec_1.Mag() / vec_2.Mag()
Beispiel #17
0
hist2d_adc_sigma.SetTitle("ADC Sigma of 1600 Channels")
hist2d_adc_sigma.GetXaxis().SetNdivisions(40)
hist2d_adc_sigma.GetYaxis().SetNdivisions(40)
for i in xrange(40):
    if (i % 8 == 0):
        hist2d_adc_sigma.GetXaxis().SetBinLabel(i + 1, "%02d" % i)
        hist2d_adc_sigma.GetYaxis().SetBinLabel(i + 1, "%02d" % i)

ROOT.gStyle.SetOptStat(0)

for i in xrange(25):
    for j in xrange(64):
        hist2d_adc_per_kev.SetBinContent(
            ijtox(i, j) + 1,
            ijtoy(i, j) + 1, adc_per_kev[i][j])
        hist2d_adc_sigma.SetBinContent(
            ijtox(i, j) + 1,
            ijtoy(i, j) + 1, adc_sigma[i][j])

c1 = ROOT.TCanvas()
c1.SetWindowSize(1600, 800)
c1.Divide(2, 1)
c1.cd(1)
c1.GetPad(1).SetGrid()
hist2d_adc_per_kev.Draw("COLZ")
c1.cd(2)
c1.GetPad(2).SetGrid()
hist2d_adc_sigma.Draw("COLZ")

wait(True)
Beispiel #18
0
import rootpy.ROOT as ROOT
from rootpy.plotting import Hist1D, Hist2D
from root_numpy import root2array

ROOT.gROOT.ProcessLine(".x ../lhcbstyle.C")
ROOT.gStyle.SetPadRightMargin(0.05)
ROOT.gStyle.SetPadLeftMargin(0.21)
ROOT.gStyle.SetTitleOffset(1.4, "Y")
ROOT.gROOT.GetColor(3).SetRGB(0., 0.6, 0.)

c = ROOT.TCanvas("c", "", 600, 500)

toy_sig = root2array("test_tuple.root", branches = ["mprime", "thetaprime"], selection = "abs(md-1.97)<0.05")
toy_sb  = root2array("test_tuple.root", branches = ["mprime", "thetaprime"], selection = "(md<1.97-0.05)||(md>1.97+0.05)")
fit_sig = root2array("fit_result_3d.root", branches = ["mprime", "thetaprime"], selection = "abs(md-1.97)<0.05")
#fit_sig = root2array("fit_result.root", branches = ["mprime", "thetaprime"], selection = "md>1.97+0.05")

hsig = Hist1D(100, 0., 1.)
hsb  = Hist1D(100, 0., 1.)
hfit = Hist1D(100, 0., 1.)

hsig.fill_array(toy_sig['mprime'])
hsb.fill_array(toy_sb['mprime'])
hfit.fill_array(fit_sig['mprime'])

hsig.SetMarkerSize(0.5)
hsig.Draw("e")
hsig.GetXaxis().SetTitle("m'")
hsig.GetYaxis().SetTitle("Entries / (0.01)")
hsb.Scale(hsig.GetSumOfWeights()/hsb.GetSumOfWeights())
hsb.SetLineColor(6)
Beispiel #19
0
        '#include "/home/twkim/MG5_aMC_v2_7_3/ExRootAnalysis/ExRootAnalysis/ExRootClasses.h"'
    )
    ROOT.gInterpreter.Declare(
        '#include "/home/twkim/MG5_aMC_v2_7_3/ExRootAnalysis/ExRootAnalysis/ExRootTreeReader.h"'
    )
except:
    pass

# Read & Write File

inputFile = sys.argv[1]
outputFile = ROOT.TFile.Open("BKG_ttbar_bpt.root",
                             "recreate")  ### <- Set Your output file name

# Create chain of root trees
chain = ROOT.TChain("LHEF")
chain.Add(inputFile)

# Create object of class ExRootTreeReader
treeReader = ROOT.ExRootTreeReader(chain)
numberOfEntries = treeReader.GetEntries()

# Get pointers to branches used in this analysis
branchParticle = treeReader.UseBranch("Particle")
# branchElectron = treeReader.UseBranch("Electron")

# Define histograms
histPT = ROOT.TH1F("pt", "p_{T} distribution", 80, 0, 400.0)
histEta = ROOT.TH1F("eta", "eta distribution", 100, -10, 10)
histPhi = ROOT.TH1F("phi", "phi distribution", 100, -10, 10)
Beispiel #20
0
    def __make_overlay(self, pileup, threshold, hists, fits, labels, header):
        with preserve_current_style():
            name = self.filename_format.format(pileup=pileup,
                                               threshold=threshold)
            # Draw each efficiency (with fit)
            draw_args = {"xtitle": self.offline_title, "ytitle": "Efficiency"}
            # TODO: special case should not be implemented here!
            if 'Jet' in name and 'HiRange' in name:
                draw_args['xlimits'] = [20, 2000]

            canvas = draw(hists, draw_args=draw_args)
            if len(fits) > 0:
                for fit, hist in zip(fits, hists):
                    fit["asymmetric"].linecolor = hist.GetLineColor()
                    fit["asymmetric"].Draw("same")

            # Add labels
            label_canvas()

            # Add a legend
            legend = Legend(
                len(hists),
                header=self.legend_title,
                topmargin=0.35,
                rightmargin=0.3,
                leftmargin=0.7,
                textsize=0.025,
                entryheight=0.028,
            )
            for hist, label in zip(hists, labels):
                legend.AddEntry(hist, label)
            legend.SetBorderSize(0)
            legend.Draw()

            xmin = 0
            xmax = self.x_max
            # TODO: also specialisation, needs removal
            if ("HT" in name):
                xmax = 800
                xmin = 30
            if ("MET" in name):
                xmin = 0
                xmax = 400
            if ("Jet" in name):
                xmin = 20
                xmax = 400
            if ("HiRange" in name):
                xmax = 2000

            for val in [0.25, 0.5, 0.75, 0.95, 1.]:
                line = ROOT.TLine(xmin, val, xmax, val)
                line.SetLineStyle("dashed")
                line.SetLineColor(15)
                line.Draw()

            for val in range(100, xmax, 100):
                line = ROOT.TLine(val, 0., val, 1.)
                line.SetLineStyle("dashed")
                line.SetLineColor(15)
                line.Draw()

            # Save canvas to file
            self.save_canvas(canvas, name)
Beispiel #21
0
                    print("Temporary filename: {}".format(filename))
                    f.seek(0, os.SEEK_END)
                    print("f length with localfile: {}".format(f.tell()))
                    f.write("Appended information in temp file.\n")
                    f.seek(0)
                    print("f.read(): {}".format(f.read()))
        except ErrorInGettingFile as e:
            print(e)

    if rootFile:
        try:
            with FileWithLocalFilename(
                    filename="246980/EMC/EMChists.2015_12_13_5_7_22.root",
                    writeFile=writeFile) as filename:
                print("Temporary filename: {}".format(filename))
                testHist = ROOT.TH1F("testHist", "testHist", 10, 0, 10)
                testHist.Fill(3)
                # Stricktly speaking, this only works on unix! But this should be fine for our purposes,
                # as Overwatch is not designed to work on Windows anyway.
                # "RECREATE" will not work, as the file is being recreated in a way that isn't
                # compatiable with the temp file!
                with rootpy.io.root_open(filename, "UPDATE") as f:
                    print("f.ls()  pre write:")
                    # Needs to be in a separate line. Otherwise, it will print before saying "pre/post write"
                    f.ls()

                    # Write hist
                    testHist.Write()

                    # Needs to be in a separate line. Otherwise, it will print before saying "pre/post write"
                    print("f.ls() post write:")
Beispiel #22
0
def SRlabel(input):
    plottitle = ROOT.TLatex(labelmargin, 0.745, input)
    plottitle.SetTextFont(43)
    plottitle.SetTextSize(canvasheight * labelscale * 1.0)
    plottitle.SetNDC()
    plottitle.Draw()
Beispiel #23
0
def toprightplotlabel(input):
    plottitle = ROOT.TLatex(0.74, 0.971, input)
    plottitle.SetTextFont(43)
    plottitle.SetTextSize(canvasheight * labelscale)
    plottitle.SetNDC()
    plottitle.Draw()
Beispiel #24
0
def topleftplotlabel(input):
    plottitle = ROOT.TLatex(labelmargin, 0.974, input)
    plottitle.SetTextFont(43)
    plottitle.SetTextSize(canvasheight * labelscale)
    plottitle.SetNDC()
    plottitle.Draw()
Beispiel #25
0
    def __init__(self,
                 files=None,
                 outname=None,
                 type='MC',
                 dtag='',
                 maxevents=-1,
                 channel=['4mu', '2mu2e'],
                 ctau=None,
                 chargedlj=False):

        if type.upper() not in ['MC', 'DATA']:
            raise ValueError("Argument `type` need to be MC/DATA")
        self.OutName = outname
        self.Type = type.upper()
        self.ChargedLJ = chargedlj
        self.MaxEvents = maxevents
        self.Channel = channel
        self.Dtag = dtag
        self.Ctau = ctau
        __signal_sample_param = dict(
            [substr.split('-') for substr in self.Dtag.split('_')])
        self.SignalParam = {
            k.upper(): float(v.replace('p', '.'))
            for k, v in __signal_sample_param.items()
        }

        if not files: raise ValueError("Argument `files` need to be non-empty")
        if isinstance(files, str): files = [
                files,
        ]
        self.Chain = TreeChain('ffNtuplizer/ffNtuple', files)

        ### register collections ###
        # self.Chain.define_collection('pvs', prefix='pv_', size='pv_n')
        self.Chain.define_collection('electrons',
                                     prefix='electron_',
                                     size='electron_n')
        self.Chain.define_collection('muons', prefix='muon_', size='muon_n')
        self.Chain.define_collection('dsamuons',
                                     prefix='dsamuon_',
                                     size='dsamuon_n')
        self.Chain.define_collection('photons',
                                     prefix='photon_',
                                     size='photon_n')
        self.Chain.define_collection('ak4jets',
                                     prefix='akjet_ak4PFJetsCHS_',
                                     size='akjet_ak4PFJetsCHS_n')
        self.Chain.define_collection('hftagscores',
                                     prefix='hftagscore_',
                                     size='hftagscore_n')
        self.Chain.define_collection('leptonjets',
                                     prefix='pfjet_',
                                     size='pfjet_n',
                                     mix=LeptonJetMix)
        self.Chain.define_collection('ljsources',
                                     prefix='ljsource_',
                                     size='ljsource_n')
        self.Chain.define_collection('cosmicmuons',
                                     prefix='cosmicmuon_',
                                     size='cosmicmuon_n')

        self.Chain.define_collection('trigobjs',
                                     prefix='trigobj_',
                                     size='trigobj_n')
        #        self.Chain.define_collection('',)

        self.Chain.define_object('hlt', prefix='HLT_')
        self.Chain.define_object('metfilters', prefix='metfilters_')
        self.Chain.define_object('cosmicveto', prefix='cosmicveto_')

        self.Triggers = [
            "DoubleL2Mu23NoVtx_2Cha",
            "DoubleL2Mu23NoVtx_2Cha_NoL2Matched",
            "DoubleL2Mu23NoVtx_2Cha_CosmicSeed",
            "DoubleL2Mu23NoVtx_2Cha_CosmicSeed_NoL2Matched",
            "DoubleL2Mu25NoVtx_2Cha_Eta2p4",
            "DoubleL2Mu25NoVtx_2Cha_CosmicSeed_Eta2p4",
        ]

        #self.addTRG = [
        # "DoubleL2Mu23NoVtx_2Cha",]

        self.Histos = {}
        for chan in channel:
            self.Histos['{}/cutflow'.format(chan)] = ROOT.Hist(
                20, 0, 20, title='cutflow', drawstyle='hist')
        self.KeepCutFlow = False
        self.RawCutFlow = False

        self.LookupWeight = root_open(
            os.path.join(
                os.getenv('CMSSW_BASE'),
                'src/FireROOT/Analysis/data/PUWeights_2018.root')).Get(
                    'puWeights')
        self.LookupMuonSFLowpT = root_open(
            os.path.join(os.getenv('CMSSW_BASE'),
                         'src/FireROOT/Analysis/data/mu_Loose_pt7.root')).Get(
                             'ratio_syst')
        self.LookupMuonSF = root_open(
            os.path.join(os.getenv('CMSSW_BASE'),
                         'src/FireROOT/Analysis/data/RunABCD_SF_ID.root')).Get(
                             'NUM_LooseID_DEN_TrackerMuons_pt_abseta_syst')
        self.LookupElectronSF = root_open(
            os.path.join(
                os.getenv('CMSSW_BASE'),
                'src/FireROOT/Analysis/data/2018_ElectronLoose.root')).Get(
                    'EGamma_SF2D')
        self.LookupPhotonSF = root_open(
            os.path.join(
                os.getenv('CMSSW_BASE'),
                'src/FireROOT/Analysis/data/2018_PhotonsLoose.root')).Get(
                    'EGamma_SF2D')
        self.Scale = 1.
ROOT.gInterpreter.Declare(
    '#include "external/ExRootAnalysis/ExRootTreeReader.h"')
from include.utils import pTof, pTetaphiIDof, get_process_ID_VV3body
from include.utils import get_process_ID_iterate, get_first_ino_ID, get_first_squark_ID, get_squark_ino_ID, get_squark_q_ID  # For ino-jet

num_particle_IDs = 6
num_jet_IDs = 8
debug = 0

inputFile = sys.argv[1]
outputFile = sys.argv[2]

if len(sys.argv) > 3:
    debug = int(sys.argv[3])

chain = ROOT.TChain("Delphes")

try:
    chain.Add(inputFile)
except:
    print("Unable to load file", inputFile, flush=True)

treeReader = ROOT.ExRootTreeReader(chain)
numevents = treeReader.GetEntries()
#numevents = 100

branchParticle = treeReader.UseBranch("Particle")

# Figure out how many good events we have
numpass = numevents
Beispiel #27
0
    t_tree_ppd_out.geocentric_d = t_tree_ppd_in.geocentric_d
    t_tree_ppd_out.ship_time_sec = t_tree_ppd_in.ship_time_sec
    t_tree_ppd_out.utc_time_sec = t_tree_ppd_in.utc_time_sec
    t_tree_ppd_out.utc_time_str = str(t_tree_ppd_in.utc_time_str)
    t_tree_ppd_out.flag_of_pos = t_tree_ppd_in.flag_of_pos
    t_tree_ppd_out.det_z_ra = t_tree_ppd_in.det_z_ra
    t_tree_ppd_out.det_z_dec = t_tree_ppd_in.det_z_dec
    t_tree_ppd_out.det_x_ra = t_tree_ppd_in.det_x_ra
    t_tree_ppd_out.det_x_dec = t_tree_ppd_in.det_x_dec
    t_tree_ppd_out.earth_ra = t_tree_ppd_in.earth_ra
    t_tree_ppd_out.earth_dec = t_tree_ppd_in.earth_dec
    t_tree_ppd_out.fill()

t_file_in.close()

t_file_out.cd()
t_tree_ppd_out.write()
ROOT.TNamed('m_dattype', 'PLATFORM PARAMETERS DATA of LEVEL 1').Write()
ROOT.TNamed('m_version', SW_NAME + " " + SW_VERSION).Write()
ROOT.TNamed('m_gentime', datetime.now(tzlocal()).isoformat()).Write()
ROOT.TNamed('m_dcdfile', basename(args.filename)).Write()
ROOT.TNamed('m_shipspan', m_shipspan.GetTitle()).Write()
ROOT.TNamed('m_utc_span', m_utc_span.GetTitle()).Write()

t_file_out.close()

print '====================================================================='
print 'shiptime span: { ' + m_shipspan.GetTitle() + ' }'
print 'UTC time span: { ' + m_utc_span.GetTitle() + ' }'
print '====================================================================='
Beispiel #28
0
 def total_entries(files, tree):
     from rootpy import ROOT
     chain = ROOT.TChain(tree)
     for _file in files:
         chain.Add(_file)
     return chain.GetEntries()
Beispiel #29
0
try:
  ROOT.gInterpreter.Declare('#include "classes/DelphesClasses.h"')
  ROOT.gInterpreter.Declare('#include "external/ExRootAnalysis/ExRootTreeReader.h"')
except:
  pass



# Read & Write File
inputFile = args.infile

if args.save:
	outputFile = root_open("W-mass.root","recreate")

# Create chain of root trees
chain = ROOT.TChain("Delphes")
chain.Add(inputFile)

# Create object of class ExRootTreeReader
treeReader = ROOT.ExRootTreeReader(chain)
numberOfEntries = treeReader.GetEntries()

# Get pointers to branches used in this analysis
branchMET = treeReader.UseBranch("MissingET")
branchElectron = treeReader.UseBranch("Electron")

# Define histograms
histMass = ROOT.TH1F("mass", "W^{+} Transverse Mass",100, 0, 300.0)


Beispiel #30
0
def pvalue_plot(poi,
                pvalues,
                pad=None,
                xtitle='X',
                ytitle='P_{0}',
                linestyle=None,
                linecolor=None,
                yrange=None,
                verbose=False):
    """
    Draw a pvalue plot

    Parameters
    ----------
    poi : list
        List of POI values tested
    pvalues : list
        List of p-values or list of lists of p-values to overlay
        multiple p-value curves
    pad : Canvas or Pad, optional (default=None)
        Pad to draw onto. Create new pad if None.
    xtitle : str, optional (default='X')
        The x-axis label (POI name)
    ytitle : str, optional (default='P_{0}')
        The y-axis label
    linestyle : str or list, optional (default=None)
        Line style for the p-value graph or a list of linestyles for
        multiple p-value graphs.
    linecolor : str or list, optional (default=None)
        Line color for the p-value graph or a list of linestyles for
        multiple p-value graphs.

    Returns
    -------
    pad : Canvas
        The pad.
    graphs : list of Graph
        The p-value graphs

    """
    if not pvalues:
        raise ValueError("pvalues is empty")
    if not poi:
        raise ValueError("poi is empty")
    # determine if pvalues is list or list of lists
    if not isinstance(pvalues[0], (list, tuple)):
        pvalues = [pvalues]
    if linecolor is not None:
        if not isinstance(linecolor, list):
            linecolor = [linecolor]
        linecolor = cycle(linecolor)
    if linestyle is not None:
        if not isinstance(linestyle, list):
            linestyle = [linestyle]
        linestyle = cycle(linestyle)

    with preserve_current_canvas():
        if pad is None:
            pad = Canvas()
        pad.cd()
        pad.SetLogy()

        # create the axis
        min_poi, max_poi = min(poi), max(poi)
        haxis = Hist(1000, min_poi, max_poi)
        xaxis = haxis.xaxis
        yaxis = haxis.yaxis
        xaxis.SetRangeUser(min_poi, max_poi)
        haxis.Draw('AXIS')

        min_pvalue = float('inf')
        graphs = []
        for ipv, pv in enumerate(pvalues):
            graph = Graph(len(poi),
                          linestyle='dashed',
                          drawstyle='L',
                          linewidth=2)
            for idx, (point, pvalue) in enumerate(zip(poi, pv)):
                graph.SetPoint(idx, point, pvalue)
            if linestyle is not None:
                graph.linestyle = linestyle.next()
            if linecolor is not None:
                graph.linecolor = linecolor.next()
            graphs.append(graph)
            curr_min_pvalue = min(pv)
            if curr_min_pvalue < min_pvalue:
                min_pvalue = curr_min_pvalue

        if verbose:
            for graph in graphs:
                log.info(['{0:1.1f}'.format(xval) for xval in list(graph.x())])
                log.info(['{0:0.3f}'.format(yval) for yval in list(graph.y())])

        # automatically handles axis limits
        axes, bounds = draw(graphs,
                            pad=pad,
                            same=True,
                            logy=True,
                            xtitle=xtitle,
                            ytitle=ytitle,
                            xaxis=xaxis,
                            yaxis=yaxis,
                            ypadding=(0.2, 0.1),
                            logy_crop_value=1E-300)

        if yrange is not None:
            xaxis, yaxis = axes
            yaxis.SetLimits(*yrange)
            yaxis.SetRangeUser(*yrange)
            min_pvalue = yrange[0]

        # draw sigma levels up to minimum of pvalues
        line = Line()
        line.SetLineStyle(2)
        line.SetLineColor(2)
        latex = ROOT.TLatex()
        latex.SetNDC(False)
        latex.SetTextSize(20)
        latex.SetTextColor(2)
        sigma = 0
        while True:
            pvalue = gaussian_cdf_c(sigma)
            if pvalue < min_pvalue:
                break
            keepalive(
                pad,
                latex.DrawLatex(max_poi, pvalue, " {0}#sigma".format(sigma)))
            keepalive(pad, line.DrawLine(min_poi, pvalue, max_poi, pvalue))
            sigma += 1

        pad.RedrawAxis()
        pad.Update()
    return pad, graphs