コード例 #1
0
ファイル: analysis.py プロジェクト: lantone/BabyNames
def produceFamilyPlot(family, surname):

    canvas = TCanvas(surname, "", 2400, 800)

    legend = TLegend(0.1, 0.5, 0.4, 0.87)
    legend.SetBorderSize(0)
    legend.SetFillStyle(0)

    counter = 0
    markers = []
    for person in family:
        if len(person) < 2:
            print "error"
            continue
        name = person[0]
        sex = person[1]

        if len(person) >= 3:
            birth = person[2]
        else:
            birth = 0

        plot = makePlot(name, sex)
        normalizePlot(plot)

        plot.SetTitle("")
        plot.GetYaxis().SetLabelSize(0)
        plot.GetXaxis().SetLabelSize(0.07)
        plot.GetYaxis().SetTickSize(0)
        plot.GetYaxis().SetTitle("normalized popularity")
        plot.GetYaxis().SetTitleSize(0.07)
        plot.GetYaxis().SetTitleOffset(0.22)

        plot.SetLineColor(colors[counter])
        legend.AddEntry(plot, name, "L")
        plot.Draw("same C")
        if birth > 0:
            marker = TMarker(birth+0.5,
                             plot.GetBinContent(plot.FindBin(birth)), 20)
            marker.SetMarkerColor(colors[counter])
            marker.SetMarkerSize(5)
            markers.append(marker)
            markers[counter].Draw("same")

        counter += 1
    legend.Draw()

    canvas.SaveAs(surname + ".pdf")
コード例 #2
0
def plotCombinedEfficiency():
    hl = plotEfficiency('.')
    canv = TCanvas("canvasCombinedEfficiency", "Combined efficiency plot",
                   1200, 1200)
    leg = TLegend(0.55, 0.1, 0.9, 0.5)
    for i, val in enumerate(hl):
        if (i == 0):
            val[0].Draw()
            val[0].SetTitle("Efficiency for several p_{T}")
        else:
            val[0].Draw('same')
        val[1].Draw('same')

    hl[0][1].SetFillColor(colorRwthMagenta)
    hl[0][0].SetFillColor(colorRwthDarkBlue)
    leg.AddEntry(hl[0][0], "L1", "f")
    leg.AddEntry(hl[0][1], "L1 + HO", "f")
    markers = []
    for i, pair in enumerate(markerpairs):
        markers.append(TMarker(1, 1, pair[0]))
        markers[i].SetMarkerSize(3)
        leg.AddEntry(markers[i], "p_{T} = " + str((i + 1) * 5) + " GeV", "p")
    leg.Draw()

    label = drawLabelCmsPrivateSimulation()

    if (not os.path.exists('plots')):
        os.mkdir('plots')
    if (not os.path.exists('plots/efficiency')):
        os.mkdir('plots/efficiency')

    canv.SaveAs('plots/efficiency/combinedEfficiency.png')
    canv.SaveAs('plots/efficiency/combinedEfficiency.pdf')
    canv.SaveAs('plots/efficiency/combinedEfficiency.root')
    return canv, leg, hl, label
コード例 #3
0
ファイル: Examples.py プロジェクト: skluth/ConstrainedFit
def _doProfile2d( solver, ipar1=0, type1="u", ipar2=1, type2= "m" ):
    from ConstrainedFit import clsq
    from ROOT import TGraph2D, TMarker, gPad
    from array import array
    global tg2d, hist, te1, te2, te3, tm
    par1= clsq.createClsqPar( ipar1, type1, solver )
    par2= clsq.createClsqPar( ipar2, type2, solver )
    parval1, parerr1, name1= _getUMParErrName( par1 )
    parval2, parerr2, name2= _getUMParErrName( par2 )
    print( "\nChi^2 profile plot " + name1 + " - " + name2 + ":" )
    corr= solver.getCorrMatrix()
    icorr1= ipar1
    icorr2= ipar2
    if type1 == "u" or type2 == "u":
        nmpar= len(solver.getMpars())
        if type1 == "u":
            icorr1= nmpar + ipar1
        if type2 == "u":
            icorr2= nmpar + ipar2
    rho= corr[icorr1,icorr2]
    te1= _makeEllipse( parval1, parval2, parerr1, parerr2, rho )
    te2= _makeEllipse( parval1, parval2, 2.0*parerr1, 2.0*parerr2, rho )
    te3= _makeEllipse( parval1, parval2, 3.0*parerr1, 3.0*parerr2, rho )
    ca= clsq.clsqAnalysis( solver )
    points= ca.profile2d( par1, par2 )
    npoints= len(points)
    tg2d= TGraph2D( npoints )
    for i in range( npoints ):
        point= points[i]
        tg2d.SetPoint( i, point[0], point[1], point[2] )
    hist= tg2d.GetHistogram()
    contourlevels= array( "d", [ 1.0, 4.0, 9.0 ] )
    hist.SetContour( 3, contourlevels )
    hist.GetXaxis().SetTitle( name1 )
    hist.GetYaxis().SetTitle( name2 )
    hist.SetTitle( "Triangle fit "+name2+" vs "+name1 )
    hist.Draw( "cont1" )
    tm= TMarker( parval1, parval2, 20 )
    tm.Draw( "s" )
    te1.Draw( "s" )
    te2.Draw( "s" )
    te3.Draw( "s" )
    gPad.Print( "triangle_errorellipse.png" )
    return
コード例 #4
0
def findIntersect(g1,g2,x1,x2):
  orientation = (g1.Eval(x1)<g2.Eval(x1))
  for iX in xrange(1000):
    x = (x2-x1)*iX/1000.+x1
    if orientation != (g1.Eval(x)<g2.Eval(x)):
      # return TGraph(1,array('f',[x]),array('f',[g1.Eval(x)]))
      return TMarker(x,g1.Eval(x),1)
      # return x
  print 'Could not find intersection!'
  return None
コード例 #5
0
def draw_potential():
    markers = []
    c1 = TCanvas("c1", "Prova")
    h2 = TH2F("h2", "h2", 1000, -100, 1200, 1000, 0, 1000)

    m = re.compile("(\d+)\s(\d+)\s([\-0-9\.]+)\s([\-0-9]+)")
    file = open("mappa_piazza.dat")
    while 1:
        line = file.readline()
        if (not line):
            break
        n = m.match(line)
        if (n):
            po = TMarker(float(n.group(1)), float(n.group(2)), 6)
            po.SetMarkerColor(abs(int(n.group(4))) + 1)
            markers.append(po)

    h2.Draw()
    for i in markers:
        i.Draw("SAME")
    c1.SaveAs("potenziale_piazza.png")
    sys.exit(1)
