コード例 #1
0
ファイル: plot_handling.py プロジェクト: keirashea/temp_study
def plot_calibrations(group_data, voltage, cal_pars_list, stacked=False):
    group_name = str(group_data[0].run_number)
    run = group_data[2]
    name = str(run.run_number)
    hists_and_lines = []
    for cal_pars in cal_pars_list:
        pars = parameters.gain_pars[cal_pars]
        run.calibrate_energies(voltage, pars)
        hist = make_hist(name, run.calibrated_energies, 0, 3500)
        K_line = TLine(1460.820, 0, 1460.820, 1000000)
        K_line.SetLineColor(632)
        Tl_line = TLine(2614.511, 0, 2614.511, 1000000)
        Tl_line.SetLineColor(632)
        hists_and_lines.append([hist, K_line, Tl_line])

    if stacked:
        print('Plotting stacked calibrated histograms.')
        run_canvas = TCanvas()
        run_canvas.SetLogy()
        colors = [808, 397, 436, 424, 628, 852, 800, 863, 403, 797]
        color_index = 0
        hs = THStack('hs', 'Group %s Histograms' % group_name)
        for entry in hists_and_lines:
            title = str(run.run_number)
            entry[0].SetLineColor(colors[color_index])
            color_index += 1
            hs.Add(entry[0])
        hs.Draw('nostack')
        K_line = TLine(1460.820, 0, 1460.820, 1000000)
        K_line.SetLineColor(632)
        K_line.Draw()
        Tl_line = TLine(2614.511, 0, 2614.511, 1000000)
        Tl_line.SetLineColor(632)
        Tl_line.Draw()
        run_canvas.BuildLegend()
        path = 'output/group_' + str(group_data[0].run_number) + '/'
        run_canvas.Print((path + str(group_data[0].run_number) +
                          '_stacked_calibrated_histogram.pdf['))
        run_canvas.Print((path + str(group_data[0].run_number) +
                          '_stacked_calibrated_histogram.pdf'))
        run_canvas.Print((path + str(group_data[0].run_number) +
                          '_stacked_calibrated_histogram.pdf]'))
    else:
        print('Plotting calibrated energy histogram.')
        run_canvas = TCanvas("run_canvas", "run canvas")
        run_canvas.Divide(3, int(len(cal_pars_list) / 2))
        canvas_index = 1
        for entry in hists_and_lines:
            pad = run_canvas.cd(canvas_index)
            pad.SetLogy()
            entry[0].Draw()
            entry[1].Draw()
            entry[2].Draw()
            pad.Update()
            canvas_index += 1

            path = 'output/group_' + group_name + '/'
            run_canvas.Print((path + name + '_calibrated_histograms.pdf['))
            run_canvas.Print((path + name + '_calibrated_histograms.pdf'))
            run_canvas.Print((path + name + '_calibrated_histograms.pdf]'))
コード例 #2
0
def doPlotEtaPtOfSuccessfulMatches():
    file = TFile.Open('L1MuonHistogram.root')
    #Prepare canvas
    canvas = TCanvas("canvasPtEtaHoMatch", "PtEtaHoMatch", 1200, 1200)
    canvas.cd().Draw()
    #prepare histogram
    hist = file.Get("hoMuonAnalyzer/etaPhi/3D/NoTrgTdmiAboveThr_EtaPhiPt")

    stack = THStack(hist, "zx", "2dStack", "", -1, -1, -1, -1, "zx", "")

    #Create new histogram and add the histograms from the stack
    histNew = TH2D("histPtEtaHoMatch",
                   "p_{T} vs. #eta distribution;#eta;p_{T} / 5 GeV;#", 40,
                   -1.6, 1.6, 40, 0, 200)
    histNew.GetYaxis().SetTitleOffset(1.2)
    for i in stack.GetHists():
        histNew.Add(i)

    gStyle.SetPalette(1)
    histNew.SetStats(0)
    histNew.Draw('COLZ')
    canvas.Update()

    palette = histNew.FindObject("palette")
    palette.SetX1NDC(0.9)
    palette.SetX2NDC(0.92)
    #add label
    label = PlotStyle.getLabelCmsPrivateSimulation()
    label.Draw()

    canvas.Update()
    canvas.SaveAs('plots/NoL1HoMatchPtEta.pdf')
    canvas.SaveAs('plots/NoL1HoMatchPtEta.png')
    return canvas, hist, stack, histNew, label, palette, file
