Exemple #1
0
    def __init__(self, label, signal, profileVars, R0_,
                 d_lumi, d_xs_dy, d_xs_st, tag, genPre, sigPre, dirIncrement, genDirPre, d_wbb,
                 quiet = False, hackZeroBins=False, templateID=None, defaults = {},
                 log=None, fixSM=False,altData=None, lumiFactor=1.0):

        np.random.seed(1981)
        for item in ['label','quiet','fixSM','profileVars'] : setattr(self,item,eval(item))
        self.log = log if log else sys.stdout
        if type(R0_) == tuple:
            diffR0_ = R0_[1]
            R0_ = R0_[0]
        else: diffR0_ = None
        prePre = dirIncrement in [0,4,5]
        channels = dict([((lep,part),
                          inputs.channel_data(lep, part, tag, signal, sigPre,
                                              "R%02d" % (R0_ + dirIncrement),
                                              genDirPre, prePre=prePre, templateID=templateID,
                                              hackZeroBins=hackZeroBins and 'QCD'==part))
                         for lep in ['el', 'mu']
                         for part in ['top', 'QCD']
                         ])
        channels['gen'] = inputs.channel_data('mu', 'top', tag,
                                              '%s; %s'%(genNameX,genNameY),
                                              sigPrefix = sigPre if dirIncrement in [0,4,5] else '',
                                              dirPrefix=genDirPre, genDirPre=genDirPre, 
                                              getTT=True, prePre = prePre)

        if diffR0_ :
            for lepPart,chan in channels.items():
                if type(lepPart) != tuple: continue
                lep,part = lepPart
                chan.subtract(inputs.channel_data(lep,part,tag,signal,sigPre,
                                                  "R%02d" % (diffR0_ + dirIncrement),
                                                  genDirPre, prePre = prePre ))

        if d_wbb: [[h.SetBinContent(iX,3, (1+d_wbb)*h.GetBinContent(iX,3))
                    for h in chan.samples['wj'].datas
                    for iX in range(1,1+h.GetNbinsX())]
                   for name,chan in channels.items() if name!='gen']

        print "###", label
        print>>self.log, "###", label
        self.model = model.topModel(channels, asymmetry=True)
        self.model.w.arg('lumi_factor').setVal(lumiFactor)
        for k,v in defaults.items(): self.model.w.arg(k).setVal(v)
        for item in ['d_lumi', 'd_xs_dy', 'd_xs_st']: self.model.w.arg(item).setVal(eval(item))

        self.fitArgs = [r.RooFit.Extended(True), r.RooFit.NumCPU(1),
                        r.RooFit.PrintLevel(-1)]
        self.model.import_data(altData)

        if fixSM: self.doSM()
        else: self.doFit()