コード例 #6
0
ファイル: EvsEtaPhi.py プロジェクト: ashrafkasem/MCHAMMER
	def calculateCentralFractionInTight(self):
		hSum = self.fileHandler.getHistogram('deltaEtaDeltaPhiEnergy/averageEMaxAroundPointpatTightToL1Muons_2dSummedWeights')
		hCounter = self.fileHandler.getHistogram('deltaEtaDeltaPhiEnergy/averageEMaxAroundPointpatTightToL1Muons_2dCounter')

		points = []
		sum = 0
		for x in range(0,5):
			for y in range(0,5):
				sum += hCounter.GetBinContent(hSum.FindBin(x*0.0435 - 0.087,y*0.0435 - 0.087))
				p = TMarker(x*0.0435 - 0.087,y*0.0435 - 0.087,20)
		#		p.Draw('same')
				points.append(p)
		print sum
		print hCounter.Integral()
		print '-----'
		print sum/hCounter.Integral()
コード例 #7
0
def plot_event(name, canvas):
  primitives = canvas.GetListOfPrimitives()
  histo = None
  point = None
  for primitive in primitives:
    if primitive.InheritsFrom(TH2Poly.Class()):
      histo = primitive
    if primitive.InheritsFrom(TMarker.Class()):
      point = primitive
  histo.SetXTitle('x [cm]')
  histo.SetYTitle('y [cm]')
  canvas_new = Canvas(700, 700)
  histo.SetAxisRange(77,100,'X')
  histo.Draw('colz')
  point.Draw()
  canvas_new.SetLogz()
  canvas_new.Print('./plots/event_{}.png'.format(name))
コード例 #8
0
def GetCanvasWithHistAndPeakMarkers(Hist, Peaks, Name):
    "Take the histogram and peaks to make a nice plot"

    c = TCanvas(Name, Name)
    c.cd()
    Hist.Draw("hist")

    Markers = []
    for peak in Peaks:
        print 'peak found at ', peak, Peaks[peak]
        Markers.append(TMarker(peak, Peaks[peak], 26))
        Markers[-1].Draw('same')

    c.SetLogy(1)
    c.SaveAs(Name + '.pdf')

    return c
コード例 #9
0
ファイル: AtlasStyle.py プロジェクト: JacobRawling/ATLASStyle
def myMarkerTextSmall2(x, y, lcolor, lstyle, mcolor, mstyle, msize, size,
                       text):

    l = TLatex()
    l.SetTextAlign(12)
    l.SetTextSize(size / 2.5)
    l.SetNDC()
    l.DrawLatex(x, y, text)

    yb1 = y - 0.15 * size
    yb2 = y + 0.15 * size
    xb1 = x - 0.28 * size - 0.45 * size
    xb2 = x + 0.28 * size - 0.45 * size

    print "box  = ", xb1, yb1, xb2, yb2

    #print "line = ",xl1,yl1,xl2,yl2
    mline1 = TLine(xb1, yb1, xb2, yb2)
    mline1.SetLineColor(lcolor)
    mline1.SetLineStyle(lstyle)
    mline1.SetLineWidth(2)
    y_new = (yb1 + yb2) / 2.
    mline1.DrawLineNDC(xb1, y_new, xb2, y_new)

    mline2 = TLine(xb1, yb1, xb2, yb2)
    mline2.SetLineColor(lcolor)
    mline2.SetLineStyle(lstyle)
    mline2.SetLineWidth(2)
    x_new = (xb1 + xb2) / 2.
    mline2.DrawLineNDC(x_new, yb1, x_new, yb2)

    marker = TMarker((xb1 + xb2) / 2.0, y, mstyle)
    marker.SetNDC()
    marker.SetMarkerColor(mcolor)
    marker.SetMarkerStyle(mstyle)
    marker.SetMarkerSize(msize)
    marker.Draw()

    return marker
