コード例 #1
0
ファイル: fit.py プロジェクト: mahmoussa/LengthScale
def fitPerBxStep(options):
    """Fit histograms (per BX and step) with a function"""
    oldname = options['scan'] + '_' + options['name']
    newname = oldname + options['extra']
    if 'method' in options:
        oldname += '_' + options['method']
        newname += '_' + options['method']
    f = openRootFileU(oldname)
    g = openRootFileW(newname)
    for bx in options['crossings']:
        for step in range(len(O['nominalPos'][options['scan']])):
            print '<<< Fit:', options['scan'], bx, 'step', step
            histname = plotName(oldname+'_bx'+str(bx)+'_step'+str(step), \
                                timestamp=False)
            histnew = plotName(newname+'_bx'+str(bx)+'_step'+str(step), \
                               timestamp=False)
            hist = f.Get(histname)
            hist.SetName(histnew)
            if options['range']:
                mini, maxi = options['range'](hist)
                hist.Fit(options['fit'], options['fitopt'], '', mini, maxi)
            else:
                hist.Fit(options['fit'], options['fitopt'])
            hist.Write('', TObject.kOverwrite)
    closeRootFile(g, newname)
    closeRootFile(f, oldname)
コード例 #2
0
def plotPerLumiSection(options):
    """Save profile histograms per lumisection to PDF files"""
    name = options['name'] + '_perLS'
    f = openRootFileR(name)
    histname = plotName(options['title'] + '_perLS', timestamp=False)
    filename = plotName(options['title'] + '_perLS', timestamp=True)
    filepath = plotPath(options['title'] + '_perLS', timestamp=True)
    print '<<< Save plot:', filepath
    hist = f.Get(histname)
    canvas = TCanvas()
    canvas.SetLogy(options['logy'])
    gStyle.SetOptStat(options['optstat'])
    hist.Draw()
    gPad.Update()
    hist.GetXaxis().SetTitle('Lumisection')
    hist.GetYaxis().SetTitle(options['ytitle'])
    hist.GetYaxis().SetTitleOffset(1.2)
    for axis in [hist.GetXaxis(), hist.GetYaxis()]:
        axis.SetTitleFont(133)
        axis.SetTitleSize(16)
        axis.SetLabelFont(133)
        axis.SetLabelSize(12)
        axis.CenterTitle()
    drawSignature(filename)
    gPad.Modified()
    gPad.Update()
    #canvas.Print(filepath)
    #canvas.Close()
    #closeRootFile(f, name)
    return [canvas, hist, f]
コード例 #3
0
def plotPerTimeStamp(options):
    """Save profile histograms per timestamp to PDF files"""
    name = options['name'] + '_' + options['scan'] + '_perTime'
    if options['extra']:
        name += '_' + options['extra']
    f = openRootFileR(options['name'] + '_perTime')
    histname = plotName(name, timestamp=False)
    filename = plotName(name, timestamp=True)
    filepath = plotPath(name, timestamp=True)
    print '<<< Save plot:', filepath
    hist = f.Get(histname)
    hist.SetErrorOption(options['error'])
    if options['big']:
        canvas = TCanvas('c', '', 8000, 1200)
    else:
        canvas = TCanvas('c', '', 1400, 500)
    canvas.SetLogy(options['logy'])
    gStyle.SetOptStat(options['optstat'])
    hist.Draw()
    gPad.Update()
    hist.GetXaxis().SetTimeDisplay(1)
    hist.GetXaxis().SetTimeFormat('#splitline{%d.%m.%y}{%H:%M:%S}%F1969-12-31' \
                                  +' 22:00:00')
    hist.GetXaxis().SetLabelOffset(0.03)
    hist.GetXaxis().SetTitle('')
    if 'xmin' in options and 'xmax' in options:
        hist.GetXaxis().SetRangeUser(options['xmin'], options['xmax'])
    hist.GetYaxis().SetTitle(options['ytitle'])
    hist.GetYaxis().SetTitleOffset(1.2)
    for axis in [hist.GetXaxis(), hist.GetYaxis()]:
        axis.SetTitleFont(133)
        axis.SetTitleSize(16)
        axis.SetLabelFont(133)
        axis.SetLabelSize(12)
        axis.CenterTitle()
        if options['big']:
            axis.SetTickLength(0.01)
    if options['big']:
        hist.GetYaxis().SetTitleOffset(0.25)
    drawSignature(filename)
    gPad.Modified()
    gPad.Update()
    if options['retrn']:
        return [canvas, hist, f]
    else:
        canvas.Print(filepath)
        canvas.Close()
        closeRootFile(f, options['name'] + '_perTime')