Exemple #2
0
    def calibrations(self, pars, which='mn', calSlice=(None,None), N=1000, label='', **kwargs):

        sampleList = [c['sample'] for c in calibration_specs() if c['which']==which]
        prePre = pars['dirIncrement'] in [0,4,5]

        args = {
            'signal':pars['signal'],
            'sigPrefix':pars['sigPre'],
            'dirPrefix':"R%02d" % (pars['R0_'] + pars['dirIncrement']),
            'genDirPre':pars['genDirPre'],
            'prePre':prePre,
            'templateID':None,
            'hackZeroBins':pars['hackZeroBins'] and 'QCD'==part,
            'sampleList': sampleList
            }
        alt_channels = dict( [ ((lep,part), inputs.channel_data(lep, part, **args))
                               for lep in ['el','mu'] for part in ['top','QCD']] )

        # get Ac_phi_ttalt and Ac_y_ttalt
        filePattern = 'data/stats_top_mu_%s.root'
        tag = 'ph_sn_jn_20'
        tfile = r.TFile.Open(filePattern%tag)
        h = lib.get(tfile,'genTopTanhDeltaAbsY_genTopDPtDPhi/'+ sampleList[0])
        Ac_y_ttalt = lib.asymmetry(h.ProjectionX())[0]
        Ac_phi_ttalt = lib.asymmetry(h.ProjectionY())[0]
        tfile.Close()

        model = self.central.model
        model.import_alt_model(alt_channels)
        wGen = model.w

        # bring xs_ttalt to the most consistant value possible
        wGen.arg('d_xs_ttalt').setVal((wGen.arg('expect_mu_tt').getVal() + wGen.arg('expect_el_tt').getVal()) /
                                      (wGen.arg('expect_mu_ttalt').getVal() + wGen.arg('expect_el_ttalt').getVal()) - 1)
        # not clear how to do the same for factor_*_qcd (equivalent bg representations)

        truth = dict([(s,eval(s)) for s in ['Ac_y_ttalt','Ac_phi_ttalt']])
        altItems = ['expect_%s_ttalt'%s for s in ['el','mu']]
        for item in (set(fit.modelItems()+altItems)-set(fit.altmodelNonItems())): truth[item] = wGen.arg(item).getVal()

        mcstudy = r.RooMCStudy(wGen.pdf('altmodel'),
                               wGen.argSet(','.join(model.observables+['channel'])),
                               r.RooFit.Binned(True),
                               r.RooFit.Extended(True)
                           )
        mcstudy.generate(N,0,True)
        for i in range(N)[slice(*calSlice)]:
            alt = mcstudy.genData(i)
            pars['label'] = '%s_cal%s%03d'%(label,which,i)
            with open(self.outNameBase + pars['label'] + '.log', 'w') as log:
                pars['log']=log
                f = fit(altData=alt, **pars)
            f.ttreeWrite(self.outNameBase + pars['label'] + '.root', truth)
Exemple #3
0
import os,inputs,ROOT as r

os.system('mkdir -p cerba')
txtname = 'cerba/cerba_efficiencies.txt'
with open(txtname,'w') as txt:
    print>>txt, '# sample    efficiency-5j/4j      efficiency3dcut'
    for lep in ['el','mu'] :
        chan = inputs.channel_data(lep, 'top', signal='jetMoments2Sum_triD')
        chan4 = inputs.channel_data(lep, 'top', signal='fitTopTanhRapiditySum_triD')

        print>>txt
        print>>txt, '# ', lep
        filename = "cerba/cerba_%s.root"%lep
        f = r.TFile.Open(filename,'RECREATE')
        for item in chan.samples:
            eff5jet = chan.samples[item].datas[0].Integral()/chan4.samples[item].datas[0].Integral()
            h = chan.samples[item].datas[0].ProjectionX(item,3,3)
            eff3d = h.Integral() / chan.samples[item].datas[0].Integral()
            if item!='data': h.Scale(1./h.Integral())
            h.Write()
            print>>txt, '\t'.join([str(i) for i in [item, eff5jet,eff3d]])
        f.Close()
        print "Wrote", filename
print "Wrote", txtname
Exemple #4
0
import math
r.gROOT.SetBatch(1)
r.gROOT.ProcessLine(".L tdrstyle.C")
r.setTDRStyle()
r.tdrStyle.SetErrorX(r.TStyle().GetErrorX())
r.tdrStyle.SetPadTopMargin(0.065)
r.TGaxis.SetMaxDigits(3)
r.tdrStyle.SetEndErrorSize(6)
#r.tdrStyle.SetPadRightMargin(0.06)

def unqueue(h):
    return utils.unQueuedBins(h,5,[-1,1],[-1,1])

threeD = True
check = False
channels = dict([(lep, channel_data(lep, 'top', signal='fitTopQueuedBin5_TridiscriminantWTopQCD', threeD=True)) for lep in ['el', 'mu']])
linetypes = [1, 2]

comps = ['ttgg','ttag','ttqg','ttqq']
colors = [r.kBlack, r.kGreen, r.kBlue, r.kRed]

