Beispiel #1
0
def showRMSPOH_DAC(sector, poh, gain, wait=True, filename=None):
    gStyle.SetOptStat(0)
    gStyle.SetCanvasColor(0)
    gStyle.SetTitleFillColor(0)

    sector.poh[poh].biasGraphs = []
    sector.poh[poh].rmsGraphs = []
    sector.poh[poh].slopeGraphs = []

    sector.ResetAllandInitAll()

    data = sector.poh[poh].ScanDACoffset()

    if filename is None:
        filename = getFilename("poh%s_%d.ps" % (sector.name, poh))

    c1 = TCanvas('c1', time.strftime("%Y-%m-%d-%m %H:%M"), 200, 10, 800, 800)
    sector.poh[poh].pl = TPaveLabel(0.8, 0.9, 0.95, 0.95,
                                    time.strftime("%Y-%m-%d-%m %H:%M"))
    sector.poh[poh].pl.Draw()
    c1.Divide(2, 3)
    for ch in range(1, 5):
        c1.cd(ch)
        title = "POHBias_POH" + str(poh) + ":" + str(
            ch) + " " + sector.name + " fed channel " + str(
                sector.poh[poh].fedchannels[ch]) + "gain =" + str(gain)
        f = TH2D('h' + title, title, 2, 0, 255, 2, 0, 1024)
        hList.append(f)
        f.GetXaxis().SetTitle("DAC")
        #f.GetYaxis().SetTitle("FED ADC")
        f.Draw()
        color = 1
        biasGraph = graph([(t[0], t[1]) for t in data[ch]],
                          color=1,
                          name="bias_" + str(poh) + ":" + str(ch))
        rmsGraph = graph([(t[0], t[2] * 10.) for t in data[ch]],
                         color=2,
                         name="rms_" + str(poh) + ":" + str(ch))
        slopeGraph = graph([(t[0], t[3] * 10.) for t in data[ch]],
                           color=3,
                           name="slope_" + str(poh) + ":" + str(ch))
        sector.poh[poh].biasGraphs.append(biasGraph)
        sector.poh[poh].rmsGraphs.append(rmsGraph)
        sector.poh[poh].slopeGraphs.append(slopeGraph)
        biasGraph.Write()
        rmsGraph.Write()
        slopeGraph.Write()

        c1.Update()

    c1.Print(filename)
    gCanvases.append(c1)

    if wait:
        raw_input("hit return to continue")
Beispiel #2
0
def showRMSAOHTestCCU(sector, aoh, wait=True, filename=None):
    gStyle.SetOptStat(0)
    gStyle.SetCanvasColor(0)
    gStyle.SetTitleFillColor(0)

    sector.aoh[aoh].biasGraphs = []
    sector.aoh[aoh].rmsGraphs = []
    sector.aoh[aoh].slopeGraphs = []
    data = sector.aoh[aoh].getBiasRMSCurvesTestCCU()

    if filename is None:
        filename = getFilename("aoh%s_%d.ps" % (sector.name, aoh))

    c1 = TCanvas('c1', time.strftime("%Y-%m-%d-%m %H:%M"), 200, 10, 800, 800)
    sector.aoh[aoh].pl = TPaveLabel(0.8, 0.9, 0.95, 0.95,
                                    time.strftime("%Y-%m-%d-%m %H:%M"))
    sector.aoh[aoh].pl.Draw()
    c1.Divide(2, 3)
    for ch in range(1, 7):
        c1.cd(ch)
        title = "AOHBias_AOH" + str(aoh) + ":" + str(
            ch) + " " + sector.name + " fed channel " + str(
                sector.aoh[aoh].fedchannels[ch])
        f = TH2D('h' + title, title, 2, 10, 40, 2, 0, 1024)
        hList.append(f)
        f.GetXaxis().SetTitle("aoh bias")
        #f.GetYaxis().SetTitle("FED ADC")
        f.Draw()
        color = 1
        biasGraph = graph([(t[0], t[1]) for t in data[ch]],
                          color=1,
                          name="bias_" + str(aoh) + ":" + str(ch))
        rmsGraph = graph([(t[0], t[2] * 100.) for t in data[ch]],
                         color=2,
                         name="rms_" + str(aoh) + ":" + str(ch))
        slopeGraph = graph([(t[0], t[3] * 10.) for t in data[ch]],
                           color=3,
                           name="slope_" + str(aoh) + ":" + str(ch))
        sector.aoh[aoh].biasGraphs.append(biasGraph)
        sector.aoh[aoh].rmsGraphs.append(rmsGraph)
        sector.aoh[aoh].slopeGraphs.append(slopeGraph)
        biasGraph.Write()
        rmsGraph.Write()
        slopeGraph.Write()

        c1.Update()

    c1.Print(filename)
    gCanvases.append(c1)

    if wait:
        raw_input("hit return to continue")
Beispiel #3
0
def createPaveLabel(x1, y1, x2, y2, text,
                    fillColor=1, textColor=0,
                    textSize=None):

    label = TPaveLabel(0.80, 0.80, 0.97, 0.88,
                           'Peak Fit')
    label.SetFillColor(fillColor)
    label.SetTextColor(textColor)
    label.SetTextFont(52)
    if (textSize != None):
        label.SetTextSize(textSize)

    label.Draw()
    return label
counter = 0
for Histogram in Histograms:
    if Histogram.InheritsFrom("TGraph") and counter == 0:
        plotting_options = "AP"
    Histogram.Draw(plotting_options)
    #    Histogram.GetXaxis().SetTitle(xAxisLabel)
    Histogram.GetYaxis().SetTitle("cut efficiency")
    if counter is 0:
        if Histogram.InheritsFrom("TGraph"):
            plotting_options = "P"
    counter = counter + 1

Legend.Draw()
if arguments.normalizeToUnitArea:
    NormLabel = TPaveLabel(0.1, 0.75, 0.35, 0.85, "Scaled to unit area", "NDC")
    NormLabel.SetBorderSize(0)
    NormLabel.SetFillColor(0)
    NormLabel.SetFillStyle(0)
    NormLabel.Draw()

outputFile.cd()
Canvas.Write()

if arguments.plot_savePdf:
    pdfFileName = outputFileName.replace(".root", ".pdf")
    Canvas.SaveAs(pdfFileName)
    print "Saved file:  " + pdfFileName

outputFile.Close()
print "Saved plot in file: " + outputFileName
Beispiel #5
0
#
# This macro displays the physical ROOT file structure
#

from ROOT import TCanvas, TPaveLabel, TPave, TLine, TArrow, TText, TPaveText
from ROOT import gROOT


gROOT.Reset()

c1 = TCanvas( 'c1', 'ROOT File description', 200, 10, 700, 550 )

c1.Range( 0, -0.25, 21, 14 )
title = TPaveLabel( 5, 12, 15, 13.7, c1.GetTitle() )
title.SetFillColor( 16 )
title.Draw()

# horizonthal file layout
file = TPave( 1, 8.5, 20, 11 )
file.SetFillColor( 11 )
file.Draw()
fileh = TPave( 1, 8.5, 2.5, 11 )
fileh.SetFillColor( 44 )
fileh.Draw()
lrh = TPave( 2.5, 8.5, 3.3, 11, 1 )
lrh.SetFillColor( 33 )
lrh.Draw()
lrh.DrawPave( 6.9, 8.5, 7.7, 11, 1 )
lrh.DrawPave( 10.5, 8.5, 11.3, 11, 1 )
lrh.DrawPave( 14.5, 8.5, 15.3, 11, 1 )
ldot = TLine( 1, 8.5, 0.5, 6.5 )
Beispiel #6
0
def plot(MillePedeUser, alignables, config):
    logger = logging.getLogger("mpsvalidate")

    # more space for labels
    gStyle.SetPadBottomMargin(0.25)
    gStyle.SetOptStat("emrs")

    for mode in ["xyz", "rot"]:
        big = PlotData(mode)

        # count number of needed bins and max shift
        for line in MillePedeUser:
            if (line.ObjId != 1):
                for i in range(3):
                    if (abs(line.Par[big.data[i]]) != 999999):
                        if (mode == "xyz"):
                            line.Par[big.data[i]] *= 10000
                        big.numberOfBins[i] += 1
                        if (abs(line.Par[big.data[i]]) > abs(big.maxShift[i])):
                            big.maxShift[i] = line.Par[big.data[i]]

        # initialize histograms
        for i in range(3):
            big.histo.append(
                TH1F("Big Structure {0} {1}".format(big.xyz[i], mode), "",
                     big.numberOfBins[i], 0, big.numberOfBins[i]))
            if (big.unit != ""):
                big.histo[i].SetYTitle("#Delta" + big.xyz[i] + " [" +
                                       big.unit + "]")
            else:
                big.histo[i].SetYTitle("#Delta" + big.xyz[i])
            big.histo[i].SetStats(0)
            big.histo[i].SetMarkerStyle(21)
            big.histoAxis.append(big.histo[i].GetXaxis())
            # bigger labels for the text
            big.histoAxis[i].SetLabelSize(0.06)
            big.histo[i].GetYaxis().SetTitleOffset(1.6)

        # add labels
        big.title = TPaveLabel(0.1, 0.8, 0.9, 0.9,
                               "High Level Structures {0}".format(mode))
        big.text = TPaveText(0.05, 0.1, 0.95, 0.75)
        big.text.SetTextAlign(12)

        # error if shift is bigger than limit
        limit = config.limit[mode]
        for i in range(3):
            if (big.unit != ""):
                big.text.AddText("max. shift {0}: {1:.2} {2}".format(
                    big.xyz[i], float(big.maxShift[i]), big.unit))
                if (abs(big.maxShift[i]) > limit):
                    big.text.AddText("! {0} shift bigger than {1} {2}".format(
                        big.xyz[i], limit, big.unit))
            else:
                big.text.AddText("max. shift {0}: {1:.2}".format(
                    big.xyz[i], float(big.maxShift[i])))
                if (abs(big.maxShift[i]) > limit):
                    big.text.AddText("! {0} shift bigger than {1}".format(
                        big.xyz[i], limit))

        # fill histograms with value and name
        for line in MillePedeUser:
            if (line.ObjId != 1):
                for i in range(3):
                    if (abs(line.Par[big.data[i]]) != 999999):
                        # set name of the structure
                        big.histoAxis[i].SetBinLabel(
                            big.binPosition[i],
                            alignables.get_name_by_objid(line.ObjId))
                        # fill with data, big.data[i] xyz or rot data
                        # transform xyz data from cm to #mu m
                        if (mode == "xyz"):
                            big.histo[i].SetBinContent(
                                big.binPosition[i],
                                10000 * line.Par[big.data[i]])
                        else:
                            big.histo[i].SetBinContent(big.binPosition[i],
                                                       line.Par[big.data[i]])
                        big.binPosition[i] += 1

        # rotate labels
        for i in range(3):
            big.histoAxis[i].LabelsOption("v")

        # reset y range
        # two types of ranges

        # 1. show all
        if (config.rangemodeHL == "all"):
            for i in range(3):
                big.usedRange[i] = big.maxShift[i]

        # 2. use given values
        if (config.rangemodeHL == "given"):
            # loop over coordinates
            for i in range(3):
                if (mode == "xyz"):
                    valuelist = config.rangexyzHL
                if (mode == "rot"):
                    valuelist = config.rangerotHL
                # loop over given values
                # without last value
                for value in valuelist:
                    # maximum smaller than given value
                    if (abs(big.maxShift[i]) < value):
                        big.usedRange[i] = value
                        break
                    # if not possible, force highest
                if (abs(big.maxShift[i]) > valuelist[-1]):
                    big.usedRange[i] = valuelist[-1]

        # all the same range
        if (config.samerangeHL == 1):
            # apply new range
            for i in range(3):
                big.usedRange[i] = max(map(abs, big.usedRange))

        # count outlieres
        if (config.rangemodeHL == "given"):
            for i in range(3):
                for binNumber in range(1, big.numberOfBins[i] + 1):
                    if (abs(big.histo[i].GetBinContent(binNumber)) >
                            big.usedRange[i]):
                        big.hiddenEntries[i] += 1

            # add number of outlieres to text
            for i in range(3):
                if (big.hiddenEntries[i] != 0):
                    big.text.AddText("! {0}: {1} outlier !".format(
                        big.xyz[i], int(big.hiddenEntries[i])))

        # create canvas
        cBig = TCanvas("canvasBigStrucutres_{0}".format(mode), "Parameter",
                       300, 0, 800, 600)
        cBig.Divide(2, 2)

        # draw histograms
        cBig.cd(1)
        big.title.Draw()
        big.text.Draw()

        # draw identification
        ident = identification(config)
        ident.Draw()

        # TGraph copy to hide outlier
        copy = 3 * [None]

        # loop over coordinates
        for i in range(3):
            cBig.cd(i + 2)
            # option "AXIS" to only draw the axis
            big.histo[i].SetLineColor(0)
            big.histo[i].Draw("AXIS")
            # set new range
            big.histo[i].GetYaxis().SetRangeUser(-1.1 * abs(big.usedRange[i]),
                                                 1.1 * abs(big.usedRange[i]))

            # TGraph object to hide outlier
            copy[i] = TGraph(big.histo[i])
            # set the new range
            copy[i].SetMaximum(1.1 * abs(big.usedRange[i]))
            copy[i].SetMinimum(-1.1 * abs(big.usedRange[i]))
            # draw the data
            copy[i].Draw("PSAME")

        cBig.Update()

        # save as pdf
        cBig.Print("{0}/plots/pdf/structures_{1}.pdf".format(
            config.outputPath, mode))

        # export as png
        image = TImage.Create()
        image.FromPad(cBig)
        image.WriteImage("{0}/plots/png/structures_{1}.png".format(
            config.outputPath, mode))

        # add to output list
        output = OutputData(plottype="big",
                            parameter=mode,
                            filename="structures_{0}".format(mode))
        config.outputList.append(output)

    # reset BottomMargin
    gStyle.SetPadBottomMargin(0.1)
print "Fitted parameters:  ctau = -1./[1] = " + str(
    ctau) + "; ctau error =  + " + str(ctauErrHi) + " - " + str(ctauErrLo)

histName = arguments.histName
histName = histName[histName.rfind('/') +
                    1:]  # strip off anything before the last '/'
outfileRoot = arguments.infile.replace(".root", "_" + histName + "Fit.root")
outputFile = TFile(outfileRoot, "RECREATE")

FitText = "Fitted <c#tau> = " \
+ str.format('{0:.1f}', ctau) + "^{+" \
+ str.format('{0:.1f}', ctauErrHi) + "}_{" \
+ str.format('{0:.1f}', ctauErrLo) + "}"
#, #chi^{2}/NDF = " \
#+ str.format('{0:.1f}', myfunc.GetChisquare()) + "/" + str(myfunc.GetNDF())
FitLabel = TPaveLabel(0.2, 0.8, 0.6, 0.9, FitText, "NDC")
FitLabel.SetBorderSize(0)
FitLabel.SetFillColor(0)
FitLabel.SetFillStyle(0)
FitLabel.Draw()

hist.Write()
can.Write()

outputFile.Close()
outfilePdf = outfileRoot.replace(".root", ".pdf")
can.SaveAs(outfilePdf)
print "Saved plot in " + outfilePdf + " and " + outfileRoot

print "Finished doExpoFit.py"
Beispiel #8
0
pad1 = TPad('pad1', 'The pad with the function', 0.03, 0.62, 0.50, 0.92, 21)
pad2 = TPad('pad2', 'The pad with the histogram', 0.51, 0.62, 0.98, 0.92, 21)
pad3 = TPad('pad3', 'The pad with the histogram', 0.03, 0.02, 0.97, 0.57, 21)
pad1.Draw()
pad2.Draw()
pad3.Draw()
#
# We connect the ROOT file generated in a previous tutorial
# see begin_html <a href="hsimple.C.html">An example creating/filling/saving histograms/ntuples on file</a> end_html
#
example = TFile('py-hsimple.root')
example.ls()

# Draw a global picture title
title = TPaveLabel(0.1, 0.94, 0.9, 0.98,
                   'Drawing options for one dimensional histograms')
title.SetFillColor(16)
title.SetTextFont(52)
title.Draw()
#
# Draw histogram hpx in first pad with the default option.
pad1.cd()
pad1.GetFrame().SetFillColor(18)
hpx = gROOT.FindObject('hpx')
hpx.SetFillColor(45)
hpx.DrawCopy()
label1 = TPaveLabel(-3.5, 700, -1, 800, 'Default option')
label1.SetFillColor(42)
label1.Draw()
#
# Draw hpx as a lego. Clicking on the lego area will show
Beispiel #9
0
from ROOT import TCanvas, TF1, TPaveLabel, TPad, TText
from ROOT import gROOT

nut = TCanvas('nut', 'FirstSession', 100, 10, 700, 900)
nut.Range(0, 0, 20, 24)
nut.SetFillColor(10)
nut.SetBorderSize(2)

pl = TPaveLabel(3, 22, 17, 23.7, 'My first PyROOT interactive session', 'br')
pl.SetFillColor(18)
pl.Draw()

t = TText(0, 0, 'a')
t.SetTextFont(62)
t.SetTextSize(0.025)
t.SetTextAlign(12)
t.DrawText(
    2, 20.3,
    'PyROOT provides ROOT bindings for Python, a powerful interpreter.')
t.DrawText(2, 19.3, 'Blocks of lines can be entered typographically.')
t.DrawText(2, 18.3, 'Previous typed lines can be recalled.')

t.SetTextFont(72)
t.SetTextSize(0.026)
t.DrawText(3, 17, r'>>>  x, y = 5, 7')
t.DrawText(3, 16, r'>>>  import math; x*math.sqrt(y)')
t.DrawText(
    3, 14,
    r'>>>  for i in range(2,7): print "sqrt(%d) = %f" % (i,math.sqrt(i))')
t.DrawText(3, 10,
           r'>>>  import ROOT; f1 = ROOT.TF1( "f1", "sin(x)/x", 0, 10 )')
Beispiel #10
0
    jbessel = TF1("J_0", "ROOT::Math::cyl_bessel_j([0],x)", 0, 10)
    jbessel.SetParameters(nu, 0.0)
    jbessel.SetTitle("")
    jbessel.SetLineStyle(1)
    jbessel.SetLineWidth(3)
    jbessel.SetLineColor(nu + 1)
    JBessel.append(jbessel)

# Setting x axis for JBessel
xaxis = JBessel[0].GetXaxis()
xaxis.SetTitle("x")
xaxis.SetTitleSize(0.06)
xaxis.SetTitleOffset(.7)

# setting the title in a label style
p1 = TPaveLabel(.0, .90, .0 + .50, .90 + .10, "Bessel J functions", "NDC")
p1.SetFillColor(0)
p1.SetTextFont(22)
p1.SetTextColor(kBlack)

# setting the legend
leg.AddEntry(JBessel[0].DrawCopy(), " J_0(x)", "l")
leg.AddEntry(JBessel[1].DrawCopy("same"), " J_1(x)", "l")
leg.AddEntry(JBessel[2].DrawCopy("same"), " J_2(x)", "l")
leg.AddEntry(JBessel[3].DrawCopy("same"), " J_3(x)", "l")
leg.AddEntry(JBessel[4].DrawCopy("same"), " J_4(x)", "l")

leg.Draw()
p1.Draw()

# Set canvas 2
Beispiel #11
0
def showRMSPOH(sector, poh, gain, wait=True, filename=None):

    gStyle.SetOptStat(0)
    gStyle.SetCanvasColor(0)
    gStyle.SetTitleFillColor(0)
    sector.poh[poh].biasGraphs = []
    sector.poh[poh].rmsGraphs = []
    sector.poh[poh].slopeGraphs = []

    # for poh in range(1,15):
    #    print sector.poh[poh].group

    if sector.poh[poh].group.find('L12') != -1:
        sector.ccu.send("channel 0x11").readlines()
    elif sector.poh[poh].group.find('L34') != -1:
        sector.ccu.send("channel 0x13").readlines()

    #cmd=sector.poh[poh].name+" setall %i %i %i %i %i %i %i %i"%(gain,gain,gain,gain,0,0,0,0)
    #sector.ccu.send(cmd).readlines()
    sector.ResetAllandInitAll()
    for ch in range(1, 5):
        sector.poh[poh].writegain(ch, gain)
    #for ch in range(1,5):
    #   print ch
    #   sector.poh[poh].writegain(ch,gain)

    data = sector.poh[poh].getBiasRMSCurves()

    if filename is None:
        filename = getFilename("poh%s_%d.ps" % (sector.name, poh))

    c1 = TCanvas('c1', time.strftime("%Y-%m-%d-%m %H:%M"), 200, 10, 800, 800)
    sector.poh[poh].pl = TPaveLabel(0.8, 0.9, 0.95, 0.95,
                                    time.strftime("%Y-%m-%d-%m %H:%M"))
    sector.poh[poh].pl.Draw()
    c1.Divide(2, 3)
    for ch in range(1, 5):
        c1.cd(ch)
        title = "POHBias_POH" + str(poh) + ":" + str(
            ch) + " " + sector.name + " fed channel " + str(
                sector.poh[poh].fedchannels[ch])
        f = TH2D('h' + title, title, 2, 0, 40, 2, 0, 1024)
        hList.append(f)
        f.GetXaxis().SetTitle("poh bias")
        #f.GetYaxis().SetTitle("FED ADC")
        f.Draw()
        color = 1
        biasGraph = graph([(t[0], t[1]) for t in data[ch]],
                          style=20,
                          color=1,
                          name="bias_" + str(poh) + ":" + str(ch))
        rmsGraph = graph([(t[0], t[2] * 10.) for t in data[ch]],
                         style=21,
                         color=31,
                         name="rms_" + str(poh) + ":" + str(ch))
        slopeGraph = graph([(t[0], t[3] * 10.) for t in data[ch]],
                           style=24,
                           color=2,
                           name="slope_" + str(poh) + ":" + str(ch))
        sector.poh[poh].biasGraphs.append(biasGraph)
        sector.poh[poh].rmsGraphs.append(rmsGraph)
        sector.poh[poh].slopeGraphs.append(slopeGraph)
        biasGraph.Write()
        print title
        biasGraph.Print()
        rmsGraph.Write()
        slopeGraph.Write()
        legend = TLegend(.64, .62, .85, .85)
        legend.AddEntry(biasGraph, "Bias", "p")

        legend.AddEntry(slopeGraph, "Slope*10,microW/mA", "p")
        legend.AddEntry(rmsGraph, "Noise", "p")
        legend.Draw()

        c1.Update()
    #################################################


#################################################

    c1.Print(filename)
    gCanvases.append(c1)

    if wait:
        raw_input("hit return to continue")