コード例 #10
0
def closureTest_plots(filename):
    f = BareRootFile(filename)
    tree = f.Get('closureTest')

    gStyle.SetStatX(0.9)
    gStyle.SetStatY(0.9)
    gStyle.SetStatW(0.2)
    gStyle.SetStatH(0.14)

    hist1 = TH1F('hist1', '', 55, 0.9, 2.0)
    hist2 = TH1F('hist2', '', 55, 0.9, 2.0)
    condition = ('fit_overlapDiff>=0 && temp_overlapDiff>=0 && '
                 'fit_chisq/fit_dof<=2 && temp_chisq/temp_dof<=2')
    tree.Draw('temp_chisq/temp_dof>>hist1', condition)
    tree.Draw('fit_chisq/fit_dof>>hist2', condition)
    for i, hist in [(0, hist1), (1, hist2)]:
        hist.SetLineColor(colors[i])
        hist.SetLineWidth(3)
    maxi = max(hist1.GetMaximum(), hist2.GetMaximum()) * 1.1
    plot = SingleHistBase(hist1,
                          'hist_numberPerChisq',
                          fill=None,
                          workinprogress=wip)
    gStyle.SetOptStat(10)
    plot._xtitle = '#chi^{2}/d.o.f.'
    plot._ytitle = 'number of toys'
    plot.yrange(0.0, maxi)
    leg = TLegend(0.65, 0.75, 0.89, 0.85)
    leg.SetBorderSize(0)
    leg.AddEntry(hist1, 'DG fit', 'L')
    leg.AddEntry(hist2, 'SupDG fit', 'L')
    plot.draw()
    hist2.Draw('SAMEH')
    leg.Draw()
    plot.save_pdf()
    plot.Close()

    hist3 = TH2F('hist3', '', 31, -0.05, 3.05, 31, -0.05, 3.05)
    tree.Draw('100*temp_overlapDiff:100*fit_overlapDiff>>hist3', condition)
    one = TF1('one', 'x', -10.0, 10.0)
    one.SetLineColor(1)
    plot = SingleHistBase(hist3,
                          'correctionDGvsSupDG',
                          fill=None,
                          workinprogress=wip)
    plot.add(one)
    plot._drawoption = 'BOX'
    plot._xtitle = 'correction [%] from SupDG fit'
    plot._ytitle = 'correction [%] from DG fit'
    plot._above = True
    plot.draw()
    plot.save_pdf()
    plot.Close()

    hist4 = TH2F('hist4', '', 22, 0.95, 1.5, 22, 0.95, 1.5)
    tree.Draw('temp_chisq/temp_dof:fit_chisq/fit_dof>>hist4', condition)
    plot = SingleHistBase(hist4,
                          'chisqDGvsSupDG',
                          fill=None,
                          workinprogress=wip)
    plot.add(one)
    plot._drawoption = 'BOX'
    plot._xtitle = '#chi^{2}/d.o.f. of SupDG fit'
    plot._ytitle = '#chi^{2}/d.o.f. of DG fit'
    plot._above = True
    plot.draw()
    plot.save_pdf()
    plot.Close()

    gStyle.SetStatX(0.9)
    gStyle.SetStatY(0.83)
    gStyle.SetStatW(0.3)
    gStyle.SetStatH(0.08)

    #bins_csq = [(0.0, 1.1), (1.1, 1.3), (1.3, 1.6), (1.6, 2.0)]
    #bins_cor = [(0.0, 0.5), (0.5, 1.0), (1.0, 1.5), (1.5, 2.0), (2.0, 2.5)]
    #bins_csq = [(1.07, 1.13), (1.06, 1.11), (1.3, 1.5), (1.08, 1.17), (1.1, 1.2)]
    #bins_cor = [(0.3, 0.8), (0.9, 1.2), (0.1, 0.5), (0.4, 0.7), (0.3, 1.1)]
    bins_csq = [(0.99, 1.06), (0.98, 1.07), (0.99, 1.10), (1.02, 1.06),
                (1.00, 1.06), (1.00, 1.04)]
    bins_cor = [(0.9, 1.9), (0.4, 1.6), (0.6, 1.5), (0.6, 1.9), (1.0, 1.3),
                (0.3, 1.5)]

    means = {
        mod: [[0.0 for __ in bins_cor] for __ in bins_csq]
        for mod in ('DG', 'SupDG')
    }
    meane = {
        mod: [[0.0 for __ in bins_cor] for __ in bins_csq]
        for mod in ('DG', 'SupDG')
    }
    rmses = {
        mod: [[0.0 for __ in bins_cor] for __ in bins_csq]
        for mod in ('DG', 'SupDG')
    }
    rmser = {
        mod: [[0.0 for __ in bins_cor] for __ in bins_csq]
        for mod in ('DG', 'SupDG')
    }

    #for i, (csq_lo, csq_hi) in enumerate(bins_csq):
    #    for j, (cor_lo, cor_hi) in enumerate(bins_cor):
    for i, ((csq_lo, csq_hi), (cor_lo,
                               cor_hi)) in enumerate(zip(bins_csq, bins_cor)):
        j = i
        name = 'hist_{{0}}_{0}csq{1}_{2}cor{3}' \
               .format(csq_lo, csq_hi, cor_lo, cor_hi)
        fields = '100*({0}_overlapDiff-toy_overlapDiff)>>hist'
        condition = (
            '100*{{0}}_overlapDiff>={0} && 100*{{0}}_overlapDiff<{1} && '
            '{{0}}_chisq/{{0}}_dof>={2} && {{0}}_chisq/{{0}}_dof<{3} && '
            'fit_overlapDiff>=0 && temp_overlapDiff>=0 && '
            'fit_chisq/fit_dof<=2 && temp_chisq/temp_dof<=2').format(
                cor_lo, cor_hi, csq_lo, csq_hi)
        xtitle = 'correction [%] from {0} fit #minus true correction [%]'
        line1 = '{0} < correction < {1}'.format(cor_lo, cor_hi)
        line2 = '{0} < #chi^{{2}}/d.o.f. < {1}'.format(csq_lo, csq_hi)
        gStyle.SetOptStat(2210)
        for prefix, modname in (('temp', 'DG'), ('fit', 'SupDG')):
            hist = TH1F('hist', '', 41, -2.05, 2.05)
            hist.StatOverflows()
            tree.Draw(fields.format(prefix), condition.format(prefix))
            plot = SingleHistBase(hist,
                                  name.format(modname),
                                  fill=None,
                                  workinprogress=wip)
            gStyle.SetOptStat(2210)
            plot._xtitle = xtitle.format(modname)
            plot._ytitle = 'number of toys'
            plot.xrange(-2.05, 2.05)
            plot.yrange(0.0, plot._graph.GetMaximum() * 1.2)
            pave = plot.add_pave(0.6, 0.83, 0.9, 0.9, border=True)
            pave(line1)
            pave(line2)
            plot.draw()
            plot.save_pdf()
            means[modname][i][j] = plot._graph.GetMean()
            meane[modname][i][j] = plot._graph.GetMeanError()
            rmses[modname][i][j] = plot._graph.GetRMS()
            rmser[modname][i][j] = plot._graph.GetRMSError()
            plot.Close()

    multi = TMultiGraph('multi', '')
    for k, modname in enumerate(('DG', 'SupDG')):
        for i, (csq_lo, csq_hi) in enumerate(bins_csq):
            xval = array(
                'd',
                [j - 0.35 + k * 0.4 + i * 0.1 for j in range(len(bins_cor))])
            xerr = array('d', [0.0] * len(bins_cor))
            yval = array('d', means[modname][i])
            yerr = array('d', rmses[modname][i])
            graph = TGraphErrors(len(bins_cor), xval, yval, xerr, yerr)
            graph.SetName('graph{0}{1}'.format(k, i))
            graph.SetMarkerStyle(22 + k)
            graph.SetMarkerColor(colors[i])
            graph.SetLineColor(colors[i])
            multi.Add(graph)
    minvalues = [
        means[mod][i][j] - rmses[mod][i][j] for j in range(len(bins_cor))
        for i in range(len(bins_csq)) for mod in ('DG', 'SupDG')
    ]
    maxvalues = [
        means[mod][i][j] + rmses[mod][i][j] for j in range(len(bins_cor))
        for i in range(len(bins_csq)) for mod in ('DG', 'SupDG')
    ]
    mini, maxi = min(minvalues), max(maxvalues)
    mini, maxi = mini - 0.1 * (maxi - mini), maxi + 0.3 * (maxi - mini)
    hist = TH2F('axishist', '', len(bins_cor), -0.5,
                len(bins_cor) - 0.5, 100, mini, maxi)
    for j, (cor_lo, cor_hi) in enumerate(bins_cor):
        hist.GetXaxis().SetBinLabel(j + 1,
                                    '{0}% #minus {1}%'.format(cor_lo, cor_hi))
    leg1 = TLegend(0.53, 0.78, 0.63, 0.86)
    leg1.SetBorderSize(0)
    dgmarker = TMarker(0.0, 0.0, 22)
    supdgmarker = TMarker(0.0, 0.0, 23)
    leg1.AddEntry(dgmarker, 'DG', 'P')
    leg1.AddEntry(supdgmarker, 'SupDG', 'P')
    leg2 = TLegend(0.65, 0.75, 0.89, 0.89)
    leg2.SetBorderSize(0)
    csqmarker = TMarker(0.0, 0.0, 1)
    for i, (csq_lo, csq_hi) in enumerate(bins_csq):
        title = '{0} < #chi^{{2}}/d.o.f. < {1}'.format(csq_lo, csq_hi)
        entry = leg2.AddEntry(csqmarker, title, 'L')
        entry.SetMarkerColor(colors[i])
        entry.SetLineColor(colors[i])
    zero = TF1('zero', '0.0', -1.0, 10.0)
    zero.SetLineColor(1)
    zero.SetLineStyle(2)
    plot = SingleHistBase(hist,
                          name='differenceDoubleDifferential',
                          fill=None,
                          workinprogress=wip)
    plot._xtitle = 'correction from fit'
    plot._ytitle = 'correction [%] from fit #minus true correction [%]'
    plot.xrange(-0.5, len(bins_cor) - 0.5)
    plot.yrange(mini, maxi)
    plot._drawoption = 'AXIS'
    plot.draw()
    plot.xaxis().SetNdivisions(len(bins_cor), False)
    plot.xaxis().SetLabelSize(0.03)
    zero.Draw('SAME')
    multi.Draw('P')
    leg1.Draw()
    leg2.Draw()
    plot.save_pdf()
    plot.Close()

    bcid = (41, 281, 872, 1783, 2063)
    DGcor1 = array('d', [0.809, 0.392, 0.846, 0.731, 0.497])
    DGerr1 = array('d', [0.548, 0.567, 0.984, 0.984, 1.018])
    DGcor2 = array('d', [1.145, 0.799, 1.58, 1.465, 1.281])
    DGerr2 = array('d', [0.432, 0.395, 0.656, 0.656, 0.649])
    DGxval = array('d', [j - 0.1 for j in range(5)])
    SupDGcor1 = array('d', [0.823, 0.761, 1.458, 0.986, 1.012])
    SupDGerr1 = array('d', [0.513, 0.513, 0.499, 0.513, 0.499])
    SupDGcor2 = array('d', [0.978, 0.916, 1.532, 1.141, 1.086])
    SupDGerr2 = array('d', [0.489, 0.489, 0.493, 0.489, 0.493])
    SupDGxval = array('d', [j + 0.1 for j in range(5)])
    xerr = array('d', [0.0] * 5)

    for fill, values in [
        (4266, {
            'DGcor': [1.021, 1.057, 0.968, 1.084, 1.114],
            'DGerr': [(e**2 + 0.74**2)**0.5
                      for e in (0.118, 0.124, 0.119, 0.117, 0.119)],
            'SupDGcor': [1.402, 1.411, 1.164, 1.549, 1.589],
            'SupDGerr': [(e**2 + 0.45**2)**0.5
                         for e in (0.106, 0.110, 0.108, 0.106, 0.115)],
            'bcids': [51, 771, 1631, 2211, 2674]
        }),
        (4954, {
            'DGcor': [0.799, 0.398, 0.845, 0.724, 0.502],
            'DGerr': [(e**2 + 0.79**2)**0.5
                      for e in (0.137, 0.124, 0.122, 0.130, 0.116)],
            'SupDGcor': [0.794, 0.694, 1.642, 0.983, 0.993],
            'SupDGerr': [(e**2 + 0.50**2)**0.5
                         for e in (0.126, 0.112, 0.186, 0.102, 0.144)],
            'bcids': [41, 281, 872, 1783, 2063]
        }),
        (4937, {
            'DGcor': [0.649, 0.494, 0.575, 0.527, 0.602],
            'DGerr':
            [(e**2 + 0.85**2)**0.5 for e in (0.127, 0.115, 0.120, 0.125)],
            'SupDGcor': [0.377, 0.611, 1.137, 0.453, 1.840],
            'SupDGerr': [(e**2 + 0.56**2)**0.5
                         for e in (0.100, 0.105, 0.288, 0.161, 0.207)],
            'bcids': [81, 875, 1610, 1690, 1730]
        }),
        (6016, {
            'DGcor': [0.146, 0.394, 0.377, 0.488, 0.184],
            'DGerr': [(e**2 + 1.15**2)**0.5
                      for e in (0.110, 0.114, 0.118, 0.123, 0.109)],
            'SupDGcor': [0.760, 0.953, 1.048, 0.847, 0.373],
            'SupDGerr': [(e**2 + 0.79**2)**0.5
                         for e in (0.219, 0.094, 0.189, 0.098, 0.169)],
            'bcids': [41, 281, 872, 1783, 2063]
        })
    ]:
        bcid = values['bcids']
        DGcor = array('d', values['DGcor'])
        DGerr = array('d', values['DGerr'])
        DGxvl = array('d', [j - 0.1 for j in range(len(bcid))])
        SupDGcor = array('d', values['SupDGcor'])
        SupDGerr = array('d', values['SupDGerr'])
        SupDGxvl = array('d', [j + 0.1 for j in range(len(bcid))])
        xerr = array('d', [0.0] * len(bcid))
        maxi = max(max([v + e for v, e in zip(DGcor, DGerr)]),
                   max([v + e for v, e in zip(SupDGcor, SupDGerr)]))
        mini = min(min([v - e for v, e in zip(DGcor, DGerr)]),
                   min([v - e for v, e in zip(SupDGcor, SupDGerr)]))
        maxi, mini = maxi + 0.2 * (maxi - mini), mini - 0.1 * (maxi - mini)

        graphDG = TGraphErrors(len(bcid), DGxvl, DGcor, xerr, DGerr)
        graphDG.SetName('graphDG')
        graphSupDG = TGraphErrors(len(bcid), SupDGxvl, SupDGcor, xerr,
                                  SupDGerr)
        graphSupDG.SetName('graphSupDG')
        multi = TMultiGraph('multi', '')
        for i, graph in [(0, graphDG), (1, graphSupDG)]:
            graph.SetMarkerStyle(22 + i)
            graph.SetMarkerColor(colors[i])
            graph.SetLineColor(colors[i])
            multi.Add(graph)
        leg = TLegend(0.15, 0.80, 0.5, 0.83)
        leg.SetNColumns(2)
        leg.SetBorderSize(0)
        leg.AddEntry(graphDG, 'DG fit', 'PL')
        leg.AddEntry(graphSupDG, 'SupDG fit', 'PL')
        axishist = TH2F('axishist', '', len(bcid), -0.5,
                        len(bcid) - 0.5, 100, mini, maxi)
        for i, bx in enumerate(bcid):
            axishist.GetXaxis().SetBinLabel(i + 1, '{0}'.format(bx))

        plot = SingleHistBase(axishist,
                              name='Fill{0}biased'.format(fill),
                              fill=fill,
                              workinprogress=wip)
        plot._xtitle = 'BCID'
        plot._ytitle = 'correction [%] from fit'
        plot.xrange(-0.5, len(bcid) - 0.5)
        plot.yrange(mini, maxi)
        plot._drawoption = 'AXIS'
        plot.draw()
        plot.xaxis().SetNdivisions(len(bcid), False)
        plot.xaxis().SetLabelSize(0.03)
        multi.Draw('P')
        leg.Draw()
        plot.save_pdf()
        plot.Close()

        print
        print 'Fill', fill
        for bx, cor, err in zip(bcid, SupDGcor, SupDGerr):
            print 'BCID {0}:\t{1:.2f} +- {2:.2f}'.format(bx, cor, err)
        print