if check:
    channels_def = dict([(lep, channel_data(lep, 'top', signal='fitTopQueuedBin5_TridiscriminantWTopQCD', threeD=False)) for lep in ['el', 'mu']])
    for lep,ch in channels.items():
        for comp in comps:
            c = ch.samples[comp].datas
            d = channels_def[lep].samples[comp].datas
            for a,b in zip(c,d):
                b.Add(a,-1)
                print ' '.join(str(b.GetBinContent(i)) for i in range(2+b.GetNbinsX()))
Exemple #5
0
r.gROOT.ProcessLine(".L tdrstyle.C")
r.setTDRStyle()
r.tdrStyle.SetErrorX(r.TStyle().GetErrorX())
r.tdrStyle.SetPadTopMargin(0.065)
r.TGaxis.SetMaxDigits(3)
#r.tdrStyle.SetPadRightMargin(0.06)
from inputs import channel_data

d_xs_wj = 0.758705 #0.75986
d_xs_tt = 0.165759 #0.166398
factor_qcd = {'el':3.1996, #3.20075,
              'mu':1.25478 #1.25533
}

channels = dict([(('_'.join([lep,par])), 
                  channel_data(lep, par, signal='fitTopQueuedBin5_TridiscriminantWTopQCD')) 
                 for lep in ['el', 'mu'] for par in ['top','QCD']])

for n,c in channels.items():
    lep,par = n.split('_')
    c.samples.update(channel_data(lep, par, signal='fitTopQueuedBin5_TridiscriminantWTopQCD', getTT=True).samples)
    for item in ['gg','qq','qg','ag'] : del c.samples['tt'+item]
    c.samples['tt'].eff /= 4
    c.samples['tt'].xs *= (1+d_xs_tt)
    c.samples['wj'].xs *= (1+d_xs_wj)
    print c