def MakeOneHist(histogramName):

    HeaderLabel = TPaveLabel(header_x_left, header_y_bottom, header_x_right,
                             header_y_top, HeaderText, "NDC")
    HeaderLabel.SetTextAlign(32)
    HeaderLabel.SetBorderSize(0)
    HeaderLabel.SetFillColor(0)
    HeaderLabel.SetFillStyle(0)

    LumiLabel = TPaveLabel(topLeft_x_left, topLeft_y_bottom, topLeft_x_right,
                           topLeft_y_top, LumiText, "NDC")
    LumiLabel.SetBorderSize(0)
    LumiLabel.SetFillColor(0)
    LumiLabel.SetFillStyle(0)

    NormLabel = TPaveLabel()
    NormLabel.SetDrawOption("NDC")
    NormLabel.SetX1NDC(topLeft_x_left)
    NormLabel.SetX2NDC(topLeft_x_right)

    NormLabel.SetBorderSize(0)
    NormLabel.SetFillColor(0)
    NormLabel.SetFillStyle(0)

    NormText = ""
    if arguments.normalizeToUnitArea:
        NormText = "Scaled to unit area"

    Legend = TLegend()
    Legend.SetBorderSize(0)
    Legend.SetFillColor(0)
    Legend.SetFillStyle(0)

    Canvas = TCanvas(histogramName)
    Histograms = []
    LegendEntries = []

    colorIndex = 0

    for source in input_sources:  # loop over different input sources in config file
        dataset_file = "condor/%s/%s.root" % (source['condor_dir'],
                                              source['dataset'])
        inputFile = TFile(dataset_file)
        NumHistogramObj = inputFile.Get("OSUAnalysis/" +
                                        source['num_channel'] + "/" +
                                        histogramName)
        if 'condor_dir_den' in source:  # If specified, take the denominator histogram from a different condor directory.
            dataset_fileDen = "condor/%s/%s.root" % (source['condor_dir_den'],
                                                     source['dataset'])
            inputFileDen = TFile(dataset_fileDen)
            DenHistogramObj = inputFileDen.Get("OSUAnalysis/" +
                                               source['den_channel'] + "/" +
                                               histogramName)
        else:  # Default is to use the same condor directory
            DenHistogramObj = inputFile.Get("OSUAnalysis/" +
                                            source['den_channel'] + "/" +
                                            histogramName)
        if not NumHistogramObj:
            print "WARNING:  Could not find histogram " + source[
                'num_channel'] + "/" + histogramName + " in file " + dataset_file + ".  Will skip it and continue."
            return
        if not DenHistogramObj:
            print "WARNING:  Could not find histogram " + source[
                'den_channel'] + "/" + histogramName + " in file " + dataset_file + ".  Will skip it and continue."
            return

        Histogram = NumHistogramObj.Clone()
        if Histogram.Class().InheritsFrom("TH2"):
            Histogram.SetName(Histogram.GetName() + "__" + source['dataset'])
        Histogram.SetDirectory(0)
        DenHistogram = DenHistogramObj.Clone()
        DenHistogram.SetDirectory(0)
        inputFile.Close()

        if arguments.rebinFactor:
            RebinFactor = int(arguments.rebinFactor)
            #don't rebin histograms which will have less than 5 bins or any gen-matching histograms
            if Histogram.GetNbinsX() >= RebinFactor * 5 and Histogram.GetTitle(
            ).find("GenMatch") is -1 and not Histogram.Class().InheritsFrom(
                    "TH2"):
                Histogram.Rebin(RebinFactor)
                DenHistogram.Rebin(RebinFactor)

        xAxisLabel = Histogram.GetXaxis().GetTitle()
        unitBeginIndex = xAxisLabel.find("[")
        unitEndIndex = xAxisLabel.find("]")

        if unitBeginIndex is not -1 and unitEndIndex is not -1:  #x axis has a unit
            yAxisLabel = "#epsilon_{ " + cutName + "} (" + str(
                Histogram.GetXaxis().GetBinWidth(1)
            ) + " " + xAxisLabel[unitBeginIndex + 1:unitEndIndex] + " width)"
        else:
            yAxisLabel = "#epsilon_{ " + cutName + "} (" + str(
                Histogram.GetXaxis().GetBinWidth(1)) + " width)"
        if arguments.normalizeToUnitArea:
            yAxisLabel = yAxisLabel + " (Unit Area Norm.)"

        #Histogram = ROOT.TGraphAsymmErrors(NumHistogramObj,DenHistogramObj)
        if arguments.noTGraph or Histogram.Class().InheritsFrom("TH2"):
            Histogram.Divide(DenHistogram)
        else:
            Histogram = TGraphAsymmErrors(Histogram, DenHistogram)

        if not arguments.makeFancy:
            fullTitle = Histogram.GetTitle()
            splitTitle = fullTitle.split(":")
            #    print splitTitle
            histoTitle = splitTitle[1].lstrip(" ")
        else:
            histoTitle = ""

        if 'color' in source:
            Histogram.SetMarkerColor(colors[source['color']])
            Histogram.SetLineColor(colors[source['color']])
        else:
            Histogram.SetMarkerColor(colors[colorList[colorIndex]])
            Histogram.SetLineColor(colors[colorList[colorIndex]])
            colorIndex = colorIndex + 1
            if colorIndex is len(colorList):
                colorIndex = 0

        markerStyle = 20
        if 'marker' in source:
            markerStyle = markers[source['marker']]
        if 'fill' in source:
            markerStyle = markerStyle + fills[source['fill']]

        Histogram.SetMarkerStyle(markerStyle)

        Histogram.SetLineWidth(line_width)
        Histogram.SetFillStyle(0)

        LegendEntries.append(source['legend_entry'])
        Histograms.append(Histogram)

    ### scaling histograms as per user's specifications
    for histogram in Histograms:
        if arguments.normalizeToUnitArea and histogram.Integral() > 0:
            histogram.Scale(1. / histogram.Integral())

    ### formatting histograms and adding to legend
    legendIndex = 0
    for histogram in Histograms:
        Legend.AddEntry(histogram, LegendEntries[legendIndex], "LEP")
        legendIndex = legendIndex + 1

    ### finding the maximum value of anything going on the canvas, so we know how to set the y-axis
    finalMax = 0
    if arguments.noTGraph:
        for histogram in Histograms:
            currentMax = histogram.GetMaximum() + histogram.GetBinError(
                histogram.GetMaximumBin())
            if (currentMax > finalMax):
                finalMax = currentMax
    finalMax = 1.5 * finalMax
    if finalMax is 0:
        finalMax = 1
    if arguments.setYMax:
        finalMax = float(arguments.setYMax)

    ### Drawing histograms to canvas

    makeRatioPlots = arguments.makeRatioPlots
    makeDiffPlots = arguments.makeDiffPlots

    yAxisMin = 0.0001
    if arguments.setYMin:
        yAxisMin = float(arguments.setYMin)

    if makeRatioPlots or makeDiffPlots:
        Canvas.SetFillStyle(0)
        Canvas.Divide(1, 2)
        Canvas.cd(1)
        gPad.SetPad(0, 0.25, 1, 1)
        gPad.SetMargin(0.15, 0.05, 0.01, 0.07)
        gPad.SetFillStyle(0)
        gPad.Update()
        gPad.Draw()
        if arguments.setLogY:
            gPad.SetLogy()
        Canvas.cd(2)
        gPad.SetPad(0, 0, 1, 0.25)
        #format: gPad.SetMargin(l,r,b,t)
        gPad.SetMargin(0.15, 0.05, 0.4, 0.01)
        gPad.SetFillStyle(0)
        gPad.SetGridy(1)
        gPad.Update()
        gPad.Draw()

        Canvas.cd(1)

    histCounter = 0
    plotting_options = ""
    if arguments.plot_hist:
        plotting_options = "HIST"

    for histogram in Histograms:
        if histogram.Class().InheritsFrom("TH2"):
            histogram.SetTitle(histoTitle)
            histogram.Draw("colz")
            DatasetName = histogram.GetName()
            DatasetName = DatasetName[
                DatasetName.rfind('__') +
                2:]  # substring starting with the last underscore
            DatasetLabel = TPaveLabel(topLeft_x_left, topLeft_y_bottom,
                                      topLeft_x_right, topLeft_y_top,
                                      DatasetName, "NDC")
            DatasetLabel.SetBorderSize(0)
            DatasetLabel.SetFillColor(0)
            DatasetLabel.SetFillStyle(0)
            DatasetLabel.Draw()
            outputFile.cd()
            Canvas.SetName(histogram.GetName())
            Canvas.Write()
            if arguments.makeFancy:
                HeaderLabel.Draw()

        else:
            if histogram.InheritsFrom("TGraph") and histCounter == 0:
                plotting_options = "AP"
            histogram.SetTitle(histoTitle)
            histogram.Draw(plotting_options)
            histogram.GetXaxis().SetTitle(xAxisLabel)
            histogram.GetYaxis().SetTitle(yAxisLabel)
            if histogram.InheritsFrom("TH1"):
                histogram.SetMaximum(finalMax)
                histogram.SetMinimum(yAxisMin)
            if makeRatioPlots or makeDiffPlots:
                histogram.GetXaxis().SetLabelSize(0)
        if histCounter is 0:
            if histogram.InheritsFrom("TH1"):
                plotting_options = plotting_options + " SAME"
            elif histogram.InheritsFrom("TGraph"):
                plotting_options = "P"
        histCounter = histCounter + 1

    if histogram.Class().InheritsFrom("TH2"):
        return

    #legend coordinates, empirically determined :-)
    x_left = 0.1677852
    x_right = 0.9647651
    y_min = 0.6765734
    y_max = 0.9

    Legend.SetX1NDC(x_left)
    Legend.SetY1NDC(y_min)
    Legend.SetX2NDC(x_right)
    Legend.SetY2NDC(y_max)
    Legend.Draw()

    if arguments.makeFancy:
        HeaderLabel.Draw()

    #drawing the ratio or difference plot if requested

    if makeRatioPlots or makeDiffPlots:
        Canvas.cd(2)
        if makeRatioPlots:
            Comparison = ratioHistogram(Histograms[0], Histograms[1])
        elif makeDiffPlots:
            Comparison = Histograms[0].Clone("diff")
            Comparison.Add(Histograms[1], -1)
            Comparison.SetTitle("")
            Comparison.GetYaxis().SetTitle("hist1-hist2")
        Comparison.GetXaxis().SetTitle(xAxisLabel)
        Comparison.GetYaxis().CenterTitle()
        Comparison.GetYaxis().SetTitleSize(0.1)
        Comparison.GetYaxis().SetTitleOffset(0.5)
        Comparison.GetXaxis().SetTitleSize(0.15)
        Comparison.GetYaxis().SetLabelSize(0.1)
        Comparison.GetXaxis().SetLabelSize(0.15)
        if makeRatioPlots:
            RatioYRange = 1.15
            if arguments.ratioYRange:
                RatioYRange = float(arguments.ratioYRange)
            Comparison.GetYaxis().SetRangeUser(-1 * RatioYRange, RatioYRange)
        elif makeDiffPlots:
            YMax = Comparison.GetMaximum()
            YMin = Comparison.GetMinimum()
            if YMax <= 0 and YMin <= 0:
                Comparison.GetYaxis().SetRangeUser(-1.2 * YMin, 0)
            elif YMax >= 0 and YMin >= 0:
                Comparison.GetYaxis().SetRangeUser(0, 1.2 * YMax)
            else:  #axis crosses y=0
                if abs(YMax) > abs(YMin):
                    Comparison.GetYaxis().SetRangeUser(-1.2 * YMax, 1.2 * YMax)
                else:
                    Comparison.GetYaxis().SetRangeUser(-1.2 * YMin, 1.2 * YMin)

        Comparison.GetYaxis().SetNdivisions(205)
        Comparison.Draw("E0")

    outputFile.cd()
    Canvas.Write()

    if arguments.savePDFs:
        Canvas.SaveAs("efficiency_histograms_pdfs/" + histogramName + ".pdf")
Beispiel #13
0
def main():

    import argparse
    parser = argparse.ArgumentParser(
        usage="makePValuePlot.py [options] -o OUTPUTFILE --card CARD1",
        description="plots pvalue scans for Z' analysis'",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument("--card",
                        dest="cards",
                        default=[],
                        action="append",
                        help='add datacard to list of curves to plot')
    parser.add_argument("--smooth",
                        dest="smooth",
                        action="store_true",
                        default=False,
                        help="Smooth observed values")
    parser.add_argument("-c",
                        "--config",
                        dest="config",
                        default='',
                        help="config name")
    parser.add_argument("-t",
                        "--tag",
                        dest="tag",
                        default='',
                        help="limit tag")
    parser.add_argument("--ratioLabel",
                        dest="ratioLabel",
                        default='',
                        help="label for ratio")
    args = parser.parse_args()

    canv = ROOT.TCanvas("c1", "c1", 600, 450)
    plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
    style = setTDRStyle()
    ROOT.gStyle.SetTitleYOffset(1)
    ROOT.gStyle.SetPadLeftMargin(0.12)
    ROOT.gStyle.SetPadBottomMargin(0.12)
    ROOT.gStyle.SetOptStat(0)
    ROOT.gStyle.SetTitleXSize(0.055)
    ROOT.gStyle.SetLabelSize(0.055, "X")
    ROOT.gStyle.SetLabelSize(0.055, "Y")
    ROOT.gStyle.SetTitleXOffset(1.05)
    #ROOT.gStyle.SetLabelYSize(0.04)
    ROOT.gStyle.SetTitleYSize(0.055)
    ROOT.gStyle.SetTitleYOffset(1.1)

    plotPad.UseCurrentStyle()
    plotPad.Draw()
    plotPad.cd()
    plotPad.DrawFrame(200, 1e-4, 4000, 10, ";M [GeV]; local p-Value")
    plotPad.SetLogy()
    #ROOT.gStyle.SetLabelXSize(0.04)
    leg = ROOT.TLegend(0.32, 0.72, 0.9, 0.875, "", "brNDC")
    leg.SetFillColor(10)
    leg.SetLineColor(10)
    leg.SetShadowColor(0)
    leg.SetBorderSize(0)
    leg.SetNColumns(2)
    leg.SetTextSize(0.06)
    graphs = []

    name = "pValues_%s_%s" % (args.config, args.tag)
    fileForHEPData = TFile("plots/" + name + "_forHEPData.root", "RECREATE")
    for index, card in enumerate(args.cards):
        if 'width' in card:
            width = "signif" + card.split('width')[-1].split('_')[0]
        else:
            width = 'signif'

        masses, pValues = getPValues(card)
        minPVal, minPValMass = getMinPValue(card)
        print card, minPVal, minPValMass
        graphs.append(
            ROOT.TGraph(len(masses), numpy.array(masses),
                        numpy.array(pValues)))
        label = card.split("_")[-1].split(".")[0]
        if args.smooth:
            smoother = ROOT.TGraphSmooth("normal")
            graphs[index] = deepcopy(
                smoother.SmoothSuper(graphs[index], "linear", 0, 0.005))

        graphs[index].SetLineColor(lineColors[width])
        graphs[index].SetLineStyle(lineStyles[width])
        leg.AddEntry(graphs[index], labels[width], "l")
        graphs[index].Draw("Lsame")
        graphs[index].SetLineWidth(2)
        graphs[index].SetName("graphPVal%s" % width)
        graphs[index].Write("graphPVal%s" % width)

    leg.Draw()
    leg.SetTextSize(0.045)
    latex = ROOT.TLatex()
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.03)
    latex.SetNDC(True)
    latexCMS = ROOT.TLatex()
    latexCMS.SetTextFont(62)
    latexCMS.SetTextSize(0.055)
    latexCMS.SetNDC(True)
    latexCMSExtra = ROOT.TLatex()
    latexCMSExtra.SetTextFont(52)
    latexCMSExtra.SetTextSize(0.03)
    latexCMSExtra.SetNDC(True)

    configName = "scanConfiguration_%s" % args.config

    config = __import__(configName)
    chan = config.leptons

    if (chan == "mumu"):
        plLumi = TPaveLabel(.65, .885, .9, .99,
                            "139.7 fb^{-1} (13 TeV, #mu^{+}#mu^{-})", "NBNDC")
    elif (chan == "elel"):
        plLumi = TPaveLabel(.65, .885, .9, .99, "136.8 fb^{-1} (13 TeV, ee)",
                            "NBNDC")
    elif (chan == "elmu"):
        plLumi = TPaveLabel(
            .27, .885, .9, .99,
            "136.8 fb^{-1} (13 TeV, ee) + 139.7 fb^{-1} (13 TeV, #mu^{+}#mu^{-})",
            "NBNDC")

    plLumi.SetTextSize(0.5)
    plLumi.SetTextFont(42)
    plLumi.SetFillColor(0)
    plLumi.SetBorderSize(0)
    plLumi.Draw()

    cmsExtra = "Preliminary"
    latexCMS.DrawLatex(0.14, 0.81, "CMS")
    if "Simulation" in cmsExtra:
        yLabelPos = 0.78
    else:
        yLabelPos = 0.78

    latexCMSExtra.DrawLatex(0.14, yLabelPos, "%s" % (cmsExtra))

    ZeroSigmaLine = ROOT.TLine(200, 0.5, 4000, 0.5)
    ZeroSigmaLine.SetLineStyle(ROOT.kDashed)
    ZeroSigmaLine.Draw("same")

    OneSigmaLine = ROOT.TLine(200, 0.317 / 2, 4000, 0.317 / 2)
    OneSigmaLine.SetLineStyle(ROOT.kDashed)
    OneSigmaLine.Draw("same")

    TwoSigmaLine = ROOT.TLine(200, 0.0455 / 2, 4000, 0.0455 / 2)
    TwoSigmaLine.SetLineStyle(ROOT.kDashed)
    TwoSigmaLine.Draw("same")

    ThreeSigmaLine = ROOT.TLine(200, 0.0027 / 2, 4000, 0.0027 / 2)
    ThreeSigmaLine.SetLineStyle(ROOT.kDashed)
    ThreeSigmaLine.Draw("same")

    FourSigmaLine = ROOT.TLine(200, 0.00006 / 2, 4000, 0.00006 / 2)
    FourSigmaLine.SetLineStyle(ROOT.kDashed)
    #~ FourSigmaLine.Draw("same")

    FiveSigmaLine = ROOT.TLine(200, 3e-07, 4000, 3e-07)
    FiveSigmaLine.SetLineStyle(ROOT.kDashed)
    #~ FiveSigmaLine.Draw("same")

    latex = ROOT.TLatex()
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.04)
    #~ latex.SetNDC(Tru78
    latex.DrawLatex(4150, 0.5, "0#sigma")
    latex.DrawLatex(4150, 0.317 / 2, "1#sigma")
    latex.DrawLatex(4150, 0.0455 / 2, "2#sigma")
    latex.DrawLatex(4150, 0.0027 / 2, "3#sigma")
    #~ latex.DrawLatex(4200, 0.00006/2, "4#sigma")
    #~ latex.DrawLatex(4200, 3e-7, "5#sigma")

    #~ ROOT.gPad.WaitPrimitive()
    plotPad.SetTicks(1, 1)
    plotPad.RedrawAxis()
    if args.smooth:
        name += "_smoothed"
    #name = name+".pdf"
    canv.Print("plots/" + name + ".pdf")
    canv.Print("plots/" + name + ".root")

    plotPad.RedrawAxis()

    fileForHEPData.Write()
    fileForHEPData.Close()
Beispiel #14
0
    f1 = TFile(plot["file1"])  
    f2 = TFile(plot["file2"]) 
    h1 = f1.Get(plot["name"])
    h2 = f2.Get(plot["name"])
    h1.GetXaxis().SetNdivisions(5)  
    h1.GetYaxis().SetNdivisions(5)  
    h1.GetXaxis().SetTitleSize(0.05)
    h1.GetYaxis().SetTitleSize(0.05)
    h1.GetZaxis().SetTitleSize(0.05)
    h1.GetXaxis().SetLabelSize(0.05)
    h1.GetYaxis().SetLabelSize(0.05)
    h1.GetZaxis().SetLabelSize(0.05)
    h1.GetXaxis().SetTitleOffset(1.0) 
    h1.GetYaxis().SetTitleOffset(1.6) 

    HeaderLabel = TPaveLabel(0.2, 0.92, 0.8, 0.98,title,"NDC")
    # HeaderLabel.SetTextAlign(32)
    HeaderLabel.SetTextFont(42)
    HeaderLabel.SetTextSize(0.8) 
    HeaderLabel.SetBorderSize(0)
    HeaderLabel.SetFillColor(0)
    HeaderLabel.SetFillStyle(0)

    if h1.Class().InheritsFrom("TH2"):
        is2D = True
    else:
        is2D = False  

    if is2D:
        c.SetRightMargin(0.15)  
        c.SetLogz(True)  
Beispiel #15
0
def MakeOneDHist(histogramDirectory, histogramName,integrateDir):

    if arguments.verbose:
        print "Creating histogram", histogramName, "in directory", histogramDirectory

    HeaderLabel = TPaveLabel(header_x_left,header_y_bottom,header_x_right,header_y_top,HeaderText,"NDC")
    HeaderLabel.SetTextAlign(32)
    HeaderLabel.SetTextFont(42)
    HeaderLabel.SetTextSize(0.697674)
    HeaderLabel.SetBorderSize(0)
    HeaderLabel.SetFillColor(0)
    HeaderLabel.SetFillStyle(0)

    CMSLabel = TPaveLabel(header_x_left,header_y_bottom,header_x_right,header_y_top,HeaderText,"NDC")
    CMSLabel.SetTextAlign(32)
    CMSLabel.SetTextFont(42)
    CMSLabel.SetTextSize(0.697674)
    CMSLabel.SetBorderSize(0)
    CMSLabel.SetFillColor(0)
    CMSLabel.SetFillStyle(0)

    if makeFancy:
        LumiLabel = TPaveLabel(topLeft_x_left,topLeft_y_bottom,topLeft_x_right,topLeft_y_top,"CMS Preliminary","NDC")
        LumiLabel.SetTextFont(62)
        LumiLabel.SetTextSize(0.7)
        LumiLabel.SetTextAlign(12)
    else:
        LumiLabel = TPaveLabel(topLeft_x_left,topLeft_y_bottom,topLeft_x_right,topLeft_y_top,LumiText,"NDC")
        LumiLabel.SetTextAlign(32)
        LumiLabel.SetTextFont(42)
    LumiLabel.SetBorderSize(0)
    LumiLabel.SetFillColor(0)
    LumiLabel.SetFillStyle(0)

    Legend = TLegend()
    Legend.SetBorderSize(0)
    Legend.SetFillColor(0)
    Legend.SetFillStyle(0)

    canvasName = histogramName
    if integrateDir is "left":
        canvasName += "_CumulativeLeft"
    elif integrateDir is "right":
        canvasName += "_CumulativeRight"
    Canvas = TCanvas(canvasName)
    Histograms = []
    RefIndex = -99
    LegendEntries = []

    colorIndex = 0
    markerStyleIndex = 0
    fillIndex = 0

    for source in input_sources: # loop over different input sources in config file
        dataset_file = "condor/%s/%s.root" % (source['condor_dir'],source['dataset'])
        inputFile = TFile(dataset_file)


        if arguments.generic:
            if histogramDirectory == "":
                histPath = histogramName
            else:
                histPath = histogramDirectory + "/" + histogramName
            HistogramObj = inputFile.Get(histPath)
        else:
            HistogramObj = inputFile.Get(source['channel'] + "Plotter/" + histogramDirectory + "/" + histogramName)
        if not HistogramObj:
            print "WARNING:  Could not find histogram " + source['channel'] + "/" + histogramName + " in file " + dataset_file + ".  Will skip it and continue."
            return
        Histogram = HistogramObj.Clone()
        Histogram.SetDirectory(0)
        inputFile.Close()
        Histogram.Sumw2()
        if arguments.verbose:
            print "  Got histogram", Histogram.GetName(), "from file", dataset_file
        if arguments.rebinFactor:
            RebinFactor = int(arguments.rebinFactor)
            #don't rebin histograms which will have less than 5 bins or any gen-matching histograms
            if Histogram.GetNbinsX() >= RebinFactor*5 and Histogram.GetTitle().find("GenMatch") is -1:
                Histogram.Rebin(RebinFactor)

        # correct bin contents of object multiplcity plots
        if Histogram.GetName().startswith("num") and "PV" not in Histogram.GetName():
            # include overflow bin
            for bin in range(2,Histogram.GetNbinsX()+2):
                content = Histogram.GetBinContent(bin)
                Histogram.SetBinContent(bin, content/float(bin-1))


        xAxisLabel = Histogram.GetXaxis().GetTitle()
        unitBeginIndex = xAxisLabel.find("[")
        unitEndIndex = xAxisLabel.find("]")
        xAxisLabelVar = xAxisLabel

        if "_pfx" in Histogram.GetName() or "_pfy" in Histogram.GetName() or "_sigma" in Histogram.GetName():
            yAxisLabel = Histogram.GetYaxis().GetTitle()
        else:

            if unitBeginIndex is not -1 and unitEndIndex is not -1: #x axis has a unit
                yAxisLabel = "Entries / " + str(Histogram.GetXaxis().GetBinWidth(1)) + " " + xAxisLabel[unitBeginIndex+1:unitEndIndex]
                xAxisLabelVar = xAxisLabel[0:unitBeginIndex]
            else:
                yAxisLabel = "Entries per bin (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " width)"
            if arguments.normalizeToUnitArea:
                yAxisLabel = yAxisLabel + " (Unit Area Norm.)"

            if arguments.normalizeToUnitArea and arguments.makeSignificancePlots:
                unit = "Efficiency"
            else:
                unit = "Yield"
            if integrateDir is "left":
                yAxisLabel = unit + ", " + xAxisLabelVar + "< x (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " bin width)"
            if integrateDir is "right":
                yAxisLabel = unit + ", " + xAxisLabelVar + "> x (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " bin width)"


        nbins = Histogram.GetNbinsX()
        if not noOverFlow:
            Histogram.SetBinContent(nbins, Histogram.GetBinContent(nbins) + Histogram.GetBinContent(nbins+1)) # Add overflow
            Histogram.SetBinError(nbins, math.sqrt(math.pow(Histogram.GetBinError(nbins),2) + math.pow(Histogram.GetBinError(nbins+1),2))) # Set the errors to be the sum in quadrature
        if not noUnderFlow:
            Histogram.SetBinContent(1, Histogram.GetBinContent(1) + Histogram.GetBinContent(0)) # Add underflow
            Histogram.SetBinError(1, math.sqrt(math.pow(Histogram.GetBinError(1), 2) + math.pow(Histogram.GetBinError(0), 2))) # Set the errors to be the sum in quadrature

        if not arguments.makeFancy and not arguments.generic:
            fullTitle = Histogram.GetTitle()
            splitTitle = fullTitle.split(":")
            if len(splitTitle) > 1:
                histoTitle = splitTitle[1].lstrip(" ")
            else:
                histoTitle = splitTitle[0]
        else:
            histoTitle = ""

        if 'color' in source:
            Histogram.SetMarkerColor(colors[source['color']])
            Histogram.SetLineColor(colors[source['color']])
        else:
            Histogram.SetMarkerColor(colors[colorList[colorIndex]])
            Histogram.SetLineColor(colors[colorList[colorIndex]])
            colorIndex = colorIndex + 1
            if colorIndex is len(colorList):
                colorIndex = 0
                markerStyleIndex = markerStyleIndex + 1
                if markerStyleIndex is len(markerStyleList):
                    markerStyleIndex = 0
                    fillIndex = fillIndex + 1


        if 'scale' in source:
            Histogram.Scale(source['scale'])

        markerStyle = 20
        if 'marker' in source:
            markerStyle = markers[source['marker']]
        else:
            markerStyle = markers[markerStyleList[markerStyleIndex]]

        fillStyle = 0
        if 'fill' in source:
            markerStyle = markerStyle + fills[source['fill']]
        else:
            markerStyle = markerStyle + fills[fillList[fillIndex]]

        Histogram.SetMarkerStyle(markerStyle)
        Histogram.SetMarkerSize(0.5)

        Histogram.SetLineWidth(line_width)
        Histogram.SetFillStyle(0)

        if arguments.normalizeToUnitArea and Histogram.Integral() > 0:
            Histogram.Scale(1./Histogram.Integral())

        Histogram = MakeIntegralHist(Histogram, integrateDir)

        LegendEntries.append(source['legend_entry'])
        Histograms.append(Histogram)
        if 'reference' in source:
            if source['reference']:
                RefIndex = len(Histograms)-1

    ### formatting histograms and adding to legend
    legendIndex = 0
    for histogram in Histograms:
        Legend.AddEntry(histogram,LegendEntries[legendIndex],"LEP")
