Esempio n. 1
0
def process_material(lcdd, m):
    #print 'Adding material ...', m.get('name')
    doc = lcdd.document()
    matname = m.get('name')
    density = m.find('D')
    composites = m.findall('fraction')
    table = doc.GetElementTable()
    mat = doc.GetMaterial(matname)
    if not mat:
        mat = TGeoMixture(matname, len(composites), density.getF('value'))
        SetOwnership(mat, False)
    elts = [mat.GetElement(i).GetName() for i in range(mat.GetNelements())]
    for c in composites:
        nam = c.get('ref')
        if nam not in elts:
            fraction = c.getF('n')
            if table.FindElement(nam):
                mat.AddElement(table.FindElement(nam), fraction)
            elif doc.GetMaterial(nam):
                mat.AddElement(doc.GetMaterial(nam), fraction)
            else:
                raise 'Something going very wrong. Undefined material:' + nam
    medium = doc.GetMedium(matname)
    if not medium:
        global unique_mat_id
        unique_mat_id = unique_mat_id - 1
        medium = TGeoMedium(matname, unique_mat_id, mat)
        SetOwnership(medium, False)
        medium.SetTitle('material')
        medium.SetUniqueID(unique_mat_id)
    lcdd.addMaterial(Handle_t(medium))
def makePlot(lumi, lumi_str, treeDA, treeMC, var, name, nbin, xmin, xmax, theCut, cuts, labelx, logx, protection):

    MC   = treeMC.getTH1F(lumi, "hMC_%s"%(name), var, nbin, xmin, xmax, theCut, '', labelx)
    MCS  = treeMC.getStack(lumi, "hMCS_%s"%(name), var, nbin, xmin, xmax, theCut, "", labelx)
    DATA = treeDA.getTH1F(lumi, "hDATA_%s"%(name), var, nbin, xmin, xmax, theCut, '', labelx)

    maxValmc = MC.GetMaximum() #GetBinContent(MC.GetMaximumBin())
    maxValdata = DATA.GetMaximum() #GetBinContent(DATA.GetMaximumBin())
    maxVal = max(maxValmc, maxValdata)
    if not logx:
        MC.GetYaxis().SetRangeUser(0.1, 1.3*maxVal)
        MCS.SetMaximum(1.3*maxVal)
        DATA.GetYaxis().SetRangeUser(0.1, 1.3*maxVal)
    else:
        MC.GetYaxis().SetRangeUser(0.1, 2.0*maxVal)
        MCS.SetMaximum(2.0*maxVal)
        DATA.GetYaxis().SetRangeUser(0.1, 2.0*maxVal)
    print "DATA integral ", DATA.Integral()
    print "MC   integral ", MC.Integral()
    SetOwnership(MC, 0 )   # 0 = release (not keep), 1 = keep
    SetOwnership(MCS, 0 )   # 0 = release (not keep), 1 = keep
    SetOwnership(DATA, 0 )   # 0 = release (not keep), 1 = keep
    plot = Canvas.Canvas('DataMC/%s/plot_%s'%(lumi_str,name), 'png,pdf,root', 0.65, 0.6, 0.85, 0.9)
    plot.addStack(MCS, "HIST", 1, 1)
    plot.addHisto(DATA, "E1,SAME", "Data", "P", r.kBlack, 1, 0)
    plot.saveRatio(1, 1, logx, lumi, DATA, MC)