コード例 #4
0
def doPerStep(options):
    """Extract data from ROOT files and sort by step"""
    c = chain(options['fileset'], options['scan'])
    name = options['scan'] + '_' + options['name']
    if 'method' in options:
        name += '_' + options['method']
    if len(O['crossings']):
        cond = O['bxname'][options['fileset']] + ' == ' + str(
            O['crossings'][0])
        if O['crossings'][1:]:
            cond = '(' + cond
            for bx in O['crossings']:
                cond += ' || ' + O['bxname'][
                    options['fileset']] + ' == ' + str(bx)
            cond += ')'
        cond = ' && ' + cond
    else:
        cond = ''
    f = openRootFileU(name)
    for step in range(len(O['nominalPos'][options['scan']])):
        print '<<< Analyze:', options['scan'], 'step', step
        histname = plotName(name + '_bxall_step' + str(step), timestamp=False)
        histtitl = plotTitle(options['scan'] + ' BX all, Step ' + str(step))
        hist = options['histo'](histname, histtitl, options['bin'], \
                                options['min'], options['max'])
        hist.StatOverflows(True)
        c.Draw(options['field'](options['scan'])+'>>'+histname, \
               options['condition'](options['scan'], step)+cond, 'goff')
        hist.Write('', TObject.kOverwrite)
    closeRootFile(f, name)
コード例 #5
0
def plotPerBxStep(options):
    """Save histograms (per BX and step) to PDF files"""
    name = options['scan'] + '_' + options['name'] + options['extra']
    if 'method' in options:
        name += '_' + options['method']
    f = openRootFileR(name)
    for bx in options['crossings']:
        for step in range(len(O['nominalPos'][options['scan']])):
            histname = plotName(name+'_bx'+str(bx)+'_step'+str(step), \
                                timestamp=False)
            filename = plotName(name+'_bx'+str(bx)+'_step'+str(step), \
                                timestamp=True)
            filepath = plotPath(name+'_bx'+str(bx)+'_step'+str(step), \
                                timestamp=True)
            print '<<< Save plot:', filepath
            hist = f.Get(histname)
            canvas = TCanvas()
            canvas.SetLogx(options['logx'])
            canvas.SetLogy(options['logy'])
            gStyle.SetOptStat(options['optstat'])
            gStyle.SetOptFit(options['optfit'])
            hist.Draw()
            gPad.Update()
            hist.GetXaxis().SetTitle(options['xtitle'])
            hist.GetXaxis().SetRangeUser(options['xmin'], options['xmax'])
            hist.GetYaxis().SetTitle(options['ytitle'])
            hist.GetYaxis().SetTitleOffset(1.2)
            for axis in [hist.GetXaxis(), hist.GetYaxis()]:
                axis.SetTitleFont(133)
                axis.SetTitleSize(16)
                axis.SetLabelFont(133)
                axis.SetLabelSize(12)
                axis.CenterTitle()
            stats = hist.FindObject('stats')
            stats.SetTextFont(133)
            stats.SetTextSize(16)
            drawSignature(filename)
            gPad.Modified()
            gPad.Update()
            if 'custom' in options:
                extragraphs = options['custom'](hist)
            canvas.Print(filepath)
            canvas.Close()
    closeRootFile(f, name)
コード例 #6
0
def combinePerStep(options):
    """Combine data from all bunch crossings into a single histogram"""
    name = options['scan'] + '_' + options['name']
    if 'method' in options:
        name += '_' + options['method']
    f = openRootFileU(name)
    for step in range(len(O['nominalPos'][options['scan']])):
        histname = plotName(name + '_bxall_step' + str(step), timestamp=False)
        histtitl = plotTitle(options['scan'] + ', Step ' + str(step) +
                             ' (all BX)')
        hist = options['histo'](histname, histtitl, options['bin'], \
                                    options['min'], options['max'])
        hist.StatOverflows(True)
        print '<<< Combine histograms:', histname
        for bx in O['crossings']:
            bxname = plotName(name+'_bx'+str(bx)+'_step'+str(step), \
                              timestamp=False)
            bxhist = f.Get(bxname)
            hist.Add(bxhist)
        hist.Write('', TObject.kOverwrite)
    closeRootFile(f, name)