#        Legend.AddEntry(histogram,LegendEntries[legendIndex],"P")
        legendIndex = legendIndex+1

    ### finding the maximum value of anything going on the canvas, so we know how to set the y-axis
    finalMax = 0
    for histogram in Histograms:
        currentMax = histogram.GetMaximum() + histogram.GetBinError(histogram.GetMaximumBin())
        if(currentMax > finalMax):
            finalMax = currentMax
    finalMax = 1.5*finalMax
    if arguments.setYMax:
        finalMax = float(arguments.setYMax)

    ### Drawing histograms to canvas

    makeRatioPlots = arguments.makeRatioPlots
    makeDiffPlots = arguments.makeDiffPlots
    addOneToRatio = -1
    if arguments.addOneToRatio:
        addOneToRatio = arguments.addOneToRatio

    yAxisMin = 0.0001
    if arguments.setYMin:
        yAxisMin = float(arguments.setYMin)

    if makeRatioPlots or makeDiffPlots:
        Canvas.SetFillStyle(0)
        Canvas.Divide(1,2)
        Canvas.cd(1)
        gPad.SetPad(0,0.25,1,1)
        gPad.SetMargin(0.15,0.05,0.01,0.07)
        gPad.SetFillStyle(0)
        gPad.Update()
        gPad.Draw()
        if arguments.setLogY:
            gPad.SetLogy()
        Canvas.cd(2)
        gPad.SetPad(0,0,1,0.25)
        #format: gPad.SetMargin(l,r,b,t)
        gPad.SetMargin(0.15,0.05,0.4,0.01)
        gPad.SetFillStyle(0)
        gPad.SetGridy(1)
        gPad.Update()
        gPad.Draw()

        Canvas.cd(1)

    histCounter = 0
    plotting_options = ""
    if arguments.generic:
        plotting_options = "p,e"
    if arguments.plot_hist:
        plotting_options = "HIST"

    for histogram in Histograms:
        histogram.SetTitle(histoTitle)
        if arguments.verbose:
            print "  Drawing hist " + histogram.GetName() + ", with plotting_options = " + plotting_options + ", with mean = " + str(histogram.GetMean()) + ", with color = " + str(histogram.GetLineColor())
        histogram.Draw(plotting_options)
        histogram.GetXaxis().SetTitle(xAxisLabel)
        histogram.GetYaxis().SetTitle(yAxisLabel)
        histogram.SetMaximum(finalMax)

        if "_pfx" not in Histogram.GetName() and "_pfy" not in Histogram.GetName() and "_sigma" not in Histogram.GetName():
            histogram.SetMinimum(yAxisMin)
        if makeRatioPlots or makeDiffPlots:
            histogram.GetXaxis().SetLabelSize(0)
        if histCounter is 0:
            plotting_options = plotting_options + " SAME"
        histCounter = histCounter + 1

    #legend coordinates, empirically determined :-)
    x_left = 0.1677852
    x_right = 0.9647651
    y_min = 0.6765734
    y_max = 0.9

    Legend.SetX1NDC(x_left)
    Legend.SetY1NDC(y_min)
    Legend.SetX2NDC(x_right)
    Legend.SetY2NDC(y_max)
    Legend.Draw()


    # Deciding which text labels to draw and drawing them
    if arguments.makeFancy:
        HeaderLabel.Draw()
        LumiLabel.Draw()




    #drawing the ratio or difference plot if requested

    if makeRatioPlots or makeDiffPlots:
        Comparisons = []
        Canvas.cd(2)
        if RefIndex == -99:
            Reference = Histograms[0]
        else:
            Reference = Histograms[RefIndex]

        for Histogram in Histograms:
            if Histogram is Reference:
                continue

            if makeRatioPlots:
                makeRatio = functools.partial (ratioHistogram,Histogram, Reference)
                if arguments.ratioRelErrMax is not -1: # it gets initialized to this dummy value of -1
                    makeRatio =  functools.partial (makeRatio, relErrMax = float(arguments.ratioRelErrMax))
                if addOneToRatio != -1: # it gets initialized to this dummy value of -1
                    makeRatio = functools.partial (makeRatio, addOne = bool (addOneToRatio))
                Comparison = makeRatio()
            elif makeDiffPlots:
                Comparison = Reference.Clone("diff")
                Comparison.Add(Histograms[1],-1)
                Comparison.SetTitle("")
                Comparison.GetYaxis().SetTitle("X-ref")

            Comparison.SetLineColor(Histogram.GetLineColor())
            Comparison.SetFillColor(Histogram.GetFillColor())
            Comparison.SetFillStyle(Histogram.GetFillStyle())
            Comparison.SetMarkerColor(Histogram.GetMarkerColor())
            Comparison.SetMarkerStyle(Histogram.GetMarkerStyle())

            Comparison.GetXaxis().SetTitle(xAxisLabel)
            Comparison.GetYaxis().CenterTitle()
            Comparison.GetYaxis().SetTitleSize(0.1)
            Comparison.GetYaxis().SetTitleOffset(0.5)
            Comparison.GetXaxis().SetTitleSize(0.15)
            Comparison.GetYaxis().SetLabelSize(0.1)
            Comparison.GetXaxis().SetLabelSize(0.15)

            if makeRatioPlots:
                RatioYRange = 1.15
                if arguments.ratioYRange:
                    RatioYRange = float(arguments.ratioYRange)
                if addOneToRatio == -1: # it gets initialized to this dummy value of -1
                    Comparison.GetYaxis().SetRangeUser(-1*RatioYRange, RatioYRange)
                else:
                    Comparison.GetYaxis().SetRangeUser(-1*RatioYRange + 1.0, RatioYRange + 1.0)

            elif makeDiffPlots:
                YMax = Comparison.GetMaximum()
                YMin = Comparison.GetMinimum()
                if YMax <= 0 and YMin <= 0:
                    Comparison.GetYaxis().SetRangeUser(-1.2*YMin,0)
                elif YMax >= 0 and YMin >= 0:
                    Comparison.GetYaxis().SetRangeUser(0,1.2*YMax)
                else: #axis crosses y=0
                    if abs(YMax) > abs(YMin):
                        Comparison.GetYaxis().SetRangeUser(-1.2*YMax,1.2*YMax)
                    else:
                        Comparison.GetYaxis().SetRangeUser(-1.2*YMin,1.2*YMin)

            Comparison.GetYaxis().SetNdivisions(205)
            Comparisons.append(Comparison)

        option = "E0"
        for index,Comparison in enumerate(Comparisons):
            if index == 0:
                option += " SAME"
            Comparison.Draw(option)

    outputFile.cd(histogramDirectory)
    Canvas.Write()
    if arguments.verbose:
        print "  Finished writing canvas: ", Canvas.GetName()

    if arguments.savePDFs:
        Canvas.SaveAs("comparison_histograms_pdfs/"+histogramName+".pdf")
def MakeOneHist(dirName, histogramName):

    HeaderLabel = TPaveLabel(header_x_left,header_y_bottom,header_x_right,header_y_top,HeaderText,"NDC")
    HeaderLabel.SetTextAlign(32)
    HeaderLabel.SetTextFont(42)
    HeaderLabel.SetTextSize(0.697674)
    HeaderLabel.SetBorderSize(0)
    HeaderLabel.SetFillColor(0)
    HeaderLabel.SetFillStyle(0)

    CMSLabel = TPaveLabel(header_x_left,header_y_bottom,header_x_right,header_y_top,HeaderText,"NDC")
    CMSLabel.SetTextAlign(32)
    CMSLabel.SetTextFont(42)
    CMSLabel.SetTextSize(0.697674)
    CMSLabel.SetBorderSize(0)
    CMSLabel.SetFillColor(0)
    CMSLabel.SetFillStyle(0)

    if makeFancy:
        LumiLabel = TPaveLabel(topLeft_x_left,topLeft_y_bottom,topLeft_x_right,topLeft_y_top,"CMS Preliminary","NDC")
        LumiLabel.SetTextFont(62)
        LumiLabel.SetTextSize(0.7)
        LumiLabel.SetTextAlign(12)
    else:
        LumiLabel = TPaveLabel(topLeft_x_left,topLeft_y_bottom,topLeft_x_right,topLeft_y_top,LumiText,"NDC")
        LumiLabel.SetTextAlign(32)
        LumiLabel.SetTextFont(42)
    LumiLabel.SetBorderSize(0)
    LumiLabel.SetFillColor(0)
    LumiLabel.SetFillStyle(0)

    #legend coordinates, empirically determined :-)
    x_left = 0.4
    x_right = 0.7
    y_min = 0.15
    y_max = 0.3

    Legend = TLegend(x_left,y_min,x_right,y_max)
    Legend.SetBorderSize(0)
    Legend.SetFillColor(0)
    Legend.SetFillStyle(0)

    Canvas = TCanvas(histogramName)
    Histograms = []
    HistogramClones = []
    NBins = []
    MaxXValues = []
    MinXValues = []
    LegendEntries = []

    colorIndex = 0

    for source in input_sources: # loop over different input sources in config file
        dataset_file = "condor/%s/%s.root" % (source['condor_dir'],source['dataset'])
        inputFile = TFile(dataset_file)
        NumHistogramObj = inputFile.Get(source['num_channel'] + "Plotter/" + dirName + "/" + histogramName)
        if 'condor_dir_den' in source:   # If specified, take the denominator histogram from a different condor directory.
            dataset_fileDen = "condor/%s/%s.root" % (source['condor_dir_den'],source['dataset'])
            inputFileDen = TFile(dataset_fileDen)
            DenHistogramObj = inputFileDen.Get(source['den_channel'] + "Plotter/" + dirName + "/" + histogramName)
        else:   # Default is to use the same condor directory
            DenHistogramObj = inputFile.Get(source['den_channel'] + "Plotter/" + dirName + "/" + histogramName)
        if not NumHistogramObj:
            print "WARNING:  Could not find histogram " + source['num_channel'] + "Plotter/" + dirName + "/" + histogramName + " in file " + dataset_file + ".  Will skip it and continue."
            return
        if not DenHistogramObj:
            print "WARNING:  Could not find histogram " + source['den_channel'] + "Plotter/" + dirName + "/" + histogramName + " in file " + dataset_file + ".  Will skip it and continue."
            return

        Histogram = NumHistogramObj.Clone()
        if Histogram.Class().InheritsFrom("TH2"):
            Histogram.SetName(Histogram.GetName() + "__" + source['dataset'])
        Histogram.SetDirectory(0)
        DenHistogram = DenHistogramObj.Clone()
        DenHistogram.SetDirectory(0)
        inputFile.Close()

        nbinsN = Histogram.GetNbinsX()
        nbinsD = DenHistogram.GetNbinsX()
        if not noOverFlow:
            # Add overflow
            Histogram.SetBinContent(   nbinsN,    Histogram.GetBinContent(nbinsN) +    Histogram.GetBinContent(nbinsN+1))
            DenHistogram.SetBinContent(nbinsD, DenHistogram.GetBinContent(nbinsD) + DenHistogram.GetBinContent(nbinsD+1))

            # Set the errors to be the sum in quadrature
            Histogram.SetBinError(  nbinsN,     math.sqrt(math.pow(Histogram.GetBinError(nbinsN),2) +    math.pow(Histogram.GetBinError(nbinsN+1),2)))
            DenHistogram.SetBinError(nbinsD, math.sqrt(math.pow(DenHistogram.GetBinError(nbinsD),2) + math.pow(DenHistogram.GetBinError(nbinsD+1),2)))

        if not noUnderFlow:
            # Add underflow
            Histogram.SetBinContent(   1,    Histogram.GetBinContent(1) +    Histogram.GetBinContent(0))
            DenHistogram.SetBinContent(1, DenHistogram.GetBinContent(1) + DenHistogram.GetBinContent(0))

            # Set the errors to be the sum in quadrature
            Histogram.SetBinError(   1,    math.sqrt(math.pow(Histogram.GetBinError(1), 2) +    math.pow(Histogram.GetBinError(0), 2)))
            DenHistogram.SetBinError(1, math.sqrt(math.pow(DenHistogram.GetBinError(1), 2) + math.pow(DenHistogram.GetBinError(0), 2)))

        if arguments.rebinFactor:
            RebinFactor = int(arguments.rebinFactor)
            #don't rebin histograms which will have less than 5 bins or any gen-matching histograms
            if Histogram.GetNbinsX() >= RebinFactor*5 and Histogram.GetTitle().find("GenMatch") is -1 and not Histogram.Class().InheritsFrom("TH2"):
                Histogram.Rebin(RebinFactor)
                DenHistogram.Rebin(RebinFactor)

        xAxisLabel = Histogram.GetXaxis().GetTitle()
        unitBeginIndex = xAxisLabel.find("[")
        unitEndIndex = xAxisLabel.find("]")

        if unitBeginIndex is not -1 and unitEndIndex is not -1: #x axis has a unit
            yAxisLabel = "#epsilon_{ " + cutName + "} (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " " + xAxisLabel[unitBeginIndex+1:unitEndIndex] + " width)"
        else:
            yAxisLabel = "#epsilon_{ " + cutName + "} (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " width)"
        if arguments.normalizeToUnitArea:
            yAxisLabel = yAxisLabel + " (Unit Area Norm.)"

        #check if bin content is consistent
        TEfficiency.CheckConsistency(Histogram,DenHistogram)
        for i in range(1,Histogram.GetNbinsX()+1):
            if Histogram.GetBinContent(i) > DenHistogram.GetBinContent(i):
                DenHistogram.SetBinContent(i,Histogram.GetBinContent(i))

        #HistogramClone and HistogramClones only used for ratio plot
        HistogramClone = Histogram.Clone()
        HistogramClone.SetDirectory(0)
        HistogramClone.Divide(DenHistogram)
        Nbins = HistogramClone.GetNbinsX()
        MaxXValue = HistogramClone.GetXaxis().GetBinLowEdge(Nbins+1)
        MinXValue = HistogramClone.GetXaxis().GetBinLowEdge(1)

        #this Histogram becomes the main TEfficiency
        if Histogram.Class().InheritsFrom("TH2"):
            Histogram.Divide(DenHistogram)
        else:
            #using default methods (which give correct uncertainties)
            #see https://root.cern.ch/doc/master/classTEfficiency.html (c.f. section IV)
            Histogram = TEfficiency(Histogram,DenHistogram)

        if not arguments.makeFancy:
            fullTitle = Histogram.GetTitle()
            splitTitle = fullTitle.split(":")
            #    print splitTitle
            if len(splitTitle) > 1:
                histoTitle = splitTitle[1].lstrip(" ")
            else:
                histoTitle = splitTitle[0]
        else:
            histoTitle = ""

        if 'color' in source:
            Histogram.SetMarkerColor(colors[source['color']])
            Histogram.SetLineColor(colors[source['color']])
        else:
            Histogram.SetMarkerColor(colors[colorList[colorIndex]])
            Histogram.SetLineColor(colors[colorList[colorIndex]])
            colorIndex = colorIndex + 1
            if colorIndex is len(colorList):
                colorIndex = 0

        markerStyle = 20
        if 'marker' in source:
            markerStyle = markers[source['marker']]
        if 'fill' in source:
            markerStyle = markerStyle + fills[source['fill']]

        Histogram.SetMarkerStyle(markerStyle)

        Histogram.SetLineWidth(line_width)
        Histogram.SetFillStyle(0)

        LegendEntries.append(source['legend_entry'])
        Histograms.append(Histogram)
        HistogramClones.append(HistogramClone)
        NBins.append(Nbins)
        MaxXValues.append(MaxXValue)
        MinXValues.append(MinXValue)

    ### scaling histograms as per user's specifications
    for histogram in Histograms:
        if arguments.normalizeToUnitArea and histogram.Integral() > 0:
            histogram.Scale(1./histogram.Integral())


    ### formatting histograms and adding to legend
    legendIndex = 0
    for histogram in Histograms:
        Legend.AddEntry(histogram,LegendEntries[legendIndex],"LEP")
        legendIndex = legendIndex+1

    ### finding the maximum value of anything going on the canvas, so we know how to set the y-axis
    finalMax = 1.1
    if arguments.setYMax:
        finalMax = float(arguments.setYMax)

    ### Drawing histograms to canvas

    makeRatioPlots = arguments.makeRatioPlots
    makeDiffPlots = arguments.makeDiffPlots
    addOneToRatio = -1
    if arguments.addOneToRatio:
        addOneToRatio = arguments.addOneToRatio

    dontRebinRatio = -1
    if arguments.dontRebinRatio:
        dontRebinRatio = arguments.dontRebinRatio

    ratioRelErrMax = -1
    if arguments.ratioRelErrMax:
        ratioRelErrMax = arguments.ratioRelErrMax

    yAxisMin = 0.0001
    if arguments.setYMin:
        yAxisMin = float(arguments.setYMin)

    if makeRatioPlots or makeDiffPlots:
        Canvas.SetFillStyle(0)
        Canvas.Divide(1,2)
        Canvas.cd(1)
        gPad.SetPad(0,0.25,1,1)
        gPad.SetMargin(0.15,0.05,0.01,0.07)
        gPad.SetFillStyle(0)
        gPad.Update()
        gPad.Draw()
        if arguments.setLogY:
            gPad.SetLogy()
        Canvas.cd(2)
        gPad.SetPad(0,0,1,0.25)
        #format: gPad.SetMargin(l,r,b,t)
        gPad.SetMargin(0.15,0.05,0.4,0.01)
        gPad.SetFillStyle(0)
        gPad.SetGridy(1)
        gPad.Update()
        gPad.Draw()

        Canvas.cd(1)

    histCounter = 0
    plotting_options = ""
    if arguments.plot_hist:
        plotting_options = "HIST"

    h = TH2F("h1","",NBins[0],MinXValues[0],MaxXValues[0],110,0.,finalMax)
    h.SetTitle(";"+xAxisLabel+";"+yAxisLabel)
    h.Draw()

    for histogram in Histograms:
        if histogram.Class().InheritsFrom("TH2"):
            histogram.SetTitle(histoTitle)
            histogram.Draw("colz")
            DatasetName = histogram.GetName()
            DatasetName = DatasetName[DatasetName.rfind('__')+2:]  # substring starting with the last underscore
            DatasetLabel = TPaveLabel(topLeft_x_left,topLeft_y_bottom,topLeft_x_right,topLeft_y_top,DatasetName,"NDC")
            DatasetLabel.SetBorderSize(0)
            DatasetLabel.SetFillColor(0)
            DatasetLabel.SetFillStyle(0)
            DatasetLabel.Draw()
            outputFile.cd()
            Canvas.SetName(histogram.GetName())
            Canvas.Write()

        else:
            if histogram.InheritsFrom("TEfficiency") and histCounter==0:
                plotting_options = "P SAME"
            histogram.SetTitle(histoTitle)
            histogram.Draw(plotting_options)

            if histogram.InheritsFrom("TH1"):
                histogram.SetMaximum(finalMax)
                histogram.SetMinimum(yAxisMin)

        if histCounter is 0:
            if histogram.InheritsFrom("TH1"):
                plotting_options = plotting_options + " SAME"
            elif histogram.InheritsFrom("TEfficiency"):
                plotting_options = "P" + " SAME"

        histCounter = histCounter + 1

    if histogram.Class().InheritsFrom("TH2"):
        return

    Legend.Draw()


    if arguments.makeFancy:
        HeaderLabel.Draw()
        LumiLabel.Draw()



    #drawing the ratio or difference plot if requested

    if makeRatioPlots or makeDiffPlots:
        Canvas.cd(2)
        if makeRatioPlots:
            makeRatio = functools.partial (ratioHistogram,HistogramClones[0],HistogramClones[1])
            if addOneToRatio != -1: # it gets initialized to this dummy value of -1
                makeRatio = functools.partial (makeRatio, addOne = bool (addOneToRatio))
            if ratioRelErrMax is not -1: # it gets initialized to this dummy value of -1
                makeRatio = functools.partial (makeRatio, relErrMax = float (ratioRelErrMax))
            if dontRebinRatio is True:
                makeRatio = functools.partial (makeRatio, dontRebinRatio)
            Comparison = makeRatio ()
        elif makeDiffPlots:
            Comparison = Histograms[0].Clone("diff")
            Comparison.Add(Histograms[1],-1)
            Comparison.SetTitle("")
            Comparison.GetYaxis().SetTitle("hist1-hist2")
        Comparison.GetXaxis().SetTitle(xAxisLabel)
        Comparison.GetYaxis().CenterTitle()
        Comparison.GetYaxis().SetTitleSize(0.1)
        Comparison.GetYaxis().SetTitleOffset(0.5)
        Comparison.GetXaxis().SetTitleSize(0.15)
        Comparison.GetYaxis().SetLabelSize(0.1)
        Comparison.GetXaxis().SetLabelSize(0.15)
        if makeRatioPlots:
            RatioYRange = 1.15
            if arguments.ratioYRange:
                RatioYRange = float(arguments.ratioYRange)
            if addOneToRatio == -1: # it gets initialized to this dummy value of -1
                Comparison.GetYaxis().SetRangeUser(-1*RatioYRange, RatioYRange)
            else:
                Comparison.GetYaxis().SetRangeUser(-1*RatioYRange + 1.0, RatioYRange + 1.0)
        elif makeDiffPlots:
            YMax = Comparison.GetMaximum()
            YMin = Comparison.GetMinimum()
            if YMax <= 0 and YMin <= 0:
                Comparison.GetYaxis().SetRangeUser(-1.2*YMin,0)
            elif YMax >= 0 and YMin >= 0:
                Comparison.GetYaxis().SetRangeUser(0,1.2*YMax)
            else: #axis crosses y=0
                if abs(YMax) > abs(YMin):
                    Comparison.GetYaxis().SetRangeUser(-1.2*YMax,1.2*YMax)
                else:
                    Comparison.GetYaxis().SetRangeUser(-1.2*YMin,1.2*YMin)

        Comparison.GetYaxis().SetNdivisions(205)
        Comparison.Draw("E0")

    outputFile.cd(dirName)
    Canvas.Write()

    if arguments.savePDFs:
        Canvas.SaveAs("efficiency_histograms_pdfs/"+histogramName+".pdf")
