Example #1
0
def add_desc_to_canvas(config, xmin, ymin, xmax, ymax, size, content):
    txt1 = TPaveText(xmin, ymin, xmax, ymax, "NDC")
    txt1.SetFillColor(kWhite)
    txt1.SetFillStyle(0)
    txt1.SetBorderSize(0)
    txt1.SetTextAlign(12) # middle,left
    txt1.SetTextFont(42) # helvetica
    txt1.SetTextSize(size)
    if content["add_alice"]:
        txt1.AddText("ALICE work in progress")
    if content["add_gran"]:
        gran_desc = "#it{n}_{#it{#varphi}} #times #it{n}_{#it{r}} #times #it{n}_{#it{z}}"
        gran_str = "%d #times %d #times %d" % (config.grid_phi, config.grid_r,
                                               config.grid_z)
        txt1.AddText("%s = %s" % (gran_desc, gran_str))
    if content["add_inputs"]:
        if config.opt_train[0] == 1 and config.opt_train[1] == 1:
            txt1.AddText("inputs: #it{#rho}_{SC} - <#it{#rho}_{SC}>, <#it{#rho}_{SC}>")
        elif config.opt_train[1] == 1:
            txt1.AddText("inputs: #it{#rho}_{SC} - <#it{#rho}_{SC}>")
    if content["add_events"]:
        txt1.AddText("#it{N}_{ev}^{training} = %d" % config.train_events)
        # txt1.AddText("#it{N}_{ev}^{validation} = %d" % config.test_events)
        # txt1.AddText("#it{N}_{ev}^{apply} = %d" % config.apply_events)
    if config.name == "dnn":
        txt1.AddText("%d epochs" % config.epochs)
    return txt1
Example #2
0
def bpmass_nonres_below5(args, figname):
    datatype = args[0]
    label = args[1]
    test = option_exists(args, '-t')
    rootname = figname.replace('bpmass_nonres_below5', 'summary')
    rootfile = set_file(atr.figpath, label, rootname, '.root', test=test)
    figfile = set_file(atr.figpath, label, figname, '.pdf', test=test)
    c = TCanvas("aCanvas", "Canvas", 600, 600)
    gStyle.SetPadLeftMargin(0.15)
    gStyle.SetOptTitle(0)
    c.UseCurrentStyle()

    f = TFile(rootfile)
    h = f.Get('h_bpmass_nonres_below5')
    h.GetYaxis().SetTitle(get_y_title(h, 'GeV'))
    h.GetYaxis().SetTitleOffset(1.6)
    h.Draw()

    pt = TPaveText()
    if label == 'Run2011v10.2':
        pt = TPaveText(4.2, 10, 4.8, 12)

    pt.SetBorderSize(0)
    pt.SetFillColor(0)
    pt.AddText("Entries = %d" % h.GetEntries())
    pt.Draw()

    c.Print(figfile)
    f.Close()
Example #3
0
def bctau(args, figname):
    datatype = args[0]
    label = args[1]
    test = option_exists(args, '-t')
    rootname = figname.replace('bctau', 'summary')
    rootfile = set_file(atr.figpath, label, rootname, '.root', test=test)
    figfile = set_file(atr.figpath, label, figname, '.pdf', test=test)
    c = TCanvas("aCanvas", "Canvas", 600, 600)
    gStyle.SetPadLeftMargin(0.15)
    gStyle.SetOptTitle(0)
    c.UseCurrentStyle()

    f = TFile(rootfile)
    h = f.Get('h_bctau')
    h.GetYaxis().SetTitle(get_y_title(h, 'cm'))
    h.GetYaxis().SetTitleOffset(1.6)
    h.Draw()

    pt = TPaveText(0.2, 1.6e5, 0.6, 1.8e5)
    pt.SetBorderSize(0)
    pt.SetFillColor(0)
    pt.AddText("Entries = %d" % h.GetEntries())
    pt.Draw()

    c.Print(figfile)
    f.Close()
def printLHCb(optLR='L', isPrelim=False, optText=''):
    global lhcbStyle
    global lhcbNames

    lhcbName = None

    if (optLR is 'R'):
        lhcbName = TPaveText(0.70 - lhcbStyle.GetPadRightMargin(),
                             0.85 - lhcbStyle.GetPadTopMargin(),
                             0.95 - lhcbStyle.GetPadRightMargin(),
                             0.95 - lhcbStyle.GetPadTopMargin(), "BRNDC")
    elif (optLR is 'L'):
        lhcbName = TPaveText(lhcbStyle.GetPadLeftMargin() + 0.05,
                             0.85 - lhcbStyle.GetPadTopMargin(),
                             lhcbStyle.GetPadLeftMargin() + 0.30,
                             0.95 - lhcbStyle.GetPadTopMargin(), "BRNDC")
    elif (optLR is 'BR'):
        lhcbName = TPaveText(0.70 - lhcbStyle.GetPadRightMargin(),
                             0.05 + lhcbStyle.GetPadBottomMargin(),
                             0.95 - lhcbStyle.GetPadRightMargin(),
                             0.15 + lhcbStyle.GetPadBottomMargin(), "BRNDC")

    if (isPrelim):
        lhcbName.AddText('#splitline{LHCb}{#scale[1.0]{Preliminary}}')
    else:
        lhcbName.AddText('LHCb')

    lhcbName.SetFillColor(0)
    lhcbName.SetTextAlign(12)
    lhcbName.SetBorderSize(0)
    lhcbName.Draw()

    lhcbNames += [lhcbName]
    return
Example #5
0
def plot(obj, plot_name, plot_notes=[]):
    canvas = TCanvas('canvas' + plot_name, "Canvas", 450, 450)
    gPad.SetLeftMargin(.13)
    gPad.SetTopMargin(.05)

    gStyle.SetOptStat(11)
    gStyle.SetOptFit(1111)

    if 'TH2' in obj.ClassName():
        gPad.SetRightMargin(.13)
        draw_options = 'COLZ'

    if 'profile' in obj.GetName():
        gPad.SetRightMargin(.05)
        draw_options = ''

    if 'graph' in obj.GetName():
        gPad.SetRightMargin(.05)
        draw_options = 'APE'
        obj.SetMarkerSize(.7)
        obj.SetMarkerStyle(21)

    note = TPaveText(.2, .7, .5, .9, "brNDC")
    note.SetFillStyle(0)
    note.SetFillColor(0)
    note.SetBorderSize(0)
    note.SetTextColor(1)
    note.SetTextFont(42)
    note.SetTextAlign(11)
    for note_text in plot_notes:
        note.AddText(note_text)

    obj.Draw(draw_options)
    note.Draw()
    canvas.Print('output/' + plot_name + '.pdf')
