def createCanvas(event, goodJets, goodBJets, Leptons, etmiss, imageDir) :

    pt_bins = [0.,10.,20.,30.,50.,100.,250.,500.,1000.,1500.,2000.]
    histo_bin =  ROOT.TH1D("hito_bins", "p_{T} [GeV]", len(pt_bins)-1, array('d', pt_bins))

    # Create the empty figure
    ecolors = {"leptons" : TColor(10007, 0., 1.0, 0.), "bjet" : TColor(10004,1., 0., 0.), "jet": TColor(10003,1,0.5,0.5), "etmiss" : TColor(10006,0.,0,0.9), "mltop" : TColor(10005,0,0,1)}
    fcolors = {"leptons" : TColor(20007, 0., 1.0, 0.), "bjet" : TColor(20004,1., 0., 0.), "jet": TColor(20003,1,0.5,0.5), "etmiss" : TColor(20006,0.,0,0.9), "mltop" : TColor(20005,0,0,0)}

    ecol = []
    fcol = []
    for x in ecolors :
      ecol.append(ecolors[x])
      fcol.append(fcolors[x])

    import os
    if not os.path.exists(imageDir): os.makedirs(imageDir)
    image_name = imageDir+"/"+str(event)+".jpg"

    size = 224
    c1 = TCanvas("c1", "c1", size, size)
    c1.Range(-4.5,-math.pi,4.5,math.pi);
    c1.SetCanvasSize(size,size);

    jets = []
    # Represent Jets
    for jet in goodBJets :
        scalePt = 1.5*histo_bin.GetXaxis().FindBin(jet.Pt())

        elj = DrawObjectROOT(jet, scalePt, "bjet")
        jets.append(elj)
        jets[-1].Draw()

    # Represent Jets
    for jet in goodJets :
        scalePt = 1.5*histo_bin.GetXaxis().FindBin(jet.Pt())

        elj = DrawObjectROOT(jet, scalePt, "jet")
        jets.append(elj)
        jets[-1].Draw()

    scalePt = 1.5*histo_bin.GetXaxis().FindBin(etmiss.Pt())
    elmet = DrawObjectROOT(etmiss, scalePt, "etmiss")
    elmet.Draw()


    # Represent Leptons
    scalePt = 1.5*histo_bin.GetXaxis().FindBin(Leptons[0].Pt())
    ell = DrawObjectROOT(Leptons[0], scalePt, "leptons")
    ell.Draw()

    #'event_numEvent.jpg'
    img = TASImage()
    img.FromPad(c1);
    img.SetImageQuality(3)
    img.SetImageCompression(50)
    img.WriteImage(image_name);
Esempio n. 2
0
    def color_loader(self, palette, key=''):
        from ROOT import TColor
        import seaborn as sns

        colors = sns.color_palette(palette)

        if key not in self.tcolor_dict:
            self.tcolor_dict[key] = [TColor(*rgb) for rgb in colors]
            colors = self.color_dict[key] = [
                tcolor.GetNumber() for tcolor in self.tcolor_dict[key]
            ]
        else:
            colors = self.color_dict[key]

        color_it = iter(colors)

        centrality_colors = {}

        def centrality_color(cent):
            cent = cent.rstrip('%')
            centparts = cent.split('-') if '-' in cent else cent.split('_')
            cent_key = tuple('%g' % float(f) for f in centparts)
            if cent_key not in centrality_colors:
                centrality_colors[cent_key] = next(color_it)
            return centrality_colors[cent_key]

        return centrality_color
Esempio n. 3
0
 def __new__(cls, r, g, b, name=""):
     self = int.__new__(cls, TColor.GetFreeColorIndex())
     self.object = TColor(self,
                          float(r) / float(255),
                          float(g) / float(255),
                          float(b) / float(255), name, 1.0)
     self.name = name
     return self
Esempio n. 4
0
def defineColors(color_code='ColorCombo424'):
    colors = {}
    rgb = 255.
    for color_number in color_codes[color_code]:
        colors[color_number] = TColor(
            color_number,
            color_codes[color_code][color_number][0] / rgb,
            color_codes[color_code][color_number][1] / rgb,
            color_codes[color_code][color_number][2] / rgb,
        )
    return colors
Esempio n. 5
0
    def draw(self, c=None):
        from ROOT import TGraphErrors, TCanvas

        import seaborn as sns

        if self.colors is None:
            from ROOT import TColor
            self.tcolors = [
                TColor(*color) for color in sns.color_palette("Paired")
            ]
            self.colors = [tcol.GetNumber() for tcol in self.tcolors]

        if c is None:
            c = TCanvas()

        plot = PlotData(c)

        return plot
Esempio n. 6
0
def _defaultColors():
    from ROOT import TColor

    _rgbcolors = [  # some rgb colors (taken from MATLABs default palette)
        [0, 0.4470, 0.7410], [0.8500, 0.3250, 0.0980],
        [0.9290, 0.6940, 0.1250], [0.4940, 0.1840, 0.5560],
        [0.4660, 0.6740, 0.1880], [0.3010, 0.7450, 0.9330],
        [0.6350, 0.0780, 0.1840]
    ]

    global _colors
    global _colorIndices

    if not _colors:  # only define the global colors if they are not already defined
        _getNewIdx = TColor.GetFreeColorIndex  # bind function call to local variable for less typing
        _colors = [(_getNewIdx(),
                    TColor(_getNewIdx(), _rgbcolors[i][0], _rgbcolors[i][1],
                           _rgbcolors[i][2])) for i in range(len(_rgbcolors))]
        _colorIndices = [i[0] for i in _colors]

    return _colorIndices