コード例 #3
0
ファイル: plotting.py プロジェクト: nhaubrich/owls-hep
def histogram_stack(*histograms):
    """Creates a THStack object with a unique identifier from the specified
    histograms.

    This method is useful due to THStack freaking out if a new THStack is
    created with the same name.

    Args:
        histograms: Each argument of this function after plot may be a single
            histogram, an iterable of histograms (each of which should be
            plotted), or even an existing THStack object whose component
            histograms should be included in the new stack.  The histograms
            should be specified from top-to-bottom.

    Returns:
        An initialized THStack object containing the specified histograms.
    """
    # Generate an iterable of all histograms provided
    histograms = chain(*(drawable_iterable(h, unpack_stacks=True)
                         for h in histograms))

    # Create a new THStack object with a unique identifier
    stack = THStack(_rand_uuid(), '')
    SetOwnership(stack, False)

    # Add histograms
    map(stack.Add, histograms)

    return stack
コード例 #4
0
ファイル: Stack.py プロジェクト: gitytakahas/rJpsi
 def DrawNormalized(self,
                    opt='',
                    xmin=None,
                    xmax=None,
                    ymin=None,
                    ymax=None):
     '''Draw a normalized version of the stack (integral=1).'''
     if len(self.hists) == 0:
         return
     integral = 0
     self.normHists = []
     self.obj = THStack(self.name, '')
     self.totalHist = None
     for hist in self.hists:
         normHist = copy.deepcopy(hist)
         normHist.Scale(1 / self.integral)
         self.normHists.append(normHist)
         self.obj.Add(normHist.weighted)
         if self.totalHist is None:
             self.totalHist = copy.deepcopy(normHist)
         else:
             self.totalHist.Add(normHist)
     # self.obj.Draw( opt )
     # self._updateTitles()
     self._Draw(opt, self.normHists, xmin, xmax, ymin, ymax)
コード例 #5
0
ファイル: TopHistoReader.py プロジェクト: joanrs95/xuAnalysis
 def GetStack(self, colors='', pr=''):
     if pr == '': pr = self.processList
     elif isinstance(pr, str) and ',' in pr:
         pr = pr.replace(' ', '').split(',')
     npr = len(pr)
     if isinstance(colors, dict): colors = [colors[p] for p in pr]
     elif colors == '': colors = [1] * npr
     elif isinstance(colors, str) and ',' in colors:
         colors = colors.replace(' ', '').split(',')
     hStack = THStack('hStack', '')
     for p, col in zip(pr, colors):
         if isinstance(self.histoname, list):
             for hname in self.histoname:
                 self.indic[p][hname].SetFillColor(col)
                 self.indic[p][hname].SetFillStyle(1000)
                 self.indic[p][hname].SetLineColor(0)
                 self.indic[p][hname].SetLineStyle(0)
                 self.indic[p][hname].SetLineWidth(0)
                 hStack.Add(self.indic[p][hname])
         else:
             self.indic[p][self.histoname].SetFillColor(col)
             self.indic[p][self.histoname].SetFillStyle(1000)
             self.indic[p][self.histoname].SetLineColor(0)
             self.indic[p][self.histoname].SetLineStyle(0)
             self.indic[p][self.histoname].SetLineWidth(0)
             hStack.Add(self.indic[p][self.histoname])
     return hStack
コード例 #6
0
   def getStack(self, lumi, name, var, nbin, xmin, xmax, cut, options, xlabel):
     if cut == '':
       cut = '(1)'
     hs = THStack(name, "")
     SetOwnership(hs, 0 )
     for b in self.blocks:
     
       AuxName = "auxStack_block_" + name + "_" + b.name
       haux = b.getTH1F(lumi, AuxName, var, nbin, xmin, xmax, cut, options, xlabel)
       haux.SetFillColor(b.color)
       haux.SetLineColor(r.kBlack)
       haux.SetTitle(b.label)
       hs.Add(haux)
       del haux


     can_aux = TCanvas("can_%s_%s"%(name, b.name))
     can_aux.cd()
     hs.Draw()

     del can_aux

     ylabel = "Events"
     if xmax != xmin:
       hs.GetXaxis().SetTitle(xlabel)
       b = int((xmax-xmin)/nbin)
       ylabel = "Events / " + str(b) + " GeV"
     else:     
       ylabel = "Events"
   
     hs.GetYaxis().SetTitle(ylabel)
     return hs   