Example #6
0
def makePage( algorithm , pagename , cdash = False, prefix=""):
    from ROOT import TCanvas,kBlue,kRed,gROOT,kGreen,kYellow
    gROOT.SetBatch(True)
    c=TCanvas( algorithm.output.name , algorithm.output.name )
    c.Divide(1,2)
    from Interface import Result
    aColor = None
    if algorithm.output.result == Result.FAILED:
        aColor = kRed
    if algorithm.output.result == Result.NOTPASSED:
        aColor = kYellow
    if algorithm.output.result == Result.SUCCESS:
        aColor = kGreen
    if aColor:
        c.SetFillColor( aColor )
    aPad = c.cd(1)
    from Utils import draw
    lims = ()
    if "TH1" not in algorithm.test.dataset1.__class__.__name__:
        lims = ( 100, 
                min( algorithm.test.dataset1.tolist() + algorithm.test.dataset2.tolist() ),
                max( algorithm.test.dataset1.tolist() + algorithm.test.dataset2.tolist() )
               )
    h1=draw( algorithm.test.dataset1 , kBlue , ""    , lims , algorithm.output.name )
    h1.SetName(h1.GetName()+"_new")
    aPad.Update()
    from ROOT import TPaveStats
    statBox = h1.GetListOfFunctions().FindObject("stats")
    statBox.SetName('new_stat')
    statBox.SetY1NDC(statBox.GetY1NDC()-.18)
    statBox.SetY2NDC(statBox.GetY2NDC()-.18)
    statBox.SetTextColor(kBlue)
    statBox.SetBorderSize(2)
    h2=draw( algorithm.test.dataset2 , kRed  , "sames", lims , algorithm.output.name+"ref")
    h2.SetName(h2.GetName()+"_ref")
    aPad.Update()
    statBox2 = h2.GetListOfFunctions().FindObject("stats")
    statBox2.SetName('ref_stat')
    statBox2.SetTextColor(kRed)
    from ROOT import TPaveText
    pave=TPaveText(0.02,0.85,0.35,0.99,"NDC")
    pave.SetTextColor(aColor)
    pave.SetFillColor(1)
    pave.AddText(" %s "%algorithm.output.result)
    pave.AddText("(p-val: %s Test: %s)"%(algorithm.output.value,
                                         algorithm.test.__class__.__name__))
    pave.Draw()
    c.cd(2)
    if 'residuals' in algorithm.test.__dict__:
        algorithm.test.residuals.Draw()
    else:
        from Utils import makeResiduals
        algorithm.test.residuals = makeResiduals( h1 , h2 )
        algorithm.test.residuals.Draw()
    c.Print(pagename+prefix)
    # only print CDASH info if the test has failed (saves space on webserver)
    if cdash == True and not (algorithm.output.result == Result.SUCCESS):
        import os
        c.Print(os.path.dirname(pagename)+"/"+algorithm.output.name.replace('/','_')+".png")
        print " <DartMeasurementFile name=\"" + algorithm.output.name +  "\" type=\"image/png\"> " + os.path.dirname(pagename) + "/" + algorithm.output.name.replace('/','_') + ".png" + " </DartMeasurementFile>"
Example #7
0
def kstarpmass(args, figname):
    datatype = args[0]
    label = args[1]
    test = option_exists(args, '-t')
    #rootname = 'SingleBuToKstarMuMu_summary_data_Run2011v10'
    rootname = figname.replace('kstarpmass', 'summary')
    rootfile = set_file(atr.figpath, label, rootname, '.root', test=test)
    figfile = set_file(atr.figpath, label, figname, '.pdf', test=test)
    c = TCanvas("aCanvas", "Canvas", 600, 600)
    gStyle.SetPadLeftMargin(0.15)
    gStyle.SetOptTitle(0)
    c.UseCurrentStyle()

    f = TFile(rootfile)
    h = f.Get('h_kstarpmass')
    h.GetYaxis().SetTitle(get_y_title(h, 'GeV'))
    h.GetYaxis().SetTitleOffset(1.5)
    h.Draw()

    pt = TPaveText()
    if label == 'Run2011v10.1':
        pt = TPaveText(1, 70, 1.1, 80)
    if label == 'Run2011v10.2':
        pt = TPaveText(1, 70, 1.1, 80)

    pt.SetBorderSize(0)
    pt.SetFillColor(0)
    pt.AddText("Entries = %d" % h.GetEntries())
    pt.Draw()

    c.Print(figfile)
    f.Close()
Example #8
0
def checklatex(texts, tag=""):
    """Check legend entries: colors, titles, ..."""
    # https://root.cern.ch/doc/master/classTPaveText.html
    LOG.header("checklegend" + tag.replace('_', ' '))
    output = ensuredir('plots')
    fname = "%s/testLatex%s" % (output, tag)
    xdim = 500
    ydim = 50 * (len(texts) + 2.5)
    print ">>> Canvas: %sx%s (nlines=%d)" % (xdim, ydim, len(texts))
    canvas = TCanvas('canvas', 'canvas', xdim, int(ydim))
    #pave1  = TPaveText(0.0,0,0.5,1,'ARC') #,'BR')
    pave2 = TPaveText(0.04, 0.04, 0.96, 0.96)  #'ARC') #,'BR')
    #pave1.SetBorderSize(0)
    pave2.SetBorderSize(0)
    #pave1.SetTextAlign(12)
    pave2.SetTextAlign(12)
    #pave1.SetTextFont(42)
    pave2.SetTextFont(42)
    #pave1.SetFillColor(0)
    pave2.SetFillColor(0)
    #pave1.SetCornerRadius(0.05)
    #pave2.SetCornerRadius(0.05)
    #pave1.SetMargin(0.12)
    #pave1.SetTextSize(tsize)
    #pave2.Copy(pave1)
    for line in texts:
        latex = makelatex(line)
        print ">>> %r -> %r" % (line, latex)
        #pave1.AddText(line)
        pave2.AddText(latex)
    #pave1.Draw()
    pave2.Draw()
    canvas.SaveAs(fname + ".png")
    #canvas.SaveAs(fname+".pdf")
    canvas.Close()
Example #9
0
	def plotHoTime(self):
		c3 = TCanvas("c3","HO Time",1200,1200)
		skipNoisePlot = False
		if not skipNoisePlot:
			c3.Divide(1,2)
			c3.cd(1).SetLogy()
			label = getLabelCmsPrivateSimulation()
			label.Draw()
			hHoTime = self.fileHandler.getHistogram('hoRecHits_Time')
			
			hHoTime.SetStats(0)
			hHoTime.SetTitle("Time distribution for all HO Rec Hits")
			hHoTime.SetLineColor(colorRwthDarkBlue)
			hHoTime.SetLineWidth(3)
			hHoTime.Draw()
			label = getLabelCmsPrivateSimulation()
			label.Draw()
			
		hHoTimeAboveThr = self.fileHandler.getHistogram('hoRecHitsAboveThr_Time')
		c3.cd(2).SetLogy()
		hHoTimeAboveThr.SetStats(0)
		hHoTimeAboveThr.SetTitle("Time distribution for HO Rec Hits > 0.2 GeV")
		hHoTimeAboveThr.SetLineColor(colorRwthDarkBlue)
		hHoTimeAboveThr.SetLineWidth(3)
		setupAxes(hHoTimeAboveThr)
		hHoTimeAboveThr.Draw()
		
		label = getLabelCmsPrivateSimulation()
		label.Draw()
		
		self.debug(80*'#')
		self.debug( 'Integral of HO > 0.2 GeV time histogram:')
		self.debug( hHoTimeAboveThr.Integral())
		self.debug('')
		
		xLow = -5
		xHigh = 5
		histogramBetween = hHoTimeAboveThr.Integral(hHoTimeAboveThr.FindBin(xLow),hHoTimeAboveThr.FindBin(xHigh))
		histogramTotal = float(hHoTimeAboveThr.Integral())
		self.debug( 'Histogram integral between %.f ns and %.f ns' % (xLow,xHigh) )
		self.debug( '%d/%d => %.2f +/- %f' % (histogramBetween,histogramTotal
											,histogramBetween/histogramTotal,calcSigma(histogramBetween, histogramTotal))) 
		self.debug( 80*'#')
		
		fit = TF1("fit","gaus",-10,10)
		hHoTimeAboveThr.Fit(fit)
		
		pText = TPaveText(0.7,0.8,0.9,0.9,'NDC')
		pText.AddText('Mean: %.2f ns' % (fit.GetParameter(1)))
		pText.AddText('#sigma: %.2f ns' % (fit.GetParameter(2)))
		pText.SetBorderSize(1)
		pText.SetFillColor(0)
		pText.Draw()
		
		c3.Update()
		self.storeCanvas(c3,"hoTime")
		
		return c3,label,hHoTimeAboveThr,pText
Example #10
0
def identification(config):
    text = TPaveText(0.0, 0.95, 1.0, 1.0, "blNDC")
    text.AddText(config.message)
    text.SetBorderSize(0)
    text.SetTextAlign(12)
    text.SetTextSizePixels(10)
    text.SetTextFont(82)
    text.SetFillColor(0)
    return text