Esempio n. 7
0
def default_colors():
    """Get a list of some nicer colors for plotting than ROOTs default.

    Creates the colors that correspond to MATLABs default palette so that they
    can be used with ROOT as well. On the first call the colors will be
    initialized and stored in module variables. Subsequent calls will only
    retrieve the cached values.

    Returns:
        list: list of integers that can be used in ROOTs SetColor methods.
    """
    from ROOT import TColor

    global _colors
    global _color_indices

    if not _colors:  # only define colors if they have not been defined already
        rgbcolors = [  # rgb values of MATLABs default palette
            [0, 0.4470, 0.7410],  # darkish blue
            [0.8500, 0.3250, 0.0980],  # "orangeish" red
            [0.9290, 0.6940, 0.1250],  # yellow
            [0.4940, 0.1840, 0.5560],  # purple
            [0.4660, 0.6740, 0.1880],  # green
            [0.3010, 0.7450, 0.9330],  # lightish blue
            [0.6350, 0.0780, 0.1840]  # wine red
        ]

        # bind TColor.GetFreeColorIndex to a shorter name for less typing
        # repeatedly calling TColor.GetFreeColorIndex in the list creation is OK
        # since it returns a different index only once it has been used.
        get_idx = TColor.GetFreeColorIndex
        _colors = [(get_idx(), TColor(get_idx(), red, green, blue))
                   for (red, green, blue) in rgbcolors]

        _color_indices = [col[0] for col in _colors]

    return _color_indices
Esempio n. 8
0
def _defaultColors():
    from ROOT import TColor

    global _colors
    global _colorIndices

    if not _colors:  # only define the global colors if they are not already defined
        _rgbcolors = [  # some rgb colors (taken from MATLABs default palette)
            [0, 0.4470, 0.7410], [0.8500, 0.3250, 0.0980],
            [0.9290, 0.6940, 0.1250], [0.4940, 0.1840, 0.5560],
            [0.4660, 0.6740, 0.1880], [0.3010, 0.7450, 0.9330],
            [0.6350, 0.0780, 0.1840]
        ]

        # calling TColor.GetFreeColorIndex returns a different index only after
        # it has actually been 'used', so that calling it twice in the tuple creation
        # is OK
        _getNewIdx = TColor.GetFreeColorIndex  # bind function call to local variable for less typing
        _colors = [(_getNewIdx(),
                    TColor(_getNewIdx(), _rgbcolors[i][0], _rgbcolors[i][1],
                           _rgbcolors[i][2])) for i in range(len(_rgbcolors))]
        _colorIndices = [i[0] for i in _colors]

    return _colorIndices
Esempio n. 9
0
def applyRootStyle():

    from ROOT import gROOT, gStyle, kWhite, kBlack, TColor

    # Start from a plain default
    gROOT.SetStyle("Plain")

    lhcbMarkerType = 8
    lhcbMarkerSize = 0.8
    lhcbFont = 62
    lhcbStatFontSize = 0.02
    lhcbStatBoxWidth = 0.12
    lhcbStatBoxHeight = 0.12
    lhcbWidth = 1
    lhcbTextSize = 0.05
    lhcbLabelSize = 0.035
    lhcbAxisLabelSize = 0.035
    lhcbForeColour = kBlack

    gStyle.SetFrameBorderMode(0)
    gStyle.SetPadBorderMode(0)

    # canvas options
    gStyle.SetCanvasBorderSize(0)
    gStyle.SetCanvasBorderMode(0)

    # fonts
    gStyle.SetTextFont(lhcbFont)
    gStyle.SetTextSize(lhcbTextSize)
    gStyle.SetLabelFont(lhcbFont, "x")
    gStyle.SetLabelFont(lhcbFont, "y")
    gStyle.SetLabelFont(lhcbFont, "z")
    gStyle.SetLabelSize(lhcbLabelSize, "x")
    gStyle.SetLabelSize(lhcbLabelSize, "y")
    gStyle.SetLabelSize(lhcbLabelSize, "z")
    gStyle.SetTitleFont(lhcbFont)
    gStyle.SetTitleSize(lhcbAxisLabelSize, "x")
    gStyle.SetTitleSize(lhcbAxisLabelSize, "y")
    gStyle.SetTitleSize(lhcbAxisLabelSize, "z")
    gStyle.SetTitleColor(kWhite)
    gStyle.SetTitleFillColor(kWhite)
    gStyle.SetTitleColor(kBlack)
    gStyle.SetTitleBorderSize(0)
    gStyle.SetTitleTextColor(kBlack)

    # set title position
    gStyle.SetTitleX(0.15)
    gStyle.SetTitleY(0.97)
    # turn off Title box
    gStyle.SetTitleBorderSize(0)
    gStyle.SetTitleTextColor(lhcbForeColour)
    gStyle.SetTitleColor(lhcbForeColour)

    # use bold lines and markers
    gStyle.SetLineWidth(lhcbWidth)
    gStyle.SetFrameLineWidth(lhcbWidth)
    gStyle.SetHistLineWidth(lhcbWidth)
    gStyle.SetFuncWidth(lhcbWidth)
    gStyle.SetGridWidth(lhcbWidth)
    gStyle.SetLineStyleString(2, "[12 12]")
    gStyle.SetMarkerStyle(lhcbMarkerType)
    gStyle.SetMarkerSize(lhcbMarkerSize)

    # Grid
    # gStyle.SetGridStyle(3)

    # label offsets
    gStyle.SetLabelOffset(0.015)

    # by default, do not display histogram decorations:
    gStyle.SetOptStat(1111)
    # show probability, parameters and errors
    gStyle.SetOptFit(1011)

    # look of the statistics box:
    gStyle.SetStatBorderSize(1)
    gStyle.SetStatFont(lhcbFont)
    gStyle.SetStatFontSize(lhcbStatFontSize)
    gStyle.SetStatX(0.9)
    gStyle.SetStatY(0.9)
    gStyle.SetStatW(lhcbStatBoxWidth)
    gStyle.SetStatH(lhcbStatBoxHeight)

    # put tick marks on top and RHS of plots
    gStyle.SetPadTickX(1)
    gStyle.SetPadTickY(1)

    # histogram divisions
    gStyle.SetNdivisions(505, "x")
    gStyle.SetNdivisions(510, "y")

    # Style for 2D zcol plots
    NRGBs = 5
    NCont = 255
    from array import array
    stops = array('d', [0.00, 0.34, 0.61, 0.84, 1.00])
    red = array('d', [0.00, 0.00, 0.87, 1.00, 0.51])
    green = array('d', [0.00, 0.81, 1.00, 0.20, 0.00])
    blue = array('d', [0.51, 1.00, 0.12, 0.00, 0.00])
    TColor().CreateGradientColorTable(NRGBs, stops, red, green, blue, NCont)
    gStyle.SetNumberContours(NCont)

    # Force the style
    gROOT.ForceStyle()