コード例 #7
0
def make_pdf_plot(key, pos=(0.7, 0.7, 0.9, 0.9)):
    h = getHist(f_all, key)
    h.SetLineStyle(1)
    h.SetLineWidth(5)
    #h.SetFillStyle(1001)
    h.SetLineColor(kBlack)

    hs = THStack("hs_" + key, "")
    h0 = getHist(f_0, key)
    h1 = getHist(f_1, key)
    h2 = getHist(f_2, key)

    h0.SetLineStyle(5)
    h0.SetFillStyle(3005)
    h0.SetFillColor(kRed)
    h0.SetLineColor(kRed)
    hs.Add(h0)
    h1.SetLineStyle(5)
    h1.SetFillStyle(3005)
    h1.SetFillColor(kBlue)
    h1.SetLineColor(kBlue)
    hs.Add(h1)
    h2.SetLineStyle(5)
    h2.SetFillStyle(3005)
    h2.SetFillColor(kGreen)
    h2.SetLineColor(kGreen)
    hs.Add(h2)
    leg = TLegend(pos[0], pos[1], pos[2], pos[3])
    leg.AddEntry(h, 'total')
    leg.AddEntry(h0, 'y == Pred == 0')
    leg.AddEntry(h1, 'y == Pred == 1')
    leg.AddEntry(h2, 'y == Pred == 2')
    return h, hs, leg
コード例 #8
0
def make_stack(tfile, stack_procs, chan, sys, distr):
    global mc_stack_n
    hs = THStack("mc_stack_%d" % mc_stack_n, "mc_stack_%d" % mc_stack_n)
    for proc in stack_procs.split(','):
        histo_name = std_histo_name(args.chan, proc, args.sys, args.distr)
        logging.debug(histo_name)

        if not tfile.Get(histo_name):
            logging.warning(histo_name + ' not in the file ' + args.in_file)
            continue

        histo = tfile.Get(histo_name)

        if args.scale_stack:
            histo.Scale(args.scale_stack)

        logging.debug(proc + ' ' + str(histo.Integral()))

        # histo styling
        col = plotting_root.nick_info[proc]['color']
        histo.SetFillColor(col)
        #histo.SetLineColor( col ); # it's needed for shapes
        histo.SetMarkerStyle(20)
        #histo.SetLineStyle(proc_ocurance);
        histo.SetMarkerColor(col)

        hs.Add(histo, "HIST")

    mc_stack_n += 1
    return hs
コード例 #9
0
 def __init__(self, files, variable, flavour="PF_SYM", selection=Selections.full_selection, luminosity=1):
     self.variable = variable
     """Luminosity unit is pb^{-1}!"""
     self.stack = THStack("stack", "")
     self.file_list = files
     self.histogram_handles = []
     for file_name in self.file_list:
         if isinstance(file_name, list):
             files = [TFile(f) for f in file_name]
             trees = [f.Get(tree_name) for f in files]
             total_events = sum([tree.GetEntriesFast() for tree in trees])
             self.histogram_handles.append(
                     reduce(
                         operator.add,
                 [HistogramHandler(f, variable, flavour, selection, total_events) for f in file_name]
                 ))
         else:
             self.histogram_handles.append(HistogramHandler(file_name, variable, flavour, selection))
     self.entries = sum(
             [h.mass_hist.Integral() for h in self.histogram_handles])
     for histo_handle in self.histogram_handles:
         histo_handle.scale(luminosity)
     self.histogram_handles = self.sum_with_same_name()
     self.build_legend()
     for histo_handle in self.histogram_handles:
         self.stack.Add(histo_handle.mass_hist)
コード例 #10
0
ファイル: Plot_RootObjects.py プロジェクト: elelias/cms
def BuildTHStack(Properties):

    stackTitle = Properties.get('title_stack', '')
    stackName = Properties.get('name_stack', 'thestack')
    theStack = THStack(stackName, stackTitle)

    #print "returning a stack ",theStack.GetXaxis()
    return theStack