Example #11
0
def draw_canvas_1d(name):
    f_mc = TFile("plots/mc/%s_mcc7.root" % name)
    print(f_mc.ls())
    print(name)
    h_mc = gDirectory.Get("h_%s_reco" % name)
    h_mc.SetName("h_%s_reco" % name)
    h_mc.SetLineColor(kRed + 1)
    h_mc.SetFillColor(kRed + 1)
    h_mc.SetFillStyle(0)
    h_mc.GetYaxis().SetTitle("Efficiency")
    h_mc.GetYaxis().SetRangeUser(0.61, 1.04)
    f = TFile("plots/data/e_%s_pandoraCosmic.root" % name)
    h = gDirectory.Get("h_%s" % name)
    h.SetMarkerStyle(20)
    h.SetLineColor(1)
    f_sys = TFile("plots/data/e_%s_sys_pandoraCosmic.root" % name)
    h_sys = gDirectory.Get("h_%s_sys" % name)
    h_ratio = h_sys.Clone()
    h_ratio.Divide(h_mc)

    x_minbin = h_mc.FindFirstBinAbove()
    low = h_mc.GetXaxis().GetBinLowEdge(x_minbin)
    x_maxbin = h_mc.FindLastBinAbove()
    high = h_mc.GetXaxis().GetBinUpEdge(x_maxbin)
    h_mc.GetXaxis().SetRangeUser(low, high)
    h_mc.GetYaxis().SetTitleSize(0.08)
    h_mc.GetYaxis().SetLabelSize(0.065)
    h_mc.GetYaxis().SetTitleOffset(0.59)

    h_ratio.GetXaxis().SetRangeUser(low, high)

    g_stat = histo2graph(h)
    g_sys = histo2graph(h_sys)

    g_sys.SetMarkerStyle(20)
    g_sys.SetLineWidth(2)
    g_stat.SetFillStyle(3001)
    g_stat.SetFillColor(kGray + 2)
    g_stat.SetLineWidth(2)
    g_stat.SetLineColor(kGray + 2)

    pt = TPaveText(0.09, 0.855, 0.32, 0.98, "ndc")
    pt.AddText("MicroBooNE")
    pt.SetFillColor(0)
    pt.SetBorderSize(0)
    pt.SetShadowColor(0)

    leg = TLegend(0.55, 0.09, 0.86, 0.4)
    leg.AddEntry(g_sys, "Data - stat. #oplus sys.", "ep")
    leg.AddEntry(g_stat, "Data - stat. only", "f")
    leg.AddEntry(h_mc, "Monte Carlo", "f")

    canvas = draw_ratio("c_%s" % name, [h_mc, g_stat, g_sys, pt, leg],
                        [h_ratio], ["hist", "2", "p", "", ""], ["ep"])
    canvas.SaveAs("plots/%s.pdf" % name)
    canvas.SaveAs("plots/%s.C" % name)
Example #12
0
def getPavetext():
    addInfo = TPaveText(0.3010112, 0.2066292, 0.4202143, 0.3523546, "NDC")
    addInfo.SetFillColor(0)
    addInfo.SetLineColor(0)
    addInfo.SetFillStyle(0)
    addInfo.SetBorderSize(0)
    addInfo.SetTextFont(42)
    addInfo.SetTextSize(0.040)
    addInfo.SetTextAlign(12)
    return addInfo
Example #13
0
class HistogramSaver:
    def __init__(self, settings=None):
        print 'Starting Histogram Saver'
        self.settings = settings
        self.run = array(self.settings.runInfo['run'], 'I')
        self.eventNumber = array(int(0), 'I')
        self.plotPath = '.'
        self.plotRootPath = './root/'
        self.plotPdfPath = './pdf/'
        self.paveTextOptions = {}
        self.dateTime = TDatime()
        self.paveText = TPaveText(0.07, 0, 0.22, 0.10, 'NDC')
        self.UpdatePaveText()
        self.verb = self.settings.runInfo['verbose']
        self.optStat1D = 'nemr'
        self.optStat2D = 'ne'
        self.DefaultPlotStyle()

    def DefaultPlotStyle(self):
        gStyle.SetPalette(55)  # 55 is kRainBow. 53 is kDarkBodyRadiator
        gStyle.SetOptStat(self.optStat1D)
        gStyle.SetOptFit(11111)
        gStyle.SetStatH(0.12)
        gStyle.SetStatW(0.15)
        gStyle.SetPadBottomMargin(0.15)
        gStyle.SetPadTopMargin(0.15)

    def SetPath(self, path='.'):
        self.plotPath = self.RemoveExtraBackSlashes(path, 2)
        self.plotRootPath = self.RemoveExtraBackSlashes(path + '/root/', 3)
        self.plotPdfPath = self.RemoveExtraBackSlashes(path + '/pdf/', 3)
        self.settings.CheckDirExistence(self.plotPath, True)
        self.settings.CheckDirExistence(self.plotRootPath, True)
        self.settings.CheckDirExistence(self.plotPdfPath, True)

    def RemoveExtraBackSlashes(self, string, times=1):
        if times == 0:
            return string
        string = string.replace('//', '/')
        return self.RemoveExtraBackSlashes(string, times - 1)

    def UpdatePaveText(self):
        self.paveText.Clear()
        self.paveText.SetTextSize(0.025)
        self.paveTextOptions['svn'] = 'Rev: ' + self.settings.version
        self.paveTextOptions['run'] = 'Run ' + str(self.run)
        self.paveTextOptions['nEvents'] = 'with ' + str(
            self.settings.runInfo['nEvents']) + 'Events'
        self.paveTextOptions['DateTime'] = self.dateTime.AsSQLString()
        self.paveText.AddText(self.paveTextOptions['svn'])
        self.paveText.AddText(self.paveTextOptions['run'])
        self.paveText.AddText(self.paveTextOptions['nEvents'])
        self.paveText.AddText(self.paveTextOptions['DateTime'])
        self.paveText.SetBorderSize(0)
        self.paveText.SetFillColor(0)
Example #14
0
 def add_pave(self, x1, y1, x2, y2, border=False):
     """Creates a pave and adds it to the plot."""
     pave = TPaveText(x1, y1, x2, y2, 'NDC')
     n = len(self._container_draw)
     pave.SetTextFont(42)
     pave.SetTextSize(0.025)
     if border:
         pave.SetBorderSize(1)
         pave.SetFillColor(0)
     self.add(pave)
     return (lambda n: lambda s: self._container_draw[n].AddText(s))(n)
Example #15
0
    def do_final_cosmetics(self):
        self.decoratee.do_final_cosmetics()

        titlebox = TPaveText(0.18, 0.94, 0.9, 0.97, "brNDC")
        titlebox.AddText(self.make_title())
        titlebox.SetTextSize(0.045)
        titlebox.SetFillStyle(0)
        titlebox.SetBorderSize(0)
        titlebox.SetTextAlign(13)
        titlebox.SetMargin(0.0)
        titlebox.SetFillColor(0)
        titlebox.Draw("SAME")
        self.titlebox = titlebox