def AeffPhiDepPlot(IRFs,
                   nph,
                   energy,
                   theta,
                   front=True,
                   back=False,
                   plot=True):
    #get phi points
    phis = [0 + i * (90. / (nph - 1.)) for i in range(nph)]
    #access available IRFs
    pyIrfLoader.Loader_go()
    if front and back:
        #get front and back IRFs, get effective area for phis for given energy and theta
        conv = 'FRONT + BACK'
        irfs_front = pyIrfLoader.IrfsFactory.instance().create(IRFs +
                                                               "::FRONT")
        irfs_back = pyIrfLoader.IrfsFactory.instance().create(IRFs + "::BACK")
        Aeff_front = getAeff_phi(irfs_front.aeff(), energy, theta, phis)
        Aeff_back = getAeff_phi(irfs_back.aeff(), energy, theta, phis)
        Aeff = Aeff_front + Aeff_back
    else:
        #access the necessary IRFs, get effective area for phis for given energy and theta
        conv = ('FRONT' if front else "BACK")
        irfs = pyIrfLoader.IrfsFactory.instance().create(IRFs + "::" + conv)
        Aeff = getAeff_phi(irfs.aeff(), energy, theta, phis)
    #expand the phi values out to 360 degrees, copy effective area values too
    phibins = array(phis + [p + 90.
                            for p in phis[1:]] + [p + 180. for p in phis[1:]] +
                    [p + 270. for p in phis[1:]])
    AeffValues = array([a for a in Aeff] + [a for a in Aeff[1:]] +
                       [a for a in Aeff[1:]] + [a for a in Aeff[1:]])
    #make and fill phi graph
    phigraph = TGraph(len(phibins), phibins, AeffValues)
    phigraph.SetMarkerStyle(20)
    phigraph.SetMarkerColor(1)
    phigraph.SetLineColor(1)
    if plot:
        #if plot set to True, draw and make some style choices
        phcan = TCanvas(
            'phcan',
            '%s %s Effective Area vs. phi for E = %.1f MeV and theta = %.1f deg'
            % (IRFs, conv, energy, theta), 1000, 800)
        phcan.SetTicks(1, 1)
        pdummy = TH1F('pdummy', '', 1000, 0, 360)
        pdummy.SetXTitle('#phi (#circ)')
        pdummy.GetXaxis().CenterTitle()
        pdummy.SetYTitle('A_{eff} (m^{2} )')
        pdummy.GetYaxis().CenterTitle()
        pdummy.GetYaxis().SetRangeUser(0., 1.)
        pdummy.Draw()
        phigraph.Draw('plsame')
        SetOwnership(phigraph, False)
        SetOwnership(phcan, False)
        SetOwnership(pdummy, False)
    return phigraph
Esempio n. 4
0
def addTRUGrid(subsystem, hist):
    """ Add a grid of TLines representing the TRU on a canvas.

    Note:
        Assumes that the canvas is already created.

    Note:
        Allocates a large number of TLines which have SetOwnership(obj, False),
        so this could lead to memory problems.

    """
    # TEMP
    logger.debug("TRU Grid histName: {0}".format(hist.histName))

    # Draw grid for TRUs in full EMCal SMs
    for x in range(8, 48, 8):
        line = TLine(x, 0, x, 60)
        SetOwnership(line, False)
        line.Draw()
    # 60 + 1 to ensure that 60 is plotted
    for y in range(12, 60 + 1, 12):
        line = TLine(0, y, 48, y)
        SetOwnership(line, False)
        line.Draw()

    # Draw grid for TRUs in 1/3 EMCal SMs
    line = TLine(0, 64, 48, 64)
    SetOwnership(line, False)
    line.Draw()
    line = TLine(24, 60, 24, 64)
    SetOwnership(line, False)
    line.Draw()

    # Draw grid for TRUs in 2/3 DCal SMs
    for x in range(8, 48, 8):
        if (x == 24):
            # skip PHOS hole
            continue
        line = TLine(x, 64, x, 100)
        SetOwnership(line, False)
        line.Draw()
    for y in range(76, 100, 12):
        line = TLine(0, y, 16, y)
        SetOwnership(line, False)
        line.Draw()
        # skip PHOS hole
        line = TLine(32, y, 48, y)
        SetOwnership(line, False)
        line.Draw()

    # Draw grid for TRUs in 1/3 DCal SMs
    line = TLine(0, 100, 48, 100)
    SetOwnership(line, False)
    line.Draw()
    line = TLine(24, 100, 24, 104)
    SetOwnership(line, False)
    line.Draw()
def draw_2histograms( histo1, histo2, x_axisName, y_axisName, leg1Name, leg2Name ):
   histo1.GetXaxis().SetTitle(x_axisName)
   if (y_axisName==""):
      histo1.GetYaxis().SetTitle("Entries/per bin")
   else:
      histo1.GetYaxis().SetTitle(y_axisName)

   histo2.SetLineColor(2)

   if (leg1Name!=""):
      histo1.SetStats(0)
      histo2.SetStats(0)
      legend=TLegend(0.45,0.78,0.9,0.9)
      legend.AddEntry(histo1, leg1Name, "l")
      legend.AddEntry(histo2, leg2Name, "l")
      legend.SetTextSize(0.05)
      SetOwnership( legend, 0 )

   maximum1 = 1.2*histo1.GetMaximum()
   maximum2 = 1.2*histo2.GetMaximum()
   maximum = maximum1
   if (maximum2>maximum):
      maximum = maximum2
   histo1.SetMaximum(maximum)
   histo1.Draw()
   histo2.Draw("same")
   if (leg1Name!=""):
      legend.Draw("same")

   gPad.Update()

   return