コード例 #7
0
def pccPerLumiSection(options):
    """Extract PCC data from ROOT files and sort by lumisection"""
    c = chain(options['fileset'], options['scan'])
    rc = reducedChain(options['fileset'], options['scan'])
    name = options['name'] + '_perLS'
    f = openRootFileU(name)
    print '<<< Analyze', options['title']
    histname = plotName(options['title'] + '_perLS', timestamp=False)
    histtitl = plotTitle()
    print '<<< Get Minimum'
    mini = int(rc.GetMinimum('LS'))
    print '<<< Get Maximum'
    maxi = int(rc.GetMaximum('LS'))
    print '<<< Fill Profile Histogram', histname
    hist = TProfile(histname, histtitl, maxi - mini + 1, mini - 0.5,
                    maxi + 0.5)
    c.Draw(options['field'] + ':LS>>' + histname, '', 'goff')
    hist.Write('', TObject.kOverwrite)
    closeRootFile(f, name)
コード例 #8
0
def pccPerTimeStamp(options):
    """Extract PCC data from ROOT files and sort by timestamps"""
    c = chain(options['fileset'], options['scan'])
    rc = chain(options['fileset'], options['scan'])
    name = options['name'] + '_' + options['scan'] + '_perTime'
    f = openRootFileU(options['name'] + '_perTime')
    print '<<< Analyze', options['scan'], options['name']
    histname = plotName(name, timestamp=False)
    histtitl = plotTitle(options['scan'])
    print '<<< Get Minimum'
    mini = int(rc.GetMinimum(O['timename'][options['fileset']]))
    print '<<< Get Maximum'
    maxi = int(rc.GetMaximum(O['timename'][options['fileset']]))
    print '<<< Fill Profile Histogram', histname
    hist = TProfile(histname, histtitl, maxi - mini + 1, mini - 0.5,
                    maxi + 0.5)
    c.Draw(options['field']+':'+O['timename'][options['fileset']]+'>>'+ \
           histname, '', 'goff')
    hist.Write('', TObject.kOverwrite)
    closeRootFile(f, options['name'] + '_perTime')
コード例 #9
0
ファイル: extract.py プロジェクト: mahmoussa/LengthScale
def extractPerDirectionBx(options):
    """Extract results from directional fits (per BX)"""
    name = options['scan'] + '_'+ options['name'] + options['fitted'] \
           + '_collected'
    f = openRootFileR(name)
    crossings = O['crossings'][:]
    if options['combine']:
        crossings.append('all')
    average = dict(zip(crossings, [[0, 0] for i in range(len(crossings))]))
    averror = dict(zip(crossings, [[0, 0] for i in range(len(crossings))]))
    def extract(graph):
        func = graph.GetFunction(options['fit'])
        return func.GetParameter(options['parameter']), \
               func.GetParError(options['parameter'])
    for bx in crossings:
        plotname = plotName(name+'_bx'+str(bx), timestamp=False)
        print '<<< Access plot:', plotname
        graphs = f.Get(plotname)
        for j, graph in enumerate(graphs.GetListOfGraphs()):
            average[bx][j], averror[bx][j] = extract(graph)
    return average, averror
コード例 #10
0
def doPerBxStep(options):
    """Extract data from ROOT files and sort by bunch crossing and step"""
    c = chain(options['fileset'], options['scan'])
    name = options['scan'] + '_' + options['name']
    if 'method' in options:
        name += '_' + options['method']
    f = openRootFileU(name)
    for bx in O['crossings']:
        for step in range(len(O['nominalPos'][options['scan']])):
            print '<<< Analyze:', options['scan'], bx, 'step', step
            histname = plotName(name+'_bx'+str(bx)+'_step'+str(step), \
                                timestamp=False)
            histtitl = plotTitle(options['scan']+' BX '+str(bx)+', Step '+\
                                str(step))
            hist = options['histo'](histname, histtitl, options['bin'], \
                                    options['min'], options['max'])
            hist.StatOverflows(True)
            c.Draw(options['field'](options['scan'])+'>>'+histname, \
                   options['condition'](options['scan'], bx, step), 'goff')
            hist.Write('', TObject.kOverwrite)
    closeRootFile(f, name)