Example #16
0
	def plotHoTimeLog(self):
		c3 = TCanvas("c3Log","HO Time Log",1200,1200)
		skipNoisePlot = True
		if not skipNoisePlot:
			c3.Divide(1,2)
			c3.cd(1).SetLogy()
			label = getLabelCmsPrivateSimulation()
			label.Draw()
			hHoTime = self.fileHandler.getHistogram('hoRecHits_Time')
			
			hHoTime.SetStats(0)
			hHoTime.SetTitle("Time distribution for all HO Rec Hits")
			hHoTime.SetLineColor(colorRwthDarkBlue)
			hHoTime.SetLineWidth(3)
			hHoTime.Draw()
			label = getLabelCmsPrivateSimulation()
			label.Draw()
			
		hHoTimeAboveThr = self.fileHandler.getHistogram('hoRecHitsAboveThr_Time')
		c3.cd(2).SetLogy()
		hHoTimeAboveThr.SetStats(0)
		hHoTimeAboveThr.SetTitle("Time distribution for HO Rec Hits > 0.2 GeV")
		hHoTimeAboveThr.SetLineColor(colorRwthDarkBlue)
		hHoTimeAboveThr.SetLineWidth(3)
		setupAxes(hHoTimeAboveThr)
		hHoTimeAboveThr.Draw()
		
		label = getLabelCmsPrivateSimulation()
		label.Draw()
	
		fit = TF1("fit","gaus",-10,10)
		fit.SetParameter(1,0)
		fit.SetParameter(2,1)
		hHoTimeAboveThr.Fit(fit,'','R',-12.5,12.5)
		
		self.debug(80*'#')
		self.debug('Chi^2: %5.2f' % fit.GetChisquare())
		self.debug('NDF: %d' % fit.GetNDF())
		self.debug(80*'#')
		
		pText = TPaveText(0.7,0.8,0.9,0.9,'NDC')
		pText.AddText('Mean: %.2f ns' % (fit.GetParameter(1)))
		pText.AddText('#sigma: %.2f ns' % (fit.GetParameter(2)))
		pText.SetBorderSize(1)
		pText.SetFillColor(0)
		pText.Draw()
		
		c3.Update()
		self.storeCanvas(c3,"hoTimeLog")
		
		return c3,pText,hHoTimeAboveThr
Example #17
0
def drawDate(filename):
	from ROOT import TPaveText
	day,month,year = extractDate(filename)

	date_string = "%s %s %s" % (day, month, year)
	pave = TPaveText(0.005, 0.005, 0.1, 0.02, 'NDC')
	pave.SetTextFont(42)
	pave.SetTextSize(0.03)
	pave.SetFillStyle(1001)
	pave.SetFillColor(0)
	pave.SetBorderSize(0)
	pave.SetTextAlign(12)
	pave.AddText(date_string)
	return pave
Example #18
0
 def add_desc_to_canvas(self):
     txt1 = TPaveText(0.15, 0.8, 0.4, 0.92, "NDC")
     txt1.SetFillColor(kWhite)
     txt1.SetFillStyle(0)
     txt1.SetBorderSize(0)
     txt1.SetTextAlign(12) # middle,left
     txt1.SetTextFont(42) # helvetica
     txt1.SetTextSize(0.04)
     txt1.AddText("#varphi slice = %d, r slice = %d, z slice = %d" % \
                  (self.grid_phi, self.grid_r, self.grid_z))
     if self.opt_train[0] == 1 and self.opt_train[1] == 1:
         txt1.AddText("inputs: #rho_{SC} - <#rho_{SC}>, <#rho_{SC}>")
     elif self.opt_train[1] == 1:
         txt1.AddText("inputs: #rho_{SC} - <#rho_{SC}>")
     txt1.Draw()
Example #19
0
def draw_canvas_2d(name):

    f_mc = TFile("plots/mc/%s_mcc7.root" % name)
    h_mc = gDirectory.Get("h_%s_reco" % name)
    f = TFile("plots/data/e_%s_pandoraCosmic.root" % name)
    h = gDirectory.Get("h_%s" % name)
    h.Divide(h_mc)
    h.GetZaxis().SetRangeUser(0.5, 1.5)
    #h.GetZaxis().SetTitle("Data/Monte Carlo")
    #h.GetZaxis().RotateTitle()
    h.SetMarkerSize(2)
    x_minbin = h.FindFirstBinAbove(0, 1)
    low_x = h.GetXaxis().GetBinLowEdge(x_minbin)
    x_maxbin = h.FindLastBinAbove(0, 1)
    high_x = h.GetXaxis().GetBinUpEdge(x_maxbin)

    y_minbin = h.FindFirstBinAbove(0, 2)
    low_y = h.GetYaxis().GetBinLowEdge(y_minbin)
    y_maxbin = h.FindLastBinAbove(0, 2)
    high_y = h.GetYaxis().GetBinUpEdge(y_maxbin)

    h.GetXaxis().SetRangeUser(low_x, high_x)
    h.GetYaxis().SetRangeUser(low_y, high_y)

    c = TCanvas("c_%s" % name)
    h.SetMarkerSize(2.5)
    gPad.SetBottomMargin(0.17)
    gPad.SetLeftMargin(0.13)
    gPad.SetTopMargin(0.15)
    gPad.SetRightMargin(0.15)

    h.GetYaxis().SetTitleSize(0.07)
    h.GetXaxis().SetTitleSize(0.07)
    h.GetYaxis().SetTitleOffset(0.8)

    pt = TPaveText(0.13, 0.855, 0.42, 0.98, "ndc")
    pt.AddText("MicroBooNE")
    pt.SetFillColor(0)
    pt.SetBorderSize(0)
    pt.SetShadowColor(0)
    h.Draw("colz texte")

    pt.Draw()
    c.Update()
    c.SaveAs("plots/%s.pdf" % name)
    c.SaveAs("plots/%s.p" % name)

    return c
Example #20
0
def add_cut_desc(cuts, x_var):
    txt = TPaveText(0.5, 0.75, 0.9, 0.89, "NDC")
    txt.SetFillColor(kWhite)
    txt.SetBorderSize(0)
    txt.SetTextAlign(12)  # left, middle
    txt.SetTextSize(0.03)
    txt.AddText(cuts["deltaSC"]["desc"](cuts["deltaSC"]["%s_lim" % x_var]))
    txt.AddText("%s, 20 epochs" %
                cuts["z"]["desc"](cuts["z"]["%s_lim" % x_var]))
    #for cut_var in cuts:
    #if cut_var == "sector":
    #    txt.AddText("%s %d" % (cut_var, int(round(cut[cut_var][0]))))
    #if cut_var not in ("fsector", "phi", "r"):
    #    txt.AddText(cuts[cut_var]["desc"](cuts[cut_var]["%s_lim" % x_var]))
    #txt.AddText("20 epochs")
    return txt
Example #21
0
def BuildTPaveText(Properties):
    """creates a TPave object according to some properties or the defaults"""

    tpave_x1 = Properties.get("tpave_x1", 0.5)
    tpave_y1 = Properties.get("tpave_y1", 0.5)
    tpave_x2 = Properties.get("tpave_x2", 0.5)
    tpave_y2 = Properties.get("tpave_y2", 0.5)
    tpave_bsize = Properties.get("tpave_bsize", 0)
    tpave_text = Properties.get("tpave_text", "")
    tpave_textsize = Properties.get("tpave_textsize", 0.04)
    #
    t1 = TPaveText(tpave_x1, tpave_y1, tpave_x2, tpave_y2, 'NDC')
    t1.SetBorderSize(tpave_bsize)
    t1.AddText(tpave_text)
    t1.SetTextSize(tpave_textsize)
    t1.SetFillColor(0)
    return t1
Example #22
0
    def addStats(self, parNames, parValues):
        pt = TPaveText(.15, .45, .55, .85, 'NDC')
        pt.SetBorderSize(1)
        pt.SetFillColor(0)
        pt.SetTextAlign(12)
        pt.SetTextFont(62)
        pt.AddText(' #chi^{2}/d.o.f.   ' + str(round(self.chi2, 2)) + ' / ' +
                   str(self.dof))

        for i, name in enumerate(parNames):
            if i not in self.fixParams:
                pt.AddText('')
                pt.AddText(' ' + name + '   ' + '{:.2e}'.format(parValues[i]) +
                           ' #pm ' + '{:.2e}'.format(self.fitErr[i]))

        pt.Draw()

        return pt