コード例 #11
0
    def backgroundStack( self ):

        #implement reordering here by total yield 
        bkgStack = THStack()
        for p in reversed( self.__processes ):
            if not p.isSignal():
                bkgStack.Add( p.nominal() )
        return bkgStack
コード例 #12
0
    def summary (self) :
        '''to be run after the event loop, before saving'''
        self.summ = THStack (self.name + '_summ', 'total energy')
        self.mean = []
        for i in range (1, 8) :
#            self.mean.append (self.histos[i].ProfileX ())
            self.mean.append (self.fromProfileToHisto (self.histos[i].ProfileX (), 10 + i * 2))
            self.summ.Add (self.mean[len (self.mean) - 1])
コード例 #13
0
def plot_hist_diff(histlist1, histlist2, labellist, log, overflow, filename,
                   options):
    canv = TCanvas("c1", "c1", 800, 600)
    canv.SetTopMargin(10)
    canv.SetRightMargin(100)
    if log: gPad.SetLogy()
    histstack = THStack("stack", histlist1[0].GetTitle())
    legend = TLegend(0.76, 0.88 - 0.08 * len(histlist1), 0.91, 0.88, '', 'NDC')
    colorlist = [4, 8, 2, 6, 1]

    if options: options += " NOSTACK"
    else: options = "NOSTACK"

    maximum = 0
    for i in range(len(histlist1)):
        entries = histlist1[i].GetEntries()
        bad_entries = histlist2[i].GetEntries()
        histlist1[i].SetLineColorAlpha(colorlist[i], 0.65)
        histlist1[i].SetLineWidth(3)

        if entries: histlist1[i].Scale(1. / entries)
        if bad_entries: histlist2[i].Scale(1. / bad_entries)
        histlist1[i].Add(histlist2[i], -1.)

        nbins = histlist1[i].GetNbinsX()
        legend.AddEntry(
            histlist1[i], "#splitline{" + labellist[i] +
            "}{#splitline{%d total jets}{%d bad jets}}" %
            (entries, bad_entries), "l")

        if overflow:
            histlist1[i].SetBinContent(
                nbins, histlist1[i].GetBinContent(nbins) +
                histlist1[i].GetBinContent(nbins + 1))  #overflow
            histlist1[i].SetBinContent(
                1, histlist1[i].GetBinContent(0) +
                histlist1[i].GetBinContent(1))  #underflow

        if histlist1[i].GetMaximum() > maximum:
            maximum = histlist1[i].GetMaximum()
        histstack.Add(histlist1[i])
        #if i == 0: histlist[i].Draw(options)
        #else: histlist[i].Draw(same+options)

    histstack.SetMaximum(maximum * 1.4)
    histstack.Draw(options)
    histstack.GetXaxis().SetTitle(histlist1[0].GetXaxis().GetTitle())
    histstack.GetYaxis().SetTitle(histlist1[0].GetYaxis().GetTitle())

    legend.SetTextSize(0.02)
    legend.SetFillStyle(0)
    legend.SetBorderSize(0)
    legend.Draw("SAME")
    canv.SaveAs(filename)
    if log: gPad.Clear()
    canv.Clear()
    del canv
コード例 #14
0
ファイル: treestack.py プロジェクト: lucastorterotot/cpyroot
 def __init__(self, name):
     '''Name is the name you want for your treestack.'''
     self.name = name
     self.trees = dict()
     self.styles = dict()
     self.treenames = []
     self.hists = []
     self.histsum = None
     self.stack = THStack('_'.join([self.name, 'stack']), 'title')
コード例 #15
0
def makeStack(mchists):
    """make stack plot"""
    stack = THStack("hs", "")
    index = 3
    for hist in mchists:
        hist.SetLineColor(index)
        hist.SetFillColor(index)
        stack.Add(hist)
        index += 1
    return stack
コード例 #16
0
def myStack(colorlist_, backgroundlist_, legendname_):
    hs = THStack("hs", "")
    leg1 = myLegend()
    for j in range(len(colorlist_)):
        h = backgroundlist_[j]
        h.SetFillColor(colorlist_[j])
        h.SetLineColor(colorlist_[j])
        hs.Add(h, "")
        leg1.AddEntry(h, legendname_[j], "f")
    return [hs, leg1]