コード例 #11
0
def plotFailedHoMatchesNoTrg():
	c = TCanvas("cFailedHoMatchesNoTrg","cFailedHoMatchesNoTrg",1200,1200)
	c.cd().SetRightMargin(0.25)
	c.cd().SetLeftMargin(0.08)
	
	#Graph for in events not in geometric acceptance
	grNotInGaNC = file.Get("hoMuonAnalyzer/graphs/NoTrgTdmiNotInGA")
	grNotInGa = PlotStyle.convertToHcalCoords(grNotInGaNC)
	grNotInGa.GetYaxis().SetTitle("i#phi / a.u.")
	grNotInGa.GetXaxis().SetTitle("i#eta / a.u.")
	grNotInGa.GetYaxis().SetTitleFont(62)
	grNotInGa.GetYaxis().SetLabelFont(62)
	grNotInGa.SetMarkerStyle(6)
	grNotInGa.SetMarkerColor(PlotStyle.colorRwthDarkBlue)
	grNotInGa.SetTitle("#eta #phi plot failed HO matches in no Single #mu Trg. events")
	grNotInGa.Draw("AP")
	
	#Graph of events with HO match below threshold
	grHoBelowThrNC = file.Get("hoMuonAnalyzer/graphs/NoTrgTdmiBelowThr")
	grHoBelowThr = PlotStyle.convertToHcalCoords(grHoBelowThrNC)
	grHoBelowThr.SetMarkerStyle(20)
	grHoBelowThr.SetMarkerSize(1.2)
	grHoBelowThr.SetMarkerColor( PlotStyle.colorRwthGruen )
	grHoBelowThr.Draw("samep")
	
	#Graph for events where HO matching failed
	grHoMatchFailNC = file.Get("hoMuonAnalyzer/graphs/NoTrgHoMatchFail")
	grHoMatchFail = PlotStyle.convertToHcalCoords(grHoMatchFailNC)
	grHoMatchFail.SetMarkerStyle(21)
	grHoMatchFail.SetMarkerSize(1)
	grHoMatchFail.SetMarkerColor( PlotStyle.colorRwthRot )
	grHoMatchFail.Draw("samep")
	
	#Draw chimneys
	chimney1Converted = PlotStyle.convertToHcalCoords(PlotStyle.chimney1)
	chimney2Converted = PlotStyle.convertToHcalCoords(PlotStyle.chimney2)
	chimney1Converted.SetLineColor(PlotStyle.colorRwthMagenta)
	chimney2Converted.SetLineColor(PlotStyle.colorRwthMagenta)
	chimney1Converted.Draw('same')
	chimney2Converted.Draw('same')
	
	#cms private label
	label = TPaveText(PlotStyle.getLabelCmsPrivateSimulation(x1ndc=0.5,x2ndc=0.75))
	label.Draw()
	
	#create extra marker for the legend
	marker = TMarker(1,1,2)
	marker.SetMarkerSize(3)
	marker.SetMarkerColor(PlotStyle.colorRwthDarkBlue)
	
	#legend
	legend = TLegend(0.75,0.8,0.99,0.9)
	legend.AddEntry(chimney2Converted,"chimney","l")
	legend.AddEntry(marker,'Not in GA','p')
	legend.AddEntry(grHoMatchFail,'HO match fail','p')
	legend.AddEntry(grHoBelowThr,'HO match < 0.2 GeV','p')
	legend.Draw()
	
	nNotMatching = grHoMatchFail.GetN()
	nNotInGa = grNotInGa.GetN()
	nBelowThr = grHoBelowThr.GetN()
	nTotal = nNotMatching + nNotInGa + nBelowThr
	
	print 80*'#'
	print 'Not Matching:\t%5d/%d\t=> %5.2f%% +- %f%%' % (nNotMatching,nTotal,nNotMatching/float(nTotal)*100,PlotStyle.calcSigma(nNotMatching,float(nTotal)))
	print 'Not in GA:\t%5d/%d\t=> %5.2f%% +- %f%%' % (nNotInGa,nTotal,nNotInGa/float(nTotal)*100,PlotStyle.calcSigma(nNotInGa,float(nTotal)))
	print 'Below Thr:\t%5d/%d\t=> %5.2f%% +- %f%%' % (nBelowThr,nTotal,nBelowThr/float(nTotal)*100,PlotStyle.calcSigma(nBelowThr,float(nTotal)))
	print 80*'#'
	
	c.Update()
	c.SaveAs('plots/graphsEtaPhi/gNoTrgHoMatchingFailed.png')
	c.SaveAs('plots/graphsEtaPhi/gNoTrgHoMatchingFailed.pdf')
	return c,grNotInGa,label,chimney1Converted,chimney2Converted,legend,grHoMatchFail,grHoBelowThr