Example #23
0
def tgs(tgraphs, title):

    tmg = TMultiGraph()
    tle = TLegend(0.6, 0.4, 0.9, 0.8)
    tit = TPaveText(0.2988506, 0.934322, 0.6997126, 1, "nbNDC")

    # Make title
    tit.SetFillColor(0)
    tit.SetFillStyle(0)
    tit.SetLineColor(0)
    tit.AddText(title)

    for i in xrange(len(tgraphs)):
        tgraphs[i].SetLineWidth(2)
        tgraphs[i].SetLineColor(i + 1)

        tmg.Add(tgraphs[i])
        tle.AddEntry(tgraphs[i], tgraphs[i].GetName(), "l")

    return [tmg, tle, tit]
Example #24
0
def plotWidth(dwdictX, fname, nameX, mX, cuts):
    sorted_dwdictX = SortedDict(dwdictX)
    n = len(sorted_dwdictX) - 1
    x = array('d', sorted_dwdictX.keys())
    y = array('d', sorted_dwdictX.values())
    gwX = TGraph(n, x, y)
    gwX.SetName("gwX")
    gwX.SetTitle("")
    gwX.GetXaxis().SetTitle("tan#beta")
    gwX.GetYaxis().SetTitle("#Gamma_{#it{" + nameX + "}}/#it{m}_{#it{" +
                            nameX + "}} [%]")
    gwX.SetLineColor(ROOT.kBlack)
    gwX.SetMarkerColor(ROOT.kBlack)
    gwX.SetMarkerStyle(20)
    gwX.SetMarkerSize(0.5)

    ptxt = TPaveText(0.62, 0.70, 0.87, 0.87, "NDC")
    ptxt.SetFillStyle(4000)  #will be transparent
    ptxt.SetFillColor(0)
    ptxt.SetTextFont(42)
    ptxt.SetBorderSize(0)
    ptxt.AddText("sin(#beta-#alpha)=1")
    ptxt.AddText("#it{m}_{#it{" + nameX + "}}=" + str(mX) + " GeV")

    c = TCanvas("c", "c", 600, 600)
    c.cd()
    c.SetLogx()
    c.SetLogy()
    c.SetGridx()
    c.SetGridy()
    c.SetTicks(1, 1)
    c.Draw()
    # gwX.Draw("p")
    gwX.Draw()
    ptxt.Draw("same")
    c.Modified()
    c.Update()
    c.SaveAs(fname)
mc_sum.Draw("same e2")

if not args.no_data:
    data.SetLineWidth(3)
    data.Draw("same P")

leg.Draw("same")

#left_title = TPaveText(0.1, 0.9, 0.4, 0.94, "brNDC")
#left_title.AddText("CMS preliminary at 13 TeV")
#left_title.SetTextFont(1)

left_title = TPaveText(0.15, 0.82, 0.25, 0.88, "brNDC")
left_title.AddText("CMS")
left_title.SetTextFont(1)
left_title.SetFillColor(0)
#left_title.Draw("same")

#right_title = TPaveText(0.75, 0.9, 0.9, 0.94, "brNDC")
#right_title.AddText("L = %s fb^{-1}" % args.lumi)
#right_title.SetTextFont(132)
#right_title.SetFillColor(0)

right_title = TPaveText(0.7, 0.9, 0.9, 0.98, "brNDC")
#if report_lumi:
#    right_title.AddText("%s fb^{-1} (13 TeV)" % (31.3 if chan == 'el' else 35.8))
#else:
#    right_title.AddText("(13 TeV)")
right_title.AddText("%s fb^{-1} (13 TeV)" % args.lumi)
right_title.SetTextFont(132)
right_title.SetFillColor(0)
Example #26
0
def createPlots_(plot, compounddetectorname):
    """Cumulative material budget from simulation.
    
       Internal function that will produce a cumulative profile of the
       material budget inferred from the simulation starting from the
       single detectors that compose the tracker. It will iterate over
       all existing detectors contained in the DETECTORS
       dictionary. The function will automatically skip non-existent
       detectors.

    """

    theDirname = "Figures"

    hist_X0_detectors = OrderedDict()
    if plot not in plots.keys():
        print("Error: chosen plot name not known %s" % plot)
        return

    # We need to keep the file content alive for the lifetime of the
    # full function....
    subDetectorFiles = []

    hist_X0_elements = OrderedDict()
    prof_X0_elements = OrderedDict()
    for subDetector, color in DETECTORS.iteritems():
        subDetectorFilename = "matbdg_%s.root" % subDetector
        if not checkFile_(subDetectorFilename):
            print("Error opening file: %s" % subDetectorFilename)
            continue

        subDetectorFiles.append(TFile(subDetectorFilename))
        subDetectorFile = subDetectorFiles[-1]
        print("Opening file: %s" % subDetectorFilename)
        prof_X0_XXX = subDetectorFile.Get("%d" % plots[plot].plotNumber)

        hist_X0_detectors[subDetector] = prof_X0_XXX.ProjectionX()

        # category profiles
        for label, [num, color, leg] in hist_label_to_num.iteritems():
            prof_X0_elements[label] = subDetectorFile.Get(
                "%d" % (num + plots[plot].plotNumber))
            hist_X0_elements[label] = assignOrAddIfExists_(
                hist_X0_elements.setdefault(label, None),
                prof_X0_elements[label])

    cumulative_matbdg = TH1D(
        "CumulativeSimulMatBdg", "CumulativeSimulMatBdg",
        hist_X0_detectors["BeamPipe"].GetNbinsX(),
        hist_X0_detectors["BeamPipe"].GetXaxis().GetXmin(),
        hist_X0_detectors["BeamPipe"].GetXaxis().GetXmax())
    cumulative_matbdg.SetDirectory(0)

    # colors
    for det, color in DETECTORS.iteritems():
        setColorIfExists_(hist_X0_detectors, det, color)

    for label, [num, color, leg] in hist_label_to_num.iteritems():
        hist_X0_elements[label].SetFillColor(color)

    # First Plot: BeamPipe + Tracker + ECAL + HCal + HGCal + MB + MGNT
    # stack
    stackTitle_SubDetectors = "Material Budget;%s;%s" % (plots[plot].abscissa,
                                                         plots[plot].ordinate)
    stack_X0_SubDetectors = THStack("stack_X0", stackTitle_SubDetectors)
    for det, histo in hist_X0_detectors.iteritems():
        stack_X0_SubDetectors.Add(histo)
        cumulative_matbdg.Add(histo, 1)

    # canvas
    can_SubDetectors = TCanvas("can_SubDetectors", "can_SubDetectors", 800,
                               800)
    #can_SubDetectors.Range(0,0,25,25)
    can_SubDetectors.SetFillColor(kWhite)

    # Draw
    stack_X0_SubDetectors.SetMinimum(plots[plot].ymin)
    stack_X0_SubDetectors.SetMaximum(plots[plot].ymax)
    stack_X0_SubDetectors.Draw("HIST")
    #stack_X0_SubDetectors.GetXaxis().SetLimits(plots[plot].xmin, plots[plot].xmax)

    # Legenda
    theLegend_SubDetectors = TLegend(0.130, 0.7, 0.93,
                                     0.90)  #(0.180,0.8,0.98,0.90)
    theLegend_SubDetectors.SetNColumns(2)
    theLegend_SubDetectors.SetFillColor(0)
    theLegend_SubDetectors.SetFillStyle(0)
    theLegend_SubDetectors.SetBorderSize(0)

    for det, histo in hist_X0_detectors.iteritems():
        theLegend_SubDetectors.AddEntry(histo, det, "f")

    theLegend_SubDetectors.Draw()

    # text
    text_SubDetectors = TPaveText(0.130, 0.627, 0.352, 0.687,
                                  "NDC")  #(0.180,0.727,0.402,0.787,"NDC")
    text_SubDetectors.SetFillColor(0)
    text_SubDetectors.SetBorderSize(0)
    text_SubDetectors.AddText("CMS Simulation")
    text_SubDetectors.SetTextAlign(11)
    text_SubDetectors.Draw()

    # Store
    can_SubDetectors.Update()
    if not checkFile_(theDirname):
        os.mkdir(theDirname)
    can_SubDetectors.SaveAs("%s/MaterialBdg_%s_%s.pdf" %
                            (theDirname, compounddetectorname, plot))
    can_SubDetectors.SaveAs("%s/MaterialBdg_%s_%s.png" %
                            (theDirname, compounddetectorname, plot))
    can_SubDetectors.SaveAs("%s/MaterialBdg_%s_%s.root" %
                            (theDirname, compounddetectorname, plot))

    if plot == "x_vs_eta" or plot == "l_vs_eta":
        canname = "MBCan_1D_%s_%s_total" % (compounddetectorname, plot)
        can2 = TCanvas(canname, canname, 800, 800)
        can2.Range(0, 0, 25, 25)
        can2.SetFillColor(kWhite)
        gStyle.SetOptStat(0)
        gStyle.SetOptTitle(0)
        #title = TPaveLabel(.11,.95,.35,.99,"Total accumulated material budget","brndc")
        stack_X0_SubDetectors.GetStack().Last().SetMarkerStyle(34)
        stack_X0_SubDetectors.GetStack().Last().GetXaxis().SetRangeUser(
            1.0, 3.5)
        stack_X0_SubDetectors.GetStack().Last().Draw()
        stack_X0_SubDetectors.GetYaxis().SetTitleOffset(1.15)
        can2.Update()
        can2.Modified()
        can2.SaveAs("%s/%s_%s_total_Zplus.pdf" %
                    (theDirname, compounddetectorname, plot))
        can2.SaveAs("%s/%s_%s_total_Zplus.png" %
                    (theDirname, compounddetectorname, plot))
        stack_X0_SubDetectors.GetStack().Last().GetXaxis().SetRangeUser(
            -3.5, -1.0)
        stack_X0_SubDetectors.GetStack().Last().Draw()
        stack_X0_SubDetectors.GetYaxis().SetTitleOffset(1.15)
        can2.Update()
        can2.Modified()
        can2.SaveAs("%s/%s_%s_total_Zminus.pdf" %
                    (theDirname, compounddetectorname, plot))
        can2.SaveAs("%s/%s_%s_total_Zminus.png" %
                    (theDirname, compounddetectorname, plot))

        #Also print them to give them exact numbers
        etavalues = []
        matbudginX0 = []
        matbudginIntLen = []
        for binx in range(
                0,
                stack_X0_SubDetectors.GetStack().Last().GetXaxis().GetNbins()):
            bincontent = stack_X0_SubDetectors.GetStack().Last().GetBinContent(
                binx)
            if bincontent == 0: continue
            etavalues.append(
                stack_X0_SubDetectors.GetStack().Last().GetBinCenter(binx))
            if plot == "x_vs_eta":
                matbudginX0.append(bincontent)
                d1 = {'Eta': etavalues, 'MatBudInX0': matbudginX0}
                df1 = pd.DataFrame(data=d1).round(2)
                df1.to_csv(
                    r'/afs/cern.ch/work/a/apsallid/CMS/PFCalStudies/CMS-HGCAL/matbudV10fromVertexToBackofHGCal/CMSSW_11_0_X_2019-06-04-2300/src/Validation/Geometry/test/EtavsMatBudinXo.txt',
                    sep=' ',
                    index=False,
                    header=False)
                #print df1
            if plot == "l_vs_eta":
                matbudginIntLen.append(bincontent)
                d2 = {'Eta': etavalues, 'MatBudInIntLen': matbudginIntLen}
                df2 = pd.DataFrame(data=d2).round(2)
                df2.to_csv(
                    r'/afs/cern.ch/work/a/apsallid/CMS/PFCalStudies/CMS-HGCAL/matbudV10fromVertexToBackofHGCal/CMSSW_11_0_X_2019-06-04-2300/src/Validation/Geometry/test/EtavsMatBudInIntLen.txt',
                    sep=' ',
                    index=False,
                    header=False)
                #print df2

    return cumulative_matbdg