Beispiel #17
0
def makeLimitPlot(output,obs,exp,chan,printStats=False):

	fileForHEPData = TFile("plots/"+output+"_forHEPData.root","RECREATE")

	obsLimits = {}
	
	for obsFile in obs:
		if 'width' in obsFile:
			width = obsFile.split('width')[-1].split('_')[0]
		else:
			width = '0.006'
		obsLimits[width] = createObsGraph(obsFile)	

        if  SMOOTH:
		for width,obsGraph in obsLimits.iteritems():
                	smooth_obs=TGraphSmooth("normal")
                	GraphObs_nonSmooth=obsGraph
                	obsLimits[width]=copy.deepcopy(smooth_obs.SmoothSuper(GraphObs_nonSmooth,"linear",0,0.005))
                	obsLimits[width].SetLineWidth(3)


	expLimits = {}
	
	for expFile in exp:
		if 'width' in expFile:
			width = expFile.split('width')[-1].split('_')[0]
		else:
			width = '0.006'	
		expLimits[width] = createExpGraph(expFile)	

    	cCL=TCanvas("cCL", "cCL",0,0,600,450)
    	gStyle.SetOptStat(0)
	gStyle.SetPadRightMargin(0.063)
	gStyle.SetPadLeftMargin(0.14)
	gStyle.SetPadBottomMargin(0.12)
	
    	plotPad = ROOT.TPad("plotPad","plotPad",0,0,1,1)
    	plotPad.Draw()	
    	plotPad.cd()


     	smoother=TGraphSmooth("normal")
    	smoother2=TGraphSmooth("normal")
	   

    
    	zprimeX=[]
    	zprimeY=[]
    	fileZPrime=open('tools/xsec_ssm.txt','r')
    	for entries in fileZPrime:
        	entry=entries.split()
        	zprimeX.append(float(entry[0]))
        	zprimeY.append(float(entry[1])/1928)
    	zpX=numpy.array(zprimeX)
    	zpY=numpy.array(zprimeY)
    	GraphZPrime=TGraph(len(zprimeX),zpX,zpY)
    	GraphZPrimeSmooth=smoother2.SmoothSuper(GraphZPrime,"linear")
    	GraphZPrimeSmooth.SetLineWidth(3)
    	GraphZPrimeSmooth.SetLineColor(ROOT.kGreen+3)
    	GraphZPrimeSmooth.SetLineStyle(2)

    	zprimePsiX=[]
    	zprimePsiY=[]
    	fileZPrimePsi=open('tools/xsec_psi.txt','r')
    	for entries in fileZPrimePsi:
        	entry=entries.split()
        	zprimePsiX.append(float(entry[0]))
        	zprimePsiY.append(float(entry[1])/1928)

   	zpPsiX=numpy.array(zprimePsiX)
	zpPsiY=numpy.array(zprimePsiY)
    	GraphZPrimePsi=TGraph(len(zprimePsiX),zpPsiX,zpPsiY)
    	GraphZPrimePsiSmooth=smoother.SmoothSuper(GraphZPrimePsi,"linear")
   	GraphZPrimePsiSmooth.SetLineWidth(3)
    	GraphZPrimePsiSmooth.SetLineColor(ROOT.kBlue)

#Draw the graphs:
    	plotPad.SetLogy()
    	DummyGraph=TH1F("DummyGraph","",100,200,5500)
    	DummyGraph.GetXaxis().SetTitle("M [GeV]")
	if SPIN2:
        		DummyGraph.GetYaxis().SetTitle("[#sigma#upoint#font[12]{B}] G_{KK} / #sigma#upoint#font[12]{B}] Z")
	else:
        		DummyGraph.GetYaxis().SetTitle("[#sigma#upoint#font[12]{B}] Z' / [#sigma#upoint#font[12]{B}] Z")

#	if SPIN2:
#	    	if chan=="mumu":
#       	 		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrow#mu^{+}#mu^{-}+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu^{+}#mu^{-}+X)")
#    		elif chan=="elel":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)")
#    		elif chan=="elmu":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)")
#	else:
#    		if chan=="mumu":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrow#mu^{+}#mu^{-}+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu^{+}#mu^{-}+X)")
#    		elif chan=="elel":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)")
#    		elif chan=="elmu":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)")



    	gStyle.SetOptStat(0)
    	DummyGraph.GetXaxis().SetRangeUser(200,5500)

    	DummyGraph.SetMinimum(1e-8)
    	DummyGraph.SetMaximum(3e-4)
    	DummyGraph.GetXaxis().SetLabelSize(0.055)
    	DummyGraph.GetXaxis().SetTitleSize(0.055)
   	DummyGraph.GetXaxis().SetTitleOffset(1.05)
    	DummyGraph.GetYaxis().SetLabelSize(0.055)
    	DummyGraph.GetYaxis().SetTitleSize(0.055)
    	DummyGraph.GetYaxis().SetTitleOffset(1.3)

    	DummyGraph.Draw()

    	plCMS=TPaveLabel(.16,.76,.27,.83,"CMS","NBNDC")
#plCMS.SetTextSize(0.8)
    	plCMS.SetTextAlign(12)
    	plCMS.SetTextFont(62)
    	plCMS.SetFillColor(0)
    	plCMS.SetBorderSize(0)
    
    	plCMS.Draw()

    	plPrelim=TPaveLabel(.16,.76,.27,.82,"Preliminary","NBNDC")
    	plPrelim.SetTextSize(0.6)
    	plPrelim.SetTextAlign(12)
    	plPrelim.SetTextFont(52)
    	plPrelim.SetFillColor(0)
    	plPrelim.SetBorderSize(0)
#    	plPrelim.Draw()

    	leg=TLegend(0.420517,0.7,0.85,0.878644,"","brNDC")   
    	legWidth=TLegend(0.625,0.5,0.9,0.7,"width","brNDC")   
#    	leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC")   
    	leg.SetTextSize(0.0425)
    	legWidth.SetTextSize(0.0425)
	colors = {'01':ROOT.kBlue,'03':ROOT.kRed,'05':ROOT.kGreen+3,'10':ROOT.kOrange}
#	for width in sorted(obsLimits):
#		obsGraph = obsLimits[width]
#		if colors.has_key(width):
#			obsGraph.SetLineColor(colors[width])
#		obsGraph.Draw("lsame")
#		if width == '0.006':
#			leg.AddEntry(obsGraph,"Observed 95% CL limit width 0.6%","l")
#		else:	
#			leg.AddEntry(obsGraph,"Observed 95%% CL limit width %d%%"%int(width),"l")
#
#	for width  in sorted(expLimits):
#		expGraph = expLimits[width]
#		if colors.has_key(width):
#			expGraph.SetLineColor(colors[width])
#		expGraph.Draw("lsame")
#		if width == '0.006':
#			leg.AddEntry(expGraph,"Expected 95% CL limit width 0.6%, median","l")
#		else:	
#			leg.AddEntry(expGraph,"Expected 95%% CL limit width %d%%, median"%(int(width)),"l")

	
	for width in sorted(obsLimits):
		obsGraph = obsLimits[width]
		if colors.has_key(width):
			obsGraph.SetLineColor(colors[width])
		obsGraph.Draw("lsame")
		if width == '0.006':
			leg.AddEntry(obsGraph,"Obs. 95% CL limit","l")

	for width  in sorted(expLimits):
		expGraph = expLimits[width]
		if colors.has_key(width):
			expGraph.SetLineColor(colors[width])
		expGraph.Draw("lsame")
		if width == '0.006':
			leg.AddEntry(expGraph,"Exp. 95% CL limit, median","l")
	for width in sorted(obsLimits):
		obsGraph = obsLimits[width]
		if colors.has_key(width):
			obsGraph.SetLineColor(colors[width])
		if width == '0.006':
			legWidth.AddEntry(obsGraph,"0.6%","l")
		else:	
			legWidth.AddEntry(obsGraph,"%d%%"%int(width),"l")


    	if not SPIN2:
        	GraphZPrimeSmooth.Draw("lsame")
        	GraphZPrimePsiSmooth.Draw("lsame")

	leg1=TLegend(0.625,0.35,0.825,0.5,"","brNDC")
	leg1.SetTextSize(0.0375)
	leg1.AddEntry(GraphZPrimeSmooth,"Z'_{SSM} (width 2.97%)","l")	
	leg1.AddEntry(GraphZPrimePsiSmooth,"Z'_{#Psi} (width 0.53%)","l")	
	
    	leg1.SetLineWidth(0)
    	leg1.SetLineStyle(0)
    	leg1.SetLineColor(0)
    	leg1.SetFillStyle(0)
    	leg1.SetBorderSize(0)

	leg1.Draw()

    	cCL.SetTickx(1)
    	cCL.SetTicky(1)
    	cCL.RedrawAxis()
    	cCL.Update()
    
    	#plCMS.Draw()
  	plotPad.SetTicks(1,1)
	plotPad.RedrawAxis()	

	

    	leg.SetLineWidth(0)
    	leg.SetLineStyle(0)
    	leg.SetLineColor(0)
    	leg.Draw("hist")
    	legWidth.SetLineWidth(0)
    	legWidth.SetLineStyle(0)
    	legWidth.SetLineColor(0)
    	legWidth.SetFillStyle(0)
	legWidth.SetNColumns(2)
    	legWidth.Draw("hist")


	if "Moriond" in output:
         	if (chan=="mumu"): 
            		plLumi=TPaveLabel(.65,.885,.9,.99,"36.3 fb^{-1} (13 TeV, #mu^{+}#mu^{-})","NBNDC")
        	elif (chan=="elel"):
            		plLumi=TPaveLabel(.65,.885,.9,.99,"35.9 fb^{-1} (13 TeV, ee)","NBNDC")
        	elif (chan=="elmu"):
            		plLumi=TPaveLabel(.27,.885,.9,.99,"35.9 fb^{-1} (13 TeV, ee) + 36.3 fb^{-1} (13 TeV, #mu^{+}#mu^{-})","NBNDC")
	else:
 	      	if (chan=="mumu"): 
            		plLumi=TPaveLabel(.65,.905,.9,.99,"13.0 fb^{-1} (13 TeV, #mu#mu)","NBNDC")
        	elif (chan=="elel"):
            		plLumi=TPaveLabel(.65,.905,.9,.99,"2.7 fb^{-1} (13 TeV, ee)","NBNDC")
        	elif (chan=="elmu"):
            		plLumi=TPaveLabel(.4,.905,.9,.99,"12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)","NBNDC")

    	plLumi.SetTextSize(0.5)
    	plLumi.SetTextFont(42)
    	plLumi.SetFillColor(0)
    	plLumi.SetBorderSize(0)
    	plLumi.Draw()
    

	plotPad.RedrawAxis()
	for width in sorted(obsLimits):
		obsGraph = obsLimits[width]
		obsGraph.SetName("graphObs%s"%width)
		obsGraph.Write("graphObs%s"%width)
	for width in sorted(expLimits):
		expGraph = expLimits[width]
		expGraph.SetName("graphExp%s"%width)
		expGraph.Write("graphExp%s"%width)


   	fileForHEPData.Write()
	fileForHEPData.Close() 


    
    	cCL.Update()
    	printPlots(cCL,output)
Beispiel #18
0
def makeBiasPlot(output,
                 muFile,
                 chan,
                 interference,
                 printStats=False,
                 obs2="",
                 ratioLabel=""):

    mu = open(muFile, 'r')

    limits = {}
    mux = []
    muy = []
    mu1SigLow = []
    mu1SigHigh = []
    mu2SigLow = []
    mu2SigHigh = []
    for entry in mu:
        massPoint = float(entry.split()[0])
        limitEntry = float(entry.split()[1])
        if massPoint not in limits: limits[massPoint] = []
        limits[massPoint].append(limitEntry)

    if printStats: print "len limits:", len(limits)
    for massPoint in sorted(limits):
        limits[massPoint].sort()
        numLimits = len(limits[massPoint])
        nrExpts = len(limits[massPoint])
        medianNr = int(nrExpts * 0.5)
        #get indexes:
        upper1Sig = int(nrExpts * (1 - (1 - 0.68) * 0.5))
        lower1Sig = int(nrExpts * (1 - 0.68) * 0.5)
        upper2Sig = int(nrExpts * (1 - (1 - 0.95) * 0.5))
        lower2Sig = int(nrExpts * (1 - 0.95) * 0.5)
        if printStats:
            print massPoint, ":", limits[massPoint][lower2Sig], limits[
                massPoint][lower1Sig], limits[massPoint][medianNr], limits[
                    massPoint][upper1Sig], limits[massPoint][upper2Sig]
        #fill lists:
        mux.append(massPoint)
        print massPoint, limits[massPoint][medianNr]
        muy.append(limits[massPoint][medianNr])
        mu1SigLow.append(limits[massPoint][lower1Sig])
        mu1SigHigh.append(limits[massPoint][upper1Sig])
        mu2SigLow.append(limits[massPoint][lower2Sig])
        mu2SigHigh.append(limits[massPoint][upper2Sig])

    muX = numpy.array(mux)
    muY = numpy.array(muy)

    values2 = []
    xPointsForValues2 = []
    values = []
    xPointsForValues = []
    if printStats: print "length of mux: ", len(mux)
    if printStats: print "length of mu1SigLow: ", len(mu1SigLow)
    if printStats: print "length of mu1SigHigh: ", len(mu1SigHigh)

    #Here is some Voodoo via Sam:
    for x in range(0, len(mux)):
        values2.append(mu2SigLow[x])
        xPointsForValues2.append(mux[x])
    for x in range(len(mux) - 1, 0 - 1, -1):
        values2.append(mu2SigHigh[x])
        xPointsForValues2.append(mux[x])
    if printStats: print "length of values2: ", len(values2)

    for x in range(0, len(mux)):
        values.append(mu1SigLow[x])
        xPointsForValues.append(mux[x])
    for x in range(len(mux) - 1, 0 - 1, -1):
        values.append(mu1SigHigh[x])
        xPointsForValues.append(mux[x])
    if printStats: print "length of values: ", len(values)

    mu2Sig = numpy.array(values2)
    xPoints2 = numpy.array(xPointsForValues2)
    mu1Sig = numpy.array(values)
    xPoints = numpy.array(xPointsForValues)
    if printStats: print "xPoints2: ", xPoints2
    if printStats: print "mu2Sig: ", mu2Sig
    if printStats: print "xPoints: ", xPoints
    if printStats: print "mu1Sig: ", mu1Sig
    GraphErr2Sig = TGraphAsymmErrors(len(xPoints), xPoints2, mu2Sig)
    GraphErr2Sig.SetFillColor(ROOT.kYellow + 1)
    GraphErr1Sig = TGraphAsymmErrors(len(xPoints), xPoints, mu1Sig)
    GraphErr1Sig.SetFillColor(ROOT.kGreen)

    cCL = TCanvas("cCL", "cCL", 0, 0, 800, 500)
    gStyle.SetOptStat(0)

    plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
    plotPad.Draw()
    plotPad.cd()

    muX = numpy.array(mux)
    muY = numpy.array(muy)
    GraphMU = TGraph(len(muX), muX, muY)
    GraphMU.SetLineWidth(3)
    GraphMU.SetLineStyle(2)
    GraphMU.SetLineColor(ROOT.kBlue)

    #Draw the graphs:
    DummyGraph = TH1F("DummyGraph", "", 100, 10, 40)
    DummyGraph.GetXaxis().SetTitle("#Lambda [TeV]")
    DummyGraph.GetYaxis().SetTitle("#hat{#mu}")
    gStyle.SetOptStat(0)
    if "Des" in output:
        DummyGraph.GetXaxis().SetRangeUser(10, 28)
    else:
        DummyGraph.GetXaxis().SetRangeUser(10, 40)

    DummyGraph.SetMinimum(-2)
    DummyGraph.SetMaximum(10)
    DummyGraph.GetXaxis().SetLabelSize(0.04)
    DummyGraph.GetXaxis().SetTitleSize(0.045)
    DummyGraph.GetXaxis().SetTitleOffset(1.)
    DummyGraph.GetYaxis().SetLabelSize(0.04)
    DummyGraph.GetYaxis().SetTitleSize(0.045)
    DummyGraph.GetYaxis().SetTitleOffset(1.)
    DummyGraph.Draw()
    DummyGraph.SetLineColor(ROOT.kWhite)
    if (FULL):
        GraphErr2Sig.Draw("F")
        GraphErr1Sig.Draw("F")
        GraphMU.Draw("lpsame")
    else:
        GraphMU.Draw("lp")
    plCMS = TPaveLabel(.12, .81, .22, .88, "CMS", "NBNDC")
    #plCMS.SetTextSize(0.8)
    plCMS.SetTextAlign(12)
    plCMS.SetTextFont(62)
    plCMS.SetFillColor(0)
    plCMS.SetFillStyle(0)
    plCMS.SetBorderSize(0)

    plCMS.Draw()

    plPrelim = TPaveLabel(.12, .76, .25, .82, "Preliminary", "NBNDC")
    plPrelim.SetTextSize(0.6)
    plPrelim.SetTextAlign(12)
    plPrelim.SetTextFont(52)
    plPrelim.SetFillColor(0)
    plPrelim.SetFillStyle(0)
    plPrelim.SetBorderSize(0)
    plPrelim.Draw()

    cCL.SetTickx(1)
    cCL.SetTicky(1)
    cCL.RedrawAxis()
    cCL.Update()

    #leg=TLegend(0.65,0.65,0.87,0.87,"","brNDC")
    leg = TLegend(0.540517, 0.623051, 0.834885, 0.878644, "", "brNDC")
    #    	leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC")
    leg.SetTextSize(0.032)
    leg.AddEntry(GraphMU, "median value", "l")
    if (FULL):
        leg.AddEntry(GraphErr1Sig, "1#sigma quantile", "f")
        leg.AddEntry(GraphErr2Sig, "2#sigma quantile", "f")

    leg.SetLineWidth(0)
    leg.SetLineStyle(0)
    leg.SetFillStyle(0)
    leg.SetLineColor(0)
    leg.Draw("hist")

    if "Moriond" in output:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "36.3 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "35.9 fb^{-1} (13 TeV, ee)", "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "35.9 fb^{-1} (13 TeV, ee) + 36.3 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")
    else:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "13.0 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99, "2.7 fb^{-1} (13 TeV, ee)",
                                "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")

    plLumi.SetTextSize(0.5)
    plLumi.SetTextFont(42)
    plLumi.SetFillColor(0)
    plLumi.SetBorderSize(0)
    plLumi.Draw()
    maxX = 40
    if "Des" in output:
        maxX = 28
    line = ROOT.TLine(10, 0, maxX, 0)
    if "mu1" in output:
        line = ROOT.TLine(10, 1, maxX, 1)
    line.SetLineStyle(ROOT.kDashed)
    line.Draw("same")

    plotPad.RedrawAxis()

    cCL.Update()
    printPlots(cCL, output)
Beispiel #19
0
#
# This macro displays the ROOT Directory data structure
#

from ROOT import TCanvas, TPaveLabel, TPaveText, TText, TArrow, TLine
from ROOT import gROOT

gROOT.Reset()

c1 = TCanvas('c1', 'ROOT FilDir description', 700, 900)
c1.Range(1, 1, 19, 24.5)

title = TPaveLabel(4, 23, 16, 24.2, 'ROOT File/Directory/Key description')
title.SetFillColor(16)
title.Draw()

keycolor = 42
dircolor = 21
objcolor = 46
file = TPaveText(2, 19, 6, 22)
file.SetFillColor(39)
file.Draw()
file.SetTextSize(0.04)
file.AddText('TFile')
file.AddText('Header')
arrow = TArrow(6, 20.5, 17, 20.5, 0.02, '|>')
arrow.SetFillStyle(1001)
arrow.SetLineWidth(2)
arrow.Draw()
free = TPaveText(8, 20, 11, 21)
free.SetFillColor(18)
Beispiel #20
0
def MakeOneDHist(pathToDir, distribution):

    numFittingSamples = 0

    HeaderLabel = TPaveLabel(header_x_left, header_y_bottom, header_x_right,
                             header_y_top, HeaderText, "NDC")
    HeaderLabel.SetTextAlign(32)
    HeaderLabel.SetBorderSize(0)
    HeaderLabel.SetFillColor(0)
    HeaderLabel.SetFillStyle(0)

    LumiLabel = TPaveLabel(topLeft_x_left, topLeft_y_bottom, topLeft_x_right,
                           topLeft_y_top, LumiText, "NDC")
    LumiLabel.SetBorderSize(0)
    LumiLabel.SetFillColor(0)
    LumiLabel.SetFillStyle(0)

    NormLabel = TPaveLabel()
    NormLabel.SetDrawOption("NDC")
    NormLabel.SetX1NDC(topLeft_x_left)
    NormLabel.SetX2NDC(topLeft_x_right)

    NormLabel.SetBorderSize(0)
    NormLabel.SetFillColor(0)
    NormLabel.SetFillStyle(0)

    NormText = ""
    if arguments.normalizeToUnitArea:
        NormText = "Scaled to unit area"
    elif arguments.normalizeToData:
        NormText = "MC scaled to data"
        NormLabel.SetLabel(NormText)

    YieldsLabel = TPaveText(0.39, 0.7, 0.59, 0.9, "NDC")
    YieldsLabel.SetBorderSize(0)
    YieldsLabel.SetFillColor(0)
    YieldsLabel.SetFillStyle(0)
    YieldsLabel.SetTextAlign(12)

    RatiosLabel = TPaveText()
    RatiosLabel.SetDrawOption("NDC")
    RatiosLabel.SetBorderSize(0)
    RatiosLabel.SetFillColor(0)
    RatiosLabel.SetFillStyle(0)
    RatiosLabel.SetTextAlign(32)

    Legend = TLegend()
    Legend.SetBorderSize(0)
    Legend.SetFillColor(0)
    Legend.SetFillStyle(0)

    fittingIntegral = 0
    scaleFactor = 1

    HistogramsToFit = []
    TargetDataset = distribution['target_dataset']

    FittingLegendEntries = []
    DataLegendEntries = []

    FittingHistogramDatasets = []

    Stack_list = []
    Stack_list.append(THStack("stack_before", distribution['name']))
    Stack_list.append(THStack("stack_after", distribution['name']))

    fileName = condor_dir + "/" + distribution['target_dataset'] + ".root"
    if not os.path.exists(fileName):
        return
    inputFile = TFile(fileName)
    if inputFile.IsZombie() or not inputFile.GetNkeys():
        return

    Target = inputFile.Get("OSUAnalysis/" + distribution['channel'] + "/" +
                           distribution['name']).Clone()
    Target.SetDirectory(0)
    inputFile.Close()

    Target.SetMarkerStyle(20)
    Target.SetMarkerSize(0.8)
    Target.SetFillStyle(0)
    Target.SetLineColor(colors[TargetDataset])
    Target.SetLineStyle(1)
    Target.SetLineWidth(2)
    targetIntegral = Target.Integral()
    if (arguments.normalizeToUnitArea and Target.Integral() > 0):
        Target.Scale(1. / Target.Integral())
    if arguments.rebinFactor:
        RebinFactor = int(arguments.rebinFactor)
        #don't rebin histograms which will have less than 5 bins or any gen-matching histograms
        if Target.GetNbinsX() >= RebinFactor * 5 and Target.GetName().find(
                "GenMatch") is -1:
            Target.Rebin(RebinFactor)

    ### formatting target histogram and adding to legend
    legendIndex = 0
    Legend.AddEntry(Target, labels[TargetDataset], "LEP")
    legendIndex = legendIndex + 1

    if not outputFile.Get("OSUAnalysis"):
        outputFile.mkdir("OSUAnalysis")
    if not outputFile.Get("OSUAnalysis/" + distribution['channel']):
        outputFile.Get("OSUAnalysis").mkdir(distribution['channel'])

    for sample in distribution[
            'datasets']:  # loop over different samples requested to be fit

        dataset_file = "%s/%s.root" % (condor_dir, sample)
        inputFile = TFile(dataset_file)
        HistogramObj = inputFile.Get(pathToDir + "/" +
                                     distribution['channel'] + "/" +
                                     distribution['name'])
        if not HistogramObj:
            print "WARNING:  Could not find histogram " + pathToDir + "/" + distribution[
                'channel'] + "/" + distribution[
                    'name'] + " in file " + dataset_file + ".  Will skip it and continue."
            continue
        Histogram = HistogramObj.Clone()
        Histogram.SetDirectory(0)
        inputFile.Close()
        if arguments.rebinFactor:
            RebinFactor = int(arguments.rebinFactor)
            #don't rebin histograms which will have less than 5 bins or any gen-matching histograms
            if Histogram.GetNbinsX() >= RebinFactor * 5 and Histogram.GetName(
            ).find("GenMatch") is -1:
                Histogram.Rebin(RebinFactor)

        xAxisLabel = Histogram.GetXaxis().GetTitle()
        unitBeginIndex = xAxisLabel.find("[")
        unitEndIndex = xAxisLabel.find("]")

        if unitBeginIndex is not -1 and unitEndIndex is not -1:  #x axis has a unit
            yAxisLabel = "Entries / " + str(Histogram.GetXaxis().GetBinWidth(
                1)) + " " + xAxisLabel[unitBeginIndex + 1:unitEndIndex]
        else:
            yAxisLabel = "Entries per bin (" + str(
                Histogram.GetXaxis().GetBinWidth(1)) + " width)"

        if not arguments.makeFancy:
            histoTitle = Histogram.GetTitle()
        else:
            histoTitle = ""

        legLabel = labels[sample]
        if (arguments.printYields):
            yieldHist = Histogram.Integral()
            legLabel = legLabel + " (%.1f)" % yieldHist
        FittingLegendEntries.append(legLabel)

        if (types[sample] == "bgMC"):

            numFittingSamples += 1
            fittingIntegral += Histogram.Integral()

            Histogram.SetLineStyle(1)
            if (arguments.noStack):
                Histogram.SetFillStyle(0)
                Histogram.SetLineColor(colors[sample])
                Histogram.SetLineWidth(2)
            else:
                Histogram.SetFillStyle(1001)
                Histogram.SetFillColor(colors[sample])
                Histogram.SetLineColor(1)
                Histogram.SetLineWidth(1)

        elif (types[sample] == "signalMC"):

            numFittingSamples += 1

            Histogram.SetFillStyle(0)
            Histogram.SetLineColor(colors[sample])
            Histogram.SetLineStyle(1)
            Histogram.SetLineWidth(2)
        if (arguments.normalizeToUnitArea and Histogram.Integral() > 0):
            Histogram.Scale(1. / Histogram.Integral())

        HistogramsToFit.append(Histogram)
        FittingHistogramDatasets.append(sample)

    #scaling histograms as per user's specifications
    if targetIntegral > 0 and fittingIntegral > 0:
        scaleFactor = targetIntegral / fittingIntegral
    for fittingHist in HistogramsToFit:
        if arguments.normalizeToData:
            fittingHist.Scale(scaleFactor)

        if arguments.normalizeToUnitArea and not arguments.noStack and fittingIntegral > 0:
            fittingHist.Scale(1. / fittingIntegral)
        elif arguments.normalizeToUnitArea and arguments.noStack and fittingHist.Integral(
        ) > 0:
            fittingHist.Scale(1. / fittingHist.Integral())

    def fitf(x, par):
        xBin = HistogramsToFit[0].FindBin(x[0])
        value = 0.0

        for i in range(0, len(HistogramsToFit)):
            value += par[i] * HistogramsToFit[i].GetBinContent(xBin) + par[
                i +
                len(HistogramsToFit)] * HistogramsToFit[i].GetBinError(xBin)

        return value

    lowerLimit = Target.GetBinLowEdge(1)
    upperLimit = Target.GetBinLowEdge(Target.GetNbinsX()) + Target.GetBinWidth(
        Target.GetNbinsX())
    if 'lowerLimit' in distribution:
        lowerLimit = distribution['lowerLimit']
    if 'upperLimit' in distribution:
        upperLimit = distribution['upperLimit']
    func = TF1("fit", fitf, lowerLimit, upperLimit, 2 * len(HistogramsToFit))

    for i in range(0, len(HistogramsToFit)):
        if 'fixed_datasets' in distribution and distribution['datasets'][
                i] in distribution['fixed_datasets']:
            func.FixParameter(i, 1.0)
        else:
            func.SetParameter(i, 1.0)