コード例 #12
0
ROCwmass.SetMaximum(1.0)
ROCwmass.GetXaxis().SetRangeUser(0.0,1.0)
ROCwmass.SetLineColor(2)
ROCwmass.SetLineWidth(2)
ROCwmass.SetTitle(";signal efficiency;background rejection")
c2 = TCanvas("c2")



ptlimstrs = [str(int(2000.0*ptlims[0])),str(int(2000.0*ptlims[1]))]
ROCwmass.Draw()
prelim.DrawLatex( 0.15, 0.85, ptlimstrs[0]+" GeV < p_{T} < "+ptlimstrs[1]+" GeV" )
if (cust=="w" or cust=="top") and Drawmarker:
	if cust=="w":
		prelim.DrawLatex( 0.44, 0.55, "N_{2}^{DDT}+msd" )
		TM = TMarker(0.4, 0.01, 23)
	if cust=="top":
		prelim.DrawLatex( 0.44, 0.60, "#tau_{32}+msd+subjetb" )
		TM = TMarker(0.4, 0.017, 23)
	TM.SetMarkerSize(2)
	TM.SetMarkerColor(4)
	TM.Draw()
c2.SetLogy()
c2.Write("rocwmass")
ROC.Draw()

c2.Write("roccomp")

dnnsig.Write()
dnnbkg.Write()
output.Write()
コード例 #13
0
def analyze(datasets, inputDir='.'):
    gROOT.SetBatch()
    gStyle.SetOptStat(0)
    gStyle.SetOptTitle(0)

    canvas = TCanvas("c1", "c1", 800, 800)

    input_ele = TFile(inputDir + '/output_electrons.root', 'read')
    input_muon = TFile(inputDir + '/output_muons.root', 'read')
    input_fake = TFile(inputDir + '/output_fake.root', 'read')

    h_disc_ele = input_ele.Get('disc')
    h_disc_muon = input_muon.Get('disc')
    h_disc_fake = input_fake.Get('disc')

    h_sigma_ele = input_ele.Get('sigma')
    h_sigma_muon = input_muon.Get('sigma')
    h_sigma_fake = input_fake.Get('sigma')

    h_disc_signal = {}
    h_sigma_signal = {}
    for dataset in datasets:
        if not dataset.startswith('higgsino'): continue
        fin = TFile(inputDir + '/output_' + dataset + '.root', 'read')

        h_disc = fin.Get('disc')
        h_sigma = fin.Get('sigma')

        h_disc.SetDirectory(0)
        h_sigma.SetDirectory(0)

        h_disc_signal[dataset] = h_disc
        h_sigma_signal[dataset] = h_sigma

        fin.Close()

    roc_curves = { 'disc_%d_%s' % (i, sig) : getROC(h_disc_ele, h_disc_muon, h_disc_fake, h_disc_signal[sig], i) for i in [4, 5, 6] for sig in h_disc_signal }
    roc_curves.update(
        { 'sigma_%d_%s' % (i, sig) : getROC(h_sigma_ele, h_sigma_muon, h_sigma_fake, h_sigma_signal[sig], i) for i in [4, 5, 6] for sig in h_disc_signal }
    )

    fout = TFile('durp.root', 'recreate')
    for curve_name in roc_curves:
        roc_curves[curve_name][0].Write(curve_name)
        print 'Optimal cut for', curve_name, '=', roc_curves[curve_name][1]
        m = TMarker(roc_curves[curve_name][2], roc_curves[curve_name][3], 29)
        m.Write(curve_name + '_optimal')
    fout.Close()

    for i in [4, 5, 6]:
        plotStack(h_disc_ele, h_disc_muon, h_disc_fake, h_disc_signal['higgsino_300_1000'], i, 'discriminant', canvas, rebin=5)
        plotStack(h_sigma_ele, h_sigma_muon, h_sigma_fake, h_sigma_signal['higgsino_300_1000'], i, 'sigma', canvas, rebin=5)

    for dataset in h_disc_signal:
        for i in [4, 5, 6]:
            wp = getWP(h_disc_ele, h_sigma_ele, h_disc_muon, h_sigma_muon, h_disc_fake, h_sigma_fake, h_disc_signal[dataset], h_sigma_signal[dataset], i)
            print dataset, '--', wp

    iClone = -1

    print '\nComparing disc < 0.3 to fiducial map method:\n'
    printChanges('Electrons nLayers=4',  h_sigma_ele, h_disc_ele, 0.3, 4, iClone)
    printChanges('Electrons nLayers=5',  h_sigma_ele, h_disc_ele, 0.3, 5, iClone)
    printChanges('Electrons nLayers>=6', h_sigma_ele, h_disc_ele, 0.3, 6, iClone)

    printChanges('Muons nLayers=4',  h_sigma_muon, h_disc_muon, 0.3, 4, iClone)
    printChanges('Muons nLayers=5',  h_sigma_muon, h_disc_muon, 0.3, 5, iClone)
    printChanges('Muons nLayers>=6', h_sigma_muon, h_disc_muon, 0.3, 6, iClone)

    printChanges('Fakes nLayers=4',  h_sigma_fake, h_disc_fake, 0.3, 4, iClone)
    printChanges('Fakes nLayers=5',  h_sigma_fake, h_disc_fake, 0.3, 5, iClone)
    printChanges('Fakes nLayers>=6', h_sigma_fake, h_disc_fake, 0.3, 6, iClone)

    extra_samples = {
        10    : ['0p' + str(i) for i in range(2, 10)] + [str(i) for i in range(0, 10)],
        100   : [str(i*10) for i in range(2, 10)],
        1000  : [str(i*100) for i in range(2, 10)],
        10000 : [str(i*1000) for i in range(2, 10)],
    }

    for i in [4, 5, 6]:
        print 'NLAYERS: ', i
        for mass in range(100, 1000, 100):
            for lifetime in [10, 100, 1000, 10000]:
                datasetName = 'higgsino_%d_%d' % (mass, lifetime)
                change_string = printChanges('Higgsino_%dGeV_%dcm_94X' % (mass, lifetime), 
                                             h_sigma_signal[datasetName], 
                                             h_disc_signal[datasetName], 
                                             0.3, 
                                             i,
                                             iClone)
                for extra_lifetime in extra_samples[lifetime]:
                    print change_string.replace('Higgsino_%dGeV_%dcm_94X' % (mass, lifetime), 'Higgsino_%dGeV_%scm_94X' % (mass, extra_lifetime))