Example #27
0
def createPlots2D_(plot, compounddetectorname):
    """2D material budget map to know exactly what we are adding.
    """

    #IBs = ["InnerServices", "Phase2PixelBarrel", "TIB", "TIDF", "TIDB"]
    theDirname = "Figures"

    hist_X0_detectors = OrderedDict()
    if plot not in plots.keys():
        print("Error: chosen plot name not known %s" % plot)
        return

    # We need to keep the file content alive for the lifetime of the
    # full function....
    subDetectorFiles = []

    hist_X0_elements = OrderedDict()
    prof_X0_elements = OrderedDict()

    for subDetector, color in DETECTORS.iteritems():
        subDetectorFilename = "matbdg_%s.root" % subDetector
        if not checkFile_(subDetectorFilename):
            print("Error opening file: %s" % subDetectorFilename)
            continue

        subDetectorFiles.append(TFile(subDetectorFilename))
        subDetectorFile = subDetectorFiles[-1]
        print("Opening file: %s" % subDetectorFilename)
        prof_X0_XXX = subDetectorFile.Get("%d" % plots[plot].plotNumber)

        #hist_X0_detectors[subDetector] = prof_X0_XXX
        hist_X0_detectors[subDetector] = prof_X0_XXX.ProjectionXY("_pxy", "B")
        print subDetector

    # First Plot: BeamPipe + Tracker + ECAL + HCal + HGCal + MB + MGNT

    # Create "null" histo
    minX = 1.03 * hist_X0_detectors["BeamPipe"].GetXaxis().GetXmin()
    maxX = 1.03 * hist_X0_detectors["BeamPipe"].GetXaxis().GetXmax()
    minY = 1.03 * hist_X0_detectors["BeamPipe"].GetYaxis().GetXmin()
    maxY = 1.03 * hist_X0_detectors["BeamPipe"].GetYaxis().GetXmax()

    frame = TH2F("frame", "", 10, minX, maxX, 10, minY, maxY)
    frame.SetMinimum(0.1)
    frame.SetMaximum(10.)
    frame.GetXaxis().SetTickLength(frame.GetXaxis().GetTickLength() * 0.50)
    frame.GetYaxis().SetTickLength(frame.GetXaxis().GetTickLength() / 4.)

    hist2d_X0_total = hist_X0_detectors["BeamPipe"]

    # stack
    hist2dTitle = (
        '%s %s;%s;%s;%s' %
        (plots[plot].quotaName, "All detectors", plots[plot].abscissa,
         plots[plot].ordinate, plots[plot].quotaName))

    hist2d_X0_total.SetTitle(hist2dTitle)
    frame.SetTitle(hist2dTitle)
    frame.SetTitleOffset(0.5, "Y")

    #If here you put different histomin,histomaxin plot_utils you won't see anything
    #for the material plots.
    if plots[plot].histoMin != -1.:
        hist2d_X0_total.SetMinimum(plots[plot].histoMin)
    if plots[plot].histoMax != -1.:
        hist2d_X0_total.SetMaximum(plots[plot].histoMax)

    #
    # canvas
    can_SubDetectors = TCanvas("can_SubDetectors", "can_SubDetectors",
                               2480 + 248, 580 + 58 + 58)
    can_SubDetectors.SetTopMargin(0.1)
    can_SubDetectors.SetBottomMargin(0.1)
    can_SubDetectors.SetLeftMargin(0.04)
    can_SubDetectors.SetRightMargin(0.06)
    can_SubDetectors.SetFillColor(kWhite)
    gStyle.SetOptStat(0)
    gStyle.SetTitleFillColor(0)
    gStyle.SetTitleBorderSize(0)
    gStyle.SetOptTitle(0)

    hist2d_X0_total.GetYaxis().SetTickLength(
        hist2d_X0_total.GetXaxis().GetTickLength() / 4.)
    hist2d_X0_total.GetYaxis().SetTickLength(
        hist2d_X0_total.GetXaxis().GetTickLength() / 4.)
    hist2d_X0_total.SetTitleOffset(0.5, "Y")
    hist2d_X0_total.GetYaxis().SetTitleOffset(0.50)
    #hist2d_X0_total.GetXaxis().SetTitleOffset(1.15);
    #hist2d_X0_total.GetXaxis().SetNoExponent(True)
    #hist2d_X0_total.GetYaxis().SetNoExponent(True)

    # colors
    for det, color in DETECTORS.iteritems():
        hist_X0_detectors[det].SetMarkerColor(color)
        hist_X0_detectors[det].SetFillColor(color)

    for det, histo in hist_X0_detectors.iteritems():
        print det
        histo.Draw("same")

    # Legenda
    theLegend_SubDetectors = TLegend(0.100, 0.7, 0.90,
                                     0.90)  #(0.180,0.8,0.98,0.90)
    theLegend_SubDetectors.SetNColumns(3)
    theLegend_SubDetectors.SetFillColor(0)
    theLegend_SubDetectors.SetFillStyle(0)
    theLegend_SubDetectors.SetBorderSize(0)

    for det, histo in hist_X0_detectors.iteritems():
        theLegend_SubDetectors.AddEntry(histo, det, "f")
    #theLegend_SubDetectors.AddEntry(hgbound1, "HGCal Eta Boundaries [1.3, 3.0]",  "l")

    theLegend_SubDetectors.Draw()

    # text
    text_SubDetectors = TPaveText(0.100, 0.627, 0.322, 0.687,
                                  "NDC")  #(0.180,0.727,0.402,0.787,"NDC")
    text_SubDetectors.SetFillColor(0)
    text_SubDetectors.SetBorderSize(0)
    text_SubDetectors.AddText("CMS Simulation")
    text_SubDetectors.SetTextAlign(11)
    text_SubDetectors.Draw()

    #Add eta labels
    keep_alive = []
    if plots[plot].iDrawEta:
        keep_alive.extend(drawEtaValues())

    # Store
    can_SubDetectors.Update()
    if not checkFile_(theDirname):
        os.mkdir(theDirname)
    can_SubDetectors.SaveAs("%s/MaterialBdg_%s_%s.png" %
                            (theDirname, compounddetectorname, plot))
    #It seems that it is too heavy to create .pdf and .root
    #can_SubDetectors.SaveAs("%s/MaterialBdg_FromVertexToEndofHGCal_%s.pdf" % (theDirname, plot))
    #can_SubDetectors.SaveAs("%s/MaterialBdg_FromVertexToEndofHGCal_%s.root" % (theDirname, plot))

    hist2d_X0_total.GetXaxis().SetRangeUser(0., 7000.)
    #Draw eta values in the zoom case
    keep_alive = []
    keep_alive.extend(drawHalfEtaValues())
    #hist2d_X0_total.Draw("COLZ")
    can_SubDetectors.Update()
    can_SubDetectors.Modified()
    can_SubDetectors.SaveAs("%s/MaterialBdg_%s_%s_Zpluszoom.png" %
                            (theDirname, compounddetectorname, plot))