Esempio n. 6
0
def combined_histogram(histograms_or_stack):
    """Returns a combined TH1 object from a collection of histograms with bin
    errors calculated.

    Args:
        histograms_or_stack: A single histogram, a non-empty iterable of
            histograms, or a THStack object which represents the collection of
            histograms

    Returns:
        A single TH1 object which is a combination of the provided histograms
        and which has bin errors calculated.
    """
    # Convert the histograms to an iterable, always unpacking THStack objects
    histograms = drawable_iterable(histograms_or_stack, True)

    # Grab the first histogram, making sure bin errors are calculated before
    # adding the remaining histograms
    result = histograms[0].Clone(_rand_uuid())
    SetOwnership(result, False)
    if result.GetSumw2N() == 0:
        result.Sumw2()

    # Add the other histograms to the result
    map(result.Add, histograms[1:])

    return result
Esempio n. 7
0
def addEnergyAxisToPatches(subsystem, hist, processingOptions):
    """ Adds an additional axis showing the conversion from ADC counts to Energy.

    These conditions are set for "{EMCal,DCal}(Max)PatchAmp".
    It creates a new TGaxis that shows the ADC to Energy conversion. It then draws it on selected
    histogram. 

    Warning:
        This function assumes that there is already a canvas created.

    Note:
        TGaxis removes ownership from Python to ensure that it continues to exist outside of the
        function scope.

    Args:
        hist (TH1): The histogram to be processed.

    Returns:
        None

    """
    kEMCL1ADCtoGeV = 0.07874  # Conversion from EMCAL Level1 ADC to energy
    adcMin = hist.hist.GetXaxis().GetXmin()
    adcMax = hist.hist.GetXaxis().GetXmax()
    EMax = adcMax * kEMCL1ADCtoGeV
    EMin = adcMin * kEMCL1ADCtoGeV
    #yMax = gPad.GetUymax()    # this function does not work here (log problem)
    yMax = 2 * hist.hist.GetMaximum()
    energyAxis = TGaxis(adcMin, yMax, adcMax, yMax, EMin, EMax, 510, "-")
    SetOwnership(energyAxis, False)
    energyAxis.SetTitle("Energy (GeV)")
    energyAxis.Draw()
Esempio n. 8
0
def showAllPlotsInDict(listOfGraphs, hAxes, cDebug):
    #print listOfGraphs

    cDebug.cd()

    color = 0  # black

    hAxes.Draw("")

    leg = root.TLegend(0.15, 0.71, 0.35, 0.88)
    leg.SetBorderSize(1)
    leg.SetFillColor(0)
    # trick to have the legend not disappearing
    SetOwnership(leg, 0)  # 0 = release (not keep), 1 = keep, ot

    for graph in listOfGraphs:

        color += 1
        leg.AddEntry(graph, "Kick Response Meas #%d" % color, "lp")

        # skip the color white
        if (color == 10):
            color = 11
        graph.SetLineColor(color)
        graph.SetMarkerColor(color)
        graph.SetMarkerStyle(20)

        graph.Draw("LP")

    leg.Draw()

    cDebug.Update()
Esempio n. 9
0
def matrixCorrection(histds, cf, CR, eventAcc, histdet, opt):
    histcs = dict()
    errorMatrices = dict()
    nsample = len(histds)
    for isample in range(nsample):
        histd = histds[isample]
        title = histd.GetTitle()
        histc = TH1D("histc" + str(isample), title + " corr", nbin, binEdges)
        SetOwnership(histc, False)
        valuesd = getArray(histd)
        errorsd = getArrayErrors(histd)
        valuesh = CR.dot(valuesd)
        if "u" in opt:
            # Use expected error
            scf = histd.GetEntries() / histdet.GetEntries()
            for i in range(nbin):
                errorsd[i] = histdet.GetBinError(i + 1) * sqrt(scf)
        # Error propagation from correction matrix; it is not
        # symmetric so order of indices matters
        diagErrorMatrixd = np.diag(errorsd**2)
        errorMatrixh = np.dot(CR, np.dot(diagErrorMatrixd, CR.transpose()))
        # Set corrected values and bin-by-bin error in histo
        errorsh = errorsd * cf
        for i in range(nbin):
            histc.SetBinContent(i + 1, valuesh[i])
            histc.SetBinError(i + 1, errorsh[i])
        # Number of entries from filled events and event acceptance
        nevent = histd.GetEntries()
        neventCorrected = nevent * eventAcc
        histc.SetEntries(neventCorrected)
        histcs[isample] = histc
        errorMatrices[isample] = errorMatrixh
    # Fin
    return histcs, errorMatrices