Esempio n. 10
0
import ROOT
from ROOT import TColor

palette = {
    'blue':
    TColor(TColor.GetFreeColorIndex(), 31. / 256., 119. / 256., 180. / 256.),
    'red':
    TColor(TColor.GetFreeColorIndex(), 214. / 256., 39. / 256., 40. / 256.),
}

d = ROOT.ROOT.RDataFrame("T", "htree.root")
d = d.Define("cosTheta", "cos(event.theta)")
d = d.Define("negHelMinus", "-event.helMinus")

c = ROOT.TCanvas("c", "c", 600, 600)
c.SetLeftMargin(.15)
c.SetBottomMargin(.15)
c.SetRightMargin(.05)
c.SetTopMargin(.05)
ROOT.gStyle.SetOptFit(1)
ROOT.gStyle.SetOptStat("e")
model = ("", "", 40, -1., 1.)
p1 = d.Profile1D(model, "cosTheta", "negHelMinus")
p2 = p1.Clone("p2")
p3 = p1.Clone("p3")

print(
    f"Underflow : {p1.GetBinContent(0)}\t\tOverflow : {p1.GetBinContent(p1.GetNbinsX()+1)}"
)
p1.Draw()
Esempio n. 11
0
from ROOT import TColor

palette = {
    'blue':
    TColor(TColor.GetFreeColorIndex(), 31. / 255., 119. / 255., 180. / 255.),
    'orange':
    TColor(TColor.GetFreeColorIndex(), 255. / 255., 127. / 255., 14. / 255.),
    'green':
    TColor(TColor.GetFreeColorIndex(), 44. / 255., 160. / 255., 44. / 255.),
    'red':
    TColor(TColor.GetFreeColorIndex(), 214. / 255., 39. / 255., 40. / 255.),
    'purple':
    TColor(TColor.GetFreeColorIndex(), 148. / 255., 103. / 255., 189. / 255.),
    'brown':
    TColor(TColor.GetFreeColorIndex(), 140. / 255., 86. / 255., 75. / 255.),
    'pink':
    TColor(TColor.GetFreeColorIndex(), 227. / 255., 119. / 255., 194. / 255.),
    'grey':
    TColor(TColor.GetFreeColorIndex(), 127. / 255., 127. / 255., 127. / 255.),
    'lightgreen':
    TColor(TColor.GetFreeColorIndex(), 188. / 255., 189. / 255., 34. / 255.),
    'cyan':
    TColor(TColor.GetFreeColorIndex(), 23. / 255., 190. / 255., 207. / 255.)
}

palette['neutral'] = palette['grey']
palette['e-'] = palette['blue']
palette['pi-'] = palette['red']
palette['mu-'] = palette['orange']
palette['gamma'] = palette['green']
palette['Scnt'] = palette['red']
Esempio n. 12
0
og = 1031
re = 1020
dr = 1021
ddr = 1010
dp = 1011
lg = 1000
gr = 1001
dg = 1002
lg = 1003
lm = 1050
ms = 1051
dm = 1052
yw = 1053
pr = 1022