コード例 #17
0
def drawAppMVAOutputPlots(region, method, isMC):

    MCstr = ""
    if isMC:
        MCstr = "BsMC12"
    Region = region[:1].upper() + region[
        1:]  #capitalize first letter for retrieving file names
    HistName = "ApplicationOutput" + MCstr + Region + method
    CvsName = "canvasMVA_" + MCstr + method + region
    canvas = TCanvas(CvsName, CvsName)
    stackBDT = THStack(HistName, HistName)
    histos = []
    appFiles = []
    canvas.Draw()

    # note: TMVApp file name structure: "TMVApp"+Region+method+sample+".root"
    #                             "BsMC12TMVApp"+Region+method+sample+".root"
    appFile = TFile(MCstr + "TMVApp" + Region + method + ".root")
    histo = appFile.Get("MVA_" + method).Clone(HistName)
    histo.Scale(1 / histo.GetEntries())
    stackBDT.Add(histo)

    for sample in range(3):
        appFiles.append(
            TFile(MCstr + "TMVApp" + Region + method + str(sample) + ".root"))
        histos.append(appFiles[sample].Get("MVA_" + method).Clone("HistName" +
                                                                  str(sample)))
        histos[sample].SetLineColor(2 * sample)
        histos[sample].Scale(1 / histos[sample].GetEntries())
        stackBDT.Add(histos[sample])

    stackBDT.Draw("nostack")
    if isMC:
        applicationBDTLegend = TLegend(0.2, 0.7, 0.5, 0.9, "", "brNDC")
        #applicationBDTLegend.SetHeader("Bs MC "+region.split("BsMC")[1])
        applicationBDTLegend.SetHeader("Bs MC " + Region)
    else:
        applicationBDTLegend = TLegend(0.55, 0.7, 0.85, 0.9, "", "brNDC")
        applicationBDTLegend.SetHeader(Region)

    applicationBDTLegend.AddEntry(histo, "Full sample", "l")
    applicationBDTLegend.AddEntry(histos[0],
                                  "Trained on 0, tested on 1, applied on 2",
                                  "l")
    applicationBDTLegend.AddEntry(histos[1],
                                  "Trained on 1, tested on 2, applied on 0",
                                  "l")
    applicationBDTLegend.AddEntry(histos[2],
                                  "Trained on 2, tested on 0, applied on 1",
                                  "l")
    applicationBDTLegend.Draw("same")
    applicationBDTLegend.SetFillColor(0)
    applicationBDTLegend.SetLineColor(0)
    canvas.SaveAs(figuresDir + "Application" + method + "Output_" + MCstr +
                  region + ".pdf")
コード例 #18
0
	def  __init__(self,processes,lumi,plot,files,fromTree=False):
		self.theStack = THStack()
			
		for process in processes:
			temphist = process.loadHistogram(lumi,files,plot,fromTree)

			self.theStack.Add(temphist.Clone())
			if self.theHistogram == None:
				self.theHistogram = temphist.Clone()
			else:	
				self.theHistogram.Add(temphist.Clone())
コード例 #19
0
ファイル: utils.py プロジェクト: dnowatsc/VLQGenStudies
def slice_and_save(sample,histo,outfile):
  outfile.cd()
  histo_stack=THStack(histo,'x','Stack_'+histo.GetName(),'')
  histo_1d=histo_stack.GetHists()
  histo_stack.Write(histo_stack.GetName()+'_'+sample)
  nextinlist=TIter(histo_1d)
  obj=nextinlist()
  while obj:
    obj.Write(obj.GetName()+'_'+sample)
    obj=nextinlist()
  histo.Write(histo.GetName()+'_'+sample)
コード例 #20
0
	def  __init__(self,processes,lumi,plot,zScale):
		self.theStack = THStack()
			
		for process in processes:
			temphist = process.loadHistogramProjected(plot,lumi,zScale)

			self.theStack.Add(temphist.Clone())
			if self.theHistogram == None:
				self.theHistogram = temphist.Clone()
			else:	
				self.theHistogram.Add(temphist.Clone())
