def import_data(self, altData=None): w = self.w if altData: altData.SetName('data') roo.wimport(w, altData) return obs_ = w.argSet(','.join(self.observables)) obs = r.RooArgList(obs_) dataHists = dict([(L, unqueue(chan.samples['data'].datas[0], self.asymmetry)) for L, chan in self.channels.items()]) datas = [(L, r.RooDataHist('data_' + L, 'N_{obs}^{%s}' % L, obs, data)) for L, data in dataHists.items()] if not self.quiet: print self.observables[0] print '\n'.join('%s: %.6f (%.6f)' % ((L, ) + lib.asymmetry(hist.ProjectionX())) for L, hist in dataHists.items()) print self.observables[1] print '\n'.join('%s: %.6f (%.6f)' % ((L, ) + lib.asymmetry(hist.ProjectionY())) for L, hist in dataHists.items()) print [roo.wimport(w, dat) for _, dat in datas] args = [r.RooFit.Import(*dat) for dat in datas] roo.wimport( w, r.RooDataHist('data', 'N_{obs}', obs, r.RooFit.Index(w.arg('channel')), *args))
def import_asymmetry(self, w): if not self.asymmetry: return roo.factory(w, "falphaT[0.18, -0.8, 0.8]") roo.factory(w, "expr::alphaT('@0/@1',{falphaT,f_qg})") roo.factory(w, "expr::alphaL('@0/@1',{falphaL,f_qq})") [(roo.factory(w, "SUM::%(n)s( alphaT * %(n)s_both, %(n)s_symm )" % {'n': L + '_ttag'}), roo.factory(w, "SUM::%(n)s( alphaT * %(n)s_both, %(n)s_symm )" % {'n': L + '_ttqg'}), roo.factory(w, "SUM::%(n)s( alphaL * %(n)s_both, %(n)s_symm )" % {'n': L + '_ttqq'})) for L in self.channels.keys()] [(roo.factory(w, "SUM::%(n)s( 0 * %(n)s_both, %(n)s_symm )" % {'n': L + '_ttag'}), roo.factory(w, "SUM::%(n)s( 0 * %(n)s_both, %(n)s_symm )" % {'n': L + '_ttqg'}), roo.factory(w, "SUM::%(n)s( 0 * %(n)s_both, %(n)s_symm )" % {'n': L + '_ttqq'})) for L in self.channels_qcd.keys()] assert self.gen.samples['tt'].datas[0].GetXaxis().GetTitle() == genNameX assert self.gen.samples['tt'].datas[0].GetYaxis().GetTitle() == genNameY for n, d in self.gen.samples.items(): y,ey = lib.asymmetry(d.datasX[0]) p,ep = lib.asymmetry(d.datasY[0]) roo.wimport_const(w, 'Ac_y_' + n, y) roo.wimport_const(w, 'Ac_phi_' + n, p) roo.wimport_const(w, 'err_Ac_y_' + n, ey) roo.wimport_const(w, 'err_Ac_phi_' + n, ep)
def asymmStr(self): unqueued = lib.unQueuedBins(self.datas[0], 5, [-1, 1], [-1, 1]) unqx = unqueued.ProjectionX() unqy = unqueued.ProjectionY() ay = tuple([100 * f for f in lib.asymmetry(unqx)]) ap = tuple([100 * f for f in lib.asymmetry(unqy)]) del unqueued, unqx, unqy return '; '.join([('ay: % .2f(%.2f)' % ay).rjust(8), ('ap: % .2f(%.2f)' % ap).rjust(8)])
def asymmStr(self): unqueued = lib.unQueuedBins(self.datas[0],5,[-1,1],[-1,1]) unqx = unqueued.ProjectionX() unqy = unqueued.ProjectionY() ay = tuple([100*f for f in lib.asymmetry(unqx)]) ap = tuple([100*f for f in lib.asymmetry(unqy)]) del unqueued, unqx, unqy return '; '.join([ ('ay: % .2f(%.2f)'%ay).rjust(8), ('ap: % .2f(%.2f)'%ap).rjust(8) ])
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)
def import_data(self, data, name=""): roo.wimport_const(self.w,"Ac_data"+name, lib.asymmetry(data)[0]) roo.wimport(self.w, r.RooDataHist('data'+name, 'N_{obs}', r.RooArgList(self.w.argSet('x')), data))
def import_asymmetry(self, w): alpha_max = 0.99 * lib.alphaMax(self.symm, self.anti) roo.factory(w, "alpha[0, -%f, %f]"%(alpha_max,alpha_max)) roo.factory(w, 'SUM::model( alpha * pdf_template_both, pdf_template_symm)') ac, eac = lib.asymmetry(self.template) roo.wimport_const(w, "Ac_template", ac) roo.factory(w, "prod::Ac(Ac_template, alpha)")
def import_asymmetry(self, w): if not self.asymmetry: return roo.factory(w, "falphaT[0.18, -0.8, 0.8]") roo.factory(w, "expr::alphaT('@0/@1',{falphaT,f_qg})") roo.factory(w, "expr::alphaL('@0/@1',{falphaL,f_qq})") [(roo.factory( w, "SUM::%(n)s( alphaT * %(n)s_both, %(n)s_symm )" % {'n': L + '_ttag'}), roo.factory( w, "SUM::%(n)s( alphaT * %(n)s_both, %(n)s_symm )" % {'n': L + '_ttqg'}), roo.factory( w, "SUM::%(n)s( alphaL * %(n)s_both, %(n)s_symm )" % {'n': L + '_ttqq'})) for L in self.channels.keys()] [(roo.factory( w, "SUM::%(n)s( 0 * %(n)s_both, %(n)s_symm )" % {'n': L + '_ttag'}), roo.factory( w, "SUM::%(n)s( 0 * %(n)s_both, %(n)s_symm )" % {'n': L + '_ttqg'}), roo.factory( w, "SUM::%(n)s( 0 * %(n)s_both, %(n)s_symm )" % {'n': L + '_ttqq'})) for L in self.channels_qcd.keys()] assert self.gen.samples['tt'].datas[0].GetXaxis().GetTitle( ) == genNameX assert self.gen.samples['tt'].datas[0].GetYaxis().GetTitle( ) == genNameY for n, d in self.gen.samples.items(): y, ey = lib.asymmetry(d.datasX[0]) p, ep = lib.asymmetry(d.datasY[0]) roo.wimport_const(w, 'Ac_y_' + n, y) roo.wimport_const(w, 'Ac_phi_' + n, p) roo.wimport_const(w, 'err_Ac_y_' + n, ey) roo.wimport_const(w, 'err_Ac_phi_' + n, ep)
def import_data(self, altData=None): w = self.w if altData: altData.SetName('data') roo.wimport(w, altData) return obs_ = w.argSet(','.join(self.observables)) obs = r.RooArgList(obs_) dataHists = dict([(L,unqueue(chan.samples['data'].datas[0], self.asymmetry)) for L,chan in self.channels.items()]) datas = [(L, r.RooDataHist('data_' + L, 'N_{obs}^{%s}' % L, obs, data)) for L, data in dataHists.items()] if not self.quiet: print self.observables[0] print '\n'.join('%s: %.6f (%.6f)'%((L,)+lib.asymmetry(hist.ProjectionX())) for L,hist in dataHists.items()) print self.observables[1] print '\n'.join('%s: %.6f (%.6f)'%((L,)+lib.asymmetry(hist.ProjectionY())) for L,hist in dataHists.items()) print [roo.wimport(w, dat) for _, dat in datas] args = [r.RooFit.Import(*dat) for dat in datas] roo.wimport(w, r.RooDataHist('data', 'N_{obs}', obs, r.RooFit.Index(w.arg('channel')), *args))
def __init__(self, props, outName, fName = 'data/stats_top_mu_ph_sn_jn_20.root', dName = 'genTopTanhDeltaAbsY', propOrder = []): tFile = r.TFile.Open(fName) hists = {} smax = 0 amax = 0 leg = r.TLegend(0.7,0.2,0.9,0.45) leg.SetBorderSize(0) leg.SetFillColor(r.kWhite) leg.SetTextFont(42) for key in (propOrder if propOrder else props): h = tFile.Get(dName + '/' + key) N = h.GetEntries() asymm = lib.asymmetry(h) print key, N, asymm h.UseCurrentStyle() h.Rebin(2) #h.SetTitle(';%s;(1/#sigma)(d#sigma/d%s)'%(Xl,Xl)) h.SetTitle(';%s;Probability / %.2f'%(Xl,h.GetBinWidth(1))) h.GetYaxis().SetTitleOffset(1) #h.Scale(1./h.Integral(),'width') h.Scale(1./h.Integral()) col,width,style = props[key] h.SetLineColor(col) h.SetLineWidth(width) h.SetLineStyle(style) h.GetXaxis().SetNdivisions(5,4,0,False) leg.AddEntry(h, labels[key] if key in labels else key, 'L') hists[key] = lib.symmAnti(h) smax = max(smax, hists[key][0].GetMaximum()) amax = max(amax, hists[key][1].GetMaximum()) c = r.TCanvas("canvas","", 800,800) c.Print(outName + '[') for i,(n,(h,_)) in enumerate(hists.items()): h.SetMaximum(1.15*smax) h.SetMinimum(0) h.Draw('hist' + ('' if not i else 'same')) leg.Draw() text.DrawTextNDC(0.45,0.96,"Symmetric") dostamp() c.Print(outName) for i,(n,(_,h)) in enumerate(hists.items()): h.SetMaximum(1.1*amax) h.SetMinimum(-1.1*amax) h.Draw('hist' + ('' if not i else 'same')) leg.Draw() text.DrawTextNDC(0.45,0.96,"Antisymmetric") dostamp() c.Print(outName) c.Print(outName + ']') tFile.Close()
def import_asymmetry(self, w): alpha_max = 0.99 * min(chan.samples['tt'].alphaMax for chan in self.channels.values() + self.channels_qcd.values()) roo.factory(w, "alpha[1, -%f, %f]"%(alpha_max,alpha_max)) [roo.factory(w, "SUM::%(n)s( alpha * %(n)s_both, %(n)s_symm )" % {'n': L+'_tt'}) for L in (self.channels.keys() + self.channels_qcd.keys())] assert self.gen.samples['tt'].datas[0].GetXaxis().GetTitle() == genNameX assert self.gen.samples['tt'].datas[0].GetYaxis().GetTitle() == genNameY for n, d in self.gen.samples.items(): hists = {'XL':d.datasX[0], 'XT':d.datasY[0]} ac, eac = lib.asymmetry(hists[self.observables[0]]) roo.wimport_const(w, 'Ac_'+n, ac) roo.wimport_const(w, 'err_Ac_'+n, eac)
keep.append(s) keep.append(a) can.Print(fname) if __name__=="__main__": print '\t'.join(['', "m(%)",'c(%)','ain(%)','aout(%)','','Ac(%)', 'Ac_measure(%)', '', 'slope']) for lep in ['el','mu']: print lep lep_hists = hists(lep) display(lep+'_recohists.pdf', lep_hists) m = simpleModel(lep_hists['ph']) for k,v in sorted(lep_hists.items()): m.import_data(v, k) m.minimize(k) Ac = lib.asymmetry(v)[0] Ac_meas = m.val('Ac') print k.rjust(6), (4*"% 0.2f ") % tuple(100*c for c in classify5(v)), print '|\t\t', '% .2f'%(100*Ac), print '\t', "% .2f" % (100*Ac_meas), print 3*'\t', "% .2f" % (Ac_meas / Ac) pars = dict(zip(['middle','central','ain','aout'], classify5(lep_hists['ph']))) pars['N'] = 10000 h = r.TH2D('ph_symm_mods','log (A_{meas} / A_{true});log(c/c_{0});log[(m/c) / (m_{0}/c_{0})]', 11, -0.2, 0.2, 11, -0.2, 0.2) for iC in range(h.GetNbinsX()): for iM in range(h.GetNbinsY()): local_pars = dict(pars) cfactor = math.exp(h.GetXaxis().GetBinCenter(1+iC)) mfactor = math.exp(h.GetYaxis().GetBinCenter(1+iM))
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()
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'])
def Ac_raw(self, channel, model=None): hist = (self.data_hist(channel) if not model else self.expected_histogram(model + '_'+channel)) return [lib.asymmetry(h)[0] for h in self.proj(hist)]
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()
def asymmStr(self): Ac = tuple([100*f for f in lib.asymmetry(self.datas[0])]) return ("%. 2f(%.2f)" % Ac).rjust(8)