Esempio n. 10
0
def OutputRootFile(outfile):

    o = TFile(outfile,"RECREATE");
    print "Output written to: ", outfile
    SetOwnership( o, False )   # tell python not to take ownership

    return o
Esempio n. 11
0
   def getLoopTH2F(self, inputdir, hname):
     
     ## Correct input dir absolute path:
     inputdir = inputdir + '/' if inputdir[-1] != '/' else inputdir

     ## Init histogram:
     _f0 = r.TFile(inputdir + '{0}__{1}__{2}__0.root'.format(self.name, self.blocks[0].name, self.blocks[0].samples[0].name))
     hth2f = copy.deepcopy(_f0.Get(hname + '__{0}__{1}__{2}__0'.format(self.name, self.blocks[0].name, self.blocks[0].samples[0].name)))
     _f0.Close()
     SetOwnership(hth2f, 0)

     ## Loop over files:
     for _b,b in enumerate(self.blocks):
       for _s,s in enumerate(b.samples):
         for t in range(0, len(s.ttrees)):
           if t == 0 and _s == 0 and _b == 0: continue
           _ft = r.TFile(inputdir + '{0}__{1}__{2}__{3}.root'.format(self.name, b.name, s.name, str(t)))
           _haux = _ft.Get(hname + '__{0}__{1}__{2}__{3}'.format(self.name, b.name, s.name, str(t)))
           try:
               _h = _haux.Clone()
               hth2f.Add(_h)
           except ReferenceError:
               print(hname + '__{0}__{1}__{2}__{3}'.format(self.name, b.name, s.name, str(t)) + ' cannot be accesed: Skipping')
               pass
           _ft.Close()

     return hth2f
Esempio n. 12
0
    def _make_underlying_model(self):
        self.pdfs = {}
        self.yields = {}  # yields are plain floats
        self.ryields = {}  # keep track of roofit objects for memory management
        nbins, xmin, xmax = self.plot.histos[0].GetBinning()
        self.xvar = RooRealVar("x", "x", xmin, xmax)
        self.xvar.setBins(nbins)
        self.pdfs = {}
        self.hists = []
        pdfs = RooArgList()
        yields = RooArgList()
        for compname, comp in self.plot.histosDict.iteritems():
            if comp.weighted.Integral() == 0:
                continue
            assert (isinstance(comp, Histogram))
            hist = RooDataHist(compname, compname, RooArgList(self.xvar),
                               comp.weighted)
            SetOwnership(hist, False)
            # self.hists.append(hist)
            pdf = RooHistPdf(compname, compname, RooArgSet(self.xvar), hist)
            self.pdfs[compname] = pdf
            # self.pdfs[compname].Print()
            pdfs.add(pdf)
            nevts = comp.Integral(xmin=xmin, xmax=xmax)
            nmin = min(0, nevts * (1 - comp.uncertainty))
            nmax = nevts * (1 + comp.uncertainty)
            theyield = RooRealVar('n{}'.format(compname),
                                  'n{}'.format(compname), nevts, nmin, nmax)
            self.ryields[compname] = theyield
            self.yields[compname] = nevts
            yields.add(theyield)

        self.underlying_model = RooAddPdf('model', 'model', pdfs, yields)
Esempio n. 13
0
   def getStack(self, lumi, name, var, nbin, xmin, xmax, cut, options, xlabel):
     if cut == '':
       cut = '(1)'
     hs = THStack(name, "")
     SetOwnership(hs, 0 )
     for b in self.blocks:
     
       AuxName = "auxStack_block_" + name + "_" + b.name
       haux = b.getTH1F(lumi, AuxName, var, nbin, xmin, xmax, cut, options, xlabel)
       haux.SetFillColor(b.color)
       haux.SetLineColor(r.kBlack)
       haux.SetTitle(b.label)
       hs.Add(haux)
       del haux


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

     del can_aux

     ylabel = "Events"
     if xmax != xmin:
       hs.GetXaxis().SetTitle(xlabel)
       b = int((xmax-xmin)/nbin)
       ylabel = "Events / " + str(b) + " GeV"
     else:     
       ylabel = "Events"
   
     hs.GetYaxis().SetTitle(ylabel)
     return hs   
Esempio n. 14
0
    def create_file_and_tree(self):
        f = ROOT.TFile(self.filename, 'RECREATE')
        t = ROOT.TTree(self.treename, self.treename)
        # Prevent double deletion of the tree (Python and C++ TFile)
        SetOwnership(t, False)

        return f, t