コード例 #21
0
def stack(wrps):
    """
    Applies only to HistoWrappers. Returns StackWrapper.
    Checks lumi to be equal among all wrappers.

    >>> from ROOT import TH1I
    >>> h1 = TH1I("h1", "", 2, .5, 4.5)
    >>> h1.Fill(1,4)
    1
    >>> w1 = wrappers.HistoWrapper(h1, lumi=2.)
    >>> h2 = TH1I("h2", "", 2, .5, 4.5)
    >>> h2.Fill(1,3)
    1
    >>> h2.Fill(3,6)
    2
    >>> w2 = wrappers.HistoWrapper(h2, lumi=2.)
    >>> w3 = stack([w1, w2])
    >>> w3.histo.Integral()
    13.0
    >>> w3.lumi
    2.0
    """
    wrps    = iterableize(wrps)
    stk_wrp = None
    lumi    = 0.
    info    = None
    sample  = ""
    for wrp in wrps:
        if not isinstance(wrp, wrappers.HistoWrapper):          # histo check
            raise WrongInputError(
                "stack accepts only HistoWrappers. wrp: "
                + str(wrp)
            )
        if not stk_wrp:                                         # stack init
            stk_wrp = THStack(wrp.name, wrp.title)
            lumi = wrp.lumi
            info = wrp.all_info()
            sample = wrp.sample
        elif lumi != wrp.lumi:                                  # lumi check
            raise NoLumiMatchError(
                "stack needs lumis to match. (%f != %f)" % (lumi, wrp.lumi)
            )
        if sample != wrp.sample:                                # add to stack
            sample = ""
        if wrp.legend:
            wrp.histo.SetTitle(wrp.legend)
        stk_wrp.Add(wrp.histo)
    if not info:
        raise TooFewWrpsError(
            "At least one Wrapper must be provided."
        )
    if not sample:
        del info["sample"]
    return wrappers.StackWrapper(stk_wrp, **info)
コード例 #22
0
ファイル: plotting.py プロジェクト: odysei/ttHTauTauAnalysis
def DrawStackHistograms(histograms, outname, blind=True, verbose=False):

    #hists_sorted = sorted(histograms, key=lambda h: h.Integral())

    hs = THStack("h_stack", "")
    h_obs = None

    l = TLegend(0.77, 0.60, 0.90, 0.87)

    for hist in histograms:

        hname = hist.GetName()

        if "data_obs" in hname:
            if not blind:
                h_obs = hist
                SetHistogramStyle(h_obs, "Observed")
                l.AddEntry(h_obs, "Observed", "p")
        else:
            SetHistogramStyle(hist)
            label = GetLabelName(hist)
            hs.Add(hist)
            l.AddEntry(hist, label, "f")

    h_est = hs.GetStack().Last().Clone()

    if verbose:
        est_err = Double(0.)
        nbins_est = h_est.GetNbinsX()
        est_yields = h_est.IntegralAndError(1, nbins_est, est_err)
        print "predicted yields :", est_yields, "+/-", est_err
        if not blind:
            print "observed yields :", h_obs.Integral()

    # draw

    # SetCMSStyle()   TODO

    canvas = TCanvas()
    gPad.SetLogy()

    #ymax_hs = hs.GetMaximum()
    #ymax = ymax_hs if h_obs is None else max(ymax_hs, h_obs.GetMaximum())
    ymax = 10000
    ymin = 0.1

    hs.SetMaximum(ymax)
    hs.SetMinimum(ymin)
    hs.Draw("HIST")
    l.Draw("same")
    if not blind:
        h_obs.Draw("same")

    canvas.SaveAs(outname)
