def main(): # setting for reduced DS to be used on the output of makeSubset.C inputfile_name = "small.root" tree_name = "upsTree" # settings for full dataset (long processing time for unbinned lh) #inputfile_name = "/data1/chibdata/collision/v2/2012_AllData_v2.root" #tree_name = "rootuple/upsTree" print "Opening file" inputfile = TFile.Open(inputfile_name, "READ") print "Importing tree" tree = TTree() inputfile.GetObject(tree_name, tree) mass = RooRealVar("ups_mass", "ups_mass", 7, 11) y = RooRealVar("ups_rapidity", "ups_rapidity", -3, 3) pt = RooRealVar("ups_pt", "ups_pt", 0, 100) print "Assigning dataset" dataArgSet = RooArgSet(mass, y, pt) dataSet = RooDataSet("yds", "Y data set", tree, dataArgSet) cuts= "abs(ups_rapidity) < 1.25"+\ "&& ups_pt>9.5"\ reduced_ds = dataSet.reduce(RooFit.Cut(cuts)) print "Performing likelihood analysis" dofit(reduced_ds, "Y3S")
def get_dataset(varargset, ftree, cut='', wt='', scale=1): """Return a dataset. Return a dataset from the ntuple `ftree'. Apply a selection cut using the `cutVar' variable and the selection `cut'. """ from rplot.fixes import ROOT from rplot.tselect import Tsplice splice = Tsplice(ftree) splice.make_splice('sel', cut) from ROOT import RooDataSet, RooFit, RooFormulaVar, RooArgList tmpdst = RooDataSet('tmpdataset', '', varargset, RooFit.Import(ftree)) if wt: wtvar = RooFormulaVar('wt', '{}*@0'.format(scale), RooArgList(varargset[wt])) wtvar = tmpdst.addColumn(wtvar) varargset.remove(varargset[wt]) varargset.add(wtvar) dst = RooDataSet('dataset', 'Dataset', varargset, RooFit.Import(tmpdst), RooFit.WeightVar(wtvar)) varargset.remove(wtvar) dst = dst.reduce(varargset) return dst
def get_dataset(varargset, ftree, cut="", wt="", scale=1): """Return a dataset. Return a dataset from the ntuple `ftree'. Apply a selection cut using the `cutVar' variable and the selection `cut'. """ from rplot.fixes import ROOT from rplot.tselect import Tsplice splice = Tsplice(ftree) splice.make_splice("sel", cut) from ROOT import RooDataSet, RooFit, RooFormulaVar, RooArgList tmpdst = RooDataSet("tmpdataset", "", varargset, RooFit.Import(ftree)) if wt: wtvar = RooFormulaVar("wt", "{}*@0".format(scale), RooArgList(varargset[wt])) wtvar = tmpdst.addColumn(wtvar) varargset.remove(varargset[wt]) varargset.add(wtvar) dst = RooDataSet("dataset", "Dataset", varargset, RooFit.Import(tmpdst), RooFit.WeightVar(wtvar)) varargset.remove(wtvar) dst = dst.reduce(varargset) return dst
def main(): inputfile_name = "/data1/chibdata/collision/v2/2012_AllData_v2.root" chibTree_name = "rootuple/chibTree" print "Opening file" inputfile = TFile.Open(inputfile_name, "READ") print "Importing tree" tree = TTree() inputfile.GetObject(chibTree_name, tree) invm1S = RooRealVar("invm1S", "invm1S", 9.5, 11.5) invm2S = RooRealVar("invm2S", "invm2S", 9.5, 20.0) invm3S = RooRealVar("invm3S", "invm3S", 9.5, 20.0) dimuon_mass = RooRealVar("dimuon_mass", "dimuon_mass", 8.0, 12.0) dimuon_rapidity = RooRealVar("dimuon_rapidity", "dimuon_rapidity", -5.0, 5.0) dimuon_pt = RooRealVar("dimuon_pt", "dimuon_pt", 0.0, 100.0) photon_eta = RooRealVar("photon_eta", "photon_eta", -5.0, 5.0) photon_pt = RooRealVar("photon_pt", "photon_pt", 0.0, 100.0) ctpv = RooRealVar("ctpv", "ctpv", -5.0, 5.0) ctpv_error = RooRealVar("ctpv_err", "ctpv_err", -5.0, 5.0) pi0_abs_mass = RooRealVar("pi0_abs_mass", "pi0_abs_mass", 0.0, 2.0) Y1S_nsigma = RooRealVar("Y1S_nsigma", "Y1S_nsigma", 0.0, 30.0) Y2S_nsigma = RooRealVar("Y2S_nsigma", "Y2S_nsigma", 0.0, 30.0) Y3S_nsigma = RooRealVar("Y3S_nsigma", "Y3S_nsigma", 0.0, 35.0) conv_vertex = RooRealVar("conv_vertex", "conv_vertex", 0.0, 70.0) dz = RooRealVar("dz", "dz", -50.0, 50.0) print "Assigning argset" dataArgSet = RooArgSet(invm1S, invm2S, invm3S, dimuon_mass, dimuon_rapidity, dimuon_pt, photon_eta, photon_pt, ctpv) dataArgSet.add(ctpv_error) dataArgSet.add(pi0_abs_mass) dataArgSet.add(Y1S_nsigma) dataArgSet.add(Y2S_nsigma) dataArgSet.add(Y3S_nsigma) dataArgSet.add(conv_vertex) dataArgSet.add(dz) print "Creating DataSet" dataSet = RooDataSet("chibds", "Chib RooDataSet", tree, dataArgSet) # Selection cuts = "photon_pt > 0.0" + \ "&&dimuon_pt > 9.5" \ "&& abs(photon_eta) < 1.4" + \ "&& abs(dimuon_rapidity) < 1.25 " + \ "&& Y3S_nsigma < 2.5 " + \ "&& abs(dz) < 0.1" rds_cutted = dataSet.reduce(RooFit.Cut(cuts)) dofit(rds_cutted, "Chib_fit_2012_3S")
def main() : inputfile_name = "/data1/chibdata/collision/v2/2012_AllData_v2.root" chibTree_name = "rootuple/chibTree" print "Opening file" inputfile = TFile.Open(inputfile_name,"READ") print "Importing tree" tree = TTree() inputfile.GetObject(chibTree_name, tree) invm1S = RooRealVar("invm1S", "invm1S", 9.5, 11.5) invm2S = RooRealVar("invm2S", "invm2S", 9.5, 20.0) invm3S = RooRealVar("invm3S", "invm3S", 9.5, 20.0) dimuon_mass = RooRealVar("dimuon_mass","dimuon_mass", 8.0, 12.0) dimuon_rapidity = RooRealVar("dimuon_rapidity", "dimuon_rapidity", -5.0, 5.0) dimuon_pt = RooRealVar("dimuon_pt","dimuon_pt", 0.0, 100.0) photon_eta = RooRealVar("photon_eta","photon_eta", -5.0, 5.0) photon_pt = RooRealVar("photon_pt","photon_pt", 0.0, 100.0) ctpv = RooRealVar("ctpv","ctpv", -5.0, 5.0) ctpv_error = RooRealVar("ctpv_err","ctpv_err", -5.0, 5.0) pi0_abs_mass = RooRealVar("pi0_abs_mass","pi0_abs_mass", 0.0, 2.0) Y1S_nsigma = RooRealVar("Y1S_nsigma","Y1S_nsigma",0.0,30.0) Y2S_nsigma = RooRealVar("Y2S_nsigma","Y2S_nsigma",0.0,30.0) Y3S_nsigma = RooRealVar("Y3S_nsigma","Y3S_nsigma",0.0,35.0) conv_vertex = RooRealVar("conv_vertex", "conv_vertex", 0.0, 70.0) dz = RooRealVar("dz","dz", -50.0, 50.0) print "Assigning argset" dataArgSet = RooArgSet(invm1S, invm2S, invm3S, dimuon_mass, dimuon_rapidity, dimuon_pt, photon_eta, photon_pt, ctpv) dataArgSet.add( ctpv_error ) dataArgSet.add( pi0_abs_mass ) dataArgSet.add( Y1S_nsigma ) dataArgSet.add( Y2S_nsigma ) dataArgSet.add( Y3S_nsigma ) dataArgSet.add( conv_vertex ) dataArgSet.add( dz ) print "Creating DataSet" dataSet = RooDataSet("chibds","Chib RooDataSet", tree, dataArgSet) # Selection cuts = "photon_pt > 0.0" + \ "&&dimuon_pt > 9.5" \ "&& abs(photon_eta) < 1.4" + \ "&& abs(dimuon_rapidity) < 1.25 " + \ "&& Y3S_nsigma < 2.5 " + \ "&& abs(dz) < 0.1" rds_cutted = dataSet.reduce( RooFit.Cut(cuts) ) dofit(rds_cutted, "Chib_fit_2012_3S")
def get_dataset(varargset, ftree, cut='', cutVars=[], *cmdArgs): """Return a dataset. Return a dataset from the ntuple `ftree'. Apply a selection cut using the `cutVar' variable and the selection `cut'. """ varargsetclone = varargset.clone('varargsetclone') for cvar in cutVars: varargsetclone.add(cvar) # Add selVar to apply cut tmpdataset = RooDataSet('dataset', 'Dataset', varargsetclone, RooFit.Import(ftree), RooFit.Cut(cut), *cmdArgs) dataset = tmpdataset.reduce(varargset) del tmpdataset return dataset
obs=w.set("obs_1d") uncVZ = w.var("uncVZ") uncVZ.setBins(1000) gauss_params = gauss_pdf.getParameters(obs) gaussexp_params = gaussexp_pdf.getParameters(obs) for i in range(1,n_massbins): #for i in range(0,totalH.GetXaxis().GetNbins()-binning+2,binning): print i centermass=yieldhist.GetXaxis().GetBinCenter(i) massrange=2.5*(massres_a*centermass + massres_b) lowedge = centermass-massrange/2.0 highedge = centermass+massrange/2.0 name="Radiative vertex Z, mass [{}, {}] GeV".format(lowedge,highedge) #dataset = RooDataSet("data","data",events,w.set("myVars"),"abs(uncM-{0})<{1}".format(centermass,massrange/2)) dataInRange = dataset.reduce(obs,"abs(uncM-{0})<{1}".format(centermass,massrange/2)) if dataInRange.sumEntries()<100: continue frame=uncVZ.frame() frame.SetTitle(name) binnedData = dataInRange.binnedClone() binnedData.plotOn(frame) mean = binnedData.mean(uncVZ) sigma = binnedData.sigma(uncVZ) print "before gaussian fit: mean={0}, sigma={1}".format(mean,sigma) uncVZ.setRange("fitRange",mean-3*sigma,mean+3*sigma) gauss_params.setRealValue("mean",mean) gauss_params.setRealValue("sigma",sigma) #gauss_params.printLatex()
pdfConfig['timeEffHistFiles'].getSettings( [ ( 'runPeriod', 'p2012' ) ] )['file'] = timeEffFile2012 pdfConfig['anglesEffType'] = 'basisSig6' pdfConfig['angEffMomsFiles'] = dataPath + 'angEffNominalRew_5thOrder.par' pdfConfig['signalData'] = dataSetAsymW pdfConfig['readFromWS'] = True from P2VV.Parameterizations.FullPDFs import Bs2Jpsiphi_PdfBuilder as PdfBuilder pdfBuild = PdfBuilder( **pdfConfig ) pdf = pdfBuild.pdf() pdfConfig.readParametersFromFile( filePath = parFilePath ) pdfConfig.setParametersInPdf(pdf) # create projection data sets projSet = [ obs for obs in pdf.ConditionalObservables() ] + [ cat for cat in pdf.indexCat().inputCatList() ] projSet = RooArgSet( obsSet.find( var.GetName() ) for var in projSet ) projDataSets = dict( plus = dataSetAsymW.reduce( Name = 'asymDataWPlus', SelectVars = projSet, Cut = 'asymCat==+1' ) , minus = dataSetAsymW.reduce( Name = 'asymDataWMinus', SelectVars = projSet, Cut = 'asymCat==-1' ) ) print 'pdfAsymmetry: projection data sets:' projDataSets['plus'].Print() projDataSets['minus'].Print() # create time ranges for time bins rangeNames = dict( ) timePoints = dict( ) lastBin = False if not timeBins : timeBins = range(8) if not periods : periods = range( int( ws['time'].getMax() / oscPeriod - binOffset / float(numTimeBinsTot) ) + 1 ) for per in periods : for bin in timeBins : timeLo = ( float(per) + ( float(bin) + binOffset ) / float(numTimeBinsTot) ) * oscPeriod
def make_fit(): adc_bin = 12 #18 for low-m gg, 24 for jpsi adc_min = 0. #10. adc_max = 400. #adc_max = 1200 ptmax = 0.18 #mmin = 1.6 #mmin = 2.1 #mmax = 2.6 #mmin = 1.5 #mmax = 5. mmin = 2.9 mmax = 3.2 #mmin = 3.4 #mmax = 4.6 #east/west projections and 2D plot ew = 1 p2d = 2 # 0: single projection by 'ew', 1: 2D plot, 2: both projections #plot colors model_col = rt.kMagenta model_col = rt.kBlue out = open("out.txt", "w") lmg = 6 ut.log_results(out, "in " + infile, lmg) strlog = "adc_bin " + str(adc_bin) + " adc_min " + str( adc_min) + " adc_max " + str(adc_max) strlog += " ptmax " + str(ptmax) + " mmin " + str(mmin) + " mmax " + str( mmax) ut.log_results(out, strlog, lmg) #adc distributions adc_east = RooRealVar("jZDCUnAttEast", "ZDC ADC east", adc_min, adc_max) adc_west = RooRealVar("jZDCUnAttWest", "ZDC ADC west", adc_min, adc_max) #kinematics variables m = RooRealVar("jRecM", "e^{+}e^{-} mass (GeV)", 0., 10.) y = RooRealVar("jRecY", "rapidity", -1., 1.) pT = RooRealVar("jRecPt", "pT", 0., 10.) #adc distributions #adc_east = RooRealVar("zdce", "ZDC ADC east", adc_min, adc_max) #adc_west = RooRealVar("zdcw", "ZDC ADC west", adc_min, adc_max) #kinematics variables #m = RooRealVar("mee", "e^{+}e^{-} mass (GeV)", 0., 10.) #y = RooRealVar("rapee", "rapidity", -1., 1.) #pT = RooRealVar("ptpair", "pT", 0., 10.) strsel = "jRecPt<{0:.3f} && jRecM>{1:.3f} && jRecM<{2:.3f}".format( ptmax, mmin, mmax) #strsel = "ptpair<{0:.3f} && mee>{1:.3f} && mee<{2:.3f}".format(ptmax, mmin, mmax) data_all = RooDataSet("data", "data", tree, RooArgSet(adc_east, adc_west, m, y, pT)) print "All input:", data_all.numEntries() data = data_all.reduce(strsel) print "Sel input:", data.numEntries() model = Model2D(adc_east, adc_west) r1 = model.model.fitTo(data, rf.Save()) ut.log_results(out, ut.log_fit_result(r1), lmg) ut.log_results(out, "Fit parameters:\n", lmg) out.write(ut.log_fit_parameters(r1, lmg + 2) + "\n") #out.write(ut.table_fit_parameters(r1)) #print ut.table_fit_parameters(r1) #create the plot if p2d != 2: can = ut.box_canvas() nbins, adc_max = ut.get_nbins(adc_bin, adc_min, adc_max) adc_east.setMax(adc_max) adc_west.setMax(adc_max) frame_east = adc_east.frame(rf.Bins(nbins), rf.Title("")) frame_west = adc_west.frame(rf.Bins(nbins), rf.Title("")) data.plotOn(frame_east, rf.Name("data")) model.model.plotOn(frame_east, rf.Precision(1e-6), rf.Name("model"), rf.LineColor(model_col)) data.plotOn(frame_west, rf.Name("data")) model.model.plotOn(frame_west, rf.Precision(1e-6), rf.Name("model"), rf.LineColor(model_col)) #reduced chi^2 in east and west projections ut.log_results(out, "chi2/ndf:\n", lmg) ut.log_results( out, " East chi2/ndf: " + str(frame_east.chiSquare("model", "data", 16)), lmg) ut.log_results( out, " West chi2/ndf: " + str(frame_west.chiSquare("model", "data", 16)), lmg) ut.log_results(out, "", 0) ytit = "Events / ({0:.0f} ADC units)".format(adc_bin) frame_east.SetYTitle(ytit) frame_west.SetYTitle(ytit) frame_east.SetTitle("") frame_west.SetTitle("") frame = [frame_east, frame_west] if p2d == 0: plot_projection(frame[ew], ew) plot_pdf = PlotPdf(model, adc_east, adc_west) if p2d == 1: plot_2d(plot_pdf) if p2d == 2: frame2 = ut.prepare_TH1D("frame2", adc_bin, adc_min, 2. * adc_max + 4.1 * adc_bin) plot_proj_both(frame2, frame_east, frame_west, adc_bin, adc_min, adc_max, ptmax, mmin, mmax) lhead = ["east ZDC", "west ZDC"] if p2d == 1: leg = ut.prepare_leg(0.003, 0.9, 0.3, 0.1, 0.035) else: leg = ut.prepare_leg(0.66, 0.8, 0.32, 0.13, 0.03) if p2d == 0: leg.AddEntry(None, "#bf{Projection to " + lhead[ew] + "}", "") leg.SetMargin(0.05) leg.AddEntry(None, "#bf{#it{p}_{T} < " + "{0:.2f}".format(ptmax) + " GeV/c}", "") mmin_fmt = "{0:.1f}".format(mmin) mmax_fmt = "{0:.1f}".format(mmax) leg.AddEntry( None, "#bf{" + mmin_fmt + " < #it{m}_{e^{+}e^{-}} < " + mmax_fmt + " GeV/c^{2}}", "") leg.Draw("same") pleg = ut.prepare_leg(0.99, 0.87, -0.4, 0.11, 0.035) pleg.SetFillStyle(1001) #pleg.AddEntry(None, "STAR Preliminary", "") pleg.AddEntry(None, "AuAu@200 GeV", "") pleg.AddEntry(None, "UPC sample", "") #pleg.Draw("same") #ut.print_pad(gPad) #b3d = TBuffer3D(0) #b3d = None #gPad.GetViewer3D().OpenComposite(b3d) #print b3d #print "All input: ", data.numEntries() #print "All input: 858" #all input data nall = float(tree.Draw("", strsel)) print "All input: ", nall n_1n1n = float(model.num_1n1n.getVal()) print "1n1n events: ", n_1n1n ratio_1n1n = n_1n1n / nall sigma_ratio_1n1n = ratio_1n1n * TMath.Sqrt( (nall - n_1n1n) / (nall * n_1n1n)) print "Ratio 1n1n / all: ", ratio_1n1n, "+/-", sigma_ratio_1n1n ut.log_results(out, "Fraction of 1n1n events:\n", lmg) ut.log_results(out, "All input: " + str(nall), lmg) ut.log_results(out, "1n1n events: " + str(model.num_1n1n.getVal()), lmg) ratio_str = "Ratio 1n1n / all: " + str(ratio_1n1n) + " +/- " + str( sigma_ratio_1n1n) ut.log_results(out, ratio_str, lmg) if p2d != 2: #ut.print_pad(gPad) ut.invert_col(gPad) can.SaveAs("01fig.pdf") if interactive == True: start_interactive()
#c.Print(remainder[0]+".pdf","Title:mass_{0}".format(mass)) num_pairs = gDirectory.Get("mass").GetEntries()*scale_factor radfrac = radfracFile.Get("radfrac").GetFunction("pol3").Eval(mass) num_rad = radfrac*num_pairs ap_yield= 3*math.pi/(2*(1/137.0))*num_rad*(mass/deltaM) print "{0} pairs, {1} radfrac, {2} rad, {3} A'".format(num_pairs,radfrac,num_rad,ap_yield) breakz = tailsFile.Get("breakz").GetFunction("pol3").Eval(mass) length = tailsFile.Get("length").GetFunction("pol3").Eval(mass) c.cd(2) gPad.SetLogy() frame=uncVZ.frame() dataInRange = dataset.reduce(obs,"abs({0}-{1})<{2}/2*({3}+{4}*uncVZ)".format(massVar,mass,masscut_nsigma,mres_p0,mres_p1)) binnedData = dataInRange.binnedClone() binnedData.plotOn(frame) mean = binnedData.mean(uncVZ) sigma = binnedData.sigma(uncVZ) uncVZ.setRange("fitRange",mean-2*sigma,mean+2*sigma) gauss_params.setRealValue("mean",mean) gauss_params.setRealValue("sigma",sigma) gauss_pdf.fitTo(binnedData,RooFit.Range("fitRange"),RooFit.PrintLevel(-1)) mean= gauss_params.getRealValue("mean") sigma= gauss_params.getRealValue("sigma") gaussexp_params.setRealValue("gauss_mean",mean) gaussexp_params.setRealValue("gauss_sigma",sigma) gaussexp_params.setRealValue("exp_breakpoint",breakz) gaussexp_params.setRealValue("exp_length",length) w.var("gauss_mean").setConstant(True)
def buildDataAndCategories(ws,options,args): #Get the input data inputData = TChain(options.treeName,'The input data') for arg in args: print 'Adding data from: ',arg inputData.Add(arg) foldname = '' phirange = [0,90] if not options.folded: foldname='' phirange = [-180,180] #variables necessary for j/psi mass,lifetime,polarization fit jPsiMass = RooRealVar('JpsiMass','M [GeV]',2.7,3.5) jPsiRap = RooRealVar('JpsiRap','#nu',-2.3,2.3) jPsiPt = RooRealVar("JpsiPt","pT [GeV]",0,40); jPsicTau = RooRealVar('Jpsict','l_{J/#psi} [mm]',-1,2.5) jPsicTauError = RooRealVar('JpsictErr','Error on l_{J/#psi} [mm]',0,2) jPsiVprob = RooRealVar('JpsiVprob','',.01,1) jPsiHXcosth = None jPsiHXphi = None jPsicTau.setBins(10000,"cache") if options.fitFrame is not None: jPsiHXcosth = RooRealVar('costh_'+options.fitFrame+foldname,'cos(#theta)_{'+options.fitFrame+'}',-1,1) jPsiHXphi = RooRealVar('phi_'+options.fitFrame+foldname,'#phi_{'+options.fitFrame+'}',phirange[0],phirange[1]) else: jPsiHXcosth = RooRealVar('costh_CS'+foldname,'cos(#theta)_{CS}',-1,1) jPsiHXphi = RooRealVar('phi_CS'+foldname,'#phi_{CS}',phirange[0],phirange[1]) #vars needed for on the fly calc of polarization variables jPsimuPosPx = RooRealVar('muPosPx','+ Muon P_{x} [GeV]',0) jPsimuPosPy = RooRealVar('muPosPy','+ Muon P_{y} [GeV]',0) jPsimuPosPz = RooRealVar('muPosPz','+ Muon P_{z} [GeV]',0) jPsimuNegPx = RooRealVar('muNegPx','- Muon P_{x} [GeV]',0) jPsimuNegPy = RooRealVar('muNegPy','- Muon P_{y} [GeV]',0) jPsimuNegPz = RooRealVar('muNegPz','- Muon P_{z} [GeV]',0) #create RooArgSet for eventual dataset creation dataVars = RooArgSet(jPsiMass,jPsiRap,jPsiPt, jPsicTau,jPsicTauError, jPsimuPosPx,jPsimuPosPy,jPsimuPosPz) #add trigger requirement if specified if options.triggerName: trigger = RooRealVar(options.triggerName,'Passes Trigger',0.5,1.5) dataVars.add(trigger) dataVars.add(jPsiVprob) dataVars.add(jPsimuNegPx) dataVars.add(jPsimuNegPy) dataVars.add(jPsimuNegPz) dataVars.add(jPsiHXcosth) dataVars.add(jPsiHXphi) redVars = RooArgSet(jPsiMass,jPsiRap,jPsiPt, jPsicTau,jPsicTauError) redVars.add(jPsiHXcosth) redVars.add(jPsiHXphi) fitVars = redVars.Clone() ### HERE IS WHERE THE BIT FOR CALCULATING POLARIZATION VARS GOES ctauStates = RooCategory('ctauRegion','Cut Region in lifetime') ctauStates.defineType('prompt',0) ctauStates.defineType('nonPrompt',1) massStates = RooCategory('massRegion','Cut Region in mass') massStates.defineType('signal',1) massStates.defineType('separation',0) massStates.defineType('leftMassSideBand',-2) massStates.defineType('rightMassSideBand',-1) states = RooCategory('mlRegion','Cut Region in mass') states.defineType('nonPromptSignal',2) states.defineType('promptSignal',1) states.defineType('separation',0) states.defineType('leftMassSideBand',-2) states.defineType('rightMassSideBand',-1) #define corresponding ranges in roorealvars #mass is a little tricky since the sidebands change definitions in each rap bin #define the names here and change as we do the fits #jPsiMass.setRange('NormalizationRangeFormlfit_promptSignal',2.7,3.5) #jPsiMass.setRange('NormalizationRangeFormlfit_nonPromptSignal',2.7,3.5) #jPsiMass.setRange('NormalizationRangeFormlfit_leftMassSideBand',2.7,3.1) #jPsiMass.setRange('NormalizationRangeFormlfit_rightMassSideBand',3.1,3.5) #want the prompt fit only done in prompt region #non-prompt only in non-prompt region #background over entire cTau range #jPsicTau.setRange('NormalizationRangeFormlfit_promptSignal',-1,.1) #jPsicTau.setRange('NormalizationRangeFormlfit_nonPromptSignal',.1,2.5) #jPsicTau.setRange('NormalizationRangeFormlfit_leftMassSideBand',-1,2.5) #jPsicTau.setRange('NormalizationRangeFormlfit_rightMassSideBand',-1,2.5) #redVars.add(ctauStates) #redVars.add(massStates) #redVars.add(states) fitVars.add(ctauStates) fitVars.add(massStates) fitVars.add(states) fullData = RooDataSet('fullData','The Full Data From the Input ROOT Trees', dataVars, ROOT.RooFit.Import(inputData)) for rap_bin in range(1,len(jpsi.pTRange)): yMin = jpsi.rapForPTRange[rap_bin-1][0] yMax = jpsi.rapForPTRange[rap_bin-1][-1] for pt_bin in range(len(jpsi.pTRange[rap_bin])): ptMin = jpsi.pTRange[rap_bin][pt_bin][0] ptMax = jpsi.pTRange[rap_bin][pt_bin][-1] sigMaxMass = jpsi.polMassJpsi[rap_bin] + jpsi.nSigMass*jpsi.sigmaMassJpsi[rap_bin] sigMinMass = jpsi.polMassJpsi[rap_bin] - jpsi.nSigMass*jpsi.sigmaMassJpsi[rap_bin] sbHighMass = jpsi.polMassJpsi[rap_bin] + jpsi.nSigBkgHigh*jpsi.sigmaMassJpsi[rap_bin] sbLowMass = jpsi.polMassJpsi[rap_bin] - jpsi.nSigBkgLow*jpsi.sigmaMassJpsi[rap_bin] ctauNonPrompt = .1 massFun = RooFormulaVar('massRegion','Function that returns the mass state.', '('+jPsiMass.GetName()+' < '+str(sigMaxMass)+' && '+jPsiMass.GetName()+' > '+str(sigMinMass)+ ') - ('+jPsiMass.GetName()+' > '+str(sbHighMass)+')'+ '-2*('+jPsiMass.GetName()+' < '+str(sbLowMass)+')', RooArgList(jPsiMass,jPsicTau)) ctauFun = RooFormulaVar('ctauRegion','Function that returns the ctau state.', '('+jPsicTau.GetName()+' > '+str(ctauNonPrompt)+')', RooArgList(jPsiMass,jPsicTau)) mlFun = RooFormulaVar('mlRegion','Function that returns the mass and lifetime state.', '('+jPsiMass.GetName()+' < '+str(sigMaxMass)+' && '+jPsiMass.GetName()+' > '+str(sigMinMass)+ ') + ('+jPsiMass.GetName()+' < '+str(sigMaxMass)+' && '+jPsiMass.GetName()+' > '+ str(sigMinMass)+' && '+jPsicTau.GetName()+' > '+str(ctauNonPrompt)+ ') - ('+jPsiMass.GetName()+' > '+str(sbHighMass)+')'+ '-2*('+jPsiMass.GetName()+' < '+str(sbLowMass)+')', RooArgList(jPsiMass,jPsicTau)) cutStringPt = '('+jPsiPt.GetName()+' > '+str(ptMin)+' && '+jPsiPt.GetName()+' < '+str(ptMax)+')' cutStringY = '( abs('+jPsiRap.GetName()+') > '+str(yMin)+' && abs('+jPsiRap.GetName()+') < '+str(yMax)+')' #cutStringM1 = '('+jPsiMass.GetName()+' < '+str(sigMinMass)+' && '+jPsiMass.GetName()+' > '+str(sbLowMass)+')' #cutStringM2 = '('+jPsiMass.GetName()+' < '+str(sbHighMass)+' && '+jPsiMass.GetName()+' > '+str(sigMaxMass)+')' #cutStringMT = '!('+cutStringM1+' || '+cutStringM2+')' cutString = cutStringPt+' && '+cutStringY #+' && '+cutStringMT print cutString #get the reduced dataset we'll do the fit on binData = fullData.reduce(ROOT.RooFit.SelectVars(redVars), ROOT.RooFit.Cut(cutString), ROOT.RooFit.Name('data_rap'+str(rap_bin)+'_pt'+str(pt_bin+1)), ROOT.RooFit.Title('Data For Fitting')) binDataWithCategory = RooDataSet('data_rap'+str(rap_bin)+'_pt'+str(pt_bin+1), 'Data For Fitting', fitVars) #categorize binData.addColumn(ctauStates) binData.addColumn(massStates) binData.addColumn(states) for ev in range(binData.numEntries()): args = binData.get(ev) jPsiMass.setVal(args.find(jPsiMass.GetName()).getVal()) jPsiRap.setVal(args.find(jPsiRap.GetName()).getVal()) jPsiPt.setVal(args.find(jPsiPt.GetName()).getVal()) jPsicTau.setVal(args.find(jPsicTau.GetName()).getVal()) jPsicTauError.setVal(args.find(jPsicTauError.GetName()).getVal()) jPsiHXcosth.setVal(args.find(jPsiHXcosth.GetName()).getVal()) jPsiHXphi.setVal(args.find(jPsiHXphi.GetName()).getVal()) massStates.setIndex(int(massFun.getVal())) ctauStates.setIndex(int(ctauFun.getVal())) states.setIndex(int(mlFun.getVal())) binDataWithCategory.add(fitVars) getattr(ws,'import')(binDataWithCategory)
def prepare_truth_models(ws,cat,mass,channel,turnon,truth): if channel in study_inputs: bkg_data = RooDataSet("bkgdata_%s"%(channel), "M_{ll#gamma} with Errors", ws.set("observables_weight"), "weight") for k,file in enumerate(study_inputs[channel]): f_in = TFile.Open(file,"READ") gDirectory.cd(pwd) n_events = f_in.Get("eventCount").GetBinContent(1) tree = f_in.Get("selected_zg").CloneTree() tree.SetName("tree_%s_%i"%(channel,k)) f_in.Close() d_in = RooDataSet("temp", "M_{ll#gamma} with Errors", tree, ws.set("observables")) norm = RooConstVar("norm","norm",n_events) weight = RooFormulaVar("weight", "weight", "1.3*@0*@1/@2", #1.3 gives 19.6/fb RooArgList(ws.var("puWeight"), ws.var("procWeight"), norm) ) d_in.addColumn(weight) d_in_weight = RooDataSet("temp_weight", "M_{ll#gamma} with Errors", d_in, ws.set("observables_weight"), '','weight') bkg_data.append(d_in_weight) # split off data for each category, create the # toy dataset truth models data = bkg_data.reduce("Mz + Mzg > 185 && r94cat == %i"%cat) getattr(ws,'import')(data, RooFit.Rename('bkgdata_%s_%i'%(channel, cat))) nevts = data.sumEntries('Mzg > %f && Mzg < %f'%(mass-1.5,mass+1.5)) #for sigm turn on we want erf truth if turnon == 'sigm' and truth == 'exp': #make RooDecay 'truth' model with erf turn on ws.factory( 'RooGaussModel::MzgResoShape_exp_erf_%s_cat%i(Mzg,'\ 'bias_exp_erf_%s_cat%i[120,90,150],sigma_exp_erf_%s_cat%i[1,0.01,10])'%( channel,cat, channel,cat, channel,cat) ) ws.factory( 'RooDecay::MzgTruthModelBase_exp_erf_%s_cat%i(Mzg,'\ 'tau_erf_%s_cat%i[25,0,50],MzgResoShape_exp_erf_%s_cat%i,' 'RooDecay::SingleSided)'%(channel,cat, channel,cat, channel,cat) ) ws.factory( 'RooExtendPdf::MzgTruthModel_exp_erf_%s_cat%i('\ 'MzgTruthModelBase_exp_erf_%s_cat%i,'\ 'norm_truth_exp_%s_cat%i[%f,%f,%f],"ROI")'%(channel,cat, channel,cat, channel,cat, nevts, 0.25*nevts,1.75*nevts) ) ws.pdf('MzgTruthModel_exp_erf_%s_cat%i'%(channel,cat)).fitTo( ws.data('bkgdata_%s_%i'%(channel,cat)), RooFit.Minimizer('Minuit2','scan'), RooFit.SumW2Error(False) ) ws.pdf('MzgTruthModel_exp_erf_%s_cat%i'%(channel,cat)).fitTo( ws.data('bkgdata_%s_%i'%(channel,cat)), RooFit.Minimizer('Minuit','simplex'), RooFit.SumW2Error(False) ) ws.pdf('MzgTruthModel_exp_erf_%s_cat%i'%(channel,cat)).fitTo( ws.data('bkgdata_%s_%i'%(channel,cat)), RooFit.SumW2Error(True) ) if turnon == 'sigm' and truth == 'pow': #make power-law truth model with erf turn on ws.factory('EXPR::MzgTruthModelShape_pow_erf_%s_cat%i('\ '"1e-20 + (@0 > @1)*((@0)^(-@2))",'\ '{Mzg,step_pow_erf_%s_cat%i[105,100,130],'\ 'pow_%s_cat%i[2,0,10]})'\ %(channel,cat, channel,cat, channel,cat)) ws.factory( 'RooGaussModel::MzgResoShape_pow_erf_%s_cat%i(Mzg,'\ 'bias_pow_erf_%s_cat%i[0],sigma_pow_erf_%s_cat%i[1,0.01,10])'%( channel,cat, channel,cat, channel,cat) ) ws.factory('FCONV::MzgTruthModelBase_pow_erf_%s_cat%i(Mzg,'\ 'MzgTruthModelShape_pow_erf_%s_cat%i,'\ 'MzgResoShape_pow_erf_%s_cat%i)'%(channel,cat, channel,cat, channel,cat)) ws.factory( 'RooExtendPdf::MzgTruthModel_pow_erf_%s_cat%i('\ 'MzgTruthModelBase_pow_erf_%s_cat%i,'\ 'norm_truth_pow_erf_%s_cat%i[%f,%f,%f],"ROI")'%(channel,cat, channel,cat, channel,cat, nevts, 0.25*nevts,1.75*nevts) ) ws.pdf('MzgTruthModel_pow_erf_%s_cat%i'%(channel,cat)).fitTo( ws.data('bkgdata_%s_%i'%(channel,cat)), RooFit.Minimizer('Minuit2','scan'), RooFit.SumW2Error(False) ) ws.pdf('MzgTruthModel_pow_erf_%s_cat%i'%(channel,cat)).fitTo( ws.data('bkgdata_%s_%i'%(channel,cat)), RooFit.Minimizer('Minuit','simplex'), RooFit.SumW2Error(False) ) ws.pdf('MzgTruthModel_pow_erf_%s_cat%i'%(channel,cat)).fitTo( ws.data('bkgdata_%s_%i'%(channel,cat)), RooFit.SumW2Error(True) ) #for erf fitting turn on we want sigmoid truth if turnon == 'erf' and truth == 'exp': #build exponential convoluted with sigmoid turn-on ws.factory('RooStepExponential::MzgTruthModelShape_exp_sigm_%s_cat%i'\ '(Mzg,tau_sigm_%s_cat%i[-0.05,-10,0],'\ 'step_exp_sigm_%s_cat%i[110,100,130])'%(channel,cat, channel,cat, channel,cat)) ws.factory( 'RooLogistics::MzgResoShape_exp_sigm_%s_cat%i(%s)'%( channel,cat, ','.join(['Mzg', 'bias_exp_sigm_%s_cat%i[0]'%(channel,cat), 'sigma_exp_sigm_%s_cat%i[5,0.01,20]'%(channel,cat)]) ) ) ws.factory('FCONV::MzgTruthModelBase_exp_sigm_%s_cat%i(Mzg,'\ 'MzgTruthModelShape_exp_sigm_%s_cat%i,'\ 'MzgResoShape_exp_sigm_%s_cat%i)'%(channel,cat, channel,cat, channel,cat)) ws.factory( 'RooExtendPdf::MzgTruthModel_exp_sigm_%s_cat%i('\ 'MzgTruthModelBase_exp_sigm_%s_cat%i,'\ 'norm_truth_exp_sigm_%s_cat%i[%f,%f,%f],"ROI")'%(channel,cat, channel,cat, channel,cat, nevts, 0.25*nevts,1.75*nevts) ) ws.pdf('MzgTruthModel_exp_sigm_%s_cat%i'%(channel,cat)).fitTo( ws.data('bkgdata_%s_%i'%(channel,cat)), RooFit.Minimizer('Minuit2','scan'), RooFit.SumW2Error(False) ) ws.pdf('MzgTruthModel_exp_sigm_%s_cat%i'%(channel,cat)).fitTo( ws.data('bkgdata_%s_%i'%(channel,cat)), RooFit.Minimizer('Minuit','simplex'), RooFit.SumW2Error(False) ) ws.pdf('MzgTruthModel_exp_sigm_%s_cat%i'%(channel,cat)).fitTo( ws.data('bkgdata_%s_%i'%(channel,cat)), RooFit.SumW2Error(True) ) if turnon == 'erf' and truth == 'pow': #build power-law convoluted with sigmoid turn-on ws.factory('EXPR::MzgTruthModelShape_pow_sigm_%s_cat%i('\ '"1e-20 + (@0 > @1)*((@0)^(-@2))",'\ '{Mzg,step_pow_sigm_%s_cat%i[105,100,130],'\ 'pow_sigm_%s_cat%i[2,0,10]})'\ %(channel,cat, channel,cat, channel,cat)) ws.factory( 'RooLogistics::MzgResoShape_pow_sigm_%s_cat%i(%s)'%( channel,cat, ','.join(['Mzg', 'bias_pow_sigm_%s_cat%i[0]'%(channel,cat), 'sigma_pow_sigm_%s_cat%i[5,0.01,20]'%(channel,cat)]) ) ) ws.factory('FCONV::MzgTruthModelBase_pow_sigm_%s_cat%i(Mzg,'\ 'MzgTruthModelShape_pow_sigm_%s_cat%i,'\ 'MzgResoShape_pow_sigm_%s_cat%i)'%(channel,cat, channel,cat, channel,cat)) ws.factory( 'RooExtendPdf::MzgTruthModel_pow_sigm_%s_cat%i('\ 'MzgTruthModelBase_pow_sigm_%s_cat%i,'\ 'norm_truth_pow_sigm_%s_cat%i[%f,%f,%f],"ROI")'%(channel,cat, channel,cat, channel,cat, nevts, 0.25*nevts,1.75*nevts) ) ws.pdf('MzgTruthModel_pow_sigm_%s_cat%i'%(channel,cat)).fitTo( ws.data('bkgdata_%s_%i'%(channel,cat)), RooFit.Minimizer('Minuit2','scan'), RooFit.SumW2Error(False) ) ws.pdf('MzgTruthModel_pow_sigm_%s_cat%i'%(channel,cat)).fitTo( ws.data('bkgdata_%s_%i'%(channel,cat)), RooFit.Minimizer('Minuit','simplex'), RooFit.SumW2Error(False) ) ws.pdf('MzgTruthModel_pow_sigm_%s_cat%i'%(channel,cat)).fitTo( ws.data('bkgdata_%s_%i'%(channel,cat)), RooFit.SumW2Error(True) )
def pdf_logPt2_prelim(): #PDF fit to log_10(pT^2) for preliminary figure #tree_in = tree_incoh tree_in = tree #ptbin = 0.04 ptbin = 0.12 ptmin = -5. ptmax = 1. mmin = 2.8 mmax = 3.2 #fitran = [-5., 1.] fitran = [-0.9, 0.1] binned = False #gamma-gamma 131 evt for pT<0.18 #input data pT = RooRealVar("jRecPt", "pT", 0, 10) m = RooRealVar("jRecM", "mass", 0, 10) dataIN = RooDataSet("data", "data", tree_in, RooArgSet(pT, m)) strsel = "jRecM>{0:.3f} && jRecM<{1:.3f}".format(mmin, mmax) data = dataIN.reduce(strsel) #x is RooRealVar for log(Pt2) draw = "TMath::Log10(jRecPt*jRecPt)" draw_func = RooFormulaVar( "x", "Dielectron log_{10}( #it{p}_{T}^{2} ) ((GeV/c)^{2})", draw, RooArgList(pT)) x = data.addColumn(draw_func) x.setRange("fitran", fitran[0], fitran[1]) #binned data nbins, ptmax = ut.get_nbins(ptbin, ptmin, ptmax) hPt = TH1D("hPt", "hPt", nbins, ptmin, ptmax) hPtCoh = ut.prepare_TH1D("hPtCoh", ptbin, ptmin, ptmax) hPtCoh.SetLineWidth(2) #fill in binned data tree_in.Draw(draw + " >> hPt", strsel) tree_coh.Draw(draw + " >> hPtCoh", strsel) dataH = RooDataHist("dataH", "dataH", RooArgList(x), hPt) #range for plot x.setMin(ptmin) x.setMax(ptmax) x.setRange("plotran", ptmin, ptmax) #create the pdf b = RooRealVar("b", "b", 5., 0., 10.) pdf_func = "log(10.)*pow(10.,x)*exp(-b*pow(10.,x))" pdf_logPt2 = RooGenericPdf("pdf_logPt2", pdf_func, RooArgList(x, b)) #make the fit if binned == True: r1 = pdf_logPt2.fitTo(dataH, rf.Range("fitran"), rf.Save()) else: r1 = pdf_logPt2.fitTo(data, rf.Range("fitran"), rf.Save()) #calculate norm to number of events xset = RooArgSet(x) ipdf = pdf_logPt2.createIntegral(xset, rf.NormSet(xset), rf.Range("fitran")) print "PDF integral:", ipdf.getVal() if binned == True: nevt = tree_incoh.Draw( "", strsel + " && " + draw + ">{0:.3f}".format(fitran[0]) + " && " + draw + "<{1:.3f}".format(fitran[0], fitran[1])) else: nevt = data.sumEntries("x", "fitran") print "nevt:", nevt pdf_logPt2.setNormRange("fitran") print "PDF norm:", pdf_logPt2.getNorm(RooArgSet(x)) #a = nevt/ipdf.getVal() a = nevt / pdf_logPt2.getNorm(RooArgSet(x)) print "a =", a #gamma-gamma contribution hPtGG = ut.prepare_TH1D("hPtGG", ptbin, ptmin, ptmax) tree_gg.Draw(draw + " >> hPtGG", strsel) #ut.norm_to_data(hPtGG, hPt, rt.kGreen, -5., -2.9) ut.norm_to_num(hPtGG, 131., rt.kGreen + 1) print "Int GG:", hPtGG.Integral() #sum of all contributions hSum = ut.prepare_TH1D("hSum", ptbin, ptmin, ptmax) hSum.SetLineWidth(3) #add ggel to the sum hSum.Add(hPtGG) #add incoherent contribution func_logPt2 = TF1("pdf_logPt2", "[0]*log(10.)*pow(10.,x)*exp(-[1]*pow(10.,x))", -10., 10.) func_logPt2.SetParameters(a, b.getVal()) hInc = ut.prepare_TH1D("hInc", ptbin, ptmin, ptmax) ut.fill_h1_tf(hInc, func_logPt2) hSum.Add(hInc) #add coherent contribution ut.norm_to_data(hPtCoh, hPt, rt.kBlue, -5., -2.2) # norm for coh hSum.Add(hPtCoh) #set to draw as a lines ut.line_h1(hSum, rt.kBlack) #create canvas frame can = ut.box_canvas() ut.set_margin_lbtr(gPad, 0.11, 0.1, 0.01, 0.01) frame = x.frame(rf.Bins(nbins), rf.Title("")) frame.SetTitle("") frame.SetYTitle("J/#psi candidates / ({0:.3f}".format(ptbin) + " (GeV/c)^{2})") frame.GetXaxis().SetTitleOffset(1.2) frame.GetYaxis().SetTitleOffset(1.6) print "Int data:", hPt.Integral() #plot the data if binned == True: dataH.plotOn(frame, rf.Name("data")) else: data.plotOn(frame, rf.Name("data")) pdf_logPt2.plotOn(frame, rf.Range("fitran"), rf.LineColor(rt.kRed), rf.Name("pdf_logPt2")) pdf_logPt2.plotOn(frame, rf.Range("plotran"), rf.LineColor(rt.kRed), rf.Name("pdf_logPt2_full"), rf.LineStyle(rt.kDashed)) frame.Draw() leg = ut.prepare_leg(0.61, 0.77, 0.16, 0.19, 0.03) #ut.add_leg_mass(leg, mmin, mmax) hx = ut.prepare_TH1D("hx", 1, 0, 1) hx.Draw("same") ln = ut.col_lin(rt.kRed, 2) leg.AddEntry(hx, "Data", "p") leg.AddEntry(hSum, "Sum", "l") leg.AddEntry(hPtCoh, "Coherent J/#psi", "l") leg.AddEntry(ln, "Incoherent parametrization", "l") leg.AddEntry(hPtGG, "#gamma#gamma#rightarrow e^{+}e^{-}", "l") #leg.AddEntry(ln, "ln(10)*#it{A}*10^{log_{10}#it{p}_{T}^{2}}exp(-#it{b}10^{log_{10}#it{p}_{T}^{2}})", "l") leg.Draw("same") l0 = ut.cut_line(fitran[0], 0.9, frame) l1 = ut.cut_line(fitran[1], 0.9, frame) #l0.Draw() #l1.Draw() pleg = ut.prepare_leg(0.12, 0.75, 0.14, 0.22, 0.03) pleg.AddEntry(None, "#bf{|#kern[0.3]{#it{y}}| < 1}", "") ut.add_leg_mass(pleg, mmin, mmax) pleg.AddEntry(None, "STAR Preliminary", "") pleg.AddEntry(None, "AuAu@200 GeV", "") pleg.AddEntry(None, "UPC sample", "") pleg.Draw("same") desc = pdesc(frame, 0.14, 0.9, 0.057) desc.set_text_size(0.03) desc.itemD("#chi^{2}/ndf", frame.chiSquare("pdf_logPt2", "data", 2), -1, rt.kRed) desc.itemD("#it{A}", a, -1, rt.kRed) desc.itemR("#it{b}", b, rt.kRed) #desc.draw() #put the sum hSum.Draw("same") frame.Draw("same") #put gamma-gamma and coherent J/psi hPtGG.Draw("same") hPtCoh.Draw("same") #ut.invert_col(rt.gPad) can.SaveAs("01fig.pdf")
(x, eval(x)) for x in ["ymin", "ymax", "ptmax", "binned", "fitran[0]", "fitran[1]"] ] strlog = ut.make_log_string(loglist1, loglist2) ut.log_results(out, strlog + "\n") #unbinned and binned input data nbins, mmax = ut.get_nbins(mbin, mmin, mmax) strsel = "jRecY>{0:.3f} && jRecY<{1:.3f} && jRecPt<{2:.3f}".format( ymin, ymax, ptmax) #unbinned data m.setMin(mmin) m.setMax(mmax) m.setRange("fitran", fitran[0], fitran[1]) dataIN = RooDataSet("data", "data", tree, RooArgSet(m, y, pT)) data = dataIN.reduce(strsel) #binned data hMass = TH1D("hMass", "hMass", nbins, mmin, mmax) tree.Draw("jRecM >> hMass", strsel) dataH = RooDataHist("dataH", "dataH", RooArgList(m), hMass) #make the fit if binned == True: r1 = cb.fitTo(dataH, rf.Range("fitran"), rf.Save()) else: r1 = cb.fitTo(data, rf.Range("fitran"), rf.Save()) #log fit results ut.log_results(out, ut.log_fit_result(r1)) ut.log_results(out, "Alpha and n in 3-digits:") ut.log_results(
mmtt_pt = RooRealVar("xPt", "xPt", 0.0, ptmax) lxysig = RooRealVar("xL", "l(xy) sign.;l(xy) sign.", 0.0, 1000.0) massvars = RooArgSet(tt_mass, mm_mass, mmtt_mass) ptvars = RooArgSet(tt_pt, mm_pt, mmtt_pt) kinvars = RooArgSet(massvars, ptvars) extravars = RooArgSet(lxysig) theData = RooDataSet("theData", "theData", theTree, RooArgSet(kinvars, extravars)) c = TCanvas("canvas", "canvas", 1200, 800) if args.nonprompt: theData = theData.reduce("xL > 3.0") region = "_nprompt_" if args.prompt: theData = theData.reduce("xL < 1.5") region = "_promt_" if args.ptcuts is not None: theData = theData.reduce("trigp_pT > " + str(args.ptcuts)) theData = theData.reduce("trign_pT > " + str(args.ptcuts)) cuts += "P_t_" + str(args.ptcuts) + "_" #### #### Plotting variables #### TrakTrak Data if args.noplot: print("TrakTrak data plotting . . .")
thevars.add(l2_mvaId) thevars.add(cos2D) thevars.add(l_xy_sig) thevars.add(svprob) fulldata = RooDataSet('fulldata', 'fulldata', tree, RooArgSet(thevars)) theBMassfunc = RooFormulaVar("theBMass", "theBMass", "@0", RooArgList(bMass)) theBMass = fulldata.addColumn(theBMassfunc) theBMass.setRange(lowRange, highRange) thevars.add(theBMass) cut = '' print cut data = fulldata.reduce(thevars, cut) ## mass model mean = RooRealVar("mass", "mean", B0Mass_, 5, 5.5, "GeV") sigma = RooRealVar("sigma", "sigma", 9.0e-2, 1.0e-4, 1.0, "GeV") alpha = RooRealVar("alpha", "alpha", 1.0, 0.0, 1.0e+4) n = RooRealVar("n", "n", 5, 1, 100) signalCB = RooCBShape("signalCB", "signal cb", theBMass, mean, sigma, alpha, n) sigma2 = RooRealVar("sigma2", "sigma2", 9.0e-3, 1.0e-5, 1.0, "GeV") alpha2 = RooRealVar("alpha2", "alpha2", 1.0, 0.0, 1.0e+4) n2 = RooRealVar("n2", "n2", 5, 1, 100) signalCB2 = RooCBShape("signalCB2", "signal cb 2", theBMass, mean, sigma2, alpha2, n2) f1 = RooRealVar("f1", "f1", 0.5, 0., 1.)
RooArgSet(masspLbTk, LbTkPt)) loadDatasetnLbTk = RooDataSet('loadData16nLbTk', 'loadData16', innLbTk, RooArgSet(massnLbTk, LbTkPt)) #tktkMassCut='tktkMass>1.100&&tktkMass<1.120' tktkMassCut = 'tktkMass>1.105&&tktkMass<1.125' #tktkMassCut='tktkMass>1.110&&tktkMass<1.120' for ptRange in ptRegion: rName = ptRange[2] pLbL0Num = 0 nLbL0Num = 0 pLbTkNum = 0 nLbTkNum = 0 if checkpLbL0: binData = loadDatasetpLbL0.reduce( tktkMassCut + '&&lbl0Pt>{0}.&&lbl0Pt<{1}.'.format(ptRange[0], ptRange[1])) pLbL0Num = binData.sumEntries() if checknLbL0: binData = loadDatasetnLbL0.reduce( tktkMassCut + '&&lbl0Pt>{0}.&&lbl0Pt<{1}.'.format(ptRange[0], ptRange[1])) nLbL0Num = binData.sumEntries() if checkpLbTk: binData = loadDatasetpLbTk.reduce( 'lbtkPt>{0}.&&lbtkPt<{1}.'.format(ptRange[0], ptRange[1])) pLbTkNum = binData.sumEntries() if checknLbTk: binData = loadDatasetnLbTk.reduce( 'lbtkPt>{0}.&&lbtkPt<{1}.'.format(ptRange[0], ptRange[1])) nLbTkNum = binData.sumEntries()
dstree.Project('sPlot_B0_hist','xM','nSig_sw'); # In[ ]: sPlot_B0_hist.Draw('e0'); cD.SaveAs('sPlot_B0_hist.eps') # In[ ]: sys.exit() xdataPrompt = (alldata.reduce('xM<4.8')).reduce('xM>4.0').reduce("xL<2.0") # In[ ]: massmin = 1.020-0.03 massmax = 1.020+0.03 phimean = 1.020 xdataPrompt.numEntries() # In[ ]: a0 = RooRealVar("a0","a0",0.001,-1.,1.)
bsMass=RooRealVar('bsMass', 'bsMass', 4., 8., "GeV") bdMass=RooRealVar('bdMass', 'bdMass', 3.5, 8., "GeV") bdbarMass=RooRealVar('bdbarMass', 'bdbarMass', 3.5, 8., "GeV") phiMass=RooRealVar('phiMass', 'phiMass', 0.5, 3., "GeV") kstarMass=RooRealVar('kstarMass', 'kstarMass', 0.5, 3., "GeV") kstarbarMass=RooRealVar('kstarbarMass', 'kstarbarMass', 0.5, 3., "GeV") tktkPt=RooRealVar('tktkPt', 'tktkPt', 0., 160., "GeV/c") fitMC=RooDataSet() fitdata=RooDataSet('2016Data', 'RunB', ntuple, RooArgSet(lbtkMass,bsMass,bdMass,bdbarMass,phiMass,kstarMass,kstarbarMass,tktkPt)) subdataset=fitdata.reduce( RooFit.Cut("tktkPt>20.&&lbtkMass>5.45&&lbtkMass<5.8") ) canv=TCanvas('c1', 'c1', 1600,1000) canv.SetFillColor(4000) canv.SetFillStyle(4000) lbtkmassFrame=lbtkMass.frame(RooFit.Range(5.,6.)) bsmassFrame=bsMass.frame(RooFit.Range(5.,6.)) bdmassFrame=bdMass.frame(RooFit.Range(5.,6.)) bdbarmassFrame=bdbarMass.frame(RooFit.Range(5.,6.)) fitdata.plotOn(lbtkmassFrame, RooFit.Cut("tktkPt>20.")) subdataset.plotOn(bsmassFrame) subdataset.plotOn(bdmassFrame) subdataset.plotOn(bdbarmassFrame) lbtkmassFrame.Draw() canv.SaveAs('h_checkPlot_lbtkMass_tktkPtB20.eps')
massAp = (massApmax - massApmin)/float(nApMass - 1) * i + massApmin massApArr.append(massAp) massVarr = [] massApres = 0.01 for j in range(0,nVMass): #massV = (massVmax - massVmin)/float(nVMass - 1) * j + massVmin massV = 0.6*massAp massVarr.append(massV) massPiarr = [] massVres = massresfile.Get("mres_l1_p0").GetFunction("pol1").Eval(massV) #zcut = 10. breakz = tailsfile.Get("breakz").GetFunction("pol3").Eval(massV) length = tailsfile.Get("length").GetFunction("pol3").Eval(massV) frame = uncVZ.frame() dataInRange = dataset.reduce(obs,"abs({0}-{1})<{2}/2*({3}+{4}*uncVZ)".format("uncM",massV,masscut_nsigma,massVres,0)) binnedData = dataInRange.binnedClone() binnedData.plotOn(frame) mean = binnedData.mean(uncVZ) sigma = binnedData.sigma(uncVZ) uncVZ.setRange("fitRange",mean-2*sigma,mean+2*sigma) gauss_params.setRealValue("mean",mean) gauss_params.setRealValue("sigma",sigma) gauss_pdf.fitTo(binnedData,RooFit.Range("fitRange"),RooFit.PrintLevel(-1)) mean = gauss_params.getRealValue("mean") sigma = gauss_params.getRealValue("sigma") gaussexp_params.setRealValue("gauss_mean",mean) gaussexp_params.setRealValue("gauss_sigma",sigma) gaussexp_params.setRealValue("exp_breakpoint",breakz) gaussexp_params.setRealValue("exp_length",length) w.var("gauss_mean").setConstant(True)
masskk.setBins(int(200)) massmumu = RooRealVar("mumuM", "mumuM", 2.5, 3.5) # In[9]: alldata = RooDataSet("alldata", "alldata", xTuple, RooArgSet(masskk, mass, lxy, hlt, massmumu)) #,cutFormula) # In[10]: alldata.numEntries() # In[ ]: xdataPrompt = (alldata.reduce('xM>5.15')).reduce('xM<5.55').reduce( "xL>=3.0").reduce("kkM<1.035").reduce("kkM>1.005") xdataPrompt.numEntries() B_c = RooRealVar("B_c", "B_c ", 0.3, -20, 100) B_b = RooRealVar("B_b", "B_b ", 0.3, -20, 100) S1 = RooRealVar("S1", "Signal", 30000, 1, 900000) S2 = RooRealVar("S2", "Signal", 30000, 1, 900000) B = RooRealVar("B", "B", 50000, 1, 900000000) mean = RooRealVar("mean", "mean of gaussian", 5.38, 5.31, 5.41) sigma1 = RooRealVar("sigma1", "width of gaussian1", 0.002, 0.0005, 0.05) sigma2 = RooRealVar("sigma2", "width of gaussian2", 0.004, 0.004, 0.01) pdfS1 = RooGaussian("pdfS1", "gaus", mass, mean, sigma1)
def buildDataAndCategories(ws, options, args): #Get the input data inputData = TChain(options.treeName, 'The input data') for arg in args: print 'Adding data from: ', arg inputData.Add(arg) foldname = '' phirange = [0, 90] if not options.folded: foldname = '' phirange = [-180, 180] #variables necessary for j/psi mass,lifetime,polarization fit jPsiMass = RooRealVar('JpsiMass', 'M [GeV]', 2.7, 3.5) jPsiRap = RooRealVar('JpsiRap', '#nu', -2.3, 2.3) jPsiPt = RooRealVar("JpsiPt", "pT [GeV]", 0, 40) jPsicTau = RooRealVar('Jpsict', 'l_{J/#psi} [mm]', -1, 2.5) jPsicTauError = RooRealVar('JpsictErr', 'Error on l_{J/#psi} [mm]', 0, 2) jPsiVprob = RooRealVar('JpsiVprob', '', .01, 1) jPsiHXcosth = None jPsiHXphi = None jPsicTau.setBins(10000, "cache") if options.fitFrame is not None: jPsiHXcosth = RooRealVar('costh_' + options.fitFrame + foldname, 'cos(#theta)_{' + options.fitFrame + '}', -1, 1) jPsiHXphi = RooRealVar('phi_' + options.fitFrame + foldname, '#phi_{' + options.fitFrame + '}', phirange[0], phirange[1]) else: jPsiHXcosth = RooRealVar('costh_CS' + foldname, 'cos(#theta)_{CS}', -1, 1) jPsiHXphi = RooRealVar('phi_CS' + foldname, '#phi_{CS}', phirange[0], phirange[1]) #vars needed for on the fly calc of polarization variables jPsimuPosPx = RooRealVar('muPosPx', '+ Muon P_{x} [GeV]', 0) jPsimuPosPy = RooRealVar('muPosPy', '+ Muon P_{y} [GeV]', 0) jPsimuPosPz = RooRealVar('muPosPz', '+ Muon P_{z} [GeV]', 0) jPsimuNegPx = RooRealVar('muNegPx', '- Muon P_{x} [GeV]', 0) jPsimuNegPy = RooRealVar('muNegPy', '- Muon P_{y} [GeV]', 0) jPsimuNegPz = RooRealVar('muNegPz', '- Muon P_{z} [GeV]', 0) #create RooArgSet for eventual dataset creation dataVars = RooArgSet(jPsiMass, jPsiRap, jPsiPt, jPsicTau, jPsicTauError, jPsimuPosPx, jPsimuPosPy, jPsimuPosPz) #add trigger requirement if specified if options.triggerName: trigger = RooRealVar(options.triggerName, 'Passes Trigger', 0.5, 1.5) dataVars.add(trigger) dataVars.add(jPsiVprob) dataVars.add(jPsimuNegPx) dataVars.add(jPsimuNegPy) dataVars.add(jPsimuNegPz) dataVars.add(jPsiHXcosth) dataVars.add(jPsiHXphi) redVars = RooArgSet(jPsiMass, jPsiRap, jPsiPt, jPsicTau, jPsicTauError) redVars.add(jPsiHXcosth) redVars.add(jPsiHXphi) fitVars = redVars.Clone() ### HERE IS WHERE THE BIT FOR CALCULATING POLARIZATION VARS GOES ctauStates = RooCategory('ctauRegion', 'Cut Region in lifetime') ctauStates.defineType('prompt', 0) ctauStates.defineType('nonPrompt', 1) massStates = RooCategory('massRegion', 'Cut Region in mass') massStates.defineType('signal', 1) massStates.defineType('separation', 0) massStates.defineType('leftMassSideBand', -2) massStates.defineType('rightMassSideBand', -1) states = RooCategory('mlRegion', 'Cut Region in mass') states.defineType('nonPromptSignal', 2) states.defineType('promptSignal', 1) states.defineType('separation', 0) states.defineType('leftMassSideBand', -2) states.defineType('rightMassSideBand', -1) #define corresponding ranges in roorealvars #mass is a little tricky since the sidebands change definitions in each rap bin #define the names here and change as we do the fits #jPsiMass.setRange('NormalizationRangeFormlfit_promptSignal',2.7,3.5) #jPsiMass.setRange('NormalizationRangeFormlfit_nonPromptSignal',2.7,3.5) #jPsiMass.setRange('NormalizationRangeFormlfit_leftMassSideBand',2.7,3.1) #jPsiMass.setRange('NormalizationRangeFormlfit_rightMassSideBand',3.1,3.5) #want the prompt fit only done in prompt region #non-prompt only in non-prompt region #background over entire cTau range #jPsicTau.setRange('NormalizationRangeFormlfit_promptSignal',-1,.1) #jPsicTau.setRange('NormalizationRangeFormlfit_nonPromptSignal',.1,2.5) #jPsicTau.setRange('NormalizationRangeFormlfit_leftMassSideBand',-1,2.5) #jPsicTau.setRange('NormalizationRangeFormlfit_rightMassSideBand',-1,2.5) #redVars.add(ctauStates) #redVars.add(massStates) #redVars.add(states) fitVars.add(ctauStates) fitVars.add(massStates) fitVars.add(states) fullData = RooDataSet('fullData', 'The Full Data From the Input ROOT Trees', dataVars, ROOT.RooFit.Import(inputData)) for rap_bin in range(1, len(jpsi.pTRange)): yMin = jpsi.rapForPTRange[rap_bin - 1][0] yMax = jpsi.rapForPTRange[rap_bin - 1][-1] for pt_bin in range(len(jpsi.pTRange[rap_bin])): ptMin = jpsi.pTRange[rap_bin][pt_bin][0] ptMax = jpsi.pTRange[rap_bin][pt_bin][-1] sigMaxMass = jpsi.polMassJpsi[ rap_bin] + jpsi.nSigMass * jpsi.sigmaMassJpsi[rap_bin] sigMinMass = jpsi.polMassJpsi[ rap_bin] - jpsi.nSigMass * jpsi.sigmaMassJpsi[rap_bin] sbHighMass = jpsi.polMassJpsi[ rap_bin] + jpsi.nSigBkgHigh * jpsi.sigmaMassJpsi[rap_bin] sbLowMass = jpsi.polMassJpsi[ rap_bin] - jpsi.nSigBkgLow * jpsi.sigmaMassJpsi[rap_bin] ctauNonPrompt = .1 massFun = RooFormulaVar( 'massRegion', 'Function that returns the mass state.', '(' + jPsiMass.GetName() + ' < ' + str(sigMaxMass) + ' && ' + jPsiMass.GetName() + ' > ' + str(sigMinMass) + ') - (' + jPsiMass.GetName() + ' > ' + str(sbHighMass) + ')' + '-2*(' + jPsiMass.GetName() + ' < ' + str(sbLowMass) + ')', RooArgList(jPsiMass, jPsicTau)) ctauFun = RooFormulaVar( 'ctauRegion', 'Function that returns the ctau state.', '(' + jPsicTau.GetName() + ' > ' + str(ctauNonPrompt) + ')', RooArgList(jPsiMass, jPsicTau)) mlFun = RooFormulaVar( 'mlRegion', 'Function that returns the mass and lifetime state.', '(' + jPsiMass.GetName() + ' < ' + str(sigMaxMass) + ' && ' + jPsiMass.GetName() + ' > ' + str(sigMinMass) + ') + (' + jPsiMass.GetName() + ' < ' + str(sigMaxMass) + ' && ' + jPsiMass.GetName() + ' > ' + str(sigMinMass) + ' && ' + jPsicTau.GetName() + ' > ' + str(ctauNonPrompt) + ') - (' + jPsiMass.GetName() + ' > ' + str(sbHighMass) + ')' + '-2*(' + jPsiMass.GetName() + ' < ' + str(sbLowMass) + ')', RooArgList(jPsiMass, jPsicTau)) cutStringPt = '(' + jPsiPt.GetName() + ' > ' + str( ptMin) + ' && ' + jPsiPt.GetName() + ' < ' + str(ptMax) + ')' cutStringY = '( abs(' + jPsiRap.GetName() + ') > ' + str( yMin) + ' && abs(' + jPsiRap.GetName() + ') < ' + str( yMax) + ')' #cutStringM1 = '('+jPsiMass.GetName()+' < '+str(sigMinMass)+' && '+jPsiMass.GetName()+' > '+str(sbLowMass)+')' #cutStringM2 = '('+jPsiMass.GetName()+' < '+str(sbHighMass)+' && '+jPsiMass.GetName()+' > '+str(sigMaxMass)+')' #cutStringMT = '!('+cutStringM1+' || '+cutStringM2+')' cutString = cutStringPt + ' && ' + cutStringY #+' && '+cutStringMT print cutString #get the reduced dataset we'll do the fit on binData = fullData.reduce( ROOT.RooFit.SelectVars(redVars), ROOT.RooFit.Cut(cutString), ROOT.RooFit.Name('data_rap' + str(rap_bin) + '_pt' + str(pt_bin + 1)), ROOT.RooFit.Title('Data For Fitting')) binDataWithCategory = RooDataSet( 'data_rap' + str(rap_bin) + '_pt' + str(pt_bin + 1), 'Data For Fitting', fitVars) #categorize binData.addColumn(ctauStates) binData.addColumn(massStates) binData.addColumn(states) for ev in range(binData.numEntries()): args = binData.get(ev) jPsiMass.setVal(args.find(jPsiMass.GetName()).getVal()) jPsiRap.setVal(args.find(jPsiRap.GetName()).getVal()) jPsiPt.setVal(args.find(jPsiPt.GetName()).getVal()) jPsicTau.setVal(args.find(jPsicTau.GetName()).getVal()) jPsicTauError.setVal( args.find(jPsicTauError.GetName()).getVal()) jPsiHXcosth.setVal(args.find(jPsiHXcosth.GetName()).getVal()) jPsiHXphi.setVal(args.find(jPsiHXphi.GetName()).getVal()) massStates.setIndex(int(massFun.getVal())) ctauStates.setIndex(int(ctauFun.getVal())) states.setIndex(int(mlFun.getVal())) binDataWithCategory.add(fitVars) getattr(ws, 'import')(binDataWithCategory)
def prepare_truth_models(ws, cat, mass, channel, turnon, truth): if channel in study_inputs: bkg_data = RooDataSet("bkgdata_%s" % (channel), "M_{ll#gamma} with Errors", ws.set("observables_weight"), "weight") for k, file in enumerate(study_inputs[channel]): f_in = TFile.Open(file, "READ") gDirectory.cd(pwd) n_events = f_in.Get("eventCount").GetBinContent(1) tree = f_in.Get("selected_zg").CloneTree() tree.SetName("tree_%s_%i" % (channel, k)) f_in.Close() d_in = RooDataSet("temp", "M_{ll#gamma} with Errors", tree, ws.set("observables")) norm = RooConstVar("norm", "norm", n_events) weight = RooFormulaVar( "weight", "weight", "1.3*@0*@1/@2", #1.3 gives 19.6/fb RooArgList(ws.var("puWeight"), ws.var("procWeight"), norm)) d_in.addColumn(weight) d_in_weight = RooDataSet("temp_weight", "M_{ll#gamma} with Errors", d_in, ws.set("observables_weight"), '', 'weight') bkg_data.append(d_in_weight) # split off data for each category, create the # toy dataset truth models data = bkg_data.reduce("Mz + Mzg > 185 && r94cat == %i" % cat) getattr(ws, 'import')(data, RooFit.Rename('bkgdata_%s_%i' % (channel, cat))) nevts = data.sumEntries('Mzg > %f && Mzg < %f' % (mass - 1.5, mass + 1.5)) #for sigm turn on we want erf truth if turnon == 'sigm' and truth == 'exp': #make RooDecay 'truth' model with erf turn on ws.factory( 'RooGaussModel::MzgResoShape_exp_erf_%s_cat%i(Mzg,'\ 'bias_exp_erf_%s_cat%i[120,90,150],sigma_exp_erf_%s_cat%i[1,0.01,10])'%( channel,cat, channel,cat, channel,cat) ) ws.factory( 'RooDecay::MzgTruthModelBase_exp_erf_%s_cat%i(Mzg,'\ 'tau_erf_%s_cat%i[25,0,50],MzgResoShape_exp_erf_%s_cat%i,' 'RooDecay::SingleSided)'%(channel,cat, channel,cat, channel,cat) ) ws.factory( 'RooExtendPdf::MzgTruthModel_exp_erf_%s_cat%i('\ 'MzgTruthModelBase_exp_erf_%s_cat%i,'\ 'norm_truth_exp_%s_cat%i[%f,%f,%f],"ROI")'%(channel,cat, channel,cat, channel,cat, nevts, 0.25*nevts,1.75*nevts) ) ws.pdf('MzgTruthModel_exp_erf_%s_cat%i' % (channel, cat)).fitTo( ws.data('bkgdata_%s_%i' % (channel, cat)), RooFit.Minimizer('Minuit2', 'scan'), RooFit.SumW2Error(False)) ws.pdf('MzgTruthModel_exp_erf_%s_cat%i' % (channel, cat)).fitTo( ws.data('bkgdata_%s_%i' % (channel, cat)), RooFit.Minimizer('Minuit', 'simplex'), RooFit.SumW2Error(False)) ws.pdf('MzgTruthModel_exp_erf_%s_cat%i' % (channel, cat)).fitTo( ws.data('bkgdata_%s_%i' % (channel, cat)), RooFit.SumW2Error(True)) if turnon == 'sigm' and truth == 'pow': #make power-law truth model with erf turn on ws.factory('EXPR::MzgTruthModelShape_pow_erf_%s_cat%i('\ '"1e-20 + (@0 > @1)*((@0)^(-@2))",'\ '{Mzg,step_pow_erf_%s_cat%i[105,100,130],'\ 'pow_%s_cat%i[2,0,10]})'\ %(channel,cat, channel,cat, channel,cat)) ws.factory( 'RooGaussModel::MzgResoShape_pow_erf_%s_cat%i(Mzg,'\ 'bias_pow_erf_%s_cat%i[0],sigma_pow_erf_%s_cat%i[1,0.01,10])'%( channel,cat, channel,cat, channel,cat) ) ws.factory('FCONV::MzgTruthModelBase_pow_erf_%s_cat%i(Mzg,'\ 'MzgTruthModelShape_pow_erf_%s_cat%i,'\ 'MzgResoShape_pow_erf_%s_cat%i)'%(channel,cat, channel,cat, channel,cat)) ws.factory( 'RooExtendPdf::MzgTruthModel_pow_erf_%s_cat%i('\ 'MzgTruthModelBase_pow_erf_%s_cat%i,'\ 'norm_truth_pow_erf_%s_cat%i[%f,%f,%f],"ROI")'%(channel,cat, channel,cat, channel,cat, nevts, 0.25*nevts,1.75*nevts) ) ws.pdf('MzgTruthModel_pow_erf_%s_cat%i' % (channel, cat)).fitTo( ws.data('bkgdata_%s_%i' % (channel, cat)), RooFit.Minimizer('Minuit2', 'scan'), RooFit.SumW2Error(False)) ws.pdf('MzgTruthModel_pow_erf_%s_cat%i' % (channel, cat)).fitTo( ws.data('bkgdata_%s_%i' % (channel, cat)), RooFit.Minimizer('Minuit', 'simplex'), RooFit.SumW2Error(False)) ws.pdf('MzgTruthModel_pow_erf_%s_cat%i' % (channel, cat)).fitTo( ws.data('bkgdata_%s_%i' % (channel, cat)), RooFit.SumW2Error(True)) #for erf fitting turn on we want sigmoid truth if turnon == 'erf' and truth == 'exp': #build exponential convoluted with sigmoid turn-on ws.factory('RooStepExponential::MzgTruthModelShape_exp_sigm_%s_cat%i'\ '(Mzg,tau_sigm_%s_cat%i[-0.05,-10,0],'\ 'step_exp_sigm_%s_cat%i[110,100,130])'%(channel,cat, channel,cat, channel,cat)) ws.factory('RooLogistics::MzgResoShape_exp_sigm_%s_cat%i(%s)' % (channel, cat, ','.join([ 'Mzg', 'bias_exp_sigm_%s_cat%i[0]' % (channel, cat), 'sigma_exp_sigm_%s_cat%i[5,0.01,20]' % (channel, cat) ]))) ws.factory('FCONV::MzgTruthModelBase_exp_sigm_%s_cat%i(Mzg,'\ 'MzgTruthModelShape_exp_sigm_%s_cat%i,'\ 'MzgResoShape_exp_sigm_%s_cat%i)'%(channel,cat, channel,cat, channel,cat)) ws.factory( 'RooExtendPdf::MzgTruthModel_exp_sigm_%s_cat%i('\ 'MzgTruthModelBase_exp_sigm_%s_cat%i,'\ 'norm_truth_exp_sigm_%s_cat%i[%f,%f,%f],"ROI")'%(channel,cat, channel,cat, channel,cat, nevts, 0.25*nevts,1.75*nevts) ) ws.pdf('MzgTruthModel_exp_sigm_%s_cat%i' % (channel, cat)).fitTo( ws.data('bkgdata_%s_%i' % (channel, cat)), RooFit.Minimizer('Minuit2', 'scan'), RooFit.SumW2Error(False)) ws.pdf('MzgTruthModel_exp_sigm_%s_cat%i' % (channel, cat)).fitTo( ws.data('bkgdata_%s_%i' % (channel, cat)), RooFit.Minimizer('Minuit', 'simplex'), RooFit.SumW2Error(False)) ws.pdf('MzgTruthModel_exp_sigm_%s_cat%i' % (channel, cat)).fitTo( ws.data('bkgdata_%s_%i' % (channel, cat)), RooFit.SumW2Error(True)) if turnon == 'erf' and truth == 'pow': #build power-law convoluted with sigmoid turn-on ws.factory('EXPR::MzgTruthModelShape_pow_sigm_%s_cat%i('\ '"1e-20 + (@0 > @1)*((@0)^(-@2))",'\ '{Mzg,step_pow_sigm_%s_cat%i[105,100,130],'\ 'pow_sigm_%s_cat%i[2,0,10]})'\ %(channel,cat, channel,cat, channel,cat)) ws.factory('RooLogistics::MzgResoShape_pow_sigm_%s_cat%i(%s)' % (channel, cat, ','.join([ 'Mzg', 'bias_pow_sigm_%s_cat%i[0]' % (channel, cat), 'sigma_pow_sigm_%s_cat%i[5,0.01,20]' % (channel, cat) ]))) ws.factory('FCONV::MzgTruthModelBase_pow_sigm_%s_cat%i(Mzg,'\ 'MzgTruthModelShape_pow_sigm_%s_cat%i,'\ 'MzgResoShape_pow_sigm_%s_cat%i)'%(channel,cat, channel,cat, channel,cat)) ws.factory( 'RooExtendPdf::MzgTruthModel_pow_sigm_%s_cat%i('\ 'MzgTruthModelBase_pow_sigm_%s_cat%i,'\ 'norm_truth_pow_sigm_%s_cat%i[%f,%f,%f],"ROI")'%(channel,cat, channel,cat, channel,cat, nevts, 0.25*nevts,1.75*nevts) ) ws.pdf('MzgTruthModel_pow_sigm_%s_cat%i' % (channel, cat)).fitTo( ws.data('bkgdata_%s_%i' % (channel, cat)), RooFit.Minimizer('Minuit2', 'scan'), RooFit.SumW2Error(False)) ws.pdf('MzgTruthModel_pow_sigm_%s_cat%i' % (channel, cat)).fitTo( ws.data('bkgdata_%s_%i' % (channel, cat)), RooFit.Minimizer('Minuit', 'simplex'), RooFit.SumW2Error(False)) ws.pdf('MzgTruthModel_pow_sigm_%s_cat%i' % (channel, cat)).fitTo( ws.data('bkgdata_%s_%i' % (channel, cat)), RooFit.SumW2Error(True))
alldata = RooDataSet("alldata", "alldata", xTuple, RooArgSet(masskk, mass, lxy, hlt, massmumu)) #,cutFormula) datasetfile = TFile("xMassDataset.root", "RECREATE") datasetfile.cd() alldata.Write() # In[10]: alldata.numEntries() # In[ ]: #xb->setRange("alt","x_coarse_bin1,x_coarse_bin3,x_coarse_bin5,x_coarse_bin7,x_coarse_bin9") ; b0dataNonPrompt = (( alldata.reduce('xHlt!=8')).reduce('xM>5.2')).reduce("xL>3.0") # In[ ]: b0dataNonPromptMass = b0dataNonPrompt.reduce(SelectVars(RooArgSet(mass))) b0dataNonPrompt.numEntries() # In[ ]: c = TCanvas("canvas", "canvas", 1200, 800) mass.setRange("fitRange", massmin, massmax) mass.setBins(200) massFrame = mass.frame(Range(massmin, massmax)) b0dataNonPrompt.plotOn(massFrame) massFrame.Draw() c.SaveAs("testmass.png")
loadDatasetlB=RooDataSet('loadData16n','loadData16',inn16,RooArgSet(massLb,massTkTk,space.var('lbl0Pt'))).reduce(ptCut) totNum=inN16.GetEntries() space.factory('numLb[{0},-100.,{1}]'.format(50,totNum)) space.factory('numlB[{0},-100.,{1}]'.format(50,totNum)) #tktkMassCut='tktkMass>1.100&&tktkMass<1.120' tktkMassCut='tktkMass>1.105&&tktkMass<1.125' #tktkMassCut='tktkMass>1.110&&tktkMass<1.120' # fit 2016 data in short range Lb mass window LbL0 {{{ if veryShortRangeFitLb: massLb.setRange('sigShortRange',5.4,5.9) massLb.setBins(50) #binData=loadDatasetLb.binnedClone('shortBinLb') binData=loadDatasetLb.reduce(tktkMassCut) label='Run2016Data_pLbL0' fitLabel='lbl0Dist_lbl0MC' space.factory('x0[-5.498]') space.factory('Addition::X({{ {x},x0 }})'.format(x='lbl0Mass')) space.factory('Polynomial::pPDF_%s(X,{c1_%s[0.01,-2.,0.2],c2_%s[0.01,-3.,1.0]})' % (label,label,label) ) #space.factory('Polynomial::pPDF_%s(lbl0Mass,{c1_%s[0.01,-5.,5.]})' % (label,label) ) # set resolution issue: Convolute a gaussian. space.factory('numCombBkg_{0}[{1},0.,{2}]'.format(label, totNum,totNum)) myPDF=RooAddPdf('totPdf_{0}'.format(label),'totPdf_{0}'.format(label), RooArgList( space.pdf('pPDF_{0}'.format(label)), space.pdf('gPDF_lbl0Dist_lbl0MC') ), RooArgList( space.var('numCombBkg_{0}'.format(label)), space.var('numLb') ),
figDir.cd() myFrame.Write(fitLabel) canv.SaveAs(outFig) fitDir.cd() fitRes.Write(fitLabel) # fit lbtkMass in Lb MC end }}} # fit lbtkMass in antiLb MC {{{ if fitToLbMass_AntiLbTkMC: fitLabel='lbtkDist_antilbtkMC' mass=space.var('lbtkMass') inN=inFF.Get('pLbTk/AntiLbTk') #dataset=RooDataSet('dataset','dataset',inN,RooArgSet(mass,tk1Pt,tk2Pt)).reduce('tk1Pt>3.&&tk2Pt>2.') dataset=RooDataSet('dataset','dataset',inN,RooArgSet(mass)) fitBkg=dataset.reduce(RooFit.Name('fitData_{0}'.format(fitLabel))) #getattr(space,'import')(fitBkg) # create target PDF. #space.factory('KeysPdf::kPDF_{0}(lbtkMass,fitData_{0},NoMirror,2.0)'.format(fitLabel)) #myPDF=space.pdf('kPDF_{0}'.format(fitLabel)) keyPDF=RooKeysPdf('kPDF_{0}'.format(fitLabel),'kPDF_{0}'.format(fitLabel),mass,fitBkg,RooKeysPdf.NoMirror,2.0) getattr(space,'import')(keyPDF) myPDF=keyPDF myFrame=mass.frame(RooFit.Title(fitLabel),RooFit.Title(fitLabel)) if setAxis: myFrame=mass.frame(xaxisMin,xaxisMax) myFrame.GetXaxis().SetTitle('J/#psi p K^{-} Mass(GeV)') dataset.plotOn(myFrame)
simulComponents = [] # find systematic of Lb {{{ if sysFitLb: label = 'LbSysFit' numSig = spaceExt.var('numLb') numBkg = spaceExt.var('numCombBkg_ShortRangeLbFit') varName = 'lbtkMass' figDir.cd() var = space.var(varName) model = spaceExt.pdf('totPdf_LbModel') #dataset=model.generate(RooArgSet(space.var('lbtkMass')),10000) dataset = loadDatasetLb.reduce(ptCut) nll = model.createNLL(dataset) fitres = model.fitTo(dataset, RooFit.Save(True), RooFit.Minos(useMinos)) plot = var.frame(RooFit.Title('toyMC check fit')) dataset.plotOn(plot) model.plotOn( plot, RooFit.Normalization(dataset.sumEntries(), RooAbsReal.NumEvent)) SaveResult(origPlot=plot, origVar=var, data={'content': dataset}, totPDF={'content': model}, fitres=fitres, label=label + 'resFitCheck_data',
def pdf_logPt2_incoh(): #PDF fit to log_10(pT^2) #tree_in = tree_incoh tree_in = tree #ptbin = 0.04 ptbin = 0.12 ptmin = -5. ptmax = 1. mmin = 2.8 mmax = 3.2 #fitran = [-5., 1.] fitran = [-0.9, 0.1] binned = False #gamma-gamma 131 evt for pT<0.18 #output log file out = open("out.txt", "w") ut.log_results( out, "in " + infile + " in_coh " + infile_coh + " in_gg " + infile_gg) loglist = [(x, eval(x)) for x in ["ptbin", "ptmin", "ptmax", "mmin", "mmax", "fitran", "binned"]] strlog = ut.make_log_string(loglist) ut.log_results(out, strlog + "\n") #input data pT = RooRealVar("jRecPt", "pT", 0, 10) m = RooRealVar("jRecM", "mass", 0, 10) dataIN = RooDataSet("data", "data", tree_in, RooArgSet(pT, m)) strsel = "jRecM>{0:.3f} && jRecM<{1:.3f}".format(mmin, mmax) data = dataIN.reduce(strsel) #x is RooRealVar for log(Pt2) draw = "TMath::Log10(jRecPt*jRecPt)" draw_func = RooFormulaVar("x", "log_{10}( #it{p}_{T}^{2} ) (GeV^{2})", draw, RooArgList(pT)) x = data.addColumn(draw_func) x.setRange("fitran", fitran[0], fitran[1]) #binned data nbins, ptmax = ut.get_nbins(ptbin, ptmin, ptmax) hPt = TH1D("hPt", "hPt", nbins, ptmin, ptmax) tree_in.Draw(draw + " >> hPt", strsel) dataH = RooDataHist("dataH", "dataH", RooArgList(x), hPt) #range for plot x.setMin(ptmin) x.setMax(ptmax) x.setRange("plotran", ptmin, ptmax) #create the pdf b = RooRealVar("b", "b", 5., 0., 10.) pdf_func = "log(10.)*pow(10.,x)*exp(-b*pow(10.,x))" pdf_logPt2 = RooGenericPdf("pdf_logPt2", pdf_func, RooArgList(x, b)) #make the fit if binned == True: r1 = pdf_logPt2.fitTo(dataH, rf.Range("fitran"), rf.Save()) else: r1 = pdf_logPt2.fitTo(data, rf.Range("fitran"), rf.Save()) ut.log_results(out, ut.log_fit_result(r1)) #calculate norm to number of events xset = RooArgSet(x) ipdf = pdf_logPt2.createIntegral(xset, rf.NormSet(xset), rf.Range("fitran")) print "PDF integral:", ipdf.getVal() if binned == True: nevt = tree_incoh.Draw( "", strsel + " && " + draw + ">{0:.3f}".format(fitran[0]) + " && " + draw + "<{1:.3f}".format(fitran[0], fitran[1])) else: nevt = data.sumEntries("x", "fitran") print "nevt:", nevt pdf_logPt2.setNormRange("fitran") print "PDF norm:", pdf_logPt2.getNorm(RooArgSet(x)) #a = nevt/ipdf.getVal() a = nevt / pdf_logPt2.getNorm(RooArgSet(x)) ut.log_results(out, "log_10(pT^2) parametrization:") ut.log_results(out, "A = {0:.2f}".format(a)) ut.log_results(out, ut.log_fit_parameters(r1, 0, 2)) print "a =", a #Coherent contribution hPtCoh = ut.prepare_TH1D("hPtCoh", ptbin, ptmin, ptmax) hPtCoh.Sumw2() #tree_coh.Draw(draw + " >> hPtCoh", strsel) tree_coh.Draw("TMath::Log10(jGenPt*jGenPt) >> hPtCoh", strsel) ut.norm_to_data(hPtCoh, hPt, rt.kBlue, -5., -2.2) # norm for coh #ut.norm_to_data(hPtCoh, hPt, rt.kBlue, -5, -2.1) #ut.norm_to_num(hPtCoh, 405, rt.kBlue) print "Coherent integral:", hPtCoh.Integral() #TMath::Log10(jRecPt*jRecPt) #Sartre generated coherent shape sartre = TFile.Open( "/home/jaroslav/sim/sartre_tx/sartre_AuAu_200GeV_Jpsi_coh_2p7Mevt.root" ) sartre_tree = sartre.Get("sartre_tree") hSartre = ut.prepare_TH1D("hSartre", ptbin, ptmin, ptmax) sartre_tree.Draw("TMath::Log10(pT*pT) >> hSartre", "rapidity>-1 && rapidity<1") ut.norm_to_data(hSartre, hPt, rt.kViolet, -5, -2) # norm for Sartre #gamma-gamma contribution hPtGG = ut.prepare_TH1D("hPtGG", ptbin, ptmin, ptmax) tree_gg.Draw(draw + " >> hPtGG", strsel) #ut.norm_to_data(hPtGG, hPt, rt.kGreen, -5., -2.9) ut.norm_to_num(hPtGG, 131., rt.kGreen) print "Int GG:", hPtGG.Integral() #psi' contribution psiP = TFile.Open(basedir_mc + "/ana_slight14e4x1_s6_sel5z.root") psiP_tree = psiP.Get("jRecTree") hPtPsiP = ut.prepare_TH1D("hPtPsiP", ptbin, ptmin, ptmax) psiP_tree.Draw(draw + " >> hPtPsiP", strsel) ut.norm_to_num(hPtPsiP, 12, rt.kViolet) #sum of all contributions hSum = ut.prepare_TH1D("hSum", ptbin, ptmin, ptmax) hSum.SetLineWidth(3) #add ggel to the sum hSum.Add(hPtGG) #add incoherent contribution func_logPt2 = TF1("pdf_logPt2", "[0]*log(10.)*pow(10.,x)*exp(-[1]*pow(10.,x))", -10., 10.) func_logPt2.SetParameters(a, b.getVal()) hInc = ut.prepare_TH1D("hInc", ptbin, ptmin, ptmax) ut.fill_h1_tf(hInc, func_logPt2) hSum.Add(hInc) #add coherent contribution hSum.Add(hPtCoh) #add psi(2S) contribution #hSum.Add(hPtPsiP) #set to draw as a lines ut.line_h1(hSum, rt.kBlack) #create canvas frame can = ut.box_canvas() ut.set_margin_lbtr(gPad, 0.11, 0.09, 0.01, 0.01) frame = x.frame(rf.Bins(nbins), rf.Title("")) frame.SetTitle("") frame.SetMaximum(75) frame.SetYTitle("Events / ({0:.3f}".format(ptbin) + " GeV^{2})") print "Int data:", hPt.Integral() #plot the data if binned == True: dataH.plotOn(frame, rf.Name("data")) else: data.plotOn(frame, rf.Name("data")) pdf_logPt2.plotOn(frame, rf.Range("fitran"), rf.LineColor(rt.kRed), rf.Name("pdf_logPt2")) pdf_logPt2.plotOn(frame, rf.Range("plotran"), rf.LineColor(rt.kRed), rf.Name("pdf_logPt2_full"), rf.LineStyle(rt.kDashed)) frame.Draw() amin = TMath.Power(10, ptmin) amax = TMath.Power(10, ptmax) - 1 print amin, amax pt2func = TF1("f1", "TMath::Power(10, x)", amin, amax) #TMath::Power(x, 10) aPt2 = TGaxis(-5, 75, 1, 75, "f1", 510, "-") ut.set_axis(aPt2) aPt2.SetTitle("pt2") #aPt2.Draw(); leg = ut.prepare_leg(0.57, 0.78, 0.14, 0.19, 0.03) ut.add_leg_mass(leg, mmin, mmax) hx = ut.prepare_TH1D("hx", 1, 0, 1) hx.Draw("same") ln = ut.col_lin(rt.kRed) leg.AddEntry(hx, "Data") leg.AddEntry(hPtCoh, "Sartre MC", "l") leg.AddEntry(hPtGG, "#gamma#gamma#rightarrow e^{+}e^{-} MC", "l") #leg.AddEntry(ln, "ln(10)*#it{A}*10^{log_{10}#it{p}_{T}^{2}}exp(-#it{b}10^{log_{10}#it{p}_{T}^{2}})", "l") #leg.AddEntry(ln, "Incoherent fit", "l") leg.Draw("same") l0 = ut.cut_line(fitran[0], 0.9, frame) l1 = ut.cut_line(fitran[1], 0.9, frame) #l0.Draw() #l1.Draw() desc = pdesc(frame, 0.14, 0.8, 0.054) desc.set_text_size(0.03) desc.itemD("#chi^{2}/ndf", frame.chiSquare("pdf_logPt2", "data", 2), -1, rt.kRed) desc.itemD("#it{A}", a, -1, rt.kRed) desc.itemR("#it{b}", b, rt.kRed) desc.draw() #put the sum #hSum.Draw("same") #gPad.SetLogy() frame.Draw("same") #put gamma-gamma hPtGG.Draw("same") #put coherent J/psi hPtCoh.Draw("same") #put Sartre generated coherent shape #hSartre.Draw("same") #put psi(2S) contribution #hPtPsiP.Draw("same") leg2 = ut.prepare_leg(0.14, 0.9, 0.14, 0.08, 0.03) leg2.AddEntry( ln, "ln(10)*#it{A}*10^{log_{10}#it{p}_{T}^{2}}exp(-#it{b}10^{log_{10}#it{p}_{T}^{2}})", "l") #leg2.AddEntry(hPtCoh, "Sartre MC reconstructed", "l") #leg2.AddEntry(hSartre, "Sartre MC generated", "l") leg2.Draw("same") ut.invert_col(rt.gPad) can.SaveAs("01fig.pdf")
fullmc = RooDataSet('fullmc', 'fullmc', tMC, RooArgSet(thevarsMC)) deltaB0M = fullmc.addColumn(deltaB0Mfunc) deltaJpsiM = fullmc.addColumn(deltaJMfunc) deltaPsiPM = fullmc.addColumn(deltaPMfunc) thevars.add(deltaB0M) thevars.add(deltaJpsiM) thevars.add(deltaPsiPM) thevarsMC.add(deltaB0M) thevarsMC.add(deltaJpsiM) thevarsMC.add(deltaPsiPM) ### define correct and wrong tag samples rt_mc = fullmc.reduce( RooArgSet(thevarsMC), '((tagB0==1 && genSignal==1) || (tagB0==0 && genSignal==2))') wt_mc = fullmc.reduce( RooArgSet(thevarsMC), '((tagB0==0 && genSignal==1) || (tagB0==1 && genSignal==2))') c1 = ROOT.TCanvas() dict_s_rt = {} dict_s_wt = {} out_f = TFile("results_fits_%s_newCB.root" % args.year, "RECREATE") w = ROOT.RooWorkspace("w") initial_n_1 = 3. initial_n_2 = 1. initial_a_1 = 1.
def fit_mass(data, column, x, sig_pdf=None, bkg_pdf=None, n_sig=None, n_bkg=None, blind=False, nll_profile=False, second_storage=None, log_plot=False, pulls=True, sPlot=False, bkg_in_region=False, importance=3, plot_importance=3): """Fit a given pdf to a variable distribution Parameter --------- data : |hepds_type| The data containing the variable to fit to column : str The name of the column to fit the pdf to sig_pdf : RooFit pdf The signal Probability Density Function. The variable to fit to has to be named 'x'. bkg_pdf : RooFit pdf The background Probability Density Function. The variable to fit to has to be named 'x'. n_sig : None or numeric The number of signals in the data. If it should be fitted, use None. n_bkg : None or numeric The number of background events in the data. If it should be fitted, use None. blind : boolean or tuple(numberic, numberic) If False, the data is fitted. If a tuple is provided, the values are used as the lower (the first value) and the upper (the second value) limit of a blinding region, which will be omitted in plots. Additionally, no true number of signal will be returned but only fake. nll_profile : boolean If True, a Negative Log-Likelihood Profile will be generated. Does not work with blind fits. second_storage : |hepds_type| A second data-storage that will be concatenated with the first one. importance : |importance_type| |importance_docstring| plot_importance : |plot_importance_type| |plot_importance_docstring| Return ------ tuple(numerical, numerical) Return the number of signals and the number of backgrounds in the signal-region. If a blind fit is performed, the signal will be a fake number. If no number of background events is required, -999 will be returned. """ if not (isinstance(column, str) or len(column) == 1): raise ValueError("Fitting to several columns " + str(column) + " not supported.") if type(sig_pdf) == type(bkg_pdf) == None: raise ValueError("sig_pdf and bkg_pdf are both None-> no fit possible") if blind is not False: lower_blind, upper_blind = blind blind = True n_bkg_below_sig = -999 # create data data_name = data.name data_array, _t1, _t2 = data.make_dataset(second_storage, columns=column) del _t1, _t2 # double crystalball variables min_x, max_x = min(data_array[column]), max(data_array[column]) # x = RooRealVar("x", "x variable", min_x, max_x) # create data data_array = np.array([i[0] for i in data_array.as_matrix()]) data_array.dtype = [('x', np.float64)] tree1 = array2tree(data_array, "x") data = RooDataSet("data", "Data", RooArgSet(x), RooFit.Import(tree1)) # # TODO: export somewhere? does not need to be defined inside... # mean = RooRealVar("mean", "Mean of Double CB PDF", 5280, 5100, 5600)#, 5300, 5500) # sigma = RooRealVar("sigma", "Sigma of Double CB PDF", 40, 0.001, 200) # alpha_0 = RooRealVar("alpha_0", "alpha_0 of one side", 5.715)#, 0, 150) # alpha_1 = RooRealVar("alpha_1", "alpha_1 of other side", -4.019)#, -200, 0.) # lambda_0 = RooRealVar("lambda_0", "Exponent of one side", 3.42)#, 0, 150) # lambda_1 = RooRealVar("lambda_1", "Exponent of other side", 3.7914)#, 0, 500) # # # TODO: export somewhere? pdf construction # frac = RooRealVar("frac", "Fraction of crystal ball pdfs", 0.479, 0.01, 0.99) # # crystalball1 = RooCBShape("crystallball1", "First CrystalBall PDF", x, # mean, sigma, alpha_0, lambda_0) # crystalball2 = RooCBShape("crystallball2", "Second CrystalBall PDF", x, # mean, sigma, alpha_1, lambda_1) # doubleCB = RooAddPdf("doubleCB", "Double CrystalBall PDF", # crystalball1, crystalball2, frac) # n_sig = RooRealVar("n_sig", "Number of signals events", 10000, 0, 1000000) # test input if n_sig == n_bkg == 0: raise ValueError("n_sig as well as n_bkg is 0...") if n_bkg is None: n_bkg = RooRealVar("n_bkg", "Number of background events", 10000, 0, 500000) elif n_bkg >= 0: n_bkg = RooRealVar("n_bkg", "Number of background events", int(n_bkg)) else: raise ValueError("n_bkg is not >= 0 or None") if n_sig is None: n_sig = RooRealVar("n_sig", "Number of signal events", 1050, 0, 200000) # START BLINDING blind_cat = RooCategory("blind_cat", "blind state category") blind_cat.defineType("unblind", 0) blind_cat.defineType("blind", 1) if blind: blind_cat.setLabel("blind") blind_n_sig = RooUnblindPrecision("blind_n_sig", "blind number of signals", "wasistdas", n_sig.getVal(), 10000, n_sig, blind_cat) else: # blind_cat.setLabel("unblind") blind_n_sig = n_sig print "n_sig value " + str(n_sig.getVal()) # raw_input("blind value " + str(blind_n_sig.getVal())) # n_sig = blind_n_sig # END BLINDING elif n_sig >= 0: n_sig = RooRealVar("n_sig", "Number of signal events", int(n_sig)) else: raise ValueError("n_sig is not >= 0") # if not blind: # blind_n_sig = n_sig # # create bkg-pdf # lambda_exp = RooRealVar("lambda_exp", "lambda exp pdf bkg", -0.00025, -1., 1.) # bkg_pdf = RooExponential("bkg_pdf", "Background PDF exp", x, lambda_exp) if blind: comb_pdf = RooAddPdf("comb_pdf", "Combined DoubleCB and bkg PDF", RooArgList(sig_pdf, bkg_pdf), RooArgList(blind_n_sig, n_bkg)) else: comb_pdf = RooAddPdf("comb_pdf", "Combined DoubleCB and bkg PDF", RooArgList(sig_pdf, bkg_pdf), RooArgList(n_sig, n_bkg)) # create test dataset # mean_gauss = RooRealVar("mean_gauss", "Mean of Gaussian", 5553, -10000, 10000) # sigma_gauss = RooRealVar("sigma_gauss", "Width of Gaussian", 20, 0.0001, 300) # gauss1 = RooGaussian("gauss1", "Gaussian test dist", x, mean_gauss, sigma_gauss) # lambda_data = RooRealVar("lambda_data", "lambda exp data", -.002) # exp_data = RooExponential("exp_data", "data example exp", x, lambda_data) # frac_data = RooRealVar("frac_data", "Fraction PDF of data", 0.15) # # data_pdf = RooAddPdf("data_pdf", "Data PDF", gauss1, exp_data, frac_data) # data = data_pdf.generate(RooArgSet(x), 30000) # data.printValue() # xframe = x.frame() # data_pdf.plotOn(xframe) # print "n_cpu:", meta_config.get_n_cpu() # input("test") # comb_pdf.fitTo(data, RooFit.Extended(ROOT.kTRUE), RooFit.NumCPU(meta_config.get_n_cpu())) # HACK to get 8 cores in testing c5 = TCanvas("c5", "RooFit pdf not fit vs " + data_name) c5.cd() x_frame1 = x.frame() # data.plotOn(x_frame1) # comb_pdf.pdfList()[1].plotOn(x_frame1) if __name__ == "__main__": n_cpu = 8 else: n_cpu = meta_config.get_n_cpu() print "n_cpu = ", n_cpu # HACK # n_cpu = 8 result_fit = comb_pdf.fitTo(data, RooFit.Minos(ROOT.kTRUE), RooFit.Extended(ROOT.kTRUE), RooFit.NumCPU(n_cpu)) # HACK end if bkg_in_region: x.setRange("signal", bkg_in_region[0], bkg_in_region[1]) bkg_pdf_fitted = comb_pdf.pdfList()[1] int_argset = RooArgSet(x) # int_argset = x # int_argset.setRange("signal", bkg_in_region[0], bkg_in_region[1]) integral = bkg_pdf_fitted.createIntegral(int_argset, RooFit.NormSet(int_argset), RooFit.Range("signal")) bkg_cdf = bkg_pdf_fitted.createCdf(int_argset, RooFit.Range("signal")) bkg_cdf.plotOn(x_frame1) # integral.plotOn(x_frame1) n_bkg_below_sig = integral.getVal(int_argset) * n_bkg.getVal() x_frame1.Draw() if plot_importance >= 3: c2 = TCanvas("c2", "RooFit pdf fit vs " + data_name) c2.cd() x_frame = x.frame() # if log_plot: # c2.SetLogy() # x_frame.SetTitle("RooFit pdf vs " + data_name) x_frame.SetTitle(data_name) if pulls: pad_data = ROOT.TPad("pad_data", "Pad with data and fit", 0, 0.33, 1, 1) pad_pulls = ROOT.TPad("pad_pulls", "Pad with data and fit", 0, 0, 1, 0.33) pad_data.SetBottomMargin(0.00001) pad_data.SetBorderMode(0) if log_plot: pad_data.SetLogy() pad_pulls.SetTopMargin(0.00001) pad_pulls.SetBottomMargin(0.2) pad_pulls.SetBorderMode(0) pad_data.Draw() pad_pulls.Draw() pad_data.cd() else: if log_plot: c2.SetLogy() if blind: # HACK column = 'x' # END HACK x.setRange("lower", min_x, lower_blind) x.setRange("upper", upper_blind, max_x) range_str = "lower,upper" lower_cut_str = str( min_x) + "<=" + column + "&&" + column + "<=" + str(lower_blind) upper_cut_str = str( upper_blind) + "<=" + column + "&&" + column + "<=" + str(max_x) sideband_cut_str = "(" + lower_cut_str + ")" + "||" + "(" + upper_cut_str + ")" n_entries = data.reduce( sideband_cut_str).numEntries() / data.numEntries() # raw_input("n_entries: " + str(n_entries)) if plot_importance >= 3: data.plotOn(x_frame, RooFit.CutRange(range_str), RooFit.NormRange(range_str)) comb_pdf.plotOn( x_frame, RooFit.Range(range_str), RooFit.Normalization(n_entries, RooAbsReal.Relative), RooFit.NormRange(range_str)) if pulls: # pull_hist(pull_frame=x_frame, pad_data=pad_data, pad_pulls=pad_pulls) x_frame_pullhist = x_frame.pullHist() else: if plot_importance >= 3: data.plotOn(x_frame) comb_pdf.plotOn(x_frame) if pulls: pad_pulls.cd() x_frame_pullhist = x_frame.pullHist() pad_data.cd() comb_pdf.plotOn(x_frame, RooFit.Components(sig_pdf.namePtr().GetName()), RooFit.LineStyle(ROOT.kDashed)) comb_pdf.plotOn(x_frame, RooFit.Components(bkg_pdf.namePtr().GetName()), RooFit.LineStyle(ROOT.kDotted)) # comb_pdf.plotPull(n_sig) if plot_importance >= 3: x_frame.Draw() if pulls: pad_pulls.cd() x_frame.SetTitleSize(0.05, 'Y') x_frame.SetTitleOffset(0.7, 'Y') x_frame.SetLabelSize(0.04, 'Y') # c11 = TCanvas("c11", "RooFit\ pulls" + data_name) # c11.cd() # frame_tmp = x_frame frame_tmp = x.frame() # frame_tmp.SetTitle("significance") frame_tmp.SetTitle("Roofit\ pulls\ " + data_name) frame_tmp.addObject(x_frame_pullhist) frame_tmp.SetMinimum(-5) frame_tmp.SetMaximum(5) # frame_tmp.GetYaxis().SetTitle("significance") frame_tmp.GetYaxis().SetNdivisions(5) frame_tmp.SetTitleSize(0.1, 'X') frame_tmp.SetTitleOffset(1, 'X') frame_tmp.SetLabelSize(0.1, 'X') frame_tmp.SetTitleSize(0.1, 'Y') frame_tmp.SetTitleOffset(0.5, 'Y') frame_tmp.SetLabelSize(0.1, 'Y') frame_tmp.Draw() # raw_input("") if not blind and nll_profile: # nll_range = RooRealVar("nll_range", "Signal for nLL", n_sig.getVal(), # -10, 2 * n_sig.getVal()) sframe = n_sig.frame(RooFit.Bins(20), RooFit.Range(1, 1000)) # HACK for best n_cpu lnL = comb_pdf.createNLL(data, RooFit.NumCPU(8)) # HACK end lnProfileL = lnL.createProfile(ROOT.RooArgSet(n_sig)) lnProfileL.plotOn(sframe, RooFit.ShiftToZero()) c4 = TCanvas("c4", "NLL Profile") c4.cd() # input("press ENTER to show plot") sframe.Draw() if plot_importance >= 3: pass params = comb_pdf.getVariables() params.Print("v") # print bkg_cdf.getVal() if sPlot: sPlotData = ROOT.RooStats.SPlot( "sPlotData", "sPlotData", data, # variable fitted to, RooDataSet comb_pdf, # fitted pdf ROOT.RooArgList( n_sig, n_bkg, # NSigB0s )) sweights = np.array([ sPlotData.GetSWeight(i, 'n_sig') for i in range(data.numEntries()) ]) return n_sig.getVal(), n_bkg_below_sig, sweights if blind: return blind_n_sig.getVal(), n_bkg_below_sig, comb_pdf else: return n_sig.getVal(), n_bkg_below_sig, comb_pdf
def fit(): #fit to log_10(pT^2) with components and plot of plain pT^2 #range in log_10(pT^2) ptbin = 0.12 ptmin = -5. ptmax = 0.99 # 1.01 #range in pT^2 ptsq_bin = 0.03 ptsq_min = 1e-5 ptsq_max = 1 mmin = 2.8 mmax = 3.2 #range for incoherent fit fitran = [-0.9, 0.1] #number of gamma-gamma events ngg = 131 #number of psi' events npsiP = 20 #input data pT = RooRealVar("jRecPt", "pT", 0, 10) m = RooRealVar("jRecM", "mass", 0, 10) data_all = RooDataSet("data", "data", tree, RooArgSet(pT, m)) #select for mass range strsel = "jRecM>{0:.3f} && jRecM<{1:.3f}".format(mmin, mmax) data = data_all.reduce(strsel) #create log(pT^2) from pT ptsq_draw = "jRecPt*jRecPt" # will be used for pT^2 logPtSq_draw = "TMath::Log10(" + ptsq_draw + ")" logPtSq_form = RooFormulaVar("logPtSq", "logPtSq", logPtSq_draw, RooArgList(pT)) logPtSq = data.addColumn(logPtSq_form) logPtSq.setRange("fitran", fitran[0], fitran[1]) #bins and range for the plot nbins, ptmax = ut.get_nbins(ptbin, ptmin, ptmax) logPtSq.setMin(ptmin) logPtSq.setMax(ptmax) logPtSq.setRange("plotran", ptmin, ptmax) #range for pT^2 ptsq_nbins, ptsq_max = ut.get_nbins(ptsq_bin, ptsq_min, ptsq_max) #incoherent parametrization bval = RooRealVar("bval", "bval", 3.3, 0, 10) inc_form = "log(10.)*pow(10.,logPtSq)*exp(-bval*pow(10.,logPtSq))" incpdf = RooGenericPdf("incpdf", inc_form, RooArgList(logPtSq, bval)) #make the incoherent fit res = incpdf.fitTo(data, rf.Range("fitran"), rf.Save()) #get incoherent norm to the number of events lset = RooArgSet(logPtSq) iinc = incpdf.createIntegral(lset, rf.NormSet(lset), rf.Range("fitran")) inc_nevt = data.sumEntries("logPtSq", "fitran") incpdf.setNormRange("fitran") aval = RooRealVar("aval", "aval", inc_nevt / incpdf.getNorm(lset)) #print "A =", aval.getVal() #print "b =", bval.getVal() #incoherent distribution from log_10(pT^2) function for the sum with gamma-gamma hIncPdf = ut.prepare_TH1D_n("hGG", nbins, ptmin, ptmax) func_incoh_logPt2 = TF1("func_incoh_logPt2", "[0]*log(10.)*pow(10.,x)*exp(-[1]*pow(10.,x))", -10., 10.) func_incoh_logPt2.SetNpx(1000) func_incoh_logPt2.SetLineColor(rt.kMagenta) func_incoh_logPt2.SetParameters( aval.getVal(), bval.getVal()) # 4.9 from incoherent mc, 3.3 from data fit ut.fill_h1_tf(hIncPdf, func_incoh_logPt2, rt.kMagenta) #gamma-gamma contribution hGG = ut.prepare_TH1D_n("hGG", nbins, ptmin, ptmax) tree_gg.Draw(logPtSq_draw + " >> hGG", strsel) ut.norm_to_num(hGG, ngg, rt.kGreen + 1) #sum of incoherent distribution and gamma-gamma hSumIncGG = ut.prepare_TH1D_n("hSumIncGG", nbins, ptmin, ptmax) hSumIncGG.Add(hIncPdf) hSumIncGG.Add(hGG) ut.line_h1(hSumIncGG, rt.kMagenta) #gamma-gamma in pT^2 hGG_ptsq = ut.prepare_TH1D_n("hGG_ptsq", ptsq_nbins, ptsq_min, ptsq_max) tree_gg.Draw(ptsq_draw + " >> hGG_ptsq", strsel) ut.norm_to_num(hGG_ptsq, ngg, rt.kGreen + 1) #psi' contribution psiP_file = TFile.Open(basedir_mc + "/ana_slight14e4x1_s6_sel5z.root") psiP_tree = psiP_file.Get("jRecTree") hPsiP = ut.prepare_TH1D_n("hPsiP", nbins, ptmin, ptmax) psiP_tree.Draw(logPtSq_draw + " >> hPsiP", strsel) ut.norm_to_num(hPsiP, npsiP, rt.kViolet) #psi' in pT^2 hPsiP_ptsq = ut.prepare_TH1D_n("hPsiP_ptsq", ptsq_nbins, ptsq_min, ptsq_max) psiP_tree.Draw(ptsq_draw + " >> hPsiP_ptsq", strsel) ut.norm_to_num(hPsiP_ptsq, npsiP, rt.kViolet) #create canvas frame gStyle.SetPadTickY(1) can = ut.box_canvas(1086, 543) # square area is still 768^2 can.SetMargin(0, 0, 0, 0) can.Divide(2, 1, 0, 0) gStyle.SetLineWidth(1) can.cd(1) ut.set_margin_lbtr(gPad, 0.11, 0.1, 0.01, 0) frame = logPtSq.frame(rf.Bins(nbins)) frame.SetTitle("") frame.SetMaximum(80) frame.SetYTitle("Events / ({0:.3f}".format(ptbin) + " GeV^{2})") frame.SetXTitle("log_{10}( #it{p}_{T}^{2} ) (GeV^{2})") frame.GetXaxis().SetTitleOffset(1.2) frame.GetYaxis().SetTitleOffset(1.6) #plot the data data.plotOn(frame, rf.Name("data"), rf.LineWidth(2)) #incoherent parametrization incpdf.plotOn(frame, rf.Range("fitran"), rf.LineColor(rt.kRed), rf.Name("incpdf"), rf.LineWidth(2)) incpdf.plotOn(frame, rf.Range("plotran"), rf.LineColor(rt.kRed), rf.Name("incpdf_full"), rf.LineStyle(rt.kDashed), rf.LineWidth(2)) frame.Draw() #add gamma-gamma contribution hGG.Draw("same") #sum of incoherent distribution and gamma-gamma #hSumIncGG.Draw("same") #add psi' #hPsiP.Draw("same") #legend for log_10(pT^2) leg = ut.prepare_leg(0.15, 0.77, 0.28, 0.19, 0.035) hxl = ut.prepare_TH1D("hxl", 1, 0, 1) hxl.Draw("same") ilin = ut.col_lin(rt.kRed, 2) ilin2 = ut.col_lin(rt.kRed, 2) ilin2.SetLineStyle(rt.kDashed) leg.AddEntry(ilin, "Incoherent parametrization, fit region", "l") leg.AddEntry(ilin2, "Incoherent parametrization, extrapolation region", "l") leg.AddEntry(hGG, "#gamma#gamma#rightarrow e^{+}e^{-}", "l") #leg.AddEntry(hxl, "Data", "lp") leg.AddEntry(hxl, "Data, log_{10}( #it{p}_{T}^{2} )", "lp") leg.Draw("same") #----- plot pT^2 on the right ----- #pT^2 variable from pT ptsq_form = RooFormulaVar("ptsq", "ptsq", ptsq_draw, RooArgList(pT)) ptsq = data.addColumn(ptsq_form) #range for pT^2 plot ptsq.setMin(ptsq_min) ptsq.setMax(ptsq_max) #make the pT^2 plot can.cd(2) gPad.SetLogy() #gPad.SetLineWidth(3) #gPad.SetFrameLineWidth(1) ut.set_margin_lbtr(gPad, 0, 0.1, 0.01, 0.15) ptsq_frame = ptsq.frame(rf.Bins(ptsq_nbins), rf.Title("")) #print type(ptsq_frame), type(ptsq) ptsq_frame.SetTitle("") ptsq_frame.SetXTitle("#it{p}_{T}^{2} (GeV^{2})") ptsq_frame.GetXaxis().SetTitleOffset(1.2) data.plotOn(ptsq_frame, rf.Name("data"), rf.LineWidth(2)) ptsq_frame.SetMaximum(9e2) ptsq_frame.SetMinimum(0.8) # 0.101 ptsq_frame.Draw() #incoherent parametrization in pT^2 over the fit region, scaled to the plot inc_ptsq = TF1("inc_ptsq", "[0]*exp(-[1]*x)", 10**fitran[0], 10**fitran[1]) inc_ptsq.SetParameters(aval.getVal() * ptsq_bin, bval.getVal()) #incoherent parametrization in the extrapolation region, below and above the fit region inc_ptsq_ext1 = TF1("inc_ptsq_ext1", "[0]*exp(-[1]*x)", 0., 10**fitran[0]) inc_ptsq_ext2 = TF1("inc_ptsq_ext2", "[0]*exp(-[1]*x)", 10**fitran[1], 10) inc_ptsq_ext1.SetParameters(aval.getVal() * ptsq_bin, bval.getVal()) inc_ptsq_ext1.SetLineStyle(rt.kDashed) inc_ptsq_ext2.SetParameters(aval.getVal() * ptsq_bin, bval.getVal()) inc_ptsq_ext2.SetLineStyle(rt.kDashed) inc_ptsq.Draw("same") inc_ptsq_ext1.Draw("same") inc_ptsq_ext2.Draw("same") #add gamma-gamma in pT^2 hGG_ptsq.Draw("same") #add psi' in pT^2 #hPsiP_ptsq.Draw("same") #redraw the frame #ptsq_frame.Draw("same") ptsq_frame.GetXaxis().SetLimits(-9e-3, ptsq_frame.GetXaxis().GetXmax()) #vertical axis for pT^2 plot xpos = ptsq_frame.GetXaxis().GetXmax() ypos = ptsq_frame.GetMaximum() ymin = ptsq_frame.GetMinimum() ptsq_axis = TGaxis(xpos, 0, xpos, ypos, ymin, ypos, 510, "+GL") ut.set_axis(ptsq_axis) ptsq_axis.SetMoreLogLabels() ptsq_axis.SetTitle("Events / ({0:.3f}".format(ptsq_bin) + " GeV^{2})") ptsq_axis.SetTitleOffset(2.2) ptsq_axis.Draw() #legend for input data #dleg = ut.prepare_leg(0.4, 0.77, 0.14, 0.18, 0.035) dleg = ut.prepare_leg(0.4, 0.71, 0.16, 0.24, 0.035) dleg.AddEntry(None, "#bf{|#kern[0.3]{#it{y}}| < 1}", "") ut.add_leg_mass(dleg, mmin, mmax) dleg.AddEntry(None, "AuAu@200 GeV", "") dleg.AddEntry(None, "UPC sample", "") dleg.AddEntry(hxl, "Data, #it{p}_{T}^{2}", "lp") dleg.Draw("same") #ut.invert_col_can(can) can.SaveAs("01fig.pdf")
simulComponents = [] # scan Lb likelihood {{{ # jack's profile likelihood scan if sysFitLb: label = 'sysLbFit' numSig = spaceExt.var('numLb') numBkg = spaceExt.var('numCombBkg_Run2016Data_pLbL0') varName = 'lbl0Mass' figDir.cd() var = space.var(varName) model = space1st.pdf('totPdf_Run2016Data_pLbL0') #dataset=model.generate(RooArgSet(space.var('lbtkMass')),10000) dataset = loadDatasetLb.reduce('{x}>{minVal}&&{x}<{maxVal}'.format( x=varName, minVal=var.getMin(), maxVal=var.getMax())) fitres = model.fitTo(dataset, RooFit.Save(True), RooFit.Minos(useMinos)) plot = var.frame(RooFit.Title('data fit {0}'.format(label))) dataset.plotOn(plot) model.plotOn( plot, RooFit.Normalization(dataset.sumEntries(), RooAbsReal.NumEvent)) SaveResult(origPlot=plot, origVar=var, data={'content': dataset}, totPDF={'content': model}, fitres=fitres, label=label, fitDir=fitDir,
num_pairs = gDirectory.Get("mass").GetEntries() * scale_factor radfrac = radfracFile.Get("radfrac").GetFunction("pol3").Eval(mass) #radfrac = radfracFile.Get("radfrac_10mrad").GetFunction("pol3").Eval(mass) num_rad = radfrac * num_pairs ap_yield = 3 * math.pi / (2 * (1 / 137.0)) * num_rad * (mass / deltaM) print "{0} pairs, {1} radfrac, {2} rad, {3} A'".format( num_pairs, radfrac, num_rad, ap_yield) breakz = tailsFile.Get("breakz").GetFunction("pol3").Eval(mass) length = tailsFile.Get("length").GetFunction("pol3").Eval(mass) c.cd(2) gPad.SetLogy() frame = vtxZRefitUnc.frame() dataInRange = dataset.reduce( obs, "abs({0}-{1})<{2}/2*({3}+{4}*{5})".format(massVar, mass, masscut_nsigma, mres_p0, mres_p1, vtxVar)) binnedData = dataInRange.binnedClone() binnedData.plotOn(frame) mean = binnedData.mean(vtxZRefitUnc) sigma = binnedData.sigma(vtxZRefitUnc) vtxZRefitUnc.setRange("fitRange", mean - 2 * sigma, mean + 2 * sigma) gauss_params.setRealValue("mean", mean) gauss_params.setRealValue("sigma", sigma) gauss_pdf.fitTo(binnedData, RooFit.Range("fitRange"), RooFit.PrintLevel(-1)) mean = gauss_params.getRealValue("mean") sigma = gauss_params.getRealValue("sigma") gaussexp_params.setRealValue("gauss_mean", mean) gaussexp_params.setRealValue("gauss_sigma", sigma) gaussexp_params.setRealValue("exp_breakpoint", breakz)
lxysig = RooRealVar("xL", "l_{xy} sign." + region + "l_{xy} / #sigma(l_{xy})", -1000.0, 1000.0) massvars = RooArgSet(tt_mass, mm_mass, mmtt_mass) ptvars = RooArgSet(tt_pt, mm_pt, mmtt_pt) kinvars = RooArgSet(massvars, ptvars) extravars = RooArgSet(lxysig) theData = RooDataSet("theData", "theData", theTree, RooArgSet(kinvars, extravars)) c = TCanvas("canvas", "canvas", 1200, 800) if args.nonprompt: theData = theData.reduce("xL > 3.0") if args.prompt: theData = theData.reduce("xL < 1.5") if args.ptcuts is not None: theData = theData.reduce("trigp_pT > " + str(args.ptcuts)) theData = theData.reduce("trign_pT > " + str(args.ptcuts)) cuts += "P_t_" + str(args.ptcuts) + "_" #### #### Plotting variables #### TrakTrak Data if args.noplot: print("TrakTrak data plotting . . .") print("All : " + str(theData.numEntries()))
masskP = space.var('kpibarMass') tk1Pt = space.var('tk1Pt') tk2Pt = space.var('tk2Pt') loadDatasetLb = RooDataSet( 'loadData16', 'loadData16', inN16, RooArgSet(massLb, massBd, massbD, massBs, massKK, massKp, masskP, tk1Pt, tk2Pt)) frame = "lbtkMass>5.3&&lbtkMass<6." ptsel = "tk1Pt>2. && tk2Pt>2." Bdbkg = "((bdMass>5.25&&bdMass<5.31)&&(kpiMass>0.86&&kpiMass<0.93))" bDbkg = "(bdbarMass>5.25&&bdbarMass<5.31&&kpibarMass<0.93)" bsbkg = "(bsMass>5.25&&bsMass<5.4&&kkMass>1.01&&kkMass<1.03)" cutData = loadDatasetLb.reduce('&&'.join([frame, ptsel])) bkgComb = loadDatasetLb.reduce('&&'.join([frame, ptsel]) + '&&' + '||'.join([Bdbkg, bDbkg, bsbkg])) space.factory('Polynomial::pPDF(lbtkMass,{c1[0.01,-5.,5.]})') keyPDF = RooKeysPdf('kPDF', 'kPDF', massLb, bkgComb, RooKeysPdf.NoMirror, 0.1) getattr(space, 'import')(keyPDF) space.factory( 'SUM::totPDF(numBKG[{initNum},0.,{maxNum}]*pPDF,{bkgNum}*kPDF)'.format( initNum=cutData.sumEntries() - bkgComb.sumEntries(), maxNum=cutData.sumEntries() * 1.05, bkgNum=bkgComb.sumEntries())) fitModel = space.factory('totPDF') massLb.setRange('leftSideband', 5.3, 5.619 - 0.03)
ApProduced = TH2F("ApProduced","ApProduced",nApMass,Medges,NepsBins,Epsedges) VProducedRho = TH2F("VProducedRho","VProducedRho",nApMass,Medges,NepsBins,Epsedges) detectableRho = TH2F("detectableRho","detectableRho",nApMass,Medges,NepsBins,Epsedges) VProducedPhi = TH2F("VProducedPhi","VProducedPhi",nApMass,Medges,NepsBins,Epsedges) detectablePhi = TH2F("detectablePhi","detectablePhi",nApMass,Medges,NepsBins,Epsedges) for k in range(0,nApMass): massAp = (massApmax - massApmin)/float(nApMass - 1) * k + massApmin massV = 0.6*massAp massPi = massAp/3. fPi = massPi/fpiArr[i] massVres = massresfile.Get("mres").GetFunction("pol1").Eval(massV) breakz = tailsfile.Get("breakz").GetFunction("pol3").Eval(massV) length = tailsfile.Get("length").GetFunction("pol3").Eval(massV) frame = uncVZ.frame() dataInRange = dataset.reduce(obs,"abs({0}-{1})<{2}/2*{3}".format("uncM",massV,masscut_nsigma,massVres)) binnedData = dataInRange.binnedClone() binnedData.plotOn(frame) mean = binnedData.mean(uncVZ) sigma = binnedData.sigma(uncVZ) uncVZ.setRange("fitRange",mean-2*sigma,mean+2*sigma) gauss_params.setRealValue("mean",mean) gauss_params.setRealValue("sigma",sigma) gauss_pdf.fitTo(binnedData,RooFit.Range("fitRange"),RooFit.PrintLevel(-1)) mean = gauss_params.getRealValue("mean") sigma = gauss_params.getRealValue("sigma") gaussexp_params.setRealValue("gauss_mean",mean) gaussexp_params.setRealValue("gauss_sigma",sigma) gaussexp_params.setRealValue("exp_breakpoint",breakz) gaussexp_params.setRealValue("exp_length",length) w.var("gauss_mean").setConstant(True)
magnet_datas = {} dp_inv = (p_inv.getMax() - p_inv.getMin()) / n_bins dp = (p.getMax() - p.getMin()) / n_bins bins_p = [0 + i * dp for i in range(n_bins + 1)] graphs = {} sigmas = defaultdict(list) sigmas_err = defaultdict(list) av = [] err_x = [] p_vars = {p_inv.GetName(): p_inv, p.GetName(): p} vname = p_inv.GetName() bins = bins_p_inv for i in range(n_bins): ds = magnet_data.reduce('{0} > {1} && {0} < {2}'.format( vname, bins[i], bins[i + 1])) magnet_datas[i] = ds av += [ds.mean(p_vars[vname])] err_x += [0.] for obs, tag in ((pull_xm, 'xm'), (pull_ym, 'ym')): cn = 'fit_canvas_' + tag canvas_fit = TCanvas(cn, cn, 1200, 800) canvas_fit.Divide(3, 3) canvases['fit_' + tag] = canvas_fit model = models[tag] for i in range(n_bins): ds = magnet_datas[i] magnet_results[(tag, i)] = model.fitTo(ds, RooFit.Minimizer('Minuit2'), RooFit.Save(), RooFit.NumCPU(2)) frame = obs.frame()
else: print "Running without 'r' argument disabled" sys.exit(0) rootInFile = TFile("../BsStuff.root") keyList = rootInFile.GetListOfKeys() keyList.At(0).ReadObj().Print() keyList.At(1).ReadObj().Print() tupleDataSet = rootInFile.Get('treeData') if not os.path.isfile(tupleDictFilename) or tupleDictFilename == "-": print "Filename argument invalid; running for default tuple dictionary file" tupleDictFilename = os.environ[ "B2DXFITTERSROOT"] + "/tutorial/tupleDict2.py" tupleDict = importTupleDict(tupleDictFilename) tupleDataSet = tupleDataSet.reduce('osDecision==ssDecision') from B2DXFitters.utils import configDictFromFile config = configDictFromFile('bsConfig.py') # start with RooFit stuff from ROOT import (RooRealVar, RooConstVar, RooCategory, RooWorkspace, RooArgSet, RooArgList, RooLinkedList, RooAbsReal, RooRandom, TRandom3, MistagDistribution, MistagCalibration, RooFormulaVar) # safe settings for numerical integration (if needed) RooAbsReal.defaultIntegratorConfig().setEpsAbs(1e-9) RooAbsReal.defaultIntegratorConfig().setEpsRel(1e-9) RooAbsReal.defaultIntegratorConfig().getConfigSection( 'RooAdaptiveGaussKronrodIntegrator1D').setCatLabel( 'method', '15Points')
(( mumuMass < {JPSIM} && !( abs(deltaB0M - deltaJpsiM) < 0.16 || abs(deltaB0M - deltaPsiPM) < 0.06) ) || \ ( mumuMass > {PSIM} && !( abs(deltaB0M - deltaJpsiM) < 0.06 || abs(deltaB0M - deltaPsiPM) < 0.03) ) || \ ( mumuMass > {JPSIM} && mumuMass < {PSIM} && !( abs(deltaB0M - deltaJpsiM) < 0.06 || abs(deltaB0M - deltaPsiPM) < 0.06 ))))'.format( JPSIM=JPsiMass_, PSIM=PsiPMass_, CUT=nSigma_psiRej) elif args.dimusel == 'keepPsi': cut = '(abs(mumuMass - {JPSIM}) < {CUT}*mumuMassE || abs(mumuMass - {PSIM}) < {CUT}*mumuMassE)'.format( JPSIM=JPsiMass_, PSIM=PsiPMass_, CUT=nSigma_psiRej) elif args.dimusel == 'nocut': cut = 'mumuMass > 0' else: print '\nYou should define which dimuon mass to consider. Please choose between following options: \nkeepPsiP, keepJpsi, rejectPsi, keepPsi' sys.exit(0) print cut data = fulldata.reduce(RooArgSet(theBMass, mumuMass, mumuMassE), cut) mean = RooRealVar("mass", "mean", B0Mass_, 3, 7, "GeV") sigma = RooRealVar("#sigma", "sigma", 0.028, 0, 10, "GeV") signalGauss = RooGaussian("signalGauss", "signal gauss", theBMass, mean, sigma) sigma2 = RooRealVar("#sigma2", "sigma2", 0.048, 0, 0.07, "GeV") signalGauss2 = RooGaussian("signalGauss2", "signal gauss2", theBMass, mean, sigma2) f1 = RooRealVar("f1", "f1", 0.8, 0., 1.) gaus = RooAddPdf("gaus", "gaus1+gaus2", RooArgList(signalGauss, signalGauss2), RooArgList(f1)) pol_c1 = RooRealVar("p1", "coeff x^0 term", 0.5, -10, 10) pol_c2 = RooRealVar("p2", "coeff x^1 term", 0.5, -10, 10) pol_c3 = RooRealVar("p3", "coeff x^2 term", 0.5, -10, 10)