#            func.SetParLimits (i, 0.0, 1.0e2) # comment this out so we don't have to pre-normalize the QCD input sample
        func.SetParName(i, labels[FittingHistogramDatasets[i]])

    shiftedScaleFactors = []
    if arguments.parametricErrors:
        # loop over all input histograms and shift them +- 1 sigma
        for i in range(0, len(HistogramsToFit)):
            sfs = []

            # -1 => -1 sigma, +1 => +1 sigma
            for j in [-1, 1]:
                # loop over the parameters holding the errors for each dataset, fixing all to 0
                for k in range(len(HistogramsToFit), 2 * len(HistogramsToFit)):
                    func.FixParameter(k, 0)
                # fix the error of the dataset of interest to +-1
                func.FixParameter(i + len(HistogramsToFit), j)

                # perform new fit
                for k in range(0, distribution['iterations'] - 1):
                    if j == -1:
                        print "Scale down " + labels[FittingHistogramDatasets[
                            i]] + " iteration " + str(k + 1) + "..."
                    if j == 1:
                        print "Scale up " + labels[FittingHistogramDatasets[
                            i]] + " iteration " + str(k + 1) + "..."
                    Target.Fit("fit", "QEMR0")
                Target.Fit("fit", "VEMR0")

                # save the new scale factors for each dataset
                for k in range(0, len(HistogramsToFit)):
                    sfs.append(func.GetParameter(k))

            shiftedScaleFactors.append(sfs)

    # reset the parameters with the errors of each dataset to 0
    for i in range(len(HistogramsToFit), 2 * len(HistogramsToFit)):
        func.FixParameter(i, 0)
    # do the fit to get the central values
    for i in range(0, distribution['iterations'] - 1):
        print "Iteration " + str(i + 1) + "..."
        Target.Fit("fit", "QEMR0")
    Target.Fit("fit", "VEMR0")

    if arguments.parametricErrors:
        # make a list of the largest errors on each contribution by shifting any other contribution
        parErrors = []
        # loop over all the datasets
        for i in range(0, len(HistogramsToFit)):
            centralValue = func.GetParameter(i)
            maxError = 0
            # find the maximum deviation from the central value and save that
            for shiftedScaleFactor in shiftedScaleFactors[i]:
                currentError = abs(shiftedScaleFactor - centralValue)
                if currentError > maxError:
                    maxError = currentError

            parErrors.append(maxError)

    finalMax = 0
    if not arguments.noStack:
        for fittingHist in HistogramsToFit:
            finalMax += fittingHist.GetMaximum()
        else:
            for fittingHist in HistogramsToFit:
                if (fittingHist.GetMaximum() > finalMax):
                    finalMax = fittingHist.GetMaximum()
    if (Target.GetMaximum() > finalMax):
        finalMax = Target.GetMaximum()

    Target.SetMaximum(1.1 * finalMax)
    Target.SetMinimum(0.0001)

    Canvas = TCanvas(distribution['name'] + "_FitFunction")
    Canvas.cd(1)
    Target.Draw()
    func.Draw("same")

    outputFile.cd("OSUAnalysis/" + distribution['channel'])
    Canvas.Write()
    if arguments.savePDFs:
        if histogram == input_histograms[0]:
            Canvas.Print(pdfFileName + "(", "pdf")
        else:
            Canvas.Print(pdfFileName, "pdf")
    Target.SetStats(0)

    ### formatting bgMC histograms and adding to legend
    legendIndex = numFittingSamples - 1
    for Histogram in reversed(HistogramsToFit):
        if (arguments.noStack):
            Legend.AddEntry(Histogram, FittingLegendEntries[legendIndex], "L")
        else:
            Legend.AddEntry(Histogram, FittingLegendEntries[legendIndex], "F")
        legendIndex = legendIndex - 1

    ### Drawing histograms to canvas

    makeRatioPlots = arguments.makeRatioPlots
    makeDiffPlots = arguments.makeDiffPlots

    yAxisMin = 0.0001
    if arguments.setYMin:
        yAxisMin = float(arguments.setYMin)

    ### Draw everything to the canvases !!!!

    for i in range(0, 2):  # 0 => before, 1 => after

        integrals = []
        ratios = []
        errors = []

        if i == 1:
            # loop over each dataset, saving it's yield and the errors on it
            for j in range(0, len(HistogramsToFit)):

                integrals.append(HistogramsToFit[j].Integral())
                HistogramsToFit[j].Scale(func.GetParameter(j))
                ratios.append(func.GetParameter(j))
                errors.append(func.GetParError(j))

        for fittingHist in HistogramsToFit:
            if not arguments.noStack:
                Stack_list[i].Add(fittingHist)

        #creating the histogram to represent the statistical errors on the stack
        if not arguments.noStack:
            ErrorHisto = HistogramsToFit[0].Clone("errors")
            ErrorHisto.SetFillStyle(3001)
            ErrorHisto.SetFillColor(13)
            ErrorHisto.SetLineWidth(0)
            if i == 1:
                Legend.AddEntry(ErrorHisto, "Stat. Errors", "F")
            for Histogram in HistogramsToFit:
                if Histogram is not HistogramsToFit[0]:
                    ErrorHisto.Add(Histogram)

        if i == 0:
            Canvas = TCanvas(distribution['name'] + "_Before")
        if i == 1:
            Canvas = TCanvas(distribution['name'] + "_After")

        if makeRatioPlots or makeDiffPlots:
            Canvas.SetFillStyle(0)
            Canvas.Divide(1, 2)
            Canvas.cd(1)
            gPad.SetPad(0, 0.25, 1, 1)
            gPad.SetMargin(0.15, 0.05, 0.01, 0.07)
            gPad.SetFillStyle(0)
            gPad.Update()
            gPad.Draw()
            if arguments.setLogY:
                gPad.SetLogy()
            Canvas.cd(2)
            gPad.SetPad(0, 0, 1, 0.25)
            # format: gPad.SetMargin(l,r,b,t)
            gPad.SetMargin(0.15, 0.05, 0.4, 0.01)
            gPad.SetFillStyle(0)
            gPad.SetGridy(1)
            gPad.Update()
            gPad.Draw()

            Canvas.cd(1)

        ### finding the maximum value of anything going on the canvas, so we know how to set the y-axis
        finalMax = 0
        if numFittingSamples is not 0 and not arguments.noStack:
            finalMax = ErrorHisto.GetMaximum() + ErrorHisto.GetBinError(
                ErrorHisto.GetMaximumBin())
        else:
            for bgMCHist in HistogramsToFit:
                if (bgMCHist.GetMaximum() > finalMax):
                    finalMax = bgMCHist.GetMaximum()
        if (Target.GetMaximum() > finalMax):
            finalMax = Target.GetMaximum() + Target.GetBinError(
                Target.GetMaximumBin())
        finalMax = 1.15 * finalMax
        if arguments.setYMax:
            finalMax = float(arguments.setYMax)

        if not arguments.noStack:  # draw stacked background samples
            Stack_list[i].SetTitle(histoTitle)
            Stack_list[i].Draw("HIST")
            Stack_list[i].GetXaxis().SetTitle(xAxisLabel)
            Stack_list[i].GetYaxis().SetTitle(yAxisLabel)
            Stack_list[i].SetMaximum(finalMax)
            Stack_list[i].SetMinimum(yAxisMin)
            if makeRatioPlots or makeDiffPlots:
                Stack_list[i].GetHistogram().GetXaxis().SetLabelSize(0)
            #draw shaded error bands
            ErrorHisto.Draw("A E2 SAME")

        else:  #draw the unstacked backgrounds
            HistogramsToFit[0].SetTitle(histoTitle)
            HistogramsToFit[0].Draw("HIST")
            HistogramsToFit[0].GetXaxis().SetTitle(xAxisLabel)
            HistogramsToFit[0].GetYaxis().SetTitle(yAxisLabel)
            HistogramsToFit[0].SetMaximum(finalMax)
            HistogramsToFit[0].SetMinimum(yAxisMin)
            for bgMCHist in HistogramsToFit:
                bgMCHist.Draw("A HIST SAME")

        Target.Draw("A E X0 SAME")

        #legend coordinates, empirically determined :-)
        x_left = 0.6761745
        x_right = 0.9328859
        x_width = x_right - x_left
        y_max = 0.9
        entry_height = 0.05

        if (numFittingSamples is not 0):  #then draw the data & bgMC legend

            numExtraEntries = 2  # count the target and (lack of) title
            Legend.SetX1NDC(x_left)
            numExtraEntries = numExtraEntries + 1  # count the stat. errors entry

            Legend.SetY1NDC(y_max - entry_height *
                            (numExtraEntries + numFittingSamples))
            Legend.SetX2NDC(x_right)
            Legend.SetY2NDC(y_max)
            Legend.Draw()

            RatiosLabel.SetX1NDC(x_left - 0.1)
            RatiosLabel.SetX2NDC(x_right)
            RatiosLabel.SetY2NDC(Legend.GetY1NDC() - 0.1)
            RatiosLabel.SetY1NDC(RatiosLabel.GetY2NDC() - entry_height *
                                 (numFittingSamples))

            # Deciding which text labels to draw and drawing them
            drawLumiLabel = False
            drawNormLabel = False
            offsetNormLabel = False
            drawHeaderLabel = False

            if not arguments.normalizeToUnitArea:  #don't draw the lumi label if there's no data and it's scaled to unit area
                drawLumiLabel = True
                # move the normalization label down before drawing if we drew the lumi. label
                offsetNormLabel = True
            if arguments.normalizeToUnitArea or arguments.normalizeToData:
                drawNormLabel = True
            if arguments.makeFancy:
                drawHeaderLabel = True
                drawLumiLabel = False

            # now that flags are set, draw the appropriate labels

            if drawLumiLabel:
                LumiLabel.Draw()

            if drawNormLabel:
                if offsetNormLabel:
                    NormLabel.SetY1NDC(topLeft_y_bottom - topLeft_y_offset)
                    NormLabel.SetY2NDC(topLeft_y_top - topLeft_y_offset)
                else:
                    NormLabel.SetY1NDC(topLeft_y_bottom)
                    NormLabel.SetY2NDC(topLeft_y_top)
                NormLabel.Draw()

            if drawHeaderLabel:
                HeaderLabel.Draw()

            YieldsLabel.Clear()
            mcYield = Stack_list[i].GetStack().Last().Integral()
            dataYield = Target.Integral()
            if i == 0:
                YieldsLabel.AddText("Before Fit to Data")
            if i == 1:
                YieldsLabel.AddText("After Fit to Data")
            YieldsLabel.AddText("data yield: " + '%.1f' % dataYield)
            YieldsLabel.AddText("bkgd yield: " + '%.1f' % mcYield)
            YieldsLabel.AddText("data/bkgd: " + '%.2f' % (dataYield / mcYield))
            if i == 1:
                for j in range(0, len(FittingLegendEntries)):
                    if abs(ratios[j] - 1) < 0.001 and abs(
                            errors[j]
                    ) < 0.001:  #then it probably was held fixed
                        continue
                    if arguments.showFittedYields:
                        yield_ = ratios[j] * integrals[j]
                        yielderror_ = errors[j] * yield_
                        text = FittingLegendEntries[
                            j] + " yield: " + '%.0f' % yield_ + ' #pm %.0f' % yielderror_
                    else:
                        text = FittingLegendEntries[
                            j] + " ratio: " + '%.2f' % ratios[
                                j] + ' #pm %.2f' % errors[j]
                    text = text + " (fit)"
                    if arguments.parametricErrors:
                        yield_ = ratios[j] * integrals[j]
                        yieldParError_ = parErrors[j] * yield_
                        if arguments.showFittedYields:
                            text += ' #pm %.2f' % yieldParError_
                        else:
                            text += ' #pm %.2f' % parErrors[j]
                        text = text + " (sys)"
                    RatiosLabel.AddText(text)
            YieldsLabel.Draw()
            RatiosLabel.Draw()

        # drawing the ratio or difference plot if requested
        if (makeRatioPlots or makeDiffPlots):
            Canvas.cd(2)
            BgSum = Stack_list[i].GetStack().Last()
            if makeRatioPlots:
                if arguments.ratioRelErrMax:
                    Comparison = ratioHistogram(Target, BgSum,
                                                arguments.ratioRelErrMax)
                else:
                    Comparison = ratioHistogram(Target, BgSum)
            elif makeDiffPlots:
                Comparison = Target.Clone("diff")
                Comparison.Add(BgSum, -1)
                Comparison.SetTitle("")
                Comparison.GetYaxis().SetTitle("Data-Bkgd")
            Comparison.GetXaxis().SetTitle(xAxisLabel)
            Comparison.GetYaxis().CenterTitle()
            Comparison.GetYaxis().SetTitleSize(0.1)
            Comparison.GetYaxis().SetTitleOffset(0.5)
            Comparison.GetXaxis().SetTitleSize(0.15)
            Comparison.GetYaxis().SetLabelSize(0.1)
            Comparison.GetXaxis().SetLabelSize(0.15)
            if makeRatioPlots:
                RatioYRange = 1.15
                if arguments.ratioYRange:
                    RatioYRange = float(arguments.ratioYRange)
                Comparison.GetYaxis().SetRangeUser(-1 * RatioYRange,
                                                   RatioYRange)
            elif makeDiffPlots:
                YMax = Comparison.GetMaximum()
                YMin = Comparison.GetMinimum()
                if YMax <= 0 and YMin <= 0:
                    Comparison.GetYaxis().SetRangeUser(-1.2 * YMin, 0)
                elif YMax >= 0 and YMin >= 0:
                    Comparison.GetYaxis().SetRangeUser(0, 1.2 * YMax)
                else:  #axis crosses y=0
                    if abs(YMax) > abs(YMin):
                        Comparison.GetYaxis().SetRangeUser(
                            -1.2 * YMax, 1.2 * YMax)
                    else:
                        Comparison.GetYaxis().SetRangeUser(
                            -1.2 * YMin, 1.2 * YMin)

            Comparison.GetYaxis().SetNdivisions(205)
            Comparison.Draw("E0")

        if i == 0:
            Canvas.Write(distribution['name'] + "_Before")
            if arguments.savePDFs:
                pathToDirString = plainTextString(pathToDir)
                Canvas.SaveAs(condor_dir + "/fitting_histogram_pdfs/" +
                              pathToDirString + "/" + distribution['name'] +
                              "_Before.pdf")

        if i == 1:
            Canvas.Write(distribution['name'] + "_After")
            if arguments.savePDFs:
                pathToDirString = plainTextString(pathToDir)
                Canvas.SaveAs(condor_dir + "/fitting_histogram_pdfs/" +
                              pathToDirString + "/" + distribution['name'] +
                              "_After.pdf")