コード例 #23
0
def stack_n_legend(used_histos, shift=0., exp_legend=False, sort_dy=False, leg=None):
    '''stack_n_legend(used_histos)

    used_histos = [(histo, nick of process, channel), ...]
    first check if there are different channels -- then add the channel name to the legend
    also the line style changes for different channels of the same process for histograms
    (not sure if it is a good hack)
    '''

    channels = [c for _, _, c in used_histos]
    homogeneous_channels = all(c == channels[0] for c in channels)

    # build Stach and legend
    hs = THStack("mc_stack", "mc_stack")
    #leg = TLegend(0.7 - (0.15 if not homogeneous_channels else 0.), 0.4, 0.89, 0.89)
    if not leg:
      if exp_legend:
        leg = TLegend(0.8 - shift, 0.55, 1.   - shift, 0.92)
      else:
        leg = TLegend(0.7 - shift, 0.55, 0.89 - shift, 0.92)

    leg.SetBorderSize(0)

    process_counter = {} # for distinguishing processes in different channels

    def sort_w_dy_option(histo_nick):
        order = nick_order.get(histo_nick, 1)
        if sort_dy and 'dy' in histo_nick:
            order = 0
        return order

    #for histo, nick, channel in sorted(used_histos, key=lambda h_n: nick_order.get(h_n[1], 1)):
    for histo, nick, channel in sorted(used_histos, key=lambda h_n: sort_w_dy_option(h_n[1])):
        logging.debug("plotting stack_n_legend: %s %s" % (nick, channel))
        proc_ocurance = process_counter.setdefault(nick, 1)
        process_counter[nick] += 1

        col = nick_colour[nick]
        histo.SetFillColor( col );
        #histo.SetLineColor( col ); # it's needed for shapes
        histo.SetMarkerStyle(20);
        histo.SetLineStyle(proc_ocurance);
        histo.SetMarkerColor(col);
        #used_histos.append(histo) # hopefully root wont screw this up
        hs.Add(histo, "HIST")

    # to have legend in the same order
    for histo, nick, channel in sorted(used_histos, key=lambda h_n: -sort_w_dy_option(h_n[1])):
        if homogeneous_channels:
            leg.AddEntry(histo, nick_info[nick]['legend'], "F")
        else:
            leg.AddEntry(histo, "%s %s" % (nick, channel), "F")

    return hs, leg
コード例 #24
0
	def  __init__(self,processes,lumi,plot,zScaleFac,genMass=False,CIBins=False,cumulative=False):
		self.theStack = THStack()
			
		for process in processes:
			temphist = process.loadHistogram(plot,lumi,zScaleFac,genMass=genMass,CIBins=CIBins)
			if cumulative:
				temphist = makeHistoCumulative(temphist)
			self.theStack.Add(temphist.Clone())
			if self.theHistogram == None:
				self.theHistogram = temphist.Clone()
			else:	
				self.theHistogram.Add(temphist.Clone())
コード例 #25
0
	def  __init__(self,processes,lumi,plot,zScale,CIBins=False):
		self.theStack = THStack()
			
		for index, process in enumerate(processes[0]):
			temphist = process.loadHistogramProjected(plot,lumi[0],zScale[0])
			temphist.Add(processes[1][index].loadHistogramProjected(plot,lumi[1],zScale[1]))
			temphist.Add(processes[2][index].loadHistogramProjected(plot,lumi[2],zScale[2]))

			self.theStack.Add(temphist.Clone())
			if self.theHistogram == None:
				self.theHistogram = temphist.Clone()
			else:	
				self.theHistogram.Add(temphist.Clone())
コード例 #26
0
ファイル: Stack.py プロジェクト: pcirkovic/cmg-cmssw
 def Draw(self, opt='', xmin=None, xmax=None, ymin=None, ymax=None):
     '''Draw the stack. opt are the ROOT options'''
     if len(self.hists) == 0:
         return
     self.obj = THStack(self.name, '')
     self.totalHist = None
     for hist in self.hists:
         self.obj.Add(hist.weighted)
         if self.totalHist is None:
             self.totalHist = copy.deepcopy(hist)
         elif hist.layer < 1000.:
             self.totalHist.Add(hist)
     self._Draw(opt, self.hists, xmin, xmax, ymin, ymax)
コード例 #27
0
    def __init__(self,
                 variable,
                 cut,
                 name,
                 nbin,
                 xmin,
                 xmax,
                 title,
                 xtitle,
                 ytitle_unity_measure,
                 norm=False,
                 logy=False,
                 stack=False,
                 set_title=True):

        TopMassStyle()

        self.variable = variable
        self.cut = cut
        self.name = name
        self.nbin = nbin
        self.xmin = xmin
        self.xmax = xmax
        self.title = title
        self.xtitle = xtitle
        self.ytitle_unity_measure = ytitle_unity_measure
        self.norm = norm
        self.logy = logy
        self.stack = stack
        self.set_title = set_title

        self.dataset = [[], []]
        self.histograms = []

        # legend
        self.leg = TLegend(0.7, 0.6, 0.9, 0.8)

        # canvas
        self.canvas = TCanvas("canvas_" + self.name, self.title, 800, 600)
        self.canvas.SetGrid()
        if logy == True:
            self.canvas.SetLogy()

        if self.stack == False:
            self.maxs_histograms = []
        else:
            if self.set_title == True:
                aux_title = self.title
            else:
                aux_title = self.variable + " {" + self.cut + "}"
            self.h_stack = THStack("h_stack_" + self.name, aux_title)