Esempio n. 15
0
def histogram_stack(*histograms):
    """Creates a THStack object with a unique identifier from the specified
    histograms.

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

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

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

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

    # Add histograms
    map(stack.Add, histograms)

    return stack
Esempio n. 16
0
def makeTObjArray(theList):
    """Turn a python iterable into a ROOT TObjArray"""
    # Make PyROOT give up ownership of the things that are being placed in the
    # TObjArary. They get deleted because of result.SetOwner()
    result = TObjArray()
    result.SetOwner()
    for item in theList:
        SetOwnership(item, False)
        result.Add(item)
    return result
Esempio n. 17
0
def patchAmpOptions(subsystem, hist, processingOptions):
    # Setup canvas as desired
    hist.canvas.SetLogy(True)
    hist.canvas.SetGrid(1, 1)

    # Check for the corresponding hist
    #if "DCal" in hist.GetName():
    #    nameToCheck = hist.GetName().replace("DCal", "EMCal")
    #else:
    #    nameToCheck = hist.GetName().replace("EMCal", "DCal")
    #otherHist = qaContainer.getHist(nameToCheck)

    # Plot both on the same canvas if they both exist
    #if otherHist is not None:
    if hist.hist.InheritsFrom(THStack.Class()):
        # Add legend
        legend = TLegend(0.6, 0.9, 0.9, 0.7)
        legend.SetBorderSize(0)
        legend.SetFillStyle(0)
        SetOwnership(legend, False)

        # Lists to use to plot
        detectors = ["EMCal", "DCal"]
        colors = [kRed + 1, kBlue + 1]
        markers = [kFullCircle, kOpenCircle]
        options = ["", ""]

        # Plot elements
        for tempHist, detector, color, marker, option in zip(
                hist.hist.GetHists(), detectors, colors, markers, options):
            tempHist.Sumw2()
            tempHist.SetMarkerSize(0.8)
            tempHist.SetMarkerStyle(marker)
            tempHist.SetLineColor(color)
            tempHist.SetMarkerColor(color)

            if processingOptions["scaleHists"]:
                tempHist.Scale(1. / subsystem.nEvents)
            tempHist.GetYaxis().SetTitle("entries / events")

            # Draw hists
            # This is not the usual philosophy. We are clearing the canvas and then plotting
            # the second hist on it
            #tempHist.Draw(option)
            legend.AddEntry(tempHist, detector, "pe")

        # Add legend
        legend.Draw()

        # Ensure that canvas is updated to account for the new object colors
        hist.canvas.Update()

        # Add energy axis
        addEnergyAxisToPatches(subsystem, hist, processingOptions)
Esempio n. 18
0
 def __init__(self, name='', yMargin = 0.2 ):
     self.name = name
     self.frame = TCanvas(name,name) # in case set the width above
     SetOwnership(self.frame,False)
     self.mainPad = TPad(name+'mainPad', '' ,0.01,yMargin,0.99,0.99)
     self.mainPad.SetBottomMargin(0)
     self.comparisonPad = TPad(name+'comparisonPad', '' ,0.01,0.01,0.99,yMargin)
     self.comparisonPad.SetTopMargin(0)
     self.comparisonPad.SetBottomMargin(0.33);
     self.comparisonPad.SetGridy()
     self.draw()
Esempio n. 19
0
def plotMC(mc, signal, name, legend, *text):
    canvas = TCanvas(name,name)
    SetOwnership(canvas,False)
    mc.Draw('fhist')
    if signal: signal.Draw('hist,same')
    if legend: legend.Draw()
    for t in range(len(text)): text[t].Draw()
    raw_input('plot MC for '+name) # why the hack this is needed?!?
    canvas.Modified()
    canvas.Update()
    return canvas
Esempio n. 20
0
def draw_2Dbis(t, title, h_bins, nBinsY, binsY, to_draw, extra_cut, opt = ""):

    nBins  = int(h_bins[1:-1].split(',')[0])
    minBin = float(h_bins[1:-1].split(',')[1])
    maxBin = float(h_bins[1:-1].split(',')[2])

    num = TH2F("num", title, nBins, minBin, maxBin, nBinsY, binsY)
    t.Draw(to_draw + ">>num", extra_cut, opt)

    SetOwnership(num, False)
    return num
Esempio n. 21
0
def process_material(description, m):
    #print 'Adding material ...', m.get('name')
    density = m.find('D')
    radlen = m.find('RL')
    intlen = m.find('NIL')
    composites = m.findall('fraction') or m.findall('composite')
    table = gGeoManager.GetElementTable()
    mat = gGeoManager.GetMaterial(m.name)
    if not mat:
        mat = TGeoMixture(
            m.name, len(composites),
            eval(
                density.get('value') + '*' + density.get('unit') + '/(g/cm3)',
                constants))
        SetOwnership(mat, False)
    rl = (radlen is not None) and eval(
        radlen.get('value') + '*' + radlen.get('unit'), constants) or 0.0
    il = (intlen is not None) and eval(
        intlen.get('value') + '*' + intlen.get('unit'), constants) or 0.0
    #mat.SetRadLen(-rl, -il)
    elts = [mat.GetElement(i).GetName() for i in range(mat.GetNelements())]
    for c in composites:
        nam = c.ref
        if nam not in elts:
            if c.tag == 'composite': fraction = c.getI('n')
            elif c.tag == 'fraction': fraction = c.getF('n')
            if table.FindElement(nam):
                mat.AddElement(table.FindElement(nam), fraction)
            elif gGeoManager.GetMaterial(nam):
                mat.AddElement(gGeoManager.GetMaterial(nam), fraction)
            else:
                raise 'Something going very wrong. Undefined material:' + nam
    medium = gGeoManager.GetMedium(m.name)
    if not medium:
        global unique_mat_id
        unique_mat_id = unique_mat_id - 1
        medium = TGeoMedium(m.name, unique_mat_id, mat)
        SetOwnership(medium, False)
        medium.SetTitle('material')
        medium.SetUniqueID(unique_mat_id)
    description.addMaterial(Handle(medium))
Esempio n. 22
0
def setupLegend(t_plots, x1, y1, x2, y2, textSize):
    
    l = TLegend(float(x1), float(y1), float(x2), float(y2))
    SetOwnership(l, 0)
    l.SetFillColor(0)
    l.SetBorderSize(0)
    l.SetTextSize(float(textSize))
    for i in reversed(xrange(len(t_plots))):
        if t_plots[i][1]:
            l.AddEntry(t_plots[i][0], t_plots[i][1], t_plots[i][2])

    l.Draw()
Esempio n. 23
0
def configureCanvasLegend(canvas,aliases,textSize=25):
	height = 1.2*len(aliases)*textSize/canvas.GetWh()
	width = int(max([len(name) for name in aliases])*textSize*.50)+70
	canvas.SetLeftMargin(canvas.GetLeftMargin()*textSize/14.)
	canvas.SetBottomMargin(canvas.GetBottomMargin()*textSize/14.)
	legend = TLegend(0.00,1-canvas.GetTopMargin(),150./width,1-canvas.GetTopMargin()-height)
	legend.SetTextSize(textSize)
	legend.SetFillColor(0)
	legend.SetShadowColor(0)
	legend.SetBorderSize(0)
	SetOwnership(legend, 0)

	return canvas,legend
Esempio n. 24
0
def draw_geff(t, title, h_bins, to_draw, den_cut, extra_num_cut,
              opt = "", color = kBlue, marker_st = 1, marker_sz = 1.):
    """Make an efficiency plot"""

    ## total numerator selection cut
    num_cut = AND(den_cut,extra_num_cut)

    ## PyROOT works a little different than ROOT when you are plotting
    ## histograms directly from tree. Hence, this work-around
    nBins  = int(h_bins[1:-1].split(',')[0])
    minBin = float(h_bins[1:-1].split(',')[1])
    maxBin = float(h_bins[1:-1].split(',')[2])

    num = TH1F("num", "", nBins, minBin, maxBin)
    den = TH1F("den", "", nBins, minBin, maxBin)

    t.Draw(to_draw + ">>num", num_cut, "goff")
    t.Draw(to_draw + ">>den", den_cut, "goff")

    debug = False
    if debug:
        print("Denominator cut", den_cut, den.GetEntries())
        print("Numerator cut", num_cut, num.GetEntries())

    ## check if the number of passed entries larger than total entries
    doConsistencyCheck = False
    if doConsistencyCheck:
        for i in range(0,nBins):
            print(i, num.GetBinContent(i), den.GetBinContent(i))
            if num.GetBinContent(i) > den.GetBinContent(i):
                print(">>>Error: passed entries > total entries")

    eff = TEfficiency(num, den)

    ## plotting options
    if not "same" in opt:
        num.Reset()
        num.GetYaxis().SetRangeUser(0.0,1.1)
        num.SetStats(0)
        num.SetTitle(title)
        num.Draw()

    eff.SetLineWidth(2)
    eff.SetLineColor(color)
    eff.SetMarkerStyle(marker_st)
    eff.SetMarkerColor(color)
    eff.SetMarkerSize(marker_sz)
    eff.Draw(opt + " same")

    SetOwnership(eff, False)
    return eff
Esempio n. 25
0
def ratioOnly(ratio_h, thred, name):
    c = r.TCanvas(name, name, 800, 800)
    ratio = ratio_h.Clone(name)
    #    ratio = ratio_h.DrawCopy(name)
    r.gPad.SetGridx()
    r.gPad.SetGridy()

    ratio.SetTitle("")
    ratio.SetMarkerStyle(20)
    ratio.SetMarkerSize(1.1)
    ratio.GetYaxis().SetTitle("Correction")
    ratio.GetYaxis().SetTitleSize(35)
    ratio.GetYaxis().SetTitleFont(43)
    ratio.GetYaxis().SetTitleOffset(1.1)
    ratio.GetYaxis().SetLabelFont(43)
    ratio.GetYaxis().SetLabelSize(30)
    ratio.GetXaxis().SetTitle("#Delta R (bb)^{ave}")
    ratio.GetXaxis().SetTitleOffset(1.0)
    ratio.GetXaxis().SetTitleSize(35)
    ratio.GetXaxis().SetTitleFont(43)
    ratio.GetXaxis().SetLabelFont(43)
    ratio.GetXaxis().SetLabelSize(30)

    fitf = r.TF1(name + "_f", "[0]", thred, 5)
    #    fitf.SetLineColor(r.kBlack)
    fitf.SetLineWidth(2)
    #    res = ratio.Fit(fitf, "R S")
    ratio.GetYaxis().SetRangeUser(0, 2)
    ratio.Draw("E0")

    leg = r.TLegend(0.6, 0.79, 0.89, 0.89)
    leg.AddEntry(ratio, "Measured")
    leg.AddEntry(fitf, "Flattened")
    #    text = "#splitline{Flatterning(95% CL)}{#chi^{2} = " + "{:.2f}".format(fitf.GetChisquare())  + " }"
    #    leg.AddEntry(interval, text)
    leg.SetBorderSize(0)
    leg.Draw("same")

    line = r.TLine(0, 1, 5, 1)
    line.SetLineWidth(2)
    line.Draw("same")
    SetOwnership(line, 0)

    CMS_lumi.CMS_lumi(c, iPeriod, iPos)
    c.cd()
    c.Update()
    c.SaveAs(outdir + "/" + name + "_Fit.pdf")
    return c
Esempio n. 26
0
def load_file(file, mode=None):
    """Open a ROOT file

    Args:
        file: The path to the ROOT file
        mode: The mode with which to open the file

    Returns:
        A TFile object
    """
    if mode is None:
        tf = TFile.Open(file)
    else:
        tf = TFile.Open(file, mode)
    SetOwnership(tf, False)
    return tf
Esempio n. 27
0
def checkForOutliers(hist, qaContainer):
    """ Checks for outliers in selected histograms.

    Outliers are calculated by looking at the standard deviation. See: :func:`hasSignalOutlier()`.
    This function is mainly a proof of concept, but could become more viable with a bit more work.

    Note:
        This function will add a large TLegend to the histogram noting the mean and the number of
        outliers. It will also display the recalculated mean excluding the outlier(s).

    Args:
        hist (TH1): The histogram to be processed.
        qaContainer (:class:`~processRuns.qa.qaFunctionContainer`): Contains information
            about the QA function and histograms, as well as the run being processed.

    Returns:
        None

    """
    # If outlier data point, print warning banner
    if hist.GetName() == "":
        tempList = hasSignalOutlier(
            hist
        )  # array of info from hasSignalOutlier function, to print on legend
        numOutliers = tempList[0]
        mean = tempList[1]
        stdev = tempList[2]
        newMean = tempList[3]
        newStdev = tempList[4]
        if (numOutliers):
            # Create TLegend and fill with information if there is an outlier.
            leg = TLegend(0.15, 0.5, 0.7, 0.8)
            SetOwnership(leg, False)

            leg.SetBorderSize(4)
            leg.SetShadowColor(2)
            leg.SetHeader("#splitline{OUTLIER SIGNAL DETECTED}{IN %s BINS!}" %
                          numOutliers)
            leg.AddEntry(
                None, "Mean: %s, Stdev: %s" % ('%.2f' % mean, '%.2f' % stdev),
                "")
            leg.AddEntry(
                None, "New mean: %s, New Stdev: %s" %
                ('%.2f' % newMean, '%.2f' % newStdev), "")
            leg.SetTextSize(0.04)
            leg.SetTextColor(2)
            leg.Draw()
Esempio n. 28
0
def LoopAndScale(dir,Weight):
    """goes through all histos and reweights them"""

    nextkey=TIter(dir.GetListOfKeys())
    key=nextkey()


    #=================================================
    #Iterate over the histos in the file
    #ListOfNewH=[]

    while(str(key).find('nil') == -1):

        #GET THE KEY
        obj=dir.Get(key.GetName() )

        #print 'the current directory is ',gDirectory.pwd()
        #rint 'currently at object',obj.GetName()
        #raw_input()
        #
        #IF a histo
        #
        #
        if obj.IsA().InheritsFrom("TH1"):

            
            newhist=obj.Clone(key.GetName())
            SetOwnership(newhist,False)
            newhist.Scale(Weight)

        elif obj.IsA().InheritsFrom("TDirectory"):

            newdir=gDirectory.mkdir(obj.GetName())
            newdir.cd()
            LoopAndScale(obj,Weight)
            #
            #
            #set it to return back to where it was
            gDirectory.GetMotherDir().cd()
        else:
            print "Unknown object"
            print "It is called ",key.GetName()
        #
        #dir.cd()
        key=nextkey()
Esempio n. 29
0
def draw_1D(t, title, h_bins, to_draw, extra_cut, opt = "",
             color = kBlue, marker_st = 20):

    nBins  = int(h_bins[1:-1].split(',')[0])
    minBin = float(h_bins[1:-1].split(',')[1])
    maxBin = float(h_bins[1:-1].split(',')[2])

    num = TH1F("num", "", nBins, minBin, maxBin)
    t.Draw(to_draw + ">>num", extra_cut, "goff")

    num.SetLineWidth(2)
    num.SetLineColor(color)
    num.SetMarkerStyle(marker_st)
    num.SetMarkerColor(color)
    num.SetMarkerSize(.5)

    SetOwnership(num, False)
    return num
Esempio n. 30
0
   def getLoopTH1F(self, inputdir, hname, doOF = True):
     
     ## Correct input dir absolute path:
     inputdir = inputdir + '/' if inputdir[-1] != '/' else inputdir

     ## Init histogram:
     _f0 = r.TFile(inputdir + '{0}__{1}__{2}__0.root'.format(self.name, self.blocks[0].name, self.blocks[0].samples[0].name))
     hth1f = copy.deepcopy(_f0.Get(hname + '__{0}__{1}__{2}__0'.format(self.name, self.blocks[0].name, self.blocks[0].samples[0].name)))
     if doOF: 
         hth1f.SetBinContent(hth1f.GetNbinsX(), hth1f.GetBinContent(hth1f.GetNbinsX()) + hth1f.GetBinContent(hth1f.GetNbinsX() + 1) )
         hth1f.SetBinError(hth1f.GetNbinsX(), hth1f.GetBinError(hth1f.GetNbinsX()) + hth1f.GetBinError(hth1f.GetNbinsX() + 1) )
     _f0.Close()
     SetOwnership(hth1f, 0)

     ## Loop over files:
     for _b,b in enumerate(self.blocks):
       for _s,s in enumerate(b.samples):
         for t in range(0, len(s.ttrees)):
           if t == 0 and _s == 0 and _b == 0: continue
           _ft = r.TFile(inputdir + '{0}__{1}__{2}__{3}.root'.format(self.name, b.name, s.name, str(t)))
           _haux = _ft.Get(hname + '__{0}__{1}__{2}__{3}'.format(self.name, b.name, s.name, str(t)))
           try:
               _h = _haux.Clone()
               if doOF: 
                   _h.SetBinContent(_h.GetNbinsX(), _h.GetBinContent(_h.GetNbinsX()) + _h.GetBinContent(_h.GetNbinsX() + 1) )
                   _h.SetBinError(_h.GetNbinsX(), _h.GetBinError(_h.GetNbinsX()) + _h.GetBinError(_h.GetNbinsX() + 1) )
               hth1f.Add(_h)
           except ReferenceError:
               print(hname + '__{0}__{1}__{2}__{3}'.format(self.name, b.name, s.name, str(t)) + ' cannot be accesed: Skipping')
               pass
           _ft.Close()

     ## Get some values:
     xmin = float(hth1f.GetXaxis().GetXmin())
     xmax = float(hth1f.GetXaxis().GetXmax())
     nbin = hth1f.GetXaxis().GetNbins()

     ## Correct y axis
     ylabel = "Events"
     b = (xmax-xmin)/float(nbin)
     ylabel = "Events / " + "{:.2f}".format(b) + " units"
     hth1f.GetYaxis().SetTitle(ylabel)

     return hth1f