void csv(TString input="tmva.csvoutput.txt", TString par1="par2", TString par2="par3", TString par3="", TString value="eventEffScaled_5") { std::cout << "Usage:" << std::endl << ".x scripts/csv.C with default arguments" << std::endl << ".x scripts/csv.C(filename, par1, par2, value)" << std::endl << std::endl << " Optional arguments:" << std::endl << " filename path to CSV file" << std::endl << " par1 name of X-parameter branch" << std::endl << " par2 name of Y-parameter branch (if empty, efficiency is drawn as a function of par1)" << std::endl << " value name of result (efficiency) branch" << std::endl << std::endl; TTree *tree = new TTree("data", "data"); tree->ReadFile(input); gStyle->SetPalette(1); gStyle->SetPadRightMargin(0.14); TCanvas *canvas = new TCanvas("csvoutput", "CSV Output", 1200, 900); tree->SetMarkerStyle(kFullDotMedium); tree->SetMarkerColor(kRed); if(par2.Length() > 0) { //tree->Draw(Form("%s:%s", par2.Data(), par1.Data())); if(par3.Length() > 0) tree->Draw(Form("%s:%s:%s:%s", par1.Data(), par2.Data(), par3.Data(), value.Data()), "", "COLZ"); //, "", "Z"); else tree->Draw(Form("%s:%s:%s", par2.Data(), par1.Data(), value.Data()), "", "COLZ"); //, "", "Z"); TH1 *histo = tree->GetHistogram(); if(!histo) return; histo->SetTitle(Form("%s with different classifier parameters", value.Data())); histo->GetXaxis()->SetTitle(Form("Classifier parameter %s", par1.Data())); histo->GetYaxis()->SetTitle(Form("Classifier parameter %s", par2.Data())); if(par3.Length() > 0) histo->GetZaxis()->SetTitle(Form("Classifier parameter %s", par3.Data())); else histo->GetZaxis()->SetTitle(""); if(par3.Length() == 0) { float x = 0; float y = 0; float val = 0; double maxVal = tree->GetMaximum(value); double minVal = tree->GetMinimum(value); tree->SetBranchAddress(par1, &x); tree->SetBranchAddress(par2, &y); tree->SetBranchAddress(value, &val); TLatex l; l.SetTextSize(0.03); Long64_t nentries = tree->GetEntries(); for(Long64_t entry=0; entry < nentries; ++entry) { tree->GetEntry(entry); l.SetTextColor(textColor(val, maxVal, minVal)); l.DrawLatex(x, y, Form("%.3f", val*100)); } } } else { tree->Draw(Form("%s:%s", value.Data(), par1.Data())); TH1 *histo = tree->GetHistogram(); if(!histo) return; histo->SetTitle(Form("%s with different classifier parameters", value.Data())); histo->GetXaxis()->SetTitle(Form("Classifier parameter %s", par1.Data())); histo->GetYaxis()->SetTitle(value); } }
int main (int argc, char **argv) { const char* chInFile = "ws.root"; const char* chOutFile = "ws_data.root"; const char* chRootFile = "BDT20.root"; const char* chCut = ""; char option_char; while ( (option_char = getopt(argc,argv, "i:o:r:c:")) != EOF ) switch (option_char) { case 'i': chInFile = optarg; break; case 'o': chOutFile = optarg; break; case 'r': chRootFile = optarg; break; case 'c': chCut = optarg; break; case '?': fprintf (stderr, "usage: %s [i<input file> o<output file>]\n", argv[0]); } cout << "In Ws = " << chInFile << endl; cout << "Out Ws = " << chOutFile << endl; cout << "Data From = " << chRootFile << endl; cout << "Extra Cut = " << chCut << endl; TFile* in_file = new TFile(chInFile); RooWorkspace *rws = (RooWorkspace*) in_file->Get("rws"); TFile* tree_file = new TFile(chRootFile); TTree* tree = (TTree*) tree_file->Get("tree"); TFile* out_file = new TFile(chOutFile, "RECREATE"); RooArgSet allVars(*rws->var("m"),*rws->var("t"),*rws->var("et"),*rws->var("cpsi"),*rws->var("ctheta"),*rws->var("phi"),*rws->var("d"),*rws->cat("dilution")); RooDataSet* data = new RooDataSet("data","data",allVars); RooDataSet* dataBkg = new RooDataSet("dataBkg","dataBkg",allVars); //TCut* cut = new TCut("5.17<bs_mass && bs_mass<5.57 && bs_pdl>-0.044 && bs_pdl<0.3 "); TCut* cut = new TCut("5.17<bs_mass && bs_mass<5.57 && bs_epdl<0.025 && bs_pdl<0.4 && bs_pdl>-0.44"); *cut += chCut; tree->Draw(">>entry_list", *cut, "entrylist"); TEntryList* event_list = (TEntryList*) out_file->Get("entry_list"); Double_t dM, dT, dEt, dCpsi, dCtheta, dPhi, dd; Int_t ddDefined; tree->SetBranchAddress("bs_mass", &dM); tree->SetBranchAddress("bs_pdl", &dT); tree->SetBranchAddress("bs_epdl", &dEt); tree->SetBranchAddress("bs_angle_cpsi", &dCpsi); tree->SetBranchAddress("bs_angle_ctheta", &dCtheta); tree->SetBranchAddress("bs_angle_phi", &dPhi); tree->SetBranchAddress("newtag_ost", &dd); tree->SetBranchAddress("newtag_ost_defined", &ddDefined); for (Long_t i=0; i<event_list->GetN(); i++){ tree->GetEntry(event_list->GetEntry(i)); *rws->var("m")=dM; *rws->var("t")=dT/0.0299792458; *rws->var("et")=dEt/0.0299792458; *rws->var("cpsi")=dCpsi; *rws->var("ctheta")=dCtheta; *rws->var("phi")=dPhi; *rws->var("d")=0; rws->cat("dilution")->setIndex(0); if ( ddDefined==1 ){ rws->cat("dilution")->setIndex(1); *rws->var("d")=dd; } data->add(allVars); if (dM<5.29 || dM>5.44) dataBkg->add(allVars); } rws->import(*data); rws->import(*dataBkg); rws->Write("rws"); out_file->Close(); in_file->Close(); tree_file->Close(); cout << endl << "Done." << endl; }
void TMVAClassificationElecTau(std::string ordering_ = "Pt", std::string bkg_ = "qqH115vsWZttQCD") { TMVA::Tools::Instance(); TString outfileName( "TMVAElecTau"+ordering_+"Ord_"+bkg_+".root" ); TFile* outputFile = TFile::Open( outfileName, "RECREATE" ); TMVA::Factory *factory = new TMVA::Factory( "TMVAClassificationElecTau"+ordering_+"Ord_"+bkg_, outputFile, "!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D" ); factory->AddVariable( "pt1", "pT-tag1", "GeV/c" , 'F' ); factory->AddVariable( "pt2", "pT-tag2", "GeV/c" , 'F' ); factory->AddVariable( "Deta","|y-tag1 - y-tag2|","" , 'F' ); //factory->AddVariable( "opposite:=abs(eta1*eta2)/eta1/eta2","sign1*sign2","" , 'F' ); //factory->AddVariable( "Dphi", "#Delta#phi" ,"" , 'F' ); factory->AddVariable( "Mjj", "M(tag1,tag2)", "GeV/c^{2}" , 'F' ); factory->AddSpectator( "eta1", "#eta_{tag1}" , 'F' ); factory->AddSpectator( "eta2", "#eta_{tag2}" , 'F' ); factory->SetWeightExpression( "sampleWeight" ); TString fSignalName = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/ElecTauStream2011/nTupleVBFH115-powheg-PUS1_Open_ElecTauStream.root"; TString fBackgroundNameDYJets = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/ElecTauStream2011/nTupleZjets-alpgen-PUS1_Open_ElecTauStream.root"; TString fBackgroundNameWJets = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/ElecTauStream2011/nTupleWJets-madgraph-PUS1_Open_ElecTauStream.root"; TString fBackgroundNameQCD = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/ElecTauStream2011/nTupleQCD_Open_ElecTauStream.root"; TString fBackgroundNameTTbar = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/ElecTauStream2011/nTupleTTJets-madgraph-PUS1_Open_ElecTauStream.root"; TFile *fSignal(0); TFile *fBackgroundDYJets(0); TFile *fBackgroundWJets(0); TFile *fBackgroundQCD(0); TFile *fBackgroundTTbar(0); fSignal = TFile::Open( fSignalName ); fBackgroundDYJets = TFile::Open( fBackgroundNameDYJets ); fBackgroundWJets = TFile::Open( fBackgroundNameWJets ); fBackgroundQCD = TFile::Open( fBackgroundNameQCD ); fBackgroundTTbar = TFile::Open( fBackgroundNameTTbar ); if(!fSignal || !fBackgroundDYJets || !fBackgroundWJets || !fBackgroundQCD || !fBackgroundTTbar) { std::cout << "ERROR: could not open files" << std::endl; exit(1); } TString tree = "outTree"+ordering_+"Ord"; TCut mycuts = ""; TCut mycutb = ""; TCut cutA = "pt1>0 && tightestHPSWP>0"; TCut cutB = "pt1>0 && combRelIsoLeg1<0.1"; TCut cutBl = "pt1>0 && combRelIsoLeg1<0.3"; TCut cutC = "pt1>0 && diTauCharge==0"; TCut cutD = "pt1>0 && MtLeg1<40"; // select events for training TFile* dummy = new TFile("dummy.root","RECREATE"); TH1F* allEvents = new TH1F("allEvents","",1,-10,10); float totalEvents, cutEvents; // signal: all TTree *signal = ((TTree*)(fSignal->Get(tree)))->CopyTree(cutA&&cutB&&cutC&&cutD); cout << "Copied signal tree with full selection: " << ((TTree*)(fSignal->Get(tree)))->GetEntries() << " --> " << signal->GetEntries() << endl; allEvents->Reset(); signal->Draw("eta1>>allEvents","sampleWeight"); cutEvents = allEvents->Integral(); Double_t signalWeight = 1.0; cout << "Signal: expected yield " << cutEvents << " -- weight " << signalWeight << endl; // Z+jets: all TTree *backgroundDYJets = ((TTree*)(fBackgroundDYJets->Get(tree)))->CopyTree(cutA&&cutB&&cutC&&cutD); cout << "Copied DYJets tree with full selection: " << ((TTree*)(fBackgroundDYJets->Get(tree)))->GetEntries() << " --> " << backgroundDYJets->GetEntries() << endl; allEvents->Reset(); backgroundDYJets->Draw("eta1>>allEvents","sampleWeight"); cutEvents = allEvents->Integral(); Double_t backgroundDYJetsWeight = 1.0; cout << "ZJets: expected yield " << cutEvents << " -- weight " << backgroundDYJetsWeight << endl; // W+jets: iso+Mt TTree *backgroundWJets = ((TTree*)(fBackgroundWJets->Get(tree)))->CopyTree(cutB&&cutD); cout << "Copied WJets tree with iso+Mt selection: " << ((TTree*)(fBackgroundWJets->Get(tree)))->GetEntries() << " --> " << backgroundWJets->GetEntries() << endl; allEvents->Reset(); backgroundWJets->Draw("eta1>>allEvents","sampleWeight"); totalEvents = allEvents->Integral(); allEvents->Reset(); backgroundWJets->Draw("eta1>>allEvents","sampleWeight*(tightestHPSWP>0 && diTauCharge==0)"); cutEvents = allEvents->Integral(); Double_t backgroundWJetsWeight = cutEvents / totalEvents; cout << "WJets: expected yield " << cutEvents << " -- weight " << backgroundWJetsWeight << endl; // QCD: Mt+loose iso TTree *backgroundQCD = ((TTree*)(fBackgroundQCD->Get(tree)))->CopyTree(cutD&&cutBl); cout << "Copied QCD tree with Mt selection: " << ((TTree*)(fBackgroundQCD->Get(tree)))->GetEntries() << " --> " << backgroundQCD->GetEntries() << endl; allEvents->Reset(); backgroundQCD->Draw("eta1>>allEvents","sampleWeight"); totalEvents = allEvents->Integral(); allEvents->Reset(); backgroundQCD->Draw("eta1>>allEvents","sampleWeight*(tightestHPSWP>0 && diTauCharge==0 && combRelIsoLeg1<0.1)"); cutEvents = allEvents->Integral(); Double_t backgroundQCDWeight = cutEvents / totalEvents; cout << "QCD: expected yield " << cutEvents << " -- weight " << backgroundQCDWeight << endl; // TTbar: iso+Mt TTree *backgroundTTbar = ((TTree*)(fBackgroundTTbar->Get(tree)))->CopyTree(cutB&&cutD); cout << "Copied TTbar tree with iso+Mt selection: " << ((TTree*)(fBackgroundTTbar->Get(tree)))->GetEntries() << " --> " << backgroundTTbar->GetEntries() << endl; allEvents->Reset(); backgroundTTbar->Draw("eta1>>allEvents","sampleWeight"); totalEvents = allEvents->Integral(); allEvents->Reset(); backgroundTTbar->Draw("eta1>>allEvents","sampleWeight*(tightestHPSWP>0 && diTauCharge==0)"); cutEvents = allEvents->Integral(); Double_t backgroundTTbarWeight = cutEvents / totalEvents; cout << "TTbar: expected yield " << cutEvents << " -- weight " << backgroundTTbarWeight << endl; delete allEvents; factory->AddSignalTree ( signal, signalWeight ); //factory->AddBackgroundTree( backgroundDYJets, backgroundDYJetsWeight ); //factory->AddBackgroundTree( backgroundWJets, backgroundWJetsWeight ); factory->AddBackgroundTree( backgroundQCD, backgroundQCDWeight ); //factory->AddBackgroundTree( backgroundTTbar, backgroundTTbarWeight ); factory->PrepareTrainingAndTestTree( mycuts, mycutb, "nTrain_Signal=0:nTrain_Background=0:nTest_Signal=1:nTest_Background=1:SplitMode=Random:NormMode=NumEvents:!V" ); factory->BookMethod( TMVA::Types::kCuts, "Cuts", "!H:!V:FitMethod=GA:EffSel:CutRangeMin[0]=25.:CutRangeMax[0]=999:CutRangeMin[1]=25.:CutRangeMax[1]=999.:CutRangeMin[2]=1.0:CutRangeMax[2]=9.:CutRangeMin[3]=100:CutRangeMax[3]=7000:VarProp=FSmart" ); /* factory->BookMethod( TMVA::Types::kBDT, "BDT", "!H:!V:NTrees=200:BoostType=AdaBoost:SeparationType=GiniIndex:nCuts=20:PruneMethod=NoPruning" ); */ factory->TrainAllMethods(); factory->TestAllMethods(); factory->EvaluateAllMethods(); outputFile->Close(); std::cout << "==> Wrote root file: " << outputFile->GetName() << std::endl; std::cout << "==> TMVAClassification is done!" << std::endl; delete factory; //if (!gROOT->IsBatch()) TMVAGui( outfileName ); }
void draw_sigvsback(std::string const & cname, std::string const & dr, std::string const & binning, std::string const & we_sig, std::string const & sig_label, std::string const & we_back, std::string const & back_label, std::string const & op = "", std::string const & title = "", std::string const & xtitle = "", std::string const & ytitle = "", bool const significance = false, bool const efficiency = false, bool const forwards = false) { TString hname_sig = "h_sig"; TString draw_str_sig = ""; draw_str_sig += dr; draw_str_sig += ">>"; draw_str_sig += hname_sig; draw_str_sig += binning; TString hname_back = "h_back"; TString draw_str_back = ""; draw_str_back += dr; draw_str_back += ">>"; draw_str_back += hname_back; draw_str_back += binning; TCanvas * canvas = new TCanvas("temp"); if(tree2) tree2->Draw(draw_str_sig.Data(), we_sig.c_str(), op.c_str()); else tree->Draw(draw_str_sig.Data(), we_sig.c_str(), op.c_str()); delete canvas; canvas = new TCanvas("temp"); tree->Draw(draw_str_back.Data(), we_back.c_str(), op.c_str()); delete canvas; TH1F * hist_sig = (TH1F*)gDirectory->Get(hname_sig.Data()); TH1F * hist_back = (TH1F*)gDirectory->Get(hname_back.Data()); if(hist_sig->GetEntries() == 0) std::cout << "draw_sigvsback: No signal for selection: \"" << we_sig << "\"\n"; if(hist_back->GetEntries() == 0) std::cout << "draw_sigvsback: No background for selection: \"" << we_back << "\"\n"; hist_back->SetStats(0); hist_back->SetTitle(title.c_str()); hist_back->GetXaxis()->SetTitle(xtitle.c_str()); hist_back->GetXaxis()->CenterTitle(); hist_back->GetYaxis()->SetTitle(ytitle.c_str()); hist_back->GetYaxis()->CenterTitle(); hist_sig->SetLineColor(kRed); hist_back->SetLineColor(kBlue); TLegend * legend = new TLegend(0.6, 0.9, 0.9, 0.6); /* legend->SetHeader(("Total: "+to_string_with_precision(hist_sig->Integral()+hist_back->Integral())+" events").c_str()); ((TLegendEntry*)legend->GetListOfPrimitives()->First())->SetTextAlign(22); legend->AddEntry(hist_sig, (sig_label+": "+to_string_with_precision(hist_sig->Integral())+" events").c_str()); legend->AddEntry(hist_back, (back_label+": "+to_string_with_precision(hist_back->Integral())+" events").c_str()); */ legend->AddEntry(hist_sig, (sig_label).c_str()); legend->AddEntry(hist_back, (back_label).c_str()); canvas = new TCanvas(cname.c_str()); TPad * pad_base = new TPad(); pad_base->Draw(); pad_base->SetFillColor(0); double ymin_base = hist_sig->GetYaxis()->GetXmin(); double ymax_base = hist_sig->GetYaxis()->GetXmax(); double dy_base = (ymax_base-ymin_base)/0.8; double xmin_base = hist_sig->GetXaxis()->GetXmin(); double xmax_base = hist_sig->GetXaxis()->GetXmax(); double dx_base = (xmax_base-xmin_base)/0.8; pad_base->Range(xmin_base-0.1*dx_base,ymin_base-0.1*dy_base,xmax_base+0.1*dx_base,ymax_base+0.1*dy_base); pad_base->cd(); hist_back->Draw(); hist_sig->Draw("same"); if(!significance && !efficiency) legend->Draw(); ////// hist_sig->Scale(run_pot / signal_pot); hist_back->Scale(run_pot / background_pot); ////// TGraph * graph_sig = nullptr; TPad * pad_sig = nullptr; if(significance) { graph_sig = getgraphsig(hist_sig, hist_back, forwards); canvas->cd(); pad_sig = new TPad(); pad_sig->SetFillStyle(4000); double ymin = graph_sig->GetYaxis()->GetXmin(); double ymax = graph_sig->GetYaxis()->GetXmax(); double dy = (ymax-ymin)/0.8; double xmax = 0; double ytemp = 0; graph_sig->GetPoint(graph_sig->GetN()-1, xmax, ytemp); pad_sig->Range(xmin_base-0.1*dx_base,ymin-0.1*dy,xmax_base+0.1*dx_base,ymax+0.1*dy); pad_sig->Draw(); pad_sig->cd(); graph_sig->Draw("samep"); TGaxis * axis = new TGaxis(xmax_base,ymin,xmax_base,ymax,ymin,ymax, 510, "+L"); axis->SetLabelColor(graph_sig->GetMarkerColor()); axis->SetLabelSize(0.03); axis->Draw(); legend->AddEntry(graph_sig, "Significance"); if(!efficiency) legend->Draw(); } TGraph * graph_eff = nullptr; TPad * pad_eff = nullptr; if(efficiency) { graph_eff = getgrapheff(hist_sig, forwards); canvas->cd(); pad_eff = new TPad(); pad_eff->SetFillStyle(4000); double ymin = graph_eff->GetYaxis()->GetXmin(); double ymax = graph_eff->GetYaxis()->GetXmax(); double dy = (ymax-ymin)/0.8; double xmax = 0; double ytemp = 0; graph_eff->GetPoint(graph_eff->GetN()-1, xmax, ytemp); pad_eff->Range(xmin_base-0.1*dx_base,ymin-0.1*dy,xmax_base+0.1*dx_base,ymax+0.1*dy); pad_eff->Draw(); pad_eff->cd(); graph_eff->Draw("samep"); double axis_offset = 0; if(significance) axis_offset = 1./14*xmax; TGaxis * axis = new TGaxis(xmax_base+axis_offset,ymin,xmax_base+axis_offset,ymax,ymin,ymax, 510, "+L"); axis->SetLabelColor(graph_eff->GetMarkerColor()); axis->SetLabelSize(0.03); axis->Draw(); legend->AddEntry(graph_eff, "Efficiency"); legend->Draw(); } hist_sig->Scale(signal_pot / run_pot); hist_sig->Scale(1. / hist_sig->Integral()); hist_back->Scale(background_pot / run_pot); hist_back->Scale(1. / hist_back->Integral()); double const ymin_hist = 0; double ymax_hist = hist_sig->GetMaximum(); if(hist_back->GetMaximum() > ymax_hist) ymax_hist = hist_back->GetMaximum(); hist_back->GetYaxis()->SetRangeUser(ymin_hist, 1.1*ymax_hist); canvas->Write(); delete canvas; delete hist_sig; delete hist_back; delete legend; if(graph_sig) delete graph_sig; if(graph_eff) delete graph_eff; }
//============================================================================= // Standard constructor, initializes variables //============================================================================= void makeLongTracksonlyunnormalized2( ) { gROOT->SetBatch(kTRUE); TString tuplelocation = "/afs/cern.ch/work/m/mwilkins/b_b-bar_cross-section/"; TString data2011tuple = tuplelocation+"Strp20r1_SL_D0andDp_MD.root"; TString MC2011tuple = tuplelocation+"MC_2011_Bu_D0Xmunu_cocktail_12873441_MC2011_S20r1_noPID_Tuples.root"; TString data2015tuple = tuplelocation+"B2DMuNuX_tuples_05082015.root"; TString MC2015tuple = tuplelocation+"MC_2015_Bu_D0Xmunu_cocktail_12873441_MC2015_S22_noPID_Tuples.root"; TFile *f[4]; f[0] = TFile::Open(data2011tuple); f[1] = TFile::Open(MC2011tuple); f[2] = TFile::Open(data2015tuple); f[3] = TFile::Open(MC2015tuple); cout<<"files opened"<<endl; const int nhpc = 2; //number of histograms per canvas const int ncanvases = 4; const int nstacks = ncanvases; THStack *hs[nstacks]; TCanvas *c[ncanvases]; TH1F *h[ncanvases][nhpc]; TLegend *leg[ncanvases]; TString outputlocation = "output/longtracksplotsunnormalized2/";//where the output will be saved TString plotfilename = "longtracksplotsunnormalized2.pdf";//name of file that will hold drawn plots TCanvas *cf = new TCanvas("cf","combined");//canvas to hold everything float sqnc = sqrt(ncanvases), sqncu = ceil(sqnc), sqncd = floor(sqnc); while(sqncu*sqncd<ncanvases) sqncu++; cf->Divide(sqncu,sqncd); TLegend *legf = new TLegend(0.84, 0.84, .99, .95); TString placeholder; //to avoid adding strings within functions; assign immediately before use TString placeholder2; cout<<"starting canvas loop..."<<endl; for(int ci =0; ci<ncanvases; ci++){ //loop over canvases //create indicators and strings: int year; if(ci<(ncanvases/2)){//2011 for 1st half canvases, 2015 for 2nd half year = 2011; }else year = 2015; TString yearstring = Form("%d",year); TString filetype; if(ci%2==0){//true every other canvas filetype = "data"; }else filetype = "MC"; int file_num=-1000;//assign file_num based on combinations of data and MC if(year==2011){ if(filetype=="data") file_num=0; if(filetype=="MC") file_num=1; } if(year==2015){ if(filetype=="data") file_num=2; if(filetype=="MC") file_num=3; } int B0;//these will be assigned within the histogram loop TString Bdecay; TString branch; TString tracktype = "nLongTracks"; TString cistring = Form("%d",ci); cout<<"loop "<<ci<<" indicators and strings created:"<<endl<<"year: "<<year<<endl; cout<<"file: "<<file_num<<endl; //create the plots placeholder = "c"+cistring; placeholder2=yearstring+filetype+tracktype; c[ci] = new TCanvas(placeholder,placeholder2,1200,800); //create the canvases c[ci]->cd(); gStyle->SetOptStat(""); leg[ci] = new TLegend(0.7, 0.7, .97, .93);//create legend placeholder = "hs"+cistring; hs[ci] = new THStack(placeholder,placeholder2); //create the stack to hold the histograms cout<<"starting histogram loop..."<<endl; for(int hi=0;hi<nhpc;hi++){ //loop over histograms in a canvas; B0=0 and B0=1 if((int)floor(hi)%2 ==0){//every other histogram B0=0; Bdecay = "B^{-}->(D^{0}->K^{-} #pi^{+})#mu^{-}"; if((filetype=="data")&&(year==2011)){ branch="tupleb2D0Mu/tupleb2D0Mu"; }else branch="Tuple_b2D0MuX/DecayTree"; } else{ B0=1; Bdecay = "B^{0}->(D^{-}->K^{+} #pi^{-} #pi^{-})#mu^{+}"; if((filetype=="data")&&(year==2011)){ branch="tupleb2DpMu/tupleb2DpMu"; }else branch="Tuple_b2DpMuX/DecayTree"; } //create convenient strings TString histring = Form("%d",hi); TString hname = "h"+cistring+histring; //create histograms if(tracktype=="nTracks") h[ci][hi] = new TH1F(hname,tracktype,104,0,1144); if(tracktype=="nLongTracks") h[ci][hi] = new TH1F(hname,tracktype,131,0,262); cout<<"histogram loop "<<hi<<" strings and histograms created"<<endl; //navigate files cout<<"navigating file..."<<endl; TTree *MyTree; f[file_num]->GetObject(branch,MyTree); //draw histograms cout<<"drawing histogram "<<hi<<"..."<<endl; h[ci][hi]->SetLineColor(hi+1); placeholder = tracktype+">>"+hname; MyTree->Draw(placeholder); cout<<"stacking histogram "<<hi<<"..."<<endl; hs[ci]->Add(h[ci][hi]);//stack histograms leg[ci]->AddEntry(h[ci][hi],Bdecay,"l");//fill legend if(ci==0) legf->AddEntry(h[ci][hi],Bdecay,"l");//fill combined legend; all the same, so using the first one is fine } //draw stacked histograms cout<<"drawing stack "<<ci<<"..."<<endl; placeholder = yearstring+": "+filetype+": "+tracktype; hs[ci]->SetTitle(placeholder); hs[ci]->Draw("nostack"); leg[ci]->Draw(); cf->cd(ci+1); hs[ci]->Draw("nostack");//not using c[ci]->DrawClonePad(); because too many legends //save stuff: cout<<"saving files..."<<endl; placeholder = outputlocation+plotfilename+"(";//the closing page is added after the loop c[ci]->Print(placeholder); placeholder = outputlocation+"c"+cistring+".C"; c[ci]->SaveAs(placeholder); cout<<endl; } cf->cd(); legf->Draw(); placeholder = outputlocation+plotfilename+")"; cf->Print(placeholder); gROOT->SetBatch(kFALSE); cout<<"done"<<endl; }
void balanceMetVsAj(TString infname = "dj_HCPR-J50U-hiGoodMergedTracks_OfficialSelv2_Final0_120_50.root", TCut myCut = "cent<30", char *title = "",bool drawLegend = false, bool drawSys = true ) { TFile *inf = new TFile(infname); TTree *t = (TTree*)inf->Get("ntjt"); t->SetAlias("metxMerged0","metx0+metx1+metx2"); t->SetAlias("metxMerged1","metx1+metx2"); t->SetAlias("metxMerged2","metx2"); t->SetAlias("metxMerged3","metx3+metx4"); const int nBin = 4; double bins[nBin+1] = {0.5,1.5,4,8,1000}; double colors[nBin] = {38, kOrange-8,kBlue-3,kRed}; const int nBinAj = 4; double ajBins[nBinAj+1] = {0.0001,0.11,0.22,0.33,0.49999}; // Selection cut TCut evtCut = "nljet>120&&abs(nljetacorr)<2&&aljet>50&&abs(aljetacorr)<2&&jdphi>2./3*TMath::Pi()&&!maskEvt"; cout << "Sel evt: " << t->GetEntries(evtCut&&myCut) << endl; TH1D *p[nBin]; for (int i=0;i<nBin;i++) { TH1D *h1 = new TH1D(Form("h1%d",i),"",nBinAj,ajBins); TH1D *h2 = new TH1D(Form("h2%d",i),"",nBinAj,ajBins); h1->Sumw2(); h2->Sumw2(); // t->Project(Form("h%d",i),"Aj", "1"*(evtCut&&myCut)); // t->Project(Form("h2%d",i),"Aj", Form("((-1*metxMerged%d))",i)*(evtCut&&myCut)); t->Draw(Form("Aj>>h1%d",i), "weight"*(evtCut&&myCut)); t->Draw(Form("Aj>>h2%d",i), Form("((-weight*metxMerged%d))",i)*(evtCut&&myCut)); p[i]=(TH1D*)h2->Clone(); p[i]->SetName(Form("p%d",i)); p[i]->Divide(h1); p[i]->SetLineColor(1); p[i]->SetMarkerColor(colors[i]); p[i]->SetFillColor(colors[i]); // p[i]->SetFillStyle(3004+fabs(i-1)); p[i]->SetFillStyle(1001); } TH1D *pall; TH1D *h1 = new TH1D(Form("hAll1"),"",nBinAj,ajBins); TH1D *h2 = new TH1D(Form("hAll2"),"",nBinAj,ajBins); h1->Sumw2(); h2->Sumw2(); t->Draw(Form("Aj>>hAll1"), "weight"*(evtCut&&myCut)); t->Draw(Form("Aj>>hAll2"), Form("((-weight*metx))")*(evtCut&&myCut)); pall=(TH1D*)h2->Clone(); pall->SetName("pall"); pall->Divide(h1); pall->SetXTitle("A_{J}"); pall->SetYTitle("<#slash{p}_{T}^{#parallel}> (GeV/c)"); pall->GetXaxis()->CenterTitle(); pall->GetYaxis()->CenterTitle(); pall->GetXaxis()->SetLabelSize(22); pall->GetXaxis()->SetLabelFont(43); pall->GetXaxis()->SetTitleSize(24); pall->GetXaxis()->SetTitleFont(43); pall->GetYaxis()->SetLabelSize(22); pall->GetYaxis()->SetLabelFont(43); pall->GetYaxis()->SetTitleSize(24); pall->GetYaxis()->SetTitleFont(43); pall->GetXaxis()->SetTitleOffset(1.8); pall->GetYaxis()->SetTitleOffset(2.4); pall->SetNdivisions(505); pall->SetAxisRange(-59.9,59.9,"Y"); pall->SetMarkerSize(1); pall->Draw("E"); for (int i=0;i<nBin;++i) { p[i]->SetLineWidth(1); p[i]->Draw("hist same"); } pall->Draw("E same"); if (drawSys == 1) { for(int i = 0; i < nBinAj; ++i){ double x = pall->GetBinCenter(i+1); double y = pall->GetBinContent(i+1); // Quote the difference between GEN and RECO in >8 Bin (20%) before adjusting eff as systematics double err = -p[nBin-1]->GetBinContent(i+1)*0.2; DrawTick(y,err,err,x,1,0.02,1); } } // Legend TLegend *leg = new TLegend(0.10,0.68,0.70,0.96); leg->SetFillStyle(0); leg->SetBorderSize(0); leg->SetTextFont(63); leg->SetTextSize(16); leg->AddEntry(pall,Form("> %.1f GeV/c",bins[0]),"pl"); for (int i=0;i<nBin;++i) { if (i!=nBin-1){ leg->AddEntry(p[i],Form("%.1f - %.1f GeV/c",bins[i],bins[i+1]),"f"); } else { leg->AddEntry(p[i],Form("> %.1f GeV/c",bins[i]),"f"); } } if (drawLegend) leg->Draw(); TLine * l0 = new TLine(0,0,0.5,0); l0->SetLineStyle(2); l0->Draw(); TLine * l1 = new TLine(0.0001,-10,0.0001,10); l1->Draw(); TText *titleText = new TText(0.3,30,title); titleText->Draw(); }
void hfCentrality(char* fname = "r151878.root", char* trg="anaPixelHitJet50U") { TFile *f1=new TFile(Form("/d101/kimy/macro/pixelTrees/rootFiles/%s",fname),"r"); TTree *trPixMB = (TTree*)f1->Get("anaPixelHitMB/PixelTree"); TTree *trPixJet = (TTree*)f1->Get("anaPixelHitJet50U/PixelTree"); // const int nscEtBin = 10; // double scetBin[nscEtBin+1] = { 15.1,18,21,24,28,32,36,40,48,55,70}; TH1D* hhfMB = new TH1D(Form("hhfMB",trg),";Sum HF Energy (TeV);Fraction of minimum bias events",70,0,160); TH1D* hhfMB1 = (TH1D*)hhfMB->Clone("hhfMB1"); TH1D* hhfMB2 = (TH1D*)hhfMB->Clone("hhfMB2"); TH1D* hhfMB3 = (TH1D*)hhfMB->Clone("hhfMB3"); TH1D* hhfJET = (TH1D*)hhfMB->Clone("hhfJET"); TCanvas* c1 = new TCanvas(Form("c1_%s",trg),"",400,400); trPixMB->Draw("hf/1000.>>hhfMB"); trPixMB->Draw("hf/1000.>>hhfMB1","cBin<=4"); trPixMB->Draw("hf/1000.>>hhfMB2","cBin>=4 && cBin<=12"); trPixMB->Draw("hf/1000.>>hhfMB3","cBin>=12 && cBin<=35"); trPixJet->Draw("hf/1000.>>hhfJET"); handsomeTH1(hhfMB1,1); handsomeTH1(hhfMB2,2); handsomeTH1(hhfMB3,4); hhfMB1->SetFillColor(1); hhfMB2->SetFillColor(2); hhfMB3->SetFillColor(4); hhfMB->Scale(1./hhfMB->GetEntries()); hhfMB->SetAxisRange(1e-5,1,"Y"); hhfJET->Scale(1./hhfJET->GetEntries()); hhfJET->SetAxisRange(1e-5,1,"Y"); hhfMB->SetLineWidth(2); handsomeTH1(hhfMB); hhfMB->DrawCopy(); // TLine* t1 = new TLine(.511,1e-5,.511,hhfMB->GetBinContent(hhfMB->FindBin(0.511))); TLine* t1 = new TLine(0,1e-5,.511,hhfMB->GetBinContent(hhfMB->FindBin(0.511))); TLine* t2 = new TLine(35.397,1e-5,35.397,hhfMB->GetBinContent(hhfMB->FindBin(35.397))); TLine* t3 = new TLine(79.370,1e-5,79.370,hhfMB->GetBinContent(hhfMB->FindBin(79.370))); t1->SetLineWidth(1); t2->SetLineWidth(1); t3->SetLineWidth(1); t1->SetLineStyle(7); t2->SetLineStyle(7); t3->SetLineStyle(7); t1->Draw(); t2->Draw(); t3->Draw(); // hhfMB3->DrawCopy(); // hhfMB2->DrawCopy("same"); // hhfMB1->DrawCopy("same"); gPad->SetLogy(); TLegend* leg0 = new TLegend(0.2813131,0.7115054,0.9,0.8439785,NULL,"brNDC"); TLegend* leg0b =new TLegend(0.3813131,0.7115054,1,0.8439785,NULL,"brNDC"); TLegend* leg1 = new TLegend(0.1767677,0.3826344,0.4467677,0.5875591,NULL,"brNDC"); TLegend* leg2 = new TLegend(0.3611111,0.3876344,0.6111111,0.5865591,NULL,"brNDC"); TLegend* leg3 = new TLegend(0.5606061,0.3876344,0.8106061,0.5865591,NULL,"brNDC"); easyLeg(leg0b,"Centrality, HLT_HIJet50U"); easyLeg(leg1,"30%-100%"); easyLeg(leg2,"10%-30% "); easyLeg(leg3," 0%-10% "); // TCanvas* c2 = new TCanvas(Form("c2_%s",trg),"",400,400); float triggerRatio = 0.29 / 49.; hhfJET->SetLineWidth(2); hhfJET->SetLineColor(2); hhfJET->SetFillColor(2); hhfJET->SetFillStyle(3544); hhfJET->Scale(triggerRatio); hhfJET->DrawCopy("same"); easyLeg(leg0,"Centrality"); leg0->AddEntry(hhfMB,"HLT_MinBiasHForBSC_Core","l"); leg0->AddEntry(hhfJET,"HLT_HiJet50U","l"); leg0->Draw(); // leg1->Draw(); // leg2->Draw(); // leg3->Draw(); TLatex *bint = new TLatex(0.1867677,0.4876344,"30%-100%"); bint->SetTextFont(63); bint->SetTextSize(13); bint->SetNDC(); bint->Draw(); bint = new TLatex(0.4011111,0.4876344,"10%-30% "); bint->SetTextFont(63); bint->SetTextSize(13); bint->SetNDC(); bint->Draw(); bint = new TLatex(0.6006061,0.4876344," 0%-10% "); bint->SetTextFont(63); bint->SetTextSize(13); bint->SetNDC(); bint->Draw(); TLatex *cms = new TLatex(0.6013,0.89,"CMS Preliminary"); cms->SetTextFont(63); cms->SetTextSize(16); cms->SetNDC(); cms->Draw(); c1->SaveAs("hf_centrality_distribution_mb_jet50_20101126_v1.eps"); c1->SaveAs("hf_centrality_distribution_mb_jet50_20101126_v1.gif"); c1->SaveAs("hf_centrality_distribution_mb_jet50_20101126_v1.C"); // TCanvas* c2 = new TCanvas(Form("c2_%s",trg),"",400,400); // hhfJET->Divide(hhfMB); // hhfJET->Draw(); // c2->SaveAs("ratio.gif"); // TLine* t1j = new TLine(.511,1e-5,.511,hhfJET->GetBinContent(hhfJET->FindBin(0.511))); // TLine* t2j = new TLine(35.397,1e-5,35.397,hhfJET->GetBinContent(hhfJET->FindBin(35.397))); // TLine* t3j = new TLine(79.370,1e-5,79.370,hhfJET->GetBinContent(hhfJET->FindBin(79.370))); // t1j->SetLineWidth(2); // t2j->SetLineWidth(2); // t3j->SetLineWidth(2); // t1j->Draw(); // t2j->Draw(); // t3j->Draw(); // TLegend* leg0 = new TLegend(0.46,0.80, 0.99, 0.95,NULL,"brNDC"); // easyLeg(leg0,"offline cleaned Superlclusters"); // leg0->AddEntry(hetSc,"HLT_HIPhoton15"); // leg0->AddEntry(hetScClean,"HLT_HICleanPhoton15"); // leg0->Draw(); }
int rootAna_meanPt_wBkg(char *strBin = "8rap9pt"){ //const int nbin = 100; //arbitrary binning for each pT hist. const int nbin = 20; //arbitrary binning for each pT hist. const int nEntry = 10000; gROOT->Macro("./JpsiStyle.C"); // read-in root file (data) TFile *fDataPbp1; // 210498<= runNb <= 210658 should be rejected TFile *fDataPbp2; // only 210498<= runNb <= 210658 will be used : 1st 7 run (Reprocessed) TFile *fDatapPb; fDataPbp1 = new TFile("/home/songkyo/kyo/pPbDataSample/Data/pPbData_1st_ntuple_PromptReco-v1_GR_P_V43D_pileupRej_newAccCut_tot.root"); fDataPbp2 = new TFile("/home/songkyo/kyo/pPbDataSample/Data/pPbData_1st_ntuple_PromptReco-v1_GR_P_V43F_pileupRej_newAccCut_tot.root"); fDatapPb = new TFile("/home/songkyo/kyo/pPbDataSample/Data/pPbData_2nd_PromptReco-v1_GR_P_V43D_pileupRej_newAccCut_tot.root"); TTree *treeDataPbp1 = (TTree*)fDataPbp1->Get("myTree"); TTree *treeDataPbp2 = (TTree*)fDataPbp2->Get("myTree"); TTree *treeDatapPb = (TTree*)fDatapPb->Get("myTree"); ///////////////////////////////////////////////////////////// ////////////// binning Double_t ptArr[] = {2.0, 3.0, 4.0, 5.0, 6.5, 7.5, 8.5, 10.0, 14.0, 30.0}; // 8rap9pt const Int_t nPt = sizeof(ptArr)/sizeof(double)-1; cout << "nPt=" << nPt << endl; // in Ycm (will be change to 1st lab and 2nd lab later) Double_t yArr[] = {1.93, 1.5, 0.9, 0., -0.9, -1.5, -1.93, -2.4, -2.87}; // 8rap9pt const Int_t nRap = sizeof(yArr)/sizeof(double)-1; cout << "nRap=" << nRap << endl; string rapstrArr[nRap]; for (int ir=0; ir<nRap; ir++){ formRapArr(yArr[ir+1], yArr[ir], &rapstrArr[ir]); cout << "rap string arr = " << rapstrArr[ir].c_str() << endl; } Double_t etArr[] = {0.0, 120.0}; // 8rap9pt //Double_t etArr[] = {0.0, 20., 30., 120.0}; // ethf const Int_t nEt = sizeof(etArr)/sizeof(double)-1; cout << "nEt=" << nEt << endl; string etstrArr[nEt]; for (int in=0; in<nEt; in++){ formEtArr(etArr[in], etArr[in+1], &etstrArr[in]); cout << "et string arr = " << etstrArr[in].c_str() << endl; } ///////////////////////////////////////////////////////////// ////////////// cut definitions TCut trigCut = "( (Reco_QQ_trig&1)==1 && (HLTriggers&1)==1 )"; TCut recoCut = "Reco_QQ_size>=1 && Reco_QQ_sign==0"; // TCut massRange = "Reco_QQ_4mom.M() >2.6 && Reco_QQ_4mom.M() < 3.5"; TCut massRange = "Reco_QQ_4mom.M() >2.9 && Reco_QQ_4mom.M() < 3.3"; TCut massRangeBkg = "((2.6 < Reco_QQ_4mom.M() && Reco_QQ_4mom.M() <2.9) || (3.3 < Reco_QQ_4mom.M() && Reco_QQ_4mom.M() < 3.5))"; TCut ctauRange = "Reco_QQ_ctau > -3.0 && Reco_QQ_ctau < 5.0 && Reco_QQ_ctauErr > 0.0 && Reco_QQ_ctauErr < 1.0"; TCut accRecoPlus = "(TMath::Abs(Reco_QQ_mupl_4mom.Eta())<2.4) && ( (TMath::Abs(Reco_QQ_mupl_4mom.Eta())<1.2 && Reco_QQ_mupl_4mom.Pt()>=3.3) || ( 1.2<= TMath::Abs(Reco_QQ_mupl_4mom.Eta()) && TMath::Abs(Reco_QQ_mupl_4mom.Eta()) < 2.1 && Reco_QQ_mupl_4mom.Pt() >= -(1.0/0.9)*TMath::Abs(Reco_QQ_mupl_4mom.Eta())+(1.2*(1.0/0.9)+2.6)) ||(2.1<=TMath::Abs(Reco_QQ_mupl_4mom.Eta()) && Reco_QQ_mupl_4mom.Pt()>=1.3) )"; TCut accRecoMinus = "(TMath::Abs(Reco_QQ_mumi_4mom.Eta())<2.4) && ( (TMath::Abs(Reco_QQ_mumi_4mom.Eta())<1.2 && Reco_QQ_mumi_4mom.Pt()>=3.3) || ( 1.2<= TMath::Abs(Reco_QQ_mumi_4mom.Eta()) && TMath::Abs(Reco_QQ_mumi_4mom.Eta()) < 2.1 && Reco_QQ_mumi_4mom.Pt() >= -(1.0/0.9)*TMath::Abs(Reco_QQ_mumi_4mom.Eta())+(1.2*(1.0/0.9)+2.6)) ||(2.1<=TMath::Abs(Reco_QQ_mumi_4mom.Eta()) && Reco_QQ_mumi_4mom.Pt()>=1.3) )"; TCut ptRange[nEt][nRap][nPt]; TCut rapRangePbp[nEt][nRap][nPt]; TCut rapRangepPb[nEt][nRap][nPt]; TCut totalCutPbp[nEt][nRap][nPt]; TCut totalCutpPb[nEt][nRap][nPt]; TCut totalCutBkgPbp[nEt][nRap][nPt]; TCut totalCutBkgpPb[nEt][nRap][nPt]; TCut runCut = "runNb >=210498 && runNb <= 210658"; //1st 7 run // forming TCut for diffential binning for (int in=0; in<nEt; in++){ for (int ir=0; ir<nRap; ir++ ) { for (int ipt=0; ipt<nPt; ipt++) { ptRange[in][ir][ipt] = Form("Reco_QQ_4mom.Pt()>%.1f && Reco_QQ_4mom.Pt()<%.1f",ptArr[ipt] , ptArr[ipt+1]); //change y_CM to y_lab rapRangePbp[in][ir][ipt] = Form("-0.47-1.*Reco_QQ_4mom.Rapidity()>%.2f && -0.47-1.*Reco_QQ_4mom.Rapidity()<%.2f",yArr[ir+1] , yArr[ir]); rapRangepPb[in][ir][ipt] = Form("-0.47+Reco_QQ_4mom.Rapidity()>%.2f && -0.47+Reco_QQ_4mom.Rapidity()<%.2f",yArr[ir+1] , yArr[ir]); cout << "ptRange = " <<ptRange[in][ir][ipt] << endl; cout << "rapRangePbp = " <<rapRangePbp[in][ir][ipt] << endl; cout << "rapRangepPb = " <<rapRangepPb[in][ir][ipt] << endl; totalCutPbp[in][ir][ipt] = trigCut && recoCut && massRange && ctauRange && accRecoPlus && accRecoMinus && rapRangePbp[in][ir][ipt] && ptRange[in][ir][ipt]; totalCutpPb[in][ir][ipt] = trigCut && recoCut && massRange && ctauRange && accRecoPlus && accRecoMinus && rapRangepPb[in][ir][ipt] && ptRange[in][ir][ipt]; totalCutBkgPbp[in][ir][ipt] = trigCut && recoCut && massRangeBkg && ctauRange && accRecoPlus && accRecoMinus && rapRangePbp[in][ir][ipt] && ptRange[in][ir][ipt]; totalCutBkgpPb[in][ir][ipt] = trigCut && recoCut && massRangeBkg && ctauRange && accRecoPlus && accRecoMinus && rapRangepPb[in][ir][ipt] && ptRange[in][ir][ipt]; } } } ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// // define 1D hist TH1D *hMeanPt[nEt][nRap][nPt]; TH1D *hMeanPtBkg[nEt][nRap][nPt]; double meanVal[nEt][nRap][nPt]; double maxVal[nEt][nRap][nPt]; double meanValBkg[nEt][nRap][nPt]; double maxValBkg[nEt][nRap][nPt]; //TCanvas* c1 = new TCanvas("c1","c1",600,600); TCanvas* cmulti[nEt][nRap]; TLegend *legUR = new TLegend(0.58,0.68,0.90,0.90,NULL,"brNDC"); TLegend *legUM = new TLegend(0.30,0.68,0.65,0.90,NULL,"brNDC"); TLegend *legUL = new TLegend(0.17,0.68,0.51,0.90,NULL,"brNDC"); TLegend *legBM = new TLegend(0.30,0.20,0.65,0.42,NULL,"brNDC"); SetLegendStyle(legUR); SetLegendStyle(legUM); SetLegendStyle(legUL); SetLegendStyle(legBM); TLatex* latex = new TLatex(); latex->SetNDC(); latex->SetTextAlign(12); latex->SetTextSize(0.04); for (int in=0; in<nEt; in++){ for (int ir=0; ir<nRap; ir++ ) { cmulti[in][ir]= new TCanvas(Form("cmulti_%d_%d",in,ir),Form("%s",rapstrArr[ir].c_str()),1500,600); cmulti[in][ir]->Divide(5,2); for (int ipt=0; ipt<nPt; ipt++) { hMeanPt[in][ir][ipt] = new TH1D(Form("hMeanPt_%d_%d_%d",in, ir, ipt),";p_{T} (GeV/c);events", nbin, ptArr[ipt], ptArr[ipt+1]); hMeanPt[in][ir][ipt] ->Sumw2(); SetHistStyle(hMeanPt[in][ir][ipt],4,0); hMeanPtBkg[in][ir][ipt] = new TH1D(Form("hMeanPtBkg_%d_%d_%d",in, ir, ipt),";p_{T} (GeV/c);events", nbin, ptArr[ipt], ptArr[ipt+1]); hMeanPtBkg[in][ir][ipt] ->Sumw2(); SetHistStyle(hMeanPtBkg[in][ir][ipt],3,10); cmulti[in][ir]->cd(ipt+1); gPad->SetLogy(1); /* treeDataPbp1->Draw(Form("Reco_QQ_4mom.Pt()>>%s",hMeanPt[in][ir][ipt]->GetName()),(totalCutPbp[in][ir][ipt]&&(!runCut)),"",nEntry); treeDataPbp2->Draw(Form("Reco_QQ_4mom.Pt()>>+%s",hMeanPt[in][ir][ipt]->GetName()),(totalCutPbp[in][ir][ipt]&&runCut),"",nEntry); treeDatapPb->Draw(Form("Reco_QQ_4mom.Pt()>>+%s",hMeanPt[in][ir][ipt]->GetName()),totalCutpPb[in][ir][ipt],"",nEntry); treeDataPbp1->Draw(Form("Reco_QQ_4mom.Pt()>>%s",hMeanPtBkg[in][ir][ipt]->GetName()),(totalCutBkgPbp[in][ir][ipt]&&(!runCut)),"pe same",nEntry); treeDataPbp2->Draw(Form("Reco_QQ_4mom.Pt()>>+%s",hMeanPtBkg[in][ir][ipt]->GetName()),(totalCutBkgPbp[in][ir][ipt]&&runCut),"pe same",nEntry); treeDatapPb->Draw(Form("Reco_QQ_4mom.Pt()>>+%s",hMeanPtBkg[in][ir][ipt]->GetName()),totalCutBkgpPb[in][ir][ipt],"pe same",nEntry); */ treeDataPbp1->Draw(Form("Reco_QQ_4mom.Pt()>>%s",hMeanPt[in][ir][ipt]->GetName()),(totalCutPbp[in][ir][ipt]&&(!runCut)),""); treeDataPbp2->Draw(Form("Reco_QQ_4mom.Pt()>>+%s",hMeanPt[in][ir][ipt]->GetName()),(totalCutPbp[in][ir][ipt]&&runCut),""); treeDatapPb->Draw(Form("Reco_QQ_4mom.Pt()>>+%s",hMeanPt[in][ir][ipt]->GetName()),totalCutpPb[in][ir][ipt],""); treeDataPbp1->Draw(Form("Reco_QQ_4mom.Pt()>>%s",hMeanPtBkg[in][ir][ipt]->GetName()),(totalCutBkgPbp[in][ir][ipt]&&(!runCut)),"pe same"); treeDataPbp2->Draw(Form("Reco_QQ_4mom.Pt()>>+%s",hMeanPtBkg[in][ir][ipt]->GetName()),(totalCutBkgPbp[in][ir][ipt]&&runCut),"pe same"); treeDatapPb->Draw(Form("Reco_QQ_4mom.Pt()>>+%s",hMeanPtBkg[in][ir][ipt]->GetName()),totalCutBkgpPb[in][ir][ipt],"pe same"); meanVal[in][ir][ipt] = hMeanPt[in][ir][ipt]->GetMean(1); maxVal[in][ir][ipt] = 50*hMeanPt[in][ir][ipt]->GetMaximum(); meanValBkg[in][ir][ipt] = hMeanPtBkg[in][ir][ipt]->GetMean(1); maxValBkg[in][ir][ipt] = 50*hMeanPtBkg[in][ir][ipt]->GetMaximum(); hMeanPt[in][ir][ipt]->GetYaxis()->SetRangeUser(0.1,maxVal[in][ir][ipt]); hMeanPtBkg[in][ir][ipt]->GetYaxis()->SetRangeUser(0.1,maxValBkg[in][ir][ipt]); std::cout << hMeanPt[in][ir][ipt]->GetName() <<" : entries = " << hMeanPt[in][ir][ipt]->GetEntries() << std::endl; cout << " Cand <p_{T}> = " << meanVal[in][ir][ipt] << endl; cout << " Bkg <p_{T}> = " << meanValBkg[in][ir][ipt] << endl; latex->DrawLatex(0.54, 0.87, rapstrArr[ir].c_str()); latex->DrawLatex(0.54, 0.80, Form("Cand <p_{T}> = %.2f (GeV/c)",meanVal[in][ir][ipt])); latex->DrawLatex(0.54, 0.72, Form("Bkg <p_{T}> = %.2f (GeV/c)",meanValBkg[in][ir][ipt])); //c1->Update(); //c1->SaveAs(Form("%s.png",hMeanPt[in][ir][ipt]->GetName())); //c1->Clear(); } cmulti[in][ir]->Update(); cmulti[in][ir]->SaveAs(Form("dir_meanPt/meanPt_%s_%d_%d_wBkg.pdf",strBin,in,ir)); //cmulti[in][ir]->Clear(); } } /// Save as a root file TFile *outFile = new TFile(Form("meanPt_%s_wBkg.root",strBin),"RECREATE"); std::cout << "strBin : " << strBin << std::endl; outFile->cd(); for (int in=0; in<nEt; in++){ for (int ir=0; ir<nRap; ir++ ) { for (int ipt=0; ipt<nPt; ipt++) { hMeanPt[in][ir][ipt]->Write(); hMeanPtBkg[in][ir][ipt]->Write(); } } } outFile->Close(); return 0; }
void plotVariable(string variable = "Elec_Fbrem", const TString& category = "TauNoGammas", const TString& xAxisTitle = "Fbrem", const TString& yAxisTitle = "a.u.", float xMin = -0.2, float xMax = 1, int nBins = 100, int numPVMin = 0, int numPVMax = 50, float PtMin = 10, float PtMax = 60, const TString& Region = "Endcap" ) { string discriminator = ""; // string discriminator = "-AntiEMed"; float AbsEtaMin = 0; float AbsEtaMax = 3.0; if(Region == "Barrel"){ AbsEtaMin = 0; AbsEtaMax = 1.479; } if(Region == "Endcap"){ AbsEtaMin = 1.479; AbsEtaMax = 3.0; } TCanvas *c1 = new TCanvas("c1","",5,30,650,600); c1->SetGrid(0,0); c1->SetFillStyle(4000); c1->SetFillColor(10); c1->SetTicky(); c1->SetObjectStat(0); gStyle->SetOptStat(0); gStyle->SetTitleFillColor(0); gStyle->SetCanvasBorderMode(0); gStyle->SetCanvasColor(0); gStyle->SetPadBorderMode(0); gStyle->SetPadColor(0); gStyle->SetTitleFillColor(0); gStyle->SetTitleBorderSize(0); gStyle->SetTitleH(0.07); gStyle->SetTitleFontSize(0.1); gStyle->SetTitleStyle(0); gStyle->SetTitleOffset(1.3,"y"); TLegend* leg = new TLegend(0.6,0.75,0.8,0.88,NULL,"brNDC"); leg->SetFillStyle(0); leg->SetBorderSize(0); leg->SetFillColor(10); leg->SetTextSize(0.03); //leg->SetHeader("#splitline{CMS Preliminary}{ #sqrt{s}=7 TeV}"); // std::string inputFileName = "/data_CMS/cms/ivo/AntiEMVA/Trees/AntiEMVA_Fall11DYJetsToLL-iter4.root"; // std::string inputFileName = "/data_CMS/cms/ivo/AntiEMVA/Trees/Trees_ForV4/AntiEMVA_AntiEMVATrees-DYJetsToLL-madgraph-PUS6.root"; std::string inputFileName = "/data_CMS/cms/ivo/AntiEMVA/Trees/Trees_ForV4/AntiEMVA_V4.root"; TFile* inputFile = new TFile (inputFileName.data(),"READ"); if(inputFile->IsZombie()){ cout << "No such file!" << endl; return; } TTree* inputTree = (TTree*)inputFile->Get("AntiEMVAAnalyzer2/tree"); // TTree* inputTree = (TTree*)inputFile->Get("AntiEMVAAnalyzer/tree"); std::vector<TH1*> histograms; std::vector<std::string> matchings ; matchings.push_back("GenHadMatch"); matchings.push_back("GenEleMatch"); for ( std::vector<std::string>::const_iterator matching = matchings.begin(); matching != matchings.end(); ++matching ) { TCut PUSelection(Form("NumPV>%i && NumPV<%i",numPVMin,numPVMax)); TCut ElecPtSelection (Form("Elec_Pt>%0f && Elec_Pt<%0f",PtMin,PtMax)); TCut TauPtSelection (Form("Tau_Pt>%0f && Tau_Pt<%0f",PtMin,PtMax)); TCut ElecAbsEtaSelection (Form("Elec_AbsEta>%0f && Elec_AbsEta<%0f",AbsEtaMin,AbsEtaMax)); TCut TauAbsEtaSelection = ""; if(Region == "Barrel"){ TauAbsEtaSelection = "Tau_Eta>-1.479 && Tau_Eta<1.479"; } if(Region == "Endcap"){ TauAbsEtaSelection = "(Tau_Eta>1.479 && Tau_Eta<3.0) || (Tau_Eta>-3.0 && Tau_Eta<-1.479)"; } // TCut TauAbsEtaSelection (Form("Tau_AbsEta>%0f && Tau_AbsEta<%0f",AbsEtaMin,AbsEtaMax)); TCut ElecMatchSelection (Form("Elec_%s == 1",matching->data())); // TCut ElecMatchSelection (Form("Elec_PFTauMatch && Elec_%s",matching->data())); TCut TauMatchSelection (Form("Tau_%s",matching->data())); TCut CategorySelection = ""; if(discriminator == ""){ if (category == "NoEleMatch") CategorySelection = "Tau_GsfEleMatch<0.5"; if (category == "woG") CategorySelection = "Tau_NumGammaCands<0.5"; if (category == "wGwoGSF") CategorySelection = "Tau_NumGammaCands>0.5 && Tau_HasGsf<0.5"; if (category == "wGwGSFwoPFMVA")CategorySelection = "Tau_NumGammaCands>0.5 && Tau_HasGsf>0.5 && Elec_PFMvaOutput<-0.1"; if (category == "wGwGSFwPFMVA")CategorySelection = "Tau_NumGammaCands>0.5 && Tau_HasGsf>0.5 && Elec_PFMvaOutput>-0.1"; } if(discriminator == "-AntiEMed"){ if (category == "NoEleMatch") CategorySelection = "Tau_GsfEleMatch<0.5"; if (category == "woG") CategorySelection = "Tau_NumGammaCands<0.5"; if (category == "wGwoGSF") CategorySelection = "Tau_NumGammaCands>0.5 && (Tau_HasGsf<0.5 || (Tau_HasGsf>0.5 && Elec_PFMvaOutput>-0.1))"; if (category == "wGwGSFwoPFMVA")CategorySelection = "Tau_NumGammaCands>0.5 && Tau_HasGsf>0.5 && Elec_PFMvaOutput<-0.1"; } TCut ElecSelection = CategorySelection && PUSelection && ElecPtSelection && ElecAbsEtaSelection && ElecMatchSelection ; TCut TauSelection = CategorySelection && PUSelection && TauPtSelection && TauAbsEtaSelection && TauMatchSelection ; TCut Selection; if (variable.find("Elec")!=std::string::npos)Selection = ElecSelection; if (variable.find("Tau")!=std::string::npos)Selection = TauSelection; TH1F* hVariable = new TH1F( "hVariable" ,"" , nBins ,xMin, xMax); hVariable->SetXTitle(Form("%s",variable.data())); if (matching->find("EleMatch")!=std::string::npos){ // hVariable->SetFillColor(kRed); // hVariable->SetFillStyle(3345); hVariable->SetLineColor(kRed); hVariable->SetLineWidth(2); } if (matching->find("HadMatch")!=std::string::npos){ // hVariable->SetFillColor(kBlue); // hVariable->SetFillStyle(3354); hVariable->SetLineColor(kBlue); hVariable->SetLineWidth(2); } inputTree->Draw(Form("%s>>hVariable",variable.data())); cout<<"Variable plotted : "<<variable<<endl; cout<<"Matching applied : "<<matching->data()<<endl; cout<<" Total number of Candidates : "<<hVariable->GetEntries()<<endl; inputTree->Draw(Form("%s>>hVariable",variable.data()),Selection); cout<<" Number of Cantidates after selection: "<<hVariable->GetEntries()<<endl; hVariable->Scale(1./hVariable->Integral()); leg->AddEntry(hVariable,Form("%s",matching->data())); histograms.push_back(hVariable); c1->Clear(); } // double yMin = +1.e+6; // double yMax = -1.e+6; TH1* refHistogram = histograms.front(); refHistogram->SetStats(false); refHistogram->SetTitle(""); // refHistogram->SetMinimum(yMin); // refHistogram->SetMaximum(yMax); if (xAxisTitle == "HoHplusE" ) { refHistogram->SetMaximum(1.0); refHistogram->SetMinimum(0.01); c1->SetLogy(); } if(xAxisTitle == "E_{#gamma}/(P_{in}-P_{out})" ){ refHistogram->SetMaximum(0.03); refHistogram->SetMinimum(0.0); } if(xAxisTitle == "HadrMva(#tau)" ){ refHistogram->SetMaximum(0.25); refHistogram->SetMinimum(0.0); } TAxis* xAxis = refHistogram->GetXaxis(); xAxis->SetTitle(xAxisTitle.Data()); xAxis->SetTitleOffset(1.15); //if(variable.find("AbsEta")!=std::string::npos)xAxis->SetLimits(AbsEtaMin, AbsEtaMax); TAxis* yAxis = refHistogram->GetYaxis(); yAxis->SetTitle(yAxisTitle.Data()); yAxis->SetTitleOffset(1.30); int numHistograms = histograms.size(); float YMax = 0; for ( int iHistogram = 0; iHistogram < numHistograms; ++iHistogram ) { TH1* histogram = histograms[iHistogram]; if(histogram->GetMaximum()>YMax) YMax = histogram->GetMaximum(); } for ( int iHistogram = 0; iHistogram < numHistograms; ++iHistogram ) { TH1* histogram = histograms[iHistogram]; yAxis->SetRangeUser(0.,YMax+0.10*YMax); std::string drawOption = "hist"; if ( iHistogram > 0 ) drawOption.append("same"); histogram->Draw(drawOption.data()); leg->Draw(); }//loop matchings string outputName = Form("plots/plotVariablesAntiEMVA/%s/plotVariablesAntiEMVA_v4_%s_%s_%s",category.Data(),category.Data(),variable.data(),Region.Data()); c1->Print(std::string(outputName).append(".png").data()); c1->Print(std::string(outputName).append(".pdf").data()); }
void test_msv(std::string var="m_sv",int nbins=25, double xmin=0, double xmax=250,std::string xtitle="m_sv", std::string ytitle="Events") { SetStyle(); gStyle->SetLineStyleString(11,"20 10"); TH1::SetDefaultSumw2(1); std::string dir = "/afs/cern.ch/work/a/arapyan/public/svfitsamples/"; double sigscale = 10; double sigscale1 = 10; std::stringstream scale; scale << sigscale; std::stringstream scale1; scale1 << sigscale1; //Cut definitions double luminosity = 3000; std::stringstream lumi; lumi << luminosity; std::string objcut = "(ptTau1>30 && ptTau2>30 && abs(etaTau1) <4.0 && abs(etaTau1)<4.0 )"; //std::string jetcut = objcut+"*(ptJet1>30 && ptJet2>30 && abs(etaJet1) <4.7 && abs(etaJet2) <4.7 )"; std::string mthcut = objcut+"*( ( (tauCat1==3 && tauCat2==2) || (tauCat2==3 && tauCat1==2) ) )"; //signal region //std::string vbfcut = ththcut+"*eventWeight*(eventType==0)*"+lumi.str(); //std::string zttcut = ththcut+"*eventWeight*(eventType==1)*"+lumi.str(); //std::string ttbarcut = ththcut+"*eventWeight*(eventType==3)*"+lumi.str(); //std::string ewkcut = ththcut+"*eventWeight*(eventType==2)*"+lumi.str(); //std::string othercut = ththcut+"*eventWeight*(eventType==4 || eventType==2)*"+lumi.str(); //-------------------------------------------------------------------------- //Get the trees TTree *tree = load(dir+"hh.root"); TTree *tree2 = load(dir+"Bjj-vbf.root"); TTree *tree3 = load(dir+"vbf_bgd.root"); //------------------------------------------------------------------------- //Get histograms TCanvas *canv0 = MakeCanvas("canv", "histograms", 600, 600); canv0->cd(); std::string vardraw; TH1F *vbf = new TH1F("VBFH","",nbins,xmin,xmax); vardraw = var+">>"+"VBFH"; tree->Draw(vardraw.c_str(),mthcut.c_str()); InitSignal(vbf); vbf->SetLineColor(kBlack); //TH1F *ttbar = new TH1F("TTbar","",nbins,xmin,xmax); //vardraw = var+">>"+"TTbar"; //tree->Draw(vardraw.c_str(),ttbarcut.c_str()); //InitHist(ttbar, xtitle.c_str(), ytitle.c_str(), TColor::GetColor(155,152,204), 1001); TH1F *ztt = new TH1F("Ztt","",nbins,xmin,xmax); vardraw = var+">>"+"Ztt"; tree2->Draw(vardraw.c_str(),mthcut.c_str()); InitHist(ztt, xtitle.c_str(), ytitle.c_str(), TColor::GetColor(248,206,104), 1001); //TH1F *ewk = new TH1F("Ewk","",nbins,xmin,xmax); //vardraw = var+">>"+"Ewk"; //tree->Draw(vardraw.c_str(),ewkcut.c_str()); //InitHist(ewk, xtitle.c_str(), ytitle.c_str(), TColor::GetColor(222,90,106), 1001); TH1F *other = new TH1F("Other","",nbins,xmin,xmax); vardraw = var+">>"+"Other"; tree3->Draw(vardraw.c_str(),mthcut.c_str()); InitHist(other, xtitle.c_str(), ytitle.c_str(), TColor::GetColor(222,90,106), 1001); delete canv0; //---------------------------------------------------------------------------- //Print out the yields /* Double_t error=0.0; ofstream outfile; outfile.open("yields_test.txt"); outfile << "Yields for the signal region." << std::endl; outfile << "VBF " << vbf->IntegralAndError(0,vbf->GetNbinsX(),error) << "+/-" << error << endl; outfile << "TTbar " << ttbar->IntegralAndError(0,ttbar->GetNbinsX(),error) << "+/-" << error << endl; outfile << "Ztt " << ztt->IntegralAndError(0,ztt->GetNbinsX(),error) << "+/-" << error << endl; //outfile << "ewk " << ewk->IntegralAndError(0,ewk->GetNbinsX(),error) << "+/-" << error << endl; outfile << "other " << other->IntegralAndError(0,other->GetNbinsX(),error) << "+/-" << error << endl; outfile << "S/sqrt(B) " << vbf->Integral()/(other->Integral()+ztt->Integral()+ttbar->Integral()) << endl; //-------------------------------------------------------------------------- //continue outputing //outfile << "Ewk total " << ewk->IntegralAndError(0,ewk->GetNbinsX(),error) << "+/-" << error << endl; outfile << endl << endl << endl; outfile << "In the signal region (100,150GeV) " <<endl; outfile << "VBF " << vbf->IntegralAndError(5,11,error) << "+/-" << error << endl; outfile << "TTbar " << ttbar->IntegralAndError(5,11,error) << "+/-" << error << endl; outfile << "Ztt " << ztt->IntegralAndError(5,11,error) << "+/-" << error << endl; //outfile << "ewk " << ewk->IntegralAndError(5,11,error) << "+/-" << error << endl; outfile << "other " << other->IntegralAndError(5,11,error) << "+/-" << error << endl; outfile.close();*/ //----------------------------------------------------------------------- //Draw the histograms TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600); canv->cd(); //ewk->Add(other); ttbar->Add(ewk); //ztt->Add(ttbar); vbf->Add(ztt); other->Add(ztt); //Error band stat TH1F* errorBand = (TH1F*)vbf ->Clone("errorBand"); errorBand ->SetMarkerSize(0); errorBand ->SetFillColor(13); errorBand ->SetFillStyle(3013); errorBand ->SetLineWidth(1); // for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){ // if(errorBand->GetBinContent(idx)>0){ // std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl; // break; // } //} Float_t n=other->GetEntries(); other->Scale(1.0/n); n=vbf->GetEntries(); vbf->Scale(1.0/n); //for (Int_t i=1; i<nbins+1; i++) { //cout << "i: " << i << " " << other->GetBinCenter(i) << " " << other->Integral(0,i) << " " << other->Integral(i,nbins+1) << endl; //} cout << " other " << other->Integral(10,15) << endl; cout << " htt " << vbf->Integral(10,15) << endl; //n=ztt->GetEntries(); //ztt->Scale(1.0/n); other->SetMaximum(1.2*std::max(maximum(vbf, 0), maximum(other, 0))); //blind(vbf,75,150); //ttbar->Draw("histsame"); //ewk->Draw("histsame"); other->Draw("hist"); //ztt->Draw("histsame"); vbf->Draw("histsame"); //errorBand->Draw("e2same"); canv->RedrawAxis(); //--------------------------------------------------------------------------- //Adding a legend TLegend* leg = new TLegend(0.53, 0.65, 0.95, 0.90); SetLegendStyle(leg); leg->AddEntry(vbf , "HH" , "F"); //leg->AddEntry(ztt , "bjj-vbf" , "F" ); //leg->AddEntry(ttbar, "t#bar{t}" , "F" ); //leg->AddEntry(ewk , "Electroweak" , "F" ); leg->AddEntry(other, "Other" , "F" ); //leg->AddEntry(errorBand,"bkg. uncertainty","F"); leg->Draw(); //--------------------------------------------------------------------------- //CMS preliminary const char* dataset = "CMS Preliminary, H#rightarrow#tau#tau, 3.0 ab^{-1} at 14 TeV"; const char* category = ""; CMSPrelim(dataset, "#mu#tau_{h}", 0.17, 0.835); //CMSPrelim(dataset, "", 0.16, 0.835); TPaveText* chan = new TPaveText(0.52, 0.35, 0.91, 0.55, "tlbrNDC"); chan->SetBorderSize( 0 ); chan->SetFillStyle( 0 ); chan->SetTextAlign( 12 ); chan->SetTextSize ( 0.05 ); chan->SetTextColor( 1 ); chan->SetTextFont ( 62 ); chan->AddText(category); chan->Draw(); //------------------------------------------------------------------------- //Save histograms canv->Print((var+"_test.png").c_str()); }
void correlation_plots2(bool rwt = true, TString catName = "e3je2t"){ int numhists = 0; // jet and tag cut for each category TString jettagcut = ""; if (catName == "ge4je2t"){ jettagcut = "numJets>3 && numTaggedJets==2"; numhists = 7; } else if(catName == "e3je2t"){ jettagcut = "numJets==3 && numTaggedJets==2"; numhists = 5; } else std::cout << "Error, wrong category name" << std::endl; //IN GLOBAL SCOPE // const int numhists = 5; // 5; const int numprofiles = pow(numhists,2); TProfile** profiles_Data = new TProfile * [numprofiles]; TProfile** profiles_MC = new TProfile * [numprofiles]; //IN MAIN FUNCTION char** histnames = new char * [numhists]; char** histXaxis = new char * [numhists]; int* histbins = new int[numhists]; double* histmin = new double[numhists]; double* histmax = new double[numhists]; if(catName == "e3je2t"){ histnames[0] = (char*) "sum_pt"; histXaxis[0] = (char*) "p_{T}(l, jets)"; histbins[0] = 13; histmin[0] = 150; histmax[0] = 930; histnames[1] = (char*) "min_dr_jets"; histXaxis[1] = (char*) "minimum #DeltaR(j, j)"; histbins[1] = 12; histmin[1] = 0.5; histmax[1] = 3.5; histnames[2] = (char*) "avg_btag_disc_non_btags"; histXaxis[2] = (char*) "#mu^{CSV}(non b-tags)"; histbins[2] = 10; histmin[2] = 0.0; histmax[2] = 0.68; histnames[3] = (char*) "avg_btag_disc_btags"; histXaxis[3] = (char*) "#mu^{CSV}"; histbins[3] = 10; histmin[3] = 0.7; histmax[3] = 1; histnames[4] = (char*) "BDTG_e3je2t"; histXaxis[4] = (char*) "BDT output"; histbins[4] = 10; histmin[4] = -1.; histmax[4] = 1.; } else if(catName == "ge4je2t"){ histnames[0] = (char*) "sum_pt"; histXaxis[0] = (char*) "p_{T}(l, jets)"; histbins[0] = 15; histmin[0] = 200; histmax[0] = 1400; histnames[1] = (char*) "min_dr_jets"; histXaxis[1] = (char*) "minimum #DeltaR(j, j)"; histbins[1] = 11; histmin[1] = 0.5; histmax[1] = 2.7; histnames[2] = (char*) "avg_btag_disc_non_btags"; histXaxis[2] = (char*) "#mu^{CSV}(non b-tags)"; histbins[2] = 11; histmin[2] = 0.0; histmax[2] = 0.605; histnames[3] = (char*) "higgsLike_dijet_mass"; histXaxis[3] = (char*) "higgsLike dijet mass"; histbins[3] = 17; histmin[3] = 34; histmax[3] = 255; histnames[4] = (char*) "higgsLike_dijet_mass2"; histXaxis[4] = (char*) "higgsLike dijet mass2"; histbins[4] = 17; histmin[4] = 30; histmax[4] = 370; histnames[5] = (char*) "numJets"; histXaxis[5] = (char*) "N_{jets}"; histbins[5] = 5; histmin[5] = 4; histmax[5] = 9; histnames[6] = (char*) "BDTG_ge4je2t"; histXaxis[6] = (char*) "BDT output"; histbins[6] = 12; histmin[6] = -0.95; histmax[6] = 0.85; } else std::cout << "Error2, wrong category name" << std::endl; //// TString cuts = "(oppositeLepCharge == 1) && (dR_leplep > 0.2) && (mass_leplep > 12) && isCleanEvent && PassZmask==1 && "; cuts += jettagcut; //// sample info TString htitle[21] = {"_singlet_s","_singlet_tW","_singlet_t","_singletbar_s","_singletbar_tW","_singletbar_t","_ttbarW","_ttbarZ","_ttbar_cc","_ttbar_bb","_ttbar_b","_ttbar","_wjets","_zjets","_zjets_lowmass","_ww","_wz","_zz","_MuEG","_DoubleElectron","_DoubleMu",}; // Float_t lumi = 19450; //////// //SKIPPING HISTOGRAM INITIALIZATION FOR OTHER 49 VARIABLES (USE ABOVE THREE EXAMPLES FOR YOUR USE) //////// TDirectory *currentDir = gDirectory; for (int i = 0; i < numhists; i++){ std::cout << "-->Figuring out binning for " << histnames[i] << std::endl; //Set the binning on the x-axis by looking at the data and combining bins (if necessary) to make sure there are no poorly populated bins //Define poorly populated arbitrarily as N < 100 currentDir->cd(); //This is because the "Draw" command only finds TString histName = Form("tempData_%s",histnames[i]); TH1 * tempHist = new TH1D(histName,"",histbins[i],histmin[i],histmax[i]); //Only look at data for (int isam=18; isam<21; isam++){ TString sample = htitle[isam]; TString fileName = "/afs/crc.nd.edu/user/w/wluo1/LHCP_2013/CMSSW_5_3_8_patch1/src/BEAN/DrawPlots/bin/treeFiles/dilSummaryTrees" +sample + "_2012_53x_July5th_all.root"; std::cout << " -->Including " << fileName << std::endl; TFile * tmpfile = new TFile(fileName); TTree * tmpTree = (TTree*)tmpfile->Get("summaryTree"); currentDir->cd(); //This is because the "Draw" command only finds TString selection = "(" + cuts + "&&"; if (isam == 18) selection+= "MuonEle && isMuEGTriggerPass"; else if (isam == 19) selection += "TwoEle && isDoubleElectronTriggerPass"; else if (isam == 20) selection += "TwoMuon && isDoubleMuTriggerPass"; selection += ")"; TString var = string(histnames[i])+">>+"+histName ; tmpTree->Draw(var, selection, "goff"); tmpfile->Close(); delete tmpfile; } std::cout << "tempHist name = " << tempHist->GetName() << std::endl; std::cout << "tempHist: Entries = " << tempHist->GetEntries() << ", Integral = " << tempHist->Integral() << std::endl; double threshold = (tempHist->Integral())/20; //Now, look through the bins of the histograms, combining when necessary int nBinsUsed = 0; double *xBins = new double[histbins[i]+1]; xBins[0] = histmin[i]; //First bin always starts at minimum double binSum = 0; for (int iBin = 1; iBin <= histbins[i]; ++iBin) { binSum += tempHist->GetBinContent(iBin); std::cout << "binSum = " << binSum << ", iBin = " << iBin << std::endl; if (binSum >= threshold) { std::cout << "Setting bin edge!" << std::endl; ++nBinsUsed; xBins[nBinsUsed] = tempHist->GetBinLowEdge(iBin+1); binSum = 0.; } } //Now check: if binSum > 0, that means the last bin was too small to be a bin //by itself. If so, we need to make sure it's combined with the bin on it's left by setting the bin edge to the histogram max if (binSum > 0) { xBins[nBinsUsed] = tempHist->GetBinLowEdge(histbins[i]+1); } std::cout << " -->Proposed binning: " << histbins[i] << ", " << histmin[i] << ", " << histmax[i] << std::endl; std::cout << " -->Using " << nBinsUsed << " bins: "; for (int iBin = 0; iBin < nBinsUsed; ++iBin) std::cout << xBins[iBin] << ", "; std::cout << xBins[nBinsUsed] << std::endl; for (int j = 0; j < numhists; j++) { currentDir->cd(); //This is because the "Draw" command only finds profiles_Data[numhists*i+j] = new TProfile(Form("profiles_Data_%s_%s",histnames[i],histnames[j]),"",nBinsUsed,xBins); profiles_Data[numhists*i+j]->Sumw2(); profiles_Data[numhists*i+j]->SetLineWidth(2); profiles_MC[numhists*i+j] = new TProfile(Form("profiles_MC_%s_%s",histnames[i],histnames[j]),"",nBinsUsed,xBins); profiles_MC[numhists*i+j]->Sumw2(); profiles_MC[numhists*i+j]->SetLineWidth(2); } delete[] xBins; } // loop over samples for (int isam=0; isam<21; isam++){ /// get the tree file for each sample TString sample = htitle[isam]; TString fileName = "/afs/crc.nd.edu/user/w/wluo1/LHCP_2013/CMSSW_5_3_8_patch1/src/BEAN/DrawPlots/bin/treeFiles/dilSummaryTrees" +sample + "_2012_53x_July5th_all.root"; std::cout << "-->start processing sample " << fileName << std::endl; TFile * tmpfile = new TFile(fileName); TTree * tmpTree = (TTree*)tmpfile->Get("summaryTree"); TString weight = "(19450*Xsec/nGen)*weight*topPtWgt*lepTotalSF*triggerSF*csvWgtlf*csvWgthf*"; ///// before rwt if (rwt) weight = "(19450*Xsec/nGen)*weight*topPtWgt*lepTotalSF*triggerSF*csvWgtlf*csvWgthf*"; ///// after rwt TString lepCut = "((MuonEle && isMuEGTriggerPass) || (TwoEle && isDoubleElectronTriggerPass) || (TwoMuon && isDoubleMuTriggerPass))"; if (isam==18) lepCut = "(MuonEle && isMuEGTriggerPass)"; if (isam==19) lepCut = "(TwoEle && isDoubleElectronTriggerPass)"; if (isam==20) lepCut = "(TwoMuon && isDoubleMuTriggerPass)"; /// selection cut TString selection = weight; // selection += Form("%f*",lumi); //Adjust for sample normalization; selection += ("(" + cuts + "&&" + lepCut + ")"); if (isam>17) selection = ("(" + cuts + "&&" + lepCut + ")"); // no weights for data // std::cout << " -->selection is: " << selection << std::endl; ///// loop through variables for (int i = 0; i < numhists; i++){ for (int j = 0; j < numhists; j++){ TString proName = profiles_MC[numhists*i+j]->GetName(); if (isam >= 18) proName = profiles_Data[numhists*i+j]->GetName(); TString var = string(histnames[j]) + ":" + string(histnames[i])+">>+"+proName ; currentDir->cd(); //This is because the "Draw" command only finds tmpTree->Draw(var, selection, "goff"); } } tmpfile->Close(); delete tmpfile; } // end sample loop //Format the plots the way Robin does for (int i = 0; i < numhists; i++) { for (int j = 0; j < numhists; j++) { profiles_MC[numhists*i+j]->SetFillColor(2); profiles_MC[numhists*i+j]->SetLineColor(0); profiles_MC[numhists*i+j]->SetMarkerSize(0); profiles_MC[numhists*i+j]->SetFillStyle(3013); profiles_MC[numhists*i+j]->GetXaxis()->SetTitle(histXaxis[i]); profiles_MC[numhists*i+j]->GetYaxis()->SetTitle(histXaxis[j]); profiles_MC[numhists*i+j]->GetYaxis()->SetTitleOffset(1.3); double minval = 9999999.0; double maxval = -9999999.0; for(int ibin = 0; ibin < profiles_Data[numhists*i+j]->GetNbinsX(); ibin++){ if(profiles_Data[numhists*i+j]->GetBinContent(ibin+1) != 0.0){ if(profiles_Data[numhists*i+j]->GetBinContent(ibin+1)-profiles_Data[numhists*i+j]->GetBinError(ibin+1) < minval) minval = profiles_Data[numhists*i+j]->GetBinContent(ibin+1)-profiles_Data[numhists*i+j]->GetBinError(ibin+1); if(profiles_Data[numhists*i+j]->GetBinContent(ibin+1)+profiles_Data[numhists*i+j]->GetBinError(ibin+1) > maxval) maxval = profiles_Data[numhists*i+j]->GetBinContent(ibin+1)+profiles_Data[numhists*i+j]->GetBinError(ibin+1); } if(profiles_MC[numhists*i+j]->GetBinContent(ibin+1) != 0.0){ if(profiles_MC[numhists*i+j]->GetBinContent(ibin+1)-profiles_MC[numhists*i+j]->GetBinError(ibin+1) < minval) minval = profiles_MC[numhists*i+j]->GetBinContent(ibin+1)-profiles_MC[numhists*i+j]->GetBinError(ibin+1); if(profiles_MC[numhists*i+j]->GetBinContent(ibin+1)+profiles_MC[numhists*i+j]->GetBinError(ibin+1) > maxval) maxval = profiles_MC[numhists*i+j]->GetBinContent(ibin+1)+profiles_MC[numhists*i+j]->GetBinError(ibin+1); } } if(minval < 0) { profiles_MC[numhists*i+j]->SetMaximum(maxval + 0.4*fabs(maxval-1.1*minval)); profiles_MC[numhists*i+j]->SetMinimum(1.1*minval); } else { profiles_MC[numhists*i+j]->SetMaximum(maxval + 0.4*fabs(maxval-0.9*minval)); profiles_MC[numhists*i+j]->SetMinimum(0.9*minval); } } //end loop j } //end loop i //Save plots in output file TString outFileName = "corrPlots"; if (rwt) outFileName += "_rwt_"; outFileName += catName; outFileName += ".root"; TFile *outputFile = TFile::Open(outFileName,"RECREATE"); outputFile->cd(); for (int i = 0; i < numhists*numhists; ++i) { profiles_MC[i]->Write(); profiles_Data[i]->Write(); } outputFile->Close(); }
// draw the same thing but after reco void genPlots02(std::string fullPath, int nOverlay = 500, bool custBinning = false) { const int fVerbose(1); setTDRStyle(); gStyle->SetOptStat(112211); gStyle->SetPalette(1); // Canvas c = new TCanvas("c2","c2",1000,600); const unsigned int nPadX = 1; const unsigned int nPadY = 1; c->Divide(nPadX,nPadY); const unsigned int nPads=nPadX*nPadY; for(unsigned int i=1; i<=nPads; i++) { TPad* pad= (TPad*)c->cd(i); pad->SetTopMargin(0.10); pad->SetRightMargin(0.20); pad->SetLeftMargin(0.15); } // Open file TFile *f = TFile::Open(fullPath.c_str()); if (f==0) { cout << "File " << fullPath << " not found -- exiting" << endl; return; } if(fVerbose>0) cout << "Succesfully opened file " << fullPath << endl; // Get TTree TTree* t = (TTree*) f->Get("events"); if(fVerbose>0) cout << "Got TTree with " << t->GetEntries() << " entries" << endl; // Do a cut, if needed //t->Draw(">>lst","chi2lb>.1&&mlb>5.61&&mlb<5.63"); //t->Draw(">>lst","chi2lb>.1&&isSig==1"); t->Draw(">>lst","(rid1m&4)==4&&(rid2m&4)==4&&mjp>2.895&&mjp<3.295&&prob1m>0.1&&prob2m>0.1&&ptjp>2&&probjp>0.005&&ml0>1.101&&ml0<1.129&&probpr>0.02&&probpi>0.02&&rptpr>rptpi&&ptl0>3&&rptpr>1&&rptpi>0.5&&probl0>0.02&&alphal0<0.3&&d3l0>1&&d3l0/d3El0>10&&problb>0.001&&alphalb<0.3"); TEventList *lst; lst = (TEventList*)gDirectory->Get("lst"); t->SetEventList(lst); if(fVerbose>0) cout << "Got TTree with " << t->GetEntries() << " entries" << endl; // Do plots c->cd(1); //doPlot2d(t,"hrzL0vtx", "vrl0:TMath::Abs(vzl0)",30,0,300,30,0,120,"Tit","|z|","r","cm","cm"); if (custBinning) { double newbinsX[]={0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50}; const int newbinsX_size = sizeof(newbinsX)/sizeof(double); std::vector<double> binvecX(newbinsX,newbinsX+newbinsX_size); //double newbinsY[]={0,1,2,3,4,5,6,7,8,9,10}; double newbinsY[]={0,0.5,1,2,4,8,16,32}; const int newbinsY_size = sizeof(newbinsY)/sizeof(double); std::vector<double> binvecY(newbinsY,newbinsY+newbinsY_size); doPlot2d(t,"hrzL0vtxreco", "vrl0:TMath::Abs(vzl0)",binvecX, binvecY,"#Lambda vertices","|z|","r","cm","cm"); } else { doPlot2d(t,"hrzL0vtxreco", "vrl0:TMath::Abs(vzl0)",30,0,50,30,0,30,"#Lambda vertices","|z|","r","cm","cm"); } // add tracker TPad* pad; pad = (TPad*)c->cd(1); pad->Modified(); pad->Update(); repositionPalette("hrzL0vtxreco"); pad->Update(); pad->SetLogz(); drawTracker(pad); if (nOverlay<=0) return; int maxN = nOverlay; if (maxN > t->GetEntries()) maxN = t->GetEntries(); double vrl0,vzl0,ppr,ppi,etapr,etapi; t->SetBranchAddress("vrl0",&vrl0); t->SetBranchAddress("vzl0",&vzl0); t->SetBranchAddress("ppr",&ppr); t->SetBranchAddress("etapr",&etapr); t->SetBranchAddress("ppi",&ppi); t->SetBranchAddress("etapi",&etapi); double scalepr = 4; double scalepi = 8; { // reference indicator const double x1pr = 0; const double y1pr = -3; const double x2pr = scalepr; const double y2pr = y1pr; const double versatz = 14; const double x1pi = x1pr+versatz; const double y1pi = -3; const double x2pi = x2pr+versatz+scalepi; const double y2pi = y1pi; TArrow *a; a = new TArrow(x1pr,y1pr,x2pr,y2pr,.01,">"); a->SetLineColor(24); a->Draw(); TLatex tl; tl.SetTextSize(20); tl.SetTextFont(4); tl.DrawLatex(x1pr,y2pr-1.2,"p(p) / 1 GeV"); a = new TArrow(x1pi,y1pi,x2pi,y2pi,.01,">"); a->SetLineColor(20); a->Draw(); tl.SetTextSize(20); tl.SetTextFont(4); tl.DrawLatex(x1pi,y2pi-1.2,"p(#pi) / 1 GeV"); } for (int i = 0; i!=maxN; i++) { t->GetEntry(i); const double thetapr = 2*TMath::ATan(TMath::Exp(-TMath::Abs(etapr))); const double thetapi = 2*TMath::ATan(TMath::Exp(-TMath::Abs(etapi))); const double x1=TMath::Abs(vzl0); const double y1=vrl0; const double x2pr=x1+scalepr*ppr*TMath::Cos(thetapr); const double y2pr=y1+scalepr*ppr*TMath::Sin(thetapr); const double x2pi=x1+scalepi*ppi*TMath::Cos(thetapi); const double y2pi=y1+scalepi*ppi*TMath::Sin(thetapi); TArrow *a; a = new TArrow(x1,y1,x2pr,y2pr,.01,">"); a->SetLineColor(24); a->Draw(); a = new TArrow(x1,y1,x2pi,y2pi,.01,">"); a->SetLineColor(20); a->Draw(); TMarker *m = new TMarker(x1,y1,7); m->SetMarkerColor(28); m->Draw(); } }
void plotDeltaPhi(int cbin, TString infname, TString pythia, TString mix, bool useWeight, bool drawXLabel, bool drawLeg) { TString cut="pt1>100 && pt2>40"; TString cutpp="pt1>100 && et2>40"; TString cstring = ""; if(cbin==0) { cstring = "0-10%"; cut+=" && bin>=0 && bin<4"; cut+=" && ((pt1-pt2)/(pt1+pt2) < 0.3)"; } else if (cbin==1) { cstring = "10-30%"; cut+=" && bin>=4 && bin<12"; cut+=" && ((et1-et2)/(et1+et2) < 0.3)"; } else { cstring = "30-100%"; cut+=" && bin>=12 && bin<40"; cut+=" && ((et1-et2)/(et1+et2) < 0.3)"; } // open the data file TFile *inf = new TFile(infname.Data()); TTree *nt =(TTree*)inf->FindObjectAny("nt"); // open the pythia (MC) file TFile *infPythia = new TFile(pythia.Data()); TTree *ntPythia = (TTree*) infPythia->FindObjectAny("nt"); // open the datamix file TFile *infMix = new TFile(mix.Data()); TTree *ntMix =(TTree*)infMix->FindObjectAny("nt"); // projection histogram TH1D *h = new TH1D("h","",20,-2.4,2.4); TH1D *hPythia = new TH1D("hPythia","",20,-2.4,2.4); TH1D *hDataMix = new TH1D("hDataMix","",20,-2.4,2.4); nt->Draw("eta1>>h",Form("(%s)",cut.Data())); if (useWeight) { // use the weight value caluculated by Matt's analysis macro ntPythia->Draw("eta1>>hPythia",Form("(%s)",cutpp.Data())); ntMix->Draw("eta1>>hDataMix",Form("(%s)*weight",cut.Data())); } else { // ignore centrality reweighting ntPythia->Draw("eta1>>hPythia",Form("(%s)",cutpp.Data())); ntMix->Draw("eta1>>hDataMix",Form("(%s)",cut.Data())); } // calculate the statistical error and normalize h->Sumw2(); h->Scale(1./h->GetEntries()); h->SetMarkerStyle(20); hPythia->Scale(1./hPythia->Integral(0,20)); hPythia->SetLineColor(kBlue); hPythia->SetFillColor(kAzure-8); hPythia->SetFillStyle(3005); hPythia->SetStats(0); hPythia->Draw("hist"); if(drawXLabel) hPythia->SetXTitle("Leading jet #eta"); hPythia->GetXaxis()->SetLabelSize(20); hPythia->GetXaxis()->SetLabelFont(43); hPythia->GetXaxis()->SetTitleSize(22); hPythia->GetXaxis()->SetTitleFont(43); hPythia->GetXaxis()->SetTitleOffset(1.5); hPythia->GetXaxis()->CenterTitle(); //hPythia->GetXaxis()->SetNdivisions(905,true); hPythia->SetYTitle("Event Fraction"); hPythia->GetYaxis()->SetLabelSize(20); hPythia->GetYaxis()->SetLabelFont(43); hPythia->GetYaxis()->SetTitleSize(20); hPythia->GetYaxis()->SetTitleFont(43); hPythia->GetYaxis()->SetTitleOffset(2.5); hPythia->GetYaxis()->CenterTitle(); hPythia->SetAxisRange(9E-4,5.9,"Y"); hDataMix->SetAxisRange(9E-4,5.9,"Y"); h->SetAxisRange(9E-4,1.9,"Y"); h->Draw("same"); hDataMix->Scale(1./hDataMix->Integral(0,20)); hDataMix->SetLineColor(kRed); hDataMix->SetFillColor(kRed-9); hDataMix->SetFillStyle(3004); hDataMix->Draw("same"); if(drawLeg){ TLegend *t3=new TLegend(0.05,0.72,0.59,0.88); t3->AddEntry(h,"Pb+Pb #sqrt{s}_{_{NN}}=2.76 TeV","pl"); t3->AddEntry(hPythia,"PYTHIA","lf"); t3->AddEntry(hDataMix,"embedded PYTHIA","lf"); t3->SetFillColor(0); t3->SetBorderSize(0); t3->SetFillStyle(0); t3->SetTextFont(63); t3->SetTextSize(15); t3->Draw(); } }
void MakePID(){ FILE* aoq_in = fopen("cutParameters/PID/Sn132/peak_aoq_in.txt","w"); FILE* aoq_out = fopen("cutParameters/PID/Sn132/peak_aoq_out.txt","w"); FILE* zet_in = fopen("cutParameters/PID/Sn132/peak_zet_in.txt","w"); FILE* zet_out = fopen("cutParameters/PID/Sn132/peak_zet_out.txt","w"); TH1F* h1_AOQ[64][2]; TH1F* h1_ZET[64][2]; TCanvas* can_AOQ[4][2]; TCanvas* can_ZET[4][2]; for(Int_t ii = 0; ii<4;ii++){ can_AOQ[ii][0] = new TCanvas(Form("can_AOQ_0_%i",ii), "AOQ 0"); can_AOQ[ii][0] ->Divide(4,4); can_AOQ[ii][1] = new TCanvas(Form("can_AOQ_2_%i",ii), "AOQ 2"); can_AOQ[ii][1] ->Divide(4,4); can_ZET[ii][0] = new TCanvas(Form("can_ZET_0_%i",ii), "ZET 0"); can_ZET[ii][0] ->Divide(4,4); can_ZET[ii][1] = new TCanvas(Form("can_ZET_2_%i",ii), "ZET 2"); can_ZET[ii][1] ->Divide(4,4); } Int_t ican = 0, ipad = 1, nentries = (int)3e5;//run = 9, Float_t aoq = 2.64, zet = 50.; TF1* f1_aoq[64][2],*f1_zet[64][2]; for(Int_t run = 9; run<64;run++){ for(short ii = 0; ii < 2; ii++){ f1_aoq[run][ii] = new TF1(Form("f1_aoq_%i_%02d",ii,run),"gaus(0)+pol0(3)",2.63,2.665); f1_zet[run][ii] = new TF1(Form("f1_zet_%i_%02d",ii,run),"gaus(0)+pol0(3)",48,52); f1_zet[run][ii]->SetParLimits(0,10,1e6); f1_zet[run][ii]->SetParameter(1,12e3); f1_zet[run][ii]->SetParameter(1,zet); f1_zet[run][ii]->SetParLimits(1,zet-1.5,zet+4.5); f1_zet[run][ii]->SetParameter(2,0.5); f1_zet[run][ii]->SetParLimits(2,0,1.); f1_aoq[run][ii]->SetParLimits(0,10,1e6); f1_aoq[run][ii]->SetParameter(1,12e3); f1_aoq[run][ii]->SetParameter(1,aoq); f1_aoq[run][ii]->SetParLimits(1,aoq-0.1,aoq+0.1); f1_aoq[run][ii]->SetParameter(2,2e-3); f1_aoq[run][ii]->SetParLimits(2,0,5e-3); }//for (ii) TFile* _file = TFile::Open(Form("data/rootfiles/new/run%04d.root",run)); TTree* tree = (TTree*)_file->Get("tree"); h1_AOQ[run][0] = new TH1F(Form("h1_AOQ_%i_0",run),Form("run %i, AOQ 0", run),400,2.5,2.7); h1_AOQ[run][1] = new TH1F(Form("h1_AOQ_%i_2",run),Form("run %i, AOQ 2", run),400,2.5,2.7); h1_ZET[run][0] = new TH1F(Form("h1_ZET_%i_0",run),Form("run %i, ZET 0", run),200,45,55); h1_ZET[run][1] = new TH1F(Form("h1_ZET_%i_2",run),Form("run %i, ZET 2", run),200,45,55); tree->Draw(Form("AOQ[0]>>h1_AOQ_%i_0",run),"TMath::Abs(ZET[0]-50)<0.5","",nentries,0); tree->Draw(Form("ZET[0]>>h1_ZET_%i_0",run),"TMath::Abs(AOQ[0]-2.64)<0.005","",nentries,0); tree->Draw(Form("AOQ[2]>>h1_AOQ_%i_2",run),"TMath::Abs(ZET[0]-50)<0.5 && TMath::Abs(AOQ[0]-2.64)<0.005 && TMath::Abs(delta[2]-delta[4])<0.5","",nentries,0); tree->Draw(Form("ZET[2]>>h1_ZET_%i_2",run),"TMath::Abs(ZET[0]-50)<0.5 && TMath::Abs(AOQ[0]-2.64)<0.005 && TMath::Abs(AOQ[2]-2.64)<0.005","",nentries,0); can_AOQ[ican][0]->cd(ipad); h1_AOQ[run][0]->Draw(); h1_AOQ[run][0]->Fit(f1_aoq[run][0]); can_AOQ[ican][1]->cd(ipad); h1_AOQ[run][1]->Draw(); h1_AOQ[run][1]->Fit(f1_aoq[run][1]); can_ZET[ican][0]->cd(ipad); h1_ZET[run][0]->Draw(); h1_ZET[run][0]->Fit(f1_zet[run][0]); can_ZET[ican][1]->cd(ipad); h1_ZET[run][1]->Draw(); h1_ZET[run][1]->Fit(f1_zet[run][1]); if(ipad==16){ ipad = 1; ican++; }else ipad++; fprintf(aoq_in,"%i %f %f \n", run, f1_aoq[run][0]->GetParameter(1),f1_aoq[run][0]->GetParameter(2)); fprintf(aoq_out,"%i %f %f \n", run, f1_aoq[run][1]->GetParameter(1),f1_aoq[run][1]->GetParameter(2)); fprintf(zet_in,"%i %f %f \n", run, f1_zet[run][0]->GetParameter(1),f1_zet[run][0]->GetParameter(2)); fprintf(zet_out,"%i %f %f \n", run, f1_zet[run][1]->GetParameter(1),f1_zet[run][1]->GetParameter(2)); //delete _file; //delete tree; } fclose(aoq_in); fclose(aoq_out); fclose(zet_in); fclose(zet_out); }
void efficiency(TString inputname, TString outputname="hists_efficiencies.root",TString mvacut="0.8",TString friendfile=""){ TString INFV="(abs(nuvtxx_truth)<360-50&&abs(nuvtxy_truth)<600-50&&nuvtxz_truth>50&&nuvtxz_truth<1394-150)"; TString SIGNAL_DEF="(abs(beamPdg)==14 && abs(neu)==12 && cc==1 &&"+ INFV + ")"; TString WEIGHTING="projected_weight"; gROOT->SetStyle("T2K"); //Figure out how we are going to select //Normal selection mode TString SELECTION="mvaresult>"+mvacut; //Selecting with a friend tree if (friendfile!=""){ SELECTION="mvatree.newmvaresult>"+mvacut; } //Get the file TFile *file = new TFile(inputname,"READ"); //Get the tree TTree *MVASelection = (TTree*) file->Get("mvaselect/MVASelection"); //If asked for, get the friend tree if (friendfile!=""){ MVASelection->AddFriend("mvatree",friendfile); } //ENu TH1F *h_enu_sig = new TH1F("h_enu_sig","h_enu_sig",25,0,10); h_enu_sig->Sumw2(); h_enu_sig->GetXaxis()->SetTitle("E_{#nu} (GeV)"); h_enu_sig->GetYaxis()->SetTitle("No. #nu"); TH1F *h_enu_sel_sig = new TH1F("h_enu_sel_sig","h_enu_sel_sig",25,0,10); h_enu_sel_sig->Sumw2(); h_enu_sel_sig->SetLineColor(4); h_enu_sel_sig->SetLineColor(4); h_enu_sel_sig->SetFillColor(4); h_enu_sel_sig->SetFillStyle(3003); h_enu_sel_sig->GetXaxis()->SetTitle("E_{#nu} (GeV)"); h_enu_sel_sig->GetYaxis()->SetTitle("No. #nu"); MVASelection->Draw("Ev >> h_enu_sig",WEIGHTING+"*("+SIGNAL_DEF+")"); MVASelection->Draw("Ev >> h_enu_sel_sig",WEIGHTING+"*("+SIGNAL_DEF+"&&"+SELECTION+")"); TEfficiency *h_eff_enu = new TEfficiency(*h_enu_sel_sig,*h_enu_sig); h_eff_enu->SetTitle(TString("eff;")+h_enu_sig->GetXaxis()->GetTitle()+TString(";Efficiency (No units)")); //h_eff_enu->Draw(); //Q2 TH1F *h_q2_sig = new TH1F("h_q2_sig","h_q2_sig",25,0,10); h_q2_sig->Sumw2(); h_q2_sig->SetFillStyle(3003); h_q2_sig->SetFillColor(1); h_q2_sig->GetXaxis()->SetTitle("Q^{2} (GeV^{2})"); h_q2_sig->GetYaxis()->SetTitle("No. #nu"); TH1F *h_q2_sel_sig = new TH1F("h_q2_sel_sig","h_q2_sel_sig",25,0,10); h_q2_sel_sig->Sumw2(); h_q2_sel_sig->SetLineColor(4); h_q2_sel_sig->SetFillColor(4); h_q2_sel_sig->SetFillStyle(3003); h_q2_sel_sig->GetXaxis()->SetTitle("Q^{2} (GeV^{2})"); h_q2_sel_sig->GetYaxis()->SetTitle("No. #nu"); MVASelection->Draw("Q2 >> h_q2_sig",WEIGHTING+"*("+SIGNAL_DEF+")"); MVASelection->Draw("Q2 >> h_q2_sel_sig",WEIGHTING+"*("+SIGNAL_DEF+"&&"+SELECTION+")"); TEfficiency *h_eff_q2 = new TEfficiency(*h_q2_sel_sig,*h_q2_sig); h_eff_q2->SetTitle(TString("eff;")+h_q2_sig->GetXaxis()->GetTitle()+TString(";Efficiency (No units)")); //Lepton angle TH1F *h_lepangle_sig = new TH1F("h_lepangle_sig","h_lepangle_sig",25,0,180); h_lepangle_sig->Sumw2(); h_lepangle_sig->SetFillStyle(3003); h_lepangle_sig->SetFillColor(1); h_lepangle_sig->GetXaxis()->SetTitle("Lepton angle to neutrino (degrees)"); h_lepangle_sig->GetYaxis()->SetTitle("No. #nu"); TH1F *h_lepangle_sel_sig = new TH1F("h_lepangle_sel_sig","h_lepangle_sel_sig",25,0,180); h_lepangle_sel_sig->Sumw2(); h_lepangle_sel_sig->SetLineColor(4); h_lepangle_sel_sig->SetFillColor(4); h_lepangle_sel_sig->SetFillStyle(3003); h_lepangle_sel_sig->GetXaxis()->SetTitle("Lepton angle to neutrino (degrees)"); h_lepangle_sel_sig->GetYaxis()->SetTitle("No. #nu"); MVASelection->Draw("LepNuAngle*180/3.14159265359 >> h_lepangle_sig",WEIGHTING+"*("+SIGNAL_DEF+")"); MVASelection->Draw("LepNuAngle*180/3.14159265359 >> h_lepangle_sel_sig",WEIGHTING+"*("+SIGNAL_DEF+"&&"+SELECTION+")"); TEfficiency *h_eff_lepangle = new TEfficiency(*h_lepangle_sel_sig,*h_lepangle_sig); h_eff_lepangle->SetTitle(TString("eff;")+h_lepangle_sig->GetXaxis()->GetTitle()+TString(";Efficiency (No units)")); //Lepton momentum TH1F *h_lepmom_sig = new TH1F("h_lepmom_sig","h_lepmom_sig",25,0,10); h_lepmom_sig->Sumw2(); h_lepmom_sig->SetFillStyle(3003); h_lepmom_sig->SetFillColor(1); h_lepmom_sig->GetXaxis()->SetTitle("Lepton momentum (GeV)"); h_lepmom_sig->GetYaxis()->SetTitle("No. #nu"); TH1F *h_lepmom_sel_sig = new TH1F("h_lepmom_sel_sig","h_lepmom_sel_sig",25,0,10); h_lepmom_sel_sig->Sumw2(); h_lepmom_sel_sig->SetLineColor(4); h_lepmom_sel_sig->SetFillColor(4); h_lepmom_sel_sig->SetFillStyle(3003); h_lepmom_sel_sig->GetXaxis()->SetTitle("Lepton momentum (GeV)"); h_lepmom_sel_sig->GetYaxis()->SetTitle("No. #nu"); MVASelection->Draw("sqrt(LepMomX*LepMomX + LepMomY*LepMomY + LepMomZ*LepMomZ) >> h_lepmom_sig",WEIGHTING+"*("+SIGNAL_DEF+")"); MVASelection->Draw("sqrt(LepMomX*LepMomX + LepMomY*LepMomY + LepMomZ*LepMomZ) >> h_lepmom_sel_sig",WEIGHTING+"*("+SIGNAL_DEF+"&&"+SELECTION+")"); TEfficiency *h_eff_lepmom = new TEfficiency(*h_lepmom_sel_sig,*h_lepmom_sig); h_eff_lepmom->SetTitle(TString("eff;")+h_lepmom_sig->GetXaxis()->GetTitle()+TString(";Efficiency (No units)")); TFile *output = new TFile(outputname,"RECREATE"); h_enu_sig->Write(); h_enu_sel_sig->Write(); h_eff_enu->Write(); h_q2_sig->Write(); h_q2_sel_sig->Write(); h_eff_q2->Write(); h_lepangle_sig->Write(); h_lepangle_sel_sig->Write(); h_eff_lepangle->Write(); h_lepmom_sig->Write(); h_lepmom_sel_sig->Write(); h_eff_lepmom->Write(); output->Close(); /* h_eff_q2->Draw(); gPad->Update(); h_eff_q2->GetPaintedGraph()->SetMaximum(1.05); h_eff_q2->GetPaintedGraph()->SetMinimum(0.0); h_eff_q2->GetPaintedGraph()->GetXaxis()->SetRangeUser(0,10.); h_q2_sig->Scale(1./h_q2_sig->GetMaximum()); */ //Oscillation probability stuff if required /* float osc_dm2=0.002457; float osc_L=1300.; float th13 = 0.148; float th23 = 0.738; TF1 *osceq = new TF1("f2","[4]*(1-(cos([2])^2*sin(2*[3])^2+sin([3])^4*sin(2*[2])^2)*sin(1.267*[0]*[1]/x)*sin(1.267*[0]*[1]/x))",0.,10.); osceq->SetParameters(osc_dm2,osc_L,th13,th23,h_enu_sig->GetMaximum()*0.8); osceq->SetLineStyle(2); osceq->Draw("same"); */ }
int plot_Fun4All_All_DeltaEta_DeltaPhi() { const std::string inFile = "LeptoAna_1000events_All.root"; const std::string inDirectory = "/gpfs/mnt/gpfs02/phenix/scratch/jlab/Leptoquark/"; std::string inputFile = inDirectory+inFile; TFile *f = TFile::Open(inputFile.c_str()); TTree *t = (TTree*)f->Get("ntp_leptoquark"); // const int Nevent = t->GetMaximum("event"); const int Nevent = 100; cout << "Running " << Nevent << " events" << endl; const int Nentries1 = t->Draw("isMaxEnergyJet","(isMaxEnergyJet<10)*(calorimeterid<10)","goff"); Double_t *arr_jet = t->GetV1(); vector<int> v_jet(Nentries1); for(int i = 0; i < Nentries1; i++) { v_jet[i] = (int)arr_jet[i]; } const int Nentries = t->Draw("towereta:towerphi:towerenergy:event","(isMaxEnergyJet<10)*(calorimeterid<10)","goff"); Double_t *arr_eta = t->GetV1(); Double_t *arr_phi = t->GetV2(); Double_t *arr_e = t->GetV3(); Double_t *arr_event = t->GetV4(); if(Nentries1 != Nentries) { cerr << "ERROR: Draw commands to not return the same dimensions. Check that your logical expressions are the same." << endl; return -1; } vector<double> v_DeltaEta, v_DeltaPhi, v_DeltaTheta, v_Energy; vector<double> v_DeltaEta_j2, v_DeltaPhi_j2, v_DeltaTheta_j2, v_Energy_j2; for(int i = 0; i < Nevent; i++) { double Emax = 0; int Emax_i = 0; double Emax_j2 = 0; int Emax_i_j2 = 0; for(int j = 0; j < Nentries; j++) { if((t->GetV4()[j]-1 == i) && (v_jet[j] == 1)) { if(t->GetV3()[j] > Emax) { Emax = t->GetV3()[j]; Emax_i = j; } } if((t->GetV4()[j]-1 == i) && (v_jet[j] == 2)) { if(t->GetV3()[j] > Emax_j2) { Emax_j2 = t->GetV3()[j]; Emax_i_j2 = j; } } } for(int j = 0; j < Nentries; j++) { if((t->GetV4()[j]-1 == i) && (v_jet[j] == 1)) { v_DeltaEta.push_back(t->GetV1()[j] - t->GetV1()[Emax_i]); v_DeltaTheta.push_back(2*TMath::ATan(TMath::Power(TMath::E(),-1*t->GetV1()[j])) - 2*TMath::ATan(TMath::Power(TMath::E(),-1*t->GetV1()[Emax_i]))); v_DeltaPhi.push_back(t->GetV2()[j] - t->GetV2()[Emax_i]); v_Energy.push_back(t->GetV3()[j]); } if((t->GetV4()[j]-1 == i) && (v_jet[j] == 2)) { v_DeltaEta_j2.push_back(t->GetV1()[j] - t->GetV1()[Emax_i_j2]); v_DeltaTheta_j2.push_back(2*TMath::ATan(TMath::Power(TMath::E(),-1*t->GetV1()[j])) - 2*TMath::ATan(TMath::Power(TMath::E(),-1*t->GetV1()[Emax_i_j2]))); v_DeltaPhi_j2.push_back(t->GetV2()[j] - t->GetV2()[Emax_i_j2]); v_Energy_j2.push_back(t->GetV3()[j]); } } } //----------------------------------------------------------------------------------------------------------- gStyle->SetOptStat(0); double xmin = -1; double xmax = 1; double ymin = -0.5; double ymax = 0.5; std::string title = "isMaxJetEnergy = 1"; TCanvas *c1 = new TCanvas(); TH2D *h1 = new TH2D("h1",title.c_str(),40,xmin,xmax,40,ymin,ymax); for(int i = 0; (unsigned)i < v_DeltaEta.size(); i++) { h1->Fill(v_DeltaEta[i],v_DeltaPhi[i], v_Energy[i]/Nevent); } c1->SetLogz(); h1->Draw("colz"); // h1->SetMinimum(1); // h1->SetMaximum(1000); h1->GetXaxis()->SetTitle("#Delta#eta"); h1->GetYaxis()->SetTitle("#Delta#phi"); c1->Update(); //----------------------------------------------------------------------------------------------------------- std::string title2 = "isMaxJetEnergy = 2"; TCanvas *c2 = new TCanvas(); TH2D *h2 = new TH2D("h2",title2.c_str(),40,xmin,xmax,40,ymin,ymax); for(int i = 0; (unsigned)i < v_DeltaEta_j2.size(); i++) { h2->Fill(v_DeltaEta_j2[i],v_DeltaPhi_j2[i], v_Energy_j2[i]/Nevent); } c2->SetLogz(); h2->Draw("colz"); // h2->SetMinimum(1); // h2->SetMaximum(1000); h2->GetXaxis()->SetTitle("#Delta#eta"); h2->GetYaxis()->SetTitle("#Delta#phi"); c2->Update(); //----------------------------------------------------------------------------------------------------------- TCanvas *c3 = new TCanvas(); TH1D *h3 = h1->ProjectionY(); h3->SetLineColor(kGreen+3); TH1D *h4 = h2->ProjectionY(); h4->SetLineColor(kBlue); TF1 *f3 = new TF1("f3", "gaus", ymin, ymax); f3->SetLineColor(kGreen+3); h3->Fit("f3","Q R"); TF1 *f4 = new TF1("f4", "gaus", ymin, ymax); f4->SetLineColor(kBlue+2); h4->Fit("f4","Q R"); h3->Draw(); h4->Draw("SAME"); TLegend *leg = new TLegend(0.2,0.9,0.7,0.75); leg->SetBorderSize(1); leg->AddEntry(h3,title.c_str(),"l"); leg->AddEntry(h4,title2.c_str(),"l"); leg->Draw("SAME"); c3->Update(); cout << endl; cout << "*******************************************************" << endl; cout << "Ratio of Gaussian Width to Max Energy:" << endl; cout << " for: " << title << " -> " << f3->GetParameter(2) << " / " << h3->GetBinContent(h3->GetMaximumBin()) << " = " << f3->GetParameter(2) / h3->GetBinContent(h3->GetMaximumBin()) << endl; cout << " for: " << title2 << " -> " << f4->GetParameter(2) << " / " << h4->GetBinContent(h4->GetMaximumBin()) << " = " << f4->GetParameter(2) / h4->GetBinContent(h4->GetMaximumBin()) << endl; cout << " Ratio of ratios: " << (f3->GetParameter(2) / h3->GetBinContent(h3->GetMaximumBin())) / (f4->GetParameter(2) / h4->GetBinContent(h4->GetMaximumBin())) << endl; cout << "*******************************************************" << endl; cout << endl; c1->Close(); c2->Close(); c3->Close(); //----------------------------------------------------------------------------------------------------------- vector<double> v_Ratios; for(int i = 0; i < Nevent; i++) { TH1D *h5 = new TH1D("h5","",20,ymin*2,ymax*2); TH1D *h6 = new TH1D("h6","",20,ymin*2,ymax*2); for(int j = 0; j < Nentries/100; j++) { if((t->GetV4()[j]-1 == i) && (v_jet[j] == 1)) { h5->Fill(v_DeltaPhi[j], v_Energy[j]); } if((t->GetV4()[j]-1 == i) && (v_jet[j] == 2)) { h6->Fill(v_DeltaPhi_j2[j], v_Energy_j2[j]); } } TF1 *f5 = new TF1("f5", "gaus", ymin, ymax); f3->SetLineColor(kGreen+3); h5->Fit("f5","Q"); TF1 *f6 = new TF1("f6", "gaus", ymin, ymax); f6->SetLineColor(kBlue+2); h6->Fit("f6","Q"); TCanvas *c5 = new TCanvas(); h5->Draw(); TCanvas *c6 = new TCanvas(); h6->Draw(); // cout << endl; // cout << "Ratio of Gaussian Width to Max Energy:" << endl; // cout << " for: " << title << " -> " << f5->GetParameter(2) << " / " << h5->GetBinContent(h5->GetMaximumBin()) // << " = " << f5->GetParameter(2) / h5->GetBinContent(h5->GetMaximumBin()) << endl; // cout << " for: " << title2 << " -> " << f6->GetParameter(2) << " / " << h6->GetBinContent(h6->GetMaximumBin()) // << " = " << f6->GetParameter(2) / h6->GetBinContent(h6->GetMaximumBin()) << endl; cout << " Ratio of ratios for event " << i+1 << " : " << (f5->GetParameter(2) / h5->GetBinContent(h5->GetMaximumBin())) / (f6->GetParameter(2) / h6->GetBinContent(h6->GetMaximumBin())) << endl; if((f5->GetParameter(2) / h5->GetBinContent(h5->GetMaximumBin())) / (f6->GetParameter(2) / h6->GetBinContent(h6->GetMaximumBin())) != NAN) v_Ratios.push_back((f5->GetParameter(2) / h5->GetBinContent(h5->GetMaximumBin())) / (f6->GetParameter(2) / h6->GetBinContent(h6->GetMaximumBin()))); delete h5; delete h6; c5->Close(); c6->Close(); } TCanvas *c7 = new TCanvas(); TH1D *h7 = new TH1D("h7","",400,-200,200); for(int i = 0; (unsigned)i < v_Ratios.size(); i++) { h7->Fill(v_Ratios[i]); } h7->Draw(); return 0; }
void printAccTable () { //---------------------------------- // // Global job params // File names, etc //--------------------------------- TString ttHFileName = "batchBEAN/merged/ttH_m120_dilepStudy_withSummaryTree_merged.root"; TString ttBarFileName = "batchBEAN/merged/ttbar_dilepStudy_withSummaryTree_merged.root"; // units are fb and inverse fb double xsec_ttH = 198; double xsec_ttBar = 157500; double lumi = 15; TFile * ttHFile = new TFile(ttHFileName); TTree * ttHSummaryTree = (TTree *) ttHFile->Get("summaryTree"); // this is your baseline double ttH_numEvents = ttHSummaryTree->GetEntries(); double ttH_numClean = ttHSummaryTree->Draw("numJets","(isCleanEvent==1) ","goff"); double ttH_numCleanAndTrig = ttHSummaryTree->Draw("numJets","(isCleanEvent==1) && (isTriggerPass==1)","goff"); cout << "Done with ttH first selections, moving on to details for ttH " << endl; // two tight muons double ttH_numTwoTightMuon = ttHSummaryTree->Draw("numJets","(isCleanEvent==1) && (isTriggerPass==1) && (numTightMuons ==2) && (numTightElectrons ==0) && (numLooseMuons == 0) && (numLooseElectrons == 0 )","goff"); double ttH_numTwoTightMuonGe2j = ttHSummaryTree->Draw("numJets","(isCleanEvent==1) && (isTriggerPass==1) && (numTightMuons ==2) && (numTightElectrons ==0) && (numLooseMuons == 0) && (numLooseElectrons == 0 ) && (numJets >=2)","goff"); double ttH_numTwoTightMuonGe2t = ttHSummaryTree->Draw("numJets","(isCleanEvent==1) && (isTriggerPass==1) && (numTightMuons ==2) && (numTightElectrons ==0) && (numLooseMuons == 0) && (numLooseElectrons == 0 ) && (numJets >=2) && (numTaggedJets>=2)","goff"); double ttH_numTwoTightMuon2jEq2t = ttHSummaryTree->Draw("numJets","(isCleanEvent==1) && (isTriggerPass==1) && (numTightMuons ==2) && (numTightElectrons ==0) && (numLooseMuons == 0) && (numLooseElectrons == 0 ) && (numJets ==2) && (numTaggedJets==2)","goff"); double ttH_numTwoTightMuon3jEq2t = ttHSummaryTree->Draw("numJets","(isCleanEvent==1) && (isTriggerPass==1) && (numTightMuons ==2) && (numTightElectrons ==0) && (numLooseMuons == 0) && (numLooseElectrons == 0 ) && (numJets ==3) && (numTaggedJets==2)","goff"); double ttH_numTwoTightMuon4jEq2t = ttHSummaryTree->Draw("numJets","(isCleanEvent==1) && (isTriggerPass==1) && (numTightMuons ==2) && (numTightElectrons ==0) && (numLooseMuons == 0) && (numLooseElectrons == 0 ) && (numJets ==4) && (numTaggedJets==2)","goff"); double ttH_numTwoTightMuon3jEq3t = ttHSummaryTree->Draw("numJets","(isCleanEvent==1) && (isTriggerPass==1) && (numTightMuons ==2) && (numTightElectrons ==0) && (numLooseMuons == 0) && (numLooseElectrons == 0 ) && (numJets ==3) && (numTaggedJets==3)","goff"); double ttH_numTwoTightMuon4jEq3t = ttHSummaryTree->Draw("numJets","(isCleanEvent==1) && (isTriggerPass==1) && (numTightMuons ==2) && (numTightElectrons ==0) && (numLooseMuons == 0) && (numLooseElectrons == 0 ) && (numJets ==4) && (numTaggedJets==3)","goff"); double ttH_numTwoTightMuonGe3t = ttHSummaryTree->Draw("numJets","(isCleanEvent==1) && (isTriggerPass==1) && (numTightMuons ==2) && (numTightElectrons ==0) && (numLooseMuons == 0) && (numLooseElectrons == 0 ) && (numJets >=3) && (numTaggedJets>=3)","goff"); double ttH_numTwoTightMuonEq4t = ttHSummaryTree->Draw("numJets","(isCleanEvent==1) && (isTriggerPass==1) && (numTightMuons ==2) && (numTightElectrons ==0) && (numLooseMuons == 0) && (numLooseElectrons == 0 ) && (numJets ==4) && (numTaggedJets==4)","goff"); double ttH_numTwoTightMuonGe3jEq2t = ttHSummaryTree->Draw("numJets","(isCleanEvent==1) && (isTriggerPass==1) && (numTightMuons ==2) && (numTightElectrons ==0) && (numLooseMuons == 0) && (numLooseElectrons == 0 ) && (numJets >=3) && (numTaggedJets==2)","goff"); cout << "Starting ttBar selections " << endl; ttHFile->Close(); // ttbar two tight TFile * ttBarFile = new TFile (ttBarFileName); TTree * ttBarSummaryTree = (TTree *) ttBarFile->Get("summaryTree"); double ttBar_numEvents = ttBarSummaryTree->GetEntries(); double ttBar_numClean = ttBarSummaryTree->Draw("numJets","(isCleanEvent==1) ","goff"); double ttBar_numCleanAndTrig = ttBarSummaryTree->Draw("numJets","(isCleanEvent==1) && (isTriggerPass==1)","goff"); double ttBar_numTwoTightMuon = ttBarSummaryTree->Draw("numJets","(isCleanEvent==1) && (isTriggerPass==1) && (numTightMuons ==2) && (numTightElectrons ==0) && (numLooseMuons == 0) && (numLooseElectrons == 0 )","goff"); cout << "One" << endl; double ttBar_numTwoTightMuonGe2j = ttBarSummaryTree->Draw("numJets","(isCleanEvent==1) && (isTriggerPass==1) && (numTightMuons ==2) && (numTightElectrons ==0) && (numLooseMuons == 0) && (numLooseElectrons == 0 ) && (numJets >=2)","goff"); cout << "Two" << endl; double ttBar_numTwoTightMuonGe2t = ttBarSummaryTree->Draw("numJets","(isCleanEvent==1) && (isTriggerPass==1) && (numTightMuons ==2) && (numTightElectrons ==0) && (numLooseMuons == 0) && (numLooseElectrons == 0 ) && (numJets >=2) && (numTaggedJets>=2)","goff"); cout << "Three" << endl; double ttBar_numTwoTightMuon2jEq2t = ttBarSummaryTree->Draw("numJets","(isCleanEvent==1) && (isTriggerPass==1) && (numTightMuons ==2) && (numTightElectrons ==0) && (numLooseMuons == 0) && (numLooseElectrons == 0 ) && (numJets ==2) && (numTaggedJets==2)","goff"); double ttBar_numTwoTightMuon3jEq2t = ttBarSummaryTree->Draw("numJets","(isCleanEvent==1) && (isTriggerPass==1) && (numTightMuons ==2) && (numTightElectrons ==0) && (numLooseMuons == 0) && (numLooseElectrons == 0 ) && (numJets ==3) && (numTaggedJets==2)","goff"); double ttBar_numTwoTightMuon4jEq2t = ttBarSummaryTree->Draw("numJets","(isCleanEvent==1) && (isTriggerPass==1) && (numTightMuons ==2) && (numTightElectrons ==0) && (numLooseMuons == 0) && (numLooseElectrons == 0 ) && (numJets ==4) && (numTaggedJets==2)","goff"); double ttBar_numTwoTightMuon3jEq3t = ttBarSummaryTree->Draw("numJets","(isCleanEvent==1) && (isTriggerPass==1) && (numTightMuons ==2) && (numTightElectrons ==0) && (numLooseMuons == 0) && (numLooseElectrons == 0 ) && (numJets ==3) && (numTaggedJets==3)","goff"); double ttBar_numTwoTightMuon4jEq3t = ttBarSummaryTree->Draw("numJets","(isCleanEvent==1) && (isTriggerPass==1) && (numTightMuons ==2) && (numTightElectrons ==0) && (numLooseMuons == 0) && (numLooseElectrons == 0 ) && (numJets ==4) && (numTaggedJets==3)","goff"); double ttBar_numTwoTightMuonGe3t = ttBarSummaryTree->Draw("numJets","(isCleanEvent==1) && (isTriggerPass==1) && (numTightMuons ==2) && (numTightElectrons ==0) && (numLooseMuons == 0) && (numLooseElectrons == 0 ) && (numJets >=3) && (numTaggedJets>=3)","goff"); double ttBar_numTwoTightMuonEq4t = ttBarSummaryTree->Draw("numJets","(isCleanEvent==1) && (isTriggerPass==1) && (numTightMuons ==2) && (numTightElectrons ==0) && (numLooseMuons == 0) && (numLooseElectrons == 0 ) && (numJets ==4) && (numTaggedJets==4)","goff"); double ttBar_numTwoTightMuonGe3jEq2t = ttBarSummaryTree->Draw("numJets","(isCleanEvent==1) && (isTriggerPass==1) && (numTightMuons ==2) && (numTightElectrons ==0) && (numLooseMuons == 0) && (numLooseElectrons == 0 ) && (numJets >=3) && (numTaggedJets==2)","goff"); // one tight one loose muon // double numTightLooseMuon = ttHSummaryTree->Draw("numJets","(isCleanEvent==1) && (isTriggerPass==1) && (numTightMuons ==1) && (numTightElectrons ==0) && (numLooseMuons == 1) && (numLooseElectrons == 0 )","goff"); // double numTightLooseMuonGe2j = ttHSummaryTree->Draw("numJets","(isCleanEvent==1) && (isTriggerPass==1) && (numTightMuons ==1) && (numTightElectrons ==0) && (numLooseMuons == 1) && (numLooseElectrons == 0 ) && (numJets >=2)","goff"); // double numTightLooseMuonGe2t = ttHSummaryTree->Draw("numJets","(isCleanEvent==1) && (isTriggerPass==1) && (numTightMuons ==1) && (numTightElectrons ==0) && (numLooseMuons == 1) && (numLooseElectrons == 0 ) && (numJets >=2) && (numTaggedJets>=2)","goff"); // double numTightLooseMuon2t = ttHSummaryTree->Draw("numJets","(isCleanEvent==1) && (isTriggerPass==1) && (numTightMuons ==1) && (numTightElectrons ==0) && (numLooseMuons == 1) && (numLooseElectrons == 0 ) && (numJets ==2) && (numTaggedJets==2)","goff"); // double numTightLooseMuonEq3t = ttHSummaryTree->Draw("numJets","(isCleanEvent==1) && (isTriggerPass==1) && (numTightMuons ==1) && (numTightElectrons ==0) && (numLooseMuons == 1) && (numLooseElectrons == 0 ) && (numJets ==3) && (numTaggedJets==3)","goff"); // double numTightLooseMuonGe3t = ttHSummaryTree->Draw("numJets","(isCleanEvent==1) && (isTriggerPass==1) && (numTightMuons ==1) && (numTightElectrons ==0) && (numLooseMuons == 1) && (numLooseElectrons == 0 ) && (numJets >=3) && (numTaggedJets>=3)","goff"); // double numTightLooseMuonEq4t = ttHSummaryTree->Draw("numJets","(isCleanEvent==1) && (isTriggerPass==1) && (numTightMuons ==1) && (numTightElectrons ==0) && (numLooseMuons == 1) && (numLooseElectrons == 0 ) && (numJets ==4) && (numTaggedJets==4)","goff"); cout << "############## " << ttHFileName << " ######################" << endl; double ttH_num_ge3j2t = (ttH_numTwoTightMuonGe3jEq2t/ttH_numEvents) * lumi * xsec_ttH; double ttH_num_ge3t = (ttH_numTwoTightMuonGe3t/ttH_numEvents) * lumi * xsec_ttH; cout << "Original = " << ttH_numEvents << endl << "Clean = " << ttH_numClean << endl << "Clean and trig = " << ttH_numCleanAndTrig << endl << "----------------------------------------" << endl << "Two Tight Muons = " << ttH_numTwoTightMuon << " Expected: " << (ttH_numTwoTightMuon/ttH_numEvents) * lumi * xsec_ttH << endl << " && >=2 jets = " << ttH_numTwoTightMuonGe2j << " Expected: " << (ttH_numTwoTightMuonGe2j/ttH_numEvents) * lumi * xsec_ttH << endl << " && >=2 tags = " << ttH_numTwoTightMuonGe2t << " Expected: " << (ttH_numTwoTightMuonGe2t/ttH_numEvents) * lumi * xsec_ttH << endl << " && ==2 jets 2 tags = " << ttH_numTwoTightMuon2jEq2t << " Expected: " << (ttH_numTwoTightMuon2jEq2t/ttH_numEvents) * lumi * xsec_ttH << endl << " && ==3 jets 2 tags = " << ttH_numTwoTightMuon3jEq2t << " Expected: " << (ttH_numTwoTightMuon3jEq2t/ttH_numEvents) * lumi * xsec_ttH << endl << " && ==4 jets 2 tags = " << ttH_numTwoTightMuon4jEq2t << " Expected: " << (ttH_numTwoTightMuon4jEq2t/ttH_numEvents) * lumi * xsec_ttH << endl << " && ==3 jets 3 tags = " << ttH_numTwoTightMuon3jEq3t << " Expected: " << (ttH_numTwoTightMuon3jEq3t/ttH_numEvents) * lumi * xsec_ttH << endl << " && ==4 jets 3 tags = " << ttH_numTwoTightMuon4jEq3t << " Expected: " << (ttH_numTwoTightMuon4jEq3t/ttH_numEvents) * lumi * xsec_ttH << endl << " && ==4 jets 4 tags = " << ttH_numTwoTightMuonEq4t << " Expected: " << (ttH_numTwoTightMuonEq4t/ttH_numEvents) * lumi * xsec_ttH << endl << " && >=3 jets 2 tags = " << ttH_numTwoTightMuonGe3jEq2t << " Expected: " << ttH_num_ge3j2t << endl << " && >=3 tags = " << ttH_numTwoTightMuonGe3t << " Expected: " << ttH_num_ge3t << endl << endl; cout << "############## " << ttBarFileName << " ######################" << endl; double ttBar_num_ge3j2t = (ttBar_numTwoTightMuonGe3jEq2t/ttBar_numEvents) * lumi * xsec_ttBar; double ttBar_num_ge3t = (ttBar_numTwoTightMuonGe3t/ttBar_numEvents) * lumi * xsec_ttBar; cout << "Original = " << ttBar_numEvents << endl << "Clean = " << ttBar_numClean << endl << "Clean and trig = " << ttBar_numCleanAndTrig << endl << "----------------------------------------" << endl << "Two Tight Muons = " << ttBar_numTwoTightMuon << " Expected: " << (ttBar_numTwoTightMuon/ttBar_numEvents) * lumi * xsec_ttBar << endl << " && >=2 jets = " << ttBar_numTwoTightMuonGe2j << " Expected: " << (ttBar_numTwoTightMuonGe2j/ttBar_numEvents) * lumi * xsec_ttBar << endl << " && >=2 tags = " << ttBar_numTwoTightMuonGe2t << " Expected: " << (ttBar_numTwoTightMuonGe2t/ttBar_numEvents) * lumi * xsec_ttBar << endl << " && ==2 jets 2 tags = " << ttBar_numTwoTightMuon2jEq2t << " Expected: " << (ttBar_numTwoTightMuon2jEq2t/ttBar_numEvents) * lumi * xsec_ttBar << endl << " && ==3 jets 2 tags = " << ttBar_numTwoTightMuon3jEq2t << " Expected: " << (ttBar_numTwoTightMuon3jEq2t/ttBar_numEvents) * lumi * xsec_ttBar << endl << " && ==4 jets 2 tags = " << ttBar_numTwoTightMuon4jEq2t << " Expected: " << (ttBar_numTwoTightMuon4jEq2t/ttBar_numEvents) * lumi * xsec_ttBar << endl << " && ==3 jets 3 tags = " << ttBar_numTwoTightMuon3jEq3t << " Expected: " << (ttBar_numTwoTightMuon3jEq3t/ttBar_numEvents) * lumi * xsec_ttBar << endl << " && ==4 jets 3 tags = " << ttBar_numTwoTightMuon4jEq3t << " Expected: " << (ttBar_numTwoTightMuon4jEq3t/ttBar_numEvents) * lumi * xsec_ttBar << endl << " && ==4 jets 4 tags = " << ttBar_numTwoTightMuonEq4t << " Expected: " << (ttBar_numTwoTightMuonEq4t/ttBar_numEvents) * lumi * xsec_ttBar << endl << " && >=3 jets 2 tags = " << ttBar_numTwoTightMuonGe3jEq2t << " Expected: " << ttBar_num_ge3j2t << endl << " && >=3 tags = " << ttBar_numTwoTightMuonGe3t << " Expected: " << ttBar_num_ge3t << endl << endl; cout << "------------- Done ------------------" << endl << endl; }
void paracoor( TString fin = "TMVA.root", Bool_t useTMVAStyle = kTRUE ) { // set style and remove existing canvas' TMVAGlob::Initialize( useTMVAStyle ); // checks if file with name "fin" is already open, and if not opens one TFile* file = TMVAGlob::OpenFile( fin ); TTree* tree = (TTree*)file->Get("TestTree"); if(!tree) { cout << "--- No TestTree saved in ROOT file. Parallel coordinates will not be plotted" << endl; return; } // first get list of leaves in tree TObjArray* leafList = tree->GetListOfLeaves(); vector<TString> vars; vector<TString> mvas; for (Int_t iar=0; iar<leafList->GetSize(); iar++) { TLeaf* leaf = (TLeaf*)leafList->At(iar); if (leaf != 0) { TString leafName = leaf->GetName(); if (leafName != "type" && leafName != "weight" && leafName != "boostweight" && leafName != "class" && leafName != "className" && leafName != "classID" && !leafName.Contains("prob_")) { // is MVA ? if (TMVAGlob::ExistMethodName( leafName )) { mvas.push_back( leafName ); } else { vars.push_back( leafName ); } } } } cout << "--- Found: " << vars.size() << " variables" << endl; cout << "--- Found: " << mvas.size() << " MVA(s)" << endl; TString type[2] = { "Signal", "Background" }; const UInt_t nmva = mvas.size(); TCanvas* csig[nmva]; TCanvas* cbkg[nmva]; for (UInt_t imva=0; imva<mvas.size(); imva++) { cout << "--- Plotting parallel coordinates for : " << mvas[imva] << " & input variables" << endl; for (Int_t itype=0; itype<2; itype++) { // create draw option TString varstr = mvas[imva] + ":"; for (UInt_t ivar=0; ivar<vars.size(); ivar++) varstr += vars[ivar] + ":"; varstr.Resize( varstr.Last( ':' ) ); // create canvas TString mvashort = mvas[imva]; mvashort.ReplaceAll("MVA_",""); TCanvas* c1 = (itype == 0) ? csig[imva] : cbkg[imva]; c1 = new TCanvas( Form( "c1_%i_%s",itype,mvashort.Data() ), Form( "Parallel coordinate representation for %s and input variables (%s events)", mvashort.Data(), type[itype].Data() ), 50*(itype), 50*(itype), 750, 500 ); tree->Draw( varstr.Data(), Form("classID==%i",1-itype) , "para" ); c1->ToggleEditor(); gStyle->SetOptTitle(0); TParallelCoord* para = (TParallelCoord*)gPad->GetListOfPrimitives()->FindObject( "ParaCoord" ); TParallelCoordVar* mvavar = (TParallelCoordVar*)para->GetVarList()->FindObject( mvas[imva] ); Double_t minrange = tree->GetMinimum( mvavar->GetName() ); Double_t maxrange = tree->GetMaximum( mvavar->GetName() ); Double_t width = 0.2*(maxrange - minrange); Double_t x1 = minrange, x2 = x1 + width; TParallelCoordRange* parrange = new TParallelCoordRange( mvavar, x1, x2 ); parrange->SetLineColor(4); mvavar->AddRange( parrange ); para->AddSelection("-1"); for (Int_t ivar=1; ivar<TMath::Min(Int_t(vars.size()) + 1,3); ivar++) { TParallelCoordVar* var = (TParallelCoordVar*)para->GetVarList()->FindObject( vars[ivar] ); minrange = tree->GetMinimum( var->GetName() ); maxrange = tree->GetMaximum( var->GetName() ); width = 0.2*(maxrange - minrange); switch (ivar) { case 0: { x1 = minrange; x2 = x1 + width; break; } case 1: { x1 = 0.5*(maxrange + minrange - width)*0.02; x2 = x1 + width*0.02; break; } case 2: { x1 = maxrange - width; x2 = x1 + width; break; } } parrange = new TParallelCoordRange( var, x1, x2 ); parrange->SetLineColor( ivar == 0 ? 2 : ivar == 1 ? 5 : 6 ); var->AddRange( parrange ); para->AddSelection( Form("%i",ivar) ); } c1->Update(); TString fname = Form( "root_mva/plots/paracoor_c%i_%s", imva, itype == 0 ? "S" : "B" ); TMVAGlob::imgconv( c1, fname ); } } }
void Run() { char const * file_percentage_max = "No File"; double percentage_max = 0; double percentage_max_mean = 2000; char const * file_mean_min = "No File"; double mean_min = 2000; double mean_min_percentage = 0; char const * file_clep_max = "No File"; double clep_max = 0; char const * file_clem_max = "No File"; double clem_max = 0; char const * file_comp_max = "No File"; double comp_max = 0; char const * file_comm_max = "No File"; double comm_max = 0; TFile * ofile = TFile::Open("shower_efficiency.root", "recreate"); for(char const * c : filenames) { ofile->cd(); std::cout << c << "\n"; TTree * otree = new TTree("shower_efficiency", ""); Double_t xdist, ydist, zdist, dist, detE, E; otree->Branch("xdist", &xdist, "xdist/D"); otree->Branch("ydist", &ydist, "ydist/D"); otree->Branch("zdist", &zdist, "zdist/D"); otree->Branch("dist", &dist, "dist/D"); otree->Branch("detE", &detE, "detE/D"); otree->Branch("E", &E, "E/D"); TFile * file = TFile::Open(c); TTree * reco_tree = dynamic_cast<TTree *>(file->Get("RecoShowerVertices")); TTree * true_tree = dynamic_cast<TTree *>(file->Get("TrueShowerVertices")); Double_t truex, truey, truez, trueE, trueDetE; true_tree->SetBranchAddress("x", &truex); true_tree->SetBranchAddress("y", &truey); true_tree->SetBranchAddress("z", &truez); true_tree->SetBranchAddress("E", &trueE); true_tree->SetBranchAddress("detE", &trueDetE); Double_t recox, recoy, recoz, recoE, recoDetE; reco_tree->SetBranchAddress("x", &recox); reco_tree->SetBranchAddress("y", &recoy); reco_tree->SetBranchAddress("z", &recoz); reco_tree->SetBranchAddress("detE", &recoDetE); for(Size_t i = 0; i < reco_tree->GetEntries(); ++i) { reco_tree->GetEntry(i); true_tree->GetEntry(i); Double_t const xd = recox - truex; Double_t const yd = recoy - truey; Double_t const zd = recoz - truez; xdist = xd; ydist = yd; zdist = zd; dist = sqrt(xd*xd+yd*yd+zd*zd); detE = trueDetE; E = trueE; otree->Fill(); } int const total = otree->GetEntries(); int const good = otree->GetEntries("dist < 2"); double const percentage = (Double_t)good/total*100; TCanvas * temp = new TCanvas("temp"); otree->Draw("dist>>ht"); delete temp; TH1F * h = dynamic_cast<TH1F *>(gDirectory->Get("ht")); double const mean = h->GetMean(); delete h; if(percentage > percentage_max) { file_percentage_max = file->GetName(); percentage_max = percentage; percentage_max_mean = mean; } if(mean < mean_min) { file_mean_min = file->GetName(); mean_min = mean; mean_min_percentage = percentage; } TTree * ERAnaVBtree = dynamic_cast<TTree *>(file->Get("ERAnaVBTest")); int const completeness_total = ERAnaVBtree->GetEntries("total_vertices > 0 && visible_direct_children > 0"); int const completeness_good = ERAnaVBtree->GetEntries("direct_children_ratio == 1 && total_vertices > 0 && visible_direct_children > 0"); double const completeness_percentage = (Double_t)completeness_good/completeness_total*100; if(completeness_percentage > comp_max) { file_comp_max = file->GetName(); comp_max = completeness_percentage; } int const cleanliness_total = ERAnaVBtree->GetEntries("total_vertices > 0 && reco_direct_children + reco_misid_children"); int const cleanliness_good = ERAnaVBtree->GetEntries("reco_misid_ratio == 1 && total_vertices > 0 && reco_direct_children + reco_misid_children"); double const cleanliness_percentage = (Double_t)cleanliness_good/cleanliness_total*100; if(completeness_percentage > clep_max) { file_clep_max = file->GetName(); clep_max = cleanliness_percentage; } TCanvas * temp1 = new TCanvas("temp"); ERAnaVBtree->Draw("direct_children_ratio>>ht", "total_vertices > 0 && visible_direct_children > 0"); delete temp1; TH1F * h1 = dynamic_cast<TH1F *>(gDirectory->Get("ht")); double const completeness_mean = h1->GetMean(); delete h1; if(completeness_mean > comm_max) { file_comm_max = file->GetName(); comm_max = completeness_mean; } TCanvas * temp2 = new TCanvas("temp"); ERAnaVBtree->Draw("reco_misid_ratio>>ht", "total_vertices > 0 && reco_direct_children + reco_misid_children"); delete temp2; TH1F * h2 = dynamic_cast<TH1F *>(gDirectory->Get("ht")); double const cleanliness_mean = h2->GetMean(); delete h2; if(cleanliness_mean > clem_max) { file_clem_max = file->GetName(); clem_max = cleanliness_mean; } file->Close(); delete otree; } ofile->Close(); std::cout << "\nPercentage max:\n" << file_percentage_max << "\n" << "Percentage: " << percentage_max << "\n" << "Mean: " << percentage_max_mean << "\n\n" << "Mean min:\n" << file_mean_min << "\n" << "Percentage: " << mean_min_percentage << "\n" << "Mean: " << mean_min << "\n"; std::cout << "\nCleanliness percentage max:\n" << "File: " << file_clep_max << "\n" << "Percentage: " << clep_max << "\n" << "\nCleanliness mean max:\n" << "File: " << file_clem_max << "\n" << "Mean:" << clem_max << "\n" << "\nCompleteness percentage max:\n" << "File: " << file_comp_max << "\n" << "Percentage: " << comp_max << "\n" << "\nCompleteness mean max:\n" << "File: " << file_comm_max << "\n" << "Mean:" << comm_max << "\n"; }
void plotRatio(int cbin, TString infname, TString DataPF, TString mix, bool useWeight, bool drawXLabel, bool drawLeg) { TString cut="et1>120&& et1<2000 && et2>50 && dphi>3.14159/3*2&&(et1-et2)/(et1+et2)<0.55 "; TString cut2="et1>120&& et1<2000 && et2>50 && dphi>3.14159/3*2&&(et1-et2)/(et1+et2)<0.55 "; TString cstring = ""; if(cbin==0) { cstring = "0-10%"; cut+=" && (bin>=0 && bin<4 || bin==-1)"; cut2+=" &&(bin>=0 && bin<4 || bin==-1)"; } else if (cbin==1) { cstring = "10-20%"; cut+=" && (bin>=4 && bin<8 || bin==-1)"; cut2+=" && (bin>=4 && bin<8 || bin==-1)"; } else if (cbin==2) { cstring = "20-30%"; cut+=" && (bin>=8 && bin<12 || bin==-1)"; cut2+=" && (bin>=8 && bin<12 || bin==-1)"; } else if (cbin==3) { cstring = "30-50%"; cut+=" && (bin>=12 && bin<20 || bin==-1)"; cut2+=" && (bin>=12 && bin<20 || bin==-1)"; } else { cstring = "50-100%"; cut+=" && (bin>=20 && bin<40 || bin==-1)"; cut2+=" && (bin>=20 && bin<40 || bin==-1)"; } // open the data file TFile *inf = new TFile(infname.Data()); TTree *nt =(TTree*)inf->FindObjectAny("nt"); // open the DataPF (MC) file TFile *infDataPF = new TFile(DataPF.Data()); TTree *ntDataPF = (TTree*) infDataPF->FindObjectAny("nt"); // open the datamix file TFile *infMix = new TFile(mix.Data()); TTree *ntMix =(TTree*)infMix->FindObjectAny("nt"); // Variable Aj char *aj = "(et1-et2)/(et1+et2)"; const int nBin = 13; double bins[nBin+1]={0,0.05,0.1,0.15,0.2,0.25,0.3,0.35,0.4,0.45,0.5,0.55,0.6,1}; // projection histogram TH1D *h = new TH1D("h","",nBin,bins); TH1D *hTmp = new TH1D("hTmp","",nBin,bins); TH1D *hEmbedded = new TH1D("hEmbedded","",nBin,bins); TH1D *hDataMix = new TH1D("hDataMix","",nBin,bins); nt->Draw(Form("%s>>h",aj),Form("(%s)*weight",cut2.Data())); if (useWeight) { // use the weight value caluculated by Matt's analysis macro ntDataPF->Draw(Form("%s>>hEmbedded",aj),Form("(%s)",cut.Data())); ntMix->Draw(Form("%s>>hDataMix",aj),Form("(%s)*weight",cut.Data())); } else { // ignore centrality reweighting ntDataPF->Draw(Form("%s>>hEmbedded",aj),Form("(%s)",cut.Data())); ntMix->Draw(Form("%s>>hDataMix",aj),Form("(%s)",cut.Data())); } // calculate the statistical error and normalize h->Sumw2(); h->Scale(1./h->Integral(0,20)); h->SetMarkerStyle(20); hEmbedded->Sumw2(); hEmbedded->Scale(1./hEmbedded->Integral(0,20)); hEmbedded->SetLineColor(kBlue); hEmbedded->SetFillColor(kAzure-8); hEmbedded->SetFillStyle(3005); hEmbedded->SetStats(0); if(drawXLabel) { hEmbedded->SetXTitle("A_{J} = (p_{T}^{j1}-p_{T}^{j2})/(p_{T}^{j1}+p_{T}^{j2})"); h->SetXTitle("A_{J} = (p_{T}^{j1}-p_{T}^{j2})/(p_{T}^{j1}+p_{T}^{j2})"); } h->GetXaxis()->SetLabelSize(20); h->GetXaxis()->SetLabelFont(43); h->GetXaxis()->SetTitleSize(22); h->GetXaxis()->SetTitleFont(43); h->GetXaxis()->SetTitleOffset(1.5); h->GetXaxis()->CenterTitle(); h->GetXaxis()->SetNdivisions(905,true); h->GetYaxis()->SetLabelSize(20); h->GetYaxis()->SetLabelFont(43); h->GetYaxis()->SetTitleSize(20); h->GetYaxis()->SetTitleFont(43); h->GetYaxis()->SetTitleOffset(2.5); h->GetYaxis()->CenterTitle(); h->SetAxisRange(0,0.3,"Y"); h->SetMarkerColor(2); h->SetYTitle("Ratio"); hEmbedded->SetYTitle("Ratio"); hDataMix->Sumw2(); hDataMix->Scale(1./hDataMix->Integral(0,20)); hDataMix->SetLineColor(kRed); hDataMix->SetFillColor(kRed-9); hDataMix->SetFillStyle(3004); h->SetAxisRange(0,5,"Y"); hEmbedded->SetAxisRange(0,10,"Y"); h->Divide(hDataMix); hEmbedded->Divide(hDataMix); h->Draw(""); TH1D *hErr = getErrorBand(h); double systematicErrorResolution[nBin] = {0.06,0.05,0.04,0.04,0.04,0.06,0.1,0.18,0.3,0.5,0.5}; double systematicErrorScale[nBin] = {0.06,0.05,0.04,0.03,0.02,0.02,0.03,0.04,0.05,0.08,0.1}; double systematicErrorEfficiency[nBin] = {0.00,0.00,0.00,0.00,0.00,0.00,0.07,0.07,0.07,0.07,0.07}; double systematicErrorBackground[nBin+1] = {0.07,0.04,0.04,0.04,0.05,0.06,0.07,0.08,0.09,0.10,0.12,0.15}; double systematicError[nBin]; for (int b=0;b<nBin;b++) { double sum=0; //sum+= systematicErrorResolution[b]*systematicErrorResolution[b]; //sum+= systematicErrorScale[b]*systematicErrorScale[b]; //sum+= systematicErrorEfficiency[b]*systematicErrorEfficiency[b]; sum+= systematicErrorBackground[b]*systematicErrorBackground[b]; systematicError[b]=sqrt(sum); hTmp->SetBinContent(b,1); } TGraph *gErrorBand; if (cbin!=0) { gErrorBand = GetErrorBand(hTmp,systematicError,systematicError,0.025,12); } else { gErrorBand = GetErrorBand(hTmp,systematicError,systematicError,0.025,12); } gErrorBand->Draw("f"); hEmbedded->SetMarkerStyle(4); hEmbedded->SetMarkerColor(4); hEmbedded->SetLineColor(4); hEmbedded->SetLineStyle(2); //hEmbedded->Draw("same"); //h->Fit("pol1","","",0,1); h->Draw("same"); TLine *l = new TLine(0,1,1,1); l->SetLineStyle(2); l->Draw(); if(drawLeg){ TLegend *t3=new TLegend(0.44,0.7,0.86,0.88); t3->AddEntry(h,"PYTHIA + Data / PYTHIA","pl"); //t3->AddEntry(hEmbedded,"Data PF / PYQUEN + Data","l"); //t3->AddEntry(hDataMix,"unquenched PYQUEN + Data","lf"); t3->SetFillColor(0); t3->SetBorderSize(0); t3->SetFillStyle(0); t3->SetTextFont(63); t3->SetTextSize(15); t3->Draw(); } }
void drawpdgstack(std::string const & which_pdg, std::string const & cname, std::string const & dr, std::string const & binning, std::string const & we = "", std::string const & op = "", std::string const & title = "", std::string const & xtitle = "", std::string const & ytitle = "", bool const pdg_sign = true) { ofile->cd(); TH1F * hist = getpdgs(which_pdg.c_str(), we); if(!hist) { std::cout << "drawpdgstack: Empty pdg hist for \"" << which_pdg << "\" with selection \"" << we << "\"\n"; return; } THStack * stack = new THStack("stack", ""); TLegend * legend = new TLegend(0.6, 0.9, 0.9, 0.6); double sig_evtsppot = 0; if(tree2) { TString draw_str = ""; draw_str += dr; draw_str += ">>h_sig"; draw_str += binning; TCanvas * canvas_pdg_temp = new TCanvas("temp"); tree2->Draw(draw_str.Data(), we.c_str(), op.c_str()); delete canvas_pdg_temp; TH1F * hist_sig = (TH1F*)gDirectory->Get("h_sig"); hist_sig->SetLineColor(1); hist_sig->SetFillColor(kRed+3); hist_sig->Scale(1. / signal_pot * run_pot); stack->Add(hist_sig); legend->AddEntry(hist_sig, ("Signal: "+to_string_with_precision(hist_sig->Integral())).c_str()); sig_evtsppot = hist_sig->Integral(); } legend->SetHeader(("Total: "+to_string_with_precision((hist->Integral()/background_pot*run_pot + sig_evtsppot))).c_str()); ((TLegendEntry*)legend->GetListOfPrimitives()->First())->SetTextAlign(22); std::vector<int> pdg_vec; for(int i = 1; i <= hist->GetNbinsX(); ++i) { if(hist->GetBinContent(i) == 0) continue; int const pdg = i+hist->GetBinLowEdge(0); if(!pdg_sign) { if(std::find(pdg_vec.begin(), pdg_vec.end(), abs(pdg)) != pdg_vec.end()) continue; pdg_vec.push_back(abs(pdg)); } TString hname = ""; hname += "h_"; hname += pdg; TString draw_str = ""; draw_str += dr; draw_str += ">>h_"; draw_str += pdg; draw_str += binning; TString weight_str = ""; weight_str += we; weight_str += "&&("; weight_str += which_pdg; weight_str += "=="; weight_str += pdg; if(!pdg_sign && pdg < 0) { weight_str += "||"; weight_str += which_pdg; weight_str += "=="; weight_str += abs(pdg); } weight_str += ")"; TCanvas * canvas_pdg_temp = new TCanvas("temp"); tree->Draw(draw_str.Data(), weight_str.Data(), op.c_str()); delete canvas_pdg_temp; int pdg_temp = pdg; if(!pdg_sign) pdg_temp = abs(pdg); pdg_stuff const & pdg_s = get_pdg_stuff(pdg_temp, pdg_sign); TH1F * hist_pdg = (TH1F*)gDirectory->Get(hname.Data()); hist_pdg->SetLineColor(1); hist_pdg->SetFillColor(pdg_s._color); hist_pdg->Scale(1. / background_pot * run_pot); stack->Add(hist_pdg); legend->AddEntry(hist_pdg, (pdg_s._particle_name+": "+to_string_with_precision(hist_pdg->Integral())).c_str()); } TCanvas * canvas = new TCanvas(cname.c_str()); stack->Draw(); stack->SetTitle(title.c_str()); stack->GetXaxis()->SetTitle(xtitle.c_str()); stack->GetXaxis()->CenterTitle(); stack->GetYaxis()->SetTitle(ytitle.c_str()); stack->GetYaxis()->CenterTitle(); legend->Draw(); canvas->Write(); delete stack; delete legend; delete canvas; delete hist; }
//Calls treeAnalyzer::applySelection(strInputTextFile) and then for each plot made here it analyzes the raw data that went into making each plot //The output is stored inside the Plots directory for each Canvas created void treeAnalyzerTDC::applySelectionTDC(string strOutputROOTFile){ //Variable Declaration bool bExitSuccess = false; //Apply the Selection //------------------------------------------------------ applySelection(strOutputROOTFile); //Load the ROOT file that was just created in the UPDATE mode //------------------------------------------------------ //TFile *file_ROOT_Output = new TFile(strOutputROOTFile.c_str(), "UPDATE", "", 1); //TFile file_ROOT_Output = getFile(strOutputROOTFile, "UPDATE", bExitSuccess); TFile * file_ROOT_Output = getFile(strOutputROOTFile, "UPDATE", bExitSuccess); if (!bExitSuccess) { //Case: Output File Was Not Created Successfully if(bVerbose_IO) { cout<< ("treeAnalyzerTDC::applySelectionTDC() - Output ROOT File: " + strOutputROOTFile + " was not successfully created, stopping\n").c_str(); cout<<"treeAnalyzerTDC::applySelectionTDC() - Please Cross-Check (Maybe you do not have write-permission in working directory or filepath does not exist???)"<<endl; } return; } //End Case: Output File Was Not Created Successfully //Loop Over Selection Input to create the indepth TDC Analysis //------------------------------------------------------ for (auto iterSel = vecSelInfo.begin(); iterSel != vecSelInfo.end(); ++iterSel) { //Loop Over vecSelInfo //Get the TDirectory that was made for this SelInfo TDirectory *dir_thisSel = file_ROOT_Output->GetDirectory( (*iterSel).strDirectory.c_str(), false, "GetDirectory" ); //Loop over all CanvasInfo's that were requested for this SelInfo //------------------------------------------------------ for (auto iterCanvas = (*iterSel).mapCanvas.begin(); iterCanvas != (*iterSel).mapCanvas.end(); ++iterCanvas) { //Loop Over (*iterSel).mapCanvas //Get the TDirectory that was made for this CanvasInfo TDirectory *dir_thisCanvas = dir_thisSel->GetDirectory( ((*iterCanvas).second).strDirectory.c_str(), false, "GetDirectory" ); //Loop over all PlotInfo's that were requested for this CanvasInfo //------------------------------------------------------ for (auto iterPlot = ((*iterCanvas).second).mapPlot.begin(); iterPlot != ((*iterCanvas).second).mapPlot.end(); ++iterPlot) { //Loop Over ((*iterCanvas).second).mapPlot //Skip this plot if no friend branch was defined by the user if ( ((*iterPlot).second).strFriendBranch.length() == 0 ) continue; //Get the TDirectory that was made for this PlotInfo //------------------------------------------------------ TDirectory *dir_thisPlot = dir_thisCanvas->GetDirectory( ((*iterPlot).second).strDirectory.c_str(), false, "GetDirectory" ); TDirectory *dir_HistoWithFit = dir_thisPlot->mkdir( ("HistoWithFit_" + ((*iterPlot).second).strVarIndep).c_str() ); TDirectory *dir_HistoOverFit = dir_thisPlot->mkdir( ("HistoOverFit_" + ((*iterPlot).second).strVarIndep).c_str() ); //Open the Input Data File //------------------------------------------------------ TFile * file_ROOT_Input = getFile( ((*iterPlot).second).strNameROOTFile, "READ", bExitSuccess ); if (!bExitSuccess) { //Case: Input File Failed To Open Successfully if (bVerbose_IO) { std::cout << ("treeAnalyzerTDC::applySelectionTDC(): error while opening file: " + ((*iterPlot).second).strNameROOTFile).c_str() << endl; std::cout << "Skipping Plot: " << ((*iterPlot).second).strName << endl; } continue; } //End Case: Input File Failed To Open Successfully //Load the TTree from file_ROOT_Input //------------------------------------------------------ TTree *treeInput = (TTree*) file_ROOT_Input->Get( ((*iterPlot).second).strNameTree.c_str() ); //Note the Selection is already setup due to calling "applySelection()" of the parent class //Declaration of TTree's leaf types //------------------------------------------------------ int iRun; //value of the run number float fVarIndep; //value of the independent variable for the i^th point TH1F *hTDC_Histo = new TH1F(); //Histogram from the i^th point TF1 *func_FriendBranch = new TF1(); //Fit Function from the i^th point //Set the branch addresses //------------------------------------------------------ treeInput->SetBranchAddress("iRun",&iRun); treeInput->SetBranchAddress( ((*iterPlot).second).strVarIndep.c_str(), &fVarIndep); treeInput->SetBranchAddress("hTDC_Histo",&hTDC_Histo); treeInput->SetBranchAddress( ((*iterPlot).second).strFriendBranch.c_str(), &func_FriendBranch); //Loop Over the Entries in treeInput that pass the selection //------------------------------------------------------ //Inform the user we have moved to a new SelInfo and then draw the tree //cout<< ("Selection = '" + (*iterSel).strSel + "'" ) << endl; //treeInput->Draw( ">>listSelEvts", (*iterSel).strSel.c_str(), "entrylist" ); cout<< ("Selection = '" + ((*iterPlot).second).strSelLocal + "'" ) << endl; treeInput->Draw( ">>listSelEvts", ((*iterPlot).second).strSelLocal.c_str(), "entrylist" ); //Get the Entry List TEntryList *listSelEvts = (TEntryList*) gDirectory->Get("listSelEvts"); //Loop Over the events passing ((*iterPlot).second).strSelLocal stored in eventList //cout<<"i\tidx_EvtList\tSigma_Fit\n"; for (int i=0; i < listSelEvts->GetN(); ++i) { //Loop over events stored in eventList //int iEvtIdx = listSelEvts->Next(); //Should probably use listSelEvts->GetEntry(i) because duplicate calls of Next() per loop iteration cause undesired iteration through the list //treeInput->GetEntry( iEvtIdx ); treeInput->GetEntry( listSelEvts->GetEntry(i) ); //Skip this Event if the Histogram pointer is a null pointer if (hTDC_Histo == nullptr){ continue; } else{ //Otherwise Set the Histogram Style hTDC_Histo = getHistogram( (*iterPlot).second, hTDC_Histo); } //treeInput->Show(); //if(i==0) treeInput->Show(); //Set the Style //Create the Canvas - Histogram w/Fit //------------------------------------------------------ //set the style based on user input //Make a copy of the CanvasInfo, reset the name, and then pass it to treeAnalyzer::getCanvas() CanvasInfo tempCanvasInfo = (*iterCanvas).second; tempCanvasInfo.strName = "canvas_DataHistoWithFit_R" + getString(iRun) + "_" + ((*iterPlot).second).strVarDepend + "_" + ((*iterPlot).second).strVarIndep + getString(fVarIndep); TCanvas *cHistoWithFit = getCanvas(tempCanvasInfo); cHistoWithFit->cd(); TLegend *leg = (TLegend *) ((*iterCanvas).second).leg->Clone( ("leg_HistoWithFit_" + getString(fVarIndep) ).c_str() ); leg->Clear(); //Wipe all previous entries leg->AddEntry(hTDC_Histo,"Data","LPE"); //Plot Histogram on the Canvas cHistoWithFit->cd(); hTDC_Histo->Draw("E1"); //Check that the fit function exists if ( func_FriendBranch != nullptr) { //Set the style func_FriendBranch->SetLineColor( ((*iterPlot).second).iColor ); func_FriendBranch->SetLineStyle( ((*iterPlot).second).iStyleLine ); func_FriendBranch->SetLineWidth( ((*iterPlot).second).fSizeLine ); //Add to the Legend leg->AddEntry(func_FriendBranch, "Fit", "L"); //Draw func_FriendBranch->Draw("same"); } //Draw the legend leg->Draw("same"); //Store dir_HistoWithFit->cd(); cHistoWithFit->Write(); hTDC_Histo->Write(); func_FriendBranch->Write(); //if ( func_FriendBranch != nullptr) func_FriendBranch->Write(); //Create the Canvas - Histogram DIVIDED by Fit //------------------------------------------------------ //set the style based on user input //Make a copy of the CanvasInfo, reset the name, and then pass it to treeAnalyzer::getCanvas() tempCanvasInfo.strName = "canvas_DataHistoOverFit_R" + getString(iRun) + "_" + ((*iterPlot).second).strVarDepend + "_" + ((*iterPlot).second).strVarIndep + getString(fVarIndep); TCanvas *cHistoOverFit = getCanvas(tempCanvasInfo); cHistoOverFit->cd(); TH1F *hTDC_HistoOverFit = (TH1F *) hTDC_Histo->Clone( (hTDC_Histo->GetName() + getString("_OverFit") ).c_str() ); hTDC_HistoOverFit->Divide(func_FriendBranch); hTDC_HistoOverFit->GetYaxis()->SetRangeUser(0.,2.); hTDC_HistoOverFit->Draw("E1"); //store dir_HistoOverFit->cd(); cHistoOverFit->Write(); hTDC_HistoOverFit->Write(); //Delete pointers delete cHistoWithFit; delete cHistoOverFit; //delete func_FriendBranch; //No this breaks the TTree::GetEntry() Call //delete hTDC_Histo; //No this breaks the TTree::GetEntry() Call delete leg; } //End Loop over events stored in eventList //Close the Input ROOT File //------------------------------------------------------ file_ROOT_Input->Close(); } //End Loop Over ((*iterCanvas).second).mapPlot } //End Loop Over (*iterSel).mapCanvas } //End Loop Over vecSelInfo //Close the output ROOT file //------------------------------------------------------ file_ROOT_Output->Close(); return; } //End treeAnalyzerTDC::applySelectionTDC()
// This ROOT macro plots the stopping depth of the muons in local coordinates void StoppingDepth(std::string filename) { TCanvas* c1 = new TCanvas("c1", "c1"); c1->SetRightMargin(0.15); int n_entries = 100000; TFile* file = new TFile(filename.c_str(), "READ"); TTree* tree = (TTree*) file->Get("tree"); double n_input_muons = tree->GetEntries(); size_t secondslash = filename.rfind("/")+1; // don't want to include the slash size_t firstdot = filename.rfind("."); size_t n_chars = firstdot - secondslash; std::string base_filename = filename.substr(secondslash, n_chars); std::string histtitle = "Plot of the Stopping Depth of Muons in " + base_filename; TH2F* hStopDepth = new TH2F("hStopDepth", histtitle.c_str(), 120,-6,6, 120,-5,55); hStopDepth->GetYaxis()->SetTitle("Local Z [#mum]"); hStopDepth->GetXaxis()->SetTitle("Local X [cm]"); hStopDepth->GetZaxis()->SetTitle("N_{stop-#mu} / N_{input-#mu}"); hStopDepth->Scale(1.0 / n_input_muons); hStopDepth->SetStats(false); tree->Draw("-1*((M_local_Oz*10000)-25):M_local_Ox>>hStopDepth", "M_particleName==\"mu-\" && M_volName==\"Target\" && M_stopped == 1", "COLZ", n_entries); c1->Update(); std::string canvasname = "hStopDepth_" + base_filename + ".png"; // c1->Print(canvasname.c_str()); TH1D* hStopZDepth = hStopDepth->ProjectionY(); hStopZDepth->Draw(); hStopZDepth->SetStats(false); hStopZDepth->GetYaxis()->SetTitle("N_{stop-#mu} / N_{input-#mu}"); // hStopZDepth->Scale(1.0 / n_input_muons); c1->Update(); canvasname = "hStopZDepth_" + base_filename + ".png"; // c1->Print(canvasname.c_str()); TH2F* hStopDepthVsTime = new TH2F("hStopDepthVsTime", histtitle.c_str(), 120,-30,30, 120,0,12); hStopDepthVsTime->GetXaxis()->SetTitle("Local Z [#mum]"); hStopDepthVsTime->GetYaxis()->SetTitle("Time [ns]"); hStopDepthVsTime->GetZaxis()->SetTitle("N_{stop-#mu} / N_{input-#mu}"); hStopDepthVsTime->Scale(1.0 / n_input_muons); hStopDepthVsTime->SetStats(false); // tree->Draw("M_Ot:M_local_Oz*10000>>hStopDepthVsTime", "M_particleName==\"mu-\" && M_volName==\"Target\" && M_stopped == 1", "COLZ", n_entries); c1->Update(); canvasname = "hStopDepthVsTime_" + base_filename + ".png"; // c1->Print(canvasname.c_str()); TH2F* hStopDepthVsMomentum = new TH2F("hStopDepthVsMomentum", histtitle.c_str(), 120,-30,30, 120,0,30); hStopDepthVsMomentum->GetXaxis()->SetTitle("Local Z [#mum]"); hStopDepthVsMomentum->GetYaxis()->SetTitle("Momentum [MeV]"); hStopDepthVsMomentum->GetZaxis()->SetTitle("N_{stop-#mu} / N_{input-#mu}"); hStopDepthVsMomentum->Scale(1.0 / n_input_muons); hStopDepthVsMomentum->SetStats(false); // tree->Draw("sqrt(M_px*M_px + M_py*M_py+ M_pz*M_pz)*1000:M_local_Oz*10000>>hStopDepthVsMomentum", "M_particleName==\"mu-\" && M_volName==\"Target\" && M_stopped == 1", "COLZ", n_entries); c1->Update(); canvasname = "hStopDepthVsMomentum_" + base_filename + ".png"; // c1->Print(canvasname.c_str()); // file->Close(); std::string outfilename = "plot_" + base_filename + ".root"; TFile* output = new TFile(outfilename.c_str(), "RECREATE"); hStopDepth->Write(); hStopZDepth->Write(); hStopDepthVsTime->Write(); hStopDepthVsMomentum->Write(); output->Close(); }
void projectPbPbMBMC() { gStyle->SetTextSize(0.05); gStyle->SetTextFont(42); gStyle->SetPadRightMargin(0.043); gStyle->SetPadLeftMargin(0.18); gStyle->SetPadTopMargin(0.1); gStyle->SetPadBottomMargin(0.145); gStyle->SetTitleX(.0f); gStyle->SetOptFit(1111); gStyle->SetOptStat(0); gStyle->SetOptTitle(0); TFile* infMCP = new TFile("/data/HeavyFlavourRun2/MC2015/Dntuple/PbPb/ntD_EvtBase_20160513_DfinderMC_PbPb_20160502_dPt1tkPt0p5_D0_prompt_Dpt2Dy1p1tkPt0p7tkEta2Decay2p9Dalpha0p14Skim_pthatweight.root"); TFile* infMCNP = new TFile("/data/HeavyFlavourRun2/MC2015/Dntuple/PbPb/ntD_EvtBase_20160513_DfinderMC_PbPb_20160502_dPt1tkPt0p5_D0_nonprompt_Dpt2Dy1p1tkPt0p7tkEta2Decay2p9Dalpha0p14Skim_pthatweight.root"); TTree* tMCP = (TTree*)infMCP->Get("ntDkpi"); TTree* tMCNP = (TTree*)infMCNP->Get("ntDkpi"); TTree* tMCPHI = (TTree*)infMCP->Get("ntHi"); TTree* tMCNPHI = (TTree*)infMCNP->Get("ntHi"); TTree* tMCPSkim = (TTree*)infMCP->Get("ntSkim"); TTree* tMCNPSkim = (TTree*)infMCNP->Get("ntSkim"); tMCP->AddFriend(tMCPHI); tMCNP->AddFriend(tMCNPHI); tMCP->AddFriend(tMCPSkim); tMCNP->AddFriend(tMCNPSkim); TFile* outf = new TFile("bFeedDownPbPbMBMC_FineDPt.hist.root","recreate"); TCut cutPbPbMB = "pclusterCompatibilityFilter&&pprimaryVertexFilter&&phfCoincFilter3&&abs(PVz)<15&&Dy>-1.&&Dy<1.&&Dtrk1highPurity&&Dtrk2highPurity&&Dtrk1Pt>1.0&&Dtrk2Pt>1.0&&Dtrk1PtErr/Dtrk1Pt<0.3&&Dtrk2PtErr/Dtrk2Pt<0.3&&abs(Dtrk1Eta)<1.5&&abs(Dtrk2Eta)<1.5&&((DlxyBS/DlxyBSErr)>1.5&&Dalpha<0.12&&((Dpt>1&&Dpt<2&&(DsvpvDistance/DsvpvDisErr)>6.0&&Dchi2cl>0.25)||(Dpt>2&&Dpt<4&&(DsvpvDistance/DsvpvDisErr)>5.86&&Dchi2cl>0.224)||(Dpt>4&&Dpt<5&&(DsvpvDistance/DsvpvDisErr)>5.46&&Dchi2cl>0.196)||(Dpt>5&&Dpt<6&&(DsvpvDistance/DsvpvDisErr)>4.86&&Dchi2cl>0.170)||(Dpt>6&&Dpt<8&&(DsvpvDistance/DsvpvDisErr)>4.54&&Dchi2cl>0.125)||(Dpt>8&&Dpt<10&&(DsvpvDistance/DsvpvDisErr)>4.42&&Dchi2cl>0.091)||(Dpt>10&&Dpt<15&&(DsvpvDistance/DsvpvDisErr)>4.06&&Dchi2cl>0.069)||(Dpt>15&&Dpt<20&&(DsvpvDistance/DsvpvDisErr)>3.71&&Dchi2cl>0.056)||(Dpt>20&&Dpt<25&&(DsvpvDistance/DsvpvDisErr)>3.25&&Dchi2cl>0.054)||(Dpt>25&&(DsvpvDistance/DsvpvDisErr)>2.97&&Dchi2cl>0.050)))"; TCut cutmc = "(Dgen==23333||Dgen==23344)"; TCut cutmcSignal = "Dgen==23333"; TCut cutmcSwapped = "Dgen==23344"; TCut cutpt = "Dpt<20"; TCut cutSignal = "abs(Dmass-1.8649)<0.025"; TCut cutSideband = "abs(Dmass-1.8649)>0.075&&abs(Dmass-1.8649)<0.1"; TCut cutPrompt = "DgenBAncestorpt<=0"; TCut cutNonPrompt ="DgenBAncestorpt>0"; TCut weightfunctionreco = "pthatweight"; TCut cutCentralityBin = "hiBin>=0&&hiBin<200"; TCut cutCentralityBinArr[] = {"hiBin>=0&&hiBin<200","hiBin>=0&&hiBin<20","hiBin>=20&&hiBin<60","hiBin>=60&&hiBin<100","hiBin>=100&&hiBin<200"}; TCut weightfunctionrecoArr[]={ "pthatweight" , "1"}; // const int nBinX = 14; // Float_t binsX[nBinX+1] = {2.,3.,4.,5.,6.,8.,10.,12.5,15.0,20.,25.,30.,40.,60.,100}; const int nBinX = 220; Float_t binsX[nBinX+1]; Float_t binPt=0.1; Float_t iPt=2; for(int i =0; i<=nBinX; i++){ binsX[i]=iPt; if(iPt<10) binPt=0.1; if(iPt>=10 && iPt< 20) binPt=0.25; if(iPt>=20 && iPt< 40) binPt=0.5; if(iPt>=40) binPt =1; iPt = iPt+binPt; cout<<"i = "<<i<<" , binsX = "<<binsX[i]<<endl; } const int nBinY = 20; Float_t binsY[nBinY+1]; float firstBinYWidth = 0.001; float binYWidthRatio = 1.27; binsY[0]=0; for(int i=1; i<=nBinY; i++) binsY[i] = binsY[i-1]+firstBinYWidth*pow(binYWidthRatio,i-1); cout<<"last y bin: "<<binsY[nBinY]<<endl; const int nBinZ = 20; Float_t binsZ[nBinZ+1]; float firstBinZ = 3.5; float binWidthZ = 5; for(int i=0; i<=nBinZ; i++) binsZ[i] = firstBinZ+binWidthZ*i; const int nBinM = 60; Float_t binsM[nBinM]; float minMassBin = 1.7; float massBinWidth = 0.005; for(int i=0; i<=nBinM; i++) binsM[i] = minMassBin + massBinWidth*i; const int nCent = 5; const int nPtWeight = 2; TH3D* hMCPSignal[nCent][nPtWeight]; TH3D* hMCNPSignal[nCent][nPtWeight]; TH3D* hPtMD0DcaMCPSignal[nCent][nPtWeight]; TH3D* hPtMD0DcaMCPSwapped[nCent][nPtWeight]; const char* CentArr[] ={"cent0to100","cent0to10", "cent10to30", "cent30to50", "cent50to100"}; const char* PtWeightArr[] ={"PtWeight","NoWeight"}; std::string iCentStr = "eta0to15"; std::string iPtWeightStr = "PtWeight"; for(int iCent=0; iCent<nCent; iCent++){ iCentStr= CentArr[iCent]; cutCentralityBin=cutCentralityBinArr[iCent]; for(int iPtWeight=0 ; iPtWeight<nPtWeight ; iPtWeight++){ iPtWeightStr= PtWeightArr[iPtWeight]; weightfunctionreco = weightfunctionrecoArr[iPtWeight]; hMCPSignal[iCent][iPtWeight] = new TH3D(Form("hMCPSignal_%s%s", iCentStr.c_str(), iPtWeightStr.c_str() ),";p_{T} (GeV/c);D^{0} DCA (cm);flight distance significance",nBinX,binsX,nBinY,binsY,nBinZ,binsZ); hMCNPSignal[iCent][iPtWeight] = new TH3D(Form("hMCNPSignal_%s%s", iCentStr.c_str(), iPtWeightStr.c_str() ),";p_{T} (GeV/c);D^{0} DCA (cm);flight distance significance",nBinX,binsX,nBinY,binsY,nBinZ,binsZ); hPtMD0DcaMCPSignal[iCent][iPtWeight] = new TH3D(Form("hPtMD0DcaMCPSignal_%s%s", iCentStr.c_str(), iPtWeightStr.c_str() ),";p_{T} (GeV/c);m (GeV/c^{2});D^{0} DCA (cm)",nBinX,binsX,nBinM,binsM,nBinY,binsY); hPtMD0DcaMCPSwapped[iCent][iPtWeight] = new TH3D(Form("hPtMD0DcaMCPSwapped_%s%s", iCentStr.c_str(), iPtWeightStr.c_str() ),";p_{T} (GeV/c);m (GeV/c^{2});D^{0} DCA (cm)",nBinX,binsX,nBinM,binsM,nBinY,binsY); hMCPSignal[iCent][iPtWeight]->Sumw2(); hMCNPSignal[iCent][iPtWeight]->Sumw2(); hPtMD0DcaMCPSignal[iCent][iPtWeight]->Sumw2(); hPtMD0DcaMCPSwapped[iCent][iPtWeight]->Sumw2(); tMCP->Draw(Form("DsvpvDistance/DsvpvDisErr:DsvpvDistance*sin(Dalpha):Dpt>>hMCPSignal_%s%s", iCentStr.c_str(), iPtWeightStr.c_str() ),weightfunctionreco*(cutpt&&cutPbPbMB&&cutSignal&&cutmc&&cutPrompt&&cutCentralityBin)); tMCNP->Draw(Form("DsvpvDistance/DsvpvDisErr:DsvpvDistance*sin(Dalpha):Dpt>>hMCNPSignal_%s%s", iCentStr.c_str(), iPtWeightStr.c_str()),weightfunctionreco*(cutpt&&cutPbPbMB&&cutSignal&&cutmc&&cutNonPrompt&&cutCentralityBin)); tMCP->Draw(Form("DsvpvDistance*sin(Dalpha):Dmass:Dpt>>hPtMD0DcaMCPSignal_%s%s", iCentStr.c_str(), iPtWeightStr.c_str()),cutpt&&cutPbPbMB&&cutmcSignal&&cutPrompt&&cutCentralityBin); tMCP->Draw(Form("DsvpvDistance*sin(Dalpha):Dmass:Dpt>>hPtMD0DcaMCPSwapped_%s%s", iCentStr.c_str(), iPtWeightStr.c_str() ),cutpt&&cutPbPbMB&&cutmcSwapped&&cutPrompt&&cutCentralityBin); } // end for(int iPtWeight=0 ; iPtWeight<nPtWeight ; iPtWeight++) } // end for(int iCent=0; iCent<nCent; iCent++) outf->Write(); }
int main(int argc, char** argv) { TDRStyle(); gStyle->SetPadTopMargin(0.2); gStyle->SetPadBottomMargin(0.2); gStyle->SetPadLeftMargin(0.07); gStyle->SetPadRightMargin(0.23); gStyle->cd(); std::cout << " " << std::endl; std::cout << " " << std::endl; std::cout << " " << std::endl; std::cout << " ___| | _) | ___| | " << std::endl; std::cout << " \\___ \\ __ \\ | | __| \\___ \\ _` | __ `__ \\ __ \\ | _ \\ " << std::endl; std::cout << " | | | | | | | ( | | | | | | | __/ " << std::endl; std::cout << " _____/ .__/ _| _| \\__| _____/ \\__,_| _| _| _| .__/ _| \\___| " << std::endl; std::cout << " _| _| " << std::endl; std::cout << " " << std::endl; std::cout << " " << std::endl; std::cout << " _ \\ _ \\ " << std::endl; std::cout << " | | | | __ \\ | | _` | __ \\ _` | _ \\ " << std::endl; std::cout << " __ < | | | | __ < ( | | | ( | __/ " << std::endl; std::cout << " _| \\_\\ \\__,_| _| _| _| \\_\\ \\__,_| _| _| \\__, | \\___| " << std::endl; std::cout << " |___/ " << std::endl; std::cout << " " << std::endl; std::cout << " " << std::endl; //Check if all nedeed arguments to parse are there if(argc != 2) { std::cerr << ">>>>> analysis.cpp::usage: " << argv[0] << " configFileName" << std::endl ; return 1; } // Parse the config file parseConfigFile (argv[1]) ; std::string treeName = gConfigParser -> readStringOption("Input::treeName"); std::string inputFileName = gConfigParser -> readStringOption("Input::inputFileName"); std::vector<int> runRangesMin = gConfigParser -> readIntListOption("Options::runRangesMin"); std::vector<int> runRangesMax = gConfigParser -> readIntListOption("Options::runRangesMax"); TTree *treeJetLepVect; std::string CutFile = gConfigParser -> readStringOption("Selections::CutFile"); std::vector<std::string> vCut; ///====> only the first cut is used! std::cout << " nCuts = " << ReadFileCut(CutFile, vCut) << std::endl; ///==== output file ==== std::string outputDirectory = gConfigParser -> readStringOption("Output::outputDirectory"); std::string OutFileName = gConfigParser -> readStringOption("Output::outFileName"); ///==== debug flag (begin) ==== bool debug = false; try { debug = gConfigParser -> readBoolOption("Input::debug"); } catch (char const* exceptionString){ std::cerr << " exception = " << exceptionString << std::endl; } std::cout << ">>>>> input::debug " << debug << std::endl; ///==== debug flag (end) ==== ///==== program ==== TFile* f = new TFile(inputFileName.c_str(), "READ"); treeJetLepVect = (TTree*) f->Get(treeName.c_str()); int totNumEvents = treeJetLepVect->GetEntries(vCut.at(0).c_str()); int numOutputFiles = runRangesMax.size(); std::cout << " totNumEvents = " << totNumEvents << std::endl; std::cout << " numOutputFiles = " << numOutputFiles << std::endl; treeJetLepVect->SetEntryList(0); treeJetLepVect->Draw(">> myList",vCut.at(0).c_str(),"entrylist"); TEntryList *myList = (TEntryList*)gDirectory->Get("myList"); treeJetLepVect->SetEntryList(myList); std::cout << " tot = " << myList->GetN() << " = " << totNumEvents << " =? " << treeJetLepVect -> GetEntries () << std::endl; TH1F* MyHistoCounterMC = (TH1F*) f->Get("AllEvents/totalEvents"); for (int iOutFile = 0; iOutFile < numOutputFiles; iOutFile++) { std::cout << " iOutFile = " << iOutFile << " : " << numOutputFiles << std::endl; TString outputRootFileName = Form("%s/%s_%d.root",outputDirectory.c_str(),OutFileName.c_str(), iOutFile); TFile outputRootFile ( outputRootFileName.Data(), "RECREATE") ; outputRootFile.cd () ; outputRootFile.mkdir ("ntupleEcalAlignment") ; outputRootFile.cd ("ntupleEcalAlignment") ; TTree* cloneTree = treeJetLepVect -> CloneTree (0) ; int countiEntry = 0; ///==== create list for this run range ==== TString Cut = Form ("((%s) && (runId >= %d && runId < %d))", vCut.at(0).c_str(), runRangesMin.at(iOutFile), runRangesMax.at(iOutFile)); treeJetLepVect->SetEntryList(0); treeJetLepVect->Draw(">> myList",Cut.Data(),"entrylist"); TEntryList *myList = (TEntryList*)gDirectory->Get("myList"); treeJetLepVect->SetEntryList(myList); for ( int iEntry = 0; iEntry < myList -> GetN () ; iEntry++) { countiEntry++; treeJetLepVect -> GetEntry (myList->Next()); cloneTree -> Fill () ; } cloneTree -> AutoSave () ; outputRootFile.cd () ; outputRootFile.mkdir ("AllEvents") ; outputRootFile.cd ("AllEvents") ; MyHistoCounterMC -> Write(); outputRootFile.Close () ; } }
TH2D* cycleHistHc(const char* filename) { TFile *f = new TFile(filename); TTree *t = (TTree*) f->Get("gammas"); TCanvas *cThc1 = new TCanvas("cTobyH1","Hag vs Cycle (1 of 4)",2000,2000); TCanvas *cThc2 = new TCanvas("cTobyH2","Hag vs Cycle (2 of 4)",2000,2000); TCanvas *cThc3 = new TCanvas("cTobyH3","Hag vs Cycle (3 of 4)",2000,2000); TCanvas *cThc4 = new TCanvas("cTobyH4","Hag vs Cycle (4 of 4)",2000,2000); cout <<"Opening 4 Canvases, with 4 each for the Hagrid crystals"<<endl; gStyle->SetOptLogz(1); cThc1->Divide(2,2,0.001,0.001); cThc2->Divide(2,2,0.001,0.001); cThc3->Divide(2,2,0.001,0.001); cThc4->Divide(2,2,0.001,0.001); TH2D* hHc0 = new TH2D("hHc0","Hag[1] vs cycle", 8000.,0.,8000.,200.,0.,200.); TH2D* hHc1 = new TH2D("hHc1","Hag[2] vs cycle", 8000.,0.,8000.,200.,0.,200.); TH2D* hHc2 = new TH2D("hHc2","Hag[3] vs cycle", 8000.,0.,8000.,200.,0.,200.); TH2D* hHc3 = new TH2D("hHc3","Hag[4] vs cycle", 8000.,0.,8000.,200.,0.,200.); TH2D* hHc4 = new TH2D("hHc4","Hag[5] vs cycle", 8000.,0.,8000.,200.,0.,200.); TH2D* hHc5 = new TH2D("hHc5","Hag[6] vs cycle", 8000.,0.,8000.,200.,0.,200.); TH2D* hHc6 = new TH2D("hHc6","Hag[7] vs cycle", 8000.,0.,8000.,200.,0.,200.); TH2D* hHc7 = new TH2D("hHc7","Hag[8] vs cycle", 8000.,0.,8000.,200.,0.,200.); TH2D* hHc8 = new TH2D("hHc8","Hag[9] vs cycle", 8000.,0.,8000.,200.,0.,200.); TH2D* hHc9 = new TH2D("hHc9","Hag[10] vs cycle", 8000.,0.,8000.,200.,0.,200.); TH2D* hHc10 = new TH2D("hHc10","Hag[11] vs cycle", 8000.,0.,8000.,200.,0.,200.); TH2D* hHc11 = new TH2D("hHc11","Hag[12] vs cycle", 8000.,0.,8000.,200.,0.,200.); TH2D* hHc12 = new TH2D("hHc12","Hag[13] vs cycle", 8000.,0.,8000.,200.,0.,200.); TH2D* hHc13 = new TH2D("hHc13","Hag[14] vs cycle", 8000.,0.,8000.,200.,0.,200.); TH2D* hHc14 = new TH2D("hHc14","Hag[15] vs cycle", 8000.,0.,8000.,200.,0.,200.); TH2D* hHc15 = new TH2D("hHc15","Hag[16] vs cycle", 8000.,0.,8000.,200.,0.,200.); //Set Min for logZ hHc0->SetMinimum(1); hHc1->SetMinimum(1); hHc2->SetMinimum(1); hHc3->SetMinimum(1); hHc4->SetMinimum(1); hHc5->SetMinimum(1); hHc6->SetMinimum(1); hHc7->SetMinimum(1); hHc8->SetMinimum(1); hHc9->SetMinimum(1); hHc10->SetMinimum(1); hHc11->SetMinimum(1); hHc12->SetMinimum(1); hHc13->SetMinimum(1); hHc14->SetMinimum(1); hHc15->SetMinimum(1); //Set Axis Zoom hHc0->GetXaxis()->SetRange(775,925); hHc1->GetXaxis()->SetRange(775,925); hHc2->GetXaxis()->SetRange(775,925); hHc3->GetXaxis()->SetRange(775,925); hHc4->GetXaxis()->SetRange(775,925); hHc5->GetXaxis()->SetRange(775,925); hHc6->GetXaxis()->SetRange(775,925); hHc7->GetXaxis()->SetRange(775,925); hHc8->GetXaxis()->SetRange(775,925); hHc9->GetXaxis()->SetRange(775,925); hHc10->GetXaxis()->SetRange(775,925); hHc11->GetXaxis()->SetRange(775,925); hHc12->GetXaxis()->SetRange(775,925); hHc13->GetXaxis()->SetRange(775,925); hHc14->GetXaxis()->SetRange(775,925); hHc15->GetXaxis()->SetRange(775,925); cThc1->cd(1); t->Draw("calgam.cycle:calgam.Hag[0]>>hHc0","calgam.Hag[0]>800 && calgam.Hag[0]<900","COLZ"); // cThc1->cd(2); // t->Draw("calgam.cycle:calgam.Hag[1]>>hHc1","calgam.Hag[1]>800 && calgam.Hag[1]<900","COLZ"); // cThc1->cd(3); // t->Draw("calgam.cycle:calgam.Hag[2]>>hHc2","calgam.Hag[2]>800 && calgam.Hag[2]<900","COLZ"); // cThc1->cd(4); // t->Draw("calgam.cycle:calgam.Hag[3]>>hHc3","calgam.Hag[3]>800 && calgam.Hag[3]<900","COLZ"); // cout<<"First Canvas Filled"<<endl; // cThc2->cd(1); // t->Draw("calgam.cycle:calgam.Hag[4]>>hHc4","calgam.Hag[4]>800 && calgam.Hag[4]<900","COLZ"); // cThc2->cd(2); // t->Draw("calgam.cycle:calgam.Hag[5]>>hHc5","calgam.Hag[5]>800 && calgam.Hag[5]<900","COLZ"); // cThc2->cd(3); // t->Draw("calgam.cycle:calgam.Hag[6]>>hHc6","calgam.Hag[6]>800 && calgam.Hag[6]<900","COLZ"); // cThc2->cd(4); // t->Draw("calgam.cycle:calgam.Hag[7]>>hHc7","calgam.Hag[7]>800 && calgam.Hag[7]<900","COLZ"); // cout<<"Second Canvas Filled"<<endl; // cThc3->cd(1); // t->Draw("calgam.cycle:calgam.Hag[8]>>hHc8","calgam.Hag[8]>800 && calgam.Hag[8]<900","COLZ"); // cThc3->cd(2); // t->Draw("calgam.cycle:calgam.Hag[9]>>hHc9","calgam.Hag[9]>800 && calgam.Hag[9]<900","COLZ"); // cThc3->cd(3); // t->Draw("calgam.cycle:calgam.Hag[10]>>hHc10","calgam.Hag[10]>800 && calgam.Hag[10]<900","COLZ"); // cThc3->cd(4); // t->Draw("calgam.cycle:calgam.Hag[11]>>hHc11","calgam.Hag[11]>800 && calgam.Hag[11]<900","COLZ"); // cout<<"Third Canvas Filled"<<endl; // cThc4->cd(1); // t->Draw("calgam.cycle:calgam.Hag[12]>>hHc12","calgam.Hag[12]>800 && calgam.Hag[12]<900","COLZ"); // cThc4->cd(2); // t->Draw("calgam.cycle:calgam.Hag[13]>>hHc13","calgam.Hag[13]>800 && calgam.Hag[13]<900","COLZ"); // cThc4->cd(3); // t->Draw("calgam.cycle:calgam.Hag[14]>>hHc14","calgam.Hag[14]>800 && calgam.Hag[14]<900","COLZ"); // cThc4->cd(4); // t->Draw("calgam.cycle:calgam.Hag[15]>>hHc15","calgam.Hag[15]>800 && calgam.Hag[15]<900","COLZ"); }
void BayesUnfoldingExample641() { #ifdef __CINT__ // Avoid CINT badness Printf("Please compile this script (root BayesUnfoldingExample641.C+) " "or use ROOT 6."); gSystem->Exit(0); #endif if (!gROOT->IsBatch()) { Printf("Several canvases coming...adding -b flag."); gROOT->SetBatch(); } gStyle->SetOptStat(0); gStyle->SetPaintTextFormat(".2f"); if (gSystem->Getenv("TMPDIR")) gSystem->SetBuildDir(gSystem->Getenv("TMPDIR")); TRandom3 ran; TStopwatch watch; // Watch starts here. A call to Start() would reset it. TObjArray *cList = new TObjArray(); // List of drawn canvases --> PDF file // Set up the problem double bins[Nt+1] = {0}; for (int j=0; j<=Nt; j++) bins[j] = 500*TMath::Exp(0.15*j); TestProblem testprob = AtlasDiJetMass(Nt, Nr, bins, bins, apar, bpar, nevts, evtWeight); TH2D *hM = testprob.Response; TH1D *hT = testprob.xTruth; TH1D *hTmc = testprob.xTruthEst; TH1D *hMt = testprob.xIni; TH1D *hD = testprob.bNoisy; TH1D *heff = testprob.eff; SetHistProps(hT,kRed+2,kNone,kRed+2); SetHistProps(hTmc,kRed,kNone,kRed); SetHistProps(hD,kBlack,kNone,kBlack,kFullCircle,1.5); TMatrixD M = MatrixUtils::Hist2Matrix(hM); TVectorD T = MatrixUtils::Hist2Vec(hT); // \hat{T} TVectorD Tmc = MatrixUtils::Hist2Vec(hTmc); // \tilde{T} TVectorD D = MatrixUtils::Hist2Vec(hD); TVectorD eff = MatrixUtils::Hist2Vec(heff); TVectorD Pt = MatrixUtils::ElemDiv(MatrixUtils::Hist2Vec(hMt), eff); // P(t) TMatrixD Prt = MatrixUtils::DivRowsByVector(M, Pt); // P(r|t) // Compute initial sampling volume and do MCMC sampling TGraphAsymmErrors *box = HyperBox(hTmc); SetGraphProps(box, kGreen+2, kNone, kSpring, kFullSquare, 1.0); // Likelihood functor LogPoissonLikeFn llfunc(Prt, D); // Curvature regularization. // Note that this is not directly penalizing curvature of the solution. // Instead it smooths the solution divided by the trial spectrum. std::vector<double> regpars; regpars.push_back(alpha); // Regularization strength for (int i=0; i<box->GetN(); i++) regpars.push_back(box->GetY()[i]); CurvatureRegFn regfunc(regpars); TTree *tmcmc = SampleMH(nMcmcSamples, 1e4, 0.01, box, llfunc, regfunc); // Create marginal prob. distributions from MCMC std::cout << Form("Marginalizing parameters from Markov chain...") << std::flush; TH1D *hMCMC[Nt]; for (int t=0; t<Nt; t++) { double tlo = box->GetY()[t] - box->GetEYlow()[t]; double thi = box->GetY()[t] + box->GetEYhigh()[t]; hMCMC[t] = new TH1D(Form("hMCMC%d",t),"",nMcmcBins, tlo, thi); hMCMC[t]->SetTitle(Form("MCMC - point %d;" "entries;" "Marginal posterior probability",t)); // Marginalize with unit weight when using MCMC, weight by // likelihood if sampling was uniform. tmcmc->Draw(Form("T%d >> hMCMC%d",t,t), "", "goff"); hMCMC[t]->Scale(1./hMCMC[t]->Integral(1, nMcmcBins)); SetHistProps(hMCMC[t], kBlack, kYellow, kBlack, kFullCircle, 1.0); hMCMC[t]->GetYaxis()->SetTitleOffset(1.5); } Printf("Done marginalizing MCMC."); // Now compute reduced sampling volume, and do uniform sampling TGraphAsymmErrors *rbox = ReducedSamplingVolume(hMCMC, box); SetGraphProps(rbox, kBlack, kNone, kNone, kFullSquare, 1.0); TH1D *hFlat[Nt]; if (doUniformSampling) { TTree *tflat = SampleUniform(nFlatSamples, D, Prt, rbox); std::cout << Form("Marginalizing parameters from uniform volume...") << std::flush; for (int t=0; t<Nt; t++) { double tlo = rbox->GetY()[t] - rbox->GetEYlow()[t]; double thi = rbox->GetY()[t] + rbox->GetEYhigh()[t]; hFlat[t] = new TH1D(Form("hFlat%d",t),"",nFlatBins, tlo, thi); hFlat[t]->SetTitle(Form("Uniform sampling - point %d;" "dijet mass (GeV/c^{2});" "Marginal posterior probability",t)); tflat->Draw(Form("T%d >> hFlat%d",t,t), "L", "goff"); hFlat[t]->Scale(1./hFlat[t]->Integral(1,nFlatBins)); SetHistProps(hFlat[t], kBlack, kOrange, kBlack, kFullCircle, 1.0); } Printf("Done marginalizing uniform volume."); } // Unfolded spectrum from MCMC TGraphErrors *unf1 = new TGraphErrors(); SetGraphProps(unf1, kBlue, kNone, kBlue, kOpenSquare, 1.5); unf1->SetLineWidth(2); for (int t=0; t<Nt; t++) { MaxDensityInterval mdi = GetMDI(hMCMC[t], 0.68); unf1->SetPoint(t, hD->GetBinCenter(t+1), mdi.u); unf1->SetPointError(t, 0.48*hD->GetBinWidth(t+1), mdi.du); } // Unfolded spectrum from uniform sampling after volume reduction TGraphErrors *unf2 = 0; if (doUniformSampling) { unf2 = new TGraphErrors(); SetGraphProps(unf2, kRed, kNone, kRed, kOpenSquare, 1.5); unf2->SetLineWidth(2); for (int t=0; t<Nt; t++) { MaxDensityInterval mdi = GetMDI(hFlat[t], 0.68); unf2->SetPoint(t, hD->GetBinCenter(t+1), mdi.u); unf2->SetPointError(t, 0.47*hD->GetBinWidth(t+1), mdi.du); } } Printf("Drawing results..."); DrawObject(hM, "colz", "matrix", cList, 550, 500); gPad->SetLogx(); gPad->SetLogy(); gPad->SetLogz(); gPad->SetRightMargin(0.15); DrawObject(heff, "", "efficiency", cList); // Draw marginal dists. from MCMC for (int t=0; t<Nt; t++) { DrawObject(hMCMC[t], "", Form("post_%d", t), cList); gPad->SetLeftMargin(0.15); if (doUniformSampling) { hFlat[t]->Scale(1./hFlat[t]->Integral(1, nFlatBins,"width")); hFlat[t]->Draw("same"); } double ymin = hMCMC[t]->GetMinimum(); double ymax = hMCMC[t]->GetMaximum(); double yDraw = 0.25*(ymax-ymin); DataPoint(hD, hMCMC[t], t, 0.75*yDraw)->Draw("ep same"); TruePoint(hT, hMCMC[t], t, yDraw)->Draw("p same"); MD68Point(hMCMC[t], yDraw)->Draw("ep same"); } // Result! hT->GetYaxis()->SetRangeUser(0.002, 101*nevts*evtWeight); DrawObject(hT, "ep", "result", cList); gPad->SetLogy(); box->Draw("e5 same"); if (doUniformSampling || drawReducedVolume) rbox->Draw("e5 same"); hT->Draw("same"); hD->Draw("ep same"); unf1->Draw("ep same"); if (unf2) unf2->Draw("ep same"); if (printPDFs) { PrintPDFs(cList, "pdfs"); // Print individuals into ./pdfs dir PrintPDF(cList, "pdfs/mcmc_unfold_example"); // Multipage PDF } Printf("All done."); watch.Stop(); watch.Print(); return; }
void scan_results(TString infile = "output/V00-00-12/skim_1lpt30_2b_aged/TChiWH14Pythia_PhaseII__140PU_baby.root", TString output = "test.root", float br = 1.0) { TFile* f = new TFile(infile); TTree* t = f->Get("t"); TFile* fout = new TFile(output,"RECREATE"); ofstream out_yields("yields.txt"); ofstream out_signif("signif.txt"); ofstream out_rinv("rinv.txt"); ofstream out_signif_syst25("signif_syst25.txt"); ofstream out_rinv_syst25("rinv_syst25.txt"); // ----------------------------- // cuts TCut nlep1("nleps==1"); TCut ptlep40("lep1pt>40"); TCut etalep("abs(lep1eta) < 2.4"); TCut agednlep1("agednleps==1"); TCut agedptlep40("agedlep1pt>40"); TCut agedetalep("abs(agedlep1eta) < 2.4"); TCut agedmu("agedlep1pt>35 && abs(agedlep1eta) < 1.1 && leptype == 1"); TCut agedel("agedlep1pt>50 && abs(agedlep1eta) < 2.4 && leptype == 0"); TCut agedlep = agedmu || agedel; TCut njmin2pt40("njets40>=2"); TCut nb2("nb==2"); TCut nb2pt40cent("nb==2 && bjet1pt > 40. && bjet2pt > 40. && abs(bjet1eta) < 2.4 && abs(bjet2eta) < 2.4"); TCut nj2("njets==2"); TCut mt100("mt > 100.0"); TCut pujetmt100("pujetmt > 100.0"); TCut smearmt100("smearmt > 100.0"); TCut smearmt150("smearmt > 150.0"); TCut smearmt200("smearmt > 200.0"); TCut met200("met > 200.0"); TCut met300("met > 300.0"); TCut met400("met > 400.0"); TCut met500("met > 500.0"); TCut pujetmet200("pujetmet > 200.0"); TCut pujetmet300("pujetmet > 300.0"); TCut pujetmet400("pujetmet > 400.0"); TCut pujetmet500("pujetmet > 500.0"); TCut smearmet200("smearmet > 200.0"); TCut smearmet300("smearmet > 300.0"); TCut smearmet400("smearmet > 400.0"); TCut smearmet500("smearmet > 500.0"); TCut smearmet600("smearmet > 600.0"); TCut mct160("mct > 160.0"); TCut mbb90("mbb > 90.0 && mbb < 150.0"); TCut photveto100("phot1pt < 100."); TCut dmet200("abs(met - pujetmet)< 200.0"); // // TString scenario = "PhaseII_700fb"; // TString scenario = "PhaseII_3000fb"; // TCut weight("3000. * weight * genweight * bgweight"); // // TCut weight("1000. * weight * genweight * bgweight"); // // TCut weight("700. * weight * genweight * bgweight"); // //TCut presel = nlep1 + ptlep40 + etalep + njmin2pt40 + nb2pt40cent + mbb90; // TCut presel = nlep1 + ptlep40 + etalep + njmin2pt40 + nb2pt40cent + mbb90 + photveto100 + dmet200; // TCut sigsel = presel + nj2 + pujetmt100 + mct160; // TCut sig200 = sigsel + pujetmet200; // TCut sig300 = sigsel + pujetmet300; // TCut sig400 = sigsel + pujetmet400; // TCut sig500 = sigsel + pujetmet500; // // --- aged detector // TString scenario = "aged_700fb"; // TCut weight("700. * weight * genweight * bgweight * agedweight"); // TCut presel = agednlep1 + agedlep + njmin2pt40 + nb2pt40cent + mbb90 + photveto100 + dmet200; // TCut sigsel = presel + nj2 + smearmt100 + mct160; // TCut sig200 = sigsel + smearmet200; // TCut sig300 = sigsel + smearmet300; // TCut sig400 = sigsel + smearmet400; // TCut sig500 = sigsel + smearmet500; // TString scenario = "aged_nosmear_700fb"; // TCut weight("700. * weight * genweight * bgweight * agedweight"); // TCut presel = agednlep1 + agedlep + njmin2pt40 + nb2pt40cent + mbb90 + photveto100 + dmet200; // TCut sigsel = presel + nj2 + pujetmt100 + mct160; // TCut sig200 = sigsel + pujetmet200; // TCut sig300 = sigsel + pujetmet300; // TCut sig400 = sigsel + pujetmet400; // TCut sig500 = sigsel + pujetmet500; // TString scenario = "aged_TPfinal_700fb"; // TCut weight("700. * weight * genweight * bgweight * agedweight"); // TCut presel = agednlep1 + agedlep + njmin2pt40 + nb2pt40cent + mbb90 + photveto100 + dmet200; // TCut sigsel = presel + nj2 + smearmt100 + mct160; // TCut sig200 = sigsel + smearmet200; // TCut sig300 = sigsel + smearmet300; // TCut sig400 = sigsel + smearmet400; // TCut sig500 = sigsel + smearmet500; // TString scenario = "PhaseII_PU200_3000fb"; // TCut weight("3000. * weight * genweight * bgweight"); // TCut presel = nlep1 + ptlep40 + etalep + njmin2pt40 + nb2pt40cent + mbb90 + photveto100 + dmet200; // TCut sigsel = presel + nj2 + smearmt150 + mct160; // TCut sig200 = sigsel + smearmet200; // TCut sig300 = sigsel + smearmet300; // TCut sig400 = sigsel + smearmet400; // TCut sig500 = sigsel + smearmet500; // TString scenario = "PhaseII_PU200_4000fb"; // TCut weight("4000. * weight * genweight * bgweight"); // TCut presel = nlep1 + ptlep40 + etalep + njmin2pt40 + nb2pt40cent + mbb90 + photveto100 + dmet200; // TCut sigsel = presel + nj2 + smearmt150 + mct160; // TCut sig200 = sigsel + smearmet200; // TCut sig300 = sigsel + smearmet300; // TCut sig400 = sigsel + smearmet400; // TCut sig500 = sigsel + smearmet500; TString scenario = "PhaseII_NoTrkExt_3000fb"; TCut weight("3000. * weight * genweight * bgweight"); TCut presel = nlep1 + ptlep40 + etalep + njmin2pt40 + nb2pt40cent + mbb90 + photveto100 + dmet200; TCut sigsel = presel + nj2 + smearmt200 + mct160; TCut sig200 = sigsel + smearmet200; TCut sig300 = sigsel + smearmet300; TCut sig400 = sigsel + smearmet400; TCut sig500 = sigsel + smearmet500; TCut sig600 = sigsel + smearmet600; const unsigned int nregs = 5; TCut sigregs[nregs] = {sig200, sig300, sig400, sig500, sig600}; // TString scenario = "PhaseI_3000fb"; // TCut weight("3000. * weight * genweight * bgweight"); // TCut presel = nlep1 + ptlep40 + etalep + njmin2pt40 + nb2pt40cent + mbb90; // TCut sigsel = presel + nj2 + mt100 + mct160; // TCut sig200 = sigsel + met200; // TCut sig300 = sigsel + met300; // TCut sig400 = sigsel + met400; // TCut sig500 = sigsel + met500; // const unsigned int nregs = 4; // TCut sigregs[nregs] = {sig200, sig300, sig400, sig500}; // TString scenario = "PhaseI_300fb"; // TCut weight("300. * weight * genweight * bgweight"); // TCut presel = nlep1 + ptlep40 + etalep + njmin2pt40 + nb2pt40cent + mbb90; // TCut sigsel = presel + nj2 + mt100 + mct160; // TCut sig200 = sigsel + met200; // TCut sig300 = sigsel + met300; // TCut sig400 = sigsel + met400; // const unsigned int nregs = 3; // TCut sigregs[nregs] = {sig200, sig300, sig400}; //---------------------------------------------- // background results std::vector<float> bg_yields; // // numbers with additional MET cleaning, PhaseII 140PU // bg_yields.push_back(1408.); // bg_yields.push_back(354.); // bg_yields.push_back(39.); // bg_yields.push_back(7.5); // numbers with additional MET cleaning, PhaseII 140PU // for 1000/fb // bg_yields.push_back(469.); // bg_yields.push_back(118.); // bg_yields.push_back(13.); // bg_yields.push_back(2.5); // // numbers with additional MET cleaning, PhaseII 140PU // // for 700/fb // bg_yields.push_back(329.); // bg_yields.push_back(83.); // bg_yields.push_back(9.1); // bg_yields.push_back(1.7); // // numbers with additional MET cleaning, PhaseII 140PU, AGED detector // // for 1000/fb // bg_yields.push_back(605.); // bg_yields.push_back(119.); // bg_yields.push_back(14.); // bg_yields.push_back(3.4); // // numbers with additional MET cleaning, PhaseII 140PU, AGED detector // // for 700/fb // bg_yields.push_back(410.); // bg_yields.push_back(82.); // bg_yields.push_back(10.); // bg_yields.push_back(2.4); // // numbers with additional MET cleaning, PhaseII 140PU, AGED detector, no MET smearing // // for 700/fb // bg_yields.push_back(125.); // bg_yields.push_back(38.); // bg_yields.push_back(4.4); // bg_yields.push_back(0.5); // // numbers with additional MET cleaning, PhaseII 140PU, AGED detector, TP final settings // // for 700/fb // bg_yields.push_back(233.); // bg_yields.push_back(54.); // bg_yields.push_back(5.3); // bg_yields.push_back(0.9); // // numbers for PhaseII smeared to PU200 3000/fb // bg_yields.push_back(952.); // bg_yields.push_back(193.); // bg_yields.push_back(48.); // bg_yields.push_back(16.); // // numbers for PhaseII smeared to PU200 4000/fb // bg_yields.push_back(1269.); // bg_yields.push_back(257.); // bg_yields.push_back(64.); // bg_yields.push_back(21.); // numbers for PhaseII smeared to NoTrkExt 3000/fb bg_yields.push_back(704.); bg_yields.push_back(160.); bg_yields.push_back(57.); bg_yields.push_back(20.); bg_yields.push_back(13.); // // numbers from PhaseI 50PU 3000/fb // bg_yields.push_back(1289.); // bg_yields.push_back(267.); // bg_yields.push_back(37.); // bg_yields.push_back(3.0); // // numbers from PhaseI 50PU 300/fb // bg_yields.push_back(129.); // bg_yields.push_back(27.); // bg_yields.push_back(3.7); // // limits on nevents, from LandS with no signal systs, PhaseII 140PU // std::vector<float> limits_25; // limits_25.push_back(534.); // limits_25.push_back(145.); // limits_25.push_back(24.9); // limits_25.push_back(10.7); // std::vector<float> limits_12p5; // limits_12p5.push_back(307.); // limits_12p5.push_back(88.); // limits_12p5.push_back(18.9); // limits_12p5.push_back(9.6); // // // limits on nevents, from LandS with no signal systs, PhaseII 140PU // // // with additional met cleaning // std::vector<float> limits_25; // limits_25.push_back(505.); // limits_25.push_back(130.); // limits_25.push_back(19.5); // limits_25.push_back(7.2); // std::vector<float> limits_12p5; // limits_12p5.push_back(287.); // limits_12p5.push_back(80.); // limits_12p5.push_back(15.6); // limits_12p5.push_back(6.9); // // limits on nevents, from LandS with no signal systs, PhaseII 140PU // // with additional met cleaning // // for 1000/fb // std::vector<float> limits_25; // limits_25.push_back(171.); // limits_25.push_back(47.4); // limits_25.push_back(9.7); // limits_25.push_back(4.6); // std::vector<float> limits_12p5; // limits_12p5.push_back(103.); // limits_12p5.push_back(32.5); // limits_12p5.push_back(8.7); // limits_12p5.push_back(4.5); // limits on nevents, from LandS with no signal systs, PhaseII 140PU, AGED detector // with additional met cleaning // for 1000/fb std::vector<float> limits_25; limits_25.push_back(218.); limits_25.push_back(47.9); limits_25.push_back(10.2); limits_25.push_back(5.1); limits_25.push_back(2); // dummy value std::vector<float> limits_12p5; limits_12p5.push_back(130.); limits_12p5.push_back(32.7); limits_12p5.push_back(9.1); limits_12p5.push_back(5.0); limits_12p5.push_back(2); // dummy value // // limits on nevents, from LandS with no signal systs, PhaseI 50PU // std::vector<float> limits_25; // limits_25.push_back(51.4); // limits_25.push_back(15.1); // limits_25.push_back(5.3); // std::vector<float> limits_12p5; // limits_12p5.push_back(34.5); // limits_12p5.push_back(12.7); // limits_12p5.push_back(5.2); TH2F* h_base = new TH2F("h_base","", 11, -50, 1050, 11, -50, 1050); // TH2F* h_base = new TH2F("h_base","", 22, -50, 1050, 22, -50, 1050); TH2F* hists_yields[nregs]; TH2F* hists_signif_25[nregs]; TH2F* hists_signif_12p5[nregs]; TH2F* hists_rinv_25[nregs]; TH2F* hists_rinv_12p5[nregs]; for (unsigned int ireg = 0; ireg < nregs; ++ireg) { TString histname = Form("h_yields_%d",ireg); TH2F* h_yields = h_base->Clone(histname); t->Draw("mlsp:mchi>>"+histname,sigregs[ireg]*weight); hists_yields[ireg] = h_yields; h_yields->Write(); TString histname_signif25 = Form("h_signif25_%d",ireg); TH2F* h_signif25 = h_base->Clone(histname_signif25); TString histname_rinv25 = Form("h_rinv25_%d",ireg); TH2F* h_rinv25 = h_base->Clone(histname_rinv25); TString histname_signif12p5 = Form("h_signif12p5_%d",ireg); TH2F* h_signif12p5 = h_base->Clone(histname_signif12p5); TString histname_rinv12p5 = Form("h_rinv12p5_%d",ireg); TH2F* h_rinv12p5 = h_base->Clone(histname_rinv12p5); for (unsigned int ix = 1; ix <= h_yields->GetNbinsX(); ++ix) { for (unsigned int iy = 1; iy <= h_yields->GetNbinsY(); ++iy) { // skip empty bins float nsig = h_yields->GetBinContent(ix,iy) * br; float nbg = bg_yields.at(ireg); if (nsig < 0.001) continue; float zbi_val_25 = RooStats::NumberCountingUtils::BinomialObsZ(nsig+nbg,nbg,0.25); h_signif25->SetBinContent(ix,iy,zbi_val_25); h_rinv25->SetBinContent(ix,iy,nsig/limits_25.at(ireg)); float zbi_val_12p5 = RooStats::NumberCountingUtils::BinomialObsZ(nsig+nbg,nbg,0.125); h_signif12p5->SetBinContent(ix,iy,zbi_val_12p5); h_rinv12p5->SetBinContent(ix,iy,nsig/limits_12p5.at(ireg)); } // y bins } // x bins hists_signif_25[ireg] = h_signif25; h_signif25->Write(); hists_signif_12p5[ireg] = h_signif12p5; h_signif12p5->Write(); hists_rinv_25[ireg] = h_rinv25; h_rinv25->Write(); hists_rinv_12p5[ireg] = h_rinv12p5; h_rinv12p5->Write(); } // loop over signal regions TH2F* h_signif25_best = h_base->Clone("h_signif25_best"); TH2F* h_rinv25_best = h_base->Clone("h_rinv25_best"); TH2F* h_signif25_all = h_base->Clone("h_signif25_all"); TH2F* h_rinv25_all = h_base->Clone("h_rinv25_all"); TH2F* h_disc25 = h_base->Clone("h_disc25"); TH2F* h_exc25 = h_base->Clone("h_exc25"); TH2F* h_signif12p5_best = h_base->Clone("h_signif12p5_best"); TH2F* h_rinv12p5_best = h_base->Clone("h_rinv12p5_best"); TH2F* h_signif12p5_all = h_base->Clone("h_signif12p5_all"); TH2F* h_rinv12p5_all = h_base->Clone("h_rinv12p5_all"); TH2F* h_disc12p5 = h_base->Clone("h_disc12p5"); TH2F* h_exc12p5 = h_base->Clone("h_exc12p5"); // out_yields << "C1 N1 BKg TChiWH" << endl; // out_signif << "C1 N1 Signif" << endl; // out_rinv << "C1 N1 Rinv" << endl; // for each point, find signal region with best expected significance for (unsigned int ix = 1; ix <= h_base->GetNbinsX(); ++ix) { for (unsigned int iy = 1; iy <= h_base->GetNbinsY(); ++iy) { int c1 = h_signif12p5_all->GetXaxis()->GetBinCenter(ix); int n1 = h_signif12p5_all->GetYaxis()->GetBinCenter(iy); if (c1 == 100) c1 = 130; if (n1 == 0) n1 = 1; else if (c1-n1 == 100) n1 = c1 - 130; // cout << Form("%d %d",c1,n1) << endl; float max_signif_25 = 0.; float max_signif_12p5 = 0.; int best_signif_25 = -1; int best_signif_12p5 = -1; // float max_rinv_25 = 999999.; // float max_rinv_12p5 = 999999.; float max_rinv_25 = 0.; float max_rinv_12p5 = 0.; int best_rinv_25 = -1; int best_rinv_12p5 = -1; for (unsigned int ireg = 0; ireg < nregs; ++ireg) { float signif_25 = hists_signif_25[ireg]->GetBinContent(ix,iy); if (signif_25 > max_signif_25) { max_signif_25 = signif_25; best_signif_25 = ireg+1; } float rinv_25 = hists_rinv_25[ireg]->GetBinContent(ix,iy); // if ((rinv_25 < max_rinv_25) && (rinv_25 > 0.0001)) { if (rinv_25 > max_rinv_25) { max_rinv_25 = rinv_25; best_rinv_25 = ireg+1; } float signif_12p5 = hists_signif_12p5[ireg]->GetBinContent(ix,iy); if (signif_12p5 > max_signif_12p5) { max_signif_12p5 = signif_12p5; best_signif_12p5 = ireg+1; } float rinv_12p5 = hists_rinv_12p5[ireg]->GetBinContent(ix,iy); // if ((rinv_12p5 < max_rinv_12p5) && (rinv_12p5 > 0.0001) ) { if (rinv_12p5 > max_rinv_12p5 ) { max_rinv_12p5 = rinv_12p5; best_rinv_12p5 = ireg+1; } } // sig regions if (best_signif_25 >= 1) { h_signif25_all->SetBinContent(ix,iy,max_signif_25); h_signif25_best->SetBinContent(ix,iy,best_signif_25); if (max_signif_25 >= 5.0) h_disc25->SetBinContent(ix,iy,1.); out_signif_syst25 << Form("%d %d %.3f",c1,n1,max_signif_25) << endl; } if (best_rinv_25 >= 1) { h_rinv25_all->SetBinContent(ix,iy,max_rinv_25); h_rinv25_best->SetBinContent(ix,iy,best_rinv_25); // if (max_rinv_25 <= 1.0) h_exc25->SetBinContent(ix,iy,1.); if (max_rinv_25 >= 1.0) h_exc25->SetBinContent(ix,iy,1.); out_rinv_syst25 << Form("%d %d %.3f",c1,n1,max_rinv_25) << endl; } if (best_signif_12p5 >= 1) { h_signif12p5_all->SetBinContent(ix,iy,max_signif_12p5); h_signif12p5_best->SetBinContent(ix,iy,best_signif_12p5); if (max_signif_12p5 >= 5.0) h_disc12p5->SetBinContent(ix,iy,1.); float nsig = hists_yields[best_signif_12p5-1]->GetBinContent(ix,iy) * br; float nbg = bg_yields.at(best_signif_12p5-1); out_yields << Form("%d %d %.1f %.1f",c1,n1,nbg,nsig) << endl; out_signif << Form("%d %d %.3f",c1,n1,max_signif_12p5) << endl; writeCard(Form("card_%s_%d_%d",scenario.Data(),c1,n1),nsig,nbg,1.125); } if (best_rinv_12p5 >= 1) { h_rinv12p5_all->SetBinContent(ix,iy,max_rinv_12p5); h_rinv12p5_best->SetBinContent(ix,iy,best_rinv_12p5); // if (max_rinv_12p5 <= 1.0) h_exc12p5->SetBinContent(ix,iy,1.); if (max_rinv_12p5 >= 1.0) h_exc12p5->SetBinContent(ix,iy,1.); out_rinv << Form("%d %d %.3f",c1,n1,max_rinv_12p5) << endl; } } // y bins } // x bins // fix a couple bins by hand h_disc25->SetBinContent(2,1,0.); h_signif25_best->Write(); h_signif25_all->Write(); h_disc25->Write(); h_rinv25_best->Write(); h_rinv25_all->Write(); h_exc25->Write(); h_signif12p5_best->Write(); h_signif12p5_all->Write(); h_disc12p5->Write(); h_rinv12p5_best->Write(); h_rinv12p5_all->Write(); h_exc12p5->Write(); // fout->Write(); fout->Close(); out_yields.close(); out_signif.close(); out_rinv.close(); }
uwLowLightCalib(){ const int numRuns = 18; const char* files[numRuns] = { "../crunchedFiles/run_00262_crunched.root", "../crunchedFiles/run_00263_crunched.root", "../crunchedFiles/run_00264_crunched.root", "../crunchedFiles/run_00265_crunched.root", "../crunchedFiles/run_00266_crunched.root", "../crunchedFiles/run_00267_crunched.root", "../crunchedFiles/run_00268_crunched.root", "../crunchedFiles/run_00269_crunched.root", "../crunchedFiles/run_00270_crunched.root", "../crunchedFiles/run_00274_crunched.root", "../crunchedFiles/run_00275_crunched.root", "../crunchedFiles/run_00278_crunched.root", "../crunchedFiles/run_00279_crunched.root", "../crunchedFiles/run_00280_crunched.root", "../crunchedFiles/run_00281_crunched.root", "../crunchedFiles/run_00282_crunched.root", "../crunchedFiles/run_00284_crunched.root", "../crunchedFiles/run_00285_crunched.root"}; gStyle->SetOptFit(1); vector<double> means[4]; vector<double> sigs[4]; vector<double> meanErrs[4]; vector<double> sigErrs[4]; for (int i = 0; i < numRuns; ++i){ TFile* f = new TFile(files[i]); TTree* t = (TTree*) f->Get("t"); for (int j = 0; j < 4; ++j){ t->Draw(Form("sipm%i.energy>>h%i",j+1,j),Form("sipm%i.valid",j+1)); TH1F* h = (TH1F*) gROOT->FindObject(Form("h%i",j)); h->Fit("gaus","0"); means[j].push_back(h->GetFunction("gaus")->GetParameter(1)); sigs[j].push_back(h->GetFunction("gaus")->GetParameter(2)); meanErrs[j].push_back(h->GetFunction("gaus")->GetParError(1)); sigErrs[j].push_back(h->GetFunction("gaus")->GetParError(2)); } } vector<double> variances[4]; vector<double> varianceErrors[4]; for(int i = 0; i < means.size(); ++i){ for(int j = 0; j < 4; ++j){ variances[j].push_back(sigs[j][i]*sigs[j][i]); varianceErrors[j].push_back(2*sigs[j][i]*sigErrs[j][i]); } } TCanvas* c1 = new TCanvas(); c1->Divide(2,2); for(int j = 0; j < 4; ++j){ c1->cd(j+1); TGraphErrors* linGraph = new TGraphErrors(means[j].size(), &means[j][0], &variances[j][0], &meanErrs[j][0], &varianceErrors[j][0]); TGraphErrors* quadGraph = new TGraphErrors(means.size(), &means[j][0], &variances[j][0], &meanErrs[j][0], &varianceErrors[j][0]); linGraph->SetMarkerStyle(20); linGraph->Fit("pol1"); linGraph->SetTitle(Form("SiPM %i", j+1)); linGraph->GetFunction("pol1")->SetLineColor(kBlue); linGraph->GetXaxis()->SetTitle("Mean"); linGraph->GetYaxis()->SetTitle("#sigma^{2}"); quadGraph->SetMarkerStyle(20); quadGraph->Fit("pol2"); quadGraph->GetFunction("pol2")->SetLineColor(kRed); linGraph->Draw("ap"); quadGraph->Draw("psame"); } for( int i = 0; i < 4; ++ i){ for (int j = 0; j<i; ++j){ new TCanvas(); TGraphErrors* corrGraph = new TGraphErrors(means[i].size(), &means[i][0], &means[j][0], &meanErrs[i][0], &meanErrs[j][0]); corrGraph->GetXaxis()->SetTitle(Form("SiPM %i Mean", i+1)); corrGraph->GetYaxis()->SetTitle(Form("SiPM %i Mean", j+1)); corrGraph->SetTitle(Form("SiPM %i vs SiPM %i",j+1, i+1)); corrGraph->Fit("pol1"); corrGraph->SetMarkerStyle(20); corrGraph->Draw("ap"); } } }
void ModXSec(string inFile, string outFile, bool removeTaus=true, bool applyKFactors=true){ bool doTC = inFile.find("TC") != string::npos; cout<<"doTC is "<<doTC<<endl; TTree* tLimit = new TTree("tLimit", "Limits"); tLimit->ReadFile(inFile.c_str()); ofstream out(outFile.c_str()); if(doTC) out<<"Rho/F:"; else out<<"Mass/F:"; if(doTC){ out<<"Pi/F:"; out<<"SinX/F:"; } out<<"Xsec/F:" <<"percentError/F" <<endl; //kfactors TGraph* gK = new TGraph(20); gK->SetPoint( 0, 200,1.347); gK->SetPoint( 1, 300,1.347); gK->SetPoint( 2, 500,1.363); gK->SetPoint( 3, 700,1.351); gK->SetPoint( 4, 900,1.347); gK->SetPoint( 5,1100,1.331); gK->SetPoint( 6,1300,1.317); gK->SetPoint( 7,1500,1.293); gK->SetPoint( 8,1700,1.257); gK->SetPoint( 9,1900,1.230); gK->SetPoint( 10,2000,1.214); //Signal pdf uncertainties TGraph* gPerErr = new TGraph(20); gPerErr->SetPoint( 0, 200,2.192); gPerErr->SetPoint( 1, 300,2.192); gPerErr->SetPoint( 2, 500,2.632); gPerErr->SetPoint( 3, 700,3.070); gPerErr->SetPoint( 4, 900,3.448); gPerErr->SetPoint( 5,1100,3.771); gPerErr->SetPoint( 6,1300,4.101); gPerErr->SetPoint( 7,1500,4.339); gPerErr->SetPoint( 8,1700,4.581); gPerErr->SetPoint( 9,1900,4.846); gPerErr->SetPoint( 10,2000,4.981); if(doTC) tLimit->Draw("Rho:Xsec:Pi:SinX", "SinX > 0.32 && SinX<0.34", "para goff"); //if(doTC) tLimit->Draw("Rho:Xsec:Pi:SinX", "(280<=Rho && Rho<=300) && (150<=Pi && Pi<=160)", "para goff"); else tLimit->Draw("Mass:Xsec", "", "para goff"); float n = tLimit->GetSelectedRows(); for(int isample=0; isample<n; ++isample){ int idx=0; Double_t mass = tLimit->GetVal(idx++)[isample]; Double_t xsec = tLimit->GetVal(idx++)[isample]; Double_t pi(-1), sinx(-1); if(doTC){ pi = tLimit->GetVal(idx++)[isample]; sinx = tLimit->GetVal(idx++)[isample]; } //cout<<"For rho: "<<rho<<" the kfactor is "<<gK->Eval(rho)<<endl; //xsec *= 1e9; //convert from mb to pb if(removeTaus) xsec *= 4./9.; //convert from emt to em if(applyKFactors) xsec *= gK->Eval(mass);//apply k factor Double_t perErr = gPerErr->Eval(mass); out.precision(0) ; out.setf ( ios::fixed, ios::floatfield); out <<mass<<"\t"; if(doTC){ out.precision(0) ; out.setf ( ios::fixed, ios::floatfield); out <<pi<<"\t"; out.precision(4) ; out.setf ( ios::fixed, ios::floatfield); out <<sinx<<"\t"; } out.precision(4) ; out.setf ( ios::scientific, ios::floatfield); out <<xsec<<"\t"; out.precision(3); out.setf ( ios::fixed, ios::floatfield); out<<perErr<<"\t"; out<<endl; } }