コード例 #28
0
	def  __init__(self,processes,lumi,plot,zScaleFac,CIBins=False,cumulative=False):
		self.theStack = THStack()
	
		for index, process in enumerate(processes[0]):
			temphist = process.loadHistogram(plot,lumi[0],zScaleFac[0],CIBins=CIBins)
			temphist.Add(processes[1][index].loadHistogram(plot,lumi[1],zScaleFac[1],CIBins=CIBins))
			temphist.Add(processes[2][index].loadHistogram(plot,lumi[2],zScaleFac[2],CIBins=CIBins))
			if cumulative:
				temphist = makeHistoCumulative(temphist)
			self.theStack.Add(temphist.Clone())
			if self.theHistogram == None:
				self.theHistogram = temphist.Clone()
			else:	
				self.theHistogram.Add(temphist.Clone())
コード例 #29
0
def study_cal_eff():
    # Import data and MC files:
    f_data = TFile.Open("../trees_5gev_e/data_nn50.root", 'read')
    t_data = f_data.data

    f_mc = TFile.Open("../trees_5gev_e/lucas.root", 'read')
    t_mc = f_mc.lumical
    t_mc.AddFriend("lumical_noise=lumical",
                   "../trees_5gev_e/lucas_geocuts_noise_cal.root")
    t_mc.AddFriend("lumical_eff=lumical",
                   "../trees_5gev_e/lucas_geocuts_noise_cal_eff.root")

    c = TCanvas()
    hs = THStack("hs", "title")

    t_data.Draw("energy*(layer > 1)>>h_data50(200, 0, 50)",
                "energy*(layer > 1) > 0")
    h_data50 = gROOT.FindObject("h_data50")
    h_data50.SetTitle("Data")
    h_data50.SetLineWidth(2)
    h_data50.SetLineColor(1)
    hs.Add(h_data50, "histo")

    t_mc.Draw("cal_energy_new/0.0885>>h_mc(200, 0, 50)",
              "cal_energy_new/0.0885 > 0", "", 100000)
    h_mc = gROOT.FindObject("h_mc")
    h_mc.SetTitle("MC smearing and cal eff")
    h_mc.SetLineWidth(2)
    h_mc.SetLineColor(3)
    h_mc.Scale(t_data.GetEntries() / 100000)  #t_mc.GetEntries())
    hs.Add(h_mc, "histo")

    t_mc.Draw("cal_energy_smeared7/0.0885>>h_mc7(200, 0, 50)",
              "cal_energy_smeared7/0.0885 > 0", "", 100000)
    h_mc7 = gROOT.FindObject("h_mc7")
    h_mc7.SetTitle("MC smearing=0.7*#sigma")
    h_mc7.SetLineWidth(2)
    h_mc7.SetLineColor(2)
    h_mc7.Scale(t_data.GetEntries() / 100000)  #t_mc.GetEntries())
    hs.Add(h_mc7, "histo")
    print(h_mc7.GetEntries())
    hs.Draw("nostack")
    hs.SetTitle(
        "Deposited energy in the pads of calorimeter;E, [MIP]; N_{hits}")

    c.SetGridx()
    c.SetGridy()
    c.BuildLegend()
    c.Update()
    input("wait")
コード例 #30
0
ファイル: helpers.py プロジェクト: minxiyang/leptonFlavor
	def  __init__(self,processes,lumi,plot,zScaleFac):
		self.theStack = THStack()
	
			
		for index, process in enumerate(processes[0]):
			print (index)
			temphist = process.loadHistogram(plot,lumi[0],zScaleFac[0])
			temphist.Add(processes[1][index].loadHistogram(plot,lumi[1],zScaleFac[1]))
			temphist.Add(processes[2][index].loadHistogram(plot,lumi[2],zScaleFac[2]))

			self.theStack.Add(temphist.Clone())
			if self.theHistogram == None:
				self.theHistogram = temphist.Clone()
			else:	
				self.theHistogram.Add(temphist.Clone())