vlightblue = TColor(1040, 180 / 255., 235 / 255.,
                    250 / 255.)  # very light blue - Zll (Fake)
lightblue = TColor(1041, 82 / 255., 195 / 255.,
                   229 / 255.)  # light blue - Zll (True)
blue = TColor(1042, 66 / 255., 156 / 255., 183 / 255.)  # blue - Ztautau (Fake)
darkblue = TColor(1043, 30 / 255., 123 / 255.,
                  150 / 255.)  # darker blue - Ztautau (True)
lightorange = TColor(1030, 237 / 255., 195 / 255.,
                     120 / 255.)  # light orange - W+Jets (Fake)
orange = TColor(1031, 237 / 255., 164 / 255.,
                45 / 255.)  # orange - W+Jets (True)
red = TColor(1020, 220 / 255., 120 / 255.,
             100 / 255.)  # red - SingleTop (Fake)
prperred = TColor(1022, 220 / 255., 87 / 255., 60 / 255.)  # red - ttbar (Fake)
darkred = TColor(1021, 220 / 255., 60 / 255.,
                 30 / 255.)  # darker red - SingleTop (True)
darkpurple = TColor(1010, 103 / 255., 73 / 255.,
Esempio n. 13
0
def CreateHistogramNP(df,
                      column_name,
                      name,
                      label,
                      variable='n',
                      color=0,
                      lumi=1,
                      Rebin=1):

    if type(color) == str:
        c1 = TColor()
        color = c1.GetColor(color)

    a = interval_from_string(df[column_name])
    nBins = len(a) - 2  #excluding under/overflow bins from plots

    bins = []
    bins = a.left[
        1:]  #excluding the underflow bin, but keeping the overflow as we want the last bin edge - which happens to be the left edge of the overflow bin
    #print(bins)
    # if ('eta' in column_name.lower()) | ('phi' in column_name.lower()):
    #     #print(bins)
    #     bins = np.round(bins, decimals=1)
    #     #print(bins)
    d_bins = array('d', bins)

    Ok_to_rebin = False

    if Rebin > 1:
        if not (nBins % Rebin):
            #        #print "Ok to rebin."
            Ok_to_rebin = True
    #   else:
    #       #print "Not ok to rebin -- using orginal binning scheme with ", nBins, " bins."

    h_test = ROOT.TH1D("h_" + name, ";" + label + ";Events;;", nBins, d_bins)

    if Ok_to_rebin:
        counter = 0
        value = 0
        N = 0
        #print("Rebin :"+str(Rebin))
        h_test.Rebin(Rebin)

        for i in range(1, nBins +
                       2):  # has to go to N+1 in order to fill the last bin

            #print i
            if (counter >= Rebin):
                #print "Bin rebinned", int(i/Rebin)
                #print "With value = ", value
                #print 1.0*int(i/Rebin)
                h_test.SetBinContent(int(i / Rebin), value)
                if N > 0:
                    h_test.SetBinError(int(i / Rebin), value / math.sqrt(N))
                else:
                    h_test.SetBinError(int(i / Rebin), 0)

                if variable != 'n':
                    h_test.SetBinContent(
                        int(i / Rebin),
                        h_test.GetBinContent(int(i / Rebin)) * lumi)
                    h_test.SetBinError(
                        int(i / Rebin),
                        h_test.GetBinError(int(i / Rebin)) * lumi)

                if (i < nBins + 1):
                    counter = 1
                    value = df[variable][i]
                    N = df['n'][i]

            else:
                #print "Counter will increase", counter
                #print "Value",  value
                #print "N",  N

                value = value + df[variable][i]
                N = N + df['n'][i]
                counter = counter + 1

    else:

        for i in range(1, nBins + 1):
            h_test.SetBinContent(i, df[variable][i])
            if df[variable][i] > 0:
                h_test.SetBinError(i, df[variable][i] / math.sqrt(df['n'][i]))
            else:
                h_test.SetBinError(i, 0)
            if variable != 'n':
                h_test.SetBinContent(i, h_test.GetBinContent(i) * lumi)
                h_test.SetBinError(i, h_test.GetBinError(i) * lumi)

    if color != 0:
        h_test.SetFillColor(color)
        h_test.SetLineColor(color)

    h_test.GetXaxis().SetRangeUser(bins[0], bins[-1])

    return h_test
Esempio n. 14
0
def convert_color(color, mode):
    """
    Convert *color* to a TColor if *mode='root'* or to (r,g,b,a) if 'mpl'.

    The *color* argument can be a ROOT TColor or color index, an *RGB*
    or *RGBA* sequence or a string in any of several forms:

        1) a letter from the set 'rgbcmykw'
        2) a hex color string, like '#00FFFF'
        3) a standard name, like 'aqua'
        4) a float, like '0.4', indicating gray on a 0-1 scale

    if *arg* is *RGBA*, the *A* will simply be discarded.

    >>> convert_color(2)
    (1.0, 0.0, 0.0)
    >>> convert_color('b')
    (0.0, 0.0, 1.0)
    >>> convert_color('blue')
    (0.0, 0.0, 1.0)
    >>> convert_color('0.25')
    (0.25, 0.25, 0.25)
    """
    mode = mode.lower()
    if mode != 'mpl' and mode != 'root':
        raise ValueError("%s is not an understood value for mode" % mode)
    # if color is None:
    #     return None
    # elif color == 'none' or color == 'None':
    #     return 'none'
    # temp fix. needs improvement.
    if __use_matplotlib:
        try:  # color is a TColor
            _color = TColor(color)
            rgb = _color.GetRed(), _color.GetGreen(), _color.GetBlue()
            return convert_color(rgb, mode)
        except (TypeError, ReferenceError):
            pass
        try:  # color is a ROOT color index
            _color = gROOT.GetColor(color)
            rgb = _color.GetRed(), _color.GetGreen(), _color.GetBlue()
            return convert_color(rgb, mode)
        except (TypeError, ReferenceError):
            pass
        try:  # color is an (r,g,b) tuple from 0 to 255
            if max(color) > 1.:
                color = [x / 255. for x in color][0:3]
        except TypeError:
            pass
        # color is something understood by matplotlib
        color = colorConverter.to_rgb(color)
        if mode == 'root':
            return TColor.GetColor(*color)
    else:  # fall back on internal conversion
        if color in __colors.values():
            return color
        if color in __colors:
            color = __colors[color]
        elif type(color) is int:
            return color
        else:
            raise ValueError("Color %s is not understood" % repr(color))
    return color
Esempio n. 15
0
def ExportPlot(TDirName, NominalHists, DataHists, SystBand, BatchMode = False):
	if BatchMode:
		ROOT.gROOT.SetBatch()

	c = ROOT.TCanvas("c2", "",800,700)
	c.cd()
	gStyle.SetOptStat(0)
	gStyle.SetHatchesLineWidth(1)
	gStyle.SetErrorX(0)

	logging.info("Defining colour palette ... ")
	colours = {}
	colours["Singletop"]= TColor(3000,54./255, 121./255,191./255)
	colours["ttbar"]=       TColor(3001,123./255, 178./255, 116./255)
	colours["Wjets"]= TColor(3002,130./255, 95./255, 135./255)
	colours["Zjets"]= TColor(3003,252./255, 176./255, 8./255)
	colours["Diboson"]=TColor(3007,168./255, 164./255, 150./255)

	# # Begin work on top pad
	pad1 = CreateTopPad("pad1")
	pad1.cd()
	pad1.SetLogy()
	SetTicks(pad1)

	# Create TLegend
	Legend = CreateLegend()

	# Get systematic band but dont draw
	TopUncertBand = DrawUncHist(SystBand, colours, Legend)

	# Draw MC
	SMHist, MCStack = DrawSMHists(NominalHists, colours, Legend)
	# Then draw the MC stack
	MCStack.Draw("HIST L")
	logging.info("Drawn MC stack")

	SMHist = ApplySystematicBand(SMHist, TopUncertBand)
	# This gives us the error on the SM Hist
	SMHist.Draw("E3 SAME")
	# This gives us the line as well as the hashed fill
	# SMHist.Draw("C SAME")
	logging.info("Drawn SM total with systematic band")

	# Draw Data
	DataHist = DrawDataHists(DataHists, colours, Legend)
	DataHist.Draw("E0 SAME")
	logging.info("Drawn data")

	# Draw Legend
	logging.info("Drawing legend ... ")
	Legend.Draw()

	logging.info("Adding more aesthetic changes ...")
	# Draw ATLAS Text
	ATLASText = DrawATLAS()

	# Begin work on DataMC Ratio
	c.cd()
	pad2 = CreateBottomPad("pad2")
	SetTicks(pad2)
	
	DataMCHist, UncBand = DrawDataMCPad(DataHist, SMHist, pad2)
	DataMCHist.Draw("ep")
	UncBand.Draw("E3 SAME")
	logging.info("Drawn dataMC ratio")

	c.Update()
	logging.info("Finished this plot!")

	PlotName = "Final_"+DataHist.GetName().split("_nominal")[0]
	c.SaveAs("Plots/" + TDirName + "/" + PlotName+".pdf")
	if not BatchMode:
		raw_input()
Esempio n. 16
0
    def analyze(self, createImages=True):

        import math
        #      import matplotlib.pyplot as plt
        import numpy as np

        # retrieving objects
        eventinfo = self.Store.getEventInfo()
        weight = eventinfo.scalefactor() * eventinfo.eventWeight(
        ) * eventinfo.scalefactorBTAG() if not self.getIsData() else 1
        self.countEvent("all", weight)

        # apply standard event based selection
        if not AH.StandardEventCuts(eventinfo): return False
        self.countEvent("EventCuts", weight)

        # neutrinos are expected, so cut on missing transverse momentum
        etmiss = self.Store.getEtMiss()
        if not (etmiss.et() > 30.0): return False
        self.countEvent("MET", weight)

        # one good lepton from one of the W boson decays is expected, so require exactly one good lepton
        goodLeptons = AH.selectAndSortContainer(self.Store.getLeptons(),
                                                AH.isGoodLepton,
                                                lambda p: p.pt())
        if not (len(goodLeptons) == 1): return False
        self.countEvent("1 Lepton", weight)

        leadlepton = goodLeptons[0]

        # two jets from one of the W boson decays as well as two b-jets from the top pair decays are expected
        goodJets = AH.selectAndSortContainer(self.Store.getJets(),
                                             AH.isGoodJet, lambda p: p.pt())
        if not len(goodJets) >= 1: return False
        self.countEvent("Jets", weight)

        # apply the b-tagging requirement using the MV2c10 algorithm at 80% efficiency
        btags = sum([1 for jet in goodJets if jet.mv2c10() > 0.8244273])
        if not (btags >= 1): return False
        self.countEvent("btags", weight)

        # apply a cut on the transverse mass of the W boson decaying to leptons
        if not (AH.WTransverseMass(leadlepton, etmiss) > 30.0): return False

        # histograms for the W boson properties
        self.hist_WtMass.Fill(AH.WTransverseMass(leadlepton, etmiss), weight)
        self.hist_WtMass_max.Fill(
            AH.WTransverseMass(leadlepton, etmiss) *
            (1 + math.sqrt((leadlepton.pt_syst() / leadlepton.pt()) *
                           (leadlepton.pt_syst() / leadlepton.pt()) +
                           (etmiss.et_syst() / etmiss.et()) *
                           (etmiss.et_syst() / etmiss.et())) / 2), weight)
        self.hist_WtMass_min.Fill(
            AH.WTransverseMass(leadlepton, etmiss) *
            (1 - math.sqrt((leadlepton.pt_syst() / leadlepton.pt()) *
                           (leadlepton.pt_syst() / leadlepton.pt()) +
                           (etmiss.et_syst() / etmiss.et()) *
                           (etmiss.et_syst() / etmiss.et())) / 2), weight)

        # histograms for missing et
        self.hist_etmiss.Fill(etmiss.et(), weight)
        self.hist_etmiss_max.Fill(etmiss.et() + etmiss.et_syst(), weight)
        self.hist_etmiss_min.Fill(etmiss.et() - etmiss.et_syst(), weight)

        # histograms detailing lepton information
        self.hist_leptn.Fill(len(goodLeptons), weight)
        self.hist_leptpt.Fill(leadlepton.pt(), weight)
        self.hist_lepteta.Fill(leadlepton.eta(), weight)
        self.hist_leptE.Fill(leadlepton.e(), weight)
        self.hist_leptphi.Fill(leadlepton.phi(), weight)
        self.hist_leptch.Fill(leadlepton.charge(), weight)
        self.hist_leptID.Fill(leadlepton.pdgId(), weight)
        self.hist_lepz0.Fill(leadlepton.z0(), weight)
        self.hist_lepd0.Fill(leadlepton.d0(), weight)
        self.hist_leptptc.Fill(leadlepton.isoptconerel30(), weight)
        self.hist_leptetc.Fill(leadlepton.isoetconerel20(), weight)
        self.hist_leptpt_max.Fill(leadlepton.pt() + leadlepton.pt_syst(),
                                  weight)
        self.hist_leptpt_min.Fill(leadlepton.pt() - leadlepton.pt_syst(),
                                  weight)
        self.hist_leptptc_max.Fill(leadlepton.isoptconerel30_max(), weight)
        self.hist_leptptc_min.Fill(leadlepton.isoptconerel30_min(), weight)
        self.hist_leptetc_max.Fill(leadlepton.isoetconerel20_max(), weight)
        self.hist_leptetc_min.Fill(leadlepton.isoetconerel20_min(), weight)

        # histograms detailing jet information
        self.hist_njets.Fill(len(goodJets), weight)
        [self.hist_jetspt.Fill(jet.pt(), weight) for jet in goodJets]
        [self.hist_jetJVT.Fill(jet.jvt(), weight) for jet in goodJets]
        [self.hist_jeteta.Fill(jet.eta(), weight) for jet in goodJets]
        [self.hist_jetmv2c10.Fill(jet.mv2c10(), weight) for jet in goodJets]
        [
            self.hist_jetspt_max.Fill(jet.pt() + jet.pt_syst(), weight)
            for jet in goodJets
        ]
        [
            self.hist_jetspt_min.Fill(jet.pt() - jet.pt_syst(), weight)
            for jet in goodJets
        ]

        # Fill Histograms
        for jet in goodJets:
            if jet.mv2c10() > 0.8244273:
                self.hist_mlb.Fill(AH.mlb(jet, leadlepton), weight)

        saveCSV = False

        if saveCSV:
            try:
                events_file = open(
                    "results/" + self.Store.filename.replace("root", "csv"),
                    "a+")
            except:
                pass

        csv_row = str(self.Store.dsid) + "," + str(eventinfo.eventNumber())

        if not createImages:
            return True

        VERBOSE = False
        if VERBOSE:
            f = open("ttbar.log", "a+")

        useROOT = True
        # Create Plot

        if useROOT:

            # Create the empty figure
            ecolors = {
                "leptons": TColor(10007, 0., 1.0, 0.),
                "bjet": TColor(10004, 1., 0., 0.),
                "jet": TColor(10003, 1, 0.5, 0.5),
                "etmiss": TColor(10006, 0., 0, 0.9),
                "mltop": TColor(10005, 0.5, 0.5, 0.5)
            }
            fcolors = {
                "leptons": TColor(20007, 0., 1.0, 0.),
                "bjet": TColor(20004, 1., 0., 0.),
                "jet": TColor(20003, 1, 0.5, 0.5),
                "etmiss": TColor(20006, 0., 0, 0.9),
                "mltop": TColor(20005, 0., 0., 1.)
            }

            ecol = []
            fcol = []
            for x in ecolors:
                ecol.append(ecolors[x])
                fcol.append(fcolors[x])

            import os
            if not os.path.exists(self.getImageDir()):
                os.makedirs(self.getImageDir())
            image_name = self.getImageDir() + "/" + str(
                eventinfo.eventNumber()) + ".jpg"

            size = 224
            c1 = TCanvas("c1", "c1", size, size)
            c1.Range(-4.5, -math.pi, 4.5, math.pi)
            c1.SetCanvasSize(size, size)
            jets = []
            csv_jets = ''

            size_factor = 2.
            # Represent Jets
            for jet in goodJets:
                scalePt = size_factor * self.hist_jetspt.GetXaxis().FindBin(
                    jet.pt())
                if VERBOSE:
                    f.write(
                        str(eventinfo.eventNumber()) + " : jet :: " +
                        str(jet.pt()) + " " + str(jet.phi()) + " " +
                        str(jet.eta()) + " " + str(scalePt) + "\n")

                if jet.mv2c10() > 0.8244273:
                    # elm = AH.DrawObjectROOT(jet, scalePt+AH.mlb(jet,leadlepton), "mltop")
                    # jets.append(elm)
                    # jets[-1].Draw()

                    elj = AH.DrawObjectROOT(jet, scalePt, "bjet")
                    jets.append(elj)
                    jets[-1].Draw()
                else:
                    elj = AH.DrawObjectROOT(jet, scalePt, "jet")
                    jets.append(elj)
                    jets[-1].Draw()
                csv_jets += ("," + sfloat(jet.pt()) + "," + sfloat(jet.phi()) +
                             "," + sfloat(jet.eta()) + "," + sfloat(jet.e()) +
                             "," + str(int(jet.mv2c10() > 0.8244273)))

            scalePt = size_factor * self.hist_etmiss.GetXaxis().FindBin(
                etmiss.et())
            elmet = AH.DrawObjectROOT(etmiss, scalePt, "etmiss")
            elmet.Draw()

            if VERBOSE:
                f.write(
                    str(eventinfo.eventNumber()) + " : etmiss :: " +
                    str(etmiss.et()) + " " + str(etmiss.phi()) + " " +
                    str(scalePt) + "\n")
            csv_met = ("," + sfloat(etmiss.et()) + " " + sfloat(etmiss.phi()))

            # Represent Leptons
            scalePt = size_factor * self.hist_leptpt.GetXaxis().FindBin(
                leadlepton.pt())
            if abs(leadlepton.pdgId()) == 11:
                ell = AH.DrawObjectROOT(leadlepton, scalePt, "leptons")
                ell.Draw()
            else:
                ell = AH.DrawObjectROOT(leadlepton, scalePt, "leptons")
                ell.Draw()
            if VERBOSE:
                f.write(
                    str(eventinfo.eventNumber()) + " : lepton :: " +
                    str(leadlepton.pt()) + " " + str(leadlepton.phi()) + " " +
                    str(leadlepton.eta()) + " " + str(scalePt) + "\n")

            csv_lep = ("," + sfloat(leadlepton.pt()) + "," +
                       sfloat(leadlepton.phi()) + "," +
                       sfloat(leadlepton.eta()) + "," + sfloat(leadlepton.e()))

            csv_row += csv_met + csv_lep + csv_jets + "\n"

            if saveCSV:
                events_file.write(csv_row)
                events_file.close()
            '''
        #'event_numEvent.jpg'
        img = TASImage()
        img.FromPad(c1);
        img.SetImageQuality(3)
        img.SetImageCompression(50)
        img.WriteImage(image_name);
'''
            del c1, jets, elj, ell, elmet, ecol, fcol

        else:
            # Create Plot

            import math
            import matplotlib.pyplot as plt

            # Create the empty figure
            fig = plt.figure(frameon=False)
            fig.set_size_inches(4, 4)
            ax = plt.Axes(fig, [0., 0., 1., 1.])
            ax.axis([-3, 3, -math.pi, math.pi])
            fig.add_axes(ax)

            size_factor = 2.
            # Represent Jets
            for jet in goodJets:
                scalePt = size_factor * self.hist_jetspt.GetXaxis().FindBin(
                    jet.pt())
                # scalePt = math.log(jet.pt(),11./10.)
                if VERBOSE:
                    f.write(
                        str(eventinfo.eventNumber()) + " : jet :: " +
                        str(jet.pt()) + " " + str(jet.phi()) + " " +
                        str(jet.eta()) + " " + str(scalePt) + "\n")
                if jet.mv2c10() > 0.8244273:
                    ax.add_artist(AH.DrawObject(jet, scalePt, "bjet"))
                    ax.add_artist(
                        AH.DrawObject(jet, scalePt + AH.mlb(jet, leadlepton),
                                      "top"))

                else:
                    ax.add_artist(AH.DrawObject(jet, scalePt, "jet"))

            # Represent MET
            scalePt = size_factor * self.hist_etmiss.GetXaxis().FindBin(
                etmiss.et())
            # scalePt = math.log(etmiss.et(),11./10.)
            ax.add_artist(AH.DrawObject(etmiss, scalePt, "etmiss"))

            if VERBOSE:
                f.write(
                    str(eventinfo.eventNumber()) + " : etmiss :: " +
                    str(etmiss.et()) + " " + str(etmiss.phi()) + " " +
                    str(scalePt) + "\n")

            # Represent Leptons
            scalePt = size_factor * self.hist_leptpt.GetXaxis().FindBin(
                leadlepton.pt())
            # scalePt = math.log(leadlepton.pt(),11./10.)
            if abs(leadlepton.pdgId()) == 11:
                ax.add_artist(AH.DrawObject(leadlepton, scalePt, "lepton"))
            else:
                ax.add_artist(AH.DrawObject(leadlepton, scalePt, "lepton"))

            if VERBOSE:
                f.write(
                    str(eventinfo.eventNumber()) + " : lepton :: " +
                    str(leadlepton.pt()) + " " + str(leadlepton.phi()) + " " +
                    str(leadlepton.eta()) + " " + str(scalePt) + "\n")

            #'event_numEvent.jpg'
            import os
            if not os.path.exists(self.getImageDir()):
                os.makedirs(self.getImageDir())
            image_name = self.getImageDir() + "/" + str(
                eventinfo.eventNumber()) + ".jpg"
            fig.savefig(image_name, dpi=56)
            plt.close(fig)
            del plt, fig

        if VERBOSE:
            f.close()

        return True
Esempio n. 17
0
import optparse
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option("-a", "--all", action="store_true", default=False, dest="all")
parser.add_option("-b", "--bash", action="store_true", default=False, dest="bash")
parser.add_option("-c", "--channel", action="store", type="string", dest="channel", default="")
parser.add_option("-s", "--signal", action="store", type="string", dest="signal", default="XZH")
parser.add_option("-e", "--efficiency", action="store_true", default=False, dest="efficiency")
parser.add_option("-p", "--parallelize", action="store_true", default=False, dest="parallelize")
parser.add_option("-v", "--verbose", action="store_true", default=False, dest="verbose")
(options, args) = parser.parse_args()
if options.bash: gROOT.SetBatch(True)

colour = [
    TColor(1001, 0., 0., 0., "black", 1.),
    TColor(1002, 230./255, 159./255, 0., "orange", 1.),
    TColor(1003, 86./255, 180./255, 233./255, "skyblue", 1.),
    TColor(1004, 0., 158./255, 115./255, "bluishgreen", 1.),
    TColor(1005, 0., 114./255, 178./255, "blue", 1.),
    TColor(1006, 213./255, 94./255, 0., "vermillion", 1.),
    TColor(1007, 204./255, 121./255, 167./255, "reddishpurple", 1.),
]

########## SETTINGS ##########

# Silent RooFit
RooMsgService.instance().setGlobalKillBelow(RooFit.FATAL)

#gStyle.SetOptStat(0)
gStyle.SetOptTitle(0)
Esempio n. 18
0
        else:
            index += len( KvKfs[i] )
    index += [i for i in range(0,len(KvKfs[KV])) if KvKfs[KV][i] == KF][0]
    return index

NColors = 60
Stops = [ 0.0000, 0.1250, 0.2500, 0.3750, 0.5000, 0.6250, 0.7500, 0.8750, 1.0000 ]
Red   = [ 243./255., 243./255., 240./255., 240./255., 241./255., 239./255., 186./255., 151./255., 129./255.]
Green = [  0./255.,  46./255.,  99./255., 149./255., 194./255., 220./255., 183./255., 166./255., 147./255. ]
Blue  = [  6./255.,   8./255.,  36./255.,  91./255., 169./255., 235./255., 246./255., 240./255., 233./255. ]
palette = []
for g in range(0, len(Red) ) :
    nColorsGradient = (math.floor(NColors*Stops[g]) - math.floor(NColors*Stops[g-1]))
    for c in range(0, int(nColorsGradient) ):
        color = TColor( 800+c ,
                        ( Red[g-1]   +  c * (Red[g]   - Red[g-1])  / nColorsGradient),
                        ( Green[g-1] +  c * (Green[g] - Green[g-1])/ nColorsGradient),
                        ( Blue[g-1]  +  c * (Blue[g]  - Blue[g-1]) / nColorsGradient) )
        palette.append(color)

signalColors = {(1.0,-1.0):kBlue , (1.0,-.5):kRed , (1.0, 0.0):kCyan , (1.0, 0.5):kGreen  ,  (1.0 , 1.0):kGray , (1.5 , -3):kOrange}
def GetXSecs():
    ret = {}
    ret[0] = [kRed,hxsec.GetBinContent(hxsec.FindBin( -1., 1. )) ,"cv=1.0,cf=-1.00"]
    for KV in Kvs:
        for KF in KvKfs[KV]:
            index = GetSignalIndex( KV, KF)
            xsec = hxsec.GetBinContent( hxsec.FindBin( KF, KV ) )
            title = "cv=%.1f,cf=%.2f" % (KV, KF)
            color = palette[ index ].GetNumber()
            if (KV,KF) in signalColors:
                color = signalColors[ (KV, KF) ]