def makeLimitPlot(output,
                  obs,
                  exp,
                  chan,
                  printStats=False,
                  obs2="",
                  ratioLabel=""):

    fileObs = open(obs, 'r')
    fileExp = open(exp, 'r')

    observedx = []
    observedy = []
    obsLimits = {}
    for entry in fileObs:
        massPoint = float(entry.split()[0])
        limitEntry = float(entry.split()[1])
        if massPoint not in obsLimits: obsLimits[massPoint] = []
        obsLimits[massPoint].append(limitEntry)
    if printStats: print "len obsLimits:", len(obsLimits)
    for massPoint in sorted(obsLimits):
        observedx.append(massPoint)
        observedy.append(numpy.mean(obsLimits[massPoint]))
        if (numpy.std(obsLimits[massPoint]) / numpy.mean(obsLimits[massPoint])
                > 0.05):
            print massPoint, " mean: ", numpy.mean(
                obsLimits[massPoint]), " std dev: ", numpy.std(
                    obsLimits[massPoint]), " from: ", obsLimits[massPoint]

    if not obs2 == "":
        fileObs2 = open(obs2, 'r')

        observedx2 = []
        observedy2 = []
        obsLimits2 = {}
        for entry in fileObs2:
            massPoint = float(entry.split()[0])
            limitEntry = float(entry.split()[1])
            if massPoint not in obsLimits2: obsLimits2[massPoint] = []
            obsLimits2[massPoint].append(limitEntry)
        if printStats: print "len obsLimits:", len(obsLimits2)
        for massPoint in sorted(obsLimits2):
            observedx2.append(massPoint)
            observedy2.append(numpy.mean(obsLimits2[massPoint]))
            if (numpy.std(obsLimits2[massPoint]) /
                    numpy.mean(obsLimits2[massPoint]) > 0.05):
                print massPoint, " mean: ", numpy.mean(
                    obsLimits2[massPoint]), " std dev: ", numpy.std(
                        obsLimits2[massPoint]
                    ), " from: ", obsLimits2[massPoint]

    limits = {}
    expectedx = []
    expectedy = []
    expected1SigLow = []
    expected1SigHigh = []
    expected2SigLow = []
    expected2SigHigh = []
    for entry in fileExp:
        massPoint = float(entry.split()[0])
        limitEntry = float(entry.split()[1])
        if massPoint not in limits: limits[massPoint] = []
        limits[massPoint].append(limitEntry)

    if printStats: print "len limits:", len(limits)
    for massPoint in sorted(limits):
        limits[massPoint].sort()
        numLimits = len(limits[massPoint])
        nrExpts = len(limits[massPoint])
        medianNr = int(nrExpts * 0.5)
        #get indexes:
        upper1Sig = int(nrExpts * (1 - (1 - 0.68) * 0.5))
        lower1Sig = int(nrExpts * (1 - 0.68) * 0.5)
        upper2Sig = int(nrExpts * (1 - (1 - 0.95) * 0.5))
        lower2Sig = int(nrExpts * (1 - 0.95) * 0.5)
        if printStats:
            print massPoint, ":", limits[massPoint][lower2Sig], limits[
                massPoint][lower1Sig], limits[massPoint][medianNr], limits[
                    massPoint][upper1Sig], limits[massPoint][upper2Sig]
        #fill lists:
        expectedx.append(massPoint)
        expectedy.append(limits[massPoint][medianNr])
        expected1SigLow.append(limits[massPoint][lower1Sig])
        expected1SigHigh.append(limits[massPoint][upper1Sig])
        expected2SigLow.append(limits[massPoint][lower2Sig])
        expected2SigHigh.append(limits[massPoint][upper2Sig])

    expX = numpy.array(expectedx)
    expY = numpy.array(expectedy)

    values2 = []
    xPointsForValues2 = []
    values = []
    xPointsForValues = []
    if printStats: print "length of expectedx: ", len(expectedx)
    if printStats: print "length of expected1SigLow: ", len(expected1SigLow)
    if printStats: print "length of expected1SigHigh: ", len(expected1SigHigh)

    #Here is some Voodoo via Sam:
    for x in range(0, len(expectedx)):
        values2.append(expected2SigLow[x])
        xPointsForValues2.append(expectedx[x])
    for x in range(len(expectedx) - 1, 0 - 1, -1):
        values2.append(expected2SigHigh[x])
        xPointsForValues2.append(expectedx[x])
    if printStats: print "length of values2: ", len(values2)

    for x in range(0, len(expectedx)):
        values.append(expected1SigLow[x])
        xPointsForValues.append(expectedx[x])
    for x in range(len(expectedx) - 1, 0 - 1, -1):
        values.append(expected1SigHigh[x])
        xPointsForValues.append(expectedx[x])
    if printStats: print "length of values: ", len(values)

    exp2Sig = numpy.array(values2)
    xPoints2 = numpy.array(xPointsForValues2)
    exp1Sig = numpy.array(values)
    xPoints = numpy.array(xPointsForValues)
    if printStats: print "xPoints2: ", xPoints2
    if printStats: print "exp2Sig: ", exp2Sig
    if printStats: print "xPoints: ", xPoints
    if printStats: print "exp1Sig: ", exp1Sig
    GraphErr2Sig = TGraphAsymmErrors(len(xPoints), xPoints2, exp2Sig)
    GraphErr2Sig.SetFillColor(ROOT.kYellow + 1)
    GraphErr1Sig = TGraphAsymmErrors(len(xPoints), xPoints, exp1Sig)
    GraphErr1Sig.SetFillColor(ROOT.kGreen)

    cCL = TCanvas("cCL", "cCL", 0, 0, 800, 500)
    gStyle.SetOptStat(0)

    if not obs2 == "":
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1)
        ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3)
        plotPad.Draw()
        ratioPad.Draw()
        plotPad.cd()
    else:
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
        plotPad.Draw()
        plotPad.cd()

    expX = numpy.array(expectedx)
    expY = numpy.array(expectedy)
    GraphExp = TGraph(len(expX), expX, expY)
    GraphExp.SetLineWidth(3)
    GraphExp.SetLineStyle(2)
    GraphExp.SetLineColor(ROOT.kBlue)

    obsX = numpy.array(observedx)
    obsY = numpy.array(observedy)
    if printStats: print "obsX: ", obsX
    if printStats: print "obsY: ", obsY

    if SMOOTH:
        smooth_obs = TGraphSmooth("normal")
        GraphObs_nonSmooth = TGraph(len(obsX), obsX, obsY)
        GraphObs = smooth_obs.SmoothSuper(GraphObs_nonSmooth, "linear", 0,
                                          0.005)
    else:
        GraphObs = TGraph(len(obsX), obsX, obsY)

    GraphObs.SetLineWidth(3)
    if not obs2 == "":

        ratio = []
        ratiox = []
        for index, val in enumerate(observedy):
            mass = observedx[index]
            foundIndex = -1
            for index2, mass2 in enumerate(observedx2):
                if mass == mass2:
                    foundIndex = index2

            if foundIndex > 0:
                ratio.append(observedy2[foundIndex] / val)
                ratiox.append(mass)
        ratioA = numpy.array(ratio)
        ratioX = numpy.array(ratiox)
        obsX2 = numpy.array(observedx2)
        obsY2 = numpy.array(observedy2)
        ratioGraph = TGraph(len(ratioX), ratioX, ratioA)
        if printStats: print "obsX2: ", obsX2
        if printStats: print "obsY2: ", obsY2

        if SMOOTH:
            smooth_obs2 = TGraphSmooth("normal")
            GraphObs2_nonSmooth = TGraph(len(obsX2), obsX2, obsY2)
            GraphObs2 = smooth_obs2.SmoothSuper(GraphObs2_nonSmooth, "linear",
                                                0, 0.005)
        else:
            GraphObs2 = TGraph(len(obsX2), obsX2, obsY2)

        GraphObs2.SetLineWidth(3)
    smoother = TGraphSmooth("normal")
    smoother2 = TGraphSmooth("normal")

    zprimeX = []
    zprimeY = []
    fileZPrime = open('tools/xsec_SSM.txt', 'r')
    for entries in fileZPrime:
        entry = entries.split()
        zprimeX.append(float(entry[0]))
        zprimeY.append(float(entry[1]) * 1.3 / 1928)
    zpX = numpy.array(zprimeX)
    zpY = numpy.array(zprimeY)
    GraphZPrime = TGraph(481, zpX, zpY)
    GraphZPrimeSmooth = smoother2.SmoothSuper(GraphZPrime, "linear")
    GraphZPrimeSmooth.SetLineWidth(3)
    GraphZPrimeSmooth.SetLineColor(ROOT.kGreen + 3)
    GraphZPrimeSmooth.SetLineStyle(2)

    zprimePsiX = []
    zprimePsiY = []
    fileZPrimePsi = open('tools/xsec_PSI.txt', 'r')
    for entries in fileZPrimePsi:
        entry = entries.split()
        zprimePsiX.append(float(entry[0]))
        zprimePsiY.append(float(entry[1]) * 1.3 / 1928)
    zpPsiX = numpy.array(zprimePsiX)
    zpPsiY = numpy.array(zprimePsiY)
    GraphZPrimePsi = TGraph(481, zpPsiX, zpPsiY)
    GraphZPrimePsiSmooth = smoother.SmoothSuper(GraphZPrimePsi, "linear")
    GraphZPrimePsiSmooth.SetLineWidth(3)
    GraphZPrimePsiSmooth.SetLineColor(ROOT.kBlue)

    #Draw the graphs:
    plotPad.SetLogy()
    if "Moriond" in output:
        DummyGraph = TH1F("DummyGraph", "", 100, 120, 4500)
    else:
        DummyGraph = TH1F("DummyGraph", "", 100, 400, 4500)
    DummyGraph.GetXaxis().SetTitle("M [GeV]")
    if chan == "mumu":
        DummyGraph.GetYaxis().SetTitle(
            "#sigma(pp#rightarrowZ'+X#rightarrow#mu#mu+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu#mu+X)"
        )
    elif chan == "elel":
        DummyGraph.GetYaxis().SetTitle(
            "#sigma(pp#rightarrowZ'+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)"
        )
    elif chan == "elmu":
        DummyGraph.GetYaxis().SetTitle(
            "#sigma(pp#rightarrowZ'+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)"
        )

    gStyle.SetOptStat(0)
    if "Moriond" in output:
        DummyGraph.GetXaxis().SetRangeUser(120, 4500)
    else:
        DummyGraph.GetXaxis().SetRangeUser(400, 4500)

    DummyGraph.SetMinimum(1e-8)
    DummyGraph.SetMaximum(4e-4)
    DummyGraph.GetXaxis().SetLabelSize(0.04)
    DummyGraph.GetXaxis().SetTitleSize(0.045)
    DummyGraph.GetXaxis().SetTitleOffset(1.)
    DummyGraph.GetYaxis().SetLabelSize(0.04)
    DummyGraph.GetYaxis().SetTitleSize(0.045)
    DummyGraph.GetYaxis().SetTitleOffset(1.)
    DummyGraph.Draw()
    if (FULL):
        GraphErr2Sig.Draw("F")
        GraphErr1Sig.Draw("F")
        GraphExp.Draw("lpsame")
    else:
        if obs2 == "":
            GraphExp.Draw("lp")

    GraphObs.Draw("plsame")
    if not obs2 == "":
        GraphObs2.SetLineColor(ROOT.kRed)
        GraphObs2.SetLineStyle(ROOT.kDashed)
        GraphObs2.Draw("plsame")
    if not SPIN2:
        GraphZPrimeSmooth.Draw("lsame")
        GraphZPrimePsiSmooth.Draw("lsame")

    cCL.SetTickx(1)
    cCL.SetTicky(1)
    cCL.RedrawAxis()
    cCL.Update()

    #leg=TLegend(0.65,0.65,0.87,0.87,"","brNDC")
    leg = TLegend(0.540517, 0.623051, 0.834885, 0.878644, "", "brNDC")
    #    	leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC")
    leg.SetTextSize(0.032)
    if not obs2 == "":
        if ratioLabel == "":
            ratioLabel = "Variant/Default"
        ratioLabels = ratioLabel.split("/")

        leg.AddEntry(GraphObs, "% Observed 95% CL limit" % ratioLabel[1], "l")
        leg.AddEntry(GraphObs2, "%s Observed 95% CL limit" % ratioLabel[0],
                     "l")

    else:
        leg.AddEntry(GraphObs, "Observed 95% CL limit", "l")
        leg.AddEntry(GraphExp, "Expected 95% CL limit, median", "l")
        if (FULL):
            leg.AddEntry(GraphErr1Sig, "Expected 95% CL limit, 1 s.d.", "f")
            leg.AddEntry(GraphErr2Sig, "Expected 95% CL limit, 2 s.d.", "f")

    leg1 = TLegend(0.665517, 0.483051, 0.834885, 0.623051, "", "brNDC")
    leg1.SetTextSize(0.032)

    if not SPIN2:
        leg1.AddEntry(GraphZPrimePsiSmooth, "Z'_{#Psi} (LOx1.3)", "l")
        leg1.AddEntry(GraphZPrimeSmooth, "Z'_{SSM} (LOx1.3)", "l")

    leg.SetLineWidth(0)
    leg.SetLineStyle(0)
    leg.SetLineColor(0)
    leg.Draw("hist")

    leg1.SetLineWidth(0)
    leg1.SetLineStyle(0)
    leg1.SetLineColor(0)
    leg1.Draw("hist")
    if "Moriond" in output:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "36.3 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99, "2.7 fb^{-1} (13 TeV, ee)",
                                "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")
    else:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "13.0 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99, "2.7 fb^{-1} (13 TeV, ee)",
                                "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")

    plLumi.SetTextSize(0.5)
    plLumi.SetTextFont(42)
    plLumi.SetFillColor(0)
    plLumi.SetBorderSize(0)
    plLumi.Draw()

    plCMS = TPaveLabel(.12, .81, .22, .88, "CMS", "NBNDC")
    #plCMS.SetTextSize(0.8)
    plCMS.SetTextAlign(12)
    plCMS.SetTextFont(62)
    plCMS.SetFillColor(0)
    plCMS.SetBorderSize(0)

    plCMS.Draw()

    plPrelim = TPaveLabel(.12, .76, .25, .82, "Preliminary", "NBNDC")
    plPrelim.SetTextSize(0.6)
    plPrelim.SetTextAlign(12)
    plPrelim.SetTextFont(52)
    plPrelim.SetFillColor(0)
    plPrelim.SetBorderSize(0)
    plPrelim.Draw()

    if not obs2 == "":

        ratioPad.cd()

        line = ROOT.TLine(400, 1, 4500, 1)
        line.SetLineStyle(ROOT.kDashed)

        ROOT.gStyle.SetTitleSize(0.12, "Y")
        ROOT.gStyle.SetTitleYOffset(0.35)
        ROOT.gStyle.SetNdivisions(000, "Y")
        ROOT.gStyle.SetNdivisions(408, "Y")
        ratioPad.DrawFrame(400, 0.9, 4500, 1.1, "; ; %s" % ratioLabel)

        line.Draw("same")

        ratioGraph.Draw("sameP")

    cCL.Update()
    printPlots(cCL, output)
def MakeOneHist(varXaxis, varConst, xvalues, constval):

    if len(xvalues)<=1:
        return # Do not make plot if there is only 1 xvalue
    Legend = TLegend()
    Legend.SetBorderSize(0)
    Legend.SetFillColor(0)
    Legend.SetFillStyle(0)
    Canvas = TCanvas("sigEff_"+varConst+str(constval)+"_vs_"+varXaxis)
    Histograms = []
    LegendEntries = []
    colorIndex = 0
    for source in input_sources: # loop over different input sources in config file
#        print "Debug:  running over input_source from: ", source['condor_dir'], " for varXaxis=", varXaxis, ", varConst=", varConst

        # Create histogram of efficiencies with appropriate binning
        xAxisBins = array('d')
        xBinWidth = xvalues[1] - xvalues[0]
        for xval in xvalues:
            xAxisBins.append(xval - xBinWidth/2.0)
        xAxisBins.append(xvalues[-1] + xBinWidth/2.0)   # add an extra bin boundary for the last bin.

        Histogram = TH1F("Histogram", ";x title;signal efficiency", len(xvalues), xAxisBins)
        Histogram.SetDirectory(0)

        # Now fill the histogram of efficiencies:
        for xval in xvalues:
            if   varXaxis=="mass" and varConst=="lifetime":
                mass = xval
                lifetime = constval
            elif varXaxis=="lifetime" and varConst=="mass":
                lifetime = xval
                mass = constval
            else:
                print "Unrecognized value of varXaxis=", varXaxis
                return
            dataset_file = "condor/%s/%s.root" % (source['condor_dir'],dataset)
            dataset_file = dataset_file.replace("MASS",     str(mass))
            dataset_file = dataset_file.replace("LIFETIME", str(lifetime))
            inputFile = TFile(dataset_file)
            HistCutflow = inputFile.Get("OSUAnalysis/" + source['channel'] + "CutFlow")
            if not HistCutflow:
                print "WARNING: Could not find histogram OSUAnalysis/" + source['channel'] + "CutFlow in file " + dataset_file + ". Will skip it and continue."
                return

            # calculate efficiency
            nbinsCutflow = HistCutflow.GetNbinsX()
            if arguments.xsecFile:
                xsec = float(signal_cross_sections[str(mass)]['value'])
                denom = xsec * intLumi
            else:
                denom = HistCutflow.GetBinContent(1)  # denominator is the first entry in the cutflow histogram
            eff    = HistCutflow.GetBinContent(nbinsCutflow) / denom
            effErr = HistCutflow.GetBinError  (nbinsCutflow) / denom
            ibin = Histogram.FindBin(xval)
            Histogram.SetBinContent(ibin, eff)
            Histogram.SetBinError  (ibin, effErr)
            print "Setting bin content for varConst = ", varConst, " = ", constval, " in ibin=", ibin, ", xval=", xval, ", eff=", eff, " +- ", effErr, ", fractional error =", effErr/eff, " numerator = ", HistCutflow.GetBinContent(nbinsCutflow), " denom = ", denom, " from file: ", dataset_file
            inputFile.Close()

        if varXaxis=="mass":
            xAxisLabel = "chargino mass [GeV]"
        elif varXaxis=="lifetime":
            xAxisLabel = "chargino c#tau [cm]"
        else:
            print "Unrecognized value of varXaxis=", varXaxis
            return

        yAxisLabel = "efficiency"

        if 'color' in source:
            Histogram.SetMarkerColor(colors[source['color']])
            Histogram.SetLineColor(colors[source['color']])
        else:
            Histogram.SetMarkerColor(colors[colorList[colorIndex]])
            Histogram.SetLineColor(colors[colorList[colorIndex]])
            colorIndex = colorIndex + 1
            if colorIndex is len(colorList):
                colorIndex = 0
        markerStyle = 20
        if 'marker' in source:
            markerStyle = markers[source['marker']]
        if 'fill' in source:
            markerStyle = markerStyle + fills[source['fill']]
        Histogram.SetMarkerStyle(markerStyle)
        Histogram.SetMarkerSize(1)
#        Histogram.SetLineWidth(line_width)
        Histogram.SetFillStyle(0)
        LegendEntries.append(source['legend_entry'])
        Histograms.append(Histogram)

    # Finish loop over input_sources

    # formatting histograms and adding to legend
    legendIndex = 0
    for histogram in Histograms:
#        print "Adding entry to legend:  ", LegendEntries[legendIndex]
#        Legend.AddEntry(histogram,LegendEntries[legendIndex],"LEP")
        Legend.AddEntry(histogram,LegendEntries[legendIndex],"P")
        legendIndex = legendIndex+1

    # finding the maximum value of anything going on the canvas, so we know how to set the y-axis
    finalMax = 0
    for histogram in Histograms:
#        currentMax = histogram.GetMaximum() + histogram.GetBinError(histogram.GetMaximumBin())
        currentMax = histogram.GetMaximum()
        if(currentMax > finalMax):
            finalMax = currentMax
    finalMax = 1.5*finalMax
    if finalMax is 0:
        finalMax = 1
##         if arguments.setYMax:
##             finalMax = float(arguments.setYMax)

    # Drawing histograms to canvas
    makeRatioPlots = arguments.makeRatioPlots
    makeDiffPlots = arguments.makeDiffPlots
    yAxisMin = 0.0
##         if arguments.setYMin:
##             yAxisMin = float(arguments.setYMin)
    if makeRatioPlots or makeDiffPlots:
        Canvas.SetFillStyle(0)
        Canvas.Divide(1,2)
        Canvas.cd(1)
        gPad.SetPad(0,0.25,1,1)
        gPad.SetMargin(0.15,0.05,0.01,0.07)
        gPad.SetFillStyle(0)
        gPad.Update()
        gPad.Draw()
##             if arguments.setLogY:
##                 gPad.SetLogy()
        Canvas.cd(2)
        gPad.SetPad(0,0,1,0.25)
        #format: gPad.SetMargin(l,r,b,t)
        gPad.SetMargin(0.15,0.05,0.4,0.01)
        gPad.SetFillStyle(0)
        gPad.SetGridy(1)
        gPad.Update()
        gPad.Draw()
        Canvas.cd(1)

    histCounter = 0
    plotting_options = "pe, x0"   # x0 suppresses the error bar along x
##         if arguments.plot_hist:
##             plotting_options = "HIST"

    for histogram in Histograms:
        #            histogram.SetTitle(histoTitle)
        histogram.Draw(plotting_options)
        histogram.GetXaxis().SetTitle(xAxisLabel)
        histogram.GetYaxis().SetTitle(yAxisLabel)
        if histogram.InheritsFrom("TH1"):
            histogram.SetMaximum(finalMax)
            histogram.SetMinimum(yAxisMin)
        if makeRatioPlots or makeDiffPlots:
            histogram.GetXaxis().SetLabelSize(0)
        if histCounter is 0:
            if histogram.InheritsFrom("TH1"):
                plotting_options = plotting_options + " SAME"
            elif histogram.InheritsFrom("TGraph"):
                plotting_options = "P"
        histCounter = histCounter + 1

    x_left = 0.15
    x_right = 0.55
    y_min = 0.6
    y_max = 0.8
    Legend.SetX1NDC(x_left)
    Legend.SetY1NDC(y_min)
    Legend.SetX2NDC(x_right)
    Legend.SetY2NDC(y_max)
    Legend.Draw()

    customText = "chargino " + varConst + " " + str(constval)
    if varConst == "mass":
        customText += " GeV"
    elif varConst == "lifetime":
        customText += " cm"
    customText = customText.replace("lifetime", "c#tau")

    CustomLabel = TPaveLabel(x_left, 0.8, x_right, 0.9, customText, "NDC")
    CustomLabel.SetBorderSize(0)
    CustomLabel.SetFillColor(0)
    CustomLabel.SetFillStyle(0)
    CustomLabel.Draw()

    #drawing the ratio or difference plot if requested
    if makeRatioPlots or makeDiffPlots:
        Canvas.cd(2)
        if makeRatioPlots:
#            Comparison = ratioHistogram(Histograms[0],Histograms[1], 1000)
            Comparison = Histograms[0].Clone()
            Comparison.Divide(Histograms[1])
            Comparison.GetYaxis().SetTitle("ratio")
        elif makeDiffPlots:
            Comparison = Histograms[0].Clone("diff")
            Comparison.Add(Histograms[1],-1)
            Comparison.SetTitle("")
            Comparison.GetYaxis().SetTitle("hist1-hist2")
        Comparison.GetXaxis().SetTitle(xAxisLabel)
        Comparison.GetYaxis().CenterTitle()
        Comparison.GetYaxis().SetTitleSize(0.1)
        Comparison.GetYaxis().SetTitleOffset(0.5)
        Comparison.GetXaxis().SetTitleSize(0.15)
        Comparison.GetYaxis().SetLabelSize(0.1)
        Comparison.GetXaxis().SetLabelSize(0.15)
        if makeRatioPlots:
#            RatioYRange = 1.15
            if arguments.ratioYRange:
                RatioYRange = float(arguments.ratioYRange)
            Comparison.GetYaxis().SetRangeUser(0.7, 1.3)
        elif makeDiffPlots:
            YMax = Comparison.GetMaximum()
            YMin = Comparison.GetMinimum()
            if YMax <= 0 and YMin <= 0:
                Comparison.GetYaxis().SetRangeUser(-1.2*YMin,0)
            elif YMax >= 0 and YMin >= 0:
                Comparison.GetYaxis().SetRangeUser(0,1.2*YMax)
            else: #axis crosses y=0
                if abs(YMax) > abs(YMin):
                    Comparison.GetYaxis().SetRangeUser(-1.2*YMax,1.2*YMax)
                else:
                    Comparison.GetYaxis().SetRangeUser(-1.2*YMin,1.2*YMin)
        Comparison.GetYaxis().SetNdivisions(205)
#        Comparison.Draw("E0")
        Comparison.Draw("PE, X0")  # X0 suppresses error bar in x direction

    outputFile.cd()
    Canvas.Write()
    if arguments.savePDFs:
        Canvas.SaveAs("efficiency_histograms_pdfs/"+histogramName+".pdf")
Beispiel #23
0
def plot(MillePedeUser, alignables, mode, struct, parentPlot, config):
    logger = logging.getLogger("mpsvalidate")

    # skip empty
    number = 0
    for i in range(3):
        if (parentPlot.histo[i].GetEntries() == 0):
            number += 1
    if (number == 3):
        return

    # number of bins to start
    numberOfBins = 10000

    ######################################################################
    # initialize data hierarchy
    # plots[subStrucut]
    #

    plots = []

    # initialize histograms
    for subStructNumber, subStruct in enumerate(struct.get_children()):
        plots.append(PlotData(mode))

        # use a copy for shorter name
        plot = plots[subStructNumber]

        for i in range(3):
            if (mode == "xyz"):
                plot.histo.append(
                    TH1F(
                        "{0} {1} {2}".format(
                            struct.get_name() + " " + subStruct.get_name(),
                            plot.xyz[i], mode),
                        "Parameter {0}".format(plot.xyz[i]), numberOfBins,
                        -1000, 1000))
            else:
                plot.histo.append(
                    TH1F(
                        "{0} {1} {2}".format(
                            struct.get_name() + " " + subStruct.get_name(),
                            plot.xyz[i], mode),
                        "Parameter {0}".format(plot.xyz[i]), numberOfBins,
                        -0.1, 0.1))

            plot.histo[i].SetXTitle(plot.unit)
            plot.histo[i].SetLineColor(6)
            plot.histo[i].SetStats(0)

        # add labels
        plot.title = TPaveLabel(
            0.1, 0.8, 0.9, 0.9,
            "Module: {0} {1}".format(struct.get_name(), mode))
        plot.text = TPaveText(0.05, 0.1, 0.95, 0.75)
        plot.text.SetTextAlign(12)
        plot.text.SetTextSizePixels(20)

        # save copy
        plots[subStructNumber] = plot

    ######################################################################
    # fill histogram
    #

    for line in MillePedeUser:
        # is module ?
        if (line.ObjId == 1):
            for subStructNumber, subStruct in enumerate(struct.get_children()):
                # use a copy for shorter name
                plot = plots[subStructNumber]

                # module in struct ?
                if (subStruct.contains_detid(line.Id)):
                    for i in range(3):
                        if (abs(line.Par[plot.data[i]]) != 999999):
                            # transform xyz data from cm to #mu m
                            if (mode == "xyz"):
                                plot.histo[i].Fill(10000 *
                                                   line.Par[plot.data[i]])
                            else:
                                plot.histo[i].Fill(line.Par[plot.data[i]])

                # save copy
                plots[subStructNumber] = plot

    ######################################################################
    # find the best range
    #
    for subStructNumber, subStruct in enumerate(struct.get_children()):
        # use a copy for shorter name
        plot = plots[subStructNumber]
        for i in range(3):
            if (plot.histo[i].GetEntries() != 0
                    and plot.histo[i].GetStdDev() != 0):
                # use binShift of the hole structure
                binShift = parentPlot.usedRange[i]

                # count entries which are not shown anymore
                # bin 1 to begin of histogram
                for j in range(1, numberOfBins / 2 - binShift):
                    plot.hiddenEntries[i] += plot.histo[i].GetBinContent(j)
                # from the end of shown bins to the end of histogram
                for j in range(numberOfBins / 2 + binShift,
                               plot.histo[i].GetNbinsX()):
                    plot.hiddenEntries[i] += plot.histo[i].GetBinContent(j)

                # merge bins, ca. 100 should be visible in the resulting plot
                mergeNumberBins = binShift
                # skip empty histogram
                if (mergeNumberBins != 0):
                    # the 2*maxBinShift bins should shrink to 100 bins
                    mergeNumberBins = int(2. * mergeNumberBins /
                                          config.numberofbins)
                    # the total number of bins should be dividable by the bins
                    # shrinked together
                    if (mergeNumberBins == 0):
                        mergeNumberBins = 1
                    while (numberOfBins % mergeNumberBins != 0
                           and mergeNumberBins != 1):
                        mergeNumberBins -= 1

                    # Rebin and save new created histogram and axis
                    plot.histo[i] = plot.histo[i].Rebin(mergeNumberBins)

                    # set view range. it is important to note that the number of bins have changed with the rebinning
                    # the total number and the number of shift must be
                    # corrected with / mergeNumberBins
                    plot.histo[i].GetXaxis().SetRange(
                        int(numberOfBins / (2 * mergeNumberBins) -
                            binShift / mergeNumberBins),
                        int(numberOfBins / (2 * mergeNumberBins) +
                            binShift / mergeNumberBins))

        # save copy
        plots[subStructNumber] = plot

    ######################################################################
    # make the plots
    #

    canvas = TCanvas("SubStruct_{0}_{1}".format(struct.get_name(), mode),
                     "Parameter", 300, 0, 800, 600)
    canvas.Divide(2, 2)

    canvas.cd(1)
    parentPlot.title.Draw()

    legend = TLegend(0.05, 0.1, 0.95, 0.75)

    for i in range(3):
        canvas.cd(i + 2)

        # find y maximum
        maximum = []

        if (parentPlot.histo[i].GetEntries() == 0):
            continue

        # normalize parent
        parentPlot.histo[i].Scale(1. / parentPlot.histo[i].Integral())
        maximum.append(parentPlot.histo[i].GetMaximum())

        for subStructNumber, subStruct in enumerate(struct.get_children()):
            # use a copy for shorter name
            plot = plots[subStructNumber]

            if (plot.histo[i].GetEntries() > 0):
                plot.histo[i].Scale(1. / plot.histo[i].Integral())
                maximum.append(plot.histo[i].GetMaximum())

            # save copy
            plots[subStructNumber] = plot

        # set range and plot
        parentPlot.histo[i].GetYaxis().SetRangeUser(0., 1.1 * max(maximum))
        parentPlot.histo[i].Draw()

        for subStructNumber, subStruct in enumerate(struct.get_children()):
            # use a copy for shorter name
            plot = plots[subStructNumber].histo[i]

            plot.SetLineColorAlpha(subStructNumber + 2, 0.5)
            plot.Draw("same")
            if (i == 0):
                legend.AddEntry(plot, subStruct.get_name(), "l")

    canvas.cd(1)

    legend.Draw()
    # draw identification
    ident = identification(config)
    ident.Draw()

    canvas.Update()

    # save as pdf
    canvas.Print("{0}/plots/pdf/subModules_{1}_{2}.pdf".format(
        config.outputPath, mode, struct.get_name()))

    # export as png
    image = TImage.Create()
    image.FromPad(canvas)
    image.WriteImage("{0}/plots/png/subModules_{1}_{2}.png".format(
        config.outputPath, mode, struct.get_name()))

    # add to output list
    output = OutputData(plottype="subMod",
                        name=struct.get_name(),
                        number=subStructNumber + 1,
                        parameter=mode,
                        filename="subModules_{0}_{1}".format(
                            mode, struct.get_name()))
    config.outputList.append(output)