コード例 #11
0
def plotPerDirectionBx(options):
    """Save directional fit plots (per BX) to PDF files"""
    name = options['scan'] + '_' + options['name'] + options['fitted']
    if 'method' in options:
        name += '_' + options['method']
    name += '_collected'
    f = openRootFileR(name)
    for bx in options['crossings']:
        plotname = plotName(name + '_bx' + str(bx), timestamp=False)
        filename = plotName(name + '_bx' + str(bx), timestamp=True)
        filepath = plotPath(name + '_bx' + str(bx), timestamp=True)
        print '<<< Save plot:', filepath
        graphs = f.Get(plotname)
        residuals = f.Get(plotname + '_residuals')
        if 'final' in options:
            graphs.SetTitle('')
            residuals.SetTitle('')

        gStyle.SetOptFit(options['optfit'])
        canvas = TCanvas(plotname + '_canvas', '', 700, 600)

        canvas.cd()
        canvas.SetMargin(0.13, 0.03, 0.33, 0.05)

        graphs.Draw('AP')
        gPad.Update()
        text = TLatex()
        text.SetNDC()
        for j, graph in enumerate(graphs.GetListOfGraphs()):
            graph.SetMarkerStyle(21)
            graph.SetMarkerColor(2 + 2 * j)
            graph.GetFunction(options['fit']).SetLineColor(2 + 2 * j)
            stats = graph.GetListOfFunctions().FindObject('stats')
            stats.SetTextColor(2 + 2 * j)
            stats.SetBorderSize(0)
            stats.SetTextSize(0.04)
            inverted = graph.GetFunction(
                options['fit']).GetParameter('p1') < 0.0
            text.SetTextFont(42)
            text.SetTextSize(0.04)
            text.SetTextColor(2 + 2 * j)
            if inverted and j == 0:
                text.DrawLatex(0.18, 0.54, options['scan'] + ' scan forward')
                stats.SetX1NDC(0.16)
                stats.SetX2NDC(0.53)
                stats.SetY1NDC(0.38)
                stats.SetY2NDC(0.53)
            elif inverted and j == 1:
                text.DrawLatex(0.61, 0.9, options['scan'] + ' scan backward')
                stats.SetX1NDC(0.59)
                stats.SetX2NDC(0.96)
                stats.SetY1NDC(0.74)
                stats.SetY2NDC(0.89)
            elif j == 0:
                text.DrawLatex(0.18, 0.9, options['scan'] + ' scan forward')
                stats.SetX1NDC(0.16)
                stats.SetX2NDC(0.53)
                stats.SetY1NDC(0.74)
                stats.SetY2NDC(0.89)
            else:
                text.DrawLatex(0.61, 0.54, options['scan'] + ' scan backward')
                stats.SetX1NDC(0.59)
                stats.SetX2NDC(0.96)
                stats.SetY1NDC(0.38)
                stats.SetY2NDC(0.53)
        graphs.GetXaxis().SetTitle('Nominal Position [#mum]')
        graphs.GetYaxis().SetTitle(options['ytitle'])
        graphs.GetYaxis().SetTitleOffset(1.3)
        if ('final' in options):
            text.SetTextColor(1)
            text.SetTextFont(42)
            text.SetTextSize(0.04)
            text.SetTextAlign(31)
            text.DrawLatex(0.97, 0.96, O['plotsig'])
            text.SetTextAlign(11)
            if options['final'] == 'wip':
                text.SetTextFont(52)
                text.SetTextSize(0.04)
                text.DrawLatex(0.13, 0.96, 'Work in Progress')
            else:
                text.SetTextFont(62)
                text.SetTextSize(0.05)
                text.DrawLatex(0.13, 0.96, 'CMS')
                text.SetTextFont(52)
                text.SetTextSize(0.04)
                text.DrawLatex(0.22, 0.96, 'Preliminary')
        for axis in [graphs.GetYaxis(), graphs.GetXaxis()]:
            axis.SetTitleSize(0.05)
            axis.SetLabelSize(0.04)
            axis.SetLabelOffset(0.01)
            axis.CenterTitle()

        pad = TPad('pad', 'pad', 0, 0, 1, 0.2)
        pad.Draw()
        pad.cd()
        pad.SetMargin(0.13, 0.03, 0.01, 0.01)
        for j, residual in enumerate(residuals.GetListOfGraphs()):
            residual.SetMarkerStyle(21)
            residual.SetMarkerColor(2 + 2 * j)
        residuals.Draw("AP")
        residuals.GetXaxis().SetTitle('')
        residuals.GetXaxis().SetLabelSize(0.0)
        residuals.GetXaxis().SetTickSize(0.151)
        residuals.GetYaxis().SetNdivisions(305)
        residuals.GetYaxis().SetTickSize(0.019)
        residuals.GetYaxis().SetLabelSize(0.2)
        residuals.GetYaxis().SetLabelOffset(0.01)
        pad.Update()
        line = TLine(pad.GetUxmin(), 0.0, pad.GetUxmax(), 0.0)
        line.SetLineColor(14)
        line.SetLineStyle(3)
        line.Draw()

        canvas.cd()
        text.SetTextFont(42)
        text.SetTextSize(0.05)
        text.SetTextAngle(90.0)
        text.DrawLatex(0.035, 0.0, 'Resid. ' + options['restitle'])

        if not 'final' in options:
            drawSignature(filename)
        # canvas.Modified()
        # canvas.Update()
        canvas.Print(filepath)
        canvas.Close()
    closeRootFile(f, name)
