//----------------------------------------------------------------------------- StatusCode RootHistCnv::RDirectoryCnv::fillObjRefs(IOpaqueAddress* pAddr,DataObject* pObj) { MsgStream log(msgSvc(), "RDirectoryCnv"); IRegistry* pReg = pObj->registry(); std::string full = pReg->identifier(); const std::string& fname = pAddr->par()[0]; TFile *tf; findTFile(full,tf).ignore(); // cd to TFile: setDirectory(full); TIter nextkey(gDirectory->GetListOfKeys()); while (TKey *key = (TKey*)nextkey()) { IOpaqueAddress* pA = 0; TObject *obj = key->ReadObj(); std::string title = obj->GetTitle(); std::string sid = obj->GetName(); std::string f2 = full + "/" + sid; int idh = ::strtol(sid.c_str(),NULL,10); // introduced by Grigori Rybkine std::string clname = key->GetClassName(); std::string clnm = clname.substr(0,3); TClass* isa = obj->IsA(); if (isa->InheritsFrom("TTree")) { createAddress(full, CLID_ColumnWiseTuple, idh, obj, pA).ignore(); TTree* tree = (TTree*) obj; tree->Print(); log << MSG::DEBUG << "Reg CWNT \"" << obj->GetTitle() << "\" as " << f2 << endmsg; title = "/" + sid; } else if (isa->InheritsFrom("TDirectory")) { createAddress(full,CLID_NTupleDirectory, title, obj, pA).ignore(); } else if ( isa == TProfile::Class() ) { createAddress(full,CLID_ProfileH,idh,obj,pA).ignore(); title = sid; } else if ( isa == TProfile2D::Class() ) { createAddress(full,CLID_ProfileH2,idh,obj,pA).ignore(); title = sid; } else if ( isa == TH1C::Class() ) { createAddress(full,CLID_H1D,idh,obj,pA).ignore(); title = sid; } else if ( isa == TH1S::Class() ) { createAddress(full,CLID_H1D,idh,obj,pA).ignore(); title = sid; } else if ( isa == TH1I::Class() ) { createAddress(full,CLID_H1D,idh,obj,pA).ignore(); title = sid; } else if ( isa == TH1F::Class() ) { createAddress(full,CLID_H1D,idh,obj,pA).ignore(); title = sid; } else if ( isa == TH1D::Class() ) { createAddress(full,CLID_H1D,idh,obj,pA).ignore(); title = sid; } else if ( isa == TH2C::Class() ) { createAddress(full,CLID_H2D,idh,obj,pA).ignore(); title = sid; } else if ( isa == TH2S::Class() ) { createAddress(full,CLID_H2D,idh,obj,pA).ignore(); title = sid; } else if ( isa == TH2I::Class() ) { createAddress(full,CLID_H2D,idh,obj,pA).ignore(); title = sid; } else if ( isa == TH2F::Class() ) { createAddress(full,CLID_H2D,idh,obj,pA).ignore(); title = sid; } else if ( isa == TH2D::Class() ) { createAddress(full,CLID_H2D,idh,obj,pA).ignore(); title = sid; } else if ( isa == TH3C::Class() ) { createAddress(full,CLID_H3D,idh,obj,pA).ignore(); title = sid; } else if ( isa == TH3S::Class() ) { createAddress(full,CLID_H3D,idh,obj,pA).ignore(); title = sid; } else if ( isa == TH3I::Class() ) { createAddress(full,CLID_H3D,idh,obj,pA).ignore(); title = sid; } else if ( isa == TH3F::Class() ) { createAddress(full,CLID_H3D,idh,obj,pA).ignore(); title = sid; } else if ( isa == TH3D::Class() ) { createAddress(full,CLID_H3D,idh,obj,pA).ignore(); title = sid; } else { log << MSG::ERROR << "Encountered an unknown object with key: " << obj->GetName() << " in ROOT file " << fname << endmsg; return StatusCode::FAILURE; } if ( 0 != pA ) { StatusCode sc = dataManager()->registerAddress(pReg, title, pA); if ( !sc.isSuccess() ) { log << MSG::ERROR << "Failed to register address for " << full << endmsg; return sc; } log << MSG::VERBOSE << "Created address for " << clnm << "'" << title << "' in " << full << endmsg; } } return StatusCode::SUCCESS; }
//______________________________________________________________________________ void alice_esd_split(Bool_t auto_size=kFALSE) { // Main function, initializes the application. // // 1. Load the auto-generated library holding ESD classes and ESD dictionaries. // 2. Open ESD data-files. // 3. Load cartoon geometry. // 4. Spawn simple GUI. // 5. Load first event. TFile::SetCacheFileDir("."); if (!alice_esd_loadlib(esd_file_name, "aliesd")) { Error("alice_esd", "Can not load project libraries."); return; } printf("*** Opening ESD ***\n"); esd_file = TFile::Open(esd_file_name, "CACHEREAD"); if (!esd_file) return; printf("*** Opening ESD-friends ***\n"); esd_friends_file = TFile::Open(esd_friends_file_name, "CACHEREAD"); if (!esd_friends_file) return; esd_tree = (TTree*) esd_file->Get("esdTree"); esd = (AliESDEvent*) esd_tree->GetUserInfo()->FindObject("AliESDEvent"); // Set the branch addresses. { TIter next(esd->fESDObjects); TObject *el; while ((el=(TNamed*)next())) { TString bname(el->GetName()); if(bname.CompareTo("AliESDfriend")==0) { // AliESDfriend needs some '.' magick. esd_tree->SetBranchAddress("ESDfriend.", esd->fESDObjects->GetObjectRef(el)); } else { esd_tree->SetBranchAddress(bname, esd->fESDObjects->GetObjectRef(el)); } } } TEveManager::Create(); // Adapt the main frame to the screen size... if (auto_size) { Int_t qq; UInt_t ww, hh; gVirtualX->GetWindowSize(gVirtualX->GetDefaultRootWindow(), qq, qq, ww, hh); Float_t screen_ratio = (Float_t)ww/(Float_t)hh; if (screen_ratio > 1.5) { gEve->GetBrowser()->MoveResize(100, 50, ww - 300, hh - 100); } else { gEve->GetBrowser()->Move(50, 50); } } { // Simple geometry TFile* geom = TFile::Open(esd_geom_file_name, "CACHEREAD"); if (!geom) return; TEveGeoShapeExtract* gse = (TEveGeoShapeExtract*) geom->Get("Gentle"); gGeoShape = TEveGeoShape::ImportShapeExtract(gse, 0); geom->Close(); delete geom; gEve->AddGlobalElement(gGeoShape); } make_gui(); // import the geometry in the projection managers if (gRPhiMgr) { TEveProjectionAxes* a = new TEveProjectionAxes(gRPhiMgr); a->SetNdivisions(3); gEve->GetScenes()->FindChild("R-Phi Projection")->AddElement(a); gRPhiMgr->ImportElements(gGeoShape); } if (gRhoZMgr) { TEveProjectionAxes* a = new TEveProjectionAxes(gRhoZMgr); a->SetNdivisions(3); gEve->GetScenes()->FindChild("Rho-Z Projection")->AddElement(a); gRhoZMgr->ImportElements(gGeoShape); } load_event(); update_projections(); gEve->Redraw3D(kTRUE); // Reset camera after the first event has been shown. }
void //Impose (TDirectory * target, TList * sourcelist, string & np_title_, vector<string> titles,vector<float> xsecs) Impose (TList * sourcelist, string & np_title_, vector<string> titles,vector<float> xsecs, TString &variable) { cout << " " << "========================================================" << endl; cout << " " << "This is a macro to superimpose plots of different root files." << endl; cout << " " << "Only TH2Dobjects are superimposed." << endl; float Lumi=1; Lumi = 15939.; bool norm_=false; int MaxEventsBin = 10; cout<<titles[0]<<" "<<titles.size()<<endl; //not really useful if plots already weighted to lumi - usefull is plots are in a.u. vector <float > lumiweights; lumiweights.clear(); // for (unsigned int kk=0; kk<signal_names.size();kk++){ // cout<<" HERE is some signal =============================================== "<<signal_names[kk]<<" "<<signalnames[kk]<<endl; // } TH2D* allbkg, *htt,*hstop,*hwj,*hdyj,*hrare,*hdib,*hqcd,*httx, *hrest; TFile *first_source = (TFile *) sourcelist->First (); first_source->cd ("muel"); TH1D* eventCount = (TH1D*)first_source->Get("muel/histWeightsH"); //TH1D* eventCount = (TH1D*)first_source->Get("muel/inputEventsH"); //TH1D* hxsec = (TH1D*)first_source->Get("muel/xsec"); float nGen = eventCount->GetSumOfWeights(); float xsec = 1;//hxsec->GetMean(); float norm = xsec*Lumi/nGen; norm =1; lumiweights.push_back(float(norm)); //cout<< " for first source file, there where "<<nGen<<" events with xsec "<<xsec<<" weight "<<lumiweights[0]<<endl;//" weight "<<float(xsec*Lumi/nGen)<<" norm "<<norm<<endl; TDirectory *current_sourcedir = gDirectory; //gain time, do not add the objects in the list in memory Bool_t status = TH1::AddDirectoryStatus (); TH1::AddDirectory (kFALSE); // loop over all keys in this directory TChain *globChain = 0; TIter nextkey (current_sourcedir->GetListOfKeys ()); //TIter nextkey (((TDirectory *) current_sourcedir->Get ("ana"))->GetListOfKeys ()); TKey *key, *oldkey = 0; while ((key = (TKey *) nextkey ())) { //variable="met_MTsum_16"; int count=0; count++; //if (count>20) break; //keep only the highest cycle number for each key // if (oldkey && !strcmp (oldkey->GetName (), key->GetName ())) // continue; // read object from first source file and create a canvas // first_source->cd (path); first_source->cd ("muel"); TObject *obj = key->ReadObj (); //string nn = obj->GetName(); // if (std::string::npos == nn.find("Cut")) continue; //cout<<obj->GetName()<<endl; string nn = obj->GetName(); bool flcont = true; bool NormTT = false; if (string::npos != nn.find("_9") || string::npos != nn.find("_10") || string::npos != nn.find("_11") || string::npos != nn.find("_12") || string::npos != nn.find("_13") || string::npos != nn.find("_14") || string::npos != nn.find("_15") || string::npos != nn.find("_16") || string::npos != nn.find("_17") || string::npos != nn.find("_18") || string::npos != nn.find("_19")) NormTT = true; //if ( string::npos != nn.find("_11") || string::npos != nn.find("_12") || string::npos != nn.find("_13") || string::npos != nn.find("_14")) NormTT = true; NormTT=true; //if ( string::npos == nn.find("CutFlowUnW")) flcont=false; //if (string::npos == nn.find(""+variable) ) flcont=false; if (string::npos == nn.find(variable) ) continue; // if (!flcont) continue; if (obj->IsA ()->InheritsFrom ("TTree") ) continue; // if (obj->IsA ()->InheritsFrom ("TH1") ) continue; if (obj->IsA ()->InheritsFrom ("TH2") ) { cout<<"=================================================== OK for variable "<<variable<<endl; TH2D* hh[1500]; TH2D* hsignal[1500]; TH2D* h1 = (TH2D*) obj; ModifyHist (h1,1,Lumi,lumiweights[0],titles[0],norm_); TFile *nextsource = (TFile *) sourcelist->After (first_source); int cl, countsignal; h1->SetStats(000000); cl=1; countsignal=1; hh[cl]=h1; THStack *hs = new THStack(h1->GetName(),h1->GetTitle()); string sn="stau"; string sdata="Single"; string sdata2="MuonEG"; string cc1="C1"; while (nextsource) { string fname= nextsource->GetName(); bool flagg= false; if (std::string::npos != fname.find(sn) || std::string::npos != fname.find(cc1) || std::string::npos != fname.find(sdata) ) flagg=true; //if (flagg) cout<<"=============================================================== "<<fname<<endl; // make sure we are at the correct directory level by cd'ing to path nextsource->cd("muel"); TH1D* eventCountt ; if ( std::string::npos == fname.find("TT_TuneCUETP8M1_13TeV-powheg-pythia8") || !NormTT) eventCountt = (TH1D*)nextsource->Get("muel/histWeightsH"); if ( NormTT && std::string::npos != fname.find("TT_TuneCUETP8M1_13TeV-powheg-pythia8") ) eventCountt = (TH1D*)nextsource->Get("muel/histTopPt"); TH1D* hxsecc = (TH1D*)nextsource->Get("muel/xsec"); float xsecc = xsecs[cl]; float nGenn = eventCountt->GetSumOfWeights(); float normm = float(xsecc*Lumi) / float(nGenn) ; if (std::string::npos != fname.find("DataDriven")) normm=1.; lumiweights.push_back(normm); TKey *key2 = (TKey *) gDirectory->GetListOfKeys ()->FindObject (h1->GetName ()); if (key2) { cl++; countsignal++; TH2D *h2; h2 = (TH2D*) key2->ReadObj (); if (h2->GetSumOfWeights()<0.) h2->Scale(0); // for (int nb=1;nb<=h2->GetNbinsX();++nb){ // if (h2->GetBinContent(nb)<0.) h2->SetBinContent(nb,0.); cout<<" setting zeros "<<nb <<" "<<h2->GetBinContent(nb)<<" "<<h2->GetName()<<" "<<h2->GetTitle()<<endl;}} ModifyHist (h2, cl,Lumi,lumiweights[cl-1],titles[cl-1],norm_); h2->SetStats(0); hh[cl] = h2; if (cl==2){ allbkg = (TH2D*) h2->Clone(); allbkg->Reset(); htt = (TH2D*) h2->Clone(); httx = (TH2D*) h2->Clone(); hstop = (TH2D*) h2->Clone(); hwj = (TH2D*) h2->Clone(); hdyj = (TH2D*) h2->Clone(); hrare = (TH2D*) h2->Clone(); hdib = (TH2D*) h2->Clone(); hqcd = (TH2D*) h2->Clone(); hrest = (TH2D*) h2->Clone(); htt->Reset(); httx->Reset(); hstop->Reset(); hdyj->Reset(); hwj->Reset(); hrare->Reset(); hdib->Reset(); hqcd->Reset(); hrest->Reset(); } string hn_ = obj->GetName(); cout<<" "<<fname<<endl; if (std::string::npos != fname.find(sn) || std::string::npos != fname.find(cc1) || std::string::npos != fname.find(sdata) || std::string::npos != fname.find(sdata2) ) flagg=true; string title_ = fname; //cout<<" "<<fname<<endl; int col = 0; if (!flagg) { if (std::string::npos != title_.find("wJets")|| std::string::npos != title_.find("WJetsToLNu") || std::string::npos != title_.find("W1JetsToLNu") || std::string::npos != title_.find("W2JetsToLNu") || std::string::npos != title_.find("W3JetsToLNu") || std::string::npos != title_.find("W4JetsToLNu")) { col=mycolorwjet ; hwj->Add(h2); hwj->SetLineColor(col);} if (std::string::npos != title_.find("TT_TuneCUETP8M1_13TeV-powheg-pythia8") || std::string::npos != title_.find("TTPow")) { col= mycolortt;htt->Add(h2); htt->SetLineColor(col) ;} if (std::string::npos != title_.find("QCD")) {col= mycolorqcd; hqcd->Add(h2); hqcd->SetLineColor(col); cout<<" QCD ======================== "<<hqcd->GetSumOfWeights()<<endl;} if (std::string::npos != title_.find("DYJets") || std::string::npos != title_.find("DY1Jets") || std::string::npos != title_.find("DY2Jets") || std::string::npos != title_.find("DY3Jets") || std::string::npos != title_.find("DY4Jets")) {col= mycolordyj;hdyj->Add(h2); hdyj->SetLineColor(col);} if (std::string::npos != title_.find("ST_") || std::string::npos != title_.find("channel") ) {col= mycolortt; hstop->Add(h2);hstop->SetLineColor(col);} if ( std::string::npos != title_.find("WW") || std::string::npos != title_.find("ZZ") || std::string::npos != title_.find("WZ") || std::string::npos != title_.find("WG") || std::string::npos != title_.find("ZG") ) {col=mycolorvv; hdib->Add(h2); hdib->SetLineColor(col);} if ( std::string::npos != title_.find("TTW") || std::string::npos != title_.find("TTZ") || std::string::npos != title_.find("tZq") || std::string::npos != title_.find("TG") || std::string::npos != title_.find("tG") || std::string::npos != title_.find("TTG") || std::string::npos != title_.find("ttW") || std::string::npos != title_.find("ttZ") || std::string::npos != title_.find("tZ") || std::string::npos != title_.find("TTT_") ) {col=mycolorttx ;httx->Add(h2); httx->SetLineColor(col);} //cout<<" will add histogram "<<h2->GetName()<< " for "<<titles[cl-1]<<" "<<fname<<" cl "<<cl<<endl; hs->Add(h2); allbkg->Add(h2); } } nextsource = (TFile *) sourcelist->After (nextsource); } // while ( nextsource ) } cout<<" Will now extract and save the 1D "<<endl; //const char *s1; TString s1; TH1D * histbkg; string n = obj->GetName(); vector<float> scales; bool b_scale=true; if (std::string::npos != n.find(variable) && obj) { TH2D *hsum = ((TH2D*)(hs->GetStack()->Last())); // the "SUM" scales.push_back(40000.); for (int sc = 0 ; sc<scales.size();sc++){ float scale = float(scales[sc])/float(Lumi); //stringstream ss (stringstream::in | stringstream::out); TString lumistring = "40invfb"; TString smFilename = "Templates_"+variable+"_"+lumistring+"_me_C1N2.root"; TFile *smFile = TFile::Open (smFilename, "recreate"); smFile->cd(); //if (sc==0) smFile->mkdir("mt"); smFile->cd(); allbkg = hsum; allbkg->SetMinimum(0.1); allbkg->SetLineColor(kRed); allbkg->SetMarkerColor(kRed); allbkg->SetFillColor(kRed); allbkg->SetFillStyle(3011); allbkg->SetMinimum(0.1); s1 = "data_obsMC_" + variable; //s1 = "data_obsMC"; allbkg->SetName(s1); cout<<" Total Integral before scaling up - "<<allbkg->GetSumOfWeights()<<" "<<variable<<" data "<<hh[1]->GetSumOfWeights()<<" tt "<< htt->GetSumOfWeights()<<" dy "<<hdyj->GetSumOfWeights()<<" wj "<<hwj->GetSumOfWeights()<<" stop "<<hstop->GetSumOfWeights()<< " vv "<<hdib->GetSumOfWeights()<<" qcd "<<hqcd->GetSumOfWeights()<<endl; if(b_scale) allbkg->Scale(scale); cout<<" Total Integral after scaling up - "<<allbkg->GetSumOfWeights()<<" "<<variable<<endl; allbkg->Write(); if(hqcd->GetSumOfWeights()<0) hqcd->Sumw2(false); histbkg = Unroll(allbkg,s1,1.); s1 = "1D_allbkg_" + variable; //s1 = "1D_data_obsMC";//_" + variable+"_"+lumistring; histbkg->SetName(s1); histbkg->SetMarkerColor(kRed); histbkg->SetLineColor(kRed); histbkg->Write(); if(b_scale){ htt->Scale(scale); hwj->Scale(scale); hdyj->Scale(scale); hstop->Scale(scale); hdib->Scale(scale); hqcd->Scale(scale); httx->Scale(scale); } htt->SetMinimum(0.1); hdyj->SetMinimum(0.1); hwj->SetMinimum(0.1); httx->SetMinimum(0.1); hstop->SetMinimum(0.1); hdib->SetMinimum(0.1); hqcd->SetMinimum(0.1); s1 = "tt_"+variable; htt->SetName(s1); htt->Write(); histbkg = Unroll(htt,s1,1.); s1 = "1D_tt_"+variable; histbkg->SetName(s1); histbkg->Write(); s1 = "wj_"+variable; hwj->SetName(s1); hwj->Write(); histbkg =Unroll(hwj,s1,1.); s1 = "1D_wj_"+variable; histbkg->SetName(s1); histbkg->Write(); s1 = "dyj_"+variable; hdyj->SetName(s1); hdyj->Write(); histbkg =Unroll(hdyj,s1,1.); s1 = "1D_dyj_"+variable; histbkg->SetName(s1); histbkg->Write(); s1 = "sT_"+variable; hstop->SetName(s1); hstop->Write(); histbkg =Unroll(hstop,s1,1.); s1 = "1D_sT_"+variable; histbkg->SetName(s1); histbkg->Write(); s1 = "dib_"+variable; hdib->SetName(s1); hdib->Write(); histbkg =Unroll(hdib,s1,1.); s1 = "1D_dib_"+variable; histbkg->SetName(s1); histbkg->Write(); s1 = "ttx_"+variable; httx->SetName(s1); httx->Write(); histbkg =Unroll(httx,s1,1.); s1 = "1D_ttx_"+variable; histbkg->SetName(s1); histbkg->Write(); s1 = "qcd_"+variable; hqcd->SetName(s1); hqcd->Write(); histbkg =Unroll(hqcd,s1,1.); s1 = "1D_qcd_"+variable; histbkg->SetName(s1); histbkg->Write(); //rest of bkg hold all but ttjets and wjets background s1 = "rest_bkg_"+variable; //hrest->Add(hdyj,1); //hrest->Add(httj,1); //hrest->Add(hwj,1); hrest->Add(hstop,1); hrest->Add(hdib,1); hrest->Add(hqcd,1); hrest->Add(httx,1); hrest->SetName(s1); hrest->Write(); histbkg =Unroll(hrest,s1,1.); s1 = "1D_rest_bkg_"+variable; histbkg->SetName(s1); histbkg->Write(); hh[1]->SetMinimum(0.1); hh[1]->SetLineColor(kBlack); hh[1]->SetFillColor(kBlack); hh[1]->SetMarkerColor(kBlack); s1 = "data_obs_"+variable; hh[1]->SetName(s1); if(b_scale) hh[1]->Scale(scale); hh[1]->Write(); histbkg =Unroll(hh[1],s1,1.); //histbkg =Unroll(allbkg,s1,1.); s1 = "1D_data_obs_"; s1 = "data_obs"; histbkg->SetName(s1); histbkg->Write(); for (unsigned int ij=0;ij<signal_names.size();++ij){ //cout<<" again "<<signal_names[ij]<<endl; //cout<<" again "<<hh[ij+2]->GetName()<<" "<<ij<<" "<<signal_names[ij].c_str()<<endl; TString ss1 = signal_names[ij].c_str(); s1 = "1D_"+ss1 +"_"+variable; if(b_scale) hh[ij+2]->Scale(scale); histbkg = Unroll(hh[ij+2],s1,1.); smFile->cd(); histbkg->SetName(s1); histbkg->SetMarkerColor(kBlue); histbkg->SetLineColor(kBlue); histbkg->Write(); } smFile->SaveSelf (kTRUE); smFile->Close(); delete smFile; }//loop over different predictions }///find variable } //delete c1; // save modifications to target file //target->SaveSelf (kTRUE); TH1::AddDirectory (status); cout << " " << "========================================================" << endl; cout<< " Ended SuperImpose of files.... " <<endl; }
void DrawComparisonXSecSyst(void){ struct STestFunctor { bool operator()(TObject *aObj) { cout<<aObj->GetTitle()<<endl; //cout<<"pippo"<<endl; //comparisonJetMCData(aObj->GetTitle,1); return true; } }; treeBKG_->Branch("bckg_leadingJetPt",&bckg_leadingJetPt); treeBKG_->Branch("bckg_2leadingJetPt",&bckg_2leadingJetPt); treeBKG_->Branch("bckg_3leadingJetPt",&bckg_3leadingJetPt); treeBKG_->Branch("bckg_4leadingJetPt",&bckg_4leadingJetPt); treeBKG_->Branch("bckg_JetMultiplicity",&bckg_JetMultiplicity); gROOT->Reset(); gROOT->ForceStyle(); gROOT->LoadMacro("tdrStyle.C++"); tdrStyle(); // Recupero l'informazione sul numero di eventi processati per singolo MC dataNumEvents = numEventsPerStep(datafile, "demo"); zNumEvents = numEventsPerStep(mcfile, "demo"); ttNumEvents = numEventsPerStep(back_ttbar, "demo"); wNumEvents = numEventsPerStep(back_w, "demo"); wzEvents = numEventsPerStep(WZ, "demo"); zzEvents = numEventsPerStep(ZZ, "demo"); wwEvents = numEventsPerStep(WW, "demo"); // --------------------------------------------------- string direc="/gpfs/cms/data/2011/Observables/"; //string direc=plotpath; if (isAngularAnalysis){ mcfile=direc+"MC_zjets"+version; back_w=direc+"MC_wjets"+version; back_ttbar=direc+"MC_ttbar"+version; WW=direc+"MC_diW"+version; ZZ=direc+"MC_siZ"+version; WZ=direc+"MC_diWZ"+version; datafile=direc+"DATA"+version; } TFile *mcf = TFile::Open(mcfile.c_str()); //MC file mcf->cd("validationJEC/"); TDirectory *dir=gDirectory; TList *mylist=(TList*)dir->GetListOfKeys(); TIter iter(mylist); // Use TIter::Next() to get each TObject mom owns. TObject* tobj = 0; string tmpname; // input and output files string FileName(outfilename); //FileName += ".root"; OutputFile = TFile::Open(FileName.c_str() , "RECREATE" ) ; int i=0; // solo di servizio quando debuggo... while ( (tobj = iter.Next()) ) { gROOT->Reset(); gROOT->ForceStyle(); tdrStyle(); gStyle->SetPadRightMargin(0.15); string name=tobj->GetName(); TString temp = (TString)name; //int num=tobj->GetUniqueID(); if(temp.Contains("weight")){ mcf = TFile::Open(mcfile.c_str()); TFile *ttbarf = TFile::Open(back_ttbar.c_str()); TFile *wf = TFile::Open(back_w.c_str()); TFile *wzf = TFile::Open(WZ.c_str()); TFile *zzf = TFile::Open(ZZ.c_str()); TFile *wwf = TFile::Open(WW.c_str()); TCanvas * Canvweight = new TCanvas("Canvweight","Canvweight",0,0,800,600); //if (Canv) delete Canv; //Canv = new TCanvas("Canv","Canv",0,0,800,600); gPad->SetLogy(1); //---- weights mcf->cd("validationJEC"); TH1F* mc; gDirectory->GetObject(name.c_str(),mc); if(mc){ mc->SetFillColor(kRed); mc->GetXaxis()->SetRangeUser(0.,12.); mc->SetMinimum(1.); mc->Draw(); zwemean = mc->GetMean(); tmpname=plotpath+name+"-zjets.png"; Canvweight->Print(tmpname.c_str()); } //---- weights ttbarf->cd("validationJEC"); TH1F* ttbar; gDirectory->GetObject(name.c_str(),ttbar); if(ttbar){ ttbar->SetFillColor(kBlue); ttbar->GetXaxis()->SetRangeUser(0.,2.); ttbar->Draw(); ttwemean = ttbar->GetMean(); tmpname=plotpath+name+"-ttbar.png"; Canvweight->Print(tmpname.c_str()); } //---- weights wf->cd("validationJEC"); TH1F* w; gDirectory->GetObject(name.c_str(),w); if(w){ w->SetFillColor(kViolet+2); w->GetXaxis()->SetRangeUser(0.,2.); w->Draw(); wwemean = w->GetMean(); tmpname=plotpath+name+"-wjets.png"; Canvweight->Print(tmpname.c_str()); } //---- weights wzf->cd("validationJEC"); TH1F* wz; gDirectory->GetObject(name.c_str(),wz); if(wz){ wz->SetFillColor(kYellow+2); wz->GetXaxis()->SetRangeUser(0.,2.); wz->Draw(); wzwemean = w->GetMean(); tmpname=plotpath+name+"-wzjets.png"; Canvweight->Print(tmpname.c_str()); } //---- weights zzf->cd("validationJEC"); TH1F* zz; gDirectory->GetObject(name.c_str(),zz); if(zz){ zz->SetFillColor(kOrange+2); zz->GetXaxis()->SetRangeUser(0.,2.); zz->Draw(); zzwemean = w->GetMean(); tmpname=plotpath+name+"-zzjets.png"; Canvweight->Print(tmpname.c_str()); } //---- weights wwf->cd("validationJEC"); TH1F* www; gDirectory->GetObject(name.c_str(),www); if(www){ www->SetFillColor(kBlack); www->GetXaxis()->SetRangeUser(0.,2.); www->Draw(); wwwemean = www->GetMean(); tmpname=plotpath+name+"-wwwjets.png"; Canvweight->Print(tmpname.c_str()); } } else comparisonJetMCData(name,1); i++; //if(i==4)break; } // AVVISI AI NAVIGANTI //if(dataNumEvents<0.) cout << "ATTENZIONE: HAI FALLITO LA NORMALIZZAZIONE DEI DATI, quindi ho normalizzato sugli eventi totali del campione\n"; //else cout << "Il numero di eventi (dati) " << dataNumEvents << "\n"; if(zNumEvents<0.) cout << "ATTENZIONE: HAI FALLITO LA NORMALIZZAZIONE DELLO Z+JETS, quindi ho normalizzato sugli eventi totali del campione\n"; else cout << "Il numero di eventi di Z+jets " << zNumEvents << "\n"; if(ttNumEvents<0.) cout << "ATTENZIONE: HAI FALLITO LA NORMALIZZAZIONE DEL TTBAR+JETS, quindi ho normalizzato sugli eventi totali del campione\n"; else cout << "Il numero di eventi di ttbar+jets " << ttNumEvents << "\n"; if(wNumEvents<0.) cout << "ATTENZIONE: HAI FALLITO LA NORMALIZZAZIONE DEL W+JETS, quindi ho normalizzato sugli eventi totali del campione\n"; else cout << "Il numero di eventi di W+jets " << wNumEvents << "\n"; if(wzEvents<0.) cout << "ATTENZIONE: HAI FALLITO LA NORMALIZZAZIONE DEL W+JETS, quindi ho normalizzato sugli eventi totali del campione\n"; else cout << "Il numero di eventi di ZW+jets " << wzEvents << "\n"; if(zzEvents<0.) cout << "ATTENZIONE: HAI FALLITO LA NORMALIZZAZIONE DEL W+JETS, quindi ho normalizzato sugli eventi totali del campione\n"; else cout << "Il numero di eventi di ZZ+jets " << zzEvents << "\n"; if(wwEvents<0.) cout << "ATTENZIONE: HAI FALLITO LA NORMALIZZAZIONE DEL W+JETS, quindi ho normalizzato sugli eventi totali del campione\n"; else cout << "Il numero di eventi di WW+jets " << wwEvents << "\n"; OutputFile->Close(); return; }
void browseStacks( bool makePictures=false, bool wait=true , bool addHistName = false, Double_t maxYScaleF = 1., bool logScale = false, bool setMinZero = true) { gStyle->SetOptTitle(0); bool keep2D=false; //fix the hNJet histos TList *list = gDirectory->GetList(); TIterator *iter = list->MakeIterator(); TObject *obj = 0; while(obj = iter->Next()) { if(TString(obj->GetName()).Contains("hnJet") && obj->InheritsFrom(TH1::Class())) { int nbins = ((TH1F*)obj)->GetNbinsX(); float overflow = ((TH1F*)obj)->GetBinContent(nbins+1); float lastbinval = ((TH1F*)obj)->GetBinContent(nbins); ((TH1F*)obj)->SetBinContent(nbins, overflow+lastbinval); ((TH1F*)obj)->GetXaxis()->SetBinLabel(nbins, "#geq4"); } } // Find out what the names of the existing histograms are // The histogram names are XX_YY_ZZ, where XX is the sample, // eg, "tt", YY is the actual name, ZZ is the final state, eg, "ee" TObjArray* myNames = getMyHistosNames("ttdil","ee",keep2D); // Now loop over histograms, and make stacks TCanvas *c = new TCanvas(); c->Divide(2,2); char* suffix[4]; suffix[0] = "ee"; suffix[1] = "mm"; suffix[2] = "em"; suffix[3] = "all"; if (makePictures) c->Print("out/stacks.ps["); for (int i=0; i<myNames->GetEntries(); i++) { for (int sample=0; sample<4; sample++) { hist::stack(Form("st_%s_%s",myNames->At(i)->GetName(),suffix[sample]), Form("%s_%s$",myNames->At(i)->GetName(), suffix[sample])); THStack* thisStack = (THStack*) gROOT->FindObjectAny( Form("st_%s_%s", myNames->At(i)->GetName(), suffix[sample])); thisStack->SetMaximum(thisStack->GetMaximum()*maxYScaleF); if(TString(myNames->At(i)->GetName()).Contains("hnJet")) { TList* histolist = thisStack->GetHists(); int hatchcount = 0; // for(int j = 0; j<histolist->GetSize();j++) { // if(TString(histolist->At(j)->GetName()).Contains("tt") || // TString(histolist->At(j)->GetName()).Contains("tautau") || // TString(histolist->At(j)->GetName()).Contains("ww") ) continue; // hatch(histolist->At(j)->GetName(), FavoriteHatches[hatchcount]); // hatchcount++; // } } TLegend* thisLeg = hist::legend(thisStack, "lpf", 0, 0, 0.75, 0.65, 0.99, 0.99); c->cd(sample+1); if (logScale) gPad->SetLogy(); else gPad->SetLogy(0); double stackMax = ((TH1*)thisStack->GetHists()->At(0))->GetMaximum(); double stackMin = ((TH1*)thisStack->GetHists()->At(0))->GetMinimum(); thisStack->SetMinimum(stackMin); if (setMinZero) thisStack->SetMinimum(0); if (logScale && stackMin <=0) thisStack->SetMinimum(1e-2*stackMax); if (logScale && stackMax == 0) thisStack->SetMinimum(1e-12); thisStack->Draw("hist"); string xtitle( ((TH1*)gROOT->FindObjectAny(Form("ttdil_%s_%s", myNames->At(i)->GetName(), suffix[sample])))->GetXaxis()->GetTitle()); string ytitle( ((TH1*)gROOT->FindObjectAny(Form("ttdil_%s_%s", myNames->At(i)->GetName(), suffix[sample])))->GetYaxis()->GetTitle()); thisStack->GetXaxis()->SetTitle(xtitle.c_str()); thisStack->GetYaxis()->SetTitle(ytitle.c_str()); TString hname = thisStack->GetName(); if(hname.Contains("hnJet")) { thisStack->GetXaxis()->SetLabelSize(0.075); thisStack->GetYaxis()->SetLabelSize(0.05); thisStack->GetXaxis()->SetTitle("N_{jets}"); } thisLeg->Draw(); TPaveText *pt1 = new TPaveText(0.1, 0.95, 0.4, 0.999, "brNDC"); pt1->SetName("pt1name"); pt1->SetBorderSize(0); pt1->SetFillStyle(0); TText *blah; if (addHistName) blah = pt1->AddText(hname); else blah = pt1->AddText("CMS Preliminary"); blah->SetTextSize(0.05); pt1->Draw(); c->Modified(); c->Update(); } if (makePictures) { c->Print("out/stacks.ps"); // c->Print(Form("out/stacks_%d.png",i+1)); //c->Print(Form("out/stacks_%s.png",myNames->At(i)->GetName())); c->Print(Form("out/stacks_%s.eps",myNames->At(i)->GetName())); } if (wait) { cout << "Enter carriage return for the next set of plots....q to quit" << endl; char in = getchar(); if (in == 'q') break; } } if (makePictures) c->Print("out/stacks.ps]"); }
/* * this script takes 2 TStrings as root filenames as a parameters * basic functionality: * loop through all directories (the mass bins) in the root file * -> create difference plots * -> create global plots * -> create 2D diff vs mass plots * -> etc... */ void plotGlobalWeightedEvts_Kpipi(TString input_filename, TString output_filename) { setupBookies(); gROOT->SetStyle("Plain"); gStyle->SetTitleFont(10*13+2,"xyz"); gStyle->SetTitleSize(0.06, "xyz"); gStyle->SetTitleOffset(1.3,"y"); gStyle->SetTitleOffset(1.3,"z"); gStyle->SetLabelFont(10*13+2,"xyz"); gStyle->SetLabelSize(0.06,"xyz"); gStyle->SetLabelOffset(0.009,"xyz"); gStyle->SetPadBottomMargin(0.16); gStyle->SetPadTopMargin(0.16); gStyle->SetPadLeftMargin(0.16); gStyle->SetPadRightMargin(0.16); gStyle->SetOptTitle(0); gStyle->SetOptStat(0); gROOT->ForceStyle(); gStyle->SetFrameFillColor(0); gStyle->SetFrameFillStyle(0); TGaxis::SetMaxDigits(3); //IsPhDStyle = true; int massbins =0; double mass= 0.0, massstart =1000.0, massend=0.0; std::map<std::string, std::pair<double, std::pair<double, double> > > diffbounds; TFile* infile = TFile::Open(input_filename, "READ"); TFile* outfile = new TFile(output_filename, "RECREATE"); outfile->mkdir("global"); TList *dirlist = infile->GetListOfKeys(); massbins = dirlist->GetSize(); infile->cd(); TIter diriter(dirlist); TDirectory *dir; std::cout<< "scanning directories and creating overview canvases..." <<std::endl; while ((dir = (TDirectory *)diriter())) { std::string dirname = dir->GetName(); // check if directory is mass bin dir unsigned int pointpos = dirname.find("."); if(pointpos == 0 || pointpos == dirname.size()) continue; std::string masslow = dirname.substr(0, pointpos+1); std::string masshigh = dirname.substr(pointpos+1); double massstarttemp = atof(masslow.c_str())/1000; double massendtemp = atof(masshigh.c_str())/1000; if((int)(massendtemp - massstarttemp) != massbinwidth) massbinwidth = (int)(massendtemp - massstarttemp); mass = (massstarttemp + massendtemp)/2; if(massstart > massstarttemp) massstart = massstarttemp; if(massend < massendtemp) massend = massendtemp; outfile->cd(); outfile->mkdir(dir->GetName()); infile->cd(dir->GetName()); // make list of MC Histograms TList mclist; TList *histlist = gDirectory->GetListOfKeys(); TIter histiter(histlist); TObject *obj; while ((obj = histiter())) { TString s(obj->GetName()); if(s.EndsWith("MC")) mclist.Add(obj); else if(s.Contains("MC_")) mclist.Add(obj); } make1DOverviewCanvas(infile, outfile, &mclist, dirname); histiter = TIter(&mclist); TH1D *diffhist, *mchist; while ((mchist = (TH1D*)histiter())) { // generate difference histograms std::string hnamemc(mchist->GetName()); // create new string with MC exchanged for Diff std::string hnamediff(hnamemc); int pos = hnamemc.find("MC"); hnamediff.erase(pos, 2); hnamediff.insert(pos, "Diff"); infile->GetObject((std::string(dir->GetName())+"/"+hnamediff).c_str(), diffhist); if (diffhist) { // get diff min max values std::pair<double, std::pair<double, double> > p; bool change =false; double maxdiff = diffhist->GetMaximum(); double maxdifftemp = diffhist->GetMinimum(); if(abs(maxdifftemp) > maxdiff) maxdiff = maxdifftemp; double diffmintemp = diffhist->GetXaxis()->GetXmin(); double diffmaxtemp = diffhist->GetXaxis()->GetXmax(); std::map<std::string, std::pair<double, std::pair<double, double> > >::iterator iter = diffbounds.find( diffhist->GetName()); if (iter != diffbounds.end()) { p.first = iter->second.first; p.second.first = iter->second.second.first; p.second.second = iter->second.second.second; if (iter->second.first < maxdiff) { change = true; p.first = maxdiff; } if (iter->second.second.first > diffmintemp) { change = true; p.second.first = diffmintemp; } if (iter->second.second.second < diffmaxtemp) { change = true; p.second.second = diffmaxtemp; } if (change) { diffbounds[diffhist->GetName()] = p; } } else { p.first = maxdiff; p.second.first = diffmintemp; p.second.second = diffmaxtemp; diffbounds.insert(std::pair<std::string, std::pair<double, std::pair<double, double> > >(diffhist->GetName(), p)); } } } histiter = TIter(&mclist); TH2D *reldiffhist2d, *diffhist2d, *mchist2d, *datahist2d; while ((mchist2d = (TH2D*) histiter())) { // generate difference histograms std::string hnamemc(mchist2d->GetName()); // create new string with MC exchanged for Diff std::string hnamediff(hnamemc); int pos = hnamemc.find("MC"); hnamediff.erase(pos, 2); hnamediff.insert(pos, "Diff"); // create new string with MC exchanged for RelDiff std::string hnamereldiff(hnamemc); hnamereldiff.erase(pos, 2); hnamereldiff.insert(pos, "RelDiff"); // create new string with MC exchanged for Data std::string hnamedata(hnamemc); hnamedata.erase(pos, 2); hnamedata.insert(pos, "Data"); infile->GetObject((std::string(dir->GetName()) + "/" + hnamereldiff).c_str(), reldiffhist2d); infile->GetObject((std::string(dir->GetName()) + "/" + hnamediff).c_str(), diffhist2d); infile->GetObject((std::string(dir->GetName()) + "/" + hnamedata).c_str(), datahist2d); infile->GetObject((std::string(dir->GetName()) + "/" + hnamemc).c_str(), mchist2d); outfile->cd(dir->GetName()); make2DOverviewCanvas(mchist2d, datahist2d, diffhist2d, reldiffhist2d, mass); } } dirlist = infile->GetListOfKeys(); infile->cd(); diriter = TIter(dirlist); std::cout << "creating global histograms and 2D diff vs mass plots..." << std::endl; while ((dir = (TDirectory *) diriter())) { std::string dirname = dir->GetName(); // check if directory is mass bin dir unsigned int pointpos = dirname.find("."); if (pointpos == 0 || pointpos == dirname.size()) continue; infile->cd(dir->GetName()); // make list of MC Histograms TList mclist; TList *histlist = gDirectory->GetListOfKeys(); TIter histiter(histlist); TObject *obj; while ((obj = histiter())) { TString s(obj->GetName()); if (s.EndsWith("MC")) mclist.Add(obj); else if (s.Contains("MC_")) mclist.Add(obj); } histiter = TIter(&mclist); TH1D *hist; TH1D *diffhist, *mchist, *datahist; while ((hist = (TH1D*) histiter())) { // generate difference histograms std::string hnamemc(hist->GetName()); // create new string with MC exchanged for Diff std::string hname(hnamemc); int pos = hnamemc.find("MC"); hname.erase(pos, 2); hname.insert(pos, "Diff"); // create new string with MC exchanged for Data std::string hnamedata(hnamemc); hnamedata.erase(pos, 2); hnamedata.insert(pos, "Data"); // create new string for MC Global Histogram std::string hnamemcglob(hnamemc); hnamemcglob.insert(pos + 2, "Global"); // create new string for MC Global Histogram std::string hnamedataglob(hnamemc); hnamedataglob.erase(pos, 2); hnamedataglob.insert(pos, "DataGlobal"); infile->GetObject((std::string(dir->GetName()) + "/" + hname + ";1").c_str(), diffhist); infile->GetObject((std::string(dir->GetName()) + "/" + hnamedata + ";1").c_str(), datahist); infile->GetObject((std::string(dir->GetName()) + "/" + hnamemc + ";1").c_str(), mchist); if (datahist) { // make global histograms in global folder outfile->cd("global"); TH1D* hmcglob = (TH1D*) outfile->Get(std::string("global/"+hnamemcglob).c_str()); if (hmcglob == NULL) hmcglob = new TH1D(hnamemcglob.c_str(), mchist->GetTitle(), mchist->GetNbinsX(), mchist->GetXaxis()->GetXmin(), mchist->GetXaxis()->GetXmax()); hmcglob->Add(mchist); TH1D* hdataglob = (TH1D*) outfile->Get(std::string("global/"+hnamedataglob).c_str()); if (hdataglob == NULL) hdataglob = new TH1D(hnamedataglob.c_str(), datahist->GetTitle(), datahist->GetNbinsX(), datahist->GetXaxis()->GetXmin(), datahist->GetXaxis()->GetXmax()); hdataglob->Add(datahist); // make diff vs. mass plots fillDiffvsMassPlot(diffhist, dir->GetName(), massbins, massstart, massend, diffbounds, outfile); } } histiter = TIter(&mclist); TH2D *mchist2d, *datahist2d; while ((mchist2d = (TH2D*) histiter())) { // generate difference histograms std::string hnamemc(mchist2d->GetName()); // create new string with MC exchanged for Diff std::string hnamediff(hnamemc); int pos = hnamemc.find("MC"); hnamediff.erase(pos, 2); hnamediff.insert(pos, "Diff"); // create new string with MC exchanged for Data std::string hnamedata(hnamemc); hnamedata.erase(pos, 2); hnamedata.insert(pos, "Data"); // create new string for MC Global Histogram std::string hnamemcglob(hnamemc); hnamemcglob.insert(pos + 2, "Global"); // create new string for MC Global Histogram std::string hnamedataglob(hnamemc); hnamedataglob.erase(pos, 2); hnamedataglob.insert(pos, "DataGlobal"); infile->GetObject((std::string(dir->GetName()) + "/" + hnamedata + ";1").c_str(), datahist2d); infile->GetObject((std::string(dir->GetName()) + "/" + hnamemc + ";1").c_str(), mchist2d); if (datahist2d) { // make global histograms in global folder outfile->cd("global"); TH2D* hmcglob = (TH2D*) outfile->Get(std::string("global/" + hnamemcglob).c_str()); if (hmcglob == NULL) { hmcglob = new TH2D(hnamemcglob.c_str(), mchist2d->GetTitle(), mchist->GetNbinsX(), mchist2d->GetXaxis()->GetXmin(), mchist2d->GetXaxis()->GetXmax(), mchist2d->GetNbinsY(), mchist2d->GetYaxis()->GetXmin(), mchist2d->GetYaxis()->GetXmax()); hmcglob->SetXTitle(mchist2d->GetXaxis()->GetTitle()); hmcglob->SetYTitle(mchist2d->GetYaxis()->GetTitle()); } hmcglob->Add(mchist2d); TH2D* hdataglob = (TH2D*) outfile->Get(std::string("global/" + hnamedataglob).c_str()); if (hdataglob == NULL) { hdataglob = new TH2D(hnamedataglob.c_str(), datahist2d->GetTitle(), datahist2d->GetNbinsX(), datahist2d->GetXaxis()->GetXmin(), datahist2d->GetXaxis()->GetXmax(), datahist2d->GetNbinsY(), datahist2d->GetYaxis()->GetXmin(), datahist2d->GetYaxis()->GetXmax()); hdataglob->SetXTitle(datahist2d->GetXaxis()->GetTitle()); hdataglob->SetYTitle(datahist2d->GetYaxis()->GetTitle()); } hdataglob->Add(datahist2d); } } } makeBookies(); std::cout<< "saving to disk..." <<std::endl; outfile->Write(); std::cout<< "done!" <<std::endl; /*// ok lets make a canvas and plug some plots into it -> add to booky TCanvas* c = new TCanvas("KineValidate" + massbin, "Weighted Events", 10, 10, 600, 800); c->Divide(4, 4); // first column contains neutral isobar histograms c->cd(1); double totMC = GJHB_neutral_isobar.isobar_mass[0]->Integral(); double totDATA = GJHB_neutral_isobar.isobar_mass[1]->Integral(); if (totMC != 0) GJHB_neutral_isobar.isobar_mass[0]->Scale(totDATA / totMC); GJHB_neutral_isobar.isobar_mass[0]->SetLineColor(kRed); GJHB_neutral_isobar.isobar_mass[0]->SetFillColor(kRed); GJHB_neutral_isobar.isobar_mass[0]->Draw("E4"); TH1D* hDiffMIsobar = new TH1D(*GJHB_neutral_isobar.isobar_mass[0]); hDiffMIsobar->Add(GJHB_neutral_isobar.isobar_mass[1], -1.); GJHB_neutral_isobar.isobar_mass[1]->Draw("same"); hDiffMIsobar->SetLineColor(kOrange - 3); hDiffMIsobar->Draw("same"); GJHB_neutral_isobar.isobar_mass[0]->GetYaxis()->SetRangeUser(hDiffMIsobar->GetMinimum() * 1.5, GJHB_neutral_isobar.isobar_mass[0]->GetMaximum() * 1.2); gPad->Update(); c->cd(5); totMC = GJHB_neutral_isobar.costheta_GJF[0]->Integral(); totDATA = GJHB_neutral_isobar.costheta_GJF[1]->Integral(); if (totMC != 0) GJHB_neutral_isobar.costheta_GJF[0]->Scale(totDATA / totMC); GJHB_neutral_isobar.costheta_GJF[0]->SetLineColor(kRed); GJHB_neutral_isobar.costheta_GJF[0]->SetFillColor(kRed); GJHB_neutral_isobar.costheta_GJF[0]->Draw("E4"); GJHB_neutral_isobar.costheta_GJF[1]->Draw("same E"); totMC = GJHB_neutral_isobar.costheta_GJF_MC_raw->Integral(); GJHB_neutral_isobar.costheta_GJF_MC_raw->Scale(totDATA / totMC); GJHB_neutral_isobar.costheta_GJF_MC_raw->Draw("same"); GJHB_neutral_isobar.costheta_GJF[0]->GetYaxis()->SetRangeUser(0, GJHB_neutral_isobar.costheta_GJF[0]->GetMaximum() * 1.5); gPad->Update(); c->cd(9); totMC = GJHB_neutral_isobar.phi_GJF[0]->Integral(); totDATA = GJHB_neutral_isobar.phi_GJF[1]->Integral(); GJHB_neutral_isobar.phi_GJF[0]->Sumw2(); if (totMC != 0) GJHB_neutral_isobar.phi_GJF[0]->Scale(totDATA / totMC); GJHB_neutral_isobar.phi_GJF[0]->SetLineColor(kRed); GJHB_neutral_isobar.phi_GJF[0]->SetFillColor(kRed); GJHB_neutral_isobar.phi_GJF[0]->Draw("E4"); GJHB_neutral_isobar.phi_GJF[1]->Draw("same E"); GJHB_neutral_isobar.phi_GJF[0]->GetYaxis()->SetRangeUser(0, GJHB_neutral_isobar.phi_GJF[0]->GetMaximum() * 1.5); gPad->Update(); c->cd(13); totMC = HHB_neutral_isobar.costheta_HF[0]->Integral(); totDATA = HHB_neutral_isobar.costheta_HF[1]->Integral(); HHB_neutral_isobar.costheta_HF[0]->Sumw2(); if (totMC != 0) HHB_neutral_isobar.costheta_HF[0]->Scale(totDATA / totMC); HHB_neutral_isobar.costheta_HF[0]->SetLineColor(kRed); HHB_neutral_isobar.costheta_HF[0]->SetFillColor(kRed); HHB_neutral_isobar.costheta_HF[0]->Draw("E4"); HHB_neutral_isobar.costheta_HF[1]->Draw("same E"); HHB_neutral_isobar.costheta_HF[0]->GetYaxis()->SetRangeUser(0, HHB_neutral_isobar.costheta_HF[0]->GetMaximum() * 1.5); gPad->Update(); c->cd(15); totMC = HHB_neutral_isobar.phi_HF[0]->Integral(); totDATA = HHB_neutral_isobar.phi_HF[1]->Integral(); HHB_neutral_isobar.phi_HF[0]->Sumw2(); if (totMC != 0) HHB_neutral_isobar.phi_HF[0]->Scale(totDATA / totMC); HHB_neutral_isobar.phi_HF[0]->SetLineColor(kRed); HHB_neutral_isobar.phi_HF[0]->SetFillColor(kRed); HHB_neutral_isobar.phi_HF[0]->Draw("E4"); HHB_neutral_isobar.phi_HF[1]->Draw("same E"); HHB_neutral_isobar.phi_HF[0]->GetYaxis()->SetRangeUser(0, HHB_neutral_isobar.phi_HF[0]->GetMaximum() * 1.5); gPad->Update(); c->cd(2); totMC = GJHB_charged_isobar.isobar_mass[0]->Integral(); totDATA = GJHB_charged_isobar.isobar_mass[1]->Integral(); if (totMC != 0) GJHB_charged_isobar.isobar_mass[0]->Scale(totDATA / totMC); GJHB_charged_isobar.isobar_mass[0]->SetLineColor(kRed); GJHB_charged_isobar.isobar_mass[0]->SetFillColor(kRed); GJHB_charged_isobar.isobar_mass[0]->Draw("E4"); TH1D* hDiffMIsobar2 = new TH1D(*GJHB_charged_isobar.isobar_mass[0]); hDiffMIsobar2->Add(GJHB_charged_isobar.isobar_mass[1], -1.); GJHB_charged_isobar.isobar_mass[1]->Draw("same"); hDiffMIsobar2->SetLineColor(kOrange - 3); hDiffMIsobar2->Draw("same"); GJHB_charged_isobar.isobar_mass[0]->GetYaxis()->SetRangeUser(hDiffMIsobar->GetMinimum() * 1.5, GJHB_charged_isobar.isobar_mass[0]->GetMaximum() * 1.2); gPad->Update(); c->cd(6); totMC = GJHB_charged_isobar.costheta_GJF[0]->Integral(); totDATA = GJHB_charged_isobar.costheta_GJF[1]->Integral(); //hGJ[0]->Sumw2(); if (totMC != 0) GJHB_charged_isobar.costheta_GJF[0]->Scale(totDATA / totMC); GJHB_charged_isobar.costheta_GJF[0]->SetLineColor(kRed); GJHB_charged_isobar.costheta_GJF[0]->SetFillColor(kRed); GJHB_charged_isobar.costheta_GJF[0]->Draw("E4"); GJHB_charged_isobar.costheta_GJF[1]->Draw("same E"); totMC = GJHB_charged_isobar.costheta_GJF_MC_raw->Integral(); GJHB_charged_isobar.costheta_GJF_MC_raw->Scale(totDATA / totMC); GJHB_charged_isobar.costheta_GJF_MC_raw->Draw("same"); GJHB_charged_isobar.costheta_GJF[0]->GetYaxis()->SetRangeUser(0, GJHB_charged_isobar.costheta_GJF[0]->GetMaximum() * 1.5); gPad->Update(); c->cd(10); totMC = GJHB_charged_isobar.phi_GJF[0]->Integral(); totDATA = GJHB_charged_isobar.phi_GJF[1]->Integral(); GJHB_charged_isobar.phi_GJF[0]->Sumw2(); if (totMC != 0) GJHB_charged_isobar.phi_GJF[0]->Scale(totDATA / totMC); GJHB_charged_isobar.phi_GJF[0]->SetLineColor(kRed); GJHB_charged_isobar.phi_GJF[0]->SetFillColor(kRed); GJHB_charged_isobar.phi_GJF[0]->Draw("E4"); GJHB_charged_isobar.phi_GJF[1]->Draw("same E"); GJHB_charged_isobar.phi_GJF[0]->GetYaxis()->SetRangeUser(0, GJHB_charged_isobar.phi_GJF[0]->GetMaximum() * 1.5); gPad->Update(); c->cd(14); totMC = HHB_charged_isobar.costheta_HF[0]->Integral(); totDATA = HHB_charged_isobar.costheta_HF[1]->Integral(); HHB_charged_isobar.costheta_HF[0]->Sumw2(); if (totMC != 0) HHB_charged_isobar.costheta_HF[0]->Scale(totDATA / totMC); HHB_charged_isobar.costheta_HF[0]->SetLineColor(kRed); HHB_charged_isobar.costheta_HF[0]->SetFillColor(kRed); HHB_charged_isobar.costheta_HF[0]->Draw("E4"); HHB_charged_isobar.costheta_HF[1]->Draw("same E"); HHB_charged_isobar.costheta_HF[0]->GetYaxis()->SetRangeUser(0, HHB_charged_isobar.costheta_HF[0]->GetMaximum() * 1.5); gPad->Update(); c->cd(16); totMC = HHB_charged_isobar.phi_HF[0]->Integral(); totDATA = HHB_charged_isobar.phi_HF[1]->Integral(); HHB_charged_isobar.phi_HF[0]->Sumw2(); if (totMC != 0) HHB_charged_isobar.phi_HF[0]->Scale(totDATA / totMC); HHB_charged_isobar.phi_HF[0]->SetLineColor(kRed); HHB_charged_isobar.phi_HF[0]->SetFillColor(kRed); HHB_charged_isobar.phi_HF[0]->Draw("E4"); HHB_charged_isobar.phi_HF[1]->Draw("same E"); HHB_charged_isobar.phi_HF[0]->GetYaxis()->SetRangeUser(0, HHB_charged_isobar.phi_HF[0]->GetMaximum() * 1.5); gPad->Update(); // add global diagrams c->cd(1); TLatex* Label = new TLatex(); Label->PaintLatex(2, GJHB_neutral_isobar.isobar_mass[0]->GetMaximum() * 0.8, 0, 0.1, massbin.Data()); c->Update(); TList* Hlist = gDirectory->GetList(); Hlist->Remove(mctr); Hlist->Remove(datatr); //Hlist->Remove("hWeights"); TFile* outfile = TFile::Open(outfilename, "UPDATE"); TString psFileName = outfilename; psFileName.ReplaceAll(".root", massbin); psFileName.Append(".ps"); if (totMC != 0) { // get mass-integrated plots (or create them if not there) // neutral isobar TH1D* hMIsobarMCGlob = (TH1D*) outfile->Get("hMIsobarMCGlob"); if (hMIsobarMCGlob == NULL) hMIsobarMCGlob = new TH1D("hMIsobarMCGlob", "2#pi neutral Isobar Mass (MC)", nbninsm, 0.2, 2.5); hMIsobarMCGlob->Add(GJHB_neutral_isobar.isobar_mass[0]); hMIsobarMCGlob->Write(); TH1D* hMIsobarDataGlob = (TH1D*) outfile->Get("hMIsobarDataGlob"); if (hMIsobarDataGlob == NULL) hMIsobarDataGlob = new TH1D("hMIsobarDataGlob", "2#pi neutral Isobar Mass (DATA)", nbninsm, 0.2, 2.5); hMIsobarDataGlob->Add(GJHB_neutral_isobar.isobar_mass[1]); hMIsobarDataGlob->Write(); TH1D* hGJMCGlob = (TH1D*) outfile->Get("hGJMCGlob"); if (hGJMCGlob == NULL) hGJMCGlob = new TH1D("hGJMCGlob", "Gottfried-Jackson Theta (MC)", nbinsang, -1, 1); hGJMCGlob->Add(GJHB_neutral_isobar.costheta_GJF[0]); hGJMCGlob->Write(); TH1D* hGJDataGlob = (TH1D*) outfile->Get("hGJDataGlob"); if (hGJDataGlob == NULL) hGJDataGlob = new TH1D("hGJDataGlob", "Gottfried-Jackson Theta (Data)", nbinsang, -1, 1); hGJDataGlob->Add(GJHB_neutral_isobar.costheta_GJF[1]); hGJDataGlob->Write(); TH1D* hTYMCGlob = (TH1D*) outfile->Get("hTYMCGlob"); if (hTYMCGlob == NULL) hTYMCGlob = new TH1D("hTYMCGlob", "Treiman-Yang Phi (MC)", nbinsang, -TMath::Pi(),TMath::Pi()); hTYMCGlob->Add(GJHB_neutral_isobar.phi_GJF[0]); hTYMCGlob->Write(); TH1D* hTYDataGlob = (TH1D*) outfile->Get("hTYDataGlob"); if (hTYDataGlob == NULL) hTYDataGlob = new TH1D("hTYDataGlob", "Treiman-Yang Phi (Data)", nbinsang, -TMath::Pi(),TMath::Pi()); hTYDataGlob->Add(GJHB_neutral_isobar.phi_GJF[1]); hTYDataGlob->Write(); c->cd(3); hMIsobarMCGlob->SetLineColor(kRed); hMIsobarMCGlob->SetFillColor(kRed); hMIsobarMCGlob->Draw("E4"); hMIsobarDataGlob->Draw("E SAME"); c->cd(7); hGJMCGlob->SetLineColor(kRed); hGJMCGlob->SetFillColor(kRed); hGJMCGlob->Draw("E4"); hGJDataGlob->Draw("E SAME"); c->cd(11); hTYMCGlob->SetLineColor(kRed); hTYMCGlob->SetFillColor(kRed); hTYMCGlob->Draw("E4"); hTYDataGlob->Draw("E SAME"); // charged isobar TH1D* hMIsobarMCGlob2 = (TH1D*) outfile->Get("hMIsobarMCGlob2"); if (hMIsobarMCGlob2 == NULL) hMIsobarMCGlob2 = new TH1D("hMIsobarMCGlob2", "2#pi charged Isobar Mass (MC)", nbninsm, 0.2, 2.5); hMIsobarMCGlob2->Add(GJHB_charged_isobar.isobar_mass[0]); hMIsobarMCGlob2->Write(); TH1D* hMIsobarDataGlob2 = (TH1D*) outfile->Get("hMIsobarDataGlob2"); if (hMIsobarDataGlob2 == NULL) hMIsobarDataGlob2 = new TH1D("hMIsobarDataGlob2", "2#pi charged Isobar mass (DATA)", nbninsm, 0.2, 2.5); hMIsobarDataGlob2->Add(GJHB_charged_isobar.isobar_mass[1]); hMIsobarDataGlob2->Write(); TH1D* hGJMCGlob2 = (TH1D*) outfile->Get("hGJMCGlob2"); if (hGJMCGlob2 == NULL) hGJMCGlob2 = new TH1D("hGJMCGlob2", "Gottfried-Jackson Theta (MC)", nbinsang, -1, 1); hGJMCGlob2->Add(GJHB_charged_isobar.costheta_GJF[0]); hGJMCGlob2->Write(); TH1D* hGJDataGlob2 = (TH1D*) outfile->Get("hGJDataGlob2"); if (hGJDataGlob2 == NULL) hGJDataGlob2 = new TH1D("hGJDataGlob2", "Gottfried-Jackson Theta (Data)", nbinsang, -1, 1); hGJDataGlob2->Add(GJHB_charged_isobar.costheta_GJF[1]); hGJDataGlob2->Write(); TH1D* hTYMCGlob2 = (TH1D*) outfile->Get("hTYMCGlob2"); if (hTYMCGlob2 == NULL) hTYMCGlob2 = new TH1D("hTYMCGlob2", "Treiman-Yang Phi (MC)", nbinsang, -TMath::Pi(),TMath::Pi()); hTYMCGlob2->Add(GJHB_charged_isobar.phi_GJF[0]); hTYMCGlob2->Write(); TH1D* hTYDataGlob2 = (TH1D*) outfile->Get("hTYDataGlob2"); if (hTYDataGlob2 == NULL) hTYDataGlob2 = new TH1D("hTYDataGlob2", "Treiman-Yang Phi (Data)", nbinsang, -TMath::Pi(),TMath::Pi()); hTYDataGlob2->Add(GJHB_charged_isobar.phi_GJF[1]); hTYDataGlob2->Write(); c->cd(4); hMIsobarMCGlob2->SetLineColor(kRed); hMIsobarMCGlob2->SetFillColor(kRed); hMIsobarMCGlob2->Draw("E4"); hMIsobarDataGlob2->Draw("E SAME"); c->cd(8); hGJMCGlob2->SetLineColor(kRed); hGJMCGlob2->SetFillColor(kRed); hGJMCGlob2->Draw("E4"); hGJDataGlob2->Draw("E SAME"); c->cd(12); hTYMCGlob2->SetLineColor(kRed); hTYMCGlob2->SetFillColor(kRed); hTYMCGlob2->Draw("E4"); hTYDataGlob2->Draw("E SAME"); } c->Write(); TCanvas dummyCanv("dummy", "dummy"); c->Print((psFileName));*/ }
//______________________________________________________________________________ void alice_esd() { // Main function, initializes the application. // // 1. Load the auto-generated library holding ESD classes and // ESD dictionaries. // 2. Open ESD data-files. // 3. Load cartoon geometry. // 4. Spawn simple GUI. // 5. Load first event. const TString weh("alice_esd()"); if (gROOT->LoadMacro("MultiView.C+") != 0) { Error(weh, "Failed loading MultiView.C in compiled mode."); return; } TFile::SetCacheFileDir("."); if (!alice_esd_loadlib("aliesd")) { Error("alice_esd", "Can not load project libraries."); return; } printf("*** Opening ESD ***\n"); esd_file = TFile::Open(esd_file_name, "CACHEREAD"); if (!esd_file) return; esd_tree = (TTree*) esd_file->Get("esdTree"); esd = (AliESDEvent*) esd_tree->GetUserInfo()->FindObject("AliESDEvent"); esd_objs = esd->fESDObjects; if (esd_friends_file_name != 0) { printf("*** Opening ESD-friends ***\n"); esd_friends_file = TFile::Open(esd_friends_file_name, "CACHEREAD"); if (!esd_friends_file) return; esd_tree->SetBranchStatus ("ESDfriend*", 1); } // Set the branch addresses. { TIter next(esd_objs); TObject *el; while ((el = (TNamed*)next())) { TString bname(el->GetName()); if (bname == "AliESDfriend") { // AliESDfriend needs special treatment. TBranch *br = esd_tree->GetBranch("ESDfriend."); br->SetAddress(esd_objs->GetObjectRef(el)); } else { TBranch *br = esd_tree->GetBranch(bname); if (br) { br->SetAddress(esd_objs->GetObjectRef(el)); } else { br = esd_tree->GetBranch(bname + "."); if (br) { br->SetAddress(esd_objs->GetObjectRef(el)); } else { Warning("AliESDEvent::ReadFromTree() " "No Branch found with Name '%s' or '%s.'.", bname.Data(),bname.Data()); } } } } } TEveManager::Create(); { // Simple geometry TFile* geom = TFile::Open(esd_geom_file_name, "CACHEREAD"); if (!geom) return; TEveGeoShapeExtract* gse = (TEveGeoShapeExtract*) geom->Get("Gentle"); gGeomGentle = TEveGeoShape::ImportShapeExtract(gse, 0); geom->Close(); delete geom; gEve->AddGlobalElement(gGeomGentle); } // Standard multi-view //===================== gMultiView = new MultiView; gMultiView->ImportGeomRPhi(gGeomGentle); gMultiView->ImportGeomRhoZ(gGeomGentle); // HTML summary view //=================== gROOT->LoadMacro("alice_esd_html_summary.C"); fgHtmlSummary = new HtmlSummary("Alice Event Display Summary Table"); slot = TEveWindow::CreateWindowInTab(gEve->GetBrowser()->GetTabRight()); fgHtml = new TGHtml(0, 100, 100); TEveWindowFrame *wf = slot->MakeFrame(fgHtml); fgHtml->MapSubwindows(); wf->SetElementName("Summary"); // Final stuff //============= gEve->GetBrowser()->GetTabRight()->SetTab(1); make_gui(); load_event(); gEve->Redraw3D(kTRUE); // Reset camera after the first event has been shown. }
void MergeRootfile( TDirectory *target, const vector<pair<TFile*, float> >& vFileList) { // cout << "Target path: " << target->GetPath() << endl; TString path( (char*)strstr( target->GetPath(), ":" ) ); path.Remove( 0, 2 ); vec_pair_it it = vFileList.begin(); TFile *first_source = (*it).first; const float first_weight = (*it).second; first_source->cd( path ); TDirectory *current_sourcedir = gDirectory; //gain time, do not add the objects in the list in memory Bool_t status = TH1::AddDirectoryStatus(); TH1::AddDirectory(kFALSE); // loop over all keys in this directory TChain *globChain = 0; TIter nextkey( current_sourcedir->GetListOfKeys() ); TKey *key, *oldkey=0; while ( (key = (TKey*)nextkey())) { //keep only the highest cycle number for each key if (oldkey && !strcmp(oldkey->GetName(),key->GetName())) continue; // read object from first source file first_source->cd( path ); TObject *obj = key->ReadObj(); if ( obj->IsA()->InheritsFrom( TH1::Class() ) ) { // descendant of TH1 -> merge it // cout << "Merging histogram " << obj->GetName() << endl; TH1 *h1 = (TH1*)obj; if (first_weight>0) { h1->Scale(first_weight); } // loop over all source files and add the content of the // correspondant histogram to the one pointed to by "h1" for (vec_pair_it nextsrc = vFileList.begin()+1; nextsrc != vFileList.end(); ++nextsrc ) { // make sure we are at the correct directory level by cd'ing to path (*nextsrc).first->cd( path ); const float next_weight = (*nextsrc).second; TKey *key2 = (TKey*)gDirectory->GetListOfKeys()->FindObject(h1->GetName()); if (key2) { TH1 *h2 = (TH1*)key2->ReadObj(); if (next_weight>0) h2->Scale(next_weight); h1->Add( h2 ); delete h2; } } } else if ( obj->IsA()->InheritsFrom( TTree::Class() ) ) { // loop over all source files create a chain of Trees "globChain" const char* obj_name= obj->GetName(); globChain = new TChain(obj_name); globChain->Add(first_source->GetName()); for (vec_pair_it nextsrc = vFileList.begin()+1; nextsrc != vFileList.end(); ++nextsrc ) { globChain->Add(nextsrc->first->GetName()); } } else if ( obj->IsA()->InheritsFrom( TDirectory::Class() ) ) { // it's a subdirectory cout << "Found subdirectory " << obj->GetName() << endl; // create a new subdir of same name and title in the target file target->cd(); TDirectory *newdir = target->mkdir( obj->GetName(), obj->GetTitle() ); // newdir is now the starting point of another round of merging // newdir still knows its depth within the target file via // GetPath(), so we can still figure out where we are in the recursion MergeRootfile( newdir, vFileList); } else { // object is of no type that we know or can handle cout << "Unknown object type, name: " << obj->GetName() << " title: " << obj->GetTitle() << endl; } // now write the merged histogram (which is "in" obj) to the target file // note that this will just store obj in the current directory level, // which is not persistent until the complete directory itself is stored // by "target->Write()" below if ( obj ) { target->cd(); //!!if the object is a tree, it is stored in globChain... if(obj->IsA()->InheritsFrom( TTree::Class() )) globChain->Merge(target->GetFile(),0,"keep"); else obj->Write( key->GetName() ); } } // while ( ( TKey *key = (TKey*)nextkey() ) ) // save modifications to target file target->SaveSelf(kTRUE); TH1::AddDirectory(status); }
void bfcread_histBranch( Int_t nevents=1, const char *MainFile= "/afs/rhic.bnl.gov/star/data/samples/gstar.dst.root", const char *fname="qa_hist.out") { // cout << " events to process = " << nevents << endl; cout << " Input File Name = " << MainFile << endl; cout << " Output file containing printouts = " << fname << endl; ofstream fout(fname); fout << " Running: bfcread_histBranch.C " << endl; fout << " events to process = " << nevents << endl; fout << " Input File Name = " << MainFile << endl; fout << " Output file containing printouts = " << fname << endl; fout << endl << endl; gSystem->Load("St_base"); gSystem->Load("StChain"); gSystem->Load("StIOMaker"); gSystem->Load("libglobal_Tables"); // Setup top part of chain chain = new StChain("bfc"); chain->SetDebug(); StIOMaker *IOMk = new StIOMaker("IO","r",MainFile,"bfcTree"); IOMk->SetDebug(); IOMk->SetIOMode("r"); IOMk->SetBranch("*",0,"0"); //deactivate all branches IOMk->SetBranch("histBranch",0,"r"); //activate hist Branch // --- now execute chain member functions chain->Init(); TDataSet *ds=0; TDataSet *obj=0; int istat=0; int i=0; int countev=0; int countevhds=0; // Event loop EventLoop: if (i < nevents && !istat) { chain->Clear(); istat = chain->Make(i); // count # times Make is called i++; // Now look at the data in the event: int countObj=0; int countHist=0; if (!istat) { countev++; cout << " start event # " << countev << endl; ds=chain->GetDataSet("hist"); TDataSetIter tabiter(ds); if (ds) { countevhds++; TDataSetIter nextHistList(ds); St_ObjectSet *histContainer = 0; TList *dirList = 0; // loop over directories: while (histContainer = (St_ObjectSet *)nextHistList()) { dirList = (TList *) histContainer->GetObject(); cout << " QAInfo: found directory: " << histContainer->GetName() << endl; fout << " QAInfo: found directory: " << histContainer->GetName() << endl; countObj++; // Notes for future reference (if we want to generalize this...) // dirList is returned 0 for non-histogram file // in that case, use GetList instead of GetObject TIter nextHist(dirList); TObject *o = 0; // loop over histograms in the directory: while (o= nextHist()) { countHist++; cout << " QAInfo: Hist name: " << o->GetName() << " ==> Title: " << o->GetTitle() << endl; fout << " QAInfo: Hist name: " << o->GetName() << " ==> Title: " << o->GetTitle() << endl; } // nextHist } // histContainer } // ds cout << " QAInfo: event # " << countev << ", # directories found = " << countObj << ", # hist found = " << countHist << endl << endl; fout << " QAInfo: event # " << countev << ", # directories found = " << countObj << ", # hist found = " << countHist << endl << endl; } // istat else // if (istat) { cout << "Last event processed. Status = " << istat << endl; } goto EventLoop; } //EventLoop cout << endl; cout << "QAInfo: End of Job " << endl; cout << "QAInfo: # times Make called = " << i << endl; cout << "QAInfo: # events read = " << countev << endl; cout << "QAInfo: # events with hist dataset = " << countevhds << endl; fout << endl; fout << "QAInfo: End of Job " << endl; fout << "QAInfo: # times Make called = " << i << endl; fout << "QAInfo: # events read = " << countev << endl; fout << "QAInfo: # events with hist dataset = " << countevhds << endl; chain->Finish(); }
void generatePlots(Files *inputs, const string &path) { Files::const_iterator first_source = inputs->begin(); TDirectory *folder = dynamic_cast<TDirectory *>(first_source->second->Get(path.c_str())); if (!folder) { cerr << "Failed to extract folder: " << path << endl; return; } // //gain time, do not add the objects in the list in memory // Bool_t status = TH1::AddDirectoryStatus(); TH1::AddDirectory(kFALSE); // loop over all keys in this directory TIter nextkey(folder->GetListOfKeys() ); for(TKey *key, *oldkey=0; key = (TKey*) nextkey(); ) { //keep only the highest cycle number for each key if (oldkey && !strcmp(oldkey->GetName(), key->GetName())) continue; // read object from first source file // TObject *obj = key->ReadObj(); if ( obj->IsA()->InheritsFrom(TH1::Class())) { cout << obj->GetName() << endl; TCanvas *canvas = new TCanvas(); canvas->SetWindowSize(640, 480); THStack *stack = new THStack(); TLegend *legend = new TLegend(.6, .98, .98, .58); legend->SetBorderSize(1); legend->SetLineStyle(1); legend->SetTextFont(43); legend->SetTextSizePixels(12); legend->SetFillColor(0); TH1 *h1 = dynamic_cast<TH1*>(obj); legend->AddEntry(h1, style(h1, first_source->first).c_str(), "pl"); h1->Scale(1.0 / h1->Integral()); stack->Add(h1); // loop over all source files and add the content of the // correspondant histogram to the one pointed to by "h1" for(Files::const_iterator input = ++inputs->begin(); inputs->end() != input; ++input) { TH1 *h2 = dynamic_cast<TH1*>(input->second->Get((path + "/" + obj->GetName()).c_str())); if (!h2) { cerr << "Failed to extract plot from input: " << endl; continue; } h2->Scale(1. / h2->Integral()); legend->AddEntry(h2, style(h2, input->first).c_str(), "pl"); stack->Add(h2); } stack->Draw("h nostack"); legend->Draw(); stack->GetXaxis()->SetTitle(h1->GetXaxis()->GetTitle()); canvas->Update(); } else { // object is of no type that we know or can handle // cout << "Unknown object type, name: " << obj->GetName() << " title: " << obj->GetTitle() << endl; } } // save modifications to target file TH1::AddDirectory(status); }
void MatrixMethod(bool isData=false){ TFile* f = new TFile("MMethod.root", "update"); string dataset=""; string channels[] = {"mumumu", "mumue", "eemu", "eee"}; // Loop over channels for(int iChannel=0; iChannel<4; iChannel++) { cout<<"-------------"<<endl; cout<<"Channel "<<channels[iChannel]<<endl; cout<<"-------------"<<endl; TH1F* htight=0; TH1F* hloose=0; TH1F* htight_err=0; TH1F* hloose_err=0; // Get cut flow histos if(isData) { if(iChannel==0) dataset="DataMu"; if(iChannel==1) dataset="DataMuEG"; if(iChannel==2) dataset="DataMuEG"; if(iChannel==3) dataset="DataEG"; htight = (TH1F*) f->Get(string("CutFlow_"+channels[iChannel]+"_tight_"+dataset).c_str()); hloose = (TH1F*) f->Get(string("CutFlow_"+channels[iChannel]+"_loose_"+dataset).c_str()); htight_err = (TH1F*) f->Get(string("ErrCutFlow_"+channels[iChannel]+"_tight_"+dataset).c_str()); hloose_err = (TH1F*) f->Get(string("ErrCutFlow_"+channels[iChannel]+"_loose_"+dataset).c_str()); } else { dataset="MC"; TIter nextkey( gDirectory->GetListOfKeys() ); TKey *key; while ( (key = (TKey*)nextkey())) { TObject *obj = key->ReadObj(); if(! obj->IsA()->InheritsFrom( TH1F::Class() )) continue; TString name(obj->GetName()); if(!name.Contains("CutFlow")) continue; if(name.Contains("Data") || name.Contains("FCNC")) continue; TH1F* h = (TH1F*) obj; if(!name.Contains(channels[iChannel])) continue; //cout<<name<<endl; if(name.Contains("CutFlow") && !name.Contains("ErrCutFlow")) { if(name.Contains("tight")) { cout<<name<<endl; if(!htight) htight = (TH1F*) h->Clone(); else htight->Add(h); //htight->Print("all"); } if(name.Contains("loose")) { if(!hloose) hloose = (TH1F*) h->Clone(); else hloose->Add(h); } } if(name.Contains("ErrCutFlow")) { if(name.Contains("tight")) { if(!htight_err) htight_err = (TH1F*) h->Clone(); else htight_err->Add(h); } if(name.Contains("loose")) { if(!hloose_err) hloose_err = (TH1F*) h->Clone(); else hloose_err->Add(h); } } } } if(!htight || !hloose) {cout<<"Histos not found."<<endl; return;} if(!htight_err || !hloose_err) {cout<<"Error histos not found."<<endl; return;} htight->Print("all"); // Prepare estimations histos TH1F* hestimation_S = (TH1F*) htight->Clone(); hestimation_S->SetName(string("Estimation_"+channels[iChannel]+"_S_"+dataset).c_str()); hestimation_S->Reset(); TH1F* hestimation_Z = (TH1F*) htight->Clone(); hestimation_Z->SetName(string("Estimation_"+channels[iChannel]+"_Z_"+dataset).c_str()); hestimation_Z->Reset(); double Nt, Nl, NtS, NtZ, Nt_err, Nl_err, NtS_err_eff, NtZ_err_eff, NtS_err_stat, NtZ_err_stat; double Eff=0.95; double Eff_err=0.05; double Fake=0.05; double Fake_err=0.02; //test //ComputeEstimation(105, 300, NtS, NtZ, Eff, Fake); //cout<<" Estimation Signal : "<<NtS<<endl; //cout<<" Estimation Z+jets : "<<NtZ<<endl; // Set efficiencies and fake rate double EffMu, EffMu_err, FakeMu, FakeMu_err; double EffEl, EffEl_err, FakeEl, FakeEl_err; //-------------------------------- // DATA efficiencies and Fake rate //-------------------------------- if(isData) { // Estimation from Data Z and QCD EffMu = 0.976603; EffMu_err = 0.000101254; FakeMu = 0.0796632; FakeMu_err = 0.0456416; EffEl = 0.970103; EffEl_err = 0.000129266; FakeEl = 0.378883; FakeEl_err = 0.0227932; } //------------------------------ // MC efficiencies and Fake rate //------------------------------ if(!isData) { // Estimation from Z and W with 1 jet. // pt > 10 GeV /* EffMu = 0.969844; EffMu_err = 0.000108481; FakeMu = 0.119625; FakeMu_err = 0.0153273; EffEl = 0.966015; EffEl_err = 0.000132852; FakeEl = 0.369239; FakeEl_err = 0.0164294;*/ // pt > 20 GeV EffMu = 0.976603; EffMu_err = 0.000101254; FakeMu = 0.0796632; // utilise val pour 2 jet, car pour 1 jet elle est exageree : 0.156161 FakeMu_err = 0.0456416; // 1jet : 0.0391486 //EffEl = 0.970103; //EffEl_err = 0.000129266; //FakeEl = 0.378883; //FakeEl_err = 0.0227932; // good El Id EffEl = 0.971209; EffEl_err = 0.000129555; FakeEl = 0.352737; FakeEl_err = 0.0258883; // pt > 20 GeV , loose Iso = 999 /*EffMu = 0.974195; EffMu_err = 0.000106013; FakeMu = 0.0181453; // utilise val pour 2 jet, car pour 1 jet elle est exageree : 0.0342193 FakeMu_err = 0.01117; // 1jet : 0.00917115 EffEl = 0.970195; EffEl_err = 0.000131647; FakeEl = 0.329943; FakeEl_err = 0.0246272;*/ // pt > 30 GeV (only for W lepton) /* EffMu = 0.984503; EffMu_err = 9.60599e-05; FakeMu = 0.144276; FakeMu_err = 0.0743225; // low stat. Wjets seems to have mainly low pt fakes EffEl = 0.977502; EffEl_err = 0.000128996; FakeEl = 0.382805; FakeEl_err = 0.0340156;*/ /* EffEl = 0.854; EffEl_err = 0.001; FakeEl = 0.157; FakeEl_err = 0.01;*/ //Test last bin eee } if(iChannel==0 || iChannel==2) { Eff=EffMu; Eff_err=EffMu_err; Fake=FakeMu; Fake_err=FakeMu_err; } if(iChannel==1 || iChannel==3) { Eff=EffEl; Eff_err=EffEl_err; Fake=FakeEl; Fake_err=FakeEl_err; } // Compute estimations // Loop on all steps of cut flow for(int iCut=0; iCut<8; iCut++) //htight->GetNbinsX() { cout<<"iCut "<<iCut<<endl; Nt = htight->GetBinContent(iCut); Nl = hloose->GetBinContent(iCut); if(!htight_err) Nt_err=0; else Nt_err = sqrt(htight_err->GetBinContent(iCut)); if(!hloose_err) Nl_err=0; else Nl_err = sqrt(hloose_err->GetBinContent(iCut)); ComputeEstimation(Nt, Nl, NtS, NtZ, Eff, Fake); //GenerateStatError(Nt, Nl, NtS_err, NtZ_err, Eff, Fake); //GenerateStatErrorMC(Nt, Nl, Nt_err, Nl_err, NtS_err, NtZ_err, Eff, Fake); // Calcul des erreurs par propagation // Propagate stat error on Nt and Nl if(isData) NtS_err_stat = NtS_Stat_Error(Nt, Nl, Eff, Fake); else NtS_err_stat = NtS_Stat_ErrorMC(Nt, Nl, Nt_err, Nl_err, Eff, Fake); if(isData) NtZ_err_stat = NtZ_Stat_Error(Nt, Nl, Eff, Fake); else NtZ_err_stat = NtZ_Stat_ErrorMC(Nt, Nl, Nt_err, Nl_err, Eff, Fake); // Propagate stat error on Eff and Fake NtS_err_eff = NtS_Syst_Error(NtS, Nl, Eff, Fake, Eff_err, Fake_err); NtZ_err_eff = NtZ_Syst_Error(NtZ, Nl, Eff, Fake, Eff_err, Fake_err); cout<<" Estimation Signal : "<<NtS<<" +/- "<<NtS_err_stat<<" +/- "<<NtS_err_eff<<endl; cout<<" Estimation Z+jets : "<<NtZ<<" +/- "<<NtZ_err_stat<<" +/- "<<NtZ_err_eff<<endl; hestimation_S->SetBinContent(iCut, NtS); hestimation_Z->SetBinContent(iCut, NtZ); // Stat errors on N already plotted on histo so take only errors from Eff and Fake hestimation_S->SetBinError(iCut, NtS_err_eff); hestimation_Z->SetBinError(iCut, NtZ_err_eff); } hestimation_S->Write(); hestimation_Z->Write(); } }
TList* readHistos(vector<string> inputRootFiles, bool fillNameStrings){ TList* thelistHistos = new TList(); for (int j=0; j< inputRootFiles.size(); j++) { int numMax = 0; //cout <<"inputProcess: "<<inputProcess.at(j)<<endl; // Access input ROOT file (can access over secure shell) cout <<"inputRootFiles.at(j) "<<inputRootFiles.at(j)<<endl; TFile *rootTFile = new TFile((inputRootFiles.at(j)).c_str()); // open root file TDirectory *current_sourcedir = gDirectory; TIter nextkey( current_sourcedir->GetListOfKeys() ); TKey *key; // loop over keys(ROOT objects) within the root file while ((key = (TKey*)nextkey())) { TObject *obj = key->ReadObj(); TH1 *histoObj = (TH1*)obj; TH1* h1 = 0; //points to the new copied hist we will make int totalbins = 0; // rename histogram if ( obj->IsA()->InheritsFrom( "TH1" ) ) { string histname = obj->GetName(); size_t found = histname.find("lumi"); string theProcess = "lumi"; string new_theProcess = "_" + theProcess; histname.erase(found-1, new_theProcess.size()); string histName = histname; cout << histName << endl; for (int o = 0; o < inputHistoName.size(); o++) { if ( histName == inputHistoName.at(o) ) { int numBins = histoObj->GetXaxis()->GetNbins(); double lowerEdge = histoObj->GetXaxis()->GetXmin(); double upperEdge = histoObj->GetXaxis()->GetXmax(); h1 = new TH1F (histName.c_str(), histName.c_str(), numBins, lowerEdge, upperEdge); TH1F* tmp2 = static_cast<TH1F*>(h1); totalbins = tmp2->GetSize(); for (int k=0; k <= totalbins; k++) { h1->SetBinContent(k,(histoObj->GetBinContent(k))); h1->SetBinError(k,(histoObj->GetBinError(k))); } h1 = Rebinh(h1); //cout<<"h1 "<<h1->GetName()<<" Integral "<<h1->Integral()<<endl; thelistHistos->Add(h1); if(fillNameStrings) nHistList++; if(fillNameStrings) theHistNameStrings.push_back(histName); numMax++; } // close if loop on selected histograms } // close for loop on selected histograms } // close if loop InheritsFrom("TH1") } // close while loop // If first input ROOT file (Data), store total number of histograms if (j == 0) numHistos = numMax; // Else exit the code if a ROOT file has a different number of histograms else { if (numMax != numHistos) { cerr << "ERROR: Input Root Files DO NOT have the same number" << " of histograms." << endl; exit (1); } } } // close for loop over root files return thelistHistos; }
void plotylms() { gStyle->SetOptStat(1000000001); TIter gdiriter(gDirectory->GetListOfKeys()); TObject *cur; char *buf; char suff[500]; char lbuf[500]; char nbuf[500]; suff[0] = '\0'; while (cur = gdiriter()) { buf = cur->GetName(); if (strstr(buf, "CfnReYlm00")) { cout << "Found suffix " << buf+10 << endl; strcpy(suff, buf+10); break; } } if (!suff[0]) { cout << "Did not find suffix" << endl; return; } int maxl = 0; gdiriter->Reset(); while (cur = gdiriter()) { buf = cur->GetName(); if ((strstr(buf, "CfnReYlm")) && (strstr(buf, suff))){ cout << "Found l " << buf+8 << endl; strncpy(lbuf, buf+8,1); lbuf[1] = '\0'; int lcur = atoi(lbuf); cout << "Found l " << lcur << endl; if (lcur > maxl) maxl = lcur; } } cout << "Maximum l " << maxl << endl; int ilmcount= 0; TH1D **cfnsr; cfnsr = malloc(sizeof(TH1D *) * (maxl+1)*(maxl+1)); TH1D **cfnsi; cfnsi = malloc(sizeof(TH1D *) * (maxl+1)*(maxl+1)); for (int il=0; il<=maxl; il++) for (int im=0; im<=il; im++) { sprintf(nbuf, "CfnReYlm%i%i%s", il, im, suff); cfnsr[ilmcount] = new TH1D(*((TH1D *) gDirectory->Get(nbuf))); checknan(cfnsr[ilmcount]); sprintf(nbuf, "CfnImYlm%i%i%s", il, im, suff); cfnsi[ilmcount] = new TH1D(*((TH1D *) gDirectory->Get(nbuf))); checknan(cfnsi[ilmcount]); ilmcount++; } TLine *l1 = new TLine(0.0, 1.0, cfnsr[0]->GetXaxis()->GetXmax(), 1.0); l1->SetLineColor(14); l1->SetLineStyle(2); TLine *l0 = new TLine(0.0, 0.0, cfnsr[0]->GetXaxis()->GetXmax(), 0.0); l0->SetLineColor(14); l0->SetLineStyle(2); TCanvas *canylm = new TCanvas("canylm","canylm",1600,800); gPad->SetFillColor(0); gPad->SetFillStyle(4000); canylm->Divide(5, 2, 0.0001, 0.0001); for (int ilm=0; ilm<(maxl+1)*(maxl+2)/2; ilm++) { cout << "Drawing " << ilm << endl; canylm->cd(ilm+1); gPad->SetFillColor(0); gPad->SetFillStyle(4000); gPad->SetTopMargin(0.01); gPad->SetRightMargin(0.01); cfnsr[ilm]->SetTitle(""); cfnsr[ilm]->SetMarkerColor(2); cfnsr[ilm]->SetMarkerSize(0.8); cfnsr[ilm]->SetMarkerStyle(8); cfnsr[ilm]->Draw(); cout << "Drawn " << ilm << endl; cfnsi[ilm]->SetTitle(""); cfnsi[ilm]->SetMarkerColor(4); cfnsi[ilm]->SetMarkerSize(0.8); cfnsi[ilm]->SetMarkerStyle(8); cfnsi[ilm]->Draw("SAME"); cout << "Drawn " << ilm << endl; if (ilm) l0->Draw(); else l1->Draw(); } TLatex lat; lat.SetTextSize(0.12); TCanvas *canylms = new TCanvas("canylms","canylms",1100,900); gPad->SetFillColor(0); gPad->SetFillStyle(4000); canylms->Divide(1, 4, 0.0001, 0.0001); int el = 0; int em = 0; for (int ilm=0; ilm<(maxl+1)*(maxl+2)/2; ilm++) { TPad *curpad; canylms->cd(el+1); curpad = gPad; cout << "Drawing " << ilm << " " << el << " " << em << " " << curpad << endl; if (em == 0) { if (el==0) gPad->Divide(2,1,0.0001,0.0001); if (el == 1) gPad->Divide(2,1,0.0001,0.0001); if (el == 2) gPad->Divide(3,1,0.0001,0.0001); if (el == 3) gPad->Divide(4,1,0.0001,0.0001); if ((el==0) && (em==0)) { curpad->cd(2); lat.DrawLatex(0.2, 0.8, "C_{0}^{0}"); lat.DrawLatex(0.2, 0.6, "C_{1}^{0}"); lat.DrawLatex(0.5, 0.6, "C_{1}^{1}"); lat.DrawLatex(0.2, 0.4, "C_{2}^{0}"); lat.DrawLatex(0.4, 0.4, "C_{2}^{1}"); lat.DrawLatex(0.6, 0.4, "C_{2}^{2}"); lat.DrawLatex(0.2, 0.2, "C_{3}^{0}"); lat.DrawLatex(0.35, 0.2, "C_{3}^{1}"); lat.DrawLatex(0.5, 0.2, "C_{3}^{2}"); lat.DrawLatex(0.65, 0.2, "C_{3}^{3}"); lat.SetTextColor(2); lat.DrawLatex(0.35, 0.8, "real part"); lat.SetTextColor(4); lat.DrawLatex(0.6, 0.8, "imaginary part"); } } cout << "Drawing " << ilm << " " << curpad << endl; curpad->cd(em+1); // canylms->cd(ilm+1); gPad->SetFillColor(0); gPad->SetFillStyle(4000); gPad->SetTopMargin(0.01); gPad->SetRightMargin(0.01); cfnsr[ilm]->SetTitle(""); cfnsr[ilm]->SetMarkerColor(2); cfnsr[ilm]->SetMarkerSize(0.8); cfnsr[ilm]->SetMarkerStyle(8); cfnsr[ilm]->Draw(); cout << "Drawn " << ilm << endl; cfnsi[ilm]->SetTitle(""); cfnsi[ilm]->SetMarkerColor(4); cfnsi[ilm]->SetMarkerSize(0.8); cfnsi[ilm]->SetMarkerStyle(8); cfnsi[ilm]->Draw("SAME"); cout << "Drawn " << ilm << endl; if (ilm) l0->Draw(); else l1->Draw(); em++; if (em>el) { el++; em = 0; } } // canylms->SaveAs("canylms.eps"); // canylms->SaveAs("canylms.png"); }
void makePlots_Combinations(short makePlots=0) { TString dirPlots("/home/rossin/Dropbox/TT/Work/figures_stubCleaning/"); TFile fIn ("/home/rossin/Dropbox/TT/Work/figures_stubCleaning/stubCleaning_Neutrino_PU140_sf1_nz4_pt3_5oo6_14k.root"); TString sLogic ("5oo6"); TString pName("Neutrino_PU140_sf1_nz4_pt3_5oo6_14k"); TString pTitle(" PU140 SF=1 Nz=4 Pt>3 GeV/c"); TFile fIn2("/home/rossin/Dropbox/TT/Work/figures_stubCleaning/stubCleaning_Neutrino_PU140_sf1_nz4_pt3_6oo6_14k.root"); TString sLogic2("6oo6"); //TString pName("Neutrino_PU140_sf1_nz4_pt3_6oo6_14k"); TString pTitle(" PU140 SF=1 Nz=4 Pt>3 GeV/c"); TFile fInOR("/home/rossin/Dropbox/TT/Work/figures_stubCleaning/stubCleaning_Neutrino_PU140_sf1_nz4_pt3_5oo6_14k_OverlapRemoved.root"); // TFile fIn("/home/rossin/Dropbox/TT/Work/figures_stubCleaning/stubCleaning_Neutrino_PU200_sf1_nz4_pt3_5oo6_4k.root"); TString sLogic("5oo6"); TString pName("Neutrino_PU200_sf1_nz4_pt3_5oo6_4k"); TString pTitle(" PU200 SF=1 Nz=4 Pt>3 GeV/c"); // TFile fInOR("/home/rossin/Dropbox/TT/Work/figures_stubCleaning/stubCleaning_Neutrino_PU200_sf1_nz4_pt3_5oo6_4k_OverlapRemoved.root"); // TFile fIn("/home/rossin/Dropbox/TT/Work/figures_stubCleaning/stubCleaning_Neutrino_PU250_sf1_nz4_pt3_5oo6_4k.root"); TString sLogic("5oo6"); TString pName("Neutrino_PU250_sf1_nz4_pt3_5oo6_4k"); TString pTitle(" PU250 SF=1 Nz=4 Pt>3 GeV/c"); // TFile fInOR("/home/rossin/Dropbox/TT/Work/figures_stubCleaning/stubCleaning_Neutrino_PU250_sf1_nz4_pt3_5oo6_4k_OverlapRemoved.root"); TH1* h1stubsInLayer [6][2]; TH1* h1stubsInLayerOR[6][2]; TH1* h1RoadPerEvent [2]; TH1* h1RoadPerEventOR[2]; TH1* h1CombPerRoad [2]; TH1* h1CombPerRoadOR [2]; TH1* h1CombPerEvent [2]; TH1* h1CombPerEventOR[2]; TH1* h1RoadPerEvent6oo6 [2]; TH1* h1CombPerRoad6oo6 [2]; TH1* h1CombPerEvent6oo6 [2]; TString sClean[2] = {TString(""), TString("_Cleaned")}; for (unsigned short iLay=0; iLay<6; ++iLay) { TList* tl = fIn.GetListOfKeys(); TIter next(tl); TObject *obj; char cc[20]; sprintf(cc,"_%d",iLay); TString hString("h1stubsInLayer__"+sLogic+TString(cc)); while ((obj=next())) { TString hName(obj->GetName()); if (hName==hString) { for (unsigned short iClean = 0; iClean < 2; ++iClean) { char cc2[100]; h1stubsInLayer [iLay][iClean] = (TH1*) fIn .Get(hName+sClean[iClean]); sprintf(cc2,"L%d - ",iLay+5); h1stubsInLayer [iLay][iClean]->SetTitle(TString(cc2)+sLogic+pTitle); h1stubsInLayerOR[iLay][iClean] = (TH1*) fInOR.Get(hName+sClean[iClean]); if (h1stubsInLayer [iLay][iClean]==0) { std::cout << "ERROR. " << hName+sClean[iClean] << " not loaded." << std::endl; return; } if (h1stubsInLayerOR[iLay][iClean]==0) { std::cout << "ERROR. " << hName+sClean[iClean] << " overlap removed not loaded." << std::endl; return; } } } } // std::cout << h1stubsInLayer [iLay][0] << "\t" << h1stubsInLayer [iLay][1] << "\t" << h1stubsInLayerOR[iLay][0] << "\t" << h1stubsInLayerOR[iLay][1] << std::endl; } for (unsigned short iClean = 0; iClean < 2; ++iClean) { TString hString("h1RoadPerEvent_"+sLogic); h1RoadPerEvent [iClean] = (TH1*) fIn .Get(hString+sClean[iClean]); h1RoadPerEventOR[iClean] = (TH1*) fInOR.Get(hString+sClean[iClean]); hString=TString("h1CombPerRoad_")+sLogic; h1CombPerRoad [iClean] = (TH1*) fIn .Get(hString+sClean[iClean]); h1CombPerRoadOR [iClean] = (TH1*) fInOR.Get(hString+sClean[iClean]); hString=TString("h1CombPerEvent_")+sLogic; h1CombPerEvent [iClean] = (TH1*) fIn .Get(hString+sClean[iClean]); h1CombPerEventOR [iClean] = (TH1*) fInOR.Get(hString+sClean[iClean]); hString=TString("h1RoadPerEvent_"+sLogic2); h1RoadPerEvent6oo6 [iClean] = (TH1*) fIn2 .Get(hString+sClean[iClean]); hString=TString("h1CombPerRoad_")+sLogic2; h1CombPerRoad6oo6 [iClean] = (TH1*) fIn2 .Get(hString+sClean[iClean]); hString=TString("h1CombPerEvent_")+sLogic2; h1CombPerEvent6oo6 [iClean] = (TH1*) fIn2 .Get(hString+sClean[iClean]); } TString cName("cStubsPerLayer_"+sLogic+pName); TString cTitle("StubsPerLayer "+sLogic+pTitle); TCanvas* cStubsPerLayer = new TCanvas(cName,cTitle,0,0,1400,900); cStubsPerLayer->Divide(3,2); for (unsigned short iLay=0; iLay<6; ++iLay) { char cc3[100]; cStubsPerLayer->cd(iLay+1); gPad->SetLogy(); h1stubsInLayer [iLay][0]->DrawCopy(); TLegend* tl = new TLegend(0.3,0.75,0.9,0.9); sprintf(cc3,"Mean # stubs: %3.2lf",h1stubsInLayer [iLay][0]->GetMean()); TLegendEntry* tle = tl->AddEntry(h1stubsInLayer [iLay][0],cc3,"l"); tle->SetLineColor(h1stubsInLayer [iLay][0]->GetLineColor()); tle->SetLineWidth(h1stubsInLayer [iLay][0]->GetLineWidth()); tl->Draw("L"); } if (makePlots) { cStubsPerLayer->SaveAs(dirPlots+cName+"__.pdf"); cStubsPerLayer->SaveAs(dirPlots+cName+"__.png"); } for (unsigned short iLay=0; iLay<6; ++iLay) { char cc3[100]; cStubsPerLayer->cd(iLay+1); gPad->SetLogy(); h1stubsInLayerOR[iLay][0]->SetLineColor(2); h1stubsInLayerOR[iLay][0]->DrawCopy("same"); TLegend* tl = new TLegend(0.25,0.75,0.9,0.9); sprintf(cc3,"Mean # stubs: %3.2lf",h1stubsInLayer [iLay][0]->GetMean()); TLegendEntry* tle = tl->AddEntry(h1stubsInLayer [iLay][0],cc3,"l"); tle->SetLineColor(h1stubsInLayer [iLay][0]->GetLineColor()); tle->SetLineWidth(h1stubsInLayer [iLay][0]->GetLineWidth()); sprintf(cc3,"Mean # stubs Overlap Removed: %3.2lf",h1stubsInLayerOR[iLay][0]->GetMean()); tle = tl->AddEntry(h1stubsInLayerOR[iLay][0],cc3,"l"); tle->SetLineColor(h1stubsInLayerOR[iLay][0]->GetLineColor()); tle->SetLineWidth(h1stubsInLayerOR[iLay][0]->GetLineWidth()); tl->Draw("L"); } if (makePlots) { cStubsPerLayer->SaveAs(dirPlots+cName+"_OR_.pdf"); cStubsPerLayer->SaveAs(dirPlots+cName+"_OR_.png"); } cName=TString("cStubsPerLayerDsClean_")+sLogic+pName; cTitle=TString("StubsPerLayer Ds clean ")+sLogic+pTitle; TCanvas* cStubsPerLayerDsClean = new TCanvas(cName,cTitle,0,0,1400,900); cStubsPerLayerDsClean->Divide(3,2); for (unsigned short iLay=0; iLay<6; ++iLay) { char cc3[100]; cStubsPerLayerDsClean->cd(iLay+1); gPad->SetLogy(); h1stubsInLayer [iLay][0]->DrawCopy(); h1stubsInLayer [iLay][1]->SetLineColor(8); h1stubsInLayer [iLay][1]->DrawCopy("same"); TLegend* tl = new TLegend(0.25,0.75,0.9,0.9); sprintf(cc3,"Mean # stubs: %3.2lf",h1stubsInLayer [iLay][0]->GetMean()); TLegendEntry* tle = tl->AddEntry(h1stubsInLayer [iLay][0],cc3,"l"); tle->SetLineColor(h1stubsInLayer [iLay][0]->GetLineColor()); tle->SetLineWidth(h1stubsInLayer [iLay][0]->GetLineWidth()); sprintf(cc3,"Mean # stubs #Deltas clean: %3.2lf",h1stubsInLayer [iLay][1]->GetMean()); tle = tl->AddEntry(h1stubsInLayer [iLay][1],cc3,"l"); tle->SetLineColor(h1stubsInLayer [iLay][1]->GetLineColor()); tle->SetLineWidth(h1stubsInLayer [iLay][1]->GetLineWidth()); tl->Draw("L"); } if (makePlots) { cStubsPerLayerDsClean->SaveAs(dirPlots+cName+"__.pdf"); cStubsPerLayerDsClean->SaveAs(dirPlots+cName+"__.png"); } cName=TString("cStubsPerLayerDsCleanOR_")+sLogic+pName; cTitle=TString("StubsPerLayer #Deltas clean Overlap Removed ")+sLogic+pTitle; TCanvas* cStubsPerLayerDsCleanOR = new TCanvas(cName,cTitle,0,0,1400,900); cStubsPerLayerDsCleanOR->Divide(3,2); for (unsigned short iLay=0; iLay<6; ++iLay) { char cc3[100]; cStubsPerLayerDsCleanOR->cd(iLay+1); gPad->SetLogy(); h1stubsInLayer [iLay][0]->DrawCopy(); h1stubsInLayerOR[iLay][0]->SetLineColor(2); h1stubsInLayerOR[iLay][0]->DrawCopy("same"); h1stubsInLayerOR[iLay][1]->SetLineColor(6); h1stubsInLayerOR[iLay][1]->DrawCopy("same"); TLegend* tl = new TLegend(0.25,0.70,0.9,0.9); sprintf(cc3,"Mean # stubs: %3.2lf",h1stubsInLayer [iLay][0]->GetMean()); TLegendEntry* tle = tl->AddEntry(h1stubsInLayer [iLay][0],cc3,"l"); tle->SetLineColor(h1stubsInLayer [iLay][0]->GetLineColor()); tle->SetLineWidth(h1stubsInLayer [iLay][0]->GetLineWidth()); sprintf(cc3,"Mean # stubs Ov. Rem.: %3.2lf",h1stubsInLayerOR[iLay][0]->GetMean()); tle = tl->AddEntry(h1stubsInLayerOR[iLay][0],cc3,"l"); tle->SetLineColor (h1stubsInLayerOR[iLay][0]->GetLineColor()); tle->SetLineWidth (h1stubsInLayerOR[iLay][0]->GetLineWidth()); sprintf(cc3,"Mean # stubs Ds clean Ov. Rem.: %3.2lf",h1stubsInLayerOR[iLay][1]->GetMean()); tle = tl->AddEntry(h1stubsInLayerOR[iLay][1],cc3,"l"); tle->SetLineColor (h1stubsInLayerOR[iLay][1]->GetLineColor()); tle->SetLineWidth (h1stubsInLayerOR[iLay][1]->GetLineWidth()); tl->Draw("L"); } if (makePlots) { cStubsPerLayerDsCleanOR->SaveAs(dirPlots+cName+"__.pdf"); cStubsPerLayerDsCleanOR->SaveAs(dirPlots+cName+"__.png"); } const short nQuant = 4; double percentiles [nQuant] = {0.90, 0.95, 0.99, 0.999}; double xpercentiles[6][nQuant]; cName=TString("cRoadPerEvent_")+sLogic+pName; cTitle=TString("Roads per Tower "+sLogic+pTitle); TCanvas* cRoadPerEvent = new TCanvas(cName,cTitle,0,0,1400,900); cRoadPerEvent->SetLogy(); h1RoadPerEvent [0]->SetTitle(cTitle); h1RoadPerEvent [0]->DrawCopy(); // h1RoadPerEvent6oo6[0]->SetLineColor(14); // h1RoadPerEvent6oo6[0]->DrawCopy("same"); char cc3[100]; h1RoadPerEvent [0]->GetQuantiles(nQuant,xpercentiles[0],percentiles); sprintf(cc3," #mu=%3.1lf, #Lambda_{%3.1lf}=%3.1lf",h1RoadPerEvent [0]->GetMean(),percentiles[3]*100,xpercentiles[0][3]); TLegend* tl = new TLegend(0.25,0.84,0.9,0.9); TLegendEntry* tle = tl->AddEntry(h1RoadPerEvent [0],cc3,"l"); tle->SetLineColor(h1RoadPerEvent [0]->GetLineColor()); tle->SetLineWidth(h1RoadPerEvent [0]->GetLineWidth()); // h1RoadPerEvent6oo6[0]->GetQuantiles(nQuant,xpercentiles[0],percentiles); // sprintf(cc3,"# roads/tower-6/6. #mu=%3.1lf, #Lambda_{%3.1lf}=%3.1lf",h1RoadPerEvent6oo6[0]->GetMean(),percentiles[3]*100,xpercentiles[0][3]); // tle = tl->AddEntry(h1RoadPerEvent6oo6[0],cc3,"l"); // tle->SetLineColor(h1RoadPerEvent6oo6[0]->GetLineColor()); // tle->SetLineWidth(h1RoadPerEvent6oo6[0]->GetLineWidth()); tl->Draw("L"); if (makePlots) { cRoadPerEvent->SaveAs(dirPlots+cName+"__.pdf"); cRoadPerEvent->SaveAs(dirPlots+cName+"__.png"); } cName=TString("cRoadPerEvent_OR_")+sLogic+pName; cTitle=TString("Roads per Tower "+sLogic+pTitle); TCanvas* cRoadPerEventOR = new TCanvas(cName,cTitle,0,0,1400,900); cRoadPerEventOR->SetLogy(); h1RoadPerEvent [0]->SetTitle(cTitle); h1RoadPerEvent [0]->DrawCopy(); h1RoadPerEvent [0]->GetQuantiles(nQuant,xpercentiles[0],percentiles); sprintf(cc3," #mu=%3.1lf, #Lambda_{%3.1lf}=%3.1lf",h1RoadPerEvent [0]->GetMean(),percentiles[3]*100,xpercentiles[0][3]); tl = new TLegend(0.25,0.8,0.9,0.9); tle = tl->AddEntry(h1RoadPerEvent [0],cc3,"l"); tle->SetLineColor(h1RoadPerEvent [0]->GetLineColor()); tle->SetLineWidth(h1RoadPerEvent [0]->GetLineWidth()); h1RoadPerEventOR[0]->SetLineColor(2); h1RoadPerEventOR[0]->DrawCopy("same"); h1RoadPerEventOR[0]->GetQuantiles(nQuant,xpercentiles[0],percentiles); sprintf(cc3,"Ov. Masked #mu=%3.1lf, #Lambda_{%3.1lf}=%3.1lf",h1RoadPerEventOR[0]->GetMean(),percentiles[3]*100,xpercentiles[0][3]); tle = tl->AddEntry(h1RoadPerEventOR[0],cc3,"l"); tle->SetLineColor(h1RoadPerEventOR[0]->GetLineColor()); tle->SetLineWidth(h1RoadPerEventOR[0]->GetLineWidth()); tl->Draw("L"); if (makePlots) { cRoadPerEventOR->SaveAs(dirPlots+cName+"__.pdf"); cRoadPerEventOR->SaveAs(dirPlots+cName+"__.png"); } cName=TString("cCombPerRoad_")+sLogic+pName; cTitle=TString("Combinations per Road "+sLogic+pTitle); TCanvas* cCombPerRoad = new TCanvas(cName,cTitle,0,0,1400,900); cCombPerRoad->SetLogy(); h1CombPerRoad [0]->SetTitle(cTitle); h1CombPerRoad [0]->DrawCopy(); h1CombPerRoad [0]->GetQuantiles(nQuant,xpercentiles[0],percentiles); sprintf(cc3,"# combinations/road. #mu=%3.1lf, #Lambda_{%3.1lf}=%3.1lf",h1CombPerRoad [0]->GetMean(),percentiles[3]*100,xpercentiles[0][3]); tl = new TLegend(0.25,0.75,0.9,0.9); tle = tl->AddEntry(h1CombPerRoad [0],cc3,"l"); tle->SetLineColor (h1CombPerRoad [0]->GetLineColor()); tle->SetLineWidth (h1CombPerRoad [0]->GetLineWidth()); tl->Draw("L"); if (makePlots) { cCombPerRoad->SaveAs(dirPlots+cName+"__.pdf"); cCombPerRoad->SaveAs(dirPlots+cName+"__.png"); } cName=TString("cCombPerRoad_OR_")+sLogic+pName; h1CombPerRoadOR[0]->SetLineColor(2); h1CombPerRoadOR[0]->DrawCopy("same"); h1CombPerRoadOR[0]->GetQuantiles(nQuant,xpercentiles[0],percentiles); sprintf(cc3,"# combinations/road. Ov. Masked. #mu=%3.1lf, #Lambda_{%3.1lf}=%3.1lf",h1CombPerRoadOR[0]->GetMean(),percentiles[3]*100,xpercentiles[0][3]); tle = tl->AddEntry(h1CombPerRoadOR[0],cc3,"l"); tle->SetLineColor (h1CombPerRoadOR[0]->GetLineColor()); tle->SetLineWidth (h1CombPerRoadOR[0]->GetLineWidth()); tl->Draw("L"); if (makePlots) { cCombPerRoad->SaveAs(dirPlots+cName+"__.pdf"); cCombPerRoad->SaveAs(dirPlots+cName+"__.png"); } cName=TString("cCombPerRoad_OR_DsClean_")+sLogic+pName; h1CombPerRoadOR[1]->SetLineColor(8); h1CombPerRoadOR[1]->DrawCopy("same"); h1CombPerRoadOR[1]->GetQuantiles(nQuant,xpercentiles[0],percentiles); sprintf(cc3,"# combinations/road. #Deltas clean Ov. Masked #mu=%3.1lf, #Lambda_{%3.1lf}=%3.1lf",h1CombPerRoadOR[1]->GetMean(),percentiles[3]*100,xpercentiles[0][3]); tle = tl->AddEntry(h1CombPerRoadOR[1],cc3,"l"); tle->SetLineColor (h1CombPerRoadOR[1]->GetLineColor()); tle->SetLineWidth (h1CombPerRoadOR[1]->GetLineWidth()); tl->Draw("L"); if (makePlots) { cCombPerRoad->SaveAs(dirPlots+cName+"__.pdf"); cCombPerRoad->SaveAs(dirPlots+cName+"__.png"); } cName=TString("cCombPerEvent_")+sLogic+pName; cTitle=TString("Combinations per Tower "+sLogic+pTitle); TCanvas* cCombPerEvent = new TCanvas(cName,cTitle,0,0,1400,900); cCombPerEvent->SetLogy(); h1CombPerEvent [0]->SetTitle(cTitle); h1CombPerEvent [0]->DrawCopy(); h1CombPerEvent [0]->GetQuantiles(nQuant,xpercentiles[0],percentiles); sprintf(cc3," #mu=%3.1lf, #Lambda_{%3.1lf}=%3.1lf",45.7,percentiles[3]*100,772.4); tl = new TLegend(0.25,0.75,0.9,0.9); tle = tl->AddEntry(h1CombPerEvent [0],cc3,"l"); tle->SetLineColor (h1CombPerEvent [0]->GetLineColor()); tle->SetLineWidth (h1CombPerEvent [0]->GetLineWidth()); tl->Draw("L"); if (makePlots) { cCombPerEvent->SaveAs(dirPlots+cName+"__.pdf"); cCombPerEvent->SaveAs(dirPlots+cName+"__.png"); } cName=TString("cCombPerEvent_OR_")+sLogic+pName; h1CombPerEventOR[0]->SetLineColor(2); h1CombPerEventOR[0]->DrawCopy("same"); h1CombPerEventOR[0]->GetQuantiles(nQuant,xpercentiles[0],percentiles); sprintf(cc3," Ov. Masked #mu=%3.1lf, #Lambda_{%3.1lf}=%3.1lf",h1CombPerEventOR[0]->GetMean(),percentiles[3]*100,467.4); tle = tl->AddEntry(h1CombPerEventOR[0],cc3,"l"); tle->SetLineColor (h1CombPerEventOR[0]->GetLineColor()); tle->SetLineWidth (h1CombPerEventOR[0]->GetLineWidth()); tl->Draw("L"); if (makePlots) { cCombPerEvent->SaveAs(dirPlots+cName+"__.pdf"); cCombPerEvent->SaveAs(dirPlots+cName+"__.png"); } cName=TString("cCombPerEvent_OR_DsClean_")+sLogic+pName; h1CombPerEventOR[1]->SetLineColor(8); // h1CombPerEventOR[1]->SetTitle(cTitle); // h1CombPerEventOR[1]->DrawCopy(); h1CombPerEvent [0]->DrawCopy(); h1CombPerEventOR[0]->DrawCopy("same"); h1CombPerEventOR[1]->DrawCopy("same"); h1CombPerEventOR[1]->GetQuantiles(nQuant,xpercentiles[0],percentiles); sprintf(cc3,"#Deltas clean Ov. Masked #mu=%3.1lf, #Lambda_{%3.1lf}=%3.1lf",h1CombPerEventOR[1]->GetMean(),percentiles[3]*100,xpercentiles[0][3]); tle = tl->AddEntry(h1CombPerEventOR[1],cc3,"l"); tle->SetLineColor (h1CombPerEventOR[1]->GetLineColor()); tle->SetLineWidth (h1CombPerEventOR[1]->GetLineWidth()); tl->Draw("L"); if (makePlots) { cCombPerEvent->SaveAs(dirPlots+cName+"__.pdf"); cCombPerEvent->SaveAs(dirPlots+cName+"__.png"); } TFile f1("/home/rossin/Dropbox/TT/Work/figures_stubOverlapRemoval/eff_LTF_SingleMuonTest_tt27_PU0_sf1_nz4_pt3_5oo6_95c_100k/efficiency1_10dedup_ppt_sf1_nz4.root"); TFile f2("/home/rossin/Dropbox/TT/Work/figures_stubOverlapRemoval/eff_LTF_SingleMuonTest_tt27_PU0_sf1_nz4_pt3_5oo6_95c_100k_removeOverlap/efficiency1_10dedup_ppt_sf1_nz4.root"); TCanvas* c1 = (TCanvas*) f1.Get("c1"); TList* list1 = c1->GetListOfPrimitives(); TIter next1(list1); TObject* obj1; TGraphAsymmErrors* eff_graph; while ((obj1 = next1())) { std::cout << obj1->GetName() << std::endl; if (obj1->GetName()==TString("eff_graph")) eff_graph = (TGraphAsymmErrors*) obj1; } // eff_graph->GetYaxis()->SetTitle("#varepsilon"); // eff_graph->SetMinimum(0.8); TCanvas* c1OR = (TCanvas*) f2.Get("c1"); c1OR->SetName("eff_OR"); c1OR->SetTitle("eff_OR"); TList* list = c1OR->GetListOfPrimitives(); TIter next(list); TObject* obj; TGraphAsymmErrors* eff_graphOR; c1->Draw(); while ((obj = next())) { std::cout << obj->GetName() << std::endl; if (obj->GetName()==TString("eff_graph")) { eff_graphOR = (TGraphAsymmErrors*) obj; eff_graphOR->SetLineStyle (eff_graph->GetLineStyle()); eff_graphOR->SetLineWidth (eff_graph->GetLineWidth()/2); eff_graphOR->SetMarkerStyle(eff_graph->GetMarkerStyle()); eff_graphOR->SetMarkerSize (eff_graph->GetMarkerSize()); eff_graphOR->SetFillColor (eff_graph->GetFillColor()); eff_graphOR->SetFillStyle (eff_graph->GetFillStyle()); eff_graphOR->SetMarkerColor(4); eff_graphOR->SetLineColor(4); eff_graphOR->GetYaxis()->SetTitle("#varepsilon"); eff_graphOR->Draw("same p"); } } tl = new TLegend(0.4,.13,0.95,0.35); tl->AddEntry(eff_graph ,"No Overlap Removal","p"); tl->AddEntry(eff_graphOR," Overlap Removal","p"); tl->Draw(); if (makePlots) { c1->SaveAs(dirPlots+TString("totalRecoEff_OR")+"__.png"); c1->SaveAs(dirPlots+TString("totalRecoEff_OR")+"__.pdf"); } return; }
void ScaleAll1file( TDirectory *target, FileInfo_t& source ) { cout << "Target path: " << target->GetPath() << endl; TString path( (char*)strstr( target->GetPath(), ":" ) ); path.Remove( 0, 2 ); source.fp->cd( path ); TDirectory *current_sourcedir = gDirectory; // loop over all keys in this directory bool newdir = true; TIter nextkey( current_sourcedir->GetListOfKeys() ); TKey *key; while ( (key = (TKey*)nextkey())) { // read object from first source file source.fp->cd( path ); TObject *obj = key->ReadObj(); if ( obj->IsA()->InheritsFrom( "TH1" ) ) { // descendant of TH1 -> scale it if (newdir) { newdir=false; cout << "Scaling histograms: " << endl; } cout << obj->GetName() << " "; TH1 *h1 = (TH1*)obj; h1->Scale(source.weight); } else if ( obj->IsA()->InheritsFrom( "TDirectory" ) ) { // it's a subdirectory newdir = true; cout << "\n=====> Found subdirectory " << obj->GetName(); cout << "<=====\n" << endl; // create a new subdir of same name and title in the target file target->cd(); TDirectory *newdir = target->mkdir( obj->GetName(), obj->GetTitle() ); // newdir is now the starting point of another round of merging // newdir still knows its depth within the target file via // GetPath(), so we can still figure out where we are in the recursion ScaleAll1file( newdir, source ); } else { // object is of no type that we know or can handle cout << "\n======> Unknown object type, name: " << obj->GetName() << " title: " << obj->GetTitle(); cout << "<======\n" << endl; } // now write the scaledd histogram (which is "in" obj) to the target file // note that this will just store obj in the current directory level, // which is not persistent until the complete directory itself is stored // by "target->Write()" below if ( obj ) { target->cd(); obj->Write( key->GetName() ); } } // while ( ( TKey *key = (TKey*)nextkey() ) ) cout << endl; // save modifications to target file target->Write(); }
void DrawStatUncertainty() { TFile *f; TString ss("ExpStat_PYTHIA_canvasOutFile.root"); f = new TFile(ss); TCanvas *c c = (TCanvas*)f->Get("_R92777"); TString algoTitle; algoTitle = "k_{T} D = 0.6"; TList *li = (TList*)gPad->GetListOfPrimitives(); TObject *obj; TIter next(li); TH1D *histList[100], *htmp; int i,j,N; while ((obj = (TObject*)next())) { TString cname = obj->ClassName(); TString name = obj->GetName(); cout << cname <<" "<<name<<endl; if (cname=="TH1D") { histList[N] = (TH1D*)gPad->FindObject(obj); histList[N]->SetFillColor(0); histList[N]->SetFillStyle(0); N++; } } TCanvas *c = new TCanvas("c","c"); gPad->SetLogx(); gPad->SetLogy(); //histList[0]->SetMaximum(1e+10); histList[0]->SetTitle(""); histList[0]->GetXaxis()->SetTitle("jet p_{T} (GeV)"); histList[0]->GetXaxis()->SetTitleFont(42); histList[0]->GetXaxis()->SetLabelFont(42); histList[0]->GetXaxis()->SetTitleSize(0.05); histList[0]->GetXaxis()->SetLabelSize(0.05); histList[0]->GetYaxis()->SetTitle("Relative Statistical Uncertainty"); histList[0]->GetYaxis()->SetTitleFont(42); histList[0]->GetYaxis()->SetLabelFont(42); histList[0]->GetYaxis()->SetTitleSize(0.05); histList[0]->GetYaxis()->SetLabelSize(0.05); histList[0]->GetYaxis()->SetNdivisions(505); histList[0]->SetLineWidth(1); histList[0]->SetLineStyle(1); histList[0]->SetLineColor(1); histList[0]->SetMarkerColor(1); histList[0]->SetMarkerStyle(20); histList[0]->SetMarkerSize(1.2); histList[1]->SetLineColor(2); histList[1]->SetMarkerColor(2); histList[1]->SetLineWidth(1); histList[1]->SetMarkerStyle(25); histList[1]->SetLineStyle(1); histList[1]->SetMarkerSize(1.2); histList[2]->SetLineWidth(1); histList[2]->SetLineStyle(1); histList[2]->SetLineColor(4); histList[2]->SetMarkerColor(4); histList[2]->SetMarkerStyle(22); histList[2]->SetMarkerSize(1.2); histList[0]->Draw("P"); histList[1]->Draw("sameP"); histList[2]->Draw("sameP"); TLegend *leg = new TLegend(0.47,0.2,0.92,0.35); leg->SetTextFont(42); leg->AddEntry(histList[0],"|y| < 0.55","P"); leg->AddEntry(histList[1],"1.10 < |y| < 1.70","P"); leg->AddEntry(histList[2],"1.70 < |y| < 2.50","P"); leg->SetFillColor(0); leg->SetBorderSize(0); leg->Draw(); TPaveText *pave3 = new TPaveText(0.2,0.65,0.45,0.9,"NDC"); pave3->SetTextFont(42); pave3->AddText("CMS preliminary"); pave3->AddText(algoTitle); pave3->AddText("#sqrt{s} = 10 TeV"); pave3->AddText(""); pave3->AddText("#int L dt = 10 pb^{-1}"); pave3->SetFillColor(0); pave3->SetBorderSize(0); pave3->Draw(); c->Print("KT6_StatUncertainty.eps"); }
void createPseudoDataFunc(double luminosity, const std::string decayChannel, TString specifier){ // specifier="NoDistort" for closure test; "topPtUp", "topPtDown", "ttbarMassUp", "ttbarMassDown" or "data" for shape distortions; "1000" for Zprime // "verbose": set detail level of output ( 0: no output, 1: std output 2: output for debugging ) int verbose=0; // "smear": say if you want to do a poisson smearing for each bin or just a combination for the different samples bool smear=false; // "dataFile": absolute path of data file, used to define plots of interest TString dataFile= ""; if(decayChannel.compare("electron")==0) dataFile="/afs/naf.desy.de/group/cms/scratch/tophh/RecentAnalysisRun8TeV_doubleKinFit/elecDiffXSecData2012ABCDAll.root"; else dataFile="/afs/naf.desy.de/group/cms/scratch/tophh/RecentAnalysisRun8TeV_doubleKinFit/muonDiffXSecData2012ABCDAll.root"; // "useReweightedTop": use parton level reweighted ttbar signal file in pseudo data? bool useReweightedTop = (specifier.Contains("NoDistort")) ? false : true; // "zprime": include additional Zprime in pseudo data? bool zprime=specifier.Contains("1000") ? true : false; // naming for outputfile, constructed within macro TString outNameExtension=""; // check input parameter validity // type of closure test if(!(specifier.Contains("NoDistort")||specifier.Contains("1000")||specifier.Contains("data")||specifier.Contains("topPtUp")||specifier.Contains("topPtDown")||specifier.Contains("ttbarMassUp")||specifier.Contains("ttbarMassDown")||specifier.Contains("topMass161p5")||specifier.Contains("topMass163p5")||specifier.Contains("topMass166p5")||specifier.Contains("topMass169p5")||specifier.Contains("topMass175p5")||specifier.Contains("topMass178p5")||specifier.Contains("topMass181p5")||specifier.Contains("topMass184p5"))){ std::cout << "ERROR: invalid input specifier=" << specifier << std::endl; std::cout << "supported are: specifier=NoDistort,1000,data,topPtUp,topPtDown,ttbarMassUp,ttbarMassDown,topMass161p5,topMass163p5,topMass166p5,topMass169p5,topMass175p5,topMass178p5,topMass181p5,topMass184p5" << std::endl; exit(0); } // decay channel if(!(decayChannel.compare("electron")==0||decayChannel.compare("muon")==0)){ std::cout << "ERROR: invalid input decayChannel=" << decayChannel << std::endl; std::cout << "supported are: decayChannel=muon,electron" << std::endl; exit(0); } // --- // create container for histos and files // --- std::map<unsigned int, TFile*> files_; std::map< TString, std::map <unsigned int, TH1F*> > histo_; std::map< TString, std::map <unsigned int, TH2F*> > histo2_; // --- // parton level reweighted top distribution // --- // a) name and path of rootfile // path TString nameTtbarReweighted="/afs/naf.desy.de/group/cms/scratch/tophh/RecentAnalysisRun8TeV_doubleKinFit/"; // subfolder for reweighting systematics if(specifier!="NoDistort"&&!specifier.Contains("p5")){ nameTtbarReweighted+="ttbarReweight/"; // SG reweighting test if(decayChannel.compare("electron")==0) nameTtbarReweighted+="elecDiffXSec"; else nameTtbarReweighted+="muonDiffXSec"; nameTtbarReweighted+="SigSysDistort"+specifier+"Summer12PF.root"; } else{ // SG sample for corresponding top mass int sys=sysNo; // == "NoDistort" if( specifier=="topMass161p5") sys=sysTopMassDown4; else if(specifier=="topMass163p5") sys=sysTopMassDown3; else if(specifier=="topMass166p5") sys=sysTopMassDown2; else if(specifier=="topMass169p5") sys=sysTopMassDown; else if(specifier=="topMass175p5") sys=sysTopMassUp; else if(specifier=="topMass178p5") sys=sysTopMassUp2; else if(specifier=="topMass181p5") sys=sysTopMassUp3; else if(specifier=="topMass184p5") sys=sysTopMassUp4; nameTtbarReweighted+=TopFilename(kSig, sys, decayChannel); } // BG TString nameTtbarBGReweighted=nameTtbarReweighted; nameTtbarBGReweighted.ReplaceAll("Sig","Bkg"); if(useReweightedTop&&!specifier.Contains("p5")) outNameExtension+="Reweighted"+specifier; // b) get average weight for reweighted samples double avWeight=1; if(useReweightedTop && specifier!="NoDistort"&& !specifier.Contains("p5")){ TFile* ttbarRewfile = new (TFile)(nameTtbarReweighted); TString weightPlot="eventWeightDileptonModelVariation/modelWeightSum"; histo_["avWeight"][kSig] = (TH1F*)(ttbarRewfile->Get(weightPlot)->Clone()); avWeight=histo_ ["avWeight"][kSig]->GetBinContent(2)/histo_ ["avWeight"][kSig]->GetBinContent(1); histo_["avWeight"].erase(kSig); TFile* sigfile = new (TFile)("/afs/naf.desy.de/group/cms/scratch/tophh/RecentAnalysisRun8TeV_doubleKinFit/"+TopFilename(kSig, sysNo, decayChannel)); TString partonPlot="analyzeTopPartonLevelKinematics/ttbarMass"; gROOT->cd(); histo_["parton" ][kSig] = (TH1F*)(sigfile ->Get(partonPlot)->Clone()); histo_["partonRew"][kSig] = (TH1F*)(ttbarRewfile->Get(partonPlot)->Clone()); double avWeight2 = histo_["partonRew"][kSig]->Integral(0, histo_["partonRew"][kSig]->GetNbinsX()+1); avWeight2 /= histo_["parton" ][kSig]->Integral(0, histo_["parton" ][kSig]->GetNbinsX()+1); if(verbose>1){ std::cout << "ratio unweighted/weighted" << std::endl; std::cout << avWeight << " (from " << weightPlot << ")" << std::endl; std::cout << avWeight2 << TString(" (from entries in ")+partonPlot+" wrt /afs/naf.desy.de/group/cms/scratch/tophh/RecentAnalysisRun8TeV_doubleKinFit/"+TopFilename(kSig, sysNo, decayChannel)+"): " << std::endl; } } // --- // Z prime // --- // xSec scaling (default value chosen for M1000W100: 5pb) double xSecSF=1.0; // path & naming TString zprimeMass =specifier; TString zprimeWidth=specifier; zprimeWidth.ReplaceAll("1000", "100"); TString nameZprime="/afs/naf.desy.de/group/cms/scratch/tophh/RecentAnalysisRun8TeV_doubleKinFit/zprime/"; if(decayChannel.compare("electron")==0) nameZprime+="elec"; else nameZprime+="muon"; nameZprime+="DiffXSecZprimeM"+zprimeMass+"W"+zprimeWidth+"Summer12PF.root"; // event weight wrt luminosity double zPrimeLumiWeight=1.; if (zprimeMass=="1000") zPrimeLumiWeight=(xSecSF*5*luminosity)/104043; // naming of oututfile TString xSecSFstr=""; if (xSecSF==0.5 ) xSecSFstr="x0p5"; else if (xSecSF==0.25) xSecSFstr="x0p25"; else if (xSecSF==0.1 ) xSecSFstr="x0p1"; else if (xSecSF==0.03) xSecSFstr="x0p03"; else if (xSecSF>1. ) xSecSFstr="x"+getTStringFromDouble(xSecSF,0); if(zprime) outNameExtension="andM"+zprimeMass+"W"+zprimeWidth+xSecSFstr+"Zprime"; // sample iteration limit int kLast =kSAToptW; int kZprime=kLast+1; if(zprime) kLast=kZprime; if(zprime&&zPrimeLumiWeight==1){ std::cout << "ERROR: chosen zprime weight is exactly 1!" << std::endl; exit(0); } // ------------------------- // !!! choose luminosity !!! // ------------------------- TString lum = getTStringFromInt(roundToInt(luminosity)); // ----------------------------------------- // !!! add all contributing samples here !!! // ----------------------------------------- TString inputFolder = "/afs/naf.desy.de/group/cms/scratch/tophh/RecentAnalysisRun8TeV_doubleKinFit/"; // save all default top analysis samples in files_ files_ = getStdTopAnalysisFiles(inputFolder, sysNo, dataFile, decayChannel); // remove combined file dor single Top & DiBoson if(files_.count(kSTop )>0)files_.erase(kSTop ); if(files_.count(kDiBos)>0)files_.erase(kDiBos); // remove combined QCD file for electron channel if(decayChannel.compare("electron")==0&&files_.count(kQCD)>0) files_.erase(kQCD); // remove all QCD files to be consistent with later treatment if(files_.count(kQCD)>0) files_.erase(kQCD); if(decayChannel.compare("electron")==0){ for(int sample = kQCDEM1; sample<=kQCDBCE3; sample++){ if(files_.count(sample)>0) files_.erase(sample); } } // add zprime if(zprime) files_[kZprime]=new (TFile)(nameZprime); // exchange default ttbar files with the reweighted ones if(useReweightedTop){ files_[kSig]=new (TFile)(nameTtbarReweighted ); files_[kBkg]=new (TFile)(nameTtbarBGReweighted); } // ----------------------------------------- // get list of all plots to be considered // ----------------------------------------- std::vector<TString> plotList_; TString currentFolder =""; TString currentPlot =""; if(verbose>0) std::cout << std::endl << "searching for all plots in file " << files_[kData]->GetName() << std::endl; // go to data file for getting plot names files_[kData]->cd(); // loop objects in file TIter fileIterator(gDirectory->GetListOfKeys()); if(verbose>2){ std::cout << "looping objects in in "; gDirectory->pwd(); } TKey *fileKey; int count=0; while( (fileKey = (TKey*)fileIterator()) ){ ++count; if(verbose>2) std::cout << "folderObject #" << count; TObject *fileObject = fileKey->ReadObj(); // check if object is a directory if(!(fileObject->InheritsFrom("TDirectory"))&&(verbose>2)) std::cout << " is no directory" << count << std::endl; if(fileObject->InheritsFrom("TDirectory")){ currentFolder = (TString)fileObject->GetName(); if(verbose>2) std::cout << " ("+currentFolder+")" << std::endl; // go to directory ((TDirectory*)fileObject)->cd(); if(verbose>2){ std::cout << "looping objects in in "; gDirectory->pwd(); } TIter folderIterator(gDirectory->GetListOfKeys()); TKey *folderKey; int count2=0; while( (folderKey = (TKey*)folderIterator()) ) { ++count2; TObject *folderObject = folderKey->ReadObj(); currentPlot = (TString)folderObject->GetName(); if(verbose>2) std::cout << "plotObject #" << count2 << " ("+currentPlot+")" << std::endl; // check if object is a TH1 if(folderObject->InheritsFrom("TH1")){ if(verbose>2) std::cout << "inherits from TH1"; // check if TH2 and neglect because a simple // re-smearing is here not possible if((folderObject->InheritsFrom("TH2"))&&(verbose>2)) std::cout << " and from TH2" << std::endl; else{ if(verbose>2) std::cout << " and NOT from TH2" << std::endl; // add to list of plots if(verbose>2) std::cout << "will be added to list of output plots" << std::endl; plotList_.push_back(currentFolder+"/"+currentPlot); } } } } } // close data file after getting plot names files_[kData]->Close(); // remove data file from list of considered files if(files_.count(kData )>0)files_.erase(kData ); // print list of files considered if(verbose>0){ std::cout << std::endl << "the following files will be considered: " << std::endl; // loop files for(int sample = kSig; sample<=kLast; sample++){ // check existence of folder in all existing files if(files_.count(sample)>0){ std::cout << files_[sample]->GetName() << std::endl; } } } // print out the name of all plots if(verbose>0){ std::cout << std::endl << "list of all plots to be considered: " << std::endl; // loop list of plots for(unsigned int plot=0; plot<plotList_.size(); ++plot){ std::cout << "\"" << plotList_[plot] << "\"" << std::endl; } std::cout << plotList_.size() << " plots in total" << std::endl; } // --------------------------------------- // !!! load all hists !!! // --------------------------------------- unsigned int N1Dplots=plotList_.size(); int Nplots=0; if(verbose>0) std::cout << std::endl << "loading plots: " << std::endl; // a) for std analysis file (& reweighted ttbar) getAllPlots(files_, plotList_, histo_, histo2_, N1Dplots, Nplots, verbose-1); if(verbose>0){ std::cout << Nplots << " plots loaded from " << plotList_.size(); std::cout << " requested" << std::endl << "empty plots are not counted" << std::endl; } // b) for zprime if(zprime){ for(unsigned int plot=0; plot<plotList_.size(); ++plot){ histo_[plotList_[plot]][kZprime] = (TH1F*)(files_[kZprime]->Get(plotList_[plot])); } } // --------------------------------------- // !!! definition of output file(name) !!! // --------------------------------------- //TString outputfile="/afs/naf.desy.de/user/g/goerner/WGspace/RecentAnalysisRun8TeV_doubleKinFit/pseudodata/"+(TString)decayChannel+"PseudoData"+lum+"pb"+outNameExtension+"8TeV.root"; TString outputfile="/afs/naf.desy.de/user/g/goerner/WGspace/RecentAnalysisRun8TeV_doubleKinFit/pseudodata/"+pseudoDataFileName(specifier, decayChannel); TFile* out = new TFile(outputfile, "recreate"); if(verbose>0) std::cout << std::endl << "outputfile: " << outputfile << std::endl; poisson(histo_, plotList_, decayChannel, *out, luminosity, verbose, smear, useReweightedTop, avWeight, zprime, zPrimeLumiWeight); // free memory for(std::map< TString, std::map <unsigned int, TH1F*> >::iterator histo=histo_.begin(); histo!=histo_.end(); ++histo){ for(std::map <unsigned int, TH1F*>::iterator histoSub=histo->second.begin(); histoSub!=histo->second.end(); ++histoSub){ if(histoSub->second) delete histoSub->second; } histo->second.clear(); } histo_ .clear(); for(std::map< TString, std::map <unsigned int, TH2F*> >::iterator histo2=histo2_.begin(); histo2!=histo2_.end(); ++histo2){ for(std::map <unsigned int, TH2F*>::iterator histo2Sub=histo2->second.begin(); histo2Sub!=histo2->second.end(); ++histo2Sub){ if(histo2Sub->second) delete histo2Sub->second; } histo2->second.clear(); } histo2_ .clear(); for(std::map<unsigned int, TFile*>::const_iterator file=files_.begin(); file!=files_.end(); ++file){ if(file->second){ file->second->Close(); delete file->second; } } files_ .clear(); out->Close(); delete out; }
void DrawLogInclusivePlots(TString ALGO) { TFile *f; TString ss(ALGO+"canvasOutFile.root"); f = new TFile(ss); TCanvas *c c = (TCanvas*)f->Get("_R80570"); TString algoTitle; if (ALGO=="KT6") algoTitle = "k_{T} D = 0.6"; else algoTitle = "SISCone R = 0.7"; TList *li = (TList*)gPad->GetListOfPrimitives(); TObject *obj; TIter next(li); TH1D *histList[100], *htmp; int i,j,N; while ((obj = (TObject*)next())) { TString cname = obj->ClassName(); TString name = obj->GetName(); cout << cname <<" "<<name<<endl; if (cname=="TH1D") { histList[N] = (TH1D*)gPad->FindObject(obj); histList[N]->SetFillColor(0); histList[N]->SetFillStyle(0); N++; } } TCanvas *c = new TCanvas("c","c"); gPad->SetLogx(); gPad->SetLogy(); histList[0]->SetMaximum(1e+10); histList[0]->SetTitle(""); histList[0]->GetXaxis()->SetTitle("jet p_{T} (GeV)"); histList[0]->GetXaxis()->SetTitleFont(42); histList[0]->GetXaxis()->SetLabelFont(42); histList[0]->GetXaxis()->SetTitleSize(0.05); histList[0]->GetXaxis()->SetLabelSize(0.05); histList[0]->GetXaxis()->SetMoreLogLabels(); histList[0]->GetXaxis()->SetNoExponent(); histList[0]->GetYaxis()->SetTitle("d^{2}#sigma/dp_{T}dy (fb/GeV)"); histList[0]->GetYaxis()->SetTitleFont(42); histList[0]->GetYaxis()->SetLabelFont(42); histList[0]->GetYaxis()->SetTitleSize(0.05); histList[0]->GetYaxis()->SetLabelSize(0.05); histList[0]->GetYaxis()->SetNdivisions(505); histList[0]->SetLineWidth(2); histList[0]->SetLineStyle(1); histList[0]->SetLineColor(2); histList[1]->SetLineColor(1); histList[1]->SetMarkerColor(1); histList[1]->SetLineWidth(1); histList[1]->SetMarkerStyle(20); histList[1]->SetLineStyle(1); histList[2]->SetLineWidth(2); histList[2]->SetLineStyle(1); histList[2]->SetLineColor(2); histList[3]->SetLineColor(1); histList[3]->SetMarkerColor(1); histList[3]->SetLineWidth(1); histList[3]->SetMarkerStyle(24); histList[3]->SetLineStyle(1); histList[4]->SetLineWidth(2); histList[4]->SetLineStyle(1); histList[4]->SetLineColor(2); histList[5]->SetLineColor(1); histList[5]->SetMarkerColor(1); histList[5]->SetLineWidth(1); histList[5]->SetMarkerStyle(21); histList[5]->SetLineStyle(1); histList[0]->Draw("C"); histList[1]->Draw("same"); histList[2]->Draw("sameC"); histList[3]->Draw("same"); histList[4]->Draw("sameC"); histList[5]->Draw("same"); TLegend *leg = new TLegend(0.47,0.75,0.92,0.9); leg->SetTextFont(42); leg->AddEntry(histList[1],"0.00 #leq |y| < 0.55 ( #times 32 )","P"); leg->AddEntry(histList[3],"1.10 < |y| < 1.70 ( #times 16 )","P"); leg->AddEntry(histList[5],"1.70 < |y| < 2.50 ( #times 8 )","P"); leg->AddEntry(histList[0],"Theory","L"); leg->SetFillColor(0); leg->SetBorderSize(0); leg->Draw(); TPaveText *pave3 = new TPaveText(0.2,0.2,0.45,0.45,"NDC"); pave3->SetTextFont(42); pave3->AddText("CMS preliminary"); pave3->AddText(algoTitle); pave3->AddText("#sqrt{s} = 10 TeV"); pave3->AddText(""); pave3->AddText("#int L dt = 10 pb^{-1}"); pave3->SetFillColor(0); pave3->SetBorderSize(0); pave3->SetTextSize(0.04); pave3->Draw(); c->Print(ALGO+"_LogLogComparison.eps"); }
void recupThePlots(){ // TDirectory *theDr = (TDirectory*) myFile->Get("eleIDdir");///denom_pt/fit_eff_plots"); //theDr->ls(); cout << "coucou" << theOutFileName << endl; TFile *myOutFile = new TFile(theOutFileName,"RECREATE"); TSystemDirectory dir(thePath, thePath); TSystemFile *file; TString fname; TIter next(dir.GetListOfFiles()); while (((file=(TSystemFile*)next()))) { fname = file->GetName(); if ((fname.BeginsWith("TnP"))&&fname.Contains("data")) { cout << "--------------------"<< "\n"; cout << fname << "\n"; TFile *myFile = new TFile(fname); TIter nextkey(myFile->GetListOfKeys()); TKey *key; while ((key = (TKey*)nextkey())) { // cout << key << "\n"; TString theTypeClasse = key->GetClassName(); TString theNomClasse = key->GetTitle(); cout << "theTypeClasse: "<< theTypeClasse << " , " << theNomClasse << "\n"; if ( theTypeClasse == "TDirectoryFile" ){ // cout << "we are here 1" << "\n"; TDirectory *theDr = (TDirectory*) myFile->Get(theNomClasse); TIter nextkey2(theDr->GetListOfKeys()); TKey *key2; while ((key2 = (TKey*)nextkey2())) { TString theTypeClasse2 = key2->GetClassName(); TString theNomClasse2 = key2->GetTitle(); if ( theTypeClasse == "TDirectoryFile" || theTypeClasse == "TGraphAsymmErrors" ){ TDirectory *theDr2 = (TDirectory*) myFile->Get(theNomClasse+"/"+theNomClasse2+"/fit_eff_plots"); TIter nextkey3(theDr2->GetListOfKeys()); TKey *key3; while ((key3 = (TKey*)nextkey3())) { TString theTypeClasse3 = key3->GetClassName(); TString theNomClasse3 = key3->GetName(); cout << "type = " << theTypeClasse3 << " nom = " << theNomClasse3 << endl; TCanvas *theCanvas = (TCanvas*) myFile->Get(theNomClasse+"/"+theNomClasse2+"/fit_eff_plots/"+theNomClasse3); TIter nextObject(theCanvas->GetListOfPrimitives()); TObject *obj; while ((obj = (TObject*)nextObject())) { if (obj->InheritsFrom("TGraphAsymmErrors")) { cout << "histo: " << obj->GetName() << endl; myOutFile->cd(); obj->Write(theNomClasse2+"_"+theNomClasse3); myFile->cd(); } if (obj->InheritsFrom("TH2F")) { cout << "the TH2F = " << obj->GetName() << endl; myOutFile->cd(); obj->Write(theNomClasse2+"_"+theNomClasse3); myFile->cd(); } } } } } } } delete myFile; } } myOutFile->Close(); }
void drawLoop( TDirectory *target, TList *sourcelist, TCanvas *c1 ) { TString path( (char*)strstr( target->GetPath(), ":" ) ); path.Remove( 0, 2 ); TString sysString(path);sysString.Prepend(baseName->Data()); TFile *first_source = (TFile*)sourcelist->First(); first_source->cd( path ); TDirectory *current_sourcedir = gDirectory; //gain time, do not add the objects in the list in memory Bool_t status = TH1::AddDirectoryStatus(); TH1::AddDirectory(kFALSE); // loop over all keys in this directory TIter nextkey( current_sourcedir->GetListOfKeys() ); TKey *key, *oldkey=0; while ( (key = (TKey*)nextkey())) { //keep only the highest cycle number for each key if (oldkey && !strcmp(oldkey->GetName(),key->GetName())) continue; // read object from first source file first_source->cd( path ); TObject *obj = key->ReadObj(); if ( obj->IsA()->InheritsFrom( "TH1" ) && !obj->IsA()->InheritsFrom("TH2") ) { // descendant of TH1 -> merge it gLegend = new TLegend(.7,.15,.95,.4,""); gLegend->SetHeader(gDirectory->GetName()); Color_t color = 1; Style_t style = 22; TH1 *h1 = (TH1*)obj; h1->SetLineColor(color); h1->SetMarkerStyle(style); h1->SetMarkerColor(color); h1->Draw(); TString tmpName(first_source->GetName()); gLegend->AddEntry(h1,tmpName,"LP"); c1->Update(); // loop over all source files and add the content of the // correspondant histogram to the one pointed to by "h1" TFile *nextsource = (TFile*)sourcelist->After( first_source ); while ( nextsource ) { // make sure we are at the correct directory level by cd'ing to path nextsource->cd( path ); TKey *key2 = (TKey*)gDirectory->GetListOfKeys()->FindObject(h1->GetName()); if (key2) { TH1 *h2 = (TH1*)key2->ReadObj(); color++; style++; h2->SetLineColor(color); h2->SetMarkerStyle(style); h2->SetMarkerColor(color); h2->Draw("same"); TString tmpName(nextsource->GetName()); gLegend->AddEntry(h2,tmpName,"LP"); gLegend->Draw("same"); c1->Update(); //- delete h2; } nextsource = (TFile*)sourcelist->After( nextsource ); } } else if ( obj->IsA()->InheritsFrom( "TH2" ) ) { // descendant of TH2 -> merge it gLegend = new TLegend(.85,.15,1.0,.30,""); gLegend->SetHeader(gDirectory->GetName()); Color_t color = 1; Style_t style = 22; TH2 *h1 = (TH2*)obj; h1->SetLineColor(color); h1->SetMarkerStyle(style); h1->SetMarkerColor(color); h1->Draw(); TString tmpName(first_source->GetName()); gLegend->AddEntry(h1,tmpName,"LP"); c1->Update(); // loop over all source files and add the content of the // correspondant histogram to the one pointed to by "h1" TFile *nextsource = (TFile*)sourcelist->After( first_source ); while ( nextsource ) { // make sure we are at the correct directory level by cd'ing to path nextsource->cd( path ); TKey *key2 = (TKey*)gDirectory->GetListOfKeys()->FindObject(h1->GetName()); if (key2) { TH2 *h2 = (TH2*)key2->ReadObj(); color++; style++; h2->SetLineColor(color); h2->SetMarkerStyle(style); h2->SetMarkerColor(color); h2->Draw("same"); TString tmpName(nextsource->GetName()); gLegend->AddEntry(h2,tmpName,"LP"); gLegend->Draw("same"); c1->Update(); //- delete h2; } nextsource = (TFile*)sourcelist->After( nextsource ); } } else if ( obj->IsA()->InheritsFrom( "TGraph" ) ) { obj->IsA()->Print(); gLegend = new TLegend(.7,.15,.95,.4,""); gLegend->SetHeader(gDirectory->GetName()); Color_t color = 1; Style_t style = 22; TGraph *h1 =(TGraph*)obj; h1->SetLineColor(color); h1->SetMarkerStyle(style); h1->SetMarkerColor(color); h1->GetHistogram()->Draw(); h1->Draw(); TString tmpName(first_source->GetName()); gLegend->AddEntry(h1,tmpName,"LP"); c1->Update(); // loop over all source files and add the content of the // correspondant histogram to the one pointed to by "h1" TFile *nextsource = (TFile*)sourcelist->After( first_source ); while ( nextsource ) { // make sure we are at the correct directory level by cd'ing to path nextsource->cd( path ); TKey *key2 = (TKey*)gDirectory->GetListOfKeys()->FindObject(h1->GetName()); if (key2) { TGraph *h2 = (TGraph*)key2->ReadObj(); color++; style++; h2->SetLineColor(color); h2->SetMarkerStyle(style); h2->SetMarkerColor(color); h2->Draw("same"); TString tmpName(nextsource->GetName()); gLegend->AddEntry(h2,tmpName,"LP"); gLegend->Draw("same"); c1->Update(); //- delete h2; } nextsource = (TFile*)sourcelist->After( nextsource ); } } else if ( obj->IsA()->InheritsFrom( "TTree" ) ) { std::cout << "I don't draw trees" << std::endl; } else if ( obj->IsA()->InheritsFrom( "TDirectory" ) ) { // it's a subdirectory std::cout << "Found subdirectory " << obj->GetName() << std::endl; // create a new subdir of same name and title in the target file target->cd(); TDirectory *newdir = target->mkdir( obj->GetName(), obj->GetTitle() ); // create a new subdir of same name in the file system TString newSysString(sysString+"/"+obj->GetName()); if(makeGraphic) gSystem->mkdir(newSysString.Data(),kTRUE); // newdir is now the starting point of another round of merging // newdir still knows its depth within the target file via // GetPath(), so we can still figure out where we are in the recursion drawLoop( newdir, sourcelist, c1 ); } else { // object is of no type that we know or can handle std::cout << "Unknown object type, name: " << obj->GetName() << " title: " << obj->GetTitle() << std::endl; } // now write the merged TCanvas (which is "in" obj) to the target file // note that this will just store obj in the current directory level, // which is not persistent until the complete directory itself is stored // by "target->Write()" below if ( obj ) { target->cd(); if ( obj->IsA()->InheritsFrom( "TH1") || obj->IsA()->InheritsFrom("TGraph")) { // && !obj->IsA()->InheritsFrom("TH2") ) { TString newName(obj->GetName()); newName.ReplaceAll("(",1,"_",1); newName.ReplaceAll(")",1,"_",1); c1->SetName(newName); c1->Write( c1->GetName(),TObject::kOverwrite ); if(makeGraphic) { if (gROOT->IsBatch()) { c1->Print("temp.eps"); gSystem->Exec("pstopnm -ppm -xborder 0 -yborder 0 -portrait temp.eps"); char tempCommand[200]; sprintf(tempCommand,"ppmtogif temp.eps001.ppm > %s/%s.gif",sysString.Data(),c1->GetName()); gSystem->Exec(tempCommand); } else { c1->Print(sysString + "/" + TString(c1->GetName())+".gif"); } } } } //if(gLegend) delete gLegend; } // while ( ( TKey *key = (TKey*)nextkey() ) ) // save modifications to target file target->SaveSelf(kTRUE); TH1::AddDirectory(status); }
void MergeRootfile(std::map<std::pair<std::string, std::string>, TObject*>& outputMap, std::vector<std::pair<std::string, TObject*> >& outputVec, TDirectory *target, TFile *source) { using namespace std; string path(target->GetPath()); path = path.substr(path.find(":") + 1); source->cd(path.c_str()); TDirectory *current_sourcedir = gDirectory; //gain time, do not add the objects in the list in memory Bool_t status = TH1::AddDirectoryStatus(); TH1::AddDirectory(kFALSE); // loop over all keys in this directory TIter nextkey( current_sourcedir->GetListOfKeys() ); TKey *key, *oldkey = 0; while(key = (TKey*)nextkey()) { //keep only the highest cycle number for each key if (oldkey && !strcmp(oldkey->GetName(), key->GetName())) continue; oldkey = key; // read object from source file source->cd(path.c_str()); TObject *obj = key->ReadObj(); if(obj->IsA()->InheritsFrom(TH1::Class())) { if(verbosity >= 4) { printf("| Found TH1: %s\n", obj->GetName()); fflush(stdout); } string path(target->GetPath()); pair<string, string> okey(path.substr(path.find(':') + 2), obj->GetName()); //cout << okey.first << "\t" << okey.second << endl; if(outputMap.find(okey) == outputMap.end()) { outputVec.push_back(make_pair(path.substr(path.find(':') + 2), obj)); outputMap[okey] = obj; } else { ((TH1*)outputMap[okey])->Add((TH1*)obj); ((TH1*)obj)->Delete(); } } else if(obj->IsA()->InheritsFrom(TTree::Class())) { string path(target->GetPath()); if(verbosity >= 4) { printf("| Found Tree: %s\n", obj->GetName()); fflush(stdout); } pair<string, string> okey(path.substr(path.find(':') + 2), obj->GetName()); if(outputMap.find(okey) == outputMap.end()) { string fname(okey.first); fname = fname + "_" + obj->GetName() + "tmpfile"; for(size_t pos; (pos = fname.find('/')) != size_t(-1); ) fname[pos] = '_'; tmpFiles.push_back(make_pair(fname, new TFile(fname.c_str(), "RECREATE"))); TTree* tree = ((TTree*)obj)->CloneTree(); ((TTree*)obj)->GetListOfClones()->Remove(tree); ((TTree*)obj)->ResetBranchAddresses(); tree->ResetBranchAddresses(); outputVec.push_back(make_pair(path.substr(path.find(':') + 2), (TObject*)tree)); outputMap[okey] = (TObject*)tree; } else { TTree* tm = (TTree*)outputMap[okey]; TTree* ts = (TTree*)obj; tm->CopyAddresses(ts); for(int i = 0; i < ts->GetEntries(); i++) { ts->GetEntry(i); tm->Fill(); } ts->ResetBranchAddresses(); if (tm->GetTreeIndex()) tm->GetTreeIndex()->Append(ts->GetTreeIndex(), kTRUE); ((TTree*)obj)->Delete(); } } else if(obj->IsA()->InheritsFrom(TDirectory::Class())) { if(verbosity >= 3) { printf("Hadding Directory: %s\n", ((TDirectory*)obj)->GetPath()); fflush(stdout); } string path(((TDirectory*)obj)->GetPath()); pair<string, string> okey(path.substr(path.find(':') + 2), " -------- "); if(outputMap.find(okey) == outputMap.end()) { outputVec.push_back(make_pair(path.substr(path.find(':') + 2), (TDirectory*)0)); outputMap[okey] = 0; } MergeRootfile(outputMap, outputVec, (TDirectory*)obj, source); } else { printf("Unknown object type, name: %s title: %s\n", obj->GetName(), obj->GetTitle()); fflush(stdout); } } // while ( ( TKey *key = (TKey*)nextkey() ) ) }
void makeUnfoldingSystematicsComparisonPlots (int whichobservable, int whichjet, int whichlepton, int inclusive) { //Open the file and form the name string fileSystematics; string suffix="/gpfs/cms/data/2011/Systematics/postApproval_v58_Journal/"; //string suffix="/tmp/"; if (whichlepton==1) suffix=suffix+"ele/"; if (whichlepton==2) suffix=suffix+"muo/"; // setTDRStyle (); gStyle->SetErrorX(0); gStyle->SetPadGridX(0); gStyle->SetPadGridY(0); bool absoluteNormalization = true; int lepton = 3; //1 -> electron, 2-> muon , 3 -> combined reults! bool addLumiUncertainties = true; double lumiError = 0.025; int use_case = whichobservable; int whichjet = whichjet; string version = "_v2_32"; //string s = "/afs/infn.it/ts/user/marone/html/ZJets/FinalPlotsForAN/v41/SVDBayes/"; string s="/afs/infn.it/ts/user/marone/html/ZJets/FinalPlotsForAN/v58_Journal/UnfoldingSyst/ele/"; // string s = "/gpfs/cms/users/schizzi/EleMuComparisonPlots/PostUnfolding/"; string eleplotpath = "/gpfs/cms/users/schizzi/Systematics/ele/"; string muoplotpath = "/gpfs/cms/users/schizzi/Systematics/muo/"; gStyle->SetOptStat (0); TCanvas *plots = new TCanvas ("plots", "EB", 200, 100, 600, 800); //DATA: //string elepathFile ="/gpfs/cms/data/2011/Unfolding/testReferenceMu.root"; //string muopathFile ="/gpfs/cms/data/2011/Unfolding/testMu.root"; string elepathFile ="/gpfs/cms/data/2011/Unfolding/UnfoldingOfficialV58_afterCWR.root"; string muopathFile ="/gpfs/cms/data/2011/Unfolding/UnfoldingOfficialV58_BinWidth.root"; string thirdpathFile ="/gpfs/cms/data/2011/Unfolding/UnfoldingOfficialV58_SherpaV2.root"; if (whichlepton==2){ elepathFile ="/gpfs/cms/data/2011/Unfolding/UnfoldingOfficialV58_afterCWRMu.root"; muopathFile ="/gpfs/cms/data/2011/Unfolding/UnfoldingOfficialV58_BinWidthMu.root"; thirdpathFile ="/gpfs/cms/data/2011/Unfolding/UnfoldingOfficialV58_SherpaV2Mu.root"; s="/afs/infn.it/ts/user/marone/html/ZJets/FinalPlotsForAN/v58_Journal/UnfoldingSyst/muo/"; } //string elepathFile ="/gpfs/cms/data/2011/Unfolding/UnfoldingOfficialV57_3NoSQRT.root"; //string muopathFile ="/gpfs/cms/data/2011/Unfolding/UnfoldingOfficialV57_3NoMCToy.root"; TFile *histof = TFile::Open (elepathFile.c_str ()); histof->cd (""); TDirectory *dir = gDirectory; TList *mylist = (TList *) dir->GetListOfKeys (); TIter iter (mylist); TObject *tobj = 0; TFile *histof2 = TFile::Open (thirdpathFile.c_str ()); histof2->cd (""); TDirectory *dir2 = gDirectory; TList *mylist2 = (TList *) dir2->GetListOfKeys (); TIter iter2 (mylist); TObject *tobj2 = 0; TFile *histofmuo = TFile::Open (muopathFile.c_str ()); string stringmatch; string systPathFile; string systPathFileMuo; histof->cd (""); int i = 0; // solo di servizio quando debuggo... while ((tobj = iter.Next ())) { string name = tobj->GetName (); if (use_case == 1) { // Jet Multiplicity stringmatch = "JetMultiplicityUnfolded"; systPathFile = eleplotpath + "systematicsEff_jetMult" + version + ".txt"; systPathFileMuo = muoplotpath + "systematicsEff_jetMult" + version + ".txt"; fileSystematics = suffix+"systematicsUnfReweight_jetMult" + version + ".txt"; } if (use_case == 2) { // Jet Pt if (whichjet == 1) { stringmatch = "jReco_leading"; systPathFile = eleplotpath + "systematicsEff_jet1Pt" + version + ".txt"; systPathFileMuo = muoplotpath + "systematicsEff_jet1Pt" + version + ".txt"; fileSystematics = suffix+"systematicsUnfReweight_jet1Pt" + version + ".txt"; } if (whichjet == 2) { stringmatch = "jReco_subleading"; systPathFile = eleplotpath + "systematicsEff_jet2Pt" + version + ".txt"; systPathFileMuo = muoplotpath + "systematicsEff_jet2Pt" + version + ".txt"; fileSystematics = suffix+"systematicsUnfReweight_jet2Pt" + version + ".txt"; } if (whichjet == 3) { stringmatch = "jReco_subsubleading"; systPathFile = eleplotpath + "systematicsEff_jet3Pt" + version + ".txt"; systPathFileMuo = muoplotpath + "systematicsEff_jet3Pt" + version + ".txt"; fileSystematics = suffix+"systematicsUnfReweight_jet3Pt" + version + ".txt"; } if (whichjet == 4) { stringmatch = "jReco_subsubsubleading"; systPathFile = eleplotpath + "systematicsEff_jet4Pt" + version + ".txt"; systPathFileMuo = muoplotpath + "systematicsEff_jet4Pt" + version + ".txt"; fileSystematics = suffix+"systematicsUnfReweight_jet4Pt" + version + ".txt"; } } if (use_case == 3) { // Jet Eta if (whichjet == 1) { stringmatch = "jReco_leadingeta"; systPathFile = eleplotpath + "systematicsEff_jet1Eta" + version + ".txt"; systPathFileMuo = muoplotpath + "systematicsEff_jet1Eta" + version + ".txt"; fileSystematics = suffix+"systematicsUnfReweight_jet1Eta" + version + ".txt"; } if (whichjet == 2) { stringmatch = "jReco_subleadingeta"; systPathFile = eleplotpath + "systematicsEff_jet2Eta" + version + ".txt"; systPathFileMuo = muoplotpath + "systematicsEff_jet2Eta" + version + ".txt"; fileSystematics = suffix+"systematicsUnfReweight_jet2Eta" + version + ".txt"; } if (whichjet == 3) { stringmatch = "jReco_subsubleadingeta"; systPathFile = eleplotpath + "systematicsEff_jet3Eta" + version + ".txt"; systPathFileMuo = muoplotpath + "systematicsEff_jet3Eta" + version + ".txt"; fileSystematics = suffix+"systematicsUnfReweight_jet3Eta" + version + ".txt"; } if (whichjet == 4) { stringmatch = "jReco_subsubsubleadingeta"; systPathFile = eleplotpath + "systematicsEff_jet4Eta" + version + ".txt"; systPathFileMuo = muoplotpath + "systematicsEff_jet4Eta" + version + ".txt"; fileSystematics = suffix+"systematicsUnfReweight_jet4Eta" + version + ".txt"; } } if (use_case == 4) { // Ht if (whichjet == 1) { stringmatch = "HReco_leading"; systPathFile = eleplotpath + "systematicsEff_jet1Ht" + version + ".txt"; systPathFileMuo = muoplotpath + "systematicsEff_jet1Ht" + version + ".txt"; fileSystematics = suffix+"systematicsUnfReweight_jet1Ht" + version + ".txt"; } if (whichjet == 2) { stringmatch = "HReco_subleading"; systPathFile = eleplotpath + "systematicsEff_jet2Ht" + version + ".txt"; systPathFileMuo = muoplotpath + "systematicsEff_jet2Ht" + version + ".txt"; fileSystematics = suffix+"systematicsUnfReweight_jet2Ht" + version + ".txt"; } if (whichjet == 3) { stringmatch = "HReco_subsubleading"; systPathFile = eleplotpath + "systematicsEff_jet3Ht" + version + ".txt"; systPathFileMuo = muoplotpath + "systematicsEff_jet3Ht" + version + ".txt"; fileSystematics = suffix+"systematicsUnfReweight_jet3Ht" + version + ".txt"; } if (whichjet == 4) { stringmatch = "HReco_subsubsubleading"; fileSystematics = suffix+"systematicsUnfReweight_jet4Ht" + version + ".txt"; systPathFile = eleplotpath + "systematicsEff_jet4Ht" + version + ".txt"; systPathFileMuo = muoplotpath + "systematicsEff_jet4Ht" + version + ".txt"; } } if (name == stringmatch) { cout << "CONFIGURATION:" << endl; cout << "stringmatch: " <<stringmatch<< endl; cout << "systPathFile: " <<systPathFile<< endl; TH1D *leading; gDirectory->GetObject (name.c_str (), leading); leading->SetMarkerSize(0.9); leading->Sumw2(); histofmuo->cd (""); TH1D *leadingmuo; gDirectory->GetObject (name.c_str (), leadingmuo); leadingmuo->SetMarkerSize(0.9); leadingmuo->Sumw2(); histof2->cd (""); TH1D *leadingthird; gDirectory->GetObject (name.c_str (), leadingthird); leadingmuo->SetMarkerSize(0.9); leadingmuo->Sumw2(); if (inclusive==1){ TH1D* leadingIncl=turnExclusiveHistoInInclusive(leading); TH1D* leadingmuoIncl=turnExclusiveHistoInInclusive(leadingmuo); TH1D* leadingthirdIncl=turnExclusiveHistoInInclusive(leadingthird); leading=leadingIncl; leadingmuo=leadingmuoIncl; leadingthird=leadingthirdIncl; } // /// EFFICIENCY Systematics: // for (int nnbins=1;nnbins<=leading->GetNbinsX ();nnbins++) { // cout << fabs(leading->GetBinContent(nnbins)-leadingmuo->GetBinContent(nnbins))/(2*leading->GetBinContent(nnbins)) << endl; // cout << leading->GetBinContent(nnbins)-leadingmuo->GetBinContent(nnbins) << endl; // } // read from file --------------------------------------------- double dat; ifstream inM; cout << "reading ... " << systPathFile << endl; inM.open (systPathFile.c_str ()); std::vector < double >systTmpM; while (1) { inM >> dat; if (!inM.good ()) break; systTmpM.push_back (dat); } inM.close (); // ------------------------------------------------------------ // read from file --------------------------------------------- ifstream inM2; cout << "reading ... " << systPathFileMuo << endl; inM2.open (systPathFileMuo.c_str ()); std::vector < double >systTmpMmuo; while (1) { inM2 >> dat; if (!inM2.good ()) break; systTmpMmuo.push_back (dat); } inM2.close (); // ------------------------------------------------------------ TH1D *leadingRatioSystematics; leadingRatioSystematics = (TH1D *) leading->Clone ("leading"); if (systTmpM.size () != leadingRatioSystematics->GetNbinsX ()) cout << "TE SON MONA! WRONG NUMBER OF BINS (# syst from file->" <<systTmpM.size()<<" - # bins->"<<leadingRatioSystematics->GetNbinsX()<<")"<<endl; for (int i = 0; i < leadingRatioSystematics->GetNbinsX (); i++) { //leadingRatioSystematics->SetBinContent(i + 1, 1.0); //leadingRatioSystematics->SetBinError (i + 1,sqrt(systTmpM[i]*systTmpM[i] + systTmpMmuo[i]*systTmpMmuo[i])); // leadingRatioSystematics->SetBinContent(i + 1, 1.0); // leadingRatioSystematics->SetBinError (i + 1,max(systTmpM[i]/100.0,systTmpMmuo[i]/100.0)); } plots->cd (); TPad *pad1 = new TPad("pad1","pad1",0.01,0.3,0.99,0.99); pad1->Draw(); pad1->cd(); pad1->SetTopMargin(0.1); pad1->SetBottomMargin(0.0); pad1->SetLeftMargin(0.2); pad1->SetRightMargin(0.0); pad1->SetFillStyle(0); if (use_case !=3) pad1->SetLogy(1); else pad1->SetLogy(0); if (use_case ==3){ leading->SetMinimum((0.5-0.05*(whichjet-1))*leading->GetMinimum()); leading->SetMaximum((1.25+0.35*(whichjet-1))*leading->GetMaximum()); } leading->SetLineColor (kRed+1); leading->SetMarkerStyle (20); leading->SetFillColor (kRed+1); leading->SetMarkerColor (kRed+1); leading->GetXaxis ()->SetTitleOffset (1.1); leading->GetXaxis ()->SetTitleSize (0.05); leading->GetXaxis ()->SetLabelSize (0.0); leading->GetXaxis ()->SetLabelFont (42); leading->GetXaxis ()->SetTitleFont (42); leading->GetYaxis ()->SetTitleOffset (1.); leading->GetYaxis ()->SetTitleSize (0.07); leading->GetYaxis ()->SetLabelSize (0.06); leading->GetYaxis ()->SetLabelFont (42); leading->GetYaxis ()->SetTitleFont (42); leading->SetTitle (); leading->GetXaxis ()->SetTitle (); if (use_case ==1) { if (absoluteNormalization) leading->GetYaxis ()->SetTitle ("d#sigma/dN [pb]"); else { if (lepton == 1) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow e^{+}e^{-}}) d#sigma/dN"); if (lepton == 2) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow #mu^{+}#mu^{-}}) d#sigma/dN"); if (lepton == 3) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow l^{+}l^{-}}) d#sigma/dN"); } } if (use_case ==2) { if (absoluteNormalization) leading->GetYaxis ()->SetTitle ("d#sigma/dp_{T} [pb/GeV]"); else { if (lepton == 1) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow e^{+}e^{-}}) d#sigma/dp_{T}"); if (lepton == 2) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow #mu^{+}#mu^{-}}) d#sigma/dp_{T}"); if (lepton == 3) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow l^{+}l^{-}}) d#sigma/dp_{T}"); } } if (use_case ==3) { if (absoluteNormalization) leading->GetYaxis ()->SetTitle ("d#sigma/d#eta [pb]"); else { if (lepton == 1) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow e^{+}e^{-}}) d#sigma/d#eta"); if (lepton == 2) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow #mu^{+}#mu^{-}}) d#sigma/d#eta"); if (lepton == 3) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow l^{+}l^{-}}) d#sigma/d#eta"); } } if (use_case ==4) { if (absoluteNormalization) leading->GetYaxis ()->SetTitle ("d#sigma/dH_{T} [pb/GeV]"); else { if (lepton == 1) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow e^{+}e^{-}}) d#sigma/dH_{T}"); if (lepton == 2) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow #mu^{+}#mu^{-}}) d#sigma/dH_{T}"); if (lepton == 3) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow l^{+}l^{-}}) d#sigma/dH_{T}"); } } leading->SetFillColor (kBlack); leading->SetFillStyle (3001); leading->SetMarkerColor (kBlack); leading->SetLineColor (kBlack); leading->SetMarkerStyle (20); leading->Draw ("E1"); leadingmuo->SetFillColor (kBlue); leadingmuo->SetFillStyle (3001); leadingmuo->SetMarkerColor (kBlue); leadingmuo->SetLineColor (kBlue); leadingmuo->SetMarkerStyle (21); leadingmuo->Draw ("E1SAME"); leadingthird->SetFillColor (kRed); leadingthird->SetFillStyle (3001); leadingthird->SetMarkerColor (kRed); leadingthird->SetLineColor (kRed); leadingthird->SetMarkerStyle (21); leadingthird->Sumw2(); //for (int j=1; j<=leadingthird->GetNbinsX();j++){ //leadingmuo->SetBinError(j,leadingmuo->GetBinError(j)/4980.0); //leadingthird->SetBinError(j,sqrt(leadingthird->GetBinContent(j))/(4980.0*100)); //} leadingthird->Draw ("E1SAME"); //------------------------------------------- TLegend *legendsx_d; legendsx_d = new TLegend (0.74, 0.6, 0.98, 0.88); legendsx_d->SetFillColor (kWhite); legendsx_d->SetBorderSize (1); legendsx_d->SetNColumns(1); legendsx_d->SetTextSize(.040); legendsx_d->AddEntry (leading, "Central", "PEL"); legendsx_d->AddEntry (leadingmuo, "Sherpa", "PEL"); legendsx_d->AddEntry (leadingthird, "Reweighting", "PEL"); legendsx_d->Draw ("same"); // Draw the ratio plot: ---------------------- leadingRatio = (TH1D *) leading->Clone ("leading"); leadingRatio->Divide(leadingmuo); leadingRatio2 = (TH1D *) leading->Clone ("leading"); leadingRatio2->Divide(leadingthird); for (int mem=1; mem<=leadingRatio->GetNbinsX(); mem++) { cout << "Syst for bin nr." << mem << ":\t" << fabs(leadingRatio->GetBinContent(mem)-1.0)/2 << endl; } plots->cd(); TPad *pad3 = new TPad("pad3","pad3",0.01,0.01,0.99,0.30); pad3->Draw(); pad3->cd(); pad3->SetTopMargin(0.0); pad3->SetBottomMargin(0.3); pad3->SetLeftMargin(0.2); pad3->SetRightMargin(0); pad3->SetFillStyle(0); leadingRatio->GetXaxis()->SetLabelFont (42); leadingRatio->GetXaxis()->SetTitleFont (42); leadingRatio->GetXaxis()->SetTitleSize(0.11); leadingRatio->GetXaxis()->SetLabelSize(0.11); leadingRatio->GetXaxis()->SetTitleOffset (1.1); leadingRatio->GetYaxis()->SetTitleSize(0.11); leadingRatio->GetYaxis()->SetLabelSize(0.10); leadingRatio->GetYaxis()->SetTitleOffset(0.65); leadingRatio->GetYaxis()->SetTitle("Ratio"); leadingRatio->GetYaxis()->SetNdivisions(5); leadingRatio->GetYaxis()->SetRangeUser(0.4,1.6); if (use_case ==1) { leadingRatio->GetXaxis ()->SetTitle ("Exclusive jet multiplicity"); } if (use_case ==2) { if (whichjet == 1) leadingRatio->GetXaxis ()->SetTitle ("Leading jet p_{T} [GeV]"); if (whichjet == 2) leadingRatio->GetXaxis ()->SetTitle ("Second jet p_{T} [GeV]"); if (whichjet == 3) leadingRatio->GetXaxis ()->SetTitle ("Third jet p_{T} [GeV]"); if (whichjet == 4) leadingRatio->GetXaxis ()->SetTitle ("Fourth jet p_{T} [GeV]"); } if (use_case ==3) { if (whichjet == 1) leadingRatio->GetXaxis ()->SetTitle ("Leading jet #eta"); if (whichjet == 2) leadingRatio->GetXaxis ()->SetTitle ("Second jet #eta"); if (whichjet == 3) leadingRatio->GetXaxis ()->SetTitle ("Third jet #eta"); if (whichjet == 4) leadingRatio->GetXaxis ()->SetTitle ("Fourth jet #eta"); } if (use_case ==4) { if (whichjet == 1) leadingRatio->GetXaxis ()->SetTitle ("H_{T}, N_{jet} >= 1 [GeV]"); if (whichjet == 2) leadingRatio->GetXaxis ()->SetTitle ("H_{T}, N_{jet} >= 2 [GeV]"); if (whichjet == 3) leadingRatio->GetXaxis ()->SetTitle ("H_{T}, N_{jet} >= 3 [GeV]"); if (whichjet == 4) leadingRatio->GetXaxis ()->SetTitle ("H_{T}, N_{jet} >= 4 [GeV]"); } leadingRatio->SetFillColor (kRed+2); leadingRatio->SetMarkerColor (kRed+2); leadingRatio->SetLineColor (kRed+2); leadingRatio->Draw ("E0"); leadingRatioSystematics->SetFillColor (kGreen+3); leadingRatioSystematics->SetFillStyle (3004); leadingRatioSystematics->SetMarkerColor (kGreen+3); leadingRatioSystematics->SetLineColor (kGreen+3); leadingRatioSystematics->SetMarkerStyle (1); //leadingRatioSystematics->Draw ("E3SAME"); leadingRatio->Draw ("E1SAME"); leadingRatio2->SetMarkerColor(kBlue); leadingRatio2->SetLineColor(kBlue); leadingRatio2->Draw ("E1SAME"); myfile.open (fileSystematics.c_str()); cout<<"TXT file saved in "<<fileSystematics<<endl; loopAndDumpEntries(leadingRatio,leadingmuo); TLine *OLine2 = new TLine(leading->GetXaxis()->GetXmin(),1.,leading->GetXaxis()->GetXmax(),1.); OLine2->SetLineColor(kBlack); OLine2->SetLineStyle(2); OLine2->Draw(); //latexLabel->SetTextSize(0.09); // latexLabel->DrawLatex(0.2,0.35,"Ratio"); ///////////////////////////////////////////////////// string title1; title1 = s + "DifferentialX" + stringmatch + ".pdf"; cout << title1 << endl; plots->Print (title1.c_str ()); plots->Draw(); return; } }
void KVRTGIDManager::SetIDFuncInTelescopes(UInt_t run){ // For each identification function of the global list which is valid for this run, we add it in the associated telescope which // have to inherits from KVTGIDManager and from a KVIDTelescope. TIter next(fIDGlobalList); KVTGID *tgid = NULL; while( (tgid = (KVTGID *)next())){ if(!tgid->IsValidForRun(run)) continue; // this list have to be deleted after use TCollection *lidtel = GetIDTelescopesForTGID(tgid); TIter nextidt(lidtel); TObject *idt = NULL; KVRTGIDManager *tgidm = NULL; while( (idt = nextidt()) ){ if(!idt->InheritsFrom("KVRTGIDManager")){ Error("KVRTGIDManager::SetIDFuncInTelescopes","The IDtelescope %s does not inherit from KVRTGIDManager",idt->GetName()); continue; } tgidm = (KVRTGIDManager* )idt->IsA()->DynamicCast(KVRTGIDManager::Class(),idt); tgidm->SetTGID(tgid); } delete lidtel; } }
void MergeRootfile( TFile *source ) { TString path(gDirectory->GetPath()); source->cd( path ); cerr << "Browsing " << path << endl; //gain time, do not add the objects in the list in memory TH1::AddDirectory(kFALSE); // loop over all keys in this directory TIter nextkey( gDirectory->GetListOfKeys() ); TKey *key, *oldkey=0; while ( (key = (TKey*)nextkey())) { //keep only the highest cycle number for each key if (oldkey && !strcmp(oldkey->GetName(),key->GetName())) continue; // read object from first source file TObject *obj = key->ReadObj(); cerr << "NAME IS " << obj->GetName() << endl; if ( obj->IsA()->InheritsFrom( TH1::Class() ) ) { cerr << " HELLO, we have the histogram " << obj->GetName() << endl; TH1 *h = (TH1*)obj; ProcessHisto(h); } else if ( obj->IsA()->InheritsFrom( THnBase::Class() )) { cerr << " HELLO-SPARSE " << obj->GetName() << endl; THnBase *h = (THnBase*)obj; ProcessSparse(h); } else if ( obj->IsA()->InheritsFrom( TDirectory::Class() ) ) { // it's a subdirectory //cerr << "Found subdirectory " << obj->GetName() << endl; source->cd( path + "/" + obj->GetName() ); MergeRootfile(source); source->cd( path ); } else if ( obj->IsA()->InheritsFrom( TCollection::Class() )) { TCollection *coll = (TCollection *)obj; //cerr << "List of something in " << obj->GetName() << endl; TIter nextelem(coll); TObject *elem; while ((elem = nextelem())) { if (elem->IsA()->InheritsFrom( TH1::Class() )) { cerr << " HELLO, we have the histogram " << elem->GetName() << endl; TH1 *h = (TH1 *)elem; ProcessHisto(h); } else if (elem->IsA()->InheritsFrom( THnBase::Class() )) { cerr << " HELLO-SPARSE " << elem->GetName() << endl; THnBase *h = (THnBase *)elem; ProcessSparse(h); } } } else { // object is of no type that we know or can handle cerr << "Unknown object type, name: " << obj->GetName() << " title: " << obj->GetTitle() << endl; } delete obj; } // while ( ( TKey *key = (TKey*)nextkey() ) ) }
const char *Name(int idx) { if (!idx) return "__ALL__"; TObject *tn = mArray.At(idx); return (tn)? tn->GetName():0;}
void createEntry(TString infostream, std::vector<TString> fileList_, bool save, unsigned int verbose){ // extract relavant information from infostream TString recoTreeLocation =getStringEntry(infostream,1,":"); TString genTreeLocation =getStringEntry(infostream,2,":"); TString outputRecoFolderLocation=getStringEntry(infostream,3,":"); TString outputGenFolderLocation =getStringEntry(infostream,4,":"); TString newVarName =getStringEntry(infostream,5,":"); TString newVarBinning =getStringEntry(infostream,6,":"); TString fillFrom =getStringEntry(infostream,7,":"); TString eventWeight =getStringEntry(infostream,8,":"); TString withCondition =getStringEntry(infostream,9,":"); //loop files for(unsigned int fileix=0; fileix<fileList_.size(); ++fileix){ TString name=fileList_[fileix]; if(verbose>1) std::cout << std::endl << "processing file " << name << std::endl; // check if ttbarSG file is processed bool ttbarSG= (name.Contains("Sig")) ? true : false; bool ttbarCentral = (ttbarSG&&!(name.Contains("Up")||name.Contains("Down")||name.Contains("Mcatnlo")||name.Contains("Powheg"))) ? true : false; // container for values read from tree std::map< TString, float > value_; // A open file TFile* file = TFile::Open(name, "Update"); if(!file||file->IsZombie()) std::cout << "ERROR: file " << name << " does not exist or is broken" << std::endl; else{ file->cd(); // B1 open reco tree TTree* recotree=(TTree*)(file->Get(recoTreeLocation+"/tree")->Clone()); if(!recotree||recotree->IsZombie()){ std::cout << "ERROR: can not load the chosen recotree " << recoTreeLocation+"/tree in file " << name << std::endl; } else{ // info output if(fileix==0&&verbose>1) std::cout << "recotree: " << recoTreeLocation+"/tree" << std::endl; // activate all branches recotree->SetBranchStatus("*",1); // get all branches from recotree TObjArray* branches=recotree->GetListOfBranches(); // loop all branches TObjArrayIter branch(branches); TObject* object; while ( ( object = branch() ) ) { // get single branch TString branchname=(TString)object->GetName(); // info output if(fileix==0&&verbose>1) std::cout << "->reco branch : " << branchname << std::endl; // set branch address for access recotree->SetBranchAddress(branchname,(&value_[branchname])); } // B2a create reco histo int nbins =(getStringEntry(newVarBinning,1,",")).Atoi(); double min=(getStringEntry(newVarBinning,2,",")).Atof(); double max=(getStringEntry(newVarBinning,3,",")).Atof(); TH1F* newRecPlot=new TH1F( newVarName+"Rec", newVarName, nbins , min , max); // B2b create reco branch entry Float_t newRec1; Float_t newRec2; TBranch *newRecBranch1 = recotree->Branch(newVarName+"Lep", &newRec1, newVarName+"Lep"+"/F"); TBranch *newRecBranch2 = recotree->Branch(newVarName+"Had", &newRec2, newVarName+"Had"+"/F"); // info output if(fileix==0&&verbose>1){ std::cout << "will add new reco plot: new TH1F(" << newVarName << ", " << newVarName; std::cout << ", " << nbins << ", " << min << ", " << max << ") in " << outputRecoFolderLocation << std::endl; std::cout << "will add new branches " << newVarName+"Lep" << " and " << newVarName+"Had"; std::cout << ") in tree " << recoTreeLocation+"/tree" << std::endl; } // B3a create gen-reco histo TH2F* newRecGenPlot; Float_t newRecGen1; Float_t newRecGen2; TBranch *newRecGenBranch1 =0; TBranch *newRecGenBranch2 =0; if(ttbarSG){ newRecGenPlot=new TH2F( newVarName+"_", newVarName+"_", nbins , min , max, nbins , min , max); if(fileix==0&&verbose>1){ std::cout << "will add new gen-reco plot: new TH2F(" << newVarName+"_" << ", " << newVarName+"_"; std::cout << ", " << nbins << ", " << min << ", " << max << ", " << std::endl; std::cout << ", " << nbins << ", " << min << ", " << max << ")" << std::endl; } // B3b create gen branch entry newRecGenBranch1 = recotree->Branch(newVarName+"Lep"+"PartonTruth", &newRecGen1, newVarName+"Lep"+"PartonTruth"+"/F"); newRecGenBranch2 = recotree->Branch(newVarName+"Had"+"PartonTruth", &newRecGen2, newVarName+"Had"+"PartonTruth"+"/F"); } // B4 fill reco plots from tree // loop recotree for(unsigned int event=0; event<recotree->GetEntries(); ++event){ recotree->GetEntry(event); // B4a fill rec branch newRec1=value_["topPtLep"]*value_["topPtLep"]; newRec2=value_["topPtHad"]*value_["topPtHad"]; newRecBranch1->Fill(); newRecBranch2->Fill(); // B4b fill rec plot newRecPlot->Fill(newRec1, value_["weight"]); newRecPlot->Fill(newRec2, value_["weight"]); // fill rec-gen plot if(newRecGenPlot){ newRecGen1=value_["topPtLepPartonTruth"]*value_["topPtLepPartonTruth"]; newRecGen2=value_["topPtHadPartonTruth"]*value_["topPtHadPartonTruth"]; newRecGenBranch1->Fill(); newRecGenBranch2->Fill(); newRecGenPlot->Fill(newRecGen1, newRec1, value_["weight"]); newRecGenPlot->Fill(newRecGen2, newRec2, value_["weight"]); } } // B5 saving if(save){ if(fileList_.size()==1){ TString debugName=((getStringEntry(name, 42, "/")).ReplaceAll(".root", "")); if(newRecPlot ) saveToRootFile("test.root", newRecPlot , true, 1, outputRecoFolderLocation+"/"+debugName); if(newRecGenPlot) saveToRootFile("test.root", newRecGenPlot, true, 1, outputRecoFolderLocation+"/"+debugName); } file->cd(outputRecoFolderLocation); if(newRecPlot ) newRecPlot ->Write(newRecPlot->GetTitle() , TObject::kOverwrite); if(newRecGenPlot) newRecGenPlot->Write(newRecGenPlot->GetTitle(), TObject::kOverwrite); if(recotree) recotree->Write(recotree->GetTitle(), TObject::kOverwrite); file->cd(); } // end if save } // end if recotree if(ttbarSG){ if(verbose>1) std::cout << "-> ttbarSG file! gen and reco-gen will be derived" << std::endl; // C open gen tree TTree* gentree=(TTree*)(file->Get(genTreeLocation+"/tree")->Clone()); if(!gentree||gentree->IsZombie()){ std::cout << "ERROR: can not load the chosen gentree " << genTreeLocation+"/tree in file " << name << std::endl; } else{ // info output if(fileix==0&&verbose>1) std::cout << "gentree: " << genTreeLocation+"/tree" << std::endl; // activate all branches gentree->SetBranchStatus("*",1); // get all branches from recotree TObjArray* branches=gentree->GetListOfBranches(); // loop all branches TObjArrayIter branch(branches); TObject* object; while ( ( object = branch() ) ) { // get single branch TString branchname=(TString)object->GetName(); // info output if(fileix==0&&verbose>1) std::cout << "->gen branch : " << branchname << std::endl; // set branch address for access gentree->SetBranchAddress(branchname,(&value_[branchname])); } // C2a create gen histo int nbins =(getStringEntry(newVarBinning,1,",")).Atoi(); double min=(getStringEntry(newVarBinning,2,",")).Atof(); double max=(getStringEntry(newVarBinning,3,",")).Atof(); TH1F* newGenPlot=new TH1F( newVarName+"Gen", newVarName, nbins , min , max); // C2b create gen branch entry Float_t newGen1; Float_t newGen2; TBranch *newGenBranch1 = gentree->Branch(newVarName+"Lep", &newGen1, newVarName+"Lep"+"/F"); TBranch *newGenBranch2 = gentree->Branch(newVarName+"Had", &newGen2, newVarName+"Had"+"/F"); // info output if(fileix==0&&verbose>1){ std::cout << "will add new gen plot: new TH1F(" << newVarName << ", " << newVarName; std::cout << ", " << nbins << ", " << min << ", " << max << ")" << std::endl; } // C3 fill gen plots from tree // loop gentree for(unsigned int event=0; event<gentree->GetEntries(); ++event){ gentree->GetEntry(event); // C3a fill gen branches newGen1=value_["topPtLep"]*value_["topPtLep"]; newGen2=value_["topPtHad"]*value_["topPtHad"]; newGenBranch1->Fill(); newGenBranch2->Fill(); // C3b fill gen plot newGenPlot->Fill(newGen1, value_["weight"]); newGenPlot->Fill(newGen2, value_["weight"]); } // C4 saving if(save){ if(fileList_.size()==1){ TString debugName=((getStringEntry(name, 42, "/")).ReplaceAll(".root", "")); if(newGenPlot ) saveToRootFile("test.root", newGenPlot , true, 1, outputGenFolderLocation+"/"+debugName ); } file->cd(outputGenFolderLocation); if(newGenPlot) newGenPlot->Write(newGenPlot->GetTitle(), TObject::kOverwrite); if(gentree ) gentree->Write(gentree->GetTitle(), TObject::kOverwrite); file->cd(); } // end if save // D process additional folders if(verbose>1&&ttbarCentral) std::cout << " -> central ttbarSG file! need to process additional folders for systematic variations" << std::endl; } // end if gentree } // end if ttbarSG } // end if file // close file file->Close(); } // end loop files }
void MergeRootfile( TDirectory *target, TList *sourcelist, double crossArray[] ) { // cout << "Target path: " << target->GetPath() << endl; TString path( (char*)strstr( target->GetPath(), ":" ) ); path.Remove( 0, 2 ); TFile *first_source = (TFile*)sourcelist->First(); first_source->cd( path ); TDirectory *current_sourcedir = gDirectory; //gain time, do not add the objects in the list in memory Bool_t status = TH1::AddDirectoryStatus(); TH1::AddDirectory(kFALSE); // loop over all keys in this directory TChain *globChain = 0; TIter nextkey( current_sourcedir->GetListOfKeys() ); TKey *key, *oldkey=0; while ( (key = (TKey*)nextkey())) { //keep only the highest cycle number for each key if (oldkey && !strcmp(oldkey->GetName(),key->GetName())) continue; // read object from first source file first_source->cd( path ); TObject *obj = key->ReadObj(); if ( obj->IsA()->InheritsFrom( "TH1" ) ) { // descendant of TH1 -> merge it cout << "Merging histogram " << obj->GetName() << endl; TH1 *h1 = (TH1*)obj; // Scale by the cross-section factor h1->Scale(crossArray[0]); // loop over all source files and add the content of the // correspondant histogram to the one pointed to by "h1" TFile *nextsource = (TFile*)sourcelist->After( first_source ); int q = 1; // This keeps track of which // cross section factor to use while ( nextsource ) { // make sure we are at the correct directory level by cd'ing to path nextsource->cd( path ); TKey *key2 = (TKey*)gDirectory->GetListOfKeys()->FindObject(h1->GetName()); if (key2) { TH1 *h2 = (TH1*)key2->ReadObj(); // Scale by the cross section factor // before adding. h2->Scale(crossArray[q]); h1->Add( h2 ); q++; delete h2; } nextsource = (TFile*)sourcelist->After( nextsource ); } } else if ( obj->IsA()->InheritsFrom( "TTree" ) ) { // loop over all source files create a chain of Trees "globChain" const char* obj_name= obj->GetName(); globChain = new TChain(obj_name); globChain->Add(first_source->GetName()); TFile *nextsource = (TFile*)sourcelist->After( first_source ); // const char* file_name = nextsource->GetName(); // cout << "file name " << file_name << endl; while ( nextsource ) { globChain->Add(nextsource->GetName()); nextsource = (TFile*)sourcelist->After( nextsource ); } } else if ( obj->IsA()->InheritsFrom( "TDirectory" ) ) { // it's a subdirectory cout << "Found subdirectory " << obj->GetName() << endl; // create a new subdir of same name and title in the target file target->cd(); TDirectory *newdir = target->mkdir( obj->GetName(), obj->GetTitle() ); // newdir is now the starting point of another round of merging // newdir still knows its depth within the target file via // GetPath(), so we can still figure out where we are in the recursion MergeRootfile( newdir, sourcelist, crossSections ); } else { // object is of no type that we know or can handle cout << "Unknown object type, name: " << obj->GetName() << " title: " << obj->GetTitle() << endl; } // now write the merged histogram (which is "in" obj) to the target file // note that this will just store obj in the current directory level, // which is not persistent until the complete directory itself is stored // by "target->Write()" below if ( obj ) { target->cd(); //!!if the object is a tree, it is stored in globChain... if(obj->IsA()->InheritsFrom( "TTree" )) globChain->Merge(target->GetFile(),0,"keep"); else obj->Write( key->GetName() ); } } // while ( ( TKey *key = (TKey*)nextkey() ) ) // save modifications to target file target->SaveSelf(kTRUE); TH1::AddDirectory(status); }
//________________________________________________________________________________ void MergeComplexHistogramFile( const Char_t *TargetName=0, const Char_t *inputFilesPattern=0) { if (TargetName && TargetName[0] && inputFilesPattern && inputFilesPattern[0] ) { printf(" An experimental version of macro.\n"); TStopwatch time; Int_t fileCounter = 0; Int_t dirCounter = 0; Int_t treeCounter = 0; Int_t histogramCounter = 0; // Create the output file TFile *outFile = TFile::Open(TargetName,"RECREATE"); TDirectory *outDir = outFile; TDirIter listOfFiles(inputFilesPattern); const char *fileName = 0; while ( (fileName = listOfFiles.NextFile() ) ) { Int_t currentDirDepth = 0; printf("."); fileCounter++; StFileIter file(fileName); TObject *obj = 0; while ( (obj = *file) ) { Int_t depth = file.GetDepth(); while (depth < currentDirDepth) { outDir = outDir->GetMotherDir(); currentDirDepth--; } if ( obj->IsA()->InheritsFrom(TH1::Class()) ) { // descendant of TH1 -> merge it // printf("Merging histogram: %s\n",obj->GetName() ); // std::cout << "Merging histogram " << obj->GetName() << std::endl; TH1 *h1 = (TH1*)obj; TH1 *dstHistogram = 0; // Check whether we found the new histogram if ( (dstHistogram = (TH1 *)outDir->FindObject(h1->GetName()))) { // Accumulate the histogram dstHistogram->Add(h1); delete h1; // Optional, to reduce the memory consumption printf("h"); } else { // First time - move the histogram h1->SetDirectory(outDir); printf(" The new Histogram found: %s \n", h1->GetName() ); histogramCounter++; } } else if ( obj->IsA()->InheritsFrom(TTree::Class()) ) { // descendant of TTree -> merge it // printf("Merging Tree %p:%s\n",obj, obj->GetName() ); TTree *tree = (TTree*)obj; TTree *dstTree = 0; // Check whether we found the new histogram if ( (dstTree = (TTree *)outDir->FindObject(tree->GetName()))) { // printf("Merging %p:%s with the existing Tree %p:%s\n" // ,tree,tree->GetName(),dstTree, dstTree->GetName() ); // Merge the tree TList *nextTree = new TList(); nextTree->Add(tree); dstTree->Merge(nextTree); delete tree; // Optional, to reduce the memory consumption delete nextTree; printf("t"); } else { // First time - move the TTree TDirectory *saveDir = 0; if (outDir != gDirectory) { saveDir = gDirectory; outDir->cd(); } TList *nextTree = new TList(); nextTree->Add(tree); dstTree = TTree::MergeTrees(nextTree); if (saveDir) saveDir->cd(); // printf(" The new TTree found: %p:%s \n",tree, tree->GetName() ); // printf(" Create the destination Tree %p:%s\n\n",dstTree, dstTree->GetName() ); delete tree; // Optional, to reduce the memory consumption delete nextTree; treeCounter++; } } else if ( obj->IsA()->InheritsFrom(TDirectory::Class()) ) { printf("The input sub-TDirectory object: %s depth=%d\n",obj->GetName(), depth); TDirectory *d = (TDirectory *)outDir->FindObject(obj->GetName()); if (!d) { d = outDir->mkdir(obj->GetName()); dirCounter++; printf("The new TDirectory object: %s depth=%d\n",d->GetPathStatic(), depth); } if (d) { outDir = d; printf("The output sub-TDirectory object: %s depth=%d\n",outDir->GetPathStatic(), depth); } } else { printf("I have no idea how to merge the %s objects of the %s class. Skipping .... \n",obj->GetName(), obj->ClassName() ); } ++file; } } printf("\n Finishing . . . \n"); outFile->Write(); // this creates a second copy of the TTree ??? outFile->Close(); delete outFile; if (fileCounter) printf(" Total files merged: %d \n", fileCounter); if (dirCounter) printf(" Total TDirectory objects merged: %d \n", dirCounter); if (histogramCounter) printf(" Total histograms merged: %d \n", histogramCounter); if (treeCounter) printf(" Total TTree\'s merged: %d \n",treeCounter); if (dirCounter || treeCounter) printf(" You have used the experimental version of the program. Please check the output file\n"); time.Print("Merge"); } else { printf("\nUsage: root MergeHistogramFile.C(\"DestinationFileName\",\"InputFilesPattern\")\n"); printf("------ where InputFilesPattern ::= <regexp_pattern_for_the_input_files>|@indirect_file_list\n"); printf(" indirect_file_list ::= a text file with the list of the files\n"); printf(" indirect_file_list can be create by the shell command:\n"); printf(" ls -1 *.root>indirect_file_list \n\n"); } }
void DrawComparisonJetMCData(void){ struct STestFunctor { bool operator()(TObject *aObj) { cout<<aObj->GetTitle()<<endl; //cout<<"pippo"<<endl; //comparisonJetMCData(aObj->GetTitle,1); return true; } }; version="_v2_58.root"; // which version you wonna analize string versionMu="Mu"+version; if (!isMu) version="_v2_58.root"; if (isMu) version="Mu"+version; if (isMu) { dataLumi2011Apix=2136.00; } //storing background infos in: string dir="/gpfs/cms/data/2011/BackgroundEvaluation/"; string bkg=dir+"Backgrounds"+version; fzj = new TFile(bkg.c_str(), "RECREATE"); plotpath ="/tmp/marone/"; //put here the path where you want the plots datafile ="/gpfs/cms/data/2011/jet/jetValidation_DATA_2011"+version; mcfile ="/gpfs/cms/data/2011/jet/jetValidation_zjets_magd_2011Mu_v2_58.root"; back_ttbar ="/gpfs/cms/data/2011/jet/jetValidation_ttbar_2011"+versionMu; back_w ="/gpfs/cms/data/2011/jet/jetValidation_w_2011_v2_27.root"; //DA RIATTIVARE SOTTO, GREPPA hs->!!!! qcd23bc ="/gpfs/cms/data/2011/jet/jetValidation_Qcd_Pt-20to30_BCtoE_v2_17pf.root"; //DA RIATTIVARE SOTTO, GREPPA hs->!!!! qcd38bc ="/gpfs/cms/data/2011/jet/jetValidation_Qcd_Pt-30to80_BCtoE_v2_17pf.root"; //DA RIATTIVARE SOTTO, GREPPA hs->!!!! qcd817bc ="/gpfs/cms/data/2011/jet/jetValidation_Qcd_Pt-80to170_BCtoE_v2_17pf.root"; //DA RIATTIVARE SOTTO, GREPPA hs->!!!! qcd23em ="/gpfs/cms/data/2011/jet/jetValidation_Qcd_Pt-20to30_Enriched_v1_10.root"; //DA RIATTIVARE SOTTO, GREPPA hs->!!!! qcd38em ="/gpfs/cms/data/2011/jet/jetValidation_Qcd_Pt-30to80_Enriched_v1_10.root"; //DA RIATTIVARE SOTTO, GREPPA hs->!!!! qcd817em ="/gpfs/cms/data/2011/jet/jetValidation_Qcd_Pt-80to170_Enriched_v1_10.root"; //DA RIATTIVARE SOTTO, GREPPA hs->!!!! WZ ="/gpfs/cms/data/2011/jet/jetValidation_wz_2011"+versionMu; ZZ ="/gpfs/cms/data/2011/jet/jetValidation_zz_2011"+versionMu; WW ="/gpfs/cms/data/2011/jet/jetValidation_ww_2011"+versionMu; mcfiletau ="/gpfs/cms/data/2011/jet/jetValidation_zjets_magd_2011"+versionMu; // if (isMu) datafile ="/gpfs/cms/data/2011/jet/jetValidation_DATA_2011Mu_v2_28.root"; //if (isMu) mcfile ="/gpfs/cms/data/2011/jet/jetValidation_zjets_magd_2011Mu_v2_28.root"; // if (isMu) version="Mu"+version; treeBKG_->Branch("bckg_leadingJetPt",&bckg_leadingJetPt); treeBKG_->Branch("bckg_2leadingJetPt",&bckg_2leadingJetPt); treeBKG_->Branch("bckg_3leadingJetPt",&bckg_3leadingJetPt); treeBKG_->Branch("bckg_4leadingJetPt",&bckg_4leadingJetPt); treeBKG_->Branch("bckg_JetMultiplicity",&bckg_JetMultiplicity); treeBKG_->Branch("bckg_leadingJetEta",&bckg_leadingJetEta); treeBKG_->Branch("bckg_2leadingJetEta",&bckg_2leadingJetEta); treeBKG_->Branch("bckg_3leadingJetEta",&bckg_3leadingJetEta); treeBKG_->Branch("bckg_4leadingJetEta",&bckg_4leadingJetEta); treeBKG_->Branch("bckg_HT",&bckg_HT); treeBKG_->Branch("bckg_HT",&bckg_HT1); treeBKG_->Branch("bckg_HT",&bckg_HT2); treeBKG_->Branch("bckg_HT",&bckg_HT3); treeBKG_->Branch("bckg_HT",&bckg_HT4); treeBKG_->Branch("bckg_PhiStar",&bckg_PhiStar); gROOT->Reset(); gROOT->ForceStyle(); gROOT->LoadMacro("tdrStyle.C++"); tdrStyle(); // Recupero l'informazione sul numero di eventi processati per singolo MC dataNumEvents = numEventsPerStep(datafile, "demo"); zNumEvents = numEventsPerStep(mcfile, "demo"); ttNumEvents = numEventsPerStep(back_ttbar, "demo"); wNumEvents = numEventsPerStep(back_w, "demo"); wzEvents = numEventsPerStep(WZ, "demo"); zzEvents = numEventsPerStep(ZZ, "demo"); wwEvents = numEventsPerStep(WW, "demo"); // --------------------------------------------------- string direc="/gpfs/cms/data/2011/Observables/Approval/"; if (isAngularAnalysis){ mcfile=direc+"MC_zjets"+version; back_w=direc+"MC_wjets"+version; back_ttbar=direc+"MC_ttbar"+version; WW=direc+"MC_diW"+version; ZZ=direc+"MC_siZ"+version; WZ=direc+"MC_diWZ"+version; datafile=direc+"DATA"+version; mcfiletau=direc+"MC_zjetstau"+version; } TFile *mcf = TFile::Open(mcfile.c_str()); //MC file cout<<"correct in line 138 the right directroy, when we move to v28!!!"<<endl; cout<<"##############################"<<endl; cout<<"Angular Analisis (and background)->"<<isAngularAnalysis<<endl; cout<<"isMu->"<<isMu<<endl; cout<<version<<endl; cout<<"##############################"<<endl; if (isAngularAnalysis) { if (!isMu) mcf->cd("validationJEC/"); if (isMu) mcf->cd("validationJECmu/"); } else { mcf->cd("validationJEC/"); if (isMu) mcf->cd("validationJECmu/"); } TDirectory *dir2=gDirectory; TList *mylist=(TList*)dir2->GetListOfKeys(); TIter iter(mylist); // Use TIter::Next() to get each TObject mom owns. TObject* tobj = 0; string tmpname; int countw=0; int i=0; // solo di servizio quando debuggo... while ( (tobj = iter.Next()) ) { gROOT->Reset(); gROOT->ForceStyle(); tdrStyle(); gStyle->SetPadRightMargin(0.15); string name=tobj->GetName(); TString temp = (TString)name; cout<<name<<endl; //int num=tobj->GetUniqueID(); if(temp.Contains("weight") && countw==0){ countw++; mcf = TFile::Open(mcfile.c_str()); TFile *ttbarf = TFile::Open(back_ttbar.c_str()); TFile *wf = TFile::Open(back_w.c_str()); TFile *wzf = TFile::Open(WZ.c_str()); TFile *zzf = TFile::Open(ZZ.c_str()); TFile *wwf = TFile::Open(WW.c_str()); TCanvas * Canvweight = new TCanvas("Canvweight","Canvweight",0,0,800,600); //if (Canv) delete Canv; //Canv = new TCanvas("Canv","Canv",0,0,800,600); gPad->SetLogy(1); //---- weights mcf->cd("validationJEC"); if (isAngularAnalysis) { if (!isMu) mcf->cd("validationJEC/"); if (isMu) mcf->cd("validationJECmu/"); } else { if (!isMu) mcf->cd("validationJEC/"); if (isMu) mcf->cd("validationJECmu/"); } TH1F* mc; gDirectory->GetObject(name.c_str(),mc); if(mc){ mc->SetFillColor(kRed); mc->GetXaxis()->SetRangeUser(0.,12.); mc->SetMinimum(1.); mc->Draw(); zwemean = mc->GetMean(); tmpname=plotpath+name+"-zjets.png"; Canvweight->Print(tmpname.c_str()); } //---- weights ttbarf->cd("validationJEC"); if (isMu) ttbarf->cd("validationJECmu/"); if (isAngularAnalysis) { if (!isMu) ttbarf->cd("validationJEC/"); if (isMu) ttbarf->cd("validationJECmu/"); } TH1F* ttbar; gDirectory->GetObject(name.c_str(),ttbar); if(ttbar){ ttbar->SetFillColor(kBlue); ttbar->GetXaxis()->SetRangeUser(0.,12.); ttbar->Draw(); ttwemean = ttbar->GetMean(); tmpname=plotpath+name+"-ttbar.png"; Canvweight->Print(tmpname.c_str()); } //---- weights wf->cd("validationJEC"); if (isMu) wf->cd("validationJECmu/"); if (isAngularAnalysis) { wf->cd("validationJEC/"); if (isMu) wf->cd("validationJECmu/"); } TH1F* w; gDirectory->GetObject(name.c_str(),w); if(w){ w->SetFillColor(kViolet+2); w->GetXaxis()->SetRangeUser(0.,12.); w->Draw(); wwemean = w->GetMean(); tmpname=plotpath+name+"-wjets.png"; Canvweight->Print(tmpname.c_str()); } //---- weights wzf->cd("validationJEC"); if (isMu) wzf->cd("validationJECmu/"); if (isAngularAnalysis) { wzf->cd("validationJEC/"); if (isMu) wzf->cd("validationJECmu/"); } TH1F* wz; gDirectory->GetObject(name.c_str(),wz); if(wz){ wz->SetFillColor(kYellow+2); wz->GetXaxis()->SetRangeUser(0.,12.); wz->Draw(); wzwemean = w->GetMean(); tmpname=plotpath+name+"-wzjets.png"; Canvweight->Print(tmpname.c_str()); } //---- weights zzf->cd("validationJEC"); if (isMu) zzf->cd("validationJECmu/"); if (isAngularAnalysis) { zzf->cd("validationJEC/"); if (isMu) zzf->cd("validationJECmu/"); } TH1F* zz; gDirectory->GetObject(name.c_str(),zz); if(zz){ zz->SetFillColor(kOrange+2); zz->GetXaxis()->SetRangeUser(0.,12.); zz->Draw(); zzwemean = w->GetMean(); tmpname=plotpath+name+"-zzjets.png"; Canvweight->Print(tmpname.c_str()); } //---- weights wwf->cd("validationJEC"); if (isMu) wwf->cd("validationJECmu/"); if (isAngularAnalysis) { wwf->cd("validationJEC/"); if (isMu) wwf->cd("validationJECmu/"); } TH1F* www; gDirectory->GetObject(name.c_str(),www); if(www){ www->SetFillColor(kBlack); www->GetXaxis()->SetRangeUser(0.,12.); www->Draw(); wwwemean = www->GetMean(); tmpname=plotpath+name+"-wwwjets.png"; Canvweight->Print(tmpname.c_str()); } } else comparisonJetMCData(name,1); i++; //if(i==4)break; //Tau?? } // AVVISI AI NAVIGANTI //if(dataNumEvents<0.) cout << "ATTENZIONE: HAI FALLITO LA NORMALIZZAZIONE DEI DATI, quindi ho normalizzato sugli eventi totali del campione\n"; //else cout << "Il numero di eventi (dati) " << dataNumEvents << "\n"; if(zNumEvents<0.) cout << "ATTENZIONE: HAI FALLITO LA NORMALIZZAZIONE DELLO Z+JETS, quindi ho normalizzato sugli eventi totali del campione\n"; else cout << "Il numero di eventi di Z+jets " << zNumEvents << "\n"; if(ttNumEvents<0.) cout << "ATTENZIONE: HAI FALLITO LA NORMALIZZAZIONE DEL TTBAR+JETS, quindi ho normalizzato sugli eventi totali del campione\n"; else cout << "Il numero di eventi di ttbar+jets " << ttNumEvents << "\n"; if(wNumEvents<0.) cout << "ATTENZIONE: HAI FALLITO LA NORMALIZZAZIONE DEL W+JETS, quindi ho normalizzato sugli eventi totali del campione\n"; else cout << "Il numero di eventi di W+jets " << wNumEvents << "\n"; if(wzEvents<0.) cout << "ATTENZIONE: HAI FALLITO LA NORMALIZZAZIONE DEL W+JETS, quindi ho normalizzato sugli eventi totali del campione\n"; else cout << "Il numero di eventi di ZW+jets " << wzEvents << "\n"; if(zzEvents<0.) cout << "ATTENZIONE: HAI FALLITO LA NORMALIZZAZIONE DEL W+JETS, quindi ho normalizzato sugli eventi totali del campione\n"; else cout << "Il numero di eventi di ZZ+jets " << zzEvents << "\n"; if(wwEvents<0.) cout << "ATTENZIONE: HAI FALLITO LA NORMALIZZAZIONE DEL W+JETS, quindi ho normalizzato sugli eventi totali del campione\n"; else cout << "Il numero di eventi di WW+jets " << wwEvents << "\n"; return; }
void combinePreFullTests( string rootFullName, string rootPreTest, string rootOutputName) { // open output file TFile *_fileSave = TFile::Open( rootOutputName.c_str(), "new" ); // open existing files TFile * fileFullTest = TFile::Open( rootFullName.c_str(),"read" ); TFile * filePreTest = TFile::Open( rootPreTest.c_str(),"read" ); fileFullTest->cd(); if( ! fileFullTest ) continue; TIter nextkey( gDirectory->GetListOfKeys() ); TKey * key; cout << "Copy Subdirectory/histograms from " << fileFullTest->GetName() << endl; cout << "into the file: " << _fileSave->GetName() << endl; while( ( key = (TKey*)nextkey() ) ) { TObject * obj = key->ReadObj(); if (obj->IsA()->InheritsFrom( "TDirectory" )){ cout << "----- Subdir " << obj->GetName() << " " << obj->GetUniqueID() << endl; // create same structure _fileSave->mkdir(obj->GetName()); // loop over all histograms in subdirectory fileFullTest->cd(obj->GetName()); TIter nextkey2( gDirectory->GetListOfKeys() ); TKey * key2; string objName = obj->GetName(); if (objName.substr(0,3) == "BB2"){ cout << "for Subdirectory BB2 in file " << fileFullTest->GetName() << " do nothing" << endl; } else{ while( ( key2 = (TKey*)nextkey2() ) ) { _fileSave->cd(); TObject * obj2 = key2->ReadObj(); if( obj2->IsA()->InheritsFrom( "TH2D" )) { //cout << "2d histograms " << obj2->GetName() << endl; TH2D * h2 = (TH2D*)obj2; _fileSave->cd(obj->GetName()); h2->Write(); } else if ( obj2->IsA()->InheritsFrom( "TH1D" )) { //cout << "1d histograms " << obj2->GetName() << endl; TH1D * h1 = (TH1D*)obj2; _fileSave->cd(obj->GetName()); h1->Write(); } } } // do not save BB2 from Fulltest but from next file // here please save BB2 to final file } else{ // store Histograms which are not in a subdirectory HA and HD _fileSave->cd(); if ( obj->IsA()->InheritsFrom( "TH1D" )) { //cout << "1d histograms " << obj->GetName() << endl; TH1D * h1 = (TH1D*)obj; _fileSave->cd(); h1->Write(); } //cout << obj->GetName() << " this is a histogram " << endl; } } // Now use BB2 from Pretest and store it in the outputfile _fileSave if( ! filePreTest ) continue; filePreTest->cd(); filePreTest->cd("BB2"); cout << "copy BB2 histograms from file " << filePreTest->GetName() << " into " << _fileSave->GetName() << endl; TIter nextkey3( gDirectory->GetListOfKeys() ); TKey * key3; while( ( key3 = (TKey*)nextkey3() ) ) { TObject * obj3 = key3->ReadObj(); if( obj3->IsA()->InheritsFrom( "TH2D" )) { //cout << "2d histograms " << obj3->GetName() << endl; TH2D * h2 = (TH2D*)obj3; _fileSave->cd("BB2"); h2->Write(); } else if ( obj3->IsA()->InheritsFrom( "TH1D" )) { //cout << "1d histograms " << obj3->GetName() << endl; TH1D * h1 = (TH1D*)obj3; _fileSave->cd("BB2"); h1->Write(); } //cout << "----- " << obj3->GetName() << endl; } fileFullTest->Close(); filePreTest->Close(); _fileSave->Close(); }