g_reco_eff_data.SetMarkerStyle(30)
g_reco_eff_data.SetMarkerSize(1.5)
g_reco_eff_data.SetLineStyle(2)

l = TLegend(0.46, 0.16, 0.85, 0.425)
l.SetBorderSize(0)
l.SetShadowColor(0)

l.AddEntry(g_purity, "Purity #it{P}", "lp")
l.AddEntry(g_acceptance, "Acceptance #it{A}", "lp")

l.AddEntry(g_eff, "MuCS-MC tagging efficiency #it{#epsilon}_{tag}^{MuCS-MC}",
           "lp")
l.AddEntry(g_data_eff, "Data tagging efficiency #it{#epsilon}_{tag}^{data}",
           "lp")

l.AddEntry(g_reco_eff,
           "MuCS-MC reconstruction efficiency #it{#epsilon}_{MuCS-MC}", "lp")
l.AddEntry(g_reco_eff_data,
           "Data reconstruction efficiency #it{#epsilon}_{data}", "lp")

l.Draw()
pt = TPaveText(0.09, 0.91, 0.34, 0.98, "ndc")
pt.AddText("MicroBooNE")
pt.SetFillColor(0)
pt.SetBorderSize(0)
pt.SetShadowColor(0)
pt.Draw()
c.Update()
input()
Example #29
0
def TrackToFile_ROOT_2D_3D(data,
                           save_path,
                           log_z=False,
                           plot_opt='',
                           force_aspect=True,
                           legend_text='',
                           fitline=None,
                           zmax=None,
                           zmax_supress_ratio=1.0):
    from ROOT import TH2F, TCanvas
    if plot_opt == '': plot_opt = 'colz0'
    if plot_opt != 'box' and plot_opt != 'colz': plot_opt = 'colz0'

    if force_aspect:
        nbinsx = xmax = max(data.shape[0], data.shape[1])
        nbinsy = ymax = max(data.shape[0], data.shape[1])
    else:
        nbinsx = xmax = data.shape[0]
        nbinsy = ymax = data.shape[1]

    if zmax != None and zmax_supress_ratio != 1.0:
        print "Warning - using both zmax absolute and zmax_supress"
        print "zmax will be set at zmax * zmax_supress - is this what you meant to do?"

    xlow = 0
    ylow = 0

    c4 = TCanvas('canvas', 'canvas', 1600, 800)  #create canvas
    c4.Divide(2, 1, 0.002, 0.00001)
    c4.cd(2)

    image_hist = TH2F('', '', nbinsx, xlow, xmax, nbinsy, ylow, ymax)
    for x in range(data.shape[0]):
        for y in range(data.shape[1]):
            value = data[x, y]
            if value != 0:
                image_hist.Fill(float(x), float(y), float(value))

    if zmax_supress_ratio != 1.0 or zmax != None:
        binnum = image_hist.GetMaximumBin()
        true_zmax = image_hist.GetBinContent(binnum)

        if zmax != None:
            new_zmax = zmax * zmax_supress_ratio
        else:
            new_zmax = true_zmax * zmax_supress_ratio

        image_hist.GetZaxis().SetRangeUser(0, new_zmax)

    image_hist.Draw(plot_opt)
    if fitline != None:
        from ROOT import TF1
        a = fitline.a
        b = fitline.b
        formula = str(a) + '*x + ' + str(b)
        plane = TF1("f2", formula, 0, xmax)
        plane.SetNpx(100)
        plane.Draw("same")

    c4.cd(1)
    image_hist.Draw("lego20")  # good for CR Tracks
    #     image_hist.Draw("surf2") # better for Timepix/medipix composites / heatmaps

    if legend_text != '':
        from ROOT import TPaveText
        textbox = TPaveText(0.0, 1, 0.2, 0.9, "NDC")
        for line in legend_text:
            textbox.AddText(line)
        textbox.SetFillColor(0)
        textbox.Draw("same")

    if log_z: c4.SetLogz()
    image_hist.SetStats(False)
    c4.SaveAs(save_path)