tfile = {'mu_QCD':r.TFile.Open('data/control_QCD_mu_ph_sn_jn_20.root'),
         'mu_top':r.TFile.Open('data/control_top_mu_ph_sn_jn_20.root'),
         'el_QCD':r.TFile.Open('data/control_QCD_el_ph_sn_jn_20.root'),
Exemple #6
0
def unqueue(h):
    return lib.unQueuedBins(h,5,[-1,1],[-1,1])

threeD = False

comps = ['ttag','ttqg','ttqq']
colors = [r.kBlack, r.kGreen, r.kBlue, r.kRed]

projections = {}
book = autoBook("stuff")

for extra in [True,False,'only']:
    for template in [None]+range(1000):
        print template
        #sys.stdout.flush()
        channels = dict([(lep, channel_data(lep, 'top', signal='fitTopQueuedBin5_TridiscriminantWTopQCD', threeD=threeD, extra=extra, templateID=template,getTT=True)) for lep in ['el', 'mu']])
        for lep,ch in channels.items():
            for comp,color in zip(comps,colors):
                name = '_'.join(['extra' if extra=='only' else 'total' if extra else 'orig' ,lep, comp])
                if template==None: name += '_actual'
                tot = unqueue(ch.samples[comp].datas[0].ProjectionX())
                v = (100*lib.asymmetry(tot.ProjectionX())[0],
                     100*lib.asymmetry(tot.ProjectionY())[0])
                book.fill( v, name, (100,100), (-3,-3), (3,3))

tfile = r.TFile.Open("jiggled_asymmetries.root","RECREATE")
for key,hist in book.items():
    hist.Write()
tfile.Close()
Exemple #7
0
r.gROOT.SetBatch(1)
r.gROOT.ProcessLine(".L lib/tdrstyle.C")
r.setTDRStyle()
r.tdrStyle.SetErrorX(r.TStyle().GetErrorX())
r.tdrStyle.SetPadTopMargin(0.065)
r.TGaxis.SetMaxDigits(3)
r.tdrStyle.SetEndErrorSize(6)
#r.tdrStyle.SetPadRightMargin(0.06)

def unqueue(h):
    return lib.unQueuedBins(h,5,[-1,1],[-1,1])

threeD = True
check = False
extra = True
channels = dict([(lep, channel_data(lep, 'top', signal='fitTopQueuedBin5_TridiscriminantWTopQCD', threeD=threeD, extra=extra)) for lep in ['el', 'mu']])
linetypes = [1, 2]

comps = ['ttgg','ttag','ttqg','ttqq']
colors = [r.kBlack, r.kGreen, r.kBlue, r.kRed]

if check:
    channels_def = dict([(lep, channel_data(lep, 'top', signal='fitTopQueuedBin5_TridiscriminantWTopQCD', threeD=threeD, extra=extra)) for lep in ['el', 'mu']])
    for lep,ch in channels.items():
        for comp in comps:
            c = ch.samples[comp].datas
            d = channels_def[lep].samples[comp].datas
            for a,b in zip(c,d):
                b.Add(a,-1)
                print ' '.join(str(b.GetBinContent(i)) for i in range(2+b.GetNbinsX()))
Exemple #8
0
import os, inputs, ROOT as r

os.system('mkdir -p cerba')
txtname = 'cerba/cerba_efficiencies.txt'
with open(txtname, 'w') as txt:
    print >> txt, '# sample    efficiency-5j/4j      efficiency3dcut'
    for lep in ['el', 'mu']:
        chan = inputs.channel_data(lep, 'top', signal='jetMoments2Sum_triD')
        chan4 = inputs.channel_data(lep,
                                    'top',
                                    signal='fitTopTanhRapiditySum_triD')

        print >> txt
        print >> txt, '# ', lep
        filename = "cerba/cerba_%s.root" % lep
        f = r.TFile.Open(filename, 'RECREATE')
        for item in chan.samples:
            eff5jet = chan.samples[item].datas[0].Integral(
            ) / chan4.samples[item].datas[0].Integral()
            h = chan.samples[item].datas[0].ProjectionX(item, 3, 3)
            eff3d = h.Integral() / chan.samples[item].datas[0].Integral()
            if item != 'data': h.Scale(1. / h.Integral())
            h.Write()
            print >> txt, '\t'.join([str(i) for i in [item, eff5jet, eff3d]])
        f.Close()
        print "Wrote", filename
print "Wrote", txtname
Exemple #9
0
import ROOT as r
r.gROOT.SetBatch(1)
r.gStyle.SetOptStat(0)

dists = ['fitTopPtOverSumPt_triD','fitTopTanhRapiditySum_triD','fitTopQueuedBin7TridiscriminantWTopQCD']
processes = ['ttgg','ttqg','ttqq','ttag']
colors = [r.kBlack,r.kRed,r.kBlue,r.kViolet]
fileName = 'graphics/fractions.pdf'

can = r.TCanvas()
can.Divide(2,2)
can.Print(fileName+'[')

for dist in dists :
    xname = dist.split('_')[0].replace('fitTopQueuedBin7TridiscriminantWTopQCD','unrolling of X_T by X_L [reco]').replace('fitTopTanhRapiditySum','tanh|t#bar{t}.y| [reco]').replace('fitTopTanhAvgRapidity','tanh(|t.y+#bar{t}.y|/2) [reco]').replace('fitTopPtOverSumPt','t#bar{t}.pt / (t.pt + #bar{t}.pt) [reco]')
    channels = dict((lepton,inputs.channel_data(lepton,'top',signal=dist,getTT=True)) for lepton in ['el','mu'])
    for i,(lep,c) in enumerate(channels.items()) : 
        titlename = {'el':'Electrons+Jets','mu':'Muons+Jets'}[lep]
        can.cd(i+1)
        denom = c.samples['tt'].datasX[0]
        denom.SetMinimum(0)
        denom.SetTitle('%s;%s;%s'%(titlename,xname,'selected t#bar{t} events / bin / 19.5 / fb'))
        denom.GetYaxis().SetTitleOffset(1.3)
        denom.Draw('hist')
        can.cd(i+3)
        hists = [c.samples[p].datasX[0] for p in processes]
        for h in hists :
            h.Divide(denom)
            h.SetMinimum(0)
            h.SetMaximum(1.0)
            h.SetTitle(';%s;%s'%(xname,'production fraction'))
Exemple #10
0
    def old_calibrations(self, pars, which='mn', calSlice=(None,None), N=1000, label='', **kwargs):

        sampleList = [c['sample'] for c in calibration_specs() if c['which']==which]
        prePre = pars['dirIncrement'] in [0,4,5]

        args = {
            'signal':pars['signal'],
            'sigPrefix':pars['sigPre'],
            'dirPrefix':"R%02d" % (pars['R0_'] + pars['dirIncrement']),
            'genDirPre':pars['genDirPre'],
            'prePre':prePre,
            'templateID':None,
            'sampleList': sampleList,
            'rebin':pars['rebin'],
            'no3D':pars['no3D']
            }
        alt_channels = dict( [ ((lep,part), inputs.channel_data(lep, part, **args))
                               for lep in ['el','mu'] for part in ['top','QCD']] )

        if 'xsfactor' in kwargs:
            alt_channels[('el','top')].samples['ttalt'].xs *= kwargs['xsfactor']
            alt_channels[('mu','top')].samples['ttalt'].xs *= kwargs['xsfactor']

        # get Ac_phi_ttalt and Ac_y_ttalt
        filePattern = 'data/stats_top_mu_%s.root'
        tag = 'ph_sn_jn_20'
        tfile = r.TFile.Open(filePattern%tag)
        h = lib.get(tfile,'genTopTanhDeltaAbsY_genTopDPtDPhi/'+ sampleList[0])
        Ac_y_ttalt = lib.asymmetry(h.ProjectionX())[0]
        Ac_phi_ttalt = lib.asymmetry(h.ProjectionY())[0]
        tfile.Close()

        model = self.central.model
        model.import_alt_model(alt_channels, pars['nobg'])
        wGen = model.w

        # bring xs_ttalt to the most consistant value possible
        wGen.arg('d_xs_ttalt').setVal((wGen.arg('expect_mu_tt').getVal() + wGen.arg('expect_el_tt').getVal()) /
                                      (wGen.arg('expect_mu_ttalt').getVal() + wGen.arg('expect_el_ttalt').getVal()) - 1)
        if not (-0.5 < wGen.arg('d_xs_ttalt').getVal() < 1.5):
            print 'ttalt xs invalid! Adjust calibration_specs!'
            exit()
        # not clear how to do the same for factor_*_qcd (equivalent bg representations)

        truth = {'Ac': Ac_y_ttalt if genNames['XL'][3:] in pars['signal'] else Ac_phi_ttalt}
        altItems = ['expect_%s_ttalt'%s for s in ['el','mu']]
        for item in (set(fit.modelItems()+altItems)-set()): truth[item] = wGen.arg(item).getVal()
        truth.update({'Ac_raw_el_model':model.Ac_raw('el','alt%smodel'%pars['nobg']),
                      'Ac_raw_mu_model':model.Ac_raw('mu','alt%smodel'%pars['nobg'])})

        mcstudy = r.RooMCStudy(wGen.pdf('alt%smodel'%pars['nobg']),
                               wGen.argSet(','.join(model.observables+['channel'])),
                               r.RooFit.Binned(True),
                               r.RooFit.Extended(True)
                           )
        mcstudy.generate(N,0,True)
        for i in range(*calSlice):
            alt = mcstudy.genData(i)
            pars['label'] = '%s_cal%s%03d'%(label,which,i)
            pars['quiet'] = True
            with open(self.outNameBase + pars['label'] + '.log', 'w') as log:
                pars['log']=log
                f = fit(altData=alt, **pars)
            f.ttreeWrite(self.outNameBase + pars['label'] + '.root', truth)
            if self.doVis: f.model.visualize(self.outNameBase + pars['label'] + '.pdf', nobg=pars['nobg'])
Exemple #11
0
r.tdrStyle.SetPadTopMargin(0.055)
r.TGaxis.SetMaxDigits(3)
r.tdrStyle.SetEndErrorSize(4)
#r.tdrStyle.SetPadRightMargin(0.06)

rebin = True
import systematics

pars = systematics.measurement_pars()
pars.update(systematics.central())
print pars

channels = dict([(lep, channel_data(lep, 'top', tag=pars['tag'],
                                    signal=pars['signal'],
                                    sigPrefix=pars['sigPre'],
                                    dirPrefix="R%02d" % (pars['R0_'] + pars['dirIncrement']),
                                    genDirPre=pars['genDirPre'],
                                    rebin = rebin
                                )) for lep in ['el','mu']])
linetypes = [1, 2]


print channels['el']
print channels['mu']


comps = ['tt']

projections = {}

for lt,(lep,ch) in zip(linetypes,channels.items()):
Exemple #12
0
can = r.TCanvas()
can.Divide(2, 2)
can.Print(fileName + '[')

for dist in dists:
    xname = dist.split('_')[0].replace(
        'fitTopQueuedBin7TridiscriminantWTopQCD',
        'unrolling of X_T by X_L [reco]').replace(
            'fitTopTanhRapiditySum', 'tanh|t#bar{t}.y| [reco]').replace(
                'fitTopTanhAvgRapidity',
                'tanh(|t.y+#bar{t}.y|/2) [reco]').replace(
                    'fitTopPtOverSumPt',
                    't#bar{t}.pt / (t.pt + #bar{t}.pt) [reco]')
    channels = dict(
        (lepton, inputs.channel_data(lepton, 'top', signal=dist, getTT=True))
        for lepton in ['el', 'mu'])
    for i, (lep, c) in enumerate(channels.items()):
        titlename = {'el': 'Electrons+Jets', 'mu': 'Muons+Jets'}[lep]
        can.cd(i + 1)
        denom = c.samples['tt'].datasX[0]
        denom.SetMinimum(0)
        denom.SetTitle(
            '%s;%s;%s' %
            (titlename, xname, 'selected t#bar{t} events / bin / 19.5 / fb'))
        denom.GetYaxis().SetTitleOffset(1.3)
        denom.Draw('hist')
        can.cd(i + 3)
        hists = [c.samples[p].datasX[0] for p in processes]
        for h in hists:
            h.Divide(denom)
Exemple #13
0
    def __init__(self,
                 label,
                 signal,
                 profileVars,
                 R0_,
                 d_lumi,
                 d_xs_dy,
                 d_xs_st,
                 tag,
                 genPre,
                 sigPre,
                 dirIncrement,
                 genDirPre,
                 d_wbb,
                 quiet=False,
                 hackZeroBins=False,
                 templateID=None,
                 defaults={},
                 log=None,
                 fixSM=False,
                 altData=None,
                 lumiFactor=1.0):

        np.random.seed(1981)
        for item in ['label', 'quiet', 'fixSM', 'profileVars']:
            setattr(self, item, eval(item))
        self.log = log if log else sys.stdout
        if type(R0_) == tuple:
            diffR0_ = R0_[1]
            R0_ = R0_[0]
        else:
            diffR0_ = None
        prePre = dirIncrement in [0, 4, 5]
        extra = True
        channels = dict([((lep, part),
                          inputs.channel_data(lep,
                                              part,
                                              tag,
                                              signal,
                                              sigPre,
                                              "R%02d" % (R0_ + dirIncrement),
                                              genDirPre,
                                              prePre=prePre,
                                              templateID=templateID,
                                              extra=extra,
                                              d_wbb=d_wbb,
                                              hackZeroBins=hackZeroBins
                                              and 'QCD' == part))
                         for lep in ['el', 'mu'] for part in ['top', 'QCD']])
        channels['gen'] = inputs.channel_data(
            'mu',
            'top',
            tag,
            '%s; %s' % (genNameX, genNameY),
            sigPrefix=sigPre if dirIncrement in [0, 4, 5] else '',
            extra=extra,
            dirPrefix=genDirPre,
            genDirPre=genDirPre,
            getTT=True,
            prePre=prePre)

        if diffR0_:
            for lepPart, chan in channels.items():
                if type(lepPart) != tuple: continue
                lep, part = lepPart
                chan.subtract(
                    inputs.channel_data(lep,
                                        part,
                                        tag,
                                        signal,
                                        sigPre,
                                        "R%02d" % (diffR0_ + dirIncrement),
                                        genDirPre,
                                        prePre=prePre))

        print "###", label
        print >> self.log, "###", label
        self.model = model.topModel(channels, asymmetry=True)
        self.model.w.arg('lumi_factor').setVal(lumiFactor)
        for k, v in defaults.items():
            self.model.w.arg(k).setVal(v)
        for item in ['d_lumi', 'd_xs_dy', 'd_xs_st']:
            self.model.w.arg(item).setVal(eval(item))

        self.fitArgs = [
            r.RooFit.Extended(True),
            r.RooFit.NumCPU(1),
            r.RooFit.PrintLevel(-1)
        ]
        self.model.import_data(altData)

        if fixSM: self.doSM()
        else: self.doFit()
Exemple #14
0
comps = ['ttag', 'ttqg', 'ttqq']
colors = [r.kBlack, r.kGreen, r.kBlue, r.kRed]

projections = {}
book = autoBook("stuff")

for extra in [True, False, 'only']:
    for template in [None] + range(1000):
        print template
        #sys.stdout.flush()
        channels = dict([
            (lep,
             channel_data(lep,
                          'top',
                          signal='fitTopQueuedBin5_TridiscriminantWTopQCD',
                          threeD=threeD,
                          extra=extra,
                          templateID=template,
                          getTT=True)) for lep in ['el', 'mu']
        ])
        for lep, ch in channels.items():
            for comp, color in zip(comps, colors):
                name = '_'.join([
                    'extra' if extra == 'only' else
                    'total' if extra else 'orig', lep, comp
                ])
                if template == None: name += '_actual'
                tot = unqueue(ch.samples[comp].datas[0].ProjectionX())
                v = (100 * lib.asymmetry(tot.ProjectionX())[0],
                     100 * lib.asymmetry(tot.ProjectionY())[0])
                book.fill(v, name, (100, 100), (-3, -3), (3, 3))
Exemple #15
0
    def __init__(self, label, signal, R0_,
                 d_lumi, d_xs_dy, d_xs_st, tag, genPre, sigPre, dirIncrement, genDirPre, d_wbb,
                 quiet = False, templateID=None, defaults = {},
                 log=None, fixSM=False, altData=None, lumiFactor=1.0,
                 only="", nobg="", rebin=False, no3D=False, twoStage=False, fixedValues={}, alttt=None, sepchan=False, twossigma={}, Rst=None,
                 partsuffix='', symmQCD=False):

        np.random.seed(1981)
        if alttt and label[:7]=='central': label = alttt + label
        for item in ['label','quiet','fixSM','only','nobg'] : setattr(self,item,eval(item))
        self.log = log if log else sys.stdout

        parNames = ['label','signal','R0_','d_lumi','d_xs_dy','d_xs_st','tag','genPre','sigPre',
                    'dirIncrement','genDirPre','d_wbb','quiet','templateID','defaults','log','fixSM',
                    'altData','lumiFactor','only','nobg','rebin','no3D','twoStage', 'alttt','sepchan','twossigma','Rst', 'partsuffix','symmQCD']

        self.pars = dict([(p,eval(p)) for p in parNames])
        print>>log, sorted(self.pars.items())
        print>>log, ''

        if sepchan:
            assert not only
            print>>log, 'fitting el'
            pars_el = dict(self.pars); pars_el.update({'sepchan':False, 'only':'_el'})
            self.fit_el = fit(**pars_el)
            print>>log, ''

            print>>log, 'fitting mu'
            pars_mu = dict(self.pars); pars_mu.update({'sepchan':False, 'only':'_mu'})
            self.fit_mu = fit(**pars_mu)
            print>>log, ''

        if type(R0_) == tuple:
            diffR0_ = R0_[1]
            R0_ = R0_[0]
        else: diffR0_ = None
        prePre = dirIncrement in [0,4,5]
        channels = dict([((lep,part),
                          inputs.channel_data(lep, part+partsuffix, tag, signal, sigPre,
                                              "R%02d" % (R0_ + dirIncrement),
                                              genDirPre, prePre=prePre, templateID=templateID,
                                              d_wbb = d_wbb, rebin=rebin, no3D=no3D, only3D=(twoStage and fixSM), Rst=Rst))
                         for lep in ['el', 'mu']
                         for part in ['top', 'QCD']
                         ])
        if symmQCD:
            for lep in ['el','mu']:
                for samp in channels[(lep,'QCD')].samples.values():
                    samp.datas = (samp.datas[1],samp.datas[1],samp.datas[2])
                    samp.datasX = (samp.datasX[1],samp.datasX[1],samp.datasX[2])
                    samp.datasY = (samp.datasY[1],samp.datasY[1],samp.datasY[2])

        channels['gen'] = inputs.channel_data('mu', 'top'+partsuffix, tag,
                                              '%s; %s'%(genNameX,genNameY),
                                              sigPrefix = sigPre if dirIncrement in [0,4,5] else '',
                                              dirPrefix=genDirPre, genDirPre=genDirPre,
                                              prePre = prePre, sampleList=['tt'], rename=False)

        if alttt:
            print 'Using %s templates rather than POWHEG' % alttt
            for lep in ['el', 'mu']:
                for part in ['top','QCD']:
                    chan = inputs.channel_data(lep, part+partsuffix, tag, signal, sigPre, "R%02d" %(R0_ + dirIncrement),
                                               genDirPre, prePre=prePre, rebin=rebin, no3D=no3D,
                                               only3D=(twoStage and fixSM), sampleList=["calib_%s.pu.sf"%alttt if 'q' not in alttt else 'ttj_%s.pu.sf'%alttt])
            chan = inputs.channel_data('mu','top'+partsuffix, tag,
                                       '%s_%s'%(genNameX,genNameY),
                                       sigPrefix = '',
                                       dirPrefix=genDirPre, genDirPre=genDirPre,
                                       prePre = prePre, sampleList=["calib_%s.pu.sf"%alttt if 'q' not in alttt else 'ttj_%s.pu.sf'%alttt], fullDir = '')
            channels['gen'].samples['tt'] = chan.samples['ttalt']

        if diffR0_ :
            assert not alttt
            for lepPart,chan in channels.items():
                if type(lepPart) != tuple: continue
                lep,part = lepPart
                chan.subtract(inputs.channel_data(lep,part+partsuffix,tag,signal,sigPre,
                                                  "R%02d" % (diffR0_ + dirIncrement),
                                                  genDirPre, prePre = prePre, rebin=rebin ))

        print "###", label
        print>>self.log, "###", label
        self.model = model.topModel(channels)
        self.model.w.arg('lumi_factor').setVal(lumiFactor)
        for k,v in defaults.items(): self.model.w.arg(k).setVal(v)
        for item in ['d_lumi', 'd_xs_dy', 'd_xs_st']: self.model.w.arg(item).setVal(eval(item))

        self.fitArgs = [r.RooFit.Extended(True), r.RooFit.NumCPU(1),
                        r.RooFit.PrintLevel(-1)]
        self.model.import_data(altData)

        for k,v in fixedValues.items():
            self.model.w.arg(k).setVal(v)
            self.model.w.arg(k).setConstant()

        if fixSM: self.doSM()
        elif twoStage: self.doTwoStage()
        else: self.doFit()
        self.model.print_n(self.log)
        self.model.print_n(self.log,qcd=True)