def getAvgHist(infile):
    global outRootFile

    inputFile = TFile(infile, "READ")
    canOrig = inputFile.Get(arguments.canName).Clone()
    can     = inputFile.Get(arguments.canName).Clone()
    if not can:
        print "Could not find TCanvas " + can + " in " + inputFile

    isFirstHist = True
    for obj in can.GetListOfPrimitives():
        if arguments.verbose:
            print "Reading: ", obj.GetName()
        if obj.InheritsFrom("TH1"):
            if isFirstHist:
                isFirstHist = False
                havg = obj.Clone()
                hwts = obj.Clone()
                havg.SetDirectory(0)
                havg.Reset()
                hwts.Reset()
                # Define average efficiency as weighted arithmetic mean:
                # (See http://en.wikipedia.org/wiki/Weighted_arithmetic_mean)
                # <eff> = (1/N) * Sum_i (eff_i   / sigma_i^2)
                # <err> = sqrt(1/N)
                # weight_i = 1 / sigma_i^2
                # normalization: N = Sum_i (1 / sigma_i^2)
            for i in range(1,obj.GetNbinsX()+1):
                eff = obj.GetBinContent(i)
                err = obj.GetBinError(i)
                if arguments.verbose:
                    print "Debug:  bin ", i, ": eff=", eff, ", err=", err
                # If error is 0, then reset to be very large value, so that it does not contribute much to the sum
                if err == 0:
                    err = 9.E9
                hwts.SetBinContent(i, hwts.GetBinContent(i) + 1.0 / math.pow(err,2))
                havg.SetBinContent(i, havg.GetBinContent(i) + eff / math.pow(err,2))
                havg.SetBinError  (i, havg.GetBinError  (i) + err / math.pow(err,2))
            if arguments.verbose:
                print "Found TH1: ", obj.GetName()
                print "yield: ", obj.GetBinContent(2), " +- ", obj.GetBinError(2)

    # After looping over all hists, calculate average
    for i in range(1,havg.GetNbinsX()+1):
        havg.SetBinContent(i, havg.GetBinContent(i) / hwts.GetBinContent(i))
        havg.SetBinError  (i, math.sqrt(        1.0 / hwts.GetBinContent(i)))
        if arguments.verbose:
            print "Bin ", i, ": range: (", havg.GetBinLowEdge(i), ", ", havg.GetBinLowEdge(i+1), "): value=", havg.GetBinContent(i), ", error=", havg.GetBinError(i)

    outRootFile.cd()
    canOrig.SetName(canOrig.GetName() + "_orig")
    canOrig.Write()
    can.cd()
    can.Clear("D")
    canNew = TCanvas("canNew", "canNew", can.GetWw(), can.GetWh())
    canNew.SetBottomMargin(can.GetBottomMargin())
    canNew.SetLeftMargin  (can.GetLeftMargin())
    havg.SetMaximum(1.1)
    if arguments.canName == "totalMcparticleStatus3SusyIdPt":
        havg.GetXaxis().SetTitle(havg.GetXaxis().GetTitle().replace("#sum", ""))
    if arguments.canName == "stopDecayVxyZoom":
        #        print "Debug:  setting max to 0.8"
        havg.SetMaximum(0.8)
    havg.GetYaxis().SetTitleOffset(1.4)
    havg.GetXaxis().SetTitleOffset(1.4)
    havg.GetXaxis().SetNdivisions(509)
    havg.Draw("P, E")


    #LumiLabel = TPaveLabel(0.7063758,0.8321678,0.9765101,0.9318182,"CMS","NDC")
    #LumiLabel = TPaveLabel(0.1641611,0.80,0.4463087,0.90,"CMS","NDC")
    LumiLabel = TPaveLabel(0.1858108,0.7904412,0.5084459,0.8897059,"CMS","NDC")
    LumiLabel.SetTextFont(62)
    LumiLabel.SetTextAlign(12)
    LumiLabel.SetBorderSize(0)
    LumiLabel.SetFillColor(0)
    LumiLabel.SetFillStyle(0)
    LumiLabel.Draw()

    #HeaderLabel = TPaveLabel(0.03187919, 0.9440559, 0.9110738, 0.9947552,"19.5 fb^{-1} (8 TeV)","NDC") # from makePlots.py
    HeaderLabel = TPaveLabel(0.02702703,0.9117647,0.9070946,0.9632353,"19.5 fb^{-1} (8 TeV)","NDC") # from makePlots.py
    HeaderLabel.SetTextAlign(32)
    HeaderLabel.SetBorderSize(0)
    HeaderLabel.SetFillColor(0)
    HeaderLabel.SetFillStyle(0)
    HeaderLabel.SetTextFont(42);
    HeaderLabel.Draw()

    outputPdf = arguments.outfile[:arguments.outfile.rfind("/")]
#    outputPdf += "/" + canNew.GetName() + ".pdf"
    outputPdf += "/" + havg.GetName() + "_avgEff.pdf"
    canNew.SaveAs(outputPdf)
    canNew.Write()
    print "Saving pdf: ", outputPdf
    inputFile.Close()

    return havg
Beispiel #25
0
from ROOT import TArrow, TLine
from ROOT import gROOT, gBenchmark

#gROOT.Reset()

c1 = TCanvas('c1', 'Tree Data Structure', 200, 10, 750, 940)
c1.Range(0, -0.1, 1, 1.15)

gBenchmark.Start('tree')

branchcolor = 26
leafcolor = 30
basketcolor = 42
offsetcolor = 43
#title = TPaveLabel(.3,1.05,.8,1.13,c1.GetTitle())
title = TPaveLabel(.3, 1.05, .8, 1.13, 'Tree Data Structure')
title.SetFillColor(16)
title.Draw()
tree = TPaveText(.01, .75, .15, 1.00)
tree.SetFillColor(18)
tree.SetTextAlign(12)
tnt = tree.AddText('Tree')
tnt.SetTextAlign(22)
tnt.SetTextSize(0.030)
tree.AddText('fScanField')
tree.AddText('fMaxEventLoop')
tree.AddText('fMaxVirtualSize')
tree.AddText('fEntries')
tree.AddText('fDimension')
tree.AddText('fSelectedRows')
tree.Draw()
Beispiel #26
0
def showRMSAOH(sector, aoh, gain, wait=True, filename=None):
    gStyle.SetOptStat(0)
    gStyle.SetCanvasColor(0)
    gStyle.SetTitleFillColor(0)

    sector.aoh[aoh].biasGraphs = []
    sector.aoh[aoh].rmsGraphs = []
    sector.aoh[aoh].slopeGraphs = []

    if sector.aoh[aoh].group.find('L12') != -1:
        sector.ccu.send("channel 0x11").readlines()
    elif sector.aoh[aoh].group.find('L3') != -1:
        sector.ccu.send("channel 0x13").readlines()

    cmd = sector.aoh[aoh].name + " setall %i %i %i %i %i %i %i %i" % (
        gain, gain, gain, gain, 0, 0, 0, 0)
    sector.ccu.send(cmd).readlines()

    #for ch in range(1,5):
    #   print ch
    #   sector.aoh[aoh].writegain(ch,gain)

    data = sector.aoh[aoh].getBiasRMSCurves()

    if filename is None:
        filename = getFilename("poh%s_%d.ps" % (sector.name, aoh))

    c1 = TCanvas('c1', time.strftime("%Y-%m-%d-%m %H:%M"), 200, 10, 800, 800)
    sector.aoh[aoh].pl = TPaveLabel(0.8, 0.9, 0.95, 0.95,
                                    time.strftime("%Y-%m-%d-%m %H:%M"))
    sector.aoh[aoh].pl.Draw()
    c1.Divide(2, 3)
    for ch in range(1, 5):
        c1.cd(ch)
        title = "POHBias_POH" + str(aoh) + ":" + str(
            ch) + " " + sector.name + " fed channel " + str(
                sector.aoh[aoh].fedchannels[ch])
        f = TH2D('h' + title, title, 2, 0, 80, 2, 0, 1024)
        hList.append(f)
        f.GetXaxis().SetTitle("poh bias")
        #f.GetYaxis().SetTitle("FED ADC")
        f.Draw()
        color = 1
        biasGraph = graph([(t[0], t[1]) for t in data[ch]],
                          color=1,
                          name="bias_" + str(aoh) + ":" + str(ch))
        rmsGraph = graph([(t[0], t[2] * 10.) for t in data[ch]],
                         color=2,
                         name="rms_" + str(aoh) + ":" + str(ch))
        slopeGraph = graph([(t[0], t[3] * 10.) for t in data[ch]],
                           color=3,
                           name="slope_" + str(aoh) + ":" + str(ch))
        sector.aoh[aoh].biasGraphs.append(biasGraph)
        sector.aoh[aoh].rmsGraphs.append(rmsGraph)
        sector.aoh[aoh].slopeGraphs.append(slopeGraph)
        biasGraph.Write()
        rmsGraph.Write()
        slopeGraph.Write()

        c1.Update()

    c1.Print(filename)
    gCanvases.append(c1)

    if wait:
        raw_input("hit return to continue")
Beispiel #27
0
def makeLimitPlot(output,
                  obs,
                  exp,
                  chan,
                  printStats=False,
                  obs2="",
                  ratioLabel=""):
    #fileForHEPData = TFile("plots/"+output+"_forHEPData.root","RECREATE")
    fileObs = open(obs, 'r')
    fileExp = open(exp, 'r')

    observedx = []
    observedy = []
    obsLimits = {}
    for entry in fileObs:
        massPoint = float(entry.split()[0])
        limitEntry = float(entry.split()[1])
        if massPoint not in obsLimits: obsLimits[massPoint] = []
        obsLimits[massPoint].append(limitEntry)
    if printStats: print "len obsLimits:", len(obsLimits)
    for massPoint in sorted(obsLimits):
        observedx.append(massPoint)
        observedy.append(numpy.mean(obsLimits[massPoint]))
        if (numpy.std(obsLimits[massPoint]) / numpy.mean(obsLimits[massPoint])
                > 0.05):
            print massPoint, " mean: ", numpy.mean(
                obsLimits[massPoint]), " std dev: ", numpy.std(
                    obsLimits[massPoint]), " from: ", obsLimits[massPoint]

    if not obs2 == "":
        fileObs2 = open(obs2, 'r')

        observedx2 = []
        observedy2 = []
        obsLimits2 = {}
        for entry in fileObs2:
            massPoint = float(entry.split()[0])
            limitEntry = float(entry.split()[1])
            if massPoint not in obsLimits2: obsLimits2[massPoint] = []
            obsLimits2[massPoint].append(limitEntry)
        if printStats: print "len obsLimits:", len(obsLimits2)
        for massPoint in sorted(obsLimits2):
            observedx2.append(massPoint)
            observedy2.append(numpy.mean(obsLimits2[massPoint]))
            if (numpy.std(obsLimits2[massPoint]) /
                    numpy.mean(obsLimits2[massPoint]) > 0.05):
                print massPoint, " mean: ", numpy.mean(
                    obsLimits2[massPoint]), " std dev: ", numpy.std(
                        obsLimits2[massPoint]
                    ), " from: ", obsLimits2[massPoint]

    limits = {}
    expectedx = []
    expectedy = []
    expected1SigLow = []
    expected1SigHigh = []
    expected2SigLow = []
    expected2SigHigh = []
    for entry in fileExp:
        massPoint = float(entry.split()[0])
        limitEntry = float(entry.split()[1])
        if massPoint not in limits: limits[massPoint] = []
        limits[massPoint].append(limitEntry)

    if printStats: print "len limits:", len(limits)
    for massPoint in sorted(limits):
        limits[massPoint].sort()
        numLimits = len(limits[massPoint])
        nrExpts = len(limits[massPoint])
        medianNr = int(nrExpts * 0.5)
        #get indexes:
        upper1Sig = int(nrExpts * (1 - (1 - 0.68) * 0.5))
        lower1Sig = int(nrExpts * (1 - 0.68) * 0.5)
        upper2Sig = int(nrExpts * (1 - (1 - 0.95) * 0.5))
        lower2Sig = int(nrExpts * (1 - 0.95) * 0.5)
        if printStats:
            print massPoint, ":", limits[massPoint][lower2Sig], limits[
                massPoint][lower1Sig], limits[massPoint][medianNr], limits[
                    massPoint][upper1Sig], limits[massPoint][upper2Sig]
        #fill lists:
        expectedx.append(massPoint)
        print massPoint, limits[massPoint][medianNr]
        expectedy.append(limits[massPoint][medianNr])
        expected1SigLow.append(limits[massPoint][lower1Sig])
        expected1SigHigh.append(limits[massPoint][upper1Sig])
        expected2SigLow.append(limits[massPoint][lower2Sig])
        expected2SigHigh.append(limits[massPoint][upper2Sig])

    expX = numpy.array(expectedx)
    expY = numpy.array(expectedy)

    values2 = []
    xPointsForValues2 = []
    values = []
    xPointsForValues = []
    xPointsForErrors = []
    if printStats: print "length of expectedx: ", len(expectedx)
    if printStats: print "length of expected1SigLow: ", len(expected1SigLow)
    if printStats: print "length of expected1SigHigh: ", len(expected1SigHigh)

    #Here is some Voodoo via Sam:
    for x in range(0, len(expectedx)):
        values2.append(expected2SigLow[x])
        xPointsForValues2.append(expectedx[x])
        xPointsForErrors.append(0)
    for x in range(len(expectedx) - 1, 0 - 1, -1):
        values2.append(expected2SigHigh[x])
        xPointsForValues2.append(expectedx[x])
    if printStats: print "length of values2: ", len(values2)

    for x in range(0, len(expectedx)):
        values.append(expected1SigLow[x])
        xPointsForValues.append(expectedx[x])
    for x in range(len(expectedx) - 1, 0 - 1, -1):
        values.append(expected1SigHigh[x])
        xPointsForValues.append(expectedx[x])
    if printStats: print "length of values: ", len(values)

    exp2Sig = numpy.array(values2)
    xPoints2 = numpy.array(xPointsForValues2)
    exp1Sig = numpy.array(values)
    xPoints = numpy.array(xPointsForValues)
    xPointsErrors = numpy.array(xPointsForErrors)
    if printStats: print "xPoints2: ", xPoints2
    if printStats: print "exp2Sig: ", exp2Sig
    if printStats: print "xPoints: ", xPoints
    if printStats: print "exp1Sig: ", exp1Sig

    GraphErr2SigForHEPData = TGraphAsymmErrors(len(expX), expX, expY,
                                               numpy.array(xPointsErrors),
                                               numpy.array(xPointsErrors),
                                               numpy.array(expected2SigLow),
                                               numpy.array(expected2SigHigh))
    GraphErr1SigForHEPData = TGraphAsymmErrors(len(expX), expX, expY,
                                               numpy.array(xPointsErrors),
                                               numpy.array(xPointsErrors),
                                               numpy.array(expected1SigLow),
                                               numpy.array(expected1SigHigh))

    GraphErr2Sig = TGraphAsymmErrors(len(xPoints), xPoints2, exp2Sig)
    GraphErr2Sig.SetFillColor(ROOT.kOrange)
    GraphErr1Sig = TGraphAsymmErrors(len(xPoints), xPoints, exp1Sig)
    GraphErr1Sig.SetFillColor(ROOT.kGreen + 1)
    #cCL=TCanvas("cCL", "cCL",0,0,567,384)
    cCL = TCanvas("cCL", "cCL", 0, 0, 600, 450)
    gStyle.SetOptStat(0)
    gStyle.SetPadRightMargin(0.063)
    gStyle.SetPadLeftMargin(0.14)
    gStyle.SetPadBottomMargin(0.12)

    if not obs2 == "":
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1)
        ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3)
        plotPad.Draw()
        ratioPad.Draw()
        plotPad.cd()
    else:
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
        plotPad.Draw()
        plotPad.cd()

    expX = numpy.array(expectedx)
    expY = numpy.array(expectedy)
    GraphExp = TGraph(len(expX), expX, expY)
    GraphExp.SetLineWidth(3)
    GraphExp.SetLineStyle(2)
    GraphExp.SetLineColor(ROOT.kBlue)

    obsX = numpy.array(observedx)
    obsY = numpy.array(observedy)
    if printStats: print "obsX: ", obsX
    if printStats: print "obsY: ", obsY

    if SMOOTH:
        smooth_obs = TGraphSmooth("normal")
        GraphObs_nonSmooth = TGraph(len(obsX), obsX, obsY)
        GraphObs = smooth_obs.SmoothSuper(GraphObs_nonSmooth, "linear", 0,
                                          0.005)
    else:
        GraphObs = TGraph(len(obsX), obsX, obsY)

    GraphObs.SetLineWidth(3)
    if not obs2 == "":

        ratio = []
        ratiox = []
        for index, val in enumerate(observedy):
            mass = observedx[index]
            foundIndex = -1
            for index2, mass2 in enumerate(observedx2):
                if mass == mass2:
                    foundIndex = index2

            if foundIndex > 0:
                ratio.append(observedy2[foundIndex] / val)
                ratiox.append(mass)
        ratioA = numpy.array(ratio)
        ratioX = numpy.array(ratiox)
        obsX2 = numpy.array(observedx2)
        obsY2 = numpy.array(observedy2)
        ratioGraph = TGraph(len(ratioX), ratioX, ratioA)
        if printStats: print "obsX2: ", obsX2
        if printStats: print "obsY2: ", obsY2

        if SMOOTH:
            smooth_obs2 = TGraphSmooth("normal")
            GraphObs2_nonSmooth = TGraph(len(obsX2), obsX2, obsY2)
            GraphObs2 = smooth_obs2.SmoothSuper(GraphObs2_nonSmooth, "linear",
                                                0, 0.005)
        else:
            GraphObs2 = TGraph(len(obsX2), obsX2, obsY2)

        GraphObs2.SetLineWidth(3)

    if SPIN2:
        signals = ["RS_kMpl01", "RS_kMpl005", "RS_kMpl001"]
    elif GUT:
        signals = ["ssm", "psi", "kai", "eta", "I", "S", "N"]
    else:
        signals = ["ssm", "psi"]

    xSecCurves = []
    for signal in signals:
        xSecCurves.append(getXSecCurve(signal, kFacs[signal]))
        #xSecCurves.append(getXSecCurve(signal,kFacs[signal],massDependent=True))

#Draw the graphs:
    plotPad.SetLogy()
    DummyGraph = TH1F("DummyGraph", "", 100, 200, 5500)
    DummyGraph.GetXaxis().SetTitle("M [GeV]")
    if SPIN2:
        DummyGraph.GetYaxis().SetTitle(
            "[#sigma#upoint#font[12]{B}] G_{KK} / [#sigma#upoint#font[12]{B}] Z"
        )
    else:
        DummyGraph.GetYaxis().SetTitle(
            "[#sigma#upoint#font[12]{B}] Z' / [#sigma#upoint#font[12]{B}] Z")

#	if SPIN2:
#	    	if chan=="mumu":
#       	 		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrow#mu^{+}#mu^{-}+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu^{+}#mu^{-}+X)")
#    		elif chan=="elel":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)")
#    		elif chan=="elmu":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)")
#	else:
#    		if chan=="mumu":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrow#mu^{+}#mu^{-}+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu^{+}#mu^{-}+X)")
#    		elif chan=="elel":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)")
#    		elif chan=="elmu":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)")

    gStyle.SetOptStat(0)
    DummyGraph.GetXaxis().SetRangeUser(200, 5500)

    DummyGraph.SetMinimum(1e-8)
    DummyGraph.SetMaximum(1e-4)
    DummyGraph.GetXaxis().SetLabelSize(0.055)
    DummyGraph.GetXaxis().SetTitleSize(0.055)
    DummyGraph.GetXaxis().SetTitleOffset(1.05)
    DummyGraph.GetYaxis().SetLabelSize(0.055)
    DummyGraph.GetYaxis().SetTitleSize(0.055)
    DummyGraph.GetYaxis().SetTitleOffset(1.3)
    DummyGraph.Draw()
    if (FULL):
        GraphErr2Sig.Draw("F")
        GraphErr1Sig.Draw("F")
        GraphExp.Draw("lpsame")
    else:
        if obs2 == "":
            GraphExp.Draw("lp")
    if not EXPONLY:
        GraphObs.Draw("plsame")
    if not obs2 == "":
        GraphObs2.SetLineColor(ROOT.kRed)
        GraphObs2.SetLineStyle(ROOT.kDashed)
        GraphObs2.Draw("plsame")
    for curve in xSecCurves:
        curve.Draw("lsame")

    plCMS = TPaveLabel(.16, .81, .27, .88, "CMS", "NBNDC")
    #plCMS.SetTextSize(0.8)
    plCMS.SetTextAlign(12)
    plCMS.SetTextFont(62)
    plCMS.SetFillColor(0)
    plCMS.SetFillStyle(0)
    plCMS.SetBorderSize(0)

    plCMS.Draw()

    plPrelim = TPaveLabel(.16, .76, .27, .82, "Preliminary", "NBNDC")
    plPrelim.SetTextSize(0.6)
    plPrelim.SetTextAlign(12)
    plPrelim.SetTextFont(52)
    plPrelim.SetFillColor(0)
    plPrelim.SetFillStyle(0)
    plPrelim.SetBorderSize(0)
    if "2017" in output or "Combination" in output:
        plPrelim.Draw()

    cCL.SetTickx(1)
    cCL.SetTicky(1)
    cCL.RedrawAxis()
    cCL.Update()

    #leg=TLegend(0.65,0.65,0.87,0.87,"","brNDC")
    #leg=TLegend(0.540517,0.623051,0.834885,0.878644,"","brNDC")   Default
    leg = TLegend(0.5, 0.58, 0.834885, 0.878644, "", "brNDC")
    if SPIN2:
        leg = TLegend(0.5, 0.58, 0.834885, 0.878644, "", "brNDC")
#    	leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC")
    leg.SetTextSize(0.0425)
    if not obs2 == "":
        if ratioLabel == "":
            ratioLabel = "Variant/Default"
        ratioLabels = ratioLabel.split("/")
        print ratioLabels
        leg.AddEntry(GraphObs, "%s Obs. 95%% CL limit" % ratioLabels[1], "l")
        leg.AddEntry(GraphObs2, "%s Obs. 95%% CL limit" % ratioLabels[0], "l")

    else:
        if not EXPONLY:
            leg.AddEntry(GraphObs, "Obs. 95% CL limit", "l")
        leg.AddEntry(GraphExp, "Exp. 95% CL limit, median", "l")
        if (FULL):
            leg.AddEntry(GraphErr1Sig, "Exp. (68%)", "f")
            leg.AddEntry(GraphErr2Sig, "Exp. (95%)", "f")

    leg1 = TLegend(0.7, 0.4, 0.9, 0.55, "", "brNDC")
    leg1.SetTextSize(0.05)
    if GUT:
        leg1 = TLegend(0.6, 0.35, 0.75, 0.623051, "", "brNDC")
    if SPIN2:
        leg1 = TLegend(0.7, 0.35, 0.9, 0.58, "G_{KK} (LO x 1.6)", "brNDC")
        leg1.SetTextSize(0.045)
    for index, signal in enumerate(signals):
        xSecCurves[index].SetName(labels[signal])
        xSecCurves[index].Write(labels[signal])
        leg1.AddEntry(xSecCurves[index], labels[signal], "l")
    leg1.SetBorderSize(0)

    leg.SetLineWidth(0)
    leg.SetLineStyle(0)
    leg.SetFillStyle(0)
    leg.SetLineColor(0)
    leg.Draw("hist")

    leg1.SetLineWidth(0)
    leg1.SetLineStyle(0)
    leg1.SetFillStyle(0)
    leg1.SetLineColor(0)
    leg1.Draw("hist")
    if "Moriond" in output:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .885, .9, .99,
                                "36.3 fb^{-1} (13 TeV, #mu^{+}#mu^{-})",
                                "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .885, .9, .99,
                                "35.9 fb^{-1} (13 TeV, ee)", "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .27, .885, .9, .99,
                "35.9 fb^{-1} (13 TeV, ee) + 36.3 fb^{-1} (13 TeV, #mu^{+}#mu^{-})",
                "NBNDC")

    elif "2017" in output or "Combination" in output:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .885, .9, .99,
                                "42.4 fb^{-1} (13 TeV, #mu^{+}#mu^{-})",
                                "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .885, .9, .99,
                                "41.4 fb^{-1} (13 TeV, ee)", "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .27, .885, .9, .99,
                "77.3 fb^{-1} (13 TeV, ee) + 78.7 fb^{-1} (13 TeV, #mu^{+}#mu^{-})",
                "NBNDC")
    else:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "13.0 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99, "2.7 fb^{-1} (13 TeV, ee)",
                                "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")

    plLumi.SetTextSize(0.5)
    plLumi.SetTextFont(42)
    plLumi.SetFillColor(0)
    plLumi.SetBorderSize(0)
    plLumi.Draw()

    plotPad.SetTicks(1, 1)
    plotPad.RedrawAxis()

    if not obs2 == "":

        ratioPad.cd()

        line = ROOT.TLine(200, 1, 5500, 1)
        line.SetLineStyle(ROOT.kDashed)

        ROOT.gStyle.SetTitleSize(0.12, "Y")
        ROOT.gStyle.SetTitleYOffset(0.35)
        ROOT.gStyle.SetNdivisions(000, "Y")
        ROOT.gStyle.SetNdivisions(408, "Y")
        ratioPad.DrawFrame(200, 0.8, 5500, 1.2, "; ; %s" % ratioLabel)

        line.Draw("same")

        ratioGraph.Draw("sameP")

