try: if sys.argv[2] == "CR": doCR = True elif sys.argv[2] == "SR": doSR = True except IndexError: pass keyIter = inputFile.GetListOfKeys().MakeIterator() key = keyIter.Next() while key: if key.GetName().find("low") == -1 and key.GetName().find("high") == -1: try: nomHist = TH1D(inputFile.Get(key.GetName())) highHist = TH1D(inputFile.Get(key.GetName() + "_high")) lowHist = TH1D(inputFile.Get(key.GetName() + "_low")) try: highRatio = highHist.Integral() / nomHist.Integral() lowRatio = lowHist.Integral() / nomHist.Integral() #print key.GetName(),"high = ",highRatio,"low = ",lowRatio if key.GetName().startswith("hQCD_"): tmp = key.GetName()[5:] if doCR: if not key.GetName().find("ChanCR") == -1: print "for", key.GetName() print ' <OverallSys Name="NormQCD_%s" High="%f" Low="%f" />' % ( tmp, highRatio, lowRatio) pass elif doSR:
"title": "m_{ll}^{(2)} [GeV]", "bin": 36, "xmin": 0, "xmax": 100 }, "higgs_m": { "name": "higgs_m", "title": "m_{4l} [GeV]", "bin": 36, "xmin": 70, "xmax": 170 }, } dict_histoS = { var: TH1D(var + "S", var + "S;" + Vars[var]["title"] + ";", Vars[var]["bin"], Vars[var]["xmin"], Vars[var]["xmax"]) for var in Vars } dict_histoB = { var: TH1D(var + "B", var + "B;" + Vars[var]["title"] + ";", Vars[var]["bin"], Vars[var]["xmin"], Vars[var]["xmax"]) for var in Vars } rootFileS = TFile(FileS, "read") treeS = rootFileS.Get(treeName) rootFileB = TFile(FileB, "read") treeB = rootFileB.Get(treeName) for entry in xrange(treeS.GetEntries()): treeS.GetEntry(entry)
#Tianai from ROOT import TH1D, gRandom h1 = TH1D("hist","histogram",100,-5,5) for i in xrange(10000): hist = gRandom.Gaus() h1.Fill(hist) h1.Draw()
def create_yields_list(channel, varName, toppt, j1j2pt, lepjetdR, bin, low, high, ylabel, xlabel, save, wprime, btags, List_to_use): if (channel == 'electron'): ch = '_el' if (channel == 'muon'): ch = '_mu' pyfile = open( "yields_For2DLimits_06Jun_finalbins_ScaleGenTopPt_QCD/" + channel + "_" + save + "_Wprime" + wprime + "_Histos-" + btags + "_dr03_lep50.py", "w") doTTbarWeight = 'True' if (channel == 'electron'): cut = 'jet_0_pt_WprimeCalc >= 120 && jet_1_pt_WprimeCalc >= 40 && elec_1_pt_WprimeCalc > 50 && abs(elec_1_eta_WprimeCalc) < 2.5 && elec_1_RelIso_WprimeCalc < 0.1 && corr_met_WprimeCalc > 20 && Muon_DeltaR_LjetsTopoCalcNew > ' + lepjetdR if (channel == 'muon'): cut = 'jet_0_pt_WprimeCalc >= 120 && jet_1_pt_WprimeCalc >= 40 && muon_1_pt_WprimeCalc > 50 && abs(muon_1_eta_WprimeCalc) < 2.1 && muon_1_RelIso_WprimeCalc < 0.12 && corr_met_WprimeCalc > 20 && Muon_DeltaR_LjetsTopoCalcNew > ' + lepjetdR print varName if btags == 'zerobtags': cutbtag = ' && ((jet_0_tag_WprimeCalc+jet_1_tag_WprimeCalc)==0) ' if btags == 'onebtags': cutbtag = ' && ((jet_0_tag_WprimeCalc+jet_1_tag_WprimeCalc)==1) ' if btags == 'ge1btags': cutbtag = ' && ((jet_0_tag_WprimeCalc+jet_1_tag_WprimeCalc)>=1) ' if btags == 'twobtags': cutbtag = ' && ((jet_0_tag_WprimeCalc+jet_1_tag_WprimeCalc)==2) ' if btags == 'ge2btags': cutbtag = ' && ( (jet_0_tag_WprimeCalc==1 && (jet_1_tag_WprimeCalc + jet_2_tag_WprimeCalc + jet_3_tag_WprimeCalc + jet_4_tag_WprimeCalc + jet_5_tag_WprimeCalc + jet_6_tag_WprimeCalc + jet_7_tag_WprimeCalc + jet_8_tag_WprimeCalc + jet_9_tag_WprimeCalc) >= 1 ) || (jet_1_tag_WprimeCalc==1 && (jet_0_tag_WprimeCalc + jet_2_tag_WprimeCalc + jet_3_tag_WprimeCalc + jet_4_tag_WprimeCalc + jet_5_tag_WprimeCalc + jet_6_tag_WprimeCalc + jet_7_tag_WprimeCalc + jet_8_tag_WprimeCalc + jet_9_tag_WprimeCalc) >= 1 ) ) ' if btags == 'final': cutbtag = ' && ( (jet_0_tag_WprimeCalc+jet_1_tag_WprimeCalc ) >= 1 )' if btags == 'final': cut = cut + ' && BestTop_LjetsTopoCalcNew > 130 && BestTop_LjetsTopoCalcNew < 210 && BestTop_Pt_LjetsTopoCalcNew > ' + toppt + ' && Jet1Jet2_Pt_LjetsTopoCalcNew > ' + j1j2pt cutwbb = ' && n_Bjets_WprimeCalc > 0' # Wb(b) cutwcc = ' && n_Bjets_WprimeCalc==0 && n_Cjets_WprimeCalc>0' # Wc(c) cutwjj = ' && n_Bjets_WprimeCalc==0 && n_Cjets_WprimeCalc==0' # W+light if (doTTbarWeight == 'True'): SFWjmu = 0.82 ## myHF120lep50, scale ttbar SFWcmu = 1.0 * 1.66 ## myHF120lep50, scale ttbar SFWbmu = 1.0 * 1.21 ## myHF120lep50, scale ttbar SFWjmuPlus = 0.82 * 0.87 ## myHF120lep50, scale ttbar SFWcmuPlus = 1.0 * 1.66 * 1.15 ## myHF120lep50, scale ttbar SFWbmuPlus = 1.0 * 1.21 * 1.15 ## myHF120lep50, scale ttbar SFWjmuMinus = 0.82 * 1.13 ## myHF120lep50, scale ttbar SFWcmuMinus = 1.0 * 1.66 * 0.85 ## myHF120lep50, scale ttbar SFWbmuMinus = 1.0 * 1.21 * 0.85 ## myHF120lep50, scale ttbar #weight_ttbarminus = '(1.188-0.001124*(BestTop_Pt_LjetsTopoCalcNew))' #weight_ttbarplus = '1.0' #weight_ttbar = '(5.809*TMath::Landau(BestTop_Pt_LjetsTopoCalcNew,149.1,154))' weight_ttbarminus = 'weight_TopPt_WprimeCalc' weight_ttbarplus = '1.0' weight_ttbar = 'weight_TopPt_WprimeCalc' if (doTTbarWeight == 'False'): SFWjmu = 0.82 ## myHF120lep50 SFWcmu = 0.93 * 1.66 ## myHF120lep50 SFWbmu = 0.93 * 1.21 ## myHF120lep50 SFWjmuPlus = 0.82 * 0.87 ## myHF120lep50 SFWcmuPlus = 0.93 * 1.66 * 1.15 ## myHF120lep50 SFWbmuPlus = 0.93 * 1.21 * 1.15 ## myHF120lep50 SFWjmuMinus = 0.82 * 1.13 ## myHF120lep50 SFWcmuMinus = 0.93 * 1.66 * 0.85 ## myHF120lep50 SFWbmuMinus = 0.93 * 1.21 * 0.85 ## myHF120lep50 weight_ttbarminus = '1.0' weight_ttbarplus = '1.0' weight_ttbar = '1.0' cutzerobtags = ' && ( (jet_0_tag_WprimeCalc+jet_1_tag_WprimeCalc+jet_2_tag_WprimeCalc+jet_3_tag_WprimeCalc+jet_4_tag_WprimeCalc+jet_5_tag_WprimeCalc+jet_6_tag_WprimeCalc+jet_7_tag_WprimeCalc+jet_8_tag_WprimeCalc+jet_9_tag_WprimeCalc) == 0 )' print wprime #print cut + cutbtag List = List_to_use Variables = {} VariablesPUup = {} Variables0tag = {} VariablesHFup = {} VariablesHFdown = {} VariablesTTbarShapeUp = {} VariablesTTbarShapeDown = {} background = 0 j = 0 nominalwprime = 'False' print List for Type in List: if (channel == 'electron'): prefix = 'elec_invmass_' + btags + '__' if (channel == 'muon'): prefix = 'mu_invmass_' + btags + '__' suffix = '' if (Type == 'Data_el' or Type == 'Data_mu'): suffix = 'DATA' + Type if (Type == 'WJets' or re.match('W[1-4]Jets', Type)): suffix = 'wjets' + Type if (Type == 'WW'): suffix = 'scaledntb' + Type if (Type == 'ZJets_M50' or Type == 'WW' or Type == 'T_t' or Type == 'Tbar_t' or Type == 'T_tW' or Type == 'Tbar_tW'): suffix = 'scaledntb' + Type if (Type == 'TTbar_Madgraph'): suffix = 'ttbar' + Type if (Type == 'T_s' or Type == 'Tbar_s'): suffix = 'tb' + Type if (Type == 'WJets_JESUP'): suffix = 'wjets_jesUp' + Type if (Type == 'TTbar_Madgraph_JESUP' or Type == 'WW_JESUP' or Type == 'ZJets_M50_JESUP' or Type == 'T_t_JESUP' or Type == 'Tbar_t_JESUP' or Type == 'T_tW_JESUP' or Type == 'Tbar_tW_JESUP'): suffix = 'scaledntb_jesUp' + Type if (Type == 'TTbar_Madgraph_JESUP'): suffix = 'scaledall_jesUp' + Type if (Type == 'T_s_JESUP' or Type == 'Tbar_s_JESUP'): suffix = 'tb_jesUp' + Type if (Type == 'WJets_JESDOWN'): suffix = 'wjets_jesDown' + Type if (Type == 'TTbar_Madgraph_JESDOWN' or Type == 'WW_JESDOWN' or Type == 'ZJets_M50_JESDOWN' or Type == 'T_t_JESDOWN' or Type == 'Tbar_t_JESDOWN' or Type == 'T_tW_JESDOWN' or Type == 'Tbar_tW_JESDOWN'): suffix = 'scaledntb_jesDown' + Type if (Type == 'TTbar_Madgraph_JESDOWN'): suffix = 'scaledall_jesDown' + Type if (Type == 'T_s_JESDOWN' or Type == 'Tbar_s_JESDOWN'): suffix = 'tb_jesDown' + Type if (Type == 'WJets_JERUP'): suffix = 'wjets_jerUp' + Type if (Type == 'TTbar_Madgraph_JERUP' or Type == 'WW_JERUP' or Type == 'ZJets_M50_JERUP' or Type == 'T_t_JERUP' or Type == 'Tbar_t_JERUP' or Type == 'T_tW_JERUP' or Type == 'Tbar_tW_JERUP'): suffix = 'scaledntb_jerUp' + Type if (Type == 'TTbar_Madgraph_JERUP'): suffix = 'scaledall_jerUp' + Type if (Type == 'T_s_JERUP' or Type == 'Tbar_s_JERUP'): suffix = 'tb_jerUp' + Type if (Type == 'WJets_JERDOWN'): suffix = 'wjets_jerDown' + Type if (Type == 'TTbar_Madgraph_JERDOWN' or Type == 'WW_JERDOWN' or Type == 'ZJets_M50_JERDOWN' or Type == 'T_t_JERDOWN' or Type == 'Tbar_t_JERDOWN' or Type == 'T_tW_JERDOWN' or Type == 'Tbar_tW_JERDOWN'): suffix = 'scaledntb_jerDown' + Type if (Type == 'TTbar_Madgraph_JERDOWN'): suffix = 'scaledall_jerDown' + Type if (Type == 'T_s_JERDOWN' or Type == 'Tbar_s_JERDOWN'): suffix = 'tb_jerDown' + Type if (Type == 'WJets_BTAGUP'): suffix = 'wjets_btagUp' + Type if (Type == 'TTbar_Madgraph_BTAGUP' or Type == 'WW_BTAGUP' or Type == 'ZJets_M50_BTAGUP' or Type == 'T_t_BTAGUP' or Type == 'Tbar_t_BTAGUP' or Type == 'T_tW_BTAGUP' or Type == 'Tbar_tW_BTAGUP'): suffix = 'scaledntb_btagUp' + Type if (Type == 'TTbar_Madgraph_BTAGUP'): suffix = 'scaledall_btagUp' + Type if (Type == 'T_s_BTAGUP' or Type == 'Tbar_s_BTAGUP'): suffix = 'tb_btagUp' + Type if (Type == 'WJets_BTAGDOWN'): suffix = 'wjets_btagDown' + Type if (Type == 'TTbar_Madgraph_BTAGDOWN' or Type == 'WW_BTAGDOWN' or Type == 'ZJets_M50_BTAGDOWN' or Type == 'T_t_BTAGDOWN' or Type == 'Tbar_t_BTAGDOWN' or Type == 'T_tW_BTAGDOWN' or Type == 'Tbar_tW_BTAGDOWN'): suffix = 'scaledntb_btagDown' + Type if (Type == 'TTbar_Madgraph_BTAGDOWN'): suffix = 'scaledall_btagDown' + Type if (Type == 'T_s_BTAGDOWN' or Type == 'Tbar_s_BTAGDOWN'): suffix = 'tb_btagDown' + Type if (Type == 'WJets_SCALEUP'): suffix = 'wjets_q2scaleUp' if (Type == 'WJets_SCALEDOWN'): suffix = 'wjets_q2scaleDown' if (Type == 'WJets_MATCHINGUP'): suffix = 'wjets_matchingUp' if (Type == 'WJets_MATCHINGDOWN'): suffix = 'wjets_matchingDown' if (Type == 'TTbar_Madgraph_SCALEUP'): suffix = 'ttbar__q2scale__plus' if (Type == 'TTbar_Madgraph_SCALEDOWN'): suffix = 'ttbar__q2scale__mins' if (Type == 'TTbar_Madgraph_MATCHINGUP'): suffix = 'ttbar__matching__plus' if (Type == 'TTbar_Madgraph_MATCHINGDOWN'): suffix = 'ttbar__matching__minus' if (Type.startswith('QCD')): suffix = 'qcd' + Type if (Type.startswith('QCD') and Type.endswith('JESUP')): suffix = 'qcd_jesUp' + Type if (Type.startswith('QCD') and Type.endswith('JESDOWN')): suffix = 'qcd_jesDown' + Type if (Type.startswith('QCD') and Type.endswith('JERUP')): suffix = 'qcd_jerUp' + Type if (Type.startswith('QCD') and Type.endswith('JERDOWN')): suffix = 'qcd_jerDown' + Type if (Type.startswith('QCD') and Type.endswith('BTAGUP')): suffix = 'qcd_btagUp' + Type if (Type.startswith('QCD') and Type.endswith('BTAGDOWN')): suffix = 'qcd_btagDown' + Type w_suffix = 'wp' if (wprime != 'ModRight'): if (Type.startswith('Wprime800' + wprime)): suffix = w_suffix + '800' if (Type.startswith('Wprime900' + wprime)): suffix = w_suffix + '900' if (Type.startswith('Wprime1000' + wprime)): suffix = w_suffix + '1000' if (Type.startswith('Wprime1100' + wprime)): suffix = w_suffix + '1100' if (Type.startswith('Wprime1200' + wprime)): suffix = w_suffix + '1200' if (Type.startswith('Wprime1300' + wprime)): suffix = w_suffix + '1300' if (Type.startswith('Wprime1400' + wprime)): suffix = w_suffix + '1400' if (Type.startswith('Wprime1500' + wprime)): suffix = w_suffix + '1500' if (Type.startswith('Wprime1600' + wprime)): suffix = w_suffix + '1600' if (Type.startswith('Wprime1700' + wprime)): suffix = w_suffix + '1700' if (Type.startswith('Wprime1800' + wprime)): suffix = w_suffix + '1800' if (Type.startswith('Wprime1900' + wprime)): suffix = w_suffix + '1900' if (Type.startswith('Wprime2000' + wprime)): suffix = w_suffix + '2000' if (Type.startswith('Wprime2100' + wprime)): suffix = w_suffix + '2100' if (Type.startswith('Wprime2200' + wprime)): suffix = w_suffix + '2200' if (Type.startswith('Wprime2300' + wprime)): suffix = w_suffix + '2300' if (Type.startswith('Wprime2400' + wprime)): suffix = w_suffix + '2400' if (Type.startswith('Wprime2500' + wprime)): suffix = w_suffix + '2500' if (Type.startswith('Wprime2600' + wprime)): suffix = w_suffix + '2600' if (Type.startswith('Wprime2700' + wprime)): suffix = w_suffix + '2700' if (Type.startswith('Wprime2800' + wprime)): suffix = w_suffix + '2800' if (Type.startswith('Wprime2900' + wprime)): suffix = w_suffix + '2900' if (Type.startswith('Wprime3000' + wprime)): suffix = w_suffix + '3000' if (Type.endswith('_JESUP')): suffix += '__jes__plus' if (Type.endswith('_JESDOWN')): suffix += '__jes__minus' if (Type.endswith('_JERUP')): suffix += '__jer__plus' if (Type.endswith('_JERDOWN')): suffix += '__jer__minus' if (Type.endswith('_BTAGUP')): suffix += '__btag__plus' if (Type.endswith('_BTAGDOWN')): suffix += '__btag__minus' else: if (Type.startswith('Wprime800Right')): suffix = w_suffix + '800' if (Type.startswith('Wprime900Right')): suffix = w_suffix + '900' if (Type.startswith('Wprime1000Right')): suffix = w_suffix + '1000' if (Type.startswith('Wprime1100Right')): suffix = w_suffix + '1100' if (Type.startswith('Wprime1200Right')): suffix = w_suffix + '1200' if (Type.startswith('Wprime1300Right')): suffix = w_suffix + '1300' if (Type.startswith('Wprime1400Right')): suffix = w_suffix + '1400' if (Type.startswith('Wprime1500Right')): suffix = w_suffix + '1500' if (Type.startswith('Wprime1600Right')): suffix = w_suffix + '1600' if (Type.startswith('Wprime1700Right')): suffix = w_suffix + '1700' if (Type.startswith('Wprime1800Right')): suffix = w_suffix + '1800' if (Type.startswith('Wprime1900Right')): suffix = w_suffix + '1900' if (Type.startswith('Wprime2000Right')): suffix = w_suffix + '2000' if (Type.startswith('Wprime2100Right')): suffix = w_suffix + '2100' if (Type.startswith('Wprime2200Right')): suffix = w_suffix + '2200' if (Type.startswith('Wprime2300Right')): suffix = w_suffix + '2300' if (Type.startswith('Wprime2400Right')): suffix = w_suffix + '2400' if (Type.startswith('Wprime2500Right')): suffix = w_suffix + '2500' if (Type.startswith('Wprime2600Right')): suffix = w_suffix + '2600' if (Type.startswith('Wprime2700Right')): suffix = w_suffix + '2700' if (Type.startswith('Wprime2800Right')): suffix = w_suffix + '2800' if (Type.startswith('Wprime2900Right')): suffix = w_suffix + '2900' if (Type.startswith('Wprime3000Right')): suffix = w_suffix + '3000' if (Type.endswith('_JESUP')): suffix += '__jes__plus' if (Type.endswith('_JESDOWN')): suffix += '__jes__minus' if (Type.endswith('_JERUP')): suffix += '__jer__plus' if (Type.endswith('_JERDOWN')): suffix += '__jer__minus' if (Type.endswith('_BTAGUP')): suffix += '__btag__plus' if (Type.endswith('_BTAGDOWN')): suffix += '__btag__minus' histName = prefix + suffix + 'varbin' histNamePUup = prefix + suffix + 'varbin' + '__PU__plus' histNamePUdown = prefix + suffix + 'varbin' + '__PU__minus' histName0tag = prefix + suffix + 'varbin' + '__0tag__plus' histNameHFup = prefix + suffix + 'varbin' + '__hf__plus' histNameHFdown = prefix + suffix + 'varbin' + '__hf__minus' histNameTTbarShapeUp = prefix + suffix + 'varbin' + '__ttbarshape__plus' histNameTTbarShapeDown = prefix + suffix + 'varbin' + '__ttbarshape__minus' histNamePre = prefix + suffix + 'varbin' + 'Pre' Variables[Type] = TH1D(histName, histName, bin, array('d', xlow)) Variables[Type].Sumw2() if (channel == 'electron'): weight = '( ((0.973*weight_PU_ABCD_PileUpCalc*weight_ElectronEff_53x_WprimeCalc)*(abs(elec_1_eta_WprimeCalc)<1.5)) + ((1.02*weight_PU_ABCD_PileUpCalc*weight_ElectronEff_53x_WprimeCalc)*(abs(elec_1_eta_WprimeCalc)>1.5 && abs(elec_1_eta_WprimeCalc)<2.5)) )' weightPUup = '( ((0.973*weight_PU_ABCD735_PileUpCalc*weight_ElectronEff_53x_WprimeCalc)*(abs(elec_1_eta_WprimeCalc)<1.5)) + ((1.02*weight_PU_ABCD735_PileUpCalc*weight_ElectronEff_53x_WprimeCalc)*(abs(elec_1_eta_WprimeCalc)>1.5 && abs(elec_1_eta_WprimeCalc)<2.5)) )' SF = 1.0 if (channel == 'muon'): weight = 'weight_PU_ABCD_PileUpCalc*weight_MuonEff_WprimeCalc' weightPUup = 'weight_PU_ABCD735_PileUpCalc*weight_MuonEff_WprimeCalc' SF = 1.0 if (Type == 'WJets' or re.match('W[1-4]Jets', Type)): WccHist = TH1D('WccHist', 'WccHist', bin, array('d', xlow)) WbbHist = TH1D('WbbHist', 'WbbHist', bin, array('d', xlow)) WccHist.Sumw2() WbbHist.Sumw2() WccHistPUup = TH1D('WccHistPUup', 'WccHistPUup', bin, array('d', xlow)) WbbHistPUup = TH1D('WbbHistPUup', 'WbbHistPUup', bin, array('d', xlow)) WccHistPUup.Sumw2() WbbHistPUup.Sumw2() WccHistHFup = TH1D('WccHistHFup', 'WccHistHFup', bin, array('d', xlow)) WbbHistHFup = TH1D('WbbHistHFup', 'WbbHistHFup', bin, array('d', xlow)) WccHistHFup.Sumw2() WbbHistHFup.Sumw2() WccHistHFdown = TH1D('WccHistHFdown', 'WccHistHFdown', bin, array('d', xlow)) WbbHistHFdown = TH1D('WbbHistHFdown', 'WbbHistHFdown', bin, array('d', xlow)) WccHistHFdown.Sumw2() WbbHistHFdown.Sumw2() WccHistPre = TH1D('WccHistPre', 'WccHistPre', bin, array('d', xlow)) WbbHistPre = TH1D('WbbHistPre', 'WbbHistPre', bin, array('d', xlow)) WccHistPre.Sumw2() WbbHistPre.Sumw2() if ((not Type.endswith('UP')) and (not Type.endswith('DOWN'))): VariablesPUup[Type] = TH1D(histNamePUup, histNamePUup, bin, array('d', xlow)) #VariablesPUdown[Type] = TH1D(histNamePUdown, histNamePUdown, bin, array('d',xlow)) Variables0tag[Type] = TH1D(histName0tag, histName0tag, bin, array('d', xlow)) VariablesHFup[Type] = TH1D(histNameHFup, histNameHFup, bin, array('d', xlow)) VariablesHFdown[Type] = TH1D(histNameHFdown, histNameHFdown, bin, array('d', xlow)) VariablesTTbarShapeUp[Type] = TH1D(histNameTTbarShapeUp, histNameTTbarShapeUp, bin, array('d', xlow)) VariablesTTbarShapeDown[Type] = TH1D(histNameTTbarShapeDown, histNameTTbarShapeDown, bin, array('d', xlow)) VariablesPUup[Type].Sumw2() #VariablesPUdown[Type].Sumw2() Variables0tag[Type].Sumw2() VariablesHFup[Type].Sumw2() VariablesHFdown[Type].Sumw2() VariablesTTbarShapeUp[Type].Sumw2() VariablesTTbarShapeDown[Type].Sumw2() print Type, histName if (Type.startswith('Data')): Trees[Type].Draw(var + " >> " + histName, "(" + cut + cutbtag + ")", 'goff') # 0 tag for data-driven shape Trees[Type].Draw(var + " >> " + histName0tag, "(" + cut + cutzerobtags + ")", 'goff') elif (Type == 'WJets' or re.match('W[1-4]Jets', Type)): Trees[Type].Draw( var + " >> " + histName, "(" + weight + ")*(" + str(SFWjmu) + ")*(" + cut + cutwjj + cutbtag + ")", 'goff') Trees[Type].Draw( var + " >> " + "WbbHist", "(" + weight + ")*(" + str(SFWbmu) + ")*(" + cut + cutwbb + cutbtag + ")", 'goff') Trees[Type].Draw( var + " >> " + "WccHist", "(" + weight + ")*(" + str(SFWcmu) + ")*(" + cut + cutwcc + cutbtag + ")", 'goff') Variables[Type].Add(WbbHist) Variables[Type].Add(WccHist) if ((not Type.endswith('UP')) and (not Type.endswith('DOWN'))): # Pile Up Trees[Type].Draw( var + " >> " + histNamePUup, "(" + weightPUup + ")*(" + str(SFWjmu) + ")*(" + cut + cutwjj + cutbtag + ")", 'goff') Trees[Type].Draw( var + " >> " + "WbbHistPUup", "(" + weightPUup + ")*(" + str(SFWbmu) + ")*(" + cut + cutwbb + cutbtag + ")", 'goff') Trees[Type].Draw( var + " >> " + "WccHistPUup", "(" + weightPUup + ")*(" + str(SFWcmu) + ")*(" + cut + cutwcc + cutbtag + ")", 'goff') VariablesPUup[Type].Add(WbbHistPUup) VariablesPUup[Type].Add(WccHistPUup) # 0 tag shape (one sided, so only one histogram) Trees[Type].Draw( var + " >> " + histName0tag, "(" + weight + ")*(" + cut + cutzerobtags + ")", 'goff') # H.F. k-factor Trees[Type].Draw( var + " >> " + histNameHFup, "(" + weight + ")*(" + str(SFWjmuPlus) + ")*(" + cut + cutwjj + cutbtag + ")", 'goff') Trees[Type].Draw( var + " >> " + "WbbHistHFup", "(" + weight + ")*(" + str(SFWbmuPlus) + ")*(" + cut + cutwbb + cutbtag + ")", 'goff') Trees[Type].Draw( var + " >> " + "WccHistHFup", "(" + weight + ")*(" + str(SFWcmuPlus) + ")*(" + cut + cutwcc + cutbtag + ")", 'goff') VariablesHFup[Type].Add(WbbHistHFup) VariablesHFup[Type].Add(WccHistHFup) Trees[Type].Draw( var + " >> " + histNameHFdown, "(" + weight + ")*(" + str(SFWjmuMinus) + ")*(" + cut + cutwjj + cutbtag + ")", 'goff') Trees[Type].Draw( var + " >> " + "WbbHistHFdown", "(" + weight + ")*(" + str(SFWbmuMinus) + ")*(" + cut + cutwbb + cutbtag + ")", 'goff') Trees[Type].Draw( var + " >> " + "WccHistHFdown", "(" + weight + ")*(" + str(SFWcmuMinus) + ")*(" + cut + cutwcc + cutbtag + ")", 'goff') VariablesHFdown[Type].Add(WbbHistHFdown) VariablesHFdown[Type].Add(WccHistHFdown) elif ((not Type.startswith('T')) and (not Type.startswith('QCD'))): Trees[Type].Draw(var + " >> " + histNamePre, "(" + weight + ")*(" + cut + ")", 'goff') Trees[Type].Draw(var + " >> " + histName, "(" + weight + ")*(" + cut + cutbtag + ")", 'goff') if ((not Type.endswith('UP')) and (not Type.endswith('DOWN'))): Trees[Type].Draw( var + " >> " + histNamePUup, "(" + weightPUup + ")*(" + cut + cutbtag + ")", 'goff') #Trees[Type].Draw(var + " >> " + histNamePUdown, "("+weightPUdown+")*("+cut+cutbtag+")", 'goff') Trees[Type].Draw( var + " >> " + histName0tag, "(" + weight + ")*(" + cut + cutzerobtags + ")", 'goff') Trees[Type].Draw(var + " >> " + histNameHFup, "(" + weight + ")*(" + cut + cutbtag + ")", 'goff') Trees[Type].Draw(var + " >> " + histNameHFdown, "(" + weight + ")*(" + cut + cutbtag + ")", 'goff') elif (Type.startswith('TTbar')): Trees[Type].Draw( var + " >> " + histName, "(" + weight + ")*(" + weight_ttbar + ")*(" + cut + cutbtag + ")", 'goff') if ((not Type.endswith('UP')) and (not Type.endswith('DOWN'))): Trees[Type].Draw( var + " >> " + histNamePUup, "(" + weightPUup + ")*(" + weight_ttbar + ")*(" + cut + cutbtag + ")", 'goff') #Trees[Type].Draw(var + " >> " + histNamePUdown, "("+weightPUdown+")*("+cut+cutbtag+")", 'goff') Trees[Type].Draw( var + " >> " + histName0tag, "(" + weight + ")*(" + weight_ttbar + ")*(" + cut + cutzerobtags + ")", 'goff') Trees[Type].Draw( var + " >> " + histNameHFup, "(" + weight + ")*(" + weight_ttbar + ")*(" + cut + cutbtag + ")", 'goff') Trees[Type].Draw( var + " >> " + histNameHFdown, "(" + weight + ")*(" + weight_ttbar + ")*(" + cut + cutbtag + ")", 'goff') Trees[Type].Draw( var + " >> " + histNameTTbarShapeUp, "(" + weight + ")*(" + weight_ttbarplus + ")*(" + cut + cutbtag + ")", 'goff') Trees[Type].Draw( var + " >> " + histNameTTbarShapeDown, "(" + weight + ")*(" + weight_ttbarminus + ")*(" + cut + cutbtag + ")", 'goff') else: #print 'cut = ',cut+cutbtag Trees[Type].Draw(var + " >> " + histName, "(" + weight + ")*(" + cut + cutbtag + ")", 'goff') if ((not Type.endswith('UP')) and (not Type.endswith('DOWN'))): Trees[Type].Draw( var + " >> " + histNamePUup, "(" + weightPUup + ")*(" + cut + cutbtag + ")", 'goff') #Trees[Type].Draw(var + " >> " + histNamePUdown, "("+weightPUdown+")*("+cut+cutbtag+")", 'goff') Trees[Type].Draw( var + " >> " + histName0tag, "(" + weight + ")*(" + cut + cutzerobtags + ")", 'goff') Trees[Type].Draw(var + " >> " + histNameHFup, "(" + weight + ")*(" + cut + cutbtag + ")", 'goff') Trees[Type].Draw(var + " >> " + histNameHFdown, "(" + weight + ")*(" + cut + cutbtag + ")", 'goff') if (not Type.startswith('Data')): #print 'EVENTS Before Scaling FOR ',Type,' = ',Variables[Type].Integral() #print str(SF),' ',str(lumi),' ',str(xsec[Type]),' ',str(Nevents[Type]) if (channel == 'electron'): lumi = lumi_el if (channel == 'muon'): lumi = lumi_mu if Variables[Type].Integral() != 0: Variables[Type].Scale( (SF * lumi * xsec_norm[Type] / Nevents[Type])) pyfile.write(" yields[mass+coup+'_" + Type + ch + "_" + btags + "'] = " + str(Variables[Type].Integral()) + "\n") if ((not Type.endswith('UP')) and (not Type.endswith('DOWN'))): VariablesPUup[Type].Scale( (SF * lumi * xsec_norm[Type] / Nevents[Type])) #VariablesPUdown[Type].Scale ( (SF*lumi*xsec_norm[Type]/Nevents[Type]) ) Variables0tag[Type].Scale( (SF * lumi * xsec_norm[Type] / Nevents[Type])) VariablesHFup[Type].Scale( (SF * lumi * xsec_norm[Type] / Nevents[Type])) VariablesHFdown[Type].Scale( (SF * lumi * xsec_norm[Type] / Nevents[Type])) VariablesTTbarShapeUp[Type].Scale( (SF * lumi * xsec_norm[Type] / Nevents[Type])) VariablesTTbarShapeDown[Type].Scale( (SF * lumi * xsec_norm[Type] / Nevents[Type])) pyfile.write(" yieldsPUup[mass+coup+'_" + Type + ch + "_" + btags + "'] = " + str(VariablesPUup[Type].Integral()) + "\n") pyfile.write(" yields0tag[mass+coup+'_" + Type + ch + "_" + btags + "'] = " + str(Variables0tag[Type].Integral()) + "\n") pyfile.write(" yieldsHFup[mass+coup+'_" + Type + ch + "_" + btags + "'] = " + str(VariablesHFup[Type].Integral()) + "\n") pyfile.write(" yieldsHFdown[mass+coup+'_" + Type + ch + "_" + btags + "'] = " + str(VariablesHFdown[Type].Integral()) + "\n") pyfile.write(" yieldsTTbarShapeUp[mass+coup+'_" + Type + ch + "_" + btags + "'] = " + str(VariablesTTbarShapeUp[Type].Integral()) + "\n") pyfile.write( " yieldsTTbarShapeDown[mass+coup+'_" + Type + ch + "_" + btags + "'] = " + str(VariablesTTbarShapeDown[Type].Integral()) + "\n") pyfile.close() for line in fileinput.input(pyfile.name, inplace=1): if '_el_el' in line: line = line.replace('_el_el', '_el') if '_mu_mu' in line: line = line.replace('_mu_mu', '_mu') if 'Data' in line: line = line.replace('Data', 'data') if 'WJets' in line: line = line.replace('WJets', 'wjets') if 'W1Jets' in line: line = line.replace('W1Jets', 'w1jets') if 'W2Jets' in line: line = line.replace('W2Jets', 'w2jets') if 'W3Jets' in line: line = line.replace('W3Jets', 'w3jets') if 'W4Jets' in line: line = line.replace('W4Jets', 'w4jets') if 'ZJets_M50' in line: line = line.replace('ZJets_M50', 'zjets') if 'WW' in line: line = line.replace('WW', 'ww') if 'T_t' in line: line = line.replace('T_t', 't') if 'Tbar_t' in line: line = line.replace('Tbar_t', 'bt') if 'tW' in line: line = line.replace('tW', 'tw') if 'T_s' in line: line = line.replace('T_s', 's') if 'Tbar_s' in line: line = line.replace('Tbar_s', 'bs') if 'TTbar_Madgraph' in line: line = line.replace('TTbar_Madgraph', 'ttbar') if 'QCD_Pt_80_170_EM' in line: line = line.replace('QCD_Pt_80_170_EM', 'qcd80to170') if 'QCD_Pt_170_250_EM' in line: line = line.replace('QCD_Pt_170_250_EM', 'qcd170to250') if 'QCD_Pt_250_350_EM' in line: line = line.replace('QCD_Pt_250_350_EM', 'qcd250to350') if 'QCD_Pt_350_EM' in line: line = line.replace('QCD_Pt_350_EM', 'qcd350') if 'Wprime' in line: line = line.replace('Wprime', 'wp') if 'Right' in line: line = line.replace('Right', 'R') if 'Left' in line: line = line.replace('Left', 'L') if 'Mix' in line: line = line.replace('Mix', 'RL') print line
HiggsHist.Add(thehist) thehist = fitUtils.File2Hist(fitterPars.MCDirectory + \ 'el_VBFHWWMH%i_CMSSW428.root' % (opts.mH), 'VBFHWW%i_el' % (opts.mH), True, 1, False) VBFHiggsHist.Add(thehist) thehist = fitUtils.File2Hist(fitterPars.MCDirectory + \ 'el_HWWTauNuMH%i_CMSSW428.root' % (opts.mH), 'HWWTauNu%i_el' % (opts.mH), True, 1, False) TauNuHiggsHist.Add(thehist) extraFactor = 10. (Ngen,otherdata) = NgenHiggs(opts.mH, pars4.includeElectrons, pars4.includeMuons) HiggsHist.Scale(1./float(Ngen), 'width') SigVisual = TH1D(HiggsHist) SigVisual.SetName('SigVisual') SigVisual.SetLineColor(kBlue) SigVisual.SetLineWidth(3) SigVisual.Scale(pars4.intLumi*extraFactor*otherdata[1]*otherdata[2]) SigVisual.Print() SigVisualLog = TH1D(SigVisual) SigVisualLog.SetName("SigVisualLog") NgenVBF = NgenVBFHiggs(opts.mH, pars4.includeElectrons, pars4.includeMuons) VBFHiggsHist.Scale(1./float(NgenVBF),'width') NgenTauNu = NgenHWWTauNu(opts.mH, pars4.includeElectrons, pars4.includeMuons) TauNuHiggsHist.Scale(1./float(NgenTauNu), 'width') print "Ngen Higgs:",Ngen,"VBF Higgs:",NgenVBF,"HWW -> tau nu jj:",NgenTauNu
bins = 100 print "Calculate histogram ranges" data = [] for i in xrange(len(data1_in)): inputs1 = data1_in[i] output1 = data1_out[i] #if (abs(inputs1[0])>1000): print i, inputs1[0] if (inputs1[0] != 0): data.append(output1[0] / inputs1[0]) xmin = min(data) xmax = max(data) print "Min value =", xmin, " Max value=", xmax xmin = -0.5 xmax = 0.5 h1 = TH1D("valid1", "valid1", bins, xmin, xmax) h1.Sumw2() h1.SetLineWidth(2) h1.SetLineStyle(1) h1.SetLineColor(1) h1.SetStats(0) h1.SetTitle("") h2 = TH1D("neuralnet1", "neuralnet1", bins, xmin, xmax) h2.Sumw2() h2.SetMarkerColor(2) h2.SetMarkerSize(0.7) h2.SetMarkerStyle(21) h2.SetLineWidth(2) h2.SetLineStyle(1) h2.SetLineColor(1)
# Canvas c1 = TCanvas( 'c1', 'Histogram Drawing Options', 200, 10, 700, 900 ) pad1 = TPad( 'pad1', 'The pad with the function', 0.03, 0.62, 0.50, 0.92, 21 ) pad2 = TPad( 'pad2', 'The pad with the histogram', 0.51, 0.62, 0.98, 0.92, 21 ) pad3 = TPad( 'pad3', 'The pad with the histogram', 0.03, 0.02, 0.97, 0.57, 21 ) pad1.Draw() pad2.Draw() pad3.Draw() npts = len(x) h1 = TH1D( 'h1', 'Full pulse profile', npts, 0, npts) h2 = TH1D( 'h2', 'Diff with template', hibin-lowbin, lowbin, hibin) h3 = TH1D( 'h3', 'Fitted pulse profile', hibin-lowbin, lowbin, hibin) for i in xrange(npts): h1.SetBinContent( i+1, x[i] ) #h2.SetBinContent( i+1, x[i] ) for i,xx in enumerate(x[lowbin:hibin]): h2.SetBinContent( i+1, xx ) h3.SetBinContent( i+1, xx ) par = array( 'd', 3*[0.] ) total = TF1( 'total', 'gaus', lowbin, hibin ) # Set initial conditions par[0] = h2.GetMaximum()
def getHists(contained_only=False): # Define the desired energy ranges ERanges = [(0.3, 0.5), (0.5, 0.7), (0.7, 0.9), (0.9, 1.1), (1.1, 1.3), (1.3, 1.5), (1.5, 1.7), (1.7, 1.9), (1.9, 2.1)] # Creating empty histograms hist_dictionary = {} for myE in ERanges: myName = "h_min%s_max%s" % (myE[0], myE[1]) if contained_only: myName = "cont_h_min%s_max%s" % (myE[0], myE[1]) myTitle = "Energies from %0.1f to %0.1f;(True p - Reco p) / True p;Entries" % ( myE[0], myE[1]) if contained_only: myTitle = "Contained Tracks: Energies from %0.1f to %0.1f;(True p - Reco p) / True p;Entries" % ( myE[0], myE[1]) hist_dictionary[myE] = TH1D(myName, myTitle, 100, -4, 4) # Loop over energy ranges to create graphs of type (2) for myE in ERanges: myPlot = "(true_mom - mcs_reco_mom) / true_mom >> h_min%0.1f_max%0.1f" % ( myE[0], myE[1]) if contained_only: myPlot = "(true_mom - mcs_reco_mom) / true_mom >> cont_h_min%0.1f_max%0.1f" % ( myE[0], myE[1]) myCut = "mcs_reco_mom > 0 && true_mom > %f && true_mom < %f" % (myE[0], myE[1]) if contained_only: myCut += " && mu_contained == 1" f.ana_tree.Draw(myPlot, myCut) # Create lists for graphs (3), (4) that will be filled in the next loop xpoints = [] filMeanVals, filSqrtHistEntries = [], [] filStdVals, filStdErrs = [], [] for myE in ERanges: # Filter out energy ranges with 0 entries if hist_dictionary[myE].GetEntries() != 0: xpoints.append(myE[0] + (myE[1] - myE[0]) / 2.) filMeanVals.append(hist_dictionary[myE].GetMean()) filSqrtHistEntries.append( TMath.sqrt(hist_dictionary[myE].GetEntries())) filStdVals.append(hist_dictionary[myE].GetRMS()) filStdErrs.append(hist_dictionary[myE].GetRMSError()) # Calculate error bars for graph (3): (stdDev / sqrt(entries)) yerrs = map(truediv, filStdVals, filSqrtHistEntries) # Define a constant width (x-error bar) for each marker xerrs = [(myE[1] - myE[0]) / 2. for myE in ERanges] # Graph (3) and (4) setup meanGraph = TGraphErrors() stdGraph = TGraphErrors() meanGraphTitle = "Mean vs. Energy;True Muon Energy (GeV);#left[p_{MC}-p_{MCS} / p_{MC}#right]" if contained_only: meanGraphTitle = "Contained Tracks: Mean vs. Energy;True Muon Energy (GeV);#left[p_{MC}-p_{MCS} / p_{MC}#right]" stdGraphTitle = "Standard Deviation vs. Energy;True Muon Energy (GeV);Fractional Momentum Resolution" if contained_only: stdGraphTitle = "Contained Tracks: Standard Deviation vs. Energy;True Muon Energy (GeV);Fractional Momentum Resolution" meanGraph.SetTitle(meanGraphTitle) stdGraph.SetTitle(stdGraphTitle) # Fill in data for graph (3) for i in xrange(len(xpoints)): meanGraph.SetPoint(i, xpoints[i], filMeanVals[i]) meanGraph.SetPointError(i, xerrs[i], yerrs[i]) meanGraph.Draw("ALP") # Fill in data for graph (4) for i in xrange(len(xpoints)): stdGraph.SetPoint(i, xpoints[i], filStdVals[i]) stdGraph.SetPointError(i, xerrs[i], filStdErrs[i]) stdGraph.Draw("ALP") return hist_dictionary, meanGraph, stdGraph
def __init__(self, histname, ncuts, **kwargs): self.hist = TH1D('cutflow', 'cutflow', ncuts, 0, ncuts) self.hist.GetXaxis().SetLabelSize(0.041) self.nextidx = 0 self.cuts = {}
h_fit = [] chMaxYRange = 0 h_1D_sX = [] h_2D_sX = [] sXMaxYRange = 0 h_1D_sY = [] h_2D_sY = [] sYMaxYRange = 0 # sort into different cluster property for h in sorted(histo1D): n = histo1D[h].GetName() if sliceL: hist1D = histo1D[h].Clone() else: hist1F = histo1D[h].Clone() hist1D = TH1D() hist1F.Copy(hist1D) if 'ch' in n: setHisto(hist1D, "Norm. on-trk. clu. charge (ke)", "On-track Clusters / 1 ke", 0) h_fit.append(fitting(hist1D)) h_1D_ch.append(hist1D) if hist1D.GetMaximum() > chMaxYRange: chMaxYRange = hist1D.GetMaximum() if 'X' in n: setHisto(hist1D, "On-track cluster size x (pixel)", "On-track Clusters / 1 pixel", 0) h_1D_sX.append(hist1D) if hist1D.GetMaximum() > sXMaxYRange: sXMaxYRange = hist1D.GetMaximum() if 'Y' in n: setHisto(hist1D, "On-Track cluster size y (pixel)", "On-track Clusters / 1 pixel", 0)
def main(optunf="Bayes"): optunfs = ["Bayes", "SVD", "TUnfold", "Invert", "Reverse"] if not optunf in optunfs: txt = "Unfolding option " + optunf + " not recognised" raise ValueError(txt) global hReco, hMeas, hTrue print "==================================== TRAIN ====================================" # Create response matrix object for 40 measured and 20 # unfolded bins: response = RooUnfoldResponse(40, -10.0, 10.0, 20, -10.0, 10.0) # Train with a Breit-Wigner, mean 0.3 and width 2.5. for i in xrange(100000): # xt= gRandom.BreitWigner( 0.3, 2.5 ) xt = gRandom.Gaus(0.0, 5.0) x = smear(xt) if x != None: response.Fill(x, xt) else: response.Miss(xt) print "==================================== TEST =====================================" hTrue = TH1D("true", "Test Truth", 20, -10.0, 10.0) hMeas = TH1D("meas", "Test Measured", 40, -10.0, 10.0) # Test with a Gaussian, mean 0 and width 2. for i in xrange(10000): # xt= gRandom.Gaus( 0.0, 2.0 ) xt = gRandom.BreitWigner(0.3, 2.5) x = smear(xt) hTrue.Fill(xt) if x != None: hMeas.Fill(x) print "==================================== UNFOLD ===================================" print "Unfolding method:", optunf if "Bayes" in optunf: # Bayes unfoldung with 4 iterations # unfold= RooUnfoldBayes( response, hMeas, 4 ) unfold = RooUnfoldBayes(response, hMeas, 10, False, True) elif "SVD" in optunf: # SVD unfoding with free regularisation # unfold= RooUnfoldSvd( response, hMeas, 20 ) unfold = RooUnfoldSvd(response, hMeas) elif "TUnfold" in optunf: # TUnfold with fixed regularisation tau=0.002 # unfold= RooUnfoldTUnfold( response, hMeas ) unfold = RooUnfoldTUnfold(response, hMeas, 0.002) elif "Invert" in optunf: unfold = RooUnfoldInvert(response, hMeas) elif "Reverse" in optunf: unfold = RooUnfoldBayes(response, hMeas, 1) hReco = unfold.Hreco() # unfold.PrintTable( cout, hTrue ) unfold.PrintTable(cout, hTrue, 2) hReco.Draw() hMeas.Draw("SAME") hTrue.SetLineColor(8) hTrue.Draw("SAME") return
def D1H_txt_to_roothist(filename, outputpath=''): from ROOT import TFile, TCanvas, TPad, TH1D, TLatex, TStyle, gStyle, TText, gPad, TPaveText from inspect import currentframe, getframeinfo import os #gStyle.SetOptStat(0) can = TCanvas("can", "can", 200, 10, 500, 500) if (filename[0] == "/"): filename = filename else: filename = os.getcwd( ) + "/" + filename # get the path included filename loca = len(filename) for i in range(1, len(filename) + 1): # find the "/" location if (filename[-i] == "/"): loca = i - 1 break FILENAME = filename.replace(filename[:-loca], "") # this is the shorten filename # print(FILENAME, "******") fileroot = filename.replace(".txt", "_F.root") fileroot = fileroot.replace("//", "/") f = open(filename, "r") lineList = f.readlines() Nbin = (len(lineList)) # get number of bins Line_string = str(lineList[0]) _, bin_init, _, _ = Line_string.split() bin_init = float(bin_init) # get initial bin Line_string = str(lineList[len(lineList) - 1]) _, _, bin_final, _ = Line_string.split() bin_final = float(bin_final) # get final bin f.seek(0) # reset python read line hist = TH1D("hist", "hist", Nbin, bin_init, bin_final) total_e = 0 for i in range(1, Nbin + 1): Line_string = str(f.readline()) _, _, _, bin_c = Line_string.split() bin_c = float(bin_c) hist.SetBinContent(i, bin_c) total_e = total_e + bin_c total_e = int(total_e) hist.Draw() text = TText(hist.GetXaxis().GetBinCenter(2), hist.GetYaxis().GetBinCenter(1), "Recycled. Total Entry : %i" % total_e) text.SetTextFont(10) text.Draw() gPad.Update() can.Update() if (outputpath == ''): wf = TFile(fileroot, "RECREATE") print(fileroot, " root file is generated !!!") else: if (outputpath[0] == "/"): fileroot = outputpath + "/" + FILENAME.replace(".txt", "_F.root") fileroot = fileroot.replace("//", "/") elif (outputpath[0] == "~"): fileroot = outputpath.replace( "~", os.environ['HOME']) + "/" + FILENAME.replace( ".txt", "_F.root") fileroot = fileroot.replace("//", "/") else: fileroot = os.getcwd() + "/" + outputpath + "/" + FILENAME.replace( ".txt", "_F.root") fileroot = fileroot.replace("//", "/") wf = TFile(fileroot, "RECREATE") print(fileroot, " root file is generated !!!") hist.Write() wf.Close() fileroot = fileroot.replace("//", "/") # print(fileroot) return fileroot
def main(argv): LOADTREE_ANADIR = "/net/user/aguilar/work/IceCube/scripts/IC79/" tr = TChain("L3CutsTree") tr.Add(LOADTREE_ANADIR + "final.v19.nugen_numu_6308_9981f_RunID_new.root") tr.GetEntries() MCzenith = ctypes.c_double(0) tr.SetBranchAddress("MC_Zr", MCzenith) MCazimuth = ctypes.c_double(0) tr.SetBranchAddress("MC_Ar", MCazimuth) eneMC = ctypes.c_double(0) tr.SetBranchAddress("MC_En", eneMC) SMPEzenith = ctypes.c_double(0) tr.SetBranchAddress("MPE_FINAL_MUON_Zd", SMPEzenith) SMPEazimuth = ctypes.c_double(0) tr.SetBranchAddress("MPE_FINAL_MUON_Ad", SMPEazimuth) ene = ctypes.c_double(0) tr.SetBranchAddress("MuE_FINAL_MUON_En", ene) sigma = ctypes.c_double(0) tr.SetBranchAddress("MPE_Pb_FINAL_MUON_SigmaDeg", sigma) oneW = ctypes.c_double(0) tr.SetBranchAddress("OW", oneW) nEv = ctypes.c_double(0) tr.SetBranchAddress("NEvents", nEv) h = TH2D("pull", "pull", 50, 1, 9, 100, 0.01, 20) h.SetStats(0) h.GetXaxis().SetTitle("log_{10}(MuEx_energy [GeV])") h.GetYaxis().SetTitle("Pull: #Delta#Psi/#sigma_{parab.}") g = TGraphAsymmErrors(50) medians = [[] for i in range(0, 50)] mediansW = [[] for i in range(0, 50)] go = TGraph(50) go.SetMarkerStyle(22) go.SetMarkerColor(4) hEneW = TH1D( "hEneW", "MCPrimary energy; log_{10}(E [GeV]); #frac{d#Phi}{dE} [GeV^{-1} cm^{-2} s^{-1} sr^{-1} ( #frac{E}{GeV} )^{-2} ", 100, 1, 9.5) hREneW = TH1D( "hREneW", "Reco energy SplineMPEMuEXDiff; log_{10}(E [GeV]); #frac{d#Phi}{dE} [GeV^{-1} cm^{-2} s^{-1} sr^{-1} ( #frac{E}{GeV} )^{-2}", 100, 1, 9) for i in range(0, tr.GetEntries()): tr.GetEntry(i) #if not hem(np.radians(SMPEzenith.value)): # continue #if np.radians(sigma.value)>np.radians(5.): # continue w = weight(oneW.value, eneMC.value, nEv.value) hEneW.Fill(log10(eneMC.value), w) hREneW.Fill(log10(ene.value), w) dAngle = SpaceAngleRad(MCzenith.value, MCazimuth.value, np.radians(SMPEzenith.value), np.radians(SMPEazimuth.value)) h.Fill(log10(ene.value), dAngle / np.radians(sigma.value), w) if h.GetXaxis().FindBin(log10(ene.value)) > 0 and h.GetXaxis().FindBin( log10(ene.value)) < 51: medians[h.GetXaxis().FindBin(log10(ene.value)) - 1].append( dAngle / np.radians(sigma.value)) mediansW[h.GetXaxis().FindBin(log10(ene.value)) - 1].append(w) #if i>200: #break npoints = 0 for i in range(1, h.GetNbinsX() + 1): if len(medians[i - 1]) > 3: g.SetPoint( npoints, h.GetXaxis().GetBinCenter(i), weighted_percentile(0.5, np.asarray(medians[i - 1]), np.asarray(mediansW[i - 1]))) g.SetPointError( npoints, 0., 0., weighted_percentile(0.5 - 0.341, np.asarray(medians[i - 1]), np.asarray(mediansW[i - 1])), weighted_percentile(0.5 + 0.341, np.asarray(medians[i - 1]), np.asarray(mediansW[i - 1]))) npoints += 1 c0 = TCanvas() hEneW.Draw() g.Set(npoints) g.SetMarkerStyle(20) gStyle.SetPalette(1) gStyle.SetOptLogz(1) spline = TSpline5("spl", TGraph(g)) filename = "SplineforCorr_IC79.root" #if hem(0.): # filename=filename+"down.root" #else: # filename=filename+"up.root" fout = TFile(filename, "RECREATE") spline.Write() fout.Close() #print "loading mpfSigmaDegRescaledIC79V2.C" #ROOT.gROOT.ProcessLine(".L mpfSigmaDegRescaledIC79V2.C+") print "loading RescaledSigma_IC79.C" ROOT.gROOT.ProcessLine(".L RescaledSigma_IC79.C+") try: ROOT.loadSplines() except: pass npoints = 0 for i in range(1, h.GetNbinsX() + 1): if len(medians[i - 1]) > 3: #if hem(0.): #plotZen=0. #else: #plotZen=100. #go.SetPoint(npoints,h.GetXaxis().GetBinCenter(i),ROOT.mpfSigmaDegRescaledIC79V2(1.,pow(10,h.GetXaxis().GetBinCenter(i)))) go.SetPoint( npoints, h.GetXaxis().GetBinCenter(i), ROOT.RescaledSigma_IC79(1., pow(10, h.GetXaxis().GetBinCenter(i)))) npoints += 1 go.Set(npoints) del medians[:] del medians del mediansW[:] del mediansW c = TCanvas() c.SetLogy() c.SetGridx() c.SetGridy() h.SetMinimum(1) h.Draw("colz") g.Draw("pl same") go.Draw("pl same") spline.Draw("lp same") h2 = TH2D("pull - corrected", "pull - corrected", 50, 1, 9, 100, 0.01, 20) h2.GetXaxis().SetTitle("log_{10}(E [GeV])") h2.GetYaxis().SetTitle("Pull_{corr}: #Delta#Psi/f_{corr}(#sigma_{parab.})") g2 = TGraphAsymmErrors(50) medians2 = [[] for i in range(0, 50)] medians2W = [[] for i in range(0, 50)] g2.SetMarkerStyle(20) for i in range(0, tr.GetEntries()): tr.GetEntry(i) #if not hem(np.radians(SMPEzenith.value)): continue #if np.radians(sigma.value)>np.radians(5.): # continue w = weight(oneW.value, eneMC.value, nEv.value) dAngle = SpaceAngleRad(MCzenith.value, MCazimuth.value, np.radians(SMPEzenith.value), np.radians(SMPEazimuth.value)) h2.Fill( log10(ene.value), dAngle / (np.radians(sigma.value) * spline.Eval(log10(ene.value))), w) if h.GetXaxis().FindBin(log10(ene.value)) > 0 and h.GetXaxis().FindBin( log10(ene.value)) < 51: medians2[h.GetXaxis().FindBin(log10(ene.value)) - 1].append( dAngle / (np.radians(sigma.value) * spline.Eval(log10(ene.value)))) medians2W[h.GetXaxis().FindBin(log10(ene.value)) - 1].append(w) #if i>200: #break npoints = 0 for i in range(1, h2.GetNbinsX() + 1): if len(medians2[i - 1]) > 3: g2.SetPoint( npoints, h.GetXaxis().GetBinCenter(i), weighted_percentile(0.5, np.asarray(medians2[i - 1]), np.asarray(medians2W[i - 1]))) g2.SetPointError( npoints, 0., 0., weighted_percentile(0.5 - 0.341, np.asarray(medians2[i - 1]), np.asarray(medians2W[i - 1])), weighted_percentile(0.5 + 0.341, np.asarray(medians2[i - 1]), np.asarray(medians2W[i - 1]))) npoints += 1 del medians2[:] del medians2 del medians2W[:] del medians2W g2.Set(npoints) c2 = TCanvas() c2.SetLogy() c2.SetGridx() c2.SetGridy() h2.SetStats(0) h2.SetMinimum(1) h2.Draw("colz") g2.Draw("pl same") h3 = TH2D("pull - corrected xcheck", "pull - corrected xcheck", 50, 1, 9, 100, 0.01, 20) h3.GetXaxis().SetTitle("log_{10}(E [GeV])") h3.GetYaxis().SetTitle("Pull_{corr}: #Delta#Psi/f_{corr}(#sigma_{parab.})") g3 = TGraphAsymmErrors(50) medians3 = [[] for i in range(0, 50)] medians3W = [[] for i in range(0, 50)] g3.SetMarkerStyle(20) SigmaBins = [(0.5, 0.6, 1), (0.6, 0.7, 2), (0.7, 0.9, 4), (0.9, 1.3, 1), (1.3, 1.7, 2)] h_pdf_corr = [] for b in range(len(SigmaBins)): h_pdf_corr.append( TH1D("h_pdf_corr" + str(b), "h_pdf_corr" + str(b) + ";#Delta#Psi [deg]", 50, 0, 3)) h_pdf_corr[-1].SetLineColor(SigmaBins[b][2]) h_pdf_corr[-1].SetLineWidth(2) for i in range(0, tr.GetEntries()): tr.GetEntry(i) #if not hem(np.radians(SMPEzenith.value)): continue #if np.radians(sigma.value)>np.radians(5.): # continue w = weight(oneW.value, eneMC.value, nEv.value) dAngle = SpaceAngleRad(MCzenith.value, MCazimuth.value, np.radians(SMPEzenith.value), np.radians(SMPEazimuth.value)) #pull=dAngle/ROOT.mpfSigmaDegRescaledIC79V2(np.radians(sigma.value),ene.value) #s_cor=ROOT.mpfSigmaDegRescaledIC79V2(np.radians(sigma.value),ene.value) pull = dAngle / ROOT.RescaledSigma_IC79(np.radians(sigma.value), ene.value) s_cor = ROOT.RescaledSigma_IC79(np.radians(sigma.value), ene.value) h3.Fill(log10(ene.value), pull, w) for b in range(len(SigmaBins)): if SigmaBins[b][0] <= np.degrees( s_cor) and SigmaBins[b][1] > np.degrees(s_cor): h_pdf_corr[b].Fill(np.degrees(dAngle), w) if h.GetXaxis().FindBin(log10(ene.value)) > 0 and h.GetXaxis().FindBin( log10(ene.value)) < 51: medians3[h.GetXaxis().FindBin(log10(ene.value)) - 1].append(pull) medians3W[h.GetXaxis().FindBin(log10(ene.value)) - 1].append(w) #if i>200: #break npoints = 0 for i in range(1, h2.GetNbinsX() + 1): if len(medians3[i - 1]) > 3: g3.SetPoint( npoints, h.GetXaxis().GetBinCenter(i), weighted_percentile(0.5, np.asarray(medians3[i - 1]), np.asarray(medians3W[i - 1]))) g3.SetPointError( npoints, 0., 0., weighted_percentile(0.5 - 0.341, np.asarray(medians3[i - 1]), np.asarray(medians3W[i - 1])), weighted_percentile(0.5 + 0.341, np.asarray(medians3[i - 1]), np.asarray(medians3W[i - 1]))) npoints += 1 c30 = TCanvas() leg = ROOT.TLegend(0.7, 0.7, 1., 1.) ffunc = [] for b in range(3): h_pdf_corr[b].Sumw2() if b == 0: h_pdf_corr[b].Draw("HIST") else: h_pdf_corr[b].Draw("same HIST") ffunc.append(TF1("ffunc" + str(b), CircGaus, 0.001, 3., 2)) ffunc[-1].SetLineColor(SigmaBins[b][2]) ffunc[-1].SetParameter(0, 1.) ffunc[-1].SetParameter(1, 1.) h_pdf_corr[b].Fit(ffunc[-1], "R") ffunc[-1].Draw("same") leg.AddEntry( h_pdf_corr[b], "range: " + str(SigmaBins[b][0]) + " to " + str(SigmaBins[b][1]) + " #sigma_{fit}=" + '{:.2f}'.format(ffunc[-1].GetParameter(0)), "l") leg.Draw() c31 = TCanvas() leg1 = ROOT.TLegend(0.7, 0.7, 1., 1.) ffunc = [] for b in range(3, 5): h_pdf_corr[b].Sumw2() if b == 0: h_pdf_corr[b].Draw("HIST") else: h_pdf_corr[b].Draw("same HIST") ffunc.append(TF1("ffunc" + str(b), CircGaus, 0.001, 3., 2)) ffunc[-1].SetLineColor(SigmaBins[b][2]) ffunc[-1].SetParameter(0, 1.) ffunc[-1].SetParameter(1, 1.) h_pdf_corr[b].Fit(ffunc[-1], "R") ffunc[-1].Draw("same") leg1.AddEntry( h_pdf_corr[b], "range: " + str(SigmaBins[b][0]) + " to " + str(SigmaBins[b][1]) + " #sigma_{fit}=" + '{:.2f}'.format(ffunc[-1].GetParameter(0)), "l") leg1.Draw() g3.Set(npoints) c3 = TCanvas() c3.SetLogy() c3.SetGridx() c3.SetGridy() h3.SetStats(0) h3.SetMinimum(1) h3.Draw("colz") g3.Draw("pl same") c3.SaveAs("mpfSigmaDegRescaledIC79V2_corrected.png") raw_input("Press Enter to continue...")
return legend thefile = TFile('rootFile/plots_DYMVA_SYS_2017_v6.root') thelist = thefile.GetListOfKeys() histos = {} values = {} errors = {} graphs = {} dymva = [0.05,0.2,0.4,0.6,0.75,0.825,0.875,0.9125,0.9375,0.9625,0.9875] e_dymva = [0.05,0.1,0.1,0.1,0.05,0.025,0.025,0.0125,0.0125,0.0125,0.0125] #loading DY histograms for dirs in thelist : histos['DY_'+dirs.GetName()] = thefile.Get(dirs.GetName()+'/dymva_alt_dnn_0j/histo_DY') histos['DATA_'+dirs.GetName()] = thefile.Get(dirs.GetName()+'/dymva_alt_dnn_0j/histo_DATA') histos['DYDATA_'+dirs.GetName()] = TH1D.Clone(histos['DATA_'+dirs.GetName()]) histos['AMC_'+dirs.GetName()] = TH1D.Clone(histos['DY_'+dirs.GetName()]) histos['VV_'+dirs.GetName()] = TH1D('VV_'+dirs.GetName(), 'VV_'+dirs.GetName(), histos['DY_'+dirs.GetName()].GetNbinsX(), histos['DY_'+dirs.GetName()].GetXaxis().GetXbins().GetArray()) # CREATING k histograms if 'in' in dirs.GetName() and not 'btag' in dirs.GetName() and not 'df' in dirs.GetName() and not 'H_' in dirs.GetName() and not 'ww_' in dirs.GetName() and not '1j' in dirs.GetName() and not '2j' in dirs.GetName() and not 'VBF' in dirs.GetName() and not 'VH' in dirs.GetName(): #print('Histos for K and R: ', dirs.GetName()) histos['k_MC_'+dirs.GetName()] = TH1D('k_MC_'+dirs.GetName(), 'k_MC_'+dirs.GetName(), histos['DY_'+dirs.GetName()].GetNbinsX(), histos['DY_'+dirs.GetName()].GetXaxis().GetXbins().GetArray()) histos['k_DATA_'+dirs.GetName()] = TH1D('k_DATA_'+dirs.GetName(), 'k_DATA_'+dirs.GetName(), histos['DATA_'+dirs.GetName()].GetNbinsX(), histos['DATA_'+dirs.GetName()].GetXaxis().GetXbins().GetArray()) # CREATING R histograms if 'out' in dirs.GetName() and not 'df' in dirs.GetName() and not 'H_' in dirs.GetName() and not 'ww_' in dirs.GetName(): #print('R dirs', dirs.GetName()) histos['R_MC_'+dirs.GetName()] = TH1D('R_MC_'+dirs.GetName(), 'R_MC_'+dirs.GetName(), histos['DY_'+dirs.GetName()].GetNbinsX(), histos['DY_'+dirs.GetName()].GetXaxis().GetXbins().GetArray()) histos['R_DATA_'+dirs.GetName()] = TH1D('R_DATA_'+dirs.GetName(), 'R_DATA_'+dirs.GetName(), histos['DATA_'+dirs.GetName()].GetNbinsX(), histos['DATA_'+dirs.GetName()].GetXaxis().GetXbins().GetArray()) histos['DATA_fromR_'+dirs.GetName()] = TH1D('DATA_fromR_'+dirs.GetName(), 'DATA_fromR_'+dirs.GetName(), histos['DATA_'+dirs.GetName()].GetNbinsX(), histos['DATA_'+dirs.GetName()].GetXaxis().GetXbins().GetArray()) histos['R_fromDATAR_'+dirs.GetName()] = TH1D('R_fromDATAR_'+dirs.GetName(), 'R_fromDATAR_'+dirs.GetName(), histos['DATA_'+dirs.GetName()].GetNbinsX(), histos['DATA_'+dirs.GetName()].GetXaxis().GetXbins().GetArray())
bin_end = 10000 if mass >= 4000: binsize = 1 bin_end = 2000 if mass >= 5000: binsize = 0.2 bin_end = 1000 if mass >= 6000: binsize = 0.1 bin_end = 500 if mass >= 6500: binsize = 0.05 bin_end = 250 bins = int(bin_end / binsize) hist = TH1D("dist{0}".format(mass), "dist", bins, 0, bin_end) r = TRandom1() expected_limits_file = op.join(args.expected_limit_dir, mass_folder, "combined-{}.txt".format(mass)) with open(expected_limits_file, "r") as result_file: for i, line in enumerate(result_file.readlines()): if len(line) == 0: continue limit = float(line) lum = r.Gaus(fb, 0.032 * fb) limit2 = fb * limit / lum #if i % 1000 == 0: # print(limit, lum, limit2) hist.Fill(limit2) #hist.Fill(fb*limit/r.Gaus(fb, 0.032*fb))
def histo(*args): histos[args[0]] = TH1D(*args)
#!/usr/bin/python from ROOT import TH1D import sys data = [] fl = open(sys.argv[1]) h = TH1D("hist", "Histogram", 1000, -1, 100) for line in fl: h.Fill(float(line.split()[int(sys.argv[2])])) h.Draw() raw_input()
valphys = {} valsyst = {} runSyst = False c1 = TCanvas("c1", "c1", 1) ## Import all measurements ## Meas 1 ### Import the file myfile["meas1"] = TFile("%s" % options.input) ## and then get the TTree mytree["meas1"] = myfile["meas1"].Get("tree") ## FastFrame ### First create an empty TH1D histogram myhist["meas1"] = TH1D("myhist_meas1", "meas1", 256, 0, 8) ### Then get the saved histogram into the new one and normalize to ns from s by *1.e9 mytree["meas1"].Draw("area*1.e9>>myhist_meas1", "", "") today = datetime.date.today() fTag = today.strftime("%Y%m%d") fName = options.input i = fName.find("/") while i > 0: fName = fName[i + 1:] i = fName.find("/") fName = fName[:-5] myhist["meas1"].SetTitle("%s" % fName) myhist["meas1"].GetXaxis().SetTitle("area [V#times ns]") myhist["meas1"].GetYaxis().SetTitle("counts")
def __init__(self, name, dataType, **kwargs): print 'TreeProducerCommon is called for', name self.name = name self._isData = dataType=='data' self._isEmb = dataType=='emb' self.doJECSys = kwargs.get('doJECSys', True ) and not self._isData ###self.isVectorLQ = kwargs.get('isVectorLQ', 'VectorLQ' in self.name ) # TREE self.outputfile = TFile(name, 'RECREATE') self.tree = TTree('tree','tree') # HISTOGRAM self.cutflow = TH1D('cutflow', 'cutflow', 25, 0, 25) self.pileup = TH1D('pileup', 'pileup', 100, 0, 100) #### CHECK genPartFlav ###self.flags_LTF_DM1 = TH1D('flags_LTF_DM1', "flags for l #rightarrow #tau_{h}, DM1", 18, 0, 18) ###self.flags_LTF_DM0 = TH1D('flags_LTF_DM0', "flags for l #rightarrow #tau_{h}, DM0", 18, 0, 18) ###self.flags_LTF_mis = TH1D('flags_LTF_mis', "flags for l #rightarrow #tau_{h}, DM1, wrong genPartFlav", 18, 0, 18) ###self.flags_LTF_DM1_sn1 = TH1D('flags_LTF_DM1_sn1', "flags for l #rightarrow #tau_{h}, DM1 (status!=1)", 18, 0, 18) ###self.flags_LTF_DM0_sn1 = TH1D('flags_LTF_DM0_sn1', "flags for l #rightarrow #tau_{h}, DM0 (status!=1)", 18, 0, 18) ###self.flags_LTF_mis_sn1 = TH1D('flags_LTF_mis_sn1', "flags for l #rightarrow #tau_{h}, DM1, wrong genPartFlav (status!=1)", 18, 0, 18) ###for hist in [self.flags_LTF_DM1, self.flags_LTF_DM0, self.flags_LTF_mis, self.flags_LTF_DM0_sn1, self.flags_LTF_DM1_sn1, self.flags_LTF_mis_sn1]: ### hist.GetXaxis().SetBinLabel( 1, "isPrompt" ) ### hist.GetXaxis().SetBinLabel( 2, "isDirectPromptTauDecayProduct" ) ### hist.GetXaxis().SetBinLabel( 3, "isHardProcess" ) ### hist.GetXaxis().SetBinLabel( 4, "fromHardProcess" ) ### hist.GetXaxis().SetBinLabel( 5, "isDirectHardProcessTauDecayProduct" ) ### hist.GetXaxis().SetBinLabel( 6, "fromHardProcessBeforeFSR" ) ### hist.GetXaxis().SetBinLabel( 7, "isFirstCopy" ) ### hist.GetXaxis().SetBinLabel( 8, "isLastCopy" ) ### hist.GetXaxis().SetBinLabel( 9, "isLastCopyBeforeFSR" ) ### hist.GetXaxis().SetBinLabel(10, "status==1" ) ### hist.GetXaxis().SetBinLabel(11, "status==23" ) ### hist.GetXaxis().SetBinLabel(12, "status==44" ) ### hist.GetXaxis().SetBinLabel(13, "status==51" ) ### hist.GetXaxis().SetBinLabel(14, "status==52" ) ### hist.GetXaxis().SetBinLabel(15, "other status" ) ### hist.GetXaxis().SetLabelSize(0.041) ###self.genmatch_corr = TH2D("genmatch_corr","correlation between Tau_genPartFlav and genmatch",6,0,6,6,0,6) ###self.genmatch_corr_DM0 = TH2D("genmatch_corr_DM0","correlation between Tau_genPartFlav and genmatch for DM0",6,0,6,6,0,6) ###self.genmatch_corr_DM1 = TH2D("genmatch_corr_DM1","correlation between Tau_genPartFlav and genmatch for DM1",6,0,6,6,0,6) ############# # EVENT # ############# self.addBranch('run', 'i') self.addBranch('lumi', 'i') self.addBranch('event', 'i') self.addBranch('isData', '?', self._isData) self.addBranch('isEmb', '?', self._isEmb) self.addBranch('npvs', 'i') self.addBranch('npvsGood', 'i') self.addBranch('metfilter', '?') if not any(x for x in [self._isData, self._isEmb]): self.addBranch('nPU', 'i', -1) self.addBranch('nTrueInt', 'i', -1) self.addBranch('LHE_Njets', 'i', -1) ############## # WEIGHT # ############## if not self._isData: self.addBranch('weight', 'f', 1.) self.addBranch('genweight', 'f', 1.) self.addBranch('trigweight', 'f', 1.) self.addBranch('puweight', 'f', 1.) self.addBranch('idisoweight_1', 'f', 1.) self.addBranch('idisoweight_2', 'f', 1.) self.addBranch('zptweight', 'f', 1.) self.addBranch('ttptweight', 'f', 1.) self.addBranch('btagweight', 'f', 1.) self.addBranch('btagweight_loose', 'f', 1.) self.addBranch('btagweight50', 'f', 1.) self.addBranch('btagweight50_loose', 'f', 1.) if self._isEmb: self.addBranch('embselweight', 'f', 1.) ############ # JETS # ############ self.addBranch('njets', 'i') self.addBranch('njets50', 'i') self.addBranch('ncjets', 'i') self.addBranch('nfjets', 'i') self.addBranch('nbtag', 'i') self.addBranch('nbtag50', 'i') self.addBranch('nbtag_loose', 'i') self.addBranch('nbtag50_loose', 'i') self.addBranch('jpt_1', 'f') self.addBranch('jeta_1', 'f') self.addBranch('jphi_1', 'f') self.addBranch('jdeepb_1', 'f') self.addBranch('jpt_2', 'f') self.addBranch('jeta_2', 'f') self.addBranch('jphi_2', 'f') self.addBranch('jdeepb_2', 'f') self.addBranch('bpt_1', 'f') self.addBranch('beta_1', 'f') self.addBranch('bpt_2', 'f') self.addBranch('beta_2', 'f') if self.doJECSys: for uncertainty in ['jer','jes']: for variation in ['Down','Up']: label = '_'+uncertainty+variation self.addBranch('njets'+label, 'i') self.addBranch('njets50'+label, 'i') self.addBranch('nbtag50'+label, 'i') self.addBranch('nbtag50_loose'+label, 'i') self.addBranch('jpt_1'+label, 'f') self.addBranch('jpt_2'+label, 'f') self.addBranch('met', 'f') self.addBranch('metphi', 'f') ###self.addBranch('puppimet', 'f') ###self.addBranch('puppimetphi', 'f') ###self.addBranch('metsignificance', 'f') ###self.addBranch('metcovXX', 'f') ###self.addBranch('metcovXY', 'f') ###self.addBranch('metcovYY', 'f') ###self.addBranch('fixedGridRhoFastjetAll', 'f') if not any(x for x in [self._isData, self._isEmb]): self.addBranch('genmet', 'f', -1) self.addBranch('genmetphi', 'f', -9) ############# # OTHER # ############# self.addBranch('pfmt_1', 'f') self.addBranch('pfmt_2', 'f') self.addBranch('m_vis', 'f') self.addBranch('pt_ll', 'f') self.addBranch('dR_ll', 'f') self.addBranch('dphi_ll', 'f') self.addBranch('deta_ll', 'f') self.addBranch('chi', 'f') self.addBranch('pzetamiss', 'f') self.addBranch('pzetavis', 'f') self.addBranch('dzeta', 'f') if self.doJECSys: for uncertainty in ['jer','jes','unclEn']: for variation in ['Down','Up']: label = '_'+uncertainty+variation self.addBranch('met'+label, 'f') self.addBranch('pfmt_1'+label, 'f') self.addBranch('dzeta'+label, 'f') self.addBranch('dilepton_veto', '?') self.addBranch('extraelec_veto', '?') self.addBranch('extramuon_veto', '?') self.addBranch('lepton_vetos', '?') self.addBranch('lepton_vetos_noTau', '?') if not self._isData: ###self.addBranch('ngentauhads', 'i', -1) ###self.addBranch('ngentaus', 'i', -1) self.addBranch('m_genboson', 'f', -1) self.addBranch('pt_genboson', 'f', -1)
### output of createHistos.py # open root file with found peak histograms if len(sys.argv) > 1: filename = sys.argv[1] print "input filename is ", filename f = TFile.Open(filename, "read") dirlist = f.GetListOfKeys() iter = dirlist.MakeIterator() key = iter.Next() histos = {} bigpeaks = {} fout = TFile.Open("summed.root", "RECREATE") hout = TH1D("hout", "peaks", 80, 0, 80) histo = None while key: if key.GetClassName() == 'TH1D': histo = key.ReadObj() hName = histo.GetName() print "found histogram", hName, histos[hName] = histo val = fit(histo) if val > 50: bigpeaks[hName] = val print val hout.Fill(val) key = iter.Next()
# ============================================================================== print "==================================== TRAIN ====================================" response= RooUnfoldResponse (40, -10.0, 10.0); # Train with a Breit-Wigner, mean 0.3 and width 2.5. for i in xrange(100000): xt= gRandom.BreitWigner (0.3, 2.5); x= smear (xt); if x!=None: response.Fill (x, xt); else: response.Miss (xt); print "==================================== TEST =====================================" hTrue= TH1D ("true", "Test Truth", 40, -10.0, 10.0); hMeas= TH1D ("meas", "Test Measured", 40, -10.0, 10.0); # Test with a Gaussian, mean 0 and width 2. for i in xrange(10000): xt= gRandom.Gaus (0.0, 2.0) x= smear (xt); hTrue.Fill(xt); if x!=None: hMeas.Fill(x); print "==================================== UNFOLD ===================================" unfold= RooUnfoldBayes (response, hMeas, 4); # OR # unfold= RooUnfoldSvd (response, hMeas, 20); # OR # unfold= RooUnfoldTUnfold (response, hMeas); # OR # unfold= RooUnfoldIds (response, hMeas, 3); # OR hReco= unfold.Hreco();
def test_unroll(fname, xvars, yvars, cut="", verb=0): """Test unrolling of 2D histogram and create 4D response matrix.""" if verb >= 1: print ">>> test_unroll(%s)" % (fname) start = time() file = TFile(fname, 'READ') assert file and not file.IsZombie(), "Could not open %s" % (fname) tree = file.Get('tree') assert tree and tree.GetEntries() > 10, "Could find TTree 'tree' in %s" % ( fname) hists = [] xvar1, xvar2 = xvars[:2] yvar1, yvar2 = yvars[:2] #xbins = xvars[2:] #ybins = yvars[2:] nxbins, xmin, xmax = xvars[2:] nybins, ymin, ymax = yvars[2:] #nxbins, nybins = xbins[0], ybins[0] nbins = nxbins * nybins hname2d = "testUnroll_%s-%s" % (vardict.get( yvar1, yvar1), vardict.get(xvar1, xvar1)) hname2dcpp = "testUnroll_%s-%s_rolledup_cpp" % (vardict.get( yvar1, yvar1), vardict.get(xvar1, xvar1)) hname4d = "testUnroll_response" hnamepy = "%s_unrolled_py" % (hname2d) hnamecpp = "%s_unrolled_cpp" % (hname2d) xtitle = titledict.get(xvar1, xvar1) ytitle = titledict.get(yvar1, yvar1) xtitle1d = "bin(%s,%s)" % (xtitle, ytitle) xtitle4d = "bin(%s,%s)" % (titledict.get( xvar2, xvar2), titledict.get(yvar2, yvar2)) ytitle4d = xtitle1d # CREATE HISTOGRAMS #hist1 = TH1D(hname1,hname1,*xbins) histpy = TH1D(hnamepy, hnamepy, nbins, 1, 1 + nbins) # unrolled hist2d = TH2D(hname2d, hname2d, nxbins, xmin, xmax, nybins, ymin, ymax) #*(xbins+ybins) hist4d = TH2D(hname4d, hname4d, nbins, 1, 1 + nbins, nbins, 1, 1 + nbins) # response / migration matrix tree.Draw("%s:%s >> %s" % (yvar1, xvar1, hname2d), cut, 'gOFF') Unroll.SetBins(hist2d, verb) # set axis for unrolling in Unroll::GetBin histcpp = Unroll.Unroll(hist2d, hnamecpp, False, verb) # unrolled tree.Draw("Unroll::GetBin(%s,%s) >> %s" % (xvar1, yvar1, hnamepy), cut, 'gOFF') # unrolled tree.Draw("Unroll::GetBin(%s,%s):Unroll::GetBin(%s,%s) >> %s" % (xvar2, yvar2, xvar1, yvar1, hname4d), cut, 'gOFF') # x: reco, y: gen hist2dcpp = Unroll.RollUp(histcpp, hname2dcpp, hist2d, verb) # rolled up #hist = TH2F(hname,hname,nbins,xmin,xmax) #tree.Draw("%s:%s >> %s"%(xvar,yvar,hname),"(%s)*%s"%(cut,weight),'gOFF') # DRAW for vars in [xvars, yvars]: nabins, amin, amax = vars[2:] for avar in vars[:2]: hname = "testUnroll_%s" % (vardict.get(avar, avar)) hist1d = TH1D(hname, hname, nabins, amin, amax) tree.Draw("%s >> %s" % (avar, hname), cut, 'gOFF') atitle = titledict.get(avar, avar) draw(hist1d, atitle) draw(histpy, xtitle1d, nbins=nybins) # rolled up draw(histcpp, xtitle1d, nbins=nybins) # rolled up draw2d(hist2d, xtitle, ytitle, number=True) # original draw2d(hist2dcpp, xtitle, ytitle, number=True) # rolled back up draw2d(hist4d, xtitle4d, ytitle4d, nxbins=nybins, nybins=nybins) # response matrix # TEST Unroll::GetBin nx, ny = 2 * nxbins, 2 * nybins # number of points to scan xbinw = float(xmax - xmin) / nx ybinw = float(ymax - ymin) / ny print ">>> nxbins=%s, xmin=%s, xmax=%s" % (nxbins, xmin, xmax) print ">>> nybins=%s, ymin=%s, ymax=%s" % (nybins, ymin, ymax) print ">>> nx=%s, xbinw=%s, ny=%s, ybinw=%s" % (nx, xbinw, ny, ybinw) xvals = [xmin + xbinw * i for i in range(-2, nx + 3)] yvals = [ymin + ybinw * i for i in range(-2, ny + 3)] #xvals = [-1,0,1,10,50,100,200] #yvals = [-1,0,1,10,50,100,200] print ">>>" print ">>> %7s |" % (r'y\x') + ' '.join("%6s" % x for x in xvals) print ">>> %8s+" % ('-' * 7) + '-' * 7 * len(xvals) for y in yvals: #print ">>> %7s |"%x+' '.join("%6s"%(Unroll.GetBin(x,y)) for x in xvals) row = ">>> %7s |" % y for x in xvals: bin = Unroll.GetBin(x, y) str = "%6s " % (bin) if bin < 1 or bin >= nxbins * nybins + 1: str = red(str) row += str print row print ">>>" print ">>> Took %.2fs" % (time() - start)
# # # # ## #printing# # # plt.figure(1) plt.title("Costfunction of (modified) Training-data") plt.xlabel("epochs") plt.ylabel("cost function") x_range = [x + 1 for x in range(0, N_epochs)] plt.plot(x_range, cost_training_data) plt.savefig("cost_on_training_data.png") plt.figure(2) plt.title("f data") plt.xlabel("epochs") plt.ylabel("total error on validation data") x_range = [x + 1 for x in range(0, N_epochs)] plt.plot(x_range, error_validation_data) plt.savefig("error_on_val_data.png") error_on_validation_data_after_training = diff_validation[-1].reshape( (1, validation_set.get_N())) hist = TH1D('hist', "Errors on val data after last training epoch", 200, -10000, 10000) fill_hist(hist, error_on_validation_data_after_training[0]) canvas = TCanvas() hist.GetXaxis().SetTitle("desired Chi^2- outputted Chi^2") hist.Draw() canvas.SaveAs('error_on_val_data_hist.png')
def compareDatasets(trigger, leg, datasets, lineColors, legendLabels, axisTitle, canvas, dataLumi, metHLTFilters, outputSuffix = None): inputFiles = [TFile.Open("triggerEfficiency_" + x + ".root") for x in datasets] efficiencies = [x.Get(trigger + "_" + leg) for x in inputFiles] for iEff in range(len(efficiencies)): SetStyle(efficiencies[iEff]) efficiencies[iEff].SetLineColor(lineColors[iEff]) efficiencies[iEff].SetMarkerColor(lineColors[iEff]) oneLine = TLine(xlo, 1.0, xhi, 1.0) oneLine.SetLineWidth(3) oneLine.SetLineStyle(2) backgroundHist = TH1D("backgroundHist", "backgroundHist", 1, xlo, xhi) backgroundHist.GetYaxis().SetTitle("Trigger Efficiency") backgroundHist.GetYaxis().SetRangeUser(ylo, yhi) backgroundHist.GetXaxis().SetTitle(axisTitle) SetStyle(backgroundHist) canvas.cd() backgroundHist.Draw() for eff in efficiencies: eff.Draw("CP same") #oneLine.Draw("same") pt_cmsPrelim = TPaveText(0.132832, 0.859453, 0.486216, 0.906716, "brNDC") pt_cmsPrelim.SetBorderSize(0) pt_cmsPrelim.SetFillStyle(0) pt_cmsPrelim.SetTextFont(62) pt_cmsPrelim.SetTextSize(0.0374065) if dataLumi > 0: pt_cmsPrelim.AddText("CMS Preliminary") else: pt_cmsPrelim.AddText("CMS Simulation") pt_cmsPrelim.Draw("same") if dataLumi > 0: pt_lumi = TPaveText(0.744361, 0.92928, 0.860902, 0.977667, "brNDC") pt_lumi.SetBorderSize(0) pt_lumi.SetFillStyle(0) pt_lumi.SetTextFont(42) pt_lumi.SetTextSize(0.0374065) pt_lumi.AddText("{:.2f}".format(dataLumi / 1000.0) + " fb^{-1}, 13 TeV") pt_lumi.Draw("same") pt_leg = TPaveText(0.160401, 0.768657, 0.342105, 0.863184, "brNDC") pt_leg.SetBorderSize(0) pt_leg.SetFillStyle(0) pt_leg.SetTextFont(42) pt_leg.SetTextSize(0.025) pt_leg.SetTextAlign(12) if leg == "METLeg": legLabel = "" for filt in metHLTFilters[:-1]: legLabel = legLabel + filt + ", " legLabel = legLabel + metHLTFilters[-1] pt_leg.AddText(legLabel) if leg == "TrackLeg": pt_leg.AddText(trigger + "*") legLabel = "" for filt in metHLTFilters[:-1]: legLabel = legLabel + filt + ", " legLabel = legLabel + metHLTFilters[-1] + " applied" pt_leg.AddText(legLabel) if leg == "METPath": if trigger == "GrandOr": pt_leg.AddText("OR of Signal Paths") else: if len(trigger) > 25 and len(trigger.split("_")) > 2: firstLine = trigger.split("_")[0] + "_" + trigger.split("_")[1] + "_" pt_leg.AddText(firstLine) secondLine = "" for line in trigger.split("_")[2:-1]: secondLine += line + "_" secondLine += trigger.split("_")[-1] + "*" pt_leg.AddText(secondLine) else: pt_leg.AddText(trigger + "*") pt_leg.Draw("same") legendLabel = trigger legend = TLegend(0.65, 0.75, 0.93, 0.88) legend.SetBorderSize(0) legend.SetFillColor(0) legend.SetFillStyle(0) legend.SetTextFont(42) if leg == 'METLeg': legend.SetHeader('MET Leg') elif leg == 'TrackLeg': legend.SetHeader('Track Leg') for iEff in range(len(efficiencies)): legend.AddEntry(efficiencies[iEff], legendLabels[iEff], 'P') legend.Draw("same") if outputSuffix is not None: canvas.SaveAs('compareDatasets_' + trigger + '_' + leg + '_' + outputSuffix + '.pdf') else: canvas.SaveAs('compareDatasets_' + trigger + '_' + leg + '_.pdf') for inputFile in inputFiles: inputFile.Close() return
if not len(sys.argv) == 5: print "usage is scaleInputHistos.py inputFileName outputFileName oldLumi newLumi" sys.exit(1) inputFile = TFile(sys.argv[1],"READ") outputFile = TFile(sys.argv[2],"RECREATE") oldLumi = float(sys.argv[3]) newLumi = float(sys.argv[4]) keyIter = inputFile.GetListOfKeys().MakeIterator() key = keyIter.Next() newHists = [] while key: hist = TH1D(inputFile.Get(key.GetName())) hist.Scale(newLumi/oldLumi) newHists.append(hist) key = keyIter.Next() outputFile.cd() for hist in newHists: hist.Write() outputFile.Close() inputFile.Close()
def compare(trigger, leg, data, mc, axisTitle, canvas, dataLumi, metHLTFilters): dataFile = TFile.Open("triggerEfficiency_" + data + ".root", "read") mcFile = TFile.Open("triggerEfficiency_" + mc + ".root", "read") dataEff = dataFile.Get(trigger + "_" + leg) mcEff = mcFile.Get(trigger + "_" + leg) SetStyle(dataEff) SetStyle(mcEff) mcEff.SetLineColor(600) mcEff.SetMarkerColor(600) oneLine = TLine(xlo, 1.0, xhi, 1.0) oneLine.SetLineWidth(3) oneLine.SetLineStyle(2) backgroundHist = TH1D("backgroundHist", "backgroundHist", 1, xlo, xhi) backgroundHist.GetYaxis().SetTitle("Trigger Efficiency") backgroundHist.GetYaxis().SetRangeUser(ylo, yhi) backgroundHist.GetXaxis().SetTitle(axisTitle) SetStyle(backgroundHist) canvas.cd() backgroundHist.Draw() dataEff.Draw("CP same") mcEff.Draw("CP same") #oneLine.Draw("same") pt_cmsPrelim = TPaveText(0.132832, 0.859453, 0.486216, 0.906716, "brNDC") pt_cmsPrelim.SetBorderSize(0) pt_cmsPrelim.SetFillStyle(0) pt_cmsPrelim.SetTextFont(62) pt_cmsPrelim.SetTextSize(0.0374065) pt_cmsPrelim.AddText("CMS Preliminary") pt_cmsPrelim.Draw("same") pt_lumi = TPaveText(0.744361, 0.92928, 0.860902, 0.977667, "brNDC") pt_lumi.SetBorderSize(0) pt_lumi.SetFillStyle(0) pt_lumi.SetTextFont(42) pt_lumi.SetTextSize(0.0374065) pt_lumi.AddText("{:.2f}".format(dataLumi / 1000.0) + " fb^{-1}, 13 TeV") pt_lumi.Draw("same") pt_leg = TPaveText(0.160401, 0.768657, 0.342105, 0.863184, "brNDC") pt_leg.SetBorderSize(0) pt_leg.SetFillStyle(0) pt_leg.SetTextFont(42) pt_leg.SetTextSize(0.025) pt_leg.SetTextAlign(12) if leg == "METLeg": legLabel = "" for filt in metHLTFilters[:-1]: legLabel = legLabel + filt + ", " legLabel = legLabel + metHLTFilters[-1] pt_leg.AddText(legLabel) if leg == "TrackLeg": pt_leg.AddText(trigger + "*") legLabel = "" for filt in metHLTFilters[:-1]: legLabel = legLabel + filt + ", " legLabel = legLabel + metHLTFilters[-1] + " applied" pt_leg.AddText(legLabel) if leg == "METPath": if trigger == "GrandOr": pt_leg.AddText("OR of Signal Paths") else: if len(trigger) > 25 and len(trigger.split("_")) > 2: firstLine = trigger.split("_")[0] + "_" + trigger.split("_")[1] + "_" pt_leg.AddText(firstLine) secondLine = "" for line in trigger.split("_")[2:-1]: secondLine += line + "_" secondLine += trigger.split("_")[-1] + "*" pt_leg.AddText(secondLine) else: pt_leg.AddText(trigger + "*") pt_leg.Draw("same") dataLabel = '2015 data' if '2016BC' in data: dataLabel = '2016 B+C data' if '2016DEFGH' in data: dataLabel = '2016 D-H data' if '2017' in data: dataLabel = '2017 data' if '2018' in data: dataLabel = '2018 data' legendLabel = trigger legend = TLegend(0.65, 0.75, 0.93, 0.88) legend.SetBorderSize(0) legend.SetFillColor(0) legend.SetFillStyle(0) legend.SetTextFont(42) if leg == 'METLeg': legend.SetHeader('MET Leg') elif leg == 'TrackLeg': legend.SetHeader('Track Leg') legend.AddEntry(dataEff, dataLabel, 'P') legend.AddEntry(mcEff, 'W #rightarrow l#nu MC', 'P') legend.Draw("same") outputDirectory = 'plots_compare' if 'BC' in data: outputDirectory = 'plots_compareBC' if 'DEFGH' in data: outputDirectory = 'plots_compareDEFGH' if not os.path.exists(outputDirectory): os.mkdir(outputDirectory) canvas.SaveAs(outputDirectory + '/' + trigger + '_' + leg + '.pdf') mcFile.Close() dataFile.Close() return
def generatePDFs(ma=0): """ Generate a set of TH1D's to be turned into RooDataHist objects. Takes axion mass (in keV) as a parameter. Full suite of diganostic plots is in ./sandbox/specPlots.py Make the binning 0.02 keV intervals - hopefully that's fine enough. TODO: BDM/ALP pdf Get from Kris's analysis in GAT TODO: WIMP pdf? Get PyWIMP from Graham """ f = TFile("./data/inputHists.root", "RECREATE") redondoScale = 1e19 * 0.511e-10**-2 # convert table to [cts / (keV cm^2 d)] axData, phoData, tritData = [], [], [] with open("./data/redondoFlux.txt") as f1: # 23577 entries lines = f1.readlines()[11:] for line in lines: data = line.split() axData.append([float(data[0]), float(data[1])]) with open("./data/ge76peXS.txt") as f2: # 2499 entries, 0.01 kev intervals lines = f2.readlines() for line in lines: data = line.split() phoData.append([float(data[0]), float(data[1])]) with open("./data/TritiumSpectrum.txt") as f3: # 20000 entries lines = f3.readlines()[1:] for line in lines: data = line.split() conv = float(data[2]) # raw spectrum convolved w/ ge cross section if conv < 0: conv = 0. tritData.append([float(data[1]), conv]) axData, phoData, tritData = np.array(axData), np.array(phoData), np.array( tritData) def sig_ae(E, m): beta = (1 - m**2. / E**2.)**(1. / 2) return (1 - (1. / 3.) * beta**(2. / 3.)) * (3. * E**2.) / (16. * np.pi * (1. / 137.) * 511.**2. * beta) kpb = 0.02 eLo, eHi = 0.1, 30. nBins = int((eHi - eLo) / kpb) h1 = TH1D("h1", "photoelectric", nBins, eLo, eHi) # [cm^2 / kg] h2 = TH1D("h2", "axioelectric", nBins, eLo, eHi) # [cm^2 / kg] h3 = TH1D("h3", "axion flux", nBins, eLo, eHi) # [cts / (keV cm^2 d)] h4 = TH1D("h4", "convolved flux", nBins, eLo, eHi) # [cts / (keV d kg)] h5 = TH1D("h5", "tritium", nBins, eLo, eHi) # [cts] (normalized to 1) for i in range(nBins): ene = i * kpb + eLo eneLo, eneHi = ene - kpb / 2., ene + kpb / 2. with warnings.catch_warnings(): warnings.simplefilter("ignore", category=RuntimeWarning) # if ma>0, we ignore entries with E <= m. # photoelectric x-section [cm^2 / kg] idx = np.where((phoData[:, 0] >= eneLo) & (phoData[:, 0] <= eneHi)) pho = np.mean(phoData[idx][:, 1]) * 1000 if np.isnan(pho) or len(phoData[idx][:, 1]) == 0: pho = 0. if phoData[idx][:, 1] <= ma: pho = 0. h1.SetBinContent(i, pho) # axioelectric x-section [cm^2 / kg] if ene > ma: axio = pho * sig_ae(ene, ma) else: axio = 0. h2.SetBinContent(i, axio) # axion flux [cts / (cm^2 d keV)] idx = np.where((axData[:, 0] >= eneLo) & (axData[:, 0] <= eneHi)) flux = np.mean(axData[idx][:, 1]) * redondoScale if np.isnan(flux): flux = 0. h3.SetBinContent(i, flux) # axion flux convolved [cts / (keV d kg)] axConv = axio * flux h4.SetBinContent(i, axConv) # tritium idx = np.where((tritData[:, 0] >= eneLo) & (tritData[:, 0] <= eneHi)) trit = np.mean(tritData[idx][:, 1]) if np.isnan(trit): trit = 0. h5.SetBinContent(i, trit) h1.Write() h2.Write() h3.Write() h4.Write() h5.Write() f.Close()
def plotEfficiency(self, doFit = False): if hasattr(self, "Denominator") and hasattr(self, "Numerator"): if self._rebinFactor != 1: self.Denominator["hist"].Rebin(self._rebinFactor) self.Numerator["hist"].Rebin(self._rebinFactor) for ibin in range(-1, self.Numerator["hist"].GetNbinsX()+1): if self.Numerator["hist"].GetBinContent(ibin+1) > self.Denominator["hist"].GetBinContent(ibin+1): print('Fixing bad bin:', (ibin+1)) self.Numerator["hist"].SetBinContent(ibin+1, self.Denominator["hist"].GetBinContent(ibin+1)) self.Numerator["hist"].SetBinError(ibin+1, self.Denominator["hist"].GetBinError(ibin+1)) efficiencyGraph = TGraphAsymmErrors(self.Numerator["hist"], self.Denominator["hist"], "cp") pt_cmsPrelim = TPaveText(0.132832, 0.859453, 0.486216, 0.906716, "brNDC") pt_cmsPrelim.SetBorderSize(0) pt_cmsPrelim.SetFillStyle(0) pt_cmsPrelim.SetTextFont(62) pt_cmsPrelim.SetTextSize(0.0374065) pt_cmsPrelim.AddText("CMS Preliminary") pt_lumi = TPaveText(0.744361, 0.92928, 0.860902, 0.977667, "brNDC") pt_lumi.SetBorderSize(0) pt_lumi.SetFillStyle(0) pt_lumi.SetTextFont(42) pt_lumi.SetTextSize(0.0374065) pt_lumi.AddText(self._luminosityLabel) pt_leg = TPaveText(0.160401, 0.768657, 0.342105, 0.863184, "brNDC") pt_leg.SetBorderSize(0) pt_leg.SetFillStyle(0) pt_leg.SetTextFont(42) pt_leg.SetTextSize(0.0349127) pt_leg.SetTextAlign(12) if self._leg == "METLeg": legLabel = "" for filt in self._metHLTFilters[:-1]: legLabel = legLabel + filt + ", " legLabel = legLabel + self._metHLTFilters[-1] pt_leg.AddText(legLabel) pt_leg.AddText(self._datasetLabel) if self._leg == "TrackLeg": pt_leg.AddText(self._path + "*") pt_leg.AddText(self._datasetLabel) legLabel = "" for filt in self._metHLTFilters[:-1]: legLabel = legLabel + filt + ", " legLabel = legLabel + self._metHLTFilters[-1] + " applied" pt_leg.AddText(legLabel) if self._leg == "METPath": if self._path == "GrandOr": pt_leg.AddText("OR of Signal Paths") else: pt_leg.AddText(self._path + "*") pt_leg.AddText(self._datasetLabel) lumiLabel = TPaveText(0.66416, 0.937339, 0.962406, 0.992894, "brNDC") lumiLabel.SetBorderSize(0) lumiLabel.SetFillStyle(0) lumiLabel.SetTextFont(42) lumiLabel.SetTextSize(0.0387597) lumiLabel.AddText(str (self._luminosityLabel)) oneLine = TLine(xlo, 1.0, xhi, 1.0) oneLine.SetLineWidth(3) oneLine.SetLineStyle(2) backgroundHist = TH1D("backgroundHist", "backgroundHist", 1, xlo, xhi) backgroundHist.GetYaxis().SetTitle("Trigger Efficiency") backgroundHist.GetYaxis().SetRangeUser(ylo, yhi) if self._leg == "METLeg" or self._leg == "METPath": backgroundHist.GetXaxis().SetTitle(self._metLegAxisTitle) elif self._leg == "TrackLeg": backgroundHist.GetXaxis().SetTitle(self._trackLegAxisTitle) SetStyle(backgroundHist) SetStyle(efficiencyGraph) self._canvas.cd() backgroundHist.Draw() efficiencyGraph.Draw("P") pt_cmsPrelim.Draw("same") pt_lumi.Draw("same") pt_leg.Draw("same") oneLine.Draw("same") if doFit: (fitFunc, fitText) = self.PlotFit(efficiencyGraph) fitFunc.Draw("same") fitText.Draw("same") if not os.path.exists('plots_' + self.Denominator["sample"]): os.mkdir('plots_' + self.Denominator["sample"]) if self._leg == "METPath": self._canvas.SaveAs('plots_' + self.Denominator["sample"] + '/' + self._path + "_Efficiency.pdf") else: self._canvas.SaveAs('plots_' + self.Denominator["sample"] + '/' + self._path + "_" + self._leg + ".pdf") self._fout.cd() if self._tgraphSuffix is not None: efficiencyGraph.Write(self._path + "_" + self._leg + "_" + self._tgraphSuffix) if doFit: fitFunc.Write(self._path + "_" + self._leg + "_" + self._tgraphSuffix + "_fitResult") else: efficiencyGraph.Write(self._path + "_" + self._leg) if doFit: fitFunc.Write(self._path + "_" + self._leg + "_fitResult") else: print("Denominator and Numerator must be defined for path ", self._path, ", leg ", self._leg) return 0.0
print "Number of Events: ", num_events4 # this is the full off-beam file file6_path = sys.argv[6] file6 = TFile(file6_path, 'Read') if(file6.IsOpen()): print 'File ', file6_path, ' is open' if(file6.IsOpen() == False): quit() dir6 = file6.AnalyzeTPCO opt_tree6 = dir6.Get("optical_tree") num_events6 = opt_tree6.GetEntries() print "Total Off-Beam Events: ", num_events6 h_timing_1 = TH1D("h_timing_1", "h_timing_1", 60, 0, 20) h_timing_2 = TH1D("h_timing_2", "h_timing_2", 60, 0, 20) h_timing_3 = TH1D("h_timing_3", "h_timing_3", 60, 0, 20) h_timing_4 = TH1D("h_timing_4", "h_timing_4", 60, 0, 20) h_timing_1_2 = TH1D("h_timing_1_2", "h_timing_1_2", 60, 0, 20) h_timing_2_2 = TH1D("h_timing_2_2", "h_timing_2_2", 60, 0, 20) h_timing_3_2 = TH1D("h_timing_3_2", "h_timing_3_2", 60, 0, 20) h_timing_4_2 = TH1D("h_timing_4_2", "h_timing_4_2", 60, 0, 20) h_pe_1 = TH1D("h_pe_1", "h_pe_1", 80, 0, 2000) h_pe_2 = TH1D("h_pe_2", "h_pe_2", 80, 0, 2000) h_pe_3 = TH1D("h_pe_3", "h_pe_3", 80, 0, 2000) h_pe_4 = TH1D("h_pe_4", "h_pe_4", 80, 0, 2000) h_pe_1_2 = TH1D("h_pe_1_2", "h_pe_1_2", 80, 0, 2000)
'kkMass': [220, 0.8, 3.0], 'bdMass': [320, 4.8, 8.0], 'kpiMass': [190, 0.6, 2.5], 'bdbarMass': [320, 4.8, 8.0], 'kpibarMass': [190, 0.6, 2.5], 'tk1Pt': [100, 0., 80.], 'tk2Pt': [100, 0., 80.], } ntuple = TNtupleD(treeName, 'flat ntuple for roofit', ':'.join(fillNames)) print ' joint names ' + ':'.join( fillNames) + 'with size = {0}'.format(len(fillNames)) hists = { fillName: TH1D(treeName + '_' + fillName, fillName, num[0], num[1], num[2]) for fillName, num in fillPars.iteritems() } for event in mytree: nCand = event.candSize for i in range(nCand): tk1p4 = TLorentzVector(event.tk1P1[i], event.tk1P2[i], event.tk1P3[i], event.tk1P0[i]) tk2p4 = TLorentzVector(event.tk2P1[i], event.tk2P2[i], event.tk2P3[i], event.tk2P0[i]) pmup4 = TLorentzVector(event.pmuP1[i], event.pmuP2[i], event.pmuP3[i], event.pmuP0[i]) nmup4 = TLorentzVector(event.nmuP1[i], event.nmuP2[i], event.nmuP3[i], event.nmuP0[i]) mumup4 = pmup4 + nmup4