コード例 #14
0
for i in xrange(1, h_coupling.GetNbinsX() + 1):
    h_coupling.SetBinContent(i, 1. / h_coupling.GetXaxis().GetBinCenter(i)**2)

n_points = h_width.GetNbinsX()
g_width = TGraph(n_points)
g_partial_width = TGraph(n_points)

for i in xrange(n_points):
    g_width.SetPoint(i, h_coupling.GetBinContent(i + 1),
                     h_width.GetBinContent(i + 1))
    g_partial_width.SetPoint(
        i, h_coupling.GetBinContent(i + 1),
        h_width.GetBinContent(i + 1) * h_br.GetBinContent(i + 1))

# Points/lines for simulated samples
p_5percent = TMarker(1., 0.05 * mass, 1)
p_10percent = TMarker(1., 0.1 * mass, 2)
p_25percent = TMarker(1., 0.025 * mass, 3)


def findX(graph, y):
    '''Find x value, assume monotonously decreasing y'''
    xvals = graph.GetX()
    yvals = graph.GetY()
    for i in xrange(graph.GetN()):
        yval = yvals[i]
        xval = xvals[i]
        print xval, yval, y
        if yval < y:
            if i == 0:
                return xval
コード例 #15
0
def plot_rocs(plotObjects, kwargs):

    from ROOT import kCyan, kRed, kGreen, kBlue, kBlack, kMagenta, kGray, kWhite, kYellow
    Colors = [kBlue, kRed, kMagenta, kBlack, kCyan, kGreen]
    from RingerCore import StdPair as std_pair
    from util import line, minmax

    dset = kwargs['set']
    ref = kwargs['reference']
    refVal = kwargs['refVal']
    eps = kwargs['eps']
    savename = kwargs['cname'] + '.pdf'

    #Some protection
    if not ('operation' in dset or 'tst' in dset):
        raise ValueError('Option set must be: tst (test) or val (validation)')
    if not ('SP' in ref or 'Pd' in ref or 'Pf' in ref):
        raise ValueError('Option reference must be: SP, Pd or Pf')

    #Create dict to hold all list plots
    curves = dict()
    #list of dicts to dict of lists
    for name in plotObjects.keys():
        curves[name] = plotObjects.tolist(name)

    paintIdx = kwargs['paintListIdx']  # [best, worst]
    paintCurves = [
        std_pair(plotObjects.index_correction(paintIdx[0]), kBlack),
        std_pair(plotObjects.index_correction(paintIdx[1]), kRed)
    ]
    curves['roc'] = curves['roc_' + dset]

    #Start to build all ROOT objects
    from ROOT import TCanvas, gROOT, kTRUE
    gROOT.SetBatch(kTRUE)
    canvas = TCanvas('canvas', 'canvas', 1600, 1300)

    x_limits = [0.00, 0.40]
    y_limits = [0.6, 1.03]

    #create dummy graph
    dummy = curves['roc'][0]
    dummy.SetTitle('Receive Operation Curve')
    dummy.GetXaxis().SetTitle('False Alarm')
    dummy.GetYaxis().SetTitle('Detection')
    dummy.GetHistogram().SetAxisRange(y_limits[0], y_limits[1], 'Y')
    dummy.GetHistogram().SetAxisRange(x_limits[0], x_limits[1], 'X')
    dummy.Draw('AL')

    corredor = None
    target = None
    from ROOT import TBox
    if ref == 'Pf':
        corredor = TBox(refVal - eps, y_limits[0], refVal + eps, y_limits[1])
        target = line(refVal, y_limits[0], refVal, y_limits[1], kBlack, 2, 1,
                      '')
    elif ref == 'Pd':
        corredor = TBox(x_limits[0], refVal - eps, x_limits[1], refVal + eps)
        target = line(x_limits[0], refVal, x_limits[1], refVal, kBlack, 2, 1,
                      '')

    if ref != 'SP':
        corredor.SetFillColor(kYellow - 9)
        corredor.Draw('same')
        target.Draw('same')
        canvas.Modified()
        canvas.Update()

    #Plot curves
    for c in curves['roc']:
        c.SetLineColor(kGray + 1)
        #c.SetMarkerStyle(7)
        #c.SetMarkerColor(kBlue)
        c.SetLineWidth(1)
        c.SetLineStyle(3)
        #c.Draw('PLsame')
        c.Draw('same')

    marker = list()
    #Paint a specifical curve
    for pair in paintCurves:
        curves['roc'][pair.first].SetLineWidth(1)
        curves['roc'][pair.first].SetLineStyle(1)
        #curves['roc'][pair.first].SetMarkerStyle(7)
        #curves['roc'][pair.first].SetMarkerColor(kBlue)
        curves['roc'][pair.first].SetLineColor(pair.second)
        #curves['roc'][pair.first].Draw('PLsame')
        curves['roc'][pair.first].Draw('same')

        if ref == 'SP':
            faVec = curves['roc'][pair.first].GetX()
            detVec = curves['roc'][pair.first].GetY()
            from RingerCore import calcSP
            spVec = [
                calcSP(detVec[i], 1 - faVec[i])
                for i in range(curves['roc'][pair.first].GetN())
            ]
            imax = spVec.index(max(spVec))
            from ROOT import TMarker
            marker.append(TMarker(faVec[imax], detVec[imax], 4))
            marker[-1].SetMarkerColor(pair.second)
            marker[-1].Draw('same')

    #Update Canvas
    canvas.Modified()
    canvas.Update()
    canvas.SaveAs(savename)
    del canvas

    return savename