Example #30
0
	def plotImprovementInTightDt(self):
		#Prepare canvas
		canvas = TCanvas("canvasTightDtImprovement","tight DT improvement",1200,1200)
		canvas.SetLogy()
		histDt = self.fileHandler.getHistogram("timingSupport_tight_UnmatchedDtHo_BxId")
		histDtNoHo = self.fileHandler.getHistogram("timingSupport_tight_UnmatchedDt_BxId")
		
		#Define variables for integrals
		histHoTime = self.fileHandler.getHistogram('timingSupport_tight_UnmatchedDtHo_Time')
		integralHoCorrect = histHoTime.Integral(histHoTime.FindBin(-12.5),histHoTime.FindBin(12.5))
		integralHoTotal = histHoTime.Integral()
		integralHoOutside = integralHoTotal - integralHoCorrect
		hoFractionWrong = integralHoOutside/float(integralHoTotal)
		hoFractionRight = integralHoCorrect/float(integralHoTotal)
		
		#Print some information
		heading = 'Integrals of the Ho timing (tight):'
		print CliColors.OKBLUE
		print 80*'#'
		print heading
		print len(heading)*'-'
		print 'Timing correct:\t%d\t=>\t%6.3f%% +/- %6.3f%%'%(integralHoCorrect,hoFractionRight*100,calcSigma(integralHoCorrect, integralHoTotal)*100)
		print 'Timing outside:\t%d\t=>\t%6.3f%% +/- %f%%'%(integralHoOutside,hoFractionWrong*100,calcSigma(integralHoOutside, integralHoTotal)*100)
		print 'Timing total:%d'%(integralHoTotal)
		print
		
		#Define Variables for bx id counts
		dtBx0 = histDt.GetBinContent(6)
		dtBxM1 = histDt.Integral(histDt.FindBin(-10),histDt.FindBin(-1))#histDt.GetBinContent(5)
		dtBxP1 = histDt.Integral(histDt.FindBin(1),histDt.FindBin(10))#histDt.GetBinContent(7)
		dtBxTotal = dtBx0 + dtBxM1 + dtBxP1
		dtFractionWrongM1 = dtBxM1/float(dtBxTotal)
		dtFractionWrongP1 = dtBxP1/float(dtBxTotal)
	
		noHodtBx0 = histDtNoHo.GetBinContent(6)
		noHodtBxM1 = histDtNoHo.Integral(histDtNoHo.FindBin(-10),histDtNoHo.FindBin(-1))
		noHodtBxP1 = histDtNoHo.Integral(histDtNoHo.FindBin(1),histDtNoHo.FindBin(10))
		noHodtBxTotal = noHodtBx0 + noHodtBxM1 + noHodtBxP1
		noHodtFractionWrongM1 = noHodtBxM1/float(noHodtBxTotal)
		noHodtFractionWrongP1 = noHodtBxP1/float(noHodtBxTotal)
		
		
		#Print some information
		heading = 'Bin contents for tight DT timing:'
		print heading
		print len(heading)*'-'
		print 'BX ID  0:\t%d\t=>\t%6.3f%% +/- %6.3f%%'%(dtBx0,dtBx0/float(dtBxTotal)*100,calcSigma(dtBx0, dtBxTotal)*100)
		print 'BX ID -1:\t%d\t=>\t%6.3f%% +/- %6.3f%%'%(dtBxM1,dtFractionWrongM1*100,calcSigma(dtBxM1, dtBxTotal)*100)
		print 'BX ID +1:\t%d\t=>\t%6.3f%% +/- %6.3f%%'%(dtBxP1,dtFractionWrongP1*100,calcSigma(dtBxP1, dtBxTotal)*100)
		print 'BX ID total:\t%d\t(hist integral: %d)' % (dtBxTotal,histDt.Integral())
		print
		
		print 'NO HO'
		print 'BX ID  0:\t%d\t=>\t%6.3f%% +/- %6.3f%%'%(noHodtBx0,noHodtBx0/float(noHodtBxTotal)*100,calcSigma(noHodtBx0, noHodtBxTotal)*100)
		print 'BX ID -1:\t%d\t=>\t%6.3f%% +/- %6.3f%%'%(noHodtBxM1,noHodtFractionWrongM1*100,calcSigma(noHodtBxM1, noHodtBxTotal)*100)
		print 'BX ID +1:\t%d\t=>\t%6.3f%% +/- %6.3f%%'%(noHodtBxP1,noHodtFractionWrongP1*100,calcSigma(noHodtBxP1, noHodtBxTotal)*100)
		print 'BX ID total:\t%d\t(hist integral: %d)' % (noHodtBxTotal,histDtNoHo.Integral())
		
		print
		
		#Calculate corrected numbers
		correctedBxIdM1 = dtBxM1 + hoFractionWrong*dtBx0/2. - hoFractionRight*dtBxM1
		correctedBxId0 = dtBx0 - hoFractionWrong*dtBx0 + hoFractionRight*dtBxM1 + hoFractionRight*dtBxP1
		correctedBxIdP1 = dtBxP1 + hoFractionWrong*dtBx0/2. - hoFractionRight*dtBxP1
		correctedTotal = correctedBxIdM1 + correctedBxId0 + correctedBxIdP1
		correctedRightFraction = correctedBxId0/float(correctedTotal)
		
		heading = 'DT After correction:'
		print heading
		print len(heading)*'-'
		print 'BX -1:\t',int(correctedBxIdM1)
		print 'BX  0:\t',int(correctedBxId0)
		print 'BX +1:\t',int(correctedBxIdP1)
		print 
		#Fill corrected histogram
		histNew = TH1D("histNewTight","BX ID in tight DT only triggers;BX ID;rel. fraction",6,-2.5,3.5)
		histNew.SetBinContent(histNew.FindBin(-1),correctedBxIdM1)
		histNew.SetBinContent(histNew.FindBin(0),correctedBxId0)
		histNew.SetBinContent(histNew.FindBin(1),correctedBxIdP1)
		histNew.SetLineColor(colorRwthMagenta)
		histNew.SetStats(0)
		histNew.Scale(1/histNew.Integral())
		histNew.SetLineStyle(9)
		setupAxes(histNew)
		setBigAxisTitles(histNew)
		histDt.GetXaxis().SetRangeUser(-3,3)
		histDt.SetLineWidth(3)
		histDt.Scale(1/histDt.Integral())
		histDt.SetLineColor(colorRwthDarkBlue)
		
		histNew.Draw()
		histDt.Draw('same')
		histNew.Draw('same')
				
		histDtNoHo.Scale(1/histDtNoHo.Integral())
		histDtNoHo.SetLineWidth(3)
		#histDtNoHo.Draw('same')
	
		#Add label
		label = self.drawLabel()
		
		#Add legend
		legend = TLegend(0.7,0.65,0.9,0.8)
		legend.AddEntry(histDt,"tight DT Only + HO","l")
		legend.AddEntry(histNew,"tight DT shifted with HO","l")
		legend.SetBorderSize(1)
		legend.Draw()
		
		#Add text object
		pText = TPaveText(0.52,0.8,0.9,0.9,'NDC')
		pText.AddText('Fraction in tight BX ID 0: %5.2f%% #pm %5.2f%%' % (dtBx0/float(dtBxTotal)*100,calcSigma(dtBx0, dtBxTotal)*100))
		pText.AddText('Fraction in tight BX ID 0 (HO corr.): %5.2f%% #pm %5.2f%%' % (correctedRightFraction*100,calcSigma(correctedBxId0, correctedTotal)*100))
		pText.SetBorderSize(1)
		pText.SetFillColor(0)
		pText.Draw()
		
		pText2 = TPaveText(0.7,0.6,0.9,0.65,'NDC')
		pText2.AddText('Entries: %d' % (histDt.GetEntries()))
		pText2.SetBorderSize(1)
		pText2.SetFillColor(0)
		pText2.Draw()
		
		#Print again some information
		heading = 'Fraction of correct BXID (tight):'
		print heading
		print len(heading)*'-'
		print 'Uncorrected:\t%5.2f%% #pm %f%%' % (dtBx0/float(dtBxTotal)*100,calcSigma(dtBx0, dtBxTotal)*100)
		print 'Corrected\t%5.2f%% #pm %f%%' % (correctedRightFraction*100,calcSigma(correctedBxId0, correctedTotal)*100)
		print 80*'#'
		print CliColors.ENDC

		setupAxes(histNew)
		
		canvas.Update()
		self.storeCanvas(canvas, 'correctedTightDt')
		return canvas, histDt,histNew,label,legend,pText2,pText,histDtNoHo