コード例 #12
0
def collectPerDirectionBx(options):
    """Fit data in both directions of a scan"""
    nSteps = len(O['nominalPos'][options['scan']])
    for i in range(nSteps - 1):
        if O['nominalPos'][options['scan']][i+1] == \
           O['nominalPos'][options['scan']][i]:
            break
    else:
        for i in range(nSteps - 1):
            if abs(O['nominalPos'][options['scan']][i+1] - \
                   O['nominalPos'][options['scan']][i]) < 10.0:
                break
        else:
            raise RuntimeError('Could not find change of direction.')
    if 'nominalPos' in options:
        nominalPos = options['nominalPos']
    else:
        nominalPos = O['nominalPos'][options['scan']]
    oldname = options['scan'] + '_' + options['name'] + options['fitted']
    if options.get('newname', False):
        newname = options['scan'] + '_' + options['newname'] + \
                  options['fitted']
    else:
        newname = oldname
    if options.get('method', False):
        oldname += '_' + options['method']
        newname += '_' + options['method']
    newname += '_collected'
    f = openRootFileR(oldname)
    g = openRootFileW(newname)
    for bx in options['crossings']:
        average = [0 for j in range(nSteps)]
        averror = [0 for j in range(nSteps)]
        for step in range(nSteps):
            print '<<< Access data from:', options['scan'], bx, 'step', step
            histname = plotName(oldname+'_bx'+str(bx)+'_step'+str(step), \
                                timestamp=False)
            hist = f.Get(histname)
            if options['custom']:
                average[step], averror[step] = options['custom'](hist, step)
            else:
                average[step] = hist.GetMean()
                averror[step] = hist.GetMeanError()
        plotname = plotName(newname + '_bx' + str(bx), timestamp=False)
        plottitl = plotTitle(options['scan'] + ' BX ' + str(bx))
        print '<<< Create plot:', plotname
        graphs = TMultiGraph(plotname, plottitl)
        residuals = TMultiGraph(plotname + '_residuals', '')
        for n, rnge in zip([i+1, nSteps-i-1], [lambda l: l[:i+1], \
                                               lambda l: l[i+1:]]):
            graph = TGraphErrors(n, \
                    array('d', [options['x'](a) for a in rnge(nominalPos)]), \
                    array('d', [options['y'](a) for a in rnge(average)]), \
                    array('d', [0]*n), \
                    array('d', [options['e'](a) for a in rnge(averror)]))
            graph.Fit(options['fit'])
            residual = TGraphErrors(n, \
                       array('d', [options['x'](a) for a in rnge(nominalPos)]), \
                       array('d', [options['y'](a) - graph.GetFunction( \
                             options['fit']).Eval(options['x'](b)) for a, b \
                             in zip(rnge(average), rnge(nominalPos))]),
                       array('d', [0]*n), \
                       array('d', [options['e'](a) for a in rnge(averror)]))
            graphs.Add(graph)
            residuals.Add(residual)
        graphs.Write('', TObject.kOverwrite)
        residuals.Write('', TObject.kOverwrite)
    closeRootFile(g, newname)
    closeRootFile(f, oldname)