コード例 #16
0
                nIterations) + ") trying hit inefficiency of " + str(i) + "..."
            chi2, N = getChi2(i)
            if N == 0:
                continue
            chi2 /= N
            if chi2 < minChi2 or minChi2 < 0.0:
                minChi2 = chi2
                minChi2HitAndTOBDrop = i
                minChi2Index = copy.deepcopy(index)
            g.SetPoint(n, i, chi2)
            n += 1
        print "(" + str(iteration + 1) + " / " + str(
            nIterations) + ") minimum chi2: " + str(minChi2) + " at " + str(
                minChi2HitAndTOBDrop)

        m = TMarker(minChi2HitAndTOBDrop, minChi2, 29)
        m.SetMarkerSize(3)

        hitDropGridLower = hitDropGrid[
            minChi2Index - 1] if minChi2Index > 0 else hitDropGrid[
                minChi2Index] - hitDropGrid[minChi2Index + 1]
        hitDropGridUpper = hitDropGrid[minChi2Index + 1] if minChi2Index < len(
            hitDropGrid) - 1 else hitDropGrid[minChi2Index] + hitDropGrid[
                minChi2Index - 1]
        hitDropGrid = numpy.linspace(max(hitDropGridLower, 0.0),
                                     hitDropGridUpper, 5)

        foutMode = "update" if iteration > 0 else "recreate"
        fout = TFile.Open("hipChi2.root", foutMode)
        fout.cd()
        g.Write("chi2VsHitDropProbability_" + str(iteration))