#GraphErr2SigForHEPData.SetName("graph2Sig")
#GraphErr2SigForHEPData.Write("graph2Sig")

#GraphErr1SigForHEPData.SetName("graph1Sig")
#GraphErr1SigForHEPData.Write("graph1Sig")

#GraphExp.SetName("graphExp")
#GraphExp.Write("graphExp")

#GraphObs.SetName("graphObs")
#GraphObs.Write("graphObs")

#fileForHEPData.Write()
#fileForHEPData.Close()
    cCL.Update()
    printPlots(cCL, output)
Beispiel #28
0
def makeLimitPlot(output, obs, exp, chan, printStats=False):

    obsLimits = {}

    for obsFile in obs:
        if 'width' in obsFile:
            width = obsFile.split('width')[-1].split('_')[0]
        else:
            width = '0.006'
        obsLimits[width] = createObsGraph(obsFile)

    if SMOOTH:
        for width, obsGraph in obsLimits.iteritems():
            smooth_obs = TGraphSmooth("normal")
            GraphObs_nonSmooth = obsGraph
            obsLimits[width] = copy.deepcopy(
                smooth_obs.SmoothSuper(GraphObs_nonSmooth, "linear", 0, 0.005))
            obsLimits[width].SetLineWidth(3)

    expLimits = {}

    for expFile in exp:
        if 'width' in expFile:
            width = expFile.split('width')[-1].split('_')[0]
        else:
            width = '0.006'
        expLimits[width] = createExpGraph(expFile)

    cCL = TCanvas("cCL", "cCL", 0, 0, 800, 500)
    gStyle.SetOptStat(0)

    plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
    plotPad.Draw()
    plotPad.cd()

    smoother = TGraphSmooth("normal")
    smoother2 = TGraphSmooth("normal")

    zprimeX = []
    zprimeY = []
    fileZPrime = open('tools/xsec_ssm.txt', 'r')
    for entries in fileZPrime:
        entry = entries.split()
        zprimeX.append(float(entry[0]))
        zprimeY.append(float(entry[1]) * 1.3 / 1928)
    zpX = numpy.array(zprimeX)
    zpY = numpy.array(zprimeY)
    GraphZPrime = TGraph(481, zpX, zpY)
    GraphZPrimeSmooth = smoother2.SmoothSuper(GraphZPrime, "linear")
    GraphZPrimeSmooth.SetLineWidth(3)
    GraphZPrimeSmooth.SetLineColor(ROOT.kGreen + 3)
    GraphZPrimeSmooth.SetLineStyle(2)

    zprimePsiX = []
    zprimePsiY = []
    fileZPrimePsi = open('tools/xsec_psi.txt', 'r')
    for entries in fileZPrimePsi:
        entry = entries.split()
        zprimePsiX.append(float(entry[0]))
        zprimePsiY.append(float(entry[1]) * 1.3 / 1928)
    zpPsiX = numpy.array(zprimePsiX)
    zpPsiY = numpy.array(zprimePsiY)
    GraphZPrimePsi = TGraph(481, zpPsiX, zpPsiY)
    GraphZPrimePsiSmooth = smoother.SmoothSuper(GraphZPrimePsi, "linear")
    GraphZPrimePsiSmooth.SetLineWidth(3)
    GraphZPrimePsiSmooth.SetLineColor(ROOT.kBlue)

    #Draw the graphs:
    plotPad.SetLogy()
    if "Moriond" in output:
        DummyGraph = TH1F("DummyGraph", "", 100, 200, 5500)
    else:
        DummyGraph = TH1F("DummyGraph", "", 100, 400, 4500)
    DummyGraph.GetXaxis().SetTitle("M [GeV]")
    if chan == "mumu":
        DummyGraph.GetYaxis().SetTitle(
            "#sigma(pp#rightarrowZ'+X#rightarrow#mu#mu+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu#mu+X)"
        )
    elif chan == "elel":
        DummyGraph.GetYaxis().SetTitle(
            "#sigma(pp#rightarrowZ'+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)"
        )
    elif chan == "elmu":
        DummyGraph.GetYaxis().SetTitle(
            "#sigma(pp#rightarrowZ'+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)"
        )

    gStyle.SetOptStat(0)
    if "Moriond" in output:
        DummyGraph.GetXaxis().SetRangeUser(200, 5500)
    else:
        DummyGraph.GetXaxis().SetRangeUser(400, 4500)

    DummyGraph.SetMinimum(1e-8)
    DummyGraph.SetMaximum(4e-4)
    DummyGraph.GetXaxis().SetLabelSize(0.04)
    DummyGraph.GetXaxis().SetTitleSize(0.045)
    DummyGraph.GetXaxis().SetTitleOffset(1.)
    DummyGraph.GetYaxis().SetLabelSize(0.04)
    DummyGraph.GetYaxis().SetTitleSize(0.045)
    DummyGraph.GetYaxis().SetTitleOffset(1.)
    DummyGraph.Draw()

    plCMS = TPaveLabel(.12, .81, .22, .88, "CMS", "NBNDC")
    #plCMS.SetTextSize(0.8)
    plCMS.SetTextAlign(12)
    plCMS.SetTextFont(62)
    plCMS.SetFillColor(0)
    plCMS.SetBorderSize(0)

    plCMS.Draw()

    plPrelim = TPaveLabel(.12, .76, .25, .82, "Preliminary", "NBNDC")
    plPrelim.SetTextSize(0.6)
    plPrelim.SetTextAlign(12)
    plPrelim.SetTextFont(52)
    plPrelim.SetFillColor(0)
    plPrelim.SetBorderSize(0)
    plPrelim.Draw()

    leg = TLegend(0.430517, 0.623051, 0.734885, 0.878644, "", "brNDC")
    #    	leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC")
    leg.SetTextSize(0.032)
    colors = {
        '01': ROOT.kBlue,
        '03': ROOT.kRed,
        '05': ROOT.kGreen + 3,
        '10': ROOT.kOrange
    }
    for width in sorted(obsLimits):
        obsGraph = obsLimits[width]
        if colors.has_key(width):
            obsGraph.SetLineColor(colors[width])
        obsGraph.Draw("lsame")
        if width == '0.006':
            leg.AddEntry(obsGraph, "Observed 95% CL limit width 0.6%", "l")
        else:
            leg.AddEntry(obsGraph,
                         "Observed 95%% CL limit width %d%%" % int(width), "l")

    for width in sorted(expLimits):
        expGraph = expLimits[width]
        if colors.has_key(width):
            expGraph.SetLineColor(colors[width])
        expGraph.Draw("lsame")
        if width == '0.006':
            leg.AddEntry(expGraph, "Expected 95% CL limit width 0.6%, median",
                         "l")
        else:
            leg.AddEntry(
                expGraph,
                "Expected 95%% CL limit width %d%%, median" % (int(width)),
                "l")

#    	if not SPIN2:
#        	GraphZPrimeSmooth.Draw("lsame")
#        	GraphZPrimePsiSmooth.Draw("lsame")

    cCL.SetTickx(1)
    cCL.SetTicky(1)
    cCL.RedrawAxis()
    cCL.Update()

    leg.SetLineWidth(0)
    leg.SetLineStyle(0)
    leg.SetLineColor(0)
    leg.Draw("hist")
    if "Moriond" in output:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "36.3 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "35.9 fb^{-1} (13 TeV, ee)", "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "35.9 fb^{-1} (13 TeV, ee) + 36.3 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")
    else:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "13.0 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99, "2.7 fb^{-1} (13 TeV, ee)",
                                "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")

    plLumi.SetTextSize(0.5)
    plLumi.SetTextFont(42)
    plLumi.SetFillColor(0)
    plLumi.SetBorderSize(0)
    plLumi.Draw()

    cCL.Update()
    printPlots(cCL, output)
Beispiel #29
0
#
# A function (any dimension) or a formula may reference
# an already defined formula
#
form1 = TFormula( 'form1', 'abs(sin(x)/x)' )
sqroot = TF1( 'sqroot', 'x*gaus(0) + [3]*form1', 0, 10 )
sqroot.SetParameters( 10, 4, 1, 20 )
pad1.SetGridx()
pad1.SetGridy()
pad1.GetFrame().SetFillColor( 42 )
pad1.GetFrame().SetBorderMode( -1 )
pad1.GetFrame().SetBorderSize( 5 )
sqroot.SetLineColor( 4 )
sqroot.SetLineWidth( 6 )
sqroot.Draw()
lfunction = TPaveLabel( 5, 39, 9.8, 46, 'The sqroot function' )
lfunction.SetFillColor( 41 )
lfunction.Draw()
c1.Update()

#
# Create a one dimensional histogram (one float per bin)
# and fill it following the distribution in function sqroot.
#
pad2.cd();
pad2.GetFrame().SetFillColor( 42 )
pad2.GetFrame().SetBorderMode( -1 )
pad2.GetFrame().SetBorderSize( 5 )
h1f = TH1F( 'h1f', 'Test random numbers', 200, 0, 10 )
h1f.SetFillColor( 45 )
h1f.FillRandom( 'sqroot', 10000 )
Beispiel #30
0
def makeLimitPlot(output,
                  obs,
                  exp,
                  chan,
                  interference,
                  printStats=False,
                  obs2="",
                  ratioLabel=""):

    fileObs = open(obs, 'r')
    fileExp = open(exp, 'r')

    observedx = []
    observedy = []
    obsLimits = {}
    xSecs = getFittedXSecCurve("CI_%s" % interference, 1.3)
    for entry in fileObs:
        massPoint = float(entry.split()[0])
        limitEntry = float(entry.split()[1]) * xSecs.Eval(
            int(float(entry.split()[0])))
        if massPoint not in obsLimits: obsLimits[massPoint] = []
        obsLimits[massPoint].append(limitEntry)
    if printStats: print "len obsLimits:", len(obsLimits)
    for massPoint in sorted(obsLimits):
        observedx.append(massPoint)
        observedy.append(numpy.mean(obsLimits[massPoint]))
        if (numpy.std(obsLimits[massPoint]) / numpy.mean(obsLimits[massPoint])
                > 0.05):
            print massPoint, " mean: ", numpy.mean(
                obsLimits[massPoint]), " std dev: ", numpy.std(
                    obsLimits[massPoint]), " from: ", obsLimits[massPoint]

    if not obs2 == "":
        fileObs2 = open(obs2, 'r')

        observedx2 = []
        observedy2 = []
        obsLimits2 = {}
        for entry in fileObs2:
            massPoint = float(entry.split()[0])
            limitEntry = float(entry.split()[1]) * xSecs.Eval(
                int(float(entry.split()[0])))
            if massPoint not in obsLimits2: obsLimits2[massPoint] = []
            obsLimits2[massPoint].append(limitEntry)
        if printStats: print "len obsLimits:", len(obsLimits2)
        for massPoint in sorted(obsLimits2):
            observedx2.append(massPoint)
            observedy2.append(numpy.mean(obsLimits2[massPoint]))
            if (numpy.std(obsLimits2[massPoint]) /
                    numpy.mean(obsLimits2[massPoint]) > 0.05):
                print massPoint, " mean: ", numpy.mean(
                    obsLimits2[massPoint]), " std dev: ", numpy.std(
                        obsLimits2[massPoint]
                    ), " from: ", obsLimits2[massPoint]

    limits = {}
    expectedx = []
    expectedy = []
    expected1SigLow = []
    expected1SigHigh = []
    expected2SigLow = []
    expected2SigHigh = []
    for entry in fileExp:
        massPoint = float(entry.split()[0])
        limitEntry = float(entry.split()[1]) * xSecs.Eval(
            int(float(entry.split()[0])))
        if massPoint not in limits: limits[massPoint] = []
        limits[massPoint].append(limitEntry)

    if printStats: print "len limits:", len(limits)
    for massPoint in sorted(limits):
        limits[massPoint].sort()
        numLimits = len(limits[massPoint])
        nrExpts = len(limits[massPoint])
        medianNr = int(nrExpts * 0.5)
        #get indexes:
        upper1Sig = int(nrExpts * (1 - (1 - 0.68) * 0.5))
        lower1Sig = int(nrExpts * (1 - 0.68) * 0.5)
        upper2Sig = int(nrExpts * (1 - (1 - 0.95) * 0.5))
        lower2Sig = int(nrExpts * (1 - 0.95) * 0.5)
        if printStats:
            print massPoint, ":", limits[massPoint][lower2Sig], limits[
                massPoint][lower1Sig], limits[massPoint][medianNr], limits[
                    massPoint][upper1Sig], limits[massPoint][upper2Sig]
        #fill lists:
        expectedx.append(massPoint)
        print massPoint, limits[massPoint][medianNr]
        expectedy.append(limits[massPoint][medianNr])
        expected1SigLow.append(limits[massPoint][lower1Sig])
        expected1SigHigh.append(limits[massPoint][upper1Sig])
        expected2SigLow.append(limits[massPoint][lower2Sig])
        expected2SigHigh.append(limits[massPoint][upper2Sig])

    expX = numpy.array(expectedx)
    expY = numpy.array(expectedy)

    values2 = []
    xPointsForValues2 = []
    values = []
    xPointsForValues = []
    if printStats: print "length of expectedx: ", len(expectedx)
    if printStats: print "length of expected1SigLow: ", len(expected1SigLow)
    if printStats: print "length of expected1SigHigh: ", len(expected1SigHigh)

    #Here is some Voodoo via Sam:
    for x in range(0, len(expectedx)):
        values2.append(expected2SigLow[x])
        xPointsForValues2.append(expectedx[x])
    for x in range(len(expectedx) - 1, 0 - 1, -1):
        values2.append(expected2SigHigh[x])
        xPointsForValues2.append(expectedx[x])
    if printStats: print "length of values2: ", len(values2)

    for x in range(0, len(expectedx)):
        values.append(expected1SigLow[x])
        xPointsForValues.append(expectedx[x])
    for x in range(len(expectedx) - 1, 0 - 1, -1):
        values.append(expected1SigHigh[x])
        xPointsForValues.append(expectedx[x])
    if printStats: print "length of values: ", len(values)

    exp2Sig = numpy.array(values2)
    xPoints2 = numpy.array(xPointsForValues2)
    exp1Sig = numpy.array(values)
    xPoints = numpy.array(xPointsForValues)
    if printStats: print "xPoints2: ", xPoints2
    if printStats: print "exp2Sig: ", exp2Sig
    if printStats: print "xPoints: ", xPoints
    if printStats: print "exp1Sig: ", exp1Sig
    GraphErr2Sig = TGraphAsymmErrors(len(xPoints), xPoints2, exp2Sig)
    GraphErr2Sig.SetFillColor(ROOT.kOrange)
    GraphErr1Sig = TGraphAsymmErrors(len(xPoints), xPoints, exp1Sig)
    GraphErr1Sig.SetFillColor(ROOT.kGreen + 1)

    cCL = TCanvas("cCL", "cCL", 0, 0, 800, 500)
    gStyle.SetOptStat(0)

    if not obs2 == "":
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1)
        ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3)
        plotPad.Draw()
        ratioPad.Draw()
        plotPad.cd()
    else:
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
        plotPad.Draw()
        plotPad.cd()

    expX = numpy.array(expectedx)
    expY = numpy.array(expectedy)
    GraphExp = TGraph(len(expX), expX, expY)
    GraphExp.SetLineWidth(3)
    GraphExp.SetLineStyle(2)
    GraphExp.SetLineColor(ROOT.kBlue)

    obsX = numpy.array(observedx)
    obsY = numpy.array(observedy)
    if printStats: print "obsX: ", obsX
    if printStats: print "obsY: ", obsY

    if SMOOTH:
        smooth_obs = TGraphSmooth("normal")
        GraphObs_nonSmooth = TGraph(len(obsX), obsX, obsY)
        GraphObs = smooth_obs.SmoothSuper(GraphObs_nonSmooth, "linear", 0,
                                          0.005)
    else:
        GraphObs = TGraph(len(obsX), obsX, obsY)

    GraphObs.SetLineWidth(3)
    if not obs2 == "":

        ratio = []
        ratiox = []
        for index, val in enumerate(observedy):
            mass = observedx[index]
            foundIndex = -1
            for index2, mass2 in enumerate(observedx2):
                if mass == mass2:
                    foundIndex = index2

            if foundIndex > 0:
                ratio.append(observedy2[foundIndex] / val)
                ratiox.append(mass)
        ratioA = numpy.array(ratio)
        ratioX = numpy.array(ratiox)
        obsX2 = numpy.array(observedx2)
        obsY2 = numpy.array(observedy2)
        ratioGraph = TGraph(len(ratioX), ratioX, ratioA)
        if printStats: print "obsX2: ", obsX2
        if printStats: print "obsY2: ", obsY2

        if SMOOTH:
            smooth_obs2 = TGraphSmooth("normal")
            GraphObs2_nonSmooth = TGraph(len(obsX2), obsX2, obsY2)
            GraphObs2 = smooth_obs2.SmoothSuper(GraphObs2_nonSmooth, "linear",
                                                0, 0.005)
        else:
            GraphObs2 = TGraph(len(obsX2), obsX2, obsY2)

        GraphObs2.SetLineWidth(3)

    xSecCurves = []
    xSecCurves.append(getFittedXSecCurve("CI_%s" % interference, 1.3))

    #Draw the graphs:
    plotPad.SetLogy()
    DummyGraph = TH1F("DummyGraph", "", 100, 10, 46)
    DummyGraph.GetXaxis().SetTitle("#Lambda [TeV]")
    if chan == "mumu":
        DummyGraph.GetYaxis().SetTitle(
            "95% CL limit on #sigma(pp#rightarrow CI+X#rightarrow#mu#mu +X) [pb]"
        )
    elif chan == "elel":
        DummyGraph.GetYaxis().SetTitle(
            "95% CL limit on #sigma(pp#rightarrow CI+X#rightarrowee +X) [pb]")
    elif chan == "elmu":
        DummyGraph.GetYaxis().SetTitle(
            "95% CL limit on #sigma(pp#rightarrow CI+X#rightarrow#font[12]{ll}) [pb]"
        )

    gStyle.SetOptStat(0)
    DummyGraph.GetXaxis().SetRangeUser(10, 46)

    DummyGraph.SetMinimum(5e-4)
    DummyGraph.SetMaximum(1)
    DummyGraph.GetXaxis().SetLabelSize(0.04)
    DummyGraph.GetXaxis().SetTitleSize(0.045)
    DummyGraph.GetXaxis().SetTitleOffset(1.)
    DummyGraph.GetYaxis().SetLabelSize(0.04)
    DummyGraph.GetYaxis().SetTitleSize(0.045)
    DummyGraph.GetYaxis().SetTitleOffset(1.)
    DummyGraph.Draw()
    if (FULL):
        GraphErr2Sig.Draw("F")
        GraphErr1Sig.Draw("F")
        GraphExp.Draw("lpsame")
    else:
        if obs2 == "":
            GraphExp.Draw("lp")
    if not EXPONLY:
        GraphObs.Draw("plsame")
    if not obs2 == "":
        GraphObs2.SetLineColor(ROOT.kRed)
        GraphObs2.SetLineStyle(ROOT.kDashed)
        GraphObs2.Draw("plsame")
    for curve in xSecCurves:
        print curve.Eval(28)
        #curve.Draw()
        curve.Draw("sameR")

    plCMS = TPaveLabel(.15, .81, .25, .88, "CMS", "NBNDC")
    #plCMS.SetTextSize(0.8)
    plCMS.SetTextAlign(12)
    plCMS.SetTextFont(62)
    plCMS.SetFillColor(0)
    plCMS.SetFillStyle(0)
    plCMS.SetBorderSize(0)

    plCMS.Draw()

    plPrelim = TPaveLabel(.15, .76, .275, .82, "Supplementary", "NBNDC")
    plPrelim.SetTextSize(0.6)
    plPrelim.SetTextAlign(12)
    plPrelim.SetTextFont(52)
    plPrelim.SetFillColor(0)
    plPrelim.SetFillStyle(0)
    plPrelim.SetBorderSize(0)
    #plPrelim.Draw()

    cCL.SetTickx(1)
    cCL.SetTicky(1)
    cCL.RedrawAxis()
    cCL.Update()

    #leg=TLegend(0.65,0.65,0.87,0.87,"","brNDC")
    leg = TLegend(0.440517, 0.523051, 0.834885, 0.878644, "", "brNDC")
    #    	leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC")
    leg.SetTextSize(0.032)
    if not obs2 == "":
        if ratioLabel == "":
            ratioLabel = "Variant/Default"
        ratioLabels = ratioLabel.split("/")
        print ratioLabels
        leg.AddEntry(GraphObs, "%s Observed 95%% CL limit" % ratioLabels[1],
                     "l")
        leg.AddEntry(GraphObs2, "%s Observed 95%% CL limit" % ratioLabels[0],
                     "l")

    else:
        if not EXPONLY:
            leg.AddEntry(GraphObs, "Obs. 95% CL limit", "l")
        leg.AddEntry(GraphExp, "Exp. 95% CL limit, median", "l")
        if (FULL):
            leg.AddEntry(GraphErr1Sig, "Exp. (68%)", "f")
            leg.AddEntry(GraphErr2Sig, "Exp. (95%)", "f")

    leg.AddEntry(xSecCurves[0], labels[interference], "l")
    leg.SetLineWidth(0)
    leg.SetLineStyle(0)
    leg.SetFillStyle(0)
    leg.SetLineColor(0)
    leg.Draw("hist")

    if "Moriond" in output:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "36.3 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "35.9 fb^{-1} (13 TeV, ee)", "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "35.9 fb^{-1} (13 TeV, ee) + 36.3 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")

    elif "2017" in output:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "42.1 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "41.5 fb^{-1} (13 TeV, ee)", "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "41.5 fb^{-1} (13 TeV, ee) + 42.1 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")
    else:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "13.0 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99, "2.7 fb^{-1} (13 TeV, ee)",
                                "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")

    plLumi.SetTextSize(0.5)
    plLumi.SetTextFont(42)
    plLumi.SetFillColor(0)
    plLumi.SetBorderSize(0)
    plLumi.Draw()

    plotPad.RedrawAxis()

    if not obs2 == "":

        ratioPad.cd()

        line = ROOT.TLine(200, 1, 5500, 1)
        line.SetLineStyle(ROOT.kDashed)

        ROOT.gStyle.SetTitleSize(0.12, "Y")
        ROOT.gStyle.SetTitleYOffset(0.35)
        ROOT.gStyle.SetNdivisions(000, "Y")
        ROOT.gStyle.SetNdivisions(408, "Y")
        ratioPad.DrawFrame(200, 0.8, 5500, 1.2, "; ; %s" % ratioLabel)

        line.Draw("same")

        ratioGraph.Draw("sameP")

    cCL.Update()
    printPlots(cCL, output)