コード例 #17
0
ファイル: geotools.py プロジェクト: dcarogancia/heppy_fcc
        xp = -xp
    xm = math.sqrt(r2**2 - ym**2)
    if abs((xm - x1)**2 + (ym - y1)**2 - r1**2) > 1e-9:
        xm = -xm
    if switchxy:
        xm, ym = ym, xm
        xp, yp = yp, xp
    return xm, ym, xp, yp


if __name__ == '__main__':

    from ROOT import TEllipse, TH2F, TCanvas, TMarker

    can = TCanvas("can", "", 600, 600)
    suph = TH2F("suph", "", 10, -5, 5, 10, -5, 5)
    suph.Draw()
    x1, y1, r1, r2 = 0., 1.8, 1., 2.
    results = circle_intersection(x1, y1, r1, r2)
    c1 = TEllipse(x1, y1, r1)
    c1.Draw('same')
    c2 = TEllipse(0., 0., r2)
    c2.Draw('same')
    c1.SetFillStyle(0)
    c2.SetFillStyle(0)
    mm = TMarker(results[0], results[1], 8)
    mp = TMarker(results[2], results[3], 21)
    mm.Draw('same')
    mp.Draw('same')
    can.Update()
コード例 #18
0
def MuFit(Nbins,irebin=1.):
	# Get histrograms
	h_bgr = GetMassDistribution(1)
	h_data = GetMassDistribution(2)
	h_sig = GetMassDistribution(125)

	h_bgr.Rebin(irebin)
	h_data.Rebin(irebin)
	h_sig.Rebin(irebin)

	h_sf = TH2D("scalefactor","title",Nbins,0.5,2.,Nbins,0.,5.)

	for i in range(1,h_sf.GetNbinsX()+1):
		for j in range(1,h_sf.GetNbinsY()+1):

			sf_bgr = h_sf.GetXaxis().GetBinCenter(i)
			sf_sig = h_sf.GetYaxis().GetBinCenter(j)

			# Loop over bins, compute likelihood
			loglik = 0.

			for iDataBin in range(1,h_data.GetNbinsX()+1):

				m4lepBin = h_data.GetBinCenter(iDataBin)
				NObsBin = h_data.GetBinContent(iDataBin)

				MeanBin = sf_bgr*h_bgr.GetBinContent(iDataBin) + sf_sig*h_sig.GetBinContent(iDataBin)

				if (MeanBin>0): loglik += TMath.Log( TMath.Poisson(NObsBin,MeanBin) )

			h_sf.SetBinContent(i,j,-2.*loglik)

	# Get best SF parameters

	x=ctypes.c_int(0)
	y=ctypes.c_int(0)
	z=ctypes.c_int(0)
	h_sf.GetBinXYZ(h_sf.GetMinimumBin(),x,y,z)
	Minimum = h_sf.GetBinContent(x.value,y.value)
	best_alpha = h_sf.GetXaxis().GetBinCenter(x.value)
	best_mu = h_sf.GetYaxis().GetBinCenter(y.value)
	print(Minimum,best_alpha,best_mu)
	

	# Rescale histogram
	for i in range(1,h_sf.GetNbinsX()+1):
		for j in range(1,h_sf.GetNbinsY()+1):
			h_sf.SetBinContent( i,j, h_sf.GetBinContent(i,j)-Minimum )


	canvas = TCanvas("canvas","Standard Canvas",600,400)
	canvas.cd()
	Min = TMarker(best_alpha,best_mu,29)
	Min.SetMarkerSize(2)
	h_sf.SetStats(kFALSE)
	h_sf.SetTitle("HIGGS PRODUCTION CROSS SECTION - PARAMETERS")
	h_sf.GetXaxis().SetTitle(r"#alpha")
	h_sf.GetYaxis().SetTitle(r"#mu")
	h_sf.Draw("COLZ")

	h_sigma = h_sf.Clone("h_sigma")
	h_sigma.Reset()
	for i in range(1,h_sigma.GetNbinsX()+1):
		for j in range(1,h_sigma.GetNbinsY()+1):
			if( h_sf.GetBinContent(i,j)<=1.): h_sigma.SetBinContent(i,j, 1.)
	h_sigma.SetMarkerColorAlpha(kRed,0.40)

	h_sigma.SetMarkerSize(10)
	h_sigma.Draw("same L")
	Min.Draw()
	leg1 = TLegend(0.65,0.85,0.85,0.75)
	leg1.SetBorderSize(1); leg1.SetFillColor(0);
	leg1a = leg1.AddEntry(Min, r"optimal (#alpha,#mu)", "p"); leg1a.SetTextSize(0.04);
	leg1.Draw()
	canvas.Print("Plots/MuFit.pdf")