UInt_t GetListOfTitles( TString & methodName, TList & titles, TDirectory *dir=0 ) { // get the list of all titles for a given method // if the input dir is 0, gDirectory is used // returns a list of keys UInt_t ni=0; if (dir==0) dir = gDirectory; TDirectory* rfdir = (TDirectory*)dir->Get( methodName ); if (rfdir==0) { cout << "+++ Could not locate directory '" << methodName << endl; return 0; } return GetListOfTitles( rfdir, titles ); TList *keys = rfdir->GetListOfKeys(); if (keys==0) { cout << "+++ Directory '" << methodName << "' contains no keys" << endl; return 0; } // TIter rfnext(rfdir->GetListOfKeys()); TKey *rfkey; titles.Clear(); titles.SetOwner(kFALSE); while ((rfkey = (TKey*)rfnext())) { // make sure, that we only look at histograms TClass *cl = gROOT->GetClass(rfkey->GetClassName()); if (cl->InheritsFrom("TDirectory")) { titles.Add(rfkey); ni++; } } cout << "--- Found " << ni << " instance(s) of the method " << methodName << endl; return ni; }
void plotasym(int top){ if (setup("vm","","pol__")==kFALSE) return; THStack* hs = new THStack(TString::Format("asym_top%d",top), TString::Format("asym_top%d",top)); int itop = top-1; TFile* fy = _fyexp[itop]; TIter nextkey(fy->GetListOfKeys()); TKey *key; while (key = (TKey*)nextkey()) { TString Q2Wdirname = key->GetName(); if(Q2Wdirname.EqualTo("hYW_Dir") || Q2Wdirname.EqualTo("hYW"))continue; cout << "Q2Wdirname = " << Q2Wdirname << endl; TString hname = TString::Format("%s/hAsym/Varset1/hAsym_ACC_CORR_phi",Q2Wdirname.Data()); cout << "hname = " << hname << endl; TH1D* h = (TH1D*)fy->Get(hname); if (h==NULL) cout << "histogram not found" << endl; //h->Draw(); hs->Add(h,"e1"); } TCanvas *c = new TCanvas(hs->GetName(),hs->GetTitle()); hs->Draw("pads"); }
void printBadEvents(string filename){ string run = filename.substr(filename.find("_R000")+10, 1); int nrun = atoi(run.c_str()); string fname(filename.substr(filename.find_last_of("/")+1) ); cout << "FileName is " << fname.c_str() << endl; ofstream outfile; stringstream namefile; namefile << "BadEvents_" << nrun << ".txt"; outfile.open(namefile.str().c_str()); outfile << "Bad events in file " << fname.c_str() << endl; TDirectory* topDir; TFile* file = TFile::Open(filename.c_str()); if (!file->IsOpen()) { cerr << "Failed to open " << filename << endl; return; } string dir = "DQMData/Run " + run + "/ParticleFlow/Run summary/ElectronValidation/JetPtRes/BadEvents"; topDir = dynamic_cast<TDirectory*>( file->Get(dir.c_str())); topDir->cd(); if (topDir){ TIter next(topDir->GetListOfKeys()); TKey *key; while ( (key = dynamic_cast<TKey*>(next())) ) { string sflag = key->GetName(); string info(sflag.substr(1, sflag.find_first_of(">")-1 ) ); string run(info.substr(0, info.find_first_of("_")) ); string evt = info.substr( info.find_first_of("_")+1, info.find_last_of("_")-2); string ls(info.substr(info.find_last_of("_")+1,info.find_first_of("_")+1)); string ptres = ( sflag.substr( sflag.find( "f=" ) + 2, 6 ) ).c_str(); cout << "Event info: Run " << run << " LS " << ls << " Evt " << evt << " Jet Pt Res = " << ptres << endl; outfile << "Event info: Run " << run << " LS " << ls << " Evt " << evt << " Jet Pt Res = " << ptres << endl; } } }
// input: - Input file (result from TMVA), // - use of TMVA plotting TStyle void BDTControlPlots( TString fin = "TMVA.root", Bool_t useTMVAStyle = kTRUE ) { // set style and remove existing canvas' TMVAGlob::Initialize( useTMVAStyle ); // checks if file with name "fin" is already open, and if not opens one TFile* file = TMVAGlob::OpenFile( fin ); // get all titles of the method BDT TList titles; UInt_t ninst = TMVAGlob::GetListOfTitles("Method_BDT",titles); if (ninst==0) { cout << "Could not locate directory 'Method_BDT' in file " << fin << endl; return; } // loop over all titles TIter keyIter(&titles); TDirectory *bdtdir; TKey *key; while ((key = TMVAGlob::NextKey(keyIter,"TDirectory"))) { bdtdir = (TDirectory *)key->ReadObj(); bdtcontrolplots( bdtdir ); } }
UInt_t GetListOfMethods( TList & methods, TDirectory *dir=0 ) { // get a list of methods // the list contains TKey objects if (dir==0) dir = gDirectory; TIter mnext(dir->GetListOfKeys()); TKey *mkey; methods.Clear(); methods.SetOwner(kFALSE); UInt_t ni=0; while ((mkey = (TKey*)mnext())) { // make sure, that we only look at TDirectory with name Method_<xxx> TString name = mkey->GetClassName(); TClass *cl = gROOT->GetClass(name); if (cl->InheritsFrom("TDirectory")) { if (TString(mkey->GetName()).BeginsWith("Method_")) { methods.Add(mkey); ni++; } } } cout << "--- Found " << ni << " classifier types" << endl; return ni; }
void drawBeamSpotGraphsAll (TFile* file, const char* fname=0) { TDirectory* module = (TDirectory*)_file0->FindObjectAny("beamSpotFitPV"); if ( module==0 ) return; // unsigned int nrun = module->GetListOfKeys()->GetSize(); // TDirectory* currDir = gDirectory; // gROOT->cd(); // TH1* hChi2 = new TH1F("runChi2","runChi2",nrun,0.5,nrun+0.5); // TH1* hConst = new TH1F("runConst","runConst",nrun,0.5,nrun+0.5); // TH1* hSlope = new TH1F("runSlope","runSlope",nrun,0.5,nrun+0.5); // currDir->cd(); TIter iter(module->GetListOfKeys()); TKey* key; // unsigned int irun(0); // float runSummary[6]; while ( (key=(TKey*)iter()) ) { std::cout << key->GetName() << std::endl; drawBeamSpotGraphs(_file0,key->GetName(),fname); TIter ic(gROOT->GetListOfCanvases()); TCanvas* c; while ( (c=(TCanvas*)ic()) ) delete c; // ++irun; // if ( runSummary[1]>0.1 ) hChi2->SetBinContent(irun,runSummary[0]/runSummary[1]); // hConst->SetBinContent(irun,runSummary[2]); // hConst->SetBinError(irun,runSummary[3]); // hSlope->SetBinContent(irun,runSummary[4]); // hSlope->SetBinError(irun,runSummary[5]); // hChi2->GetXaxis()->SetBinLabel(irun,key->GetName()); // hConst->GetXaxis()->SetBinLabel(irun,key->GetName()); // hSlope->GetXaxis()->SetBinLabel(irun,key->GetName()); // if ( irun==3 ) return; } }
void ReadHist(TString currFName){ TFile *currFile = TFile::Open( currFName.Data(),"READONLY" ); TIter next( gDirectory->GetListOfKeys() ); //-dir-content-- Int_t oncePRsum=0; //--reading-flow-histograms-from-ROOT-file-------------(begin)---- TKey *key; while( (key = (TKey*)next()) ){ //cout << " Classname " << key->GetClassName() << endl; //cout << " Name " << key->GetName() << endl; //cout << " Title " << key->GetTitle() << endl; printf("Class=%s Name=%s Title=\"%s\"\n", key->GetClassName(), key->GetName(), key->GetTitle()); TObject *obj = key->ReadObj(); if ( obj->IsA()->InheritsFrom( TH1::Class() ) ) { TH1 *h = (TH1*)obj; //h = (TH1*)obj; //h->Draw(); //c.Update(); sscanf(key->GetTitle(), "%s %i %s %i %s %i" , ch1, &iC, ch2, &iY, ch3, &iPt); //printf("%s - %i - %s - %i\n", ch1, iC, ch2, iY); TString s(key->GetName()); if( s.Contains("hPhiPRp") ){ //hPhiPRp printf("[PR]--%s[%i]%s[%i]%s[%i]--->\n",ch1,iC, ch2,iY, ch3,iPt); hPhiPR[iC][iY][iPt] = new TH1F; hPhiPR[iC][iY][iPt] = (TH1F*)obj; } if( s.Contains("hPhiABp") ){ //hPhiABp printf("[AB]--%s[%i]%s[%i]%s[%i]--->\n",ch1,iC, ch2,iY, ch3,iPt); hPhiAB[iC][iY][iPt] = new TH1F; hPhiAB[iC][iY][iPt] = (TH1F*)obj; } if( s.Contains("hPhiEPp") ){ //hPhiEPp printf("[EP]--%s[%i]%s[%i]%s[%i]--->\n",ch1,iC, ch2,iY, ch3,iPt); hPhiEP[iC][iY][iPt] = new TH1F; hPhiEP[iC][iY][iPt] = (TH1F*)obj; } if( s.Contains("hMulTrp") ){ //hMulTrp printf("[Tr]--%s[%i]%s[%i]%s[%i]--->\n",ch1,iC, ch2,iY, ch3,iPt); hMulTr[iC][iY][iPt] = new TH1F; hMulTr[iC][iY][iPt] = (TH1F*)obj; } } } }
//________________________________________________________ void GFOverlay::Overlay(const TObjArray &dirs, const TObjArray &legends) { // 'directories' must contain TDirectory and inheriting, being parallel with legends TDirectory *dir1 = 0; for (Int_t iDir = 0; !dir1 && iDir < dirs.GetEntriesFast(); ++iDir) { dir1 = static_cast<TDirectory*>(dirs[iDir]); } if (!dir1) return; const Int_t currentLayer = fLayer; fLayer += (fSummaries ? 2 : 1); std::vector<TH1*> meanHists, rmsHists; UInt_t counter = 0; TIter nextKey(dir1->GetListOfKeys()); // // while(TKey* key = static_cast <TKey*> (nextKey())) { // // OK, make CINT happy, i.e. make .L GFOverlay.C work without extending '+': TKey* key = NULL; while ((key = static_cast <TKey*> (nextKey()))) { if (!fNames.IsEmpty() && !this->KeyContainsListMember(key->GetName(), fNames)) continue; if (this->KeyContainsListMember(key->GetName(), fSkipNames)) continue; TObjArray hists(this->GetTypeWithNameFromDirs(TH1::Class(), key->GetName(), dirs)); if (this->AddHistsAt(hists, legends, currentLayer, counter) > 0) { if (fSummaries) { this->CreateFillMeanRms(hists, currentLayer, dir1->GetName(), meanHists, rmsHists); } ++counter; } TObjArray subDirs(this->GetTypeWithNameFromDirs(TDirectory::Class(), key->GetName(), dirs)); if (subDirs.GetEntries()) { // NOT GetEntriesFast()! ::Info("GFOverlay::Overlay", "Key '%s' has directories to do recursion.", key->GetName()); this->Overlay(subDirs, legends); } } // If mean/rms hists created, add them to manager: for (unsigned int iMean = 0; iMean < meanHists.size(); ++iMean) { fHistMan->AddHistSame(meanHists[iMean], currentLayer + 1, 0, legends[iMean]->GetName()); fHistMan->AddHistSame(rmsHists[iMean], currentLayer + 1, 1, legends[iMean]->GetName()); } }
std::vector<std::string> signalList(const char* dirName="", const char* pattern="", unsigned int debug=0) { std::vector<std::string> histnames; TIter next(gDirectory->GetListOfKeys()); TKey* iobj; unsigned int idx=0; while((iobj = (TKey*)next())){ if(iobj->IsFolder()) continue; if(debug>2){ std::cout << "[" << ++idx << "] ...Found object: " << iobj->GetName() << " of type: " << iobj->GetClassName() << std::endl; } std::string fullpath(dirName); fullpath += fullpath == std::string("") ? "" : "/"; fullpath += iobj->GetName(); // why does \\w*_\\d+ not work to catch them all?!? if(std::string(pattern).empty() && httSignal(iobj->GetName())){ histnames.push_back(fullpath); } else if(!std::string(pattern).empty() && match(iobj->GetName(), (char*)pattern)){ histnames.push_back(fullpath); } } return histnames; }
void MergeRootfile( char *core, TDirectory *target, TList *sourcelist ) { printf("merging only histos with core=%s=\n",core); // 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; int nh=0; // loop over all keys in this directory TChain *globChain = 0; TIter nextkey( current_sourcedir->GetListOfKeys() ); TKey *key; while ( (key = (TKey*)nextkey())) { const char *name=key->GetName(); char * c1=strstr(name,core); if(c1==0) continue; if(c1-name>2) continue; nh++; if(nh%100==0) printf("nh=%d addingX %s\n",nh,name); // 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; // 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 ); TH1 *h2 = (TH1*)gDirectory->Get( h1->GetName() ); if ( h2 ) { h1->Add( h2 ); delete h2; // don't know if this is necessary, i.e. if // h2 is created by the call to gDirectory above. } 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( core,newdir, sourcelist ); } 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->Write( key->GetName() ); else obj->Write( key->GetName() ); } } // while ( ( TKey *key = (TKey*)nextkey() ) ) // save modifications to target file target->Write(); }
void plot_efficiencies( TFile* file, Int_t type = 2, TDirectory* BinDir) { // input: - Input file (result from TMVA), // - type = 1 --> plot efficiency(B) versus eff(S) // = 2 --> plot rejection (B) versus efficiency (S) Bool_t __PLOT_LOGO__ = kTRUE; Bool_t __SAVE_IMAGE__ = kTRUE; // the coordinates Float_t x1 = 0; Float_t x2 = 1; Float_t y1 = 0; Float_t y2 = 0.8; // reverse order if "rejection" if (type == 2) { Float_t z = y1; y1 = 1 - y2; y2 = 1 - z; // cout << "--- type==2: plot background rejection versus signal efficiency" << endl; } else { // cout << "--- type==1: plot background efficiency versus signal efficiency" << endl; } // create canvas TCanvas* c = new TCanvas( "c", "the canvas", 200, 0, 650, 500 ); // global style settings c->SetGrid(); c->SetTicks(); // legend Float_t x0L = 0.107, y0H = 0.899; Float_t dxL = 0.457-x0L, dyH = 0.22; if (type == 2) { x0L = 0.15; y0H = 1 - y0H + dyH + 0.07; } TLegend *legend = new TLegend( x0L, y0H-dyH, x0L+dxL, y0H ); legend->SetTextSize( 0.05 ); legend->SetHeader( "MVA Method:" ); legend->SetMargin( 0.4 ); TString xtit = "Signal efficiency"; TString ytit = "Background efficiency"; if (type == 2) ytit = "Background rejection"; TString ftit = ytit + " versus " + xtit; if (TString(BinDir->GetName()).Contains("multicut")){ ftit += " Bin: "; ftit += (BinDir->GetTitle()); } // draw empty frame if(gROOT->FindObject("frame")!=0) gROOT->FindObject("frame")->Delete(); TH2F* frame = new TH2F( "frame", ftit, 500, x1, x2, 500, y1, y2 ); frame->GetXaxis()->SetTitle( xtit ); frame->GetYaxis()->SetTitle( ytit ); TMVAGlob::SetFrameStyle( frame, 1.0 ); frame->Draw(); Int_t color = 1; Int_t nmva = 0; TKey *key, *hkey; TString hNameRef = "effBvsS"; if (type == 2) hNameRef = "rejBvsS"; TList hists; TList methods; UInt_t nm = TMVAGlob::GetListOfMethods( methods ); // TIter next(file->GetListOfKeys()); TIter next(&methods); // loop over all methods while (key = (TKey*)next()) { TDirectory * mDir = (TDirectory*)key->ReadObj(); TList titles; UInt_t ninst = TMVAGlob::GetListOfTitles(mDir,titles); TIter nextTitle(&titles); TKey *titkey; TDirectory *titDir; while ((titkey = TMVAGlob::NextKey(nextTitle,"TDirectory"))) { titDir = (TDirectory *)titkey->ReadObj(); TString methodTitle; TMVAGlob::GetMethodTitle(methodTitle,titDir); TIter nextKey( titDir->GetListOfKeys() ); while ((hkey = TMVAGlob::NextKey(nextKey,"TH1"))) { TH1 *h = (TH1*)hkey->ReadObj(); TString hname = h->GetName(); if (hname.Contains( hNameRef ) && hname.BeginsWith( "MVA_" )) { h->SetLineWidth(3); h->SetLineColor(color); color++; if (color == 5 || color == 10 || color == 11) color++; h->Draw("csame"); hists.Add(h); nmva++; } } } } while (hists.GetSize()) { TListIter hIt(&hists); TH1* hist(0); Double_t largestInt=-1; TH1* histWithLargestInt(0); while ((hist = (TH1*)hIt())!=0) { Double_t integral = hist->Integral(1,hist->FindBin(0.9999)); if (integral>largestInt) { largestInt = integral; histWithLargestInt = hist; } } if (histWithLargestInt == 0) { cout << "ERROR - unknown hist \"histWithLargestInt\" --> serious problem in ROOT file" << endl; break; } legend->AddEntry(histWithLargestInt,TString(histWithLargestInt->GetTitle()).ReplaceAll("MVA_",""),"l"); hists.Remove(histWithLargestInt); } // rescale legend box size // current box size has been tuned for 3 MVAs + 1 title if (type == 1) { dyH *= (1.0 + Float_t(nmva - 3.0)/4.0); legend->SetY1( y0H - dyH ); } else { dyH *= (Float_t(nmva - 3.0)/4.0); legend->SetY2( y0H + dyH); } // redraw axes frame->Draw("sameaxis"); legend->Draw("same"); // ============================================================ if (__PLOT_LOGO__) TMVAGlob::plot_logo(); // ============================================================ c->Update(); TString fname = "plots/" + hNameRef; if (TString(BinDir->GetName()).Contains("multicut")){ TString fprepend(BinDir->GetName()); fprepend.ReplaceAll("multicutMVA_",""); fname = "plots/" + fprepend + "_" + hNameRef; } if (__SAVE_IMAGE__) TMVAGlob::imgconv( c, fname ); return; }
void simple_overlay() { //open function bracket const int num_hists = 43; TH1F *first_histogram[num_hists]; TH1F *second_histogram[num_hists]; string first_hname[num_hists]= { "Energy_Positron","Energy_Neutrino", "Energy_First_a01", "Energy_Second_a01", "Energy_Tau_1", "Energy_Tau_2", "Energy_Tau_3", "Energy_Tau_4", "PT_Positron","PT_Neutrino", "PT_First_a01", "PT_Second_a01", "PT_Tau_1", "PT_Tau_2", "PT_Tau_3", "PT_Tau_4", "Eta_Tau_1","Eta_Tau_2", "Eta_Tau_3", "Eta_Tau_4", "DeltaEta_Tau_12", "DeltaEta_Tau_13", "DeltaEta_Tau_14", "DeltaEta_Tau_23", "DeltaEta_Tau_24", "DeltaEta_Tau_34", "DeltaPhi_Tau_12", "DeltaPhi_Tau_13", "DeltaPhi_Tau_14", "DeltaPhi_Tau_23", "DeltaPhi_Tau_24", "DeltaPhi_Tau_34", "DeltaR_Tau_12", "DeltaR_Tau_13", "DeltaR_Tau_14", "DeltaR_Tau_23", "DeltaR_Tau_24", "DeltaR_Tau_34", "Invariant_Mass_Pair12", "Invariant_Mass_Pair14", "Invariant_Mass_Pair32", "Invariant_Mass_Pair34", "Invariant_Mass_4_Taus"}; // enter info for histograms here string second_hname[num_hists]= { "energy_ele_hist","energy_nu_hist","energy_a1_hist","energy_a2_hist","energy_tau1_hist","energy_tau2_hist","energy_tau3_hist", "energy_tau4_hist", "pT_ele_hist","pT_nu_hist","pT_a1_hist","pT_a2_hist","pT_tau1_hist","pT_tau2_hist","pT_tau3_hist", "pT_tau4_hist", "eta_tau1", "eta_tau2", "eta_tau3", "eta_tau4", "deleta_tau12", "deleta_tau13", "deleta_tau14", "deleta_tau23", "deleta_tau24", "deleta_tau34", "delphi_tau12", "delphi_tau13", "delphi_tau14", "delphi_tau23", "delphi_tau24", "delphi_tau34", "delR_tau12", "delR_tau13", "delR_tau14", "delR_tau23", "delR_tau24", "delR_tau34", "mass_12", "mass_14", "mass_32", "mass_34", "mass_1234"}; TFile *first_file = new TFile("Entries_3000_Histograms_h01_115_a01_9.root"); //put name of one file here TFile *second_file = new TFile("KinematicsPlots_NewBinning.root"); //put name of other file here for (int i=0; i < num_hists; i++) { TIter next(first_file->GetListOfKeys()); TKey *key; string hName; while((key=(TKey*)next())) { hName = key->GetName(); if (hName.find(first_hname[i]) != -1) { first_histogram[i] = (TH1F*)(first_file->Get(hName.c_str())); cout << "first_hname[" << i << "]" << first_hname[i] << endl; break; } } TIter next(second_file->GetListOfKeys()); while((key=(TKey*)next())) { hName = key->GetName(); if (hName.find(second_hname[i]) != -1) { second_histogram[i] = (TH1F*)(second_file->Get(hName.c_str())); cout << "second_hname[" << i << "]" << first_hname[i] << endl; break; } } TCanvas *c1 = new TCanvas(); double statXstart[5] = {.8,.8,.8,.8,.8}; double statXend[5] = {1.,1.,1.,1.,1.}; double statYstart[5] = {.80,.70,.60,.50,.40}; double statYend[5] = {.70,.60,.50,.40,.30}; Color_t color_array[15] = {kBlue+1,kRed+0,kViolet,kAzure+10,kGreen+2,kBlue+1,kRed+0,kViolet,kAzure+10,kGreen+2,kBlue+1,kRed+0,kViolet,kAzure+10,kGreen+2}; size_t name_length; TPaveText *title = new TPaveText(0.306092,0.9390678,0.693908,0.995,"blNDC"); gStyle->SetOptTitle(0); title->SetBorderSize(0); title->SetFillColor(kWhite); title->SetTextFont(42); TPaveStats *st; string directory = "Francesca_Overlaid_Tau_Histograms"; gSystem->MakeDirectory(directory.c_str()); directory = directory + "/"; c1->cd(); gStyle->SetOptStat("nmre"); gStyle->SetStatH(0.03); gStyle->SetStatW(0.20); //TH1F *first_histogram = new TH1F(first_histogram_title, first_histogram_title, 200, 0., 500); //TH1F *second_histogram = new TH1F(second_histogram_title, second_histogram_title, 200, 0., 500); first_histogram[i]->SetLineColor(color_array[0]); first_histogram[i]->SetLineWidth(2); first_histogram[i]->SetTitle(first_hname[i].c_str()); // WHAT DOES THIS DO? eg. does it just set the name for hist title, or also for legend title? first_histogram[i]->SetName(first_hname[i].c_str()); // WHAT DOES THIS DO? eg. does it just set name for legend title? first_histogram[i]->Draw(); gPad->Update(); st = (TPaveStats*)first_histogram[i]->FindObject("stats"); st->SetX1NDC(statXstart[0]); st->SetX2NDC(statXend[0]); st->SetY1NDC(statYstart[0]); st->SetY2NDC(statYend[0]); second_histogram[i]->SetLineColor(color_array[1]); second_histogram[i]->SetLineWidth(2); second_histogram[i]->SetTitle(second_hname[i].c_str()); second_histogram[i]->SetName(second_hname[i].c_str()); second_histogram[i]->Draw("sames"); gPad->Update(); st = (TPaveStats*)second_histogram[i]->FindObject("stats"); st->SetX1NDC(statXstart[1]); st->SetX2NDC(statXend[1]); st->SetY1NDC(statYstart[1]); st->SetY2NDC(statYend[1]); c1->BuildLegend(.85,.8,1.,1.); c1->SetTitle("Dwarves"); title->Clear(); //this clears the title for the histogram title->AddText((first_hname[i]).c_str()); //this adds text to the TPaveText box that we created before the loop title->Draw(); //this draws the TPaveText box with the new text... e.g. it makes our new title c1->SaveAs((directory + first_hname[i] + ".png").c_str()); } //close for loop } //close function bracket
void compareplots_noRatio(){ vector<TFile*> files; files.push_back(new TFile("/storage/9/schweiger/analyseFxFx/pythia8/100kEvents/ttbarMergedFxFx8TeVCTEQ6M-extracted.root")); files.push_back(new TFile("/storage/9/schweiger/analyseFxFx/pythia8/100kEvents/mergingscale_30/ttbarMergedFxFxMS30GeVMECut10GeV8TeVCTEQ6M-extracted.root")); files.push_back(new TFile("/storage/9/schweiger/analyseFxFx/pythia8/100kEvents/mergingscale_100/ttbarMergedMS100GeV8TeVCTEQ6M-extracted.root")); files.push_back(new TFile("/storage/9/schweiger/analyseFxFx/pythia8/100kEvents/mergingscale_100/ttbarMergedMS100GeVMCCut50GeV8TeVCTEQ6M-extracted.root")); vector<TString> names; names.push_back("ttbar +0/1 Jet, #mu_{Q}=10 GeV #mu_{ME} = 10 GeV"); names.push_back("ttbar +0/1 Jet, #mu_{Q}=30 GeV #mu_{ME} = 10 GeV"); names.push_back("ttbar +0/1 Jet, #mu_{Q}=100 GeV #mu_{ME} = 10 GeV"); names.push_back("ttbar +0/1 Jet, #mu_{Q}=100 GeV #mu_{ME} = 50 GeV"); vector<TString> titles; titles.push_back("Gen-Jet p_{T} with pos weights (GeV)"); titles.push_back("Gen-Jet p_{T} with neg weights (GeV)"); titles.push_back("Gen-Jet p_{T} (GeV)"); titles.push_back("Gen_Jet #phi with pos. weights"); titles.push_back("Gen_Jet #phi with neg. weights"); titles.push_back("Gen_Jet #phi"); titles.push_back("Gen Jet #theta with pos weights"); titles.push_back("Gen Jet #theta with neg weights"); titles.push_back("Gen Jet #theta"); titles.push_back("Gen Jet Energy with pos weights (GeV) "); titles.push_back("Gen Jet Energy with neg weights (GeV)"); titles.push_back("Gen Jet Energy (GeV)"); titles.push_back("p_{T} of hardest Gen-Jet with pos weights (GeV)"); titles.push_back("p_{T} of hardest Gen-Jet with neg weights (GeV)"); titles.push_back("p_{T} of hardest Gen-Jet (GeV)"); titles.push_back("p_{T} of 2nd hardest Gen-Jet with pos weights (GeV)"); titles.push_back("p_{T} of 2nd hardest Gen-Jet with neg weights (GeV)"); titles.push_back("p_{T} of 2nd hardest Gen-Jet (GeV)"); titles.push_back("#eta of hardest Gen-Jets with pos weights"); titles.push_back("#eta of hardest Gen-Jets with neg weights"); titles.push_back("#eta of hardest Gen-Jets"); titles.push_back("Number of Gen-Jets with pos. weights"); titles.push_back("Number of Gen-Jets with neg. weights"); titles.push_back("Number of Gen-Jets"); TFile *vergleich = new TFile("vergleich_ttbar_0Jet.root","RECREATE"); // Show no statistics box gStyle->SetOptStat(0); TH1::SetDefaultSumw2(); // Main program part TIter nextkey(files.at(0)->GetListOfKeys()); TKey *key; bool first=true; TCanvas* c = new TCanvas(); c->Print("plots.pdf["); // Save also as pictures int pictureNumber = 0; int run = 0; while (key = (TKey*)nextkey()) { pictureNumber++; TString pictureName = TString::Format("%d.png",pictureNumber); vector<TH1F*> histos; histos.push_back((TH1F*)key->ReadObj()); for(size_t i=1;i<files.size();i++){ histos.push_back((TH1F*)files.at(i)->Get(histos.at(0)->GetName())); } for(size_t i=0;i<histos.size();i++){ if(i == 0){ histos.at(i)->SetLineColor(kBlack); } if(i == 1){ histos.at(i)->SetLineColor(kRed); } if(i == 2){ histos.at(i)->SetLineColor(kBlue); } if(i == 3){ histos.at(i)->SetLineColor(kGreen+2); } if(i == 4){ histos.at(i)->SetLineColor(kMagenta-7); } if(i == 5){ histos.at(i)->SetLineColor(kOrange+7); } } for(size_t i=0;i<histos.size();i++){ histos.at(i)->Sumw2(); histos.at(i)->Scale(1./histos.at(i)->Integral(),"width"); } // Set axis title histos.at(0)->GetYaxis()->SetTitle("Normalized units"); std::string const histogramName = histos.at(1)->GetName(); histos.at(0)->GetXaxis()->SetLabelSize(0.05); histos.at(0)->GetXaxis()->SetLabelOffset(0.006); histos.at(0)->GetYaxis()->SetLabelSize(0.05); histos.at(0)->GetYaxis()->SetLabelOffset(0.006); histos.at(0)->GetXaxis()->SetTitleSize(0.06); histos.at(0)->GetXaxis()->SetTitleOffset(1.1); histos.at(0)->GetYaxis()->SetTitleSize(0.06); histos.at(0)->GetYaxis()->SetTitleOffset(1.15); histos.at(0)->GetXaxis()->SetTitle(titles.at(run)); run = run+1; if(run == (3*8)){ run = 0; } // If only two histograms per plot make a ratio plot if(histos.size() == 2) { //create main pad TPad *mainPad = new TPad("","",0.0,0.0,1.0,1.0); mainPad->SetNumber(1); mainPad->SetBottomMargin(0.15); mainPad->SetRightMargin(0.04); mainPad->SetLeftMargin(0.13); mainPad->Draw(); gStyle->SetOptTitle(0); //create ratio pad /*TPad *ratioPad = new TPad("","",0.0,0.0,1.0,0.3); ratioPad->SetTopMargin(0.0); ratioPad->SetBottomMargin(0.4); ratioPad->SetLeftMargin(0.13); ratioPad->SetRightMargin(0.04); gStyle->SetOptTitle(0); ratioPad->SetFillColor(0); ratioPad->SetNumber(2); ratioPad->SetGridy(); ratioPad->Draw();*/ // Draw both histograms first c->cd(1); histos.at(0)->Draw("histo E"); histos.at(1)->Draw("histo same E"); // Show legend and statistical tests in first pad for(size_t i=0;i<histos.size()-1;i=i+2){ double ksresult = histos.at(i)->KolmogorovTest(histos.at(i+1)); ksresult=floor(ksresult*1000+0.5)/1000; double chi2result =histos.at(i)->Chi2Test(histos.at(i+1),"WW"); chi2result=floor(chi2result*1000+0.5)/1000; stringstream ss; //ss << " KS: " <<std::setprecision(3) << ksresult << " chi2: " <<std::setprecision(3) << chi2result << " Private Work"; ss << " Private Work"; const char * ch = & ss.str().c_str();; TLatex * ks = new TLatex(0.1, 0.9-0.03*i, ch ); ks->SetTextColor(histos.at(i)->GetLineColor()); ks->SetNDC(); ks->Draw(""); } TLegend* l = new TLegend(0.40,0.9,0.69,0.99); // Options for legend l->SetBorderSize(0); l->SetLineStyle(0); l->SetTextSize(0.049); l->SetFillStyle(0); for(size_t i=0;i<names.size();i++){ l->AddEntry(histos.at(i),names.at(i),"L"); } l->Draw("same"); /* // Clone histograms and draw ratio plot c->cd(2); TH1F* ratioHisto = (TH1F*)histos.at(0)->Clone(); ratioHisto->Divide(histos.at(1)); ratioHisto->SetLineColor(kBlue); ratioHisto->SetStats(false); ratioHisto->GetYaxis()->SetTitle("Ratio #frac{noFxFx}{FxFx}"); // Same Size like in histogram ratioHisto->SetLabelSize(histos.at(0)->GetLabelSize() * 0.7 / 0.3); ratioHisto->SetTitleOffset((histos.at(0)->GetTitleOffset("Y") * 0.3 / 0.7), "Y"); ratioHisto->SetTitleSize((histos.at(0)->GetTitleSize("Y") * 0.7 / 0.3), "Y"); ratioHisto->SetTitleOffset((histos.at(0)->GetTitleOffset("X")), "X"); ratioHisto->SetTitleSize((histos.at(0)->GetTitleSize("X") * 0.7 / 0.3), "X"); // Use nicer range ratioHisto->GetYaxis()->SetRangeUser(0, 2.2); ratioHisto->GetYaxis()->SetNdivisions(503); ratioHisto->GetYaxis()->SetLabelSize(0.06 * 0.7 / 0.3); ratioHisto->Draw();*/ } else { TPad *mainPad = new TPad("","",0.0,0.0,1.0,1.0); mainPad->SetNumber(1); mainPad->SetBottomMargin(0.15); mainPad->SetRightMargin(0.04); mainPad->SetLeftMargin(0.13); mainPad->Draw(); gStyle->SetOptTitle(0); //mainPad->SetLogx(1); c->cd(1); histos.at(0)->Draw("histo E"); for(size_t i=0;i<histos.size();i++){ histos.at(i)->Draw("histo same E"); } for(size_t i=0;i<histos.size()-1;i=i+2){ /* double ksresult = histos.at(i)->KolmogorovTest(histos.at(i+1)); ksresult=floor(ksresult*1000+0.5)/1000; double chi2result =histos.at(i)->Chi2Test(histos.at(i+1),"WW"); chi2result=floor(chi2result*1000+0.5)/1000; stringstream ss; ss << "KS: " <<std::setprecision(3) << ksresult << " chi2: " <<std::setprecision(3) << chi2result; const char * ch = & ss.str().c_str();; TText * ks = new TText(0.1, 0.9-0.03*i, ch ); ks->SetTextColor(histos.at(i)->GetLineColor()); ks->SetNDC(); ks->Draw(""); */ } TLegend* l = new TLegend(0.65,0.5,0.9,0.7); l->SetBorderSize(0); l->SetLineStyle(0); // l->SetTextSize(0.039); l->SetFillStyle(0); for(size_t i=0;i<names.size();i++){ l->AddEntry(histos.at(i),names.at(i),"L"); } l->Draw("same"); } c->Print("plots.pdf"); c->SaveAs(pictureName); vergleich->WriteTObject(c); } c->Print("plots.pdf]"); }
void XMLimport::readKeyGroup( TKey * pParent ) { TKey * pT; if( pParent ) { pT = new TKey( pParent, mpHost ); } else { pT = new TKey( 0, mpHost ); } mpHost->getKeyUnit()->registerKey( pT ); pT->setIsActive( ( attributes().value("isActive") == "yes" ) ); pT->mIsFolder = ( attributes().value("isFolder") == "yes" ); if (module) pT->mModuleMember = true; while( ! atEnd() ) { readNext(); if( isEndElement() ) break; if( isStartElement() ) { if( name() == "name" ) { pT->mName = readElementText(); continue; } else if( name() == "packageName") { pT->mPackageName = readElementText(); continue; } else if( name() == "script") { QString script = readElementText(); pT->setScript( script ); continue; } else if( name() == "command") { pT->mCommand = readElementText(); continue; } else if( name() == "keyCode" ) { pT->mKeyCode = readElementText().toInt(); continue; } else if( name() == "keyModifier" ) { pT->mKeyModifier = readElementText().toInt(); continue; } else if( name() == "KeyGroup" ) { readKeyGroup( pT ); } else if( name() == "Key" ) { readKeyGroup( pT ); } else { readUnknownKeyElement(); } } } }
// input: - Input file (result from TMVA) // - use of TMVA plotting TStyle void mvas( TString fin = "TMVA.root", HistType htype = MVAType, Bool_t useTMVAStyle = kTRUE ) { // set style and remove existing canvas' TMVAGlob::Initialize( useTMVAStyle ); // switches const Bool_t Save_Images = kTRUE; // checks if file with name "fin" is already open, and if not opens one TFile* file = TMVAGlob::OpenFile( fin ); // define Canvas layout here! Int_t xPad = 1; // no of plots in x Int_t yPad = 1; // no of plots in y Int_t noPad = xPad * yPad ; const Int_t width = 600; // size of canvas // this defines how many canvases we need TCanvas *c = 0; // counter variables Int_t countCanvas = 0; // search for the right histograms in full list of keys TIter next(file->GetListOfKeys()); TKey *key(0); while ((key = (TKey*)next())) { if (!TString(key->GetName()).BeginsWith("Method_")) continue; if( ! gROOT->GetClass(key->GetClassName())->InheritsFrom("TDirectory") ) continue; TString methodName; TMVAGlob::GetMethodName(methodName,key); TDirectory* mDir = (TDirectory*)key->ReadObj(); TIter keyIt(mDir->GetListOfKeys()); TKey *titkey; while ((titkey = (TKey*)keyIt())) { if (!gROOT->GetClass(titkey->GetClassName())->InheritsFrom("TDirectory")) continue; TDirectory *titDir = (TDirectory *)titkey->ReadObj(); TString methodTitle; TMVAGlob::GetMethodTitle(methodTitle,titDir); cout << "--- Found directory for method: " << methodName << "::" << methodTitle << flush; TString hname = "MVA_" + methodTitle; if (htype == ProbaType ) hname += "_Proba"; else if (htype == RarityType ) hname += "_Rarity"; TH1* sig = dynamic_cast<TH1*>(titDir->Get( hname + "_S" )); TH1* bgd = dynamic_cast<TH1*>(titDir->Get( hname + "_B" )); if (sig==0 || bgd==0) { if (htype == MVAType) cout << "mva distribution not available (this is normal for Cut classifier)" << endl; else if(htype == ProbaType) cout << "probability distribution not available (this is normal for Cut classifier)" << endl; else if(htype == RarityType) cout << "rarity distribution not available (this is normal for Cut classifier)" << endl; else if(htype == CompareType) cout << "overtraining check not available (this is normal for Cut classifier)" << endl; else cout << endl; } else { cout << endl; // chop off useless stuff sig->SetTitle( Form("TMVA response for classifier: %s", methodTitle.Data()) ); if (htype == ProbaType) sig->SetTitle( Form("TMVA probability for classifier: %s", methodTitle.Data()) ); else if (htype == RarityType) sig->SetTitle( Form("TMVA Rarity for classifier: %s", methodTitle.Data()) ); else if (htype == CompareType) sig->SetTitle( Form("TMVA overtraining check for classifier: %s", methodTitle.Data()) ); // create new canvas TString ctitle = ((htype == MVAType) ? Form("TMVA response %s",methodTitle.Data()) : (htype == ProbaType) ? Form("TMVA probability %s",methodTitle.Data()) : (htype == CompareType) ? Form("TMVA comparison %s",methodTitle.Data()) : Form("TMVA Rarity %s",methodTitle.Data())); TString cname = ((htype == MVAType) ? Form("output_%s",methodTitle.Data()) : (htype == ProbaType) ? Form("probability_%s",methodTitle.Data()) : (htype == CompareType) ? Form("comparison_%s",methodTitle.Data()) : Form("rarity_%s",methodTitle.Data())); c = new TCanvas( Form("canvas%d", countCanvas+1), ctitle, countCanvas*50+200, countCanvas*20, width, (Int_t)width*0.78 ); // set the histogram style TMVAGlob::SetSignalAndBackgroundStyle( sig, bgd ); // normalise both signal and background TMVAGlob::NormalizeHists( sig, bgd ); // frame limits (choose judicuous x range) Float_t nrms = 4; cout << "--- Mean and RMS (S): " << sig->GetMean() << ", " << sig->GetRMS() << endl; cout << "--- Mean and RMS (B): " << bgd->GetMean() << ", " << bgd->GetRMS() << endl; Float_t xmin = TMath::Max( TMath::Min(sig->GetMean() - nrms*sig->GetRMS(), bgd->GetMean() - nrms*bgd->GetRMS() ), sig->GetXaxis()->GetXmin() ); Float_t xmax = TMath::Min( TMath::Max(sig->GetMean() + nrms*sig->GetRMS(), bgd->GetMean() + nrms*bgd->GetRMS() ), sig->GetXaxis()->GetXmax() ); Float_t ymin = 0; Float_t maxMult = (htype == CompareType) ? 1.3 : 1.2; Float_t ymax = TMath::Max( sig->GetMaximum(), bgd->GetMaximum() )*maxMult; // build a frame Int_t nb = 500; TString hFrameName(TString("frame") + methodTitle); TObject *o = gROOT->FindObject(hFrameName); if(o) delete o; TH2F* frame = new TH2F( hFrameName, sig->GetTitle(), nb, xmin, xmax, nb, ymin, ymax ); frame->GetXaxis()->SetTitle( methodTitle + ((htype == MVAType || htype == CompareType) ? " response" : "") ); if (htype == ProbaType ) frame->GetXaxis()->SetTitle( "Signal probability" ); else if (htype == RarityType ) frame->GetXaxis()->SetTitle( "Signal rarity" ); frame->GetYaxis()->SetTitle("Normalized"); TMVAGlob::SetFrameStyle( frame ); // eventually: draw the frame frame->Draw(); c->GetPad(0)->SetLeftMargin( 0.105 ); frame->GetYaxis()->SetTitleOffset( 1.2 ); // Draw legend TLegend *legend= new TLegend( c->GetLeftMargin(), 1 - c->GetTopMargin() - 0.12, c->GetLeftMargin() + (htype == CompareType ? 0.40 : 0.3), 1 - c->GetTopMargin() ); legend->SetFillStyle( 1 ); legend->AddEntry(sig,TString("Signal") + ((htype == CompareType) ? " (test sample)" : ""), "F"); legend->AddEntry(bgd,TString("Background") + ((htype == CompareType) ? " (test sample)" : ""), "F"); legend->SetBorderSize(1); legend->SetMargin( (htype == CompareType ? 0.2 : 0.3) ); legend->Draw("same"); // overlay signal and background histograms sig->Draw("samehist"); bgd->Draw("samehist"); if (htype == CompareType) { // if overtraining check, load additional histograms TH1* sigOv = 0; TH1* bgdOv = 0; TString ovname = hname += "_Train"; sigOv = dynamic_cast<TH1*>(titDir->Get( ovname + "_S" )); bgdOv = dynamic_cast<TH1*>(titDir->Get( ovname + "_B" )); if (sigOv == 0 || bgdOv == 0) { cout << "+++ Problem in \"mvas.C\": overtraining check histograms do not exist" << endl; } else { cout << "--- Found comparison histograms for overtraining check" << endl; TLegend *legend2= new TLegend( 1 - c->GetRightMargin() - 0.42, 1 - c->GetTopMargin() - 0.12, 1 - c->GetRightMargin(), 1 - c->GetTopMargin() ); legend2->SetFillStyle( 1 ); legend2->SetBorderSize(1); legend2->AddEntry(sigOv,"Signal (training sample)","P"); legend2->AddEntry(bgdOv,"Background (training sample)","P"); legend2->SetMargin( 0.1 ); legend2->Draw("same"); } Int_t col = sig->GetLineColor(); sigOv->SetMarkerColor( col ); sigOv->SetMarkerSize( 0.7 ); sigOv->SetMarkerStyle( 20 ); sigOv->SetLineWidth( 1 ); sigOv->SetLineColor( col ); sigOv->Draw("e1same"); col = bgd->GetLineColor(); bgdOv->SetMarkerColor( col ); bgdOv->SetMarkerSize( 0.7 ); bgdOv->SetMarkerStyle( 20 ); bgdOv->SetLineWidth( 1 ); bgdOv->SetLineColor( col ); bgdOv->Draw("e1same"); ymax = TMath::Max( ymax, TMath::Max( sigOv->GetMaximum(), bgdOv->GetMaximum() )*maxMult ); frame->GetYaxis()->SetLimits( 0, ymax ); // for better visibility, plot thinner lines sig->SetLineWidth( 1 ); bgd->SetLineWidth( 1 ); // perform K-S test cout << "--- Perform Kolmogorov-Smirnov tests" << endl; Double_t kolS = sig->KolmogorovTest( sigOv ); Double_t kolB = bgd->KolmogorovTest( bgdOv ); cout << "--- Goodness of signal (background) consistency: " << kolS << " (" << kolB << ")" << endl; TString probatext = Form( "Kolmogorov-Smirnov test: signal (background) probability = %5.3g (%5.3g)", kolS, kolB ); TText* tt = new TText( 0.12, 0.74, probatext ); tt->SetNDC(); tt->SetTextSize( 0.032 ); tt->AppendPad(); } // redraw axes frame->Draw("sameaxis"); // text for overflows Int_t nbin = sig->GetNbinsX(); Double_t dxu = sig->GetBinWidth(0); Double_t dxo = sig->GetBinWidth(nbin+1); TString uoflow = Form( "U/O-flow (S,B): (%.1f, %.1f)%% / (%.1f, %.1f)%%", sig->GetBinContent(0)*dxu*100, bgd->GetBinContent(0)*dxu*100, sig->GetBinContent(nbin+1)*dxo*100, bgd->GetBinContent(nbin+1)*dxo*100 ); TText* t = new TText( 0.975, 0.115, uoflow ); t->SetNDC(); t->SetTextSize( 0.030 ); t->SetTextAngle( 90 ); t->AppendPad(); // update canvas c->Update(); // save canvas to file TMVAGlob::plot_logo(1.058); if (Save_Images) { if (htype == MVAType) TMVAGlob::imgconv( c, Form("plots/mva_%s", methodTitle.Data()) ); else if (htype == ProbaType) TMVAGlob::imgconv( c, Form("plots/proba_%s", methodTitle.Data()) ); else if (htype == CompareType) TMVAGlob::imgconv( c, Form("plots/overtrain_%s", methodTitle.Data()) ); else TMVAGlob::imgconv( c, Form("plots/rarity_%s", methodTitle.Data()) ); } countCanvas++; } } } }
//------------------------------------------------------------------------------ THStack* PlotAlignmentValidation::addHists(const char *selection, const TString &residType, bool printModuleIds) { enum ResidType { xPrimeRes, yPrimeRes, xPrimeNormRes, yPrimeNormRes, xRes, yRes, xNormRes, /*yResNorm*/ ResXvsXProfile, ResXvsYProfile, ResYvsXProfile, ResYvsYProfile }; ResidType rType = xPrimeRes; if (residType == "xPrime") rType = xPrimeRes; else if (residType == "yPrime") rType = yPrimeRes; else if (residType == "xPrimeNorm") rType = xPrimeNormRes; else if (residType == "yPrimeNorm") rType = yPrimeNormRes; else if (residType == "x") rType = xRes; else if (residType == "y") rType = yRes; else if (residType == "xNorm") rType = xNormRes; // else if (residType == "yNorm") rType = yResNorm; else if (residType == "ResXvsXProfile") rType = ResXvsXProfile; else if (residType == "ResYvsXProfile") rType = ResYvsXProfile; else if (residType == "ResXvsYProfile") rType = ResXvsYProfile; else if (residType == "ResYvsYProfile") rType = ResYvsYProfile; else { std::cout << "PlotAlignmentValidation::addHists: Unknown residual type " << residType << std::endl; return 0; } cout << "PlotAlignmentValidation::addHists: using selection " << selection << endl; THStack * retHistoStack = new THStack(); double legendY = 0.80; TLegend * myLegend = new TLegend(0.17, legendY, 0.85, 0.88); setLegendStyle( *myLegend ); for(std::vector<TkOfflineVariables*>::iterator itSourceFile = sourceList.begin(); itSourceFile != sourceList.end(); ++itSourceFile) { // TFile *f = (*sourceList.begin())->getFile(); TFile *f = (*itSourceFile)->getFile(); // TTree *tree= (*sourceList.begin())->getTree(); TTree *tree= (*itSourceFile)->getTree(); int myLineColor = (*itSourceFile)->getLineColor(); int myLineStyle = (*itSourceFile)->getLineStyle(); TString myLegendName = (*itSourceFile)->getName(); if (!f || !tree) { std::cout << "PlotAlignmentValidation::addHists: no tree or no file" << std::endl; return 0; } // Todo: TLegend? // first loop on tree to find out which entries (i.e. modules) fulfill the selection // 'Entry$' gives the entry number in the tree Long64_t nSel = tree->Draw("Entry$", selection, "goff"); if (nSel == -1) return 0; // error in selection if (nSel == 0) { std::cout << "PlotAlignmentValidation::addHists: no selected module." << std::endl; return 0; } // copy entry numbers that fulfil the selection const std::vector<double> selected(tree->GetV1(), tree->GetV1() + nSel); TH1 *h = 0; // becomes result UInt_t nEmpty = 0;// selected, but empty hists Long64_t nentries = tree->GetEntriesFast(); std::vector<double>::const_iterator iterEnt = selected.begin(); // second loop on tree: // for each selected entry get the hist from the file and merge TkOffTreeVariables *treeMem = 0; // ROOT will initialise tree->SetBranchAddress("TkOffTreeVariables", &treeMem); for (Long64_t i = 0; i < nentries; i++){ if (i < *iterEnt - 0.1 // smaller index (with tolerance): skip || iterEnt == selected.end()) { // at the end: skip continue; } else if (TMath::Abs(i - *iterEnt) < 0.11) { ++iterEnt; // take this entry! } else std::cout << "Must not happen: " << i << " " << *iterEnt << std::endl; tree->GetEntry(i); if (printModuleIds) { std::cout << treeMem->moduleId << ": " << treeMem->entries << " entries" << std::endl; } if (treeMem->entries <= 0) { // little speed up: skip empty hists ++nEmpty; continue; } TString hName; switch(rType) { case xPrimeRes: hName = treeMem->histNameX.c_str(); break; case yPrimeRes: hName = treeMem->histNameY.c_str(); break; case xPrimeNormRes: hName = treeMem->histNameNormX.c_str(); break; case yPrimeNormRes: hName = treeMem->histNameNormY.c_str(); break; case xRes: hName = treeMem->histNameLocalX.c_str(); break; case yRes: hName = treeMem->histNameLocalY.c_str(); break; case xNormRes: hName = treeMem->histNameNormLocalX.c_str(); break; /*case yResNorm: hName = treeMem->histNameNormLocalY.c_str(); break;*/ case ResXvsXProfile: hName = treeMem->profileNameResXvsX.c_str(); break; case ResXvsYProfile: hName = treeMem->profileNameResXvsY.c_str(); break; case ResYvsXProfile: hName = treeMem->profileNameResYvsX.c_str(); break; case ResYvsYProfile: hName = treeMem->profileNameResYvsY.c_str(); break; } TKey *histKey = f->FindKeyAny(hName); TH1 *newHist = (histKey ? static_cast<TH1*>(histKey->ReadObj()) : 0); if (!newHist) { std::cout << "Hist " << hName << " not found in file, break loop." << std::endl; break; } newHist->SetLineColor(myLineColor); newHist->SetLineStyle(myLineStyle); if (!h) { // first hist: clone, but rename keeping only first part of name TString name(newHist->GetName()); Ssiz_t pos_ = 0; for (UInt_t i2 = 0; i2 < 3; ++i2) pos_ = name.Index("_", pos_+1); name = name(0, pos_); // only up to three '_' h = static_cast<TH1*>(newHist->Clone("summed_"+name)); // TString myTitle = Form("%s: %lld modules", selection, nSel); // h->SetTitle( myTitle ); } else { // otherwise just add h->Add(newHist); } delete newHist; } std::cout << "PlotAlignmentValidation::addHists" << "Result is merged from " << nSel-nEmpty << " modules, " << nEmpty << " hists were empty." << std::endl; if (nSel-nEmpty == 0) continue; myLegend->AddEntry(myLegendName, myLegendName, "L"); retHistoStack->Add(h); } myLegend->Draw(); return retHistoStack; }
void th2polyEurope(Int_t npoints=500000) { Int_t i,j; Double_t lon1 = -25; Double_t lon2 = 35; Double_t lat1 = 34; Double_t lat2 = 72; Double_t R = (lat2-lat1)/(lon2-lon1); Int_t W = 800; Int_t H = (Int_t)(R*800); gStyle->SetStatX(0.28); gStyle->SetStatY(0.45); gStyle->SetStatW(0.15); // Canvas used to draw TH2Poly (the map) TCanvas *ce = new TCanvas("ce", "ce",0,0,W,H); ce->ToggleEventStatus(); ce->SetGridx(); ce->SetGridy(); // Real surfaces taken from Wikipedia. const Int_t nx = 36; // see http://en.wikipedia.org/wiki/Area_and_population_of_European_countries const char *countries[nx] = { "france", "spain", "sweden", "germany", "finland", "norway", "poland", "italy", "yugoslavia", "united_kingdom", "romania", "belarus","greece", "czechoslovakia","bulgaria", "iceland", "hungary","portugal","austria", "ireland", "lithuania", "latvia", "estonia", "denmark", "netherlands", "switzerland","moldova","belgium", "albania", "cyprus", "luxembourg", "andorra","malta", "liechtenstein", "san_marino", "monaco" }; Float_t surfaces[nx] = { 547030, 505580, 449964, 357021, 338145, 324220, 312685, 301230, 255438, 244820, 237500, 207600, 131940, 127711, 110910, 103000, 93030, 89242, 83870, 70280, 65200, 64589, 45226, 43094, 41526, 41290, 33843, 30528, 28748, 9250, 2586, 468, 316, 160, 61, 2}; TH1F *h = new TH1F("h","Countries surfaces (in km^{2})",3,0,3); for (i=0; i<nx; i++) h->Fill(countries[i], surfaces[i]); h->LabelsDeflate(); TFile::SetCacheFileDir("."); TFile *f; f = TFile::Open("http://root.cern.ch/files/europe.root","cacheread"); if (!f) { printf("Cannot access europe.root. Is internet working ?\n"); return; } TH2Poly *p = new TH2Poly( "Europe", "Europe (bin contents are normalized to the surfaces in km^{2})", lon1,lon2,lat1,lat2); p->GetXaxis()->SetNdivisions(520); p->GetXaxis()->SetTitle("longitude"); p->GetYaxis()->SetTitle("latitude"); p->SetContour(100); TMultiGraph *mg; TKey *key; TIter nextkey(gDirectory->GetListOfKeys()); while ((key = (TKey*)nextkey())) { TObject *obj = key->ReadObj(); if (obj->InheritsFrom("TMultiGraph")) { mg = (TMultiGraph*)obj; p->AddBin(mg); } } TRandom r; Double_t longitude, latitude; Double_t x, y, pi4 = TMath::Pi()/4, alpha = TMath::Pi()/360; gBenchmark->Start("Partitioning"); p->ChangePartition(100, 100); gBenchmark->Show("Partitioning"); // Fill TH2Poly according to a Mercator projection. gBenchmark->Start("Filling"); for (i=0; i<npoints; i++) { longitude = r.Uniform(lon1,lon2); latitude = r.Uniform(lat1,lat2); x = longitude; y = 38*TMath::Log(TMath::Tan(pi4+alpha*latitude)); p->Fill(x,y); } gBenchmark->Show("Filling"); Int_t nbins = p->GetNumberOfBins(); Double_t maximum = p->GetMaximum(); // h2 contains the surfaces computed from TH2Poly. TH1F *h2 = (TH1F *)h->Clone("h2"); h2->Reset(); for (j=0; j<nx; j++) { for (i=0; i<nbins; i++) { if (strstr(countries[j],p->GetBinName(i+1))) { h2->Fill(countries[j],p->GetBinContent(i+1)); h2->SetBinError(j, p->GetBinError(i+1)); } } } // Normalize the TH2Poly bin contents to the real surfaces. Double_t scale = surfaces[0]/maximum; for (i=0; i<nbins; i++) p->SetBinContent(i+1, scale*p->GetBinContent(i+1)); gStyle->SetOptStat(1111); p->Draw("COLZ"); TCanvas *c1 = new TCanvas("c1", "c1",W+10,0,W-20,H); c1->SetRightMargin(0.047); scale = h->GetMaximum()/h2->GetMaximum(); h->SetStats(0); h->SetLineColor(kRed-3); h->SetLineWidth(2); h->SetMarkerStyle(20); h->SetMarkerColor(kBlue); h->SetMarkerSize(0.8); h->Draw("LP"); h->GetXaxis()->SetLabelFont(42); h->GetXaxis()->SetLabelSize(0.03); h->GetYaxis()->SetLabelFont(42); h2->Scale(scale); Double_t scale2=TMath::Sqrt(scale); for (i=0; i<nx; i++) h2->SetBinError(i+1, scale2*h2->GetBinError(i+1)); h2->Draw("E SAME"); h2->SetMarkerStyle(20); h2->SetMarkerSize(0.8); TLegend *leg = new TLegend(0.5,0.67,0.92,0.8,NULL,"NDC"); leg->SetTextFont(42); leg->SetTextSize(0.025); leg->AddEntry(h,"Real countries surfaces from Wikipedia (in km^{2})","lp"); leg->AddEntry(h2,"Countries surfaces from TH2Poly (with errors)","lp"); leg->Draw(); leg->Draw(); Double_t wikiSum = h->Integral(); Double_t polySum = h2->Integral(); Double_t error = TMath::Abs(wikiSum-polySum)/wikiSum; printf("THPoly Europe surface estimation error wrt wikipedia = %f per cent when using %d points\n",100*error,npoints); }
void plotauto(TString infilename) { TString plname = infilename+".ps"; TCanvas* cc = new TCanvas("validate","validate",500,370); cc->Print(plname+"["); TText tt; tt.SetTextColor(2); tt.SetTextSize(0.02); gStyle->SetMarkerSize(0.1); gStyle->SetTitleSize(0.15,"ff"); gStyle->SetTitleTextColor(4); std::vector < TString > vnames; vnames.push_back("Sim_HitEn"); vnames.push_back("Sim_HitTime"); vnames.push_back("Sim_posXY"); vnames.push_back("Sim_posXZ"); vnames.push_back("Sim_posYZ"); vnames.push_back("Sim_posRZ"); std::vector <TString> exts; exts.push_back(""); exts.push_back("_posZ"); exts.push_back("_negZ"); TH1F* h; TH2F* hh; TKey *key; TIter next; TKey *key2; TIter next2; TFile* infile = new TFile(infilename, "read"); // overall geometry TDirectory* td = (TDirectory*) infile->Get("ALLCollections"); cc->Clear(); cc->Divide(3,3); cc->cd(1); hh = (TH2F*) td->Get("ALLCollections_overallhitZR"); hh->Draw("box"); cc->cd(2); int icol=1; bool first=true; TLegend* tl = new TLegend(0., 0., 1, 1); next = td->GetListOfKeys(); while ((key = (TKey*)next())) { TClass *cll = gROOT->GetClass(key->GetClassName()); if (cll->InheritsFrom("TH2F")) { hh = (TH2F*)key->ReadObj(); TString hn = hh->GetName(); if ( hn.Contains("ALL") ) continue; if ( hn.Contains("_Log") ) continue; hh->SetLineColor(icol); if ( first ) {hh->Draw("box"); first=false;} else hh->Draw("same;box"); icol++; if (icol==10) icol=1; TString ss = hn.ReplaceAll( "_overallhitZR", ""); tl->AddEntry(hh, ss , "l"); } } // the legend cc->cd(3); tl->Draw(); cc->cd(4); hh = (TH2F*) td->Get("ALLCollections_Log_overallhitZR"); hh->Draw("box"); cc->cd(5); icol=1; first=true; next = td->GetListOfKeys(); while ((key = (TKey*)next())) { TClass *cll = gROOT->GetClass(key->GetClassName()); if (cll->InheritsFrom("TH2F")) { hh = (TH2F*)key->ReadObj(); TString hn = hh->GetName(); if ( hn.Contains("ALL" ) ) continue; if ( ! hn.Contains("_Log_") ) continue; hh->SetLineColor(icol); if ( first ) {hh->Draw("box"); first=false;} else hh->Draw("same;box"); icol++; if (icol==10) icol=1; } } cc->cd(7); hh = (TH2F*) td->Get("ALLCollections_LogLog_overallhitZR"); hh->Draw("box"); cc->cd(8); icol=1; first=true; next = td->GetListOfKeys(); while ((key = (TKey*)next())) { TClass *cll = gROOT->GetClass(key->GetClassName()); if (cll->InheritsFrom("TH2F")) { hh = (TH2F*)key->ReadObj(); TString hn = hh->GetName(); if ( hn.Contains("ALL" ) ) continue; if ( ! hn.Contains("_LogLog_") ) continue; hh->SetLineColor(icol); if ( first ) {hh->Draw("box"); first=false;} else hh->Draw("same;box"); icol++; if (icol==10) icol=1; } } cc->Print(plname); // now collection-by-collection next = infile->GetListOfKeys(); while ((key = (TKey*)next())) { TClass *cll = gROOT->GetClass(key->GetClassName()); if (cll->InheritsFrom("TDirectory")) { td = (TDirectory*)key->ReadObj(); TString dirname = td->GetName(); if ( dirname=="ALLCollections" ) continue; // is it an endcap collection? bool isEndcap = td->Get(dirname+"_hitXY_posZ"); // first overall geometry cc->Clear(); cc->Divide(3,2); cc->cd(1); ( (TH2F*) td->Get(dirname+"_hitEn"))->Draw("box"); cc->cd(4)->SetLogy(); ( (TH2F*) td->Get(dirname+"_hitTime"))->Draw("box"); if ( isEndcap ) { cc->cd(2); ( (TH2F*) td->Get(dirname+"_hitXY_posZ"))->Draw("box"); cc->cd(3); ( (TH2F*) td->Get(dirname+"_hitXY_negZ"))->Draw("box"); cc->cd(5); ((TH2F*) td->Get(dirname+"_hitZR_posZ"))->Draw("box"); cc->cd(6); ((TH2F*) td->Get(dirname+"_hitZR_negZ"))->Draw("box"); } else { cc->cd(2); ( (TH2F*) td->Get(dirname+"_hitXY"))->Draw("box"); cc->cd(3); ( (TH2F*) td->Get(dirname+"_hitZR"))->Draw("box"); } cc->Print(plname); // then the cell indices // work out how many indices/variables we're dealing with std::vector < TString > indices; std::vector < TString > variables; next2 = td->GetListOfKeys(); while ((key2 = (TKey*)next2())) { cll = gROOT->GetClass(key2->GetClassName()); if (cll->InheritsFrom("TH2F")) { hh = (TH2F*) key2->ReadObj(); TString hn = hh->GetName(); if ( hn.Contains("Indx") ) { TString ss = hn.ReplaceAll(dirname+"_", ""); TString asas = ((TObjString*) (ss.Tokenize("_") -> At(0)))->GetString(); if ( find( indices.begin(), indices.end(), asas )==indices.end() ) indices.push_back(asas); asas = ((TObjString*) (ss.Tokenize("_") -> At(1)))->GetString(); if ( find( variables.begin(), variables.end(), asas )==variables.end() ) variables.push_back(asas); } } } if ( indices.size()==0 || variables.size()==0 ) continue; for (int inp=0; inp<2; inp++) { if ( !isEndcap && inp==1 ) continue; cc->Clear(); cc->Divide(indices.size(), variables.size()); int ic=1; next2 = td->GetListOfKeys(); while ((key2 = (TKey*)next2())) { cll = gROOT->GetClass(key2->GetClassName()); if (cll->InheritsFrom("TH2F")) { hh = (TH2F*) key2->ReadObj(); TString hn = hh->GetName(); if ( isEndcap ) { if ( inp==0 && ! hn.Contains("posZ") ) continue; else if ( inp==1 && ! hn.Contains("negZ") ) continue; } if ( hn.Contains("Indx") ) { TString asas = ((TObjString*) (hn.Tokenize("_") -> At(1)))->GetString(); asas = asas(4,asas.Length()); cc->cd(ic++); hh->Draw("box"); } } } cc->cd(); for ( size_t k=0; k<variables.size(); k++) { tt.DrawTextNDC( 0.0, 0.9 - (1.0*k)/(variables.size()), variables[k] ); } for ( size_t k=0; k<indices.size(); k++) { tt.DrawTextNDC( 0.05 + (1.0*k)/(indices.size()), 0.02, indices[k].ReplaceAll("Indx","Indx_") ); } tt.DrawTextNDC( 0.1, 0.99, dirname); if ( isEndcap ) { if (inp==0 ) tt.DrawTextNDC( 0.35, 0.99, "posZ"); else tt.DrawTextNDC( 0.35, 0.99, "negZ"); } cc->Print(plname); } } } infile->Close(); cc->Print(plname+"]"); }
int main(int argc, char * argv[]){ cout<<"****************************** FILES OPENING ***************************************"<<endl; string INPUT(argv[1]); string OUTPUT(argv[2]); FileSaver finalHistos; FileSaver Plots; finalHistos.setName(INPUT.c_str()); Plots.setName(OUTPUT.c_str()); bool checkfile = finalHistos.CheckFile(); cout<<"****************************** BINS ***************************************"<<endl; SetBins(); PRB.Print(); cout<<"**TOF**"<<endl; ToFDB.Print(); cout<<"**NaF**"<<endl; NaFDB.Print(); cout<<"**Agl**"<<endl; AglDB.Print(); ToFDB.UseBetaEdges(); NaFDB.UseBetaEdges(); AglDB.UseBetaEdges(); PRB.UseREdges(); cout<<endl; cout<<"****************************** READING DATABASES *************************************"<<endl; string filename2="./database_P.root"; TFile * file2 = TFile::Open(filename2.c_str(),"READ"); string filename3="./database_D.root"; TFile * file3 = TFile::Open(filename3.c_str(),"READ"); string filename4="./database_PD.root"; TFile * file4 = TFile::Open(filename4.c_str(),"READ"); std::vector<TGraphAsymmErrors *> D_Graphs; std::vector<TGraphAsymmErrors *> PD_Graphs; TList *ExperimentsD = file3->GetListOfKeys(); TIter nextD(ExperimentsD); TKey * keyD; TObject * obj; while((keyD = (TKey*)nextD())){ obj = file3->Get(keyD->GetName()); if(obj->InheritsFrom("TGraphAsymmErrors")) D_Graphs.push_back((TGraphAsymmErrors *)obj); } TList *ExperimentsPD = file4->GetListOfKeys(); TIter nextPD(ExperimentsPD); TKey * keyPD; while((keyPD = (TKey*)nextPD())){ obj = file4->Get(keyPD->GetName()); if(obj->InheritsFrom("TGraphAsymmErrors")) PD_Graphs.push_back((TGraphAsymmErrors *)obj); } cout<<"****************************** PLOTTING FLUXES ***************************************"<<endl; Flux * DFluxTOF = new Flux(finalHistos, "DFluxTOF", "FullsetEff_D_TOF","FullsetEfficiency","TOFfits/Fit Results/Primary Deuteron Counts","ExposureTOF","Gen. Acceptance",ToFDB); Flux * DFluxNaF = new Flux(finalHistos, "DFluxNaF", "FullsetEff_D_NaF","FullsetEfficiency","NaFfits/Fit Results/Primary Deuteron Counts","ExposureNaF","Gen. Acceptance",NaFDB); Flux * DFluxAgl = new Flux(finalHistos, "DFluxAgl", "FullsetEff_D_Agl","FullsetEfficiency","Aglfits/Fit Results/Primary Deuteron Counts","ExposureAgl","Gen. Acceptance",AglDB); TCanvas *c1 = new TCanvas("Gen. Acceptance"); c1->SetCanvasSize(2000,1500); PlotTH1FintoGraph(gPad,ToFDB, DFluxTOF->GetGenAcceptance(),"Kinetic Energy [GeV/nucl.]", "Gen. Acceptance [m^{2} sr]",1,true,"Psame",0.1,10,0.1,3,"TOF range",8); PlotTH1FintoGraph(gPad,NaFDB, DFluxNaF->GetGenAcceptance(),"Kinetic Energy [GeV/nucl.]", "Gen. Acceptance [m^{2} sr]",1,true,"Psame",0.1,10,0.1,3,"NaF range",22); PlotTH1FintoGraph(gPad,AglDB, DFluxAgl->GetGenAcceptance(),"Kinetic Energy [GeV/nucl.]", "Gen. Acceptance [m^{2} sr]",1,true,"Psame",0.1,10,0.1,3,"Agl range",29); Plots.Add(c1); Plots.writeObjsInFolder("Fluxes"); float potenza = 0; TCanvas *c2 = new TCanvas("Deuteron Primary Flux"); c2->SetCanvasSize(2000,1500); TH2F * Frame = CreateFrame(0.01,25,0.01,1000,"Kin.En./nucl. [GeV/nucl.]","Flux [(m^2 sr GeV/nucl.)^{-1}]"); c2->cd(); gPad->SetLogx(); gPad->SetLogy(); gPad->SetGridx(); gPad->SetGridy(); TGraph* galprop3P=new TGraph(); TGraph* galprop3P2=new TGraph(); float x,y=0; int j=0; { string filename="./Galprop/Tom/deut_1500.dat"; cout<<filename<<endl; ifstream fp(filename.c_str()); while (!fp.eof()){ fp>>x>>y; if(x/1e3>0.05&&x/1e3<=100) galprop3P->SetPoint(j,x/1e3,y*1e7*pow(x/1e3,potenza)); j++; } } j=0; { string filename="./Galprop/Tom/deut_100.dat"; cout<<filename<<endl; ifstream fp(filename.c_str()); while (!fp.eof()){ fp>>x>>y; if(x/1e3>0.05&&x/1e3<=100) galprop3P2->SetPoint(j,x/1e3,y*1e7*pow(x/1e3,potenza)); j++; } } galprop3P->GetXaxis()->SetRangeUser(0.1,20); galprop3P->GetYaxis()->SetRangeUser(1e-3,1e3); galprop3P->SetTitle("Deutons Flux: Geo. Zones"); galprop3P->GetXaxis()->SetTitle("Kin.En./nucl. [GeV/nucl.]"); galprop3P ->GetYaxis()->SetTitle("Flux [(m^2 sr GeV/nucl.)^-1]"); galprop3P ->GetXaxis()->SetTitleSize(0.045); galprop3P->GetYaxis()->SetTitleSize(0.045); galprop3P ->GetYaxis()->SetRangeUser(1e-2,1e4); Frame->Draw(); galprop3P->Draw("sameC"); galprop3P2->Draw("sameC"); TLegend * leg =new TLegend(0.8, 0.1,0.95,0.95); leg->SetName("leg"); for(uint n=0;n<D_Graphs.size();n++){ D_Graphs[n] ->Draw("Psame"); D_Graphs[n]->SetMarkerSize(2); leg->AddEntry(D_Graphs[n],D_Graphs[n]->GetTitle(),"p"); } leg->SetFillColor(0); leg->SetLineWidth(2); leg->Draw("same"); DFluxNaF->GetFlux()->Smooth(); PlotTH1FintoGraph(gPad,ToFDB, DFluxTOF->GetFlux(),"Kinetic Energy [GeV/nucl.]", "Flux",1,true,"Psame",0.1,10,0.01,1000,"This Work (TOF)",8); PlotTH1FintoGraph(gPad,NaFDB, DFluxNaF->GetFlux(),"Kinetic Energy [GeV/nucl.]", "Flux",1,true,"Psame",0.1,10,0.01,1000,"This Work (NaF)",22); PlotTH1FintoGraph(gPad,AglDB, DFluxAgl->GetFlux(),"Kinetic Energy [GeV/nucl.]", "Flux",1,true,"Psame",0.1,10,0.01,1000,"This Work (Agl)",29); Plots.Add(c2); Plots.writeObjsInFolder("Fluxes"); TCanvas *c3 = new TCanvas("D/P ratio"); c3->SetCanvasSize(2000,1500); j=0; TGraph* galprop3DP=new TGraph(); TGraph* galprop3DP2=new TGraph(); { string filename="./Galprop/Tom/dP_1500.dat"; cout<<filename<<endl; ifstream fp(filename.c_str()); while (!fp.eof()){ fp>>x>>y; if(x/1e3>0.05&&x/1e3<=100) galprop3DP->SetPoint(j,x/(0.5*1e3),y); j++; } } j=0; { string filename="./Galprop/Tom/dP_500.dat"; cout<<filename<<endl; ifstream fp(filename.c_str()); while (!fp.eof()){ fp>>x>>y; if(x/1e3>0.05&&x/1e3<=100) galprop3DP2->SetPoint(j,x/(0.5*1e3),y); j++; } } galprop3DP->GetXaxis()->SetRangeUser(0.1,20); galprop3DP->SetTitle("Deutons Flux: Geo. Zones"); galprop3DP->GetXaxis()->SetTitle("Kin.En./nucl. [GeV/nucl.]"); galprop3DP ->GetYaxis()->SetTitle("Flux [(m^2 sr GeV/nucl.)^-1]"); galprop3DP ->GetXaxis()->SetTitleSize(0.045); TH1F * DPRatioTOF = (TH1F *)finalHistos.Get("Fluxes/DP ratio TOF"); TH1F * DPRatioNaF = (TH1F *)finalHistos.Get("Fluxes/DP ratio NaF"); TH1F * DPRatioAgl = (TH1F *)finalHistos.Get("Fluxes/DP ratio Agl"); DPRatioNaF->Smooth(); cout<<DPRatioTOF<<endl; PlotTH1FintoGraph(gPad,ToFDB, DPRatioTOF ,"Kinetic Energy [GeV/nucl.]", "Flux",1,true,"Psame",0.1,10,0.00001,0.07,"This Work (TOF)",8); PlotTH1FintoGraph(gPad,NaFDB, DPRatioNaF ,"Kinetic Energy [GeV/nucl.]", "Flux",1,true,"Psame",0.1,10,0.00001,0.07,"This Work (NaF)",22); PlotTH1FintoGraph(gPad,AglDB, DPRatioAgl ,"Kinetic Energy [GeV/nucl.]", "Flux",1,true,"Psame",0.1,10,0.00001,0.07,"This Work (Agl)",29); galprop3DP->Draw("sameC"); galprop3DP2->Draw("sameC"); leg = (TLegend*) gPad->FindObject("leg"); for(uint n=0;n<PD_Graphs.size();n++){ PD_Graphs[n] ->Draw("Psame"); PD_Graphs[n]->SetMarkerSize(2); leg->AddEntry(PD_Graphs[n],PD_Graphs[n]->GetTitle(),"p"); } Plots.Add(c3); Plots.writeObjsInFolder("Fluxes"); return 0; }
void dumpComparePDF(std::string inputFile1_,std::string inputFile2_,bool normalize=true) { TString endfix1=gSystem->GetFromPipe(Form("file=%s; test=${file##*/}; echo \"${test%%.root}\"",inputFile1_.data())); cout << endfix1 << endl; TString endfix2=gSystem->GetFromPipe(Form("file=%s; test=${file##*/}; echo \"${test%%.root}\"",inputFile2_.data())); cout << endfix2 << endl; TLegend* leg = new TLegend(0.3333,0.7027,0.8333,0.9023); leg->SetFillColor(0); leg->SetFillStyle(0); leg->SetTextSize(0.04); leg->SetBorderSize(0); std::string dirName = "fig"; gSystem->mkdir(dirName.data()); std::string outputFileName=Form("%s/%s_%s.pdf",dirName.data(), endfix1.Data(), endfix2.Data()); TCanvas* c1 = new TCanvas("c1","",500,500); TFile *_file1 = TFile::Open(inputFile1_.data()); TFile *_file2 = TFile::Open(inputFile2_.data()); _file1->cd(); TDirectory *current_sourcedir = gDirectory; int nPage=0; // loop over all keys in this directory TIter nextkey( current_sourcedir->GetListOfKeys() ); TKey *key; while ((key = (TKey*)nextkey()) ) { TObject *obj = key->ReadObj(); if ( obj->IsA()->InheritsFrom( "TH1" ) ) { // descendant of TH1 -> scale it cout << "outputing histogram " << obj->GetName() << endl; TH1 *h1 = (TH1*)_file1->FindObjectAny(obj->GetName()); h1->SetMarkerStyle(8); h1->SetMarkerSize(1); h1->SetLineWidth(3); h1->SetLineColor(4); TH1 *h2 = (TH1*)_file2->FindObjectAny(obj->GetName()); h2->SetMarkerStyle(25); h2->SetMarkerSize(1); h2->SetLineWidth(3); h2->SetLineColor(2); gStyle->SetOptStat(0); h1->Sumw2(); h2->Sumw2(); if(normalize) { h1->Scale(1.0/h1->Integral()); h2->Scale(1.0/h2->Integral()); } float max = h1->GetMaximum()>h2->GetMaximum()? h1->GetMaximum():h2->GetMaximum(); h1->SetMaximum(1.1*max); h2->SetMaximum(1.1*max); double chi2=0.; int nbins=0; chi2NbinsCompare(h1,h2,chi2,nbins,1,h1->GetNbinsX()); h1->Draw("hist"); h2->Draw("histsame"); leg->Clear(); leg->SetHeader(""); leg->AddEntry((TObject*)0, Form("#chi^{2}/NDF=%.1f/%d",chi2,nbins), ""); leg->AddEntry((TObject*)0, Form("#chi^{2} Prob=%.2f",TMath::Prob(chi2,nbins)), ""); leg->AddEntry((TObject*)0, "", ""); leg->AddEntry(h1,endfix1.Data(),"l"); leg->AddEntry(h2,endfix2.Data(),"l"); leg->Draw("same"); if(nPage==0) c1->Print(Form("%s(",outputFileName.data()),"pdf"); else c1->Print(Form("%s",outputFileName.data()),"pdf"); nPage++; } // if the object is a histogram } // loop over keys c1->Print(Form("%s)",outputFileName.data()),"pdf"); }
void process_file(TFile* file, float stdmargin) { standardmargin=stdmargin; xsecfilename=PlottingSetup::cbafbasedir+"/"+PlottingSetup::SMSReferenceXSFile; // can receive a file with systematics and limits mixed, or a file with systematics only , or a file with limits only. TIter nextkey(file->GetListOfKeys()); TKey *key; int scantype=PlottingSetup::SMS; std::string scanx = "0"; // Just for the legend vector<TH2F*> systematics_histos; vector<TH2F*> limits_histos; while ((key = (TKey*)nextkey())) { TObject *obj = key->ReadObj(); if (!(obj->IsA()->InheritsFrom("TH2"))) continue; TString name=(TString)(obj->GetName()); bool is_limit=false; bool is_systematic=false; if(name.Contains("limitmap")) is_limit=true; if(name.Contains("explimitmap")) is_limit=true; if(name.Contains("exp1plimitmap")) is_limit=true; if(name.Contains("exp2plimitmap")) is_limit=true; if(name.Contains("exp1mlimitmap")) is_limit=true; if(name.Contains("exp2mlimitmap")) is_limit=true; if(name.Contains("exclusionmap")) is_limit=true; if(name.Contains("crosssectionmap")) is_limit=true; if(name.Contains("XS")) is_limit=true; if(name.Contains("absXS")) is_limit=true; if(name.Contains("limitflipmap")) is_limit=true; if(name.Contains("sysjes")) is_systematic=true; if(name.Contains("sysjsu")) is_systematic=true; if(name.Contains("sysresmap")) is_systematic=true; if(name.Contains("efficiencymap")) is_systematic=true; if(name.Contains("efficiencymapAcc")) is_systematic=true; if(name.Contains("efficiencymapID")) is_systematic=true; if(name.Contains("efficiencymapJets")) is_systematic=true; if(name.Contains("efficiencymapSignal")) is_systematic=true; if(name.Contains("noscefficiencymap")) is_systematic=true; if(name.Contains("Neventsmap")) is_systematic=true; if(name.Contains("ipointmap")) is_systematic=true; if(name.Contains("syspdfmap")) is_systematic=true; if(name.Contains("systotmap")) is_systematic=true; if(name.Contains("sysstatmap")) is_systematic=true; if(name.Contains("timemap")) is_systematic=true; if(name.Contains("flipmap")) is_systematic=true; if(name.Contains("limitmap0")) continue; if(is_limit) limits_histos.push_back((TH2F*) obj); else if(is_systematic) systematics_histos.push_back((TH2F*) obj); if(name.Contains("mSUGRA")) scantype=PlottingSetup::mSUGRA; if(name.Contains("GMSB")) scantype=PlottingSetup::GMSB; if(name.Contains("ScanIdentifier")) scanx=IdentifyScan(name); } // if (TString(file->GetName()).Contains("T5zzl")) scanx = "0.75"; // else if(TString(file->GetName()).Contains("T5zzh")) scanx = "0.25"; // else if(TString(file->GetName()).Contains("T5zz")) scanx = "0.5"; write_warning(__FUNCTION__,"Deactivated systematics plots"); // if(systematics_histos.size()>0) make_all_syst_plots(systematics_histos,scantype,scanx); if(limits_histos.size()>0) create_exclusion_plots(limits_histos,scantype,scanx); }
void EWKcorr_Ele() { // Int_t iso=00; Int_t pt=3; Target = TFile::Open( "Total_FRcorr60_60.root", "RECREATE" ); char faa[100]; FileList = new TList(); strcpy(faa,""); sprintf(faa,"SingleElectron_FR60_60.root"); FileList->Add( TFile::Open(faa) ); strcpy(faa,""); sprintf(faa,"Wjets_FR60_60.root"); FileList->Add( TFile::Open(faa) ); strcpy(faa,""); sprintf(faa,"DY_10-50_FR60_60.root"); FileList->Add( TFile::Open(faa) ); strcpy(faa,""); sprintf(faa,"DY_50_FR60_60.root"); FileList->Add( TFile::Open(faa) ); strcpy(faa,""); sprintf(faa,"ttbar_FR60_60.root"); FileList->Add( TFile::Open(faa) ); strcpy(faa,""); sprintf(faa,"Wgamma_FR60_60.root"); FileList->Add( TFile::Open(faa) ); strcpy(faa,""); /* sprintf(faa,"Zjet_20-30_FR60_28.root"); FileList->Add( TFile::Open(faa) ); strcpy(faa,""); sprintf(faa,"Zjet_30-50_FR60_28.root"); FileList->Add( TFile::Open(faa) ); strcpy(faa,""); sprintf(faa,"Zjet_50-80_FR60_28.root"); FileList->Add( TFile::Open(faa) ); strcpy(faa,""); sprintf(faa,"Zjet_80-120_FR60_28.root"); FileList->Add( TFile::Open(faa) ); strcpy(faa,""); sprintf(faa,"Zjet_120-170_FR60_28.root"); FileList->Add( TFile::Open(faa) ); strcpy(faa,""); sprintf(faa,"Zjet_170-230_FR60_28.root"); FileList->Add( TFile::Open(faa) ); strcpy(faa,""); sprintf(faa,"Zjet_230-300_FR60_28.root"); FileList->Add( TFile::Open(faa) ); strcpy(faa,""); sprintf(faa,"Zjet_300_FR60_28.root"); FileList->Add( TFile::Open(faa) ); */ FileList->Print(); TString path( (char*)strstr( Target->GetPath(), ":" ) ); path.Remove( 0, 2 ); TFile *first_source = (TFile*)FileList->First(); first_source->cd( path ); TDirectory *current_sourcedir = gDirectory; // loop over all keys in this directory TChain *globChain = 0; TIter nextkey( current_sourcedir->GetListOfKeys() ); TKey *key; while ( (key = (TKey*)nextkey())) { // read object from first source file first_source->cd( path ); TObject *obj = key->ReadObj(); if ( obj->IsA()->InheritsFrom( "TH1F" ) || obj->IsA()->InheritsFrom( "TH2F" ) ) { // descendant of TH1F -> merge it // cout << "Merging histogram " << obj->GetName() << endl; TH1F *h1 = (TH1F*)obj; // loop over all source files and add the content of the // correspondant histogram to the one pointed to by "h1" TFile *nextsource = (TFile*)FileList->After( first_source ); Int_t scal=0; while ( nextsource ) { // make sure we are at the correct directory level by cd'ing to path nextsource->cd( path ); TH1F *h2 = (TH1F*)gDirectory->Get( h1->GetName() ); h1->SetDefaultSumw2(true); if ( h2 ) { h2->SetDefaultSumw2(true); h1->Add( h2 , scaling[scal] ); //scale factor not need if is need the same as to be applied to h1 cout<<"file "<<nextsource->GetName()<<endl; cout<<"scaling "<<scaling[scal]<<" scal "<<scal<<endl; delete h2; // don't know if this is necessary, i.e. if // h2 is created by the call to gDirectory above. } nextsource = (TFile*)FileList->After( nextsource ); scal++; } } // 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(); obj->Write( key->GetName() ); } } // while ( ( TKey *key = (TKey*)nextkey() ) ) Target->Write(); Target->cd(); getFakerate2(h_nEvents, h_nEventsFO, h_FOrate); getFakerate1(h_nVertex1, h_nVertex0, h_nVertex2); h_FOrate->Write("h_FOrate3"); h_nEvents->Write("h_Events2"); h_nEventsFO->Write("h_EventsFO2"); h_nVertex1->Write("h_nVertex1_2"); h_nVertex0->Write("h_nVertex0_2"); h_nVertex2->Write("h_nVertex3"); delete h_nVertex2; delete h_FOrate; Target->Close(); }
int main( int argc, char* argv[] ) { DrawTools::setStyle(); std::string tag = "V00"; std::string config = "SiPM2015Config"; if( argc>1 ) { std::string tag_str(argv[1]); tag = tag_str; if( argc>2 ) { std::string config_str(argv[2]); config=config_str; } } else { std::cout << "Usage:" << std::endl; std::cout << "./plotterMaps ([tag]) ([config])" << std::endl; exit(12345); } std::cout<<config<<std::endl; theConfiguration_=readConfiguration(config); std::string constDirName = "plots_Simplemaps_"; constDirName+=theConfiguration_.setup; if(theConfiguration_.addTagFileName){ constDirName+="_"; constDirName+=theConfiguration_.tagFileName; } system(Form("mkdir -p %s", constDirName.c_str())); TString dir(constDirName); TString filename= "plots_timingPerformance_"+theConfiguration_.setup+"/mapCreatorOutput_"+tag+".root"; TFile* file = TFile::Open(filename.Data()); std::map<TString,TH1F*> histoNames; std::map<TString,TH2F*> histoNames2D; TList* list = file->GetListOfKeys() ; if (!list) { printf("<E> No keys found in file\n") ; exit(1) ; } TIter next(list) ; TKey* key ; TObject* obj ; while ( key = (TKey*)next() ) { obj = key->ReadObj() ; if ( (strcmp(obj->IsA()->GetName(),"TProfile")!=0) && (!obj->InheritsFrom("TH2")) && (!obj->InheritsFrom("TH1")) ) { printf("<W> Object %s is not 1D or 2D histogram : " "will not be converted\n",obj->GetName()) ; } printf("Histo name:%s title:%s\n",obj->GetName(),obj->GetTitle()); if((strcmp(obj->IsA()->GetName(),"TH1F"))==0){ histoNames[obj->GetName()]=(TH1F*)obj; }else if ((strcmp(obj->IsA()->GetName(),"TH2F"))==0){ histoNames2D[obj->GetName()]=(TH2F*)obj; } } for(std::map<TString,TH2F*>::const_iterator out=histoNames2D.begin();out!=histoNames2D.end();++out){ gStyle->SetPadRightMargin(0.19);//for the palette and ztitle TCanvas c1; TH2F* histo=(TH2F*)out->second->Clone(out->first+"_clone"); histo->GetZaxis()->SetTitleOffset(1.4); if(out->first.Contains("amplitude"))histo->SetZTitle("Amplitude [ADC]"); if(out->first.Contains("timing"))histo->SetZTitle("#DeltaT [ns]"); histo->Draw("colz"); c1.SaveAs(dir+"/"+out->first+".pdf"); c1.SaveAs(dir+"/"+out->first+".png"); } gStyle->SetPadRightMargin(0.10); TH1F* maxAmpl_sel_fibre=(TH1F*)file->Get("maxAmpl_sel_fibre"); TH1F* maxAmpl_sel_channel=(TH1F*)file->Get("maxAmpl_sel_channel"); TCanvas c2; maxAmpl_sel_channel->GetXaxis()->SetRangeUser(0,800.); maxAmpl_sel_channel->SetLineWidth(2); maxAmpl_sel_fibre->SetLineWidth(2); maxAmpl_sel_channel->DrawNormalized(); maxAmpl_sel_fibre->DrawNormalized("same"); TPaveText* pave = DrawTools::getLabelTop_expOnXaxis("Electron Beam"); pave->Draw("same"); c2.SaveAs(dir+"/maxAmpl_comparison.pdf"); c2.SaveAs(dir+"/maxAmpl_comparison.png"); }
int main(int argc, char * argv[]) { string programName(argv[0]); string descString(programName); descString += " [options] "; descString += "data_file \nAllowed options"; options_description desc(descString); desc.add_options() (kHelpCommandOpt, "produce help message") (kOutputFileCommandOpt, value<string>()->default_value("out.root"), "output root file") (kWeightsCommandOpt, value<string>(), "list of weights (comma separates).\ndefault: weights are assumed to be 1") (kInputFilesCommandOpt, value<vector<string> >()->multitoken(), "input root files"); positional_options_description p; variables_map vm; try { store(command_line_parser(argc,argv).options(desc).positional(p).run(), vm); notify(vm); } catch(const error&) { cerr << "invalid arguments. usage:" << endl; cerr << desc <<std::endl; return -1; } if(vm.count(kHelpOpt)) { cout << desc <<std::endl; return 0; } vector<string> fileNames; if(vm.count(kInputFilesOpt)) { fileNames = vm[kInputFilesOpt].as<vector<string> >(); } else { cerr << "option -i must be specifyed" << endl; return -1; } if(fileNames.size()==0) { cerr << "at least one file name must be specified with option -i" <<endl; return -1; } string outputFile; if(vm.count(kOutputFileOpt)) { outputFile = vm[kOutputFileOpt].as<string>(); } else { cerr << "option -o must be specifyed" << endl; return -1; } if(vm.count(kWeightsOpt)) { string w = vm[kWeightsOpt].as<string>(); char_separator<char> sep(","); tokenizer<char_separator<char> > tokens(w, sep); for(tokenizer<char_separator<char> >::iterator t = tokens.begin(); t != tokens.end();++t) { const char * begin = t->c_str(); char * end; double w = strtod(begin, &end); size_t s = end - begin; if(s < t->size()) { cerr << "invalid weight: " << begin << endl; exit(1); } weights.push_back(w); } } else { weights = vector<double>(fileNames.size(), 1.0); } if(weights.size() != fileNames.size()) { cerr << "the number of weights and the number of files must be the same" << endl; exit(-1); } gROOT->SetBatch(); TFile out(outputFile.c_str(), "RECREATE"); if(!out.IsOpen()) { cerr << "can't open output file: " << outputFile <<endl; return -1; } bool empty = true; for(size_t i = 0; i < fileNames.size(); ++i) { string fileName = fileNames[i]; TFile file(fileName.c_str(), "read"); if(!file.IsOpen()) { cerr << "can't open input file: " << fileName <<endl; return -1; } TIter next(file.GetListOfKeys()); TKey *key; while ((key = dynamic_cast<TKey*>(next()))) { string className(key->GetClassName()); string name(key->GetName()); TObject * obj = file.Get(name.c_str()); if(obj == 0) { cerr <<"error: key " << name << " not found in file " << fileName << endl; return -1; } if(empty) make(out, obj); fill(out, obj, weights[i]); } file.Close(); empty = false; } out.Write(); out.Close(); return 0; }
void rescaleSignal(bool armed, double scale, const char* filename, const char* pattern="", unsigned int debug=0) { std::vector<std::string> histnames; histnames.clear(); if( debug>0 ){ std::cout << "file = " << filename << std::endl; std::cout << "scale = " << scale << std::endl; std::cout << "armed = " << armed << std::endl; } TFile* file = new TFile(filename, "update"); TIter nextDirectory(file->GetListOfKeys()); std::vector<std::string> buffer; TKey* idir; while((idir = (TKey*)nextDirectory())){ buffer.clear(); if( idir->IsFolder() ){ file->cd(); // make sure to start in directory head if( debug>0 ){ std::cout << "Found directory: " << idir->GetName() << std::endl; } if( file->GetDirectory(idir->GetName()) ){ file->cd(idir->GetName()); // change to sub-directory buffer = signalList(idir->GetName(), pattern, debug); } // append to the vector of histograms to be rescaled for(std::vector<std::string>::const_iterator elem=buffer.begin(); elem!=buffer.end(); ++elem){ histnames.push_back(*elem); } if(debug>1){ std::cout << "added " << buffer.size() << " elements to histnames [" << histnames.size() << "] for directory " << idir->GetName() << std::endl; } } } // pick up files which are not kept in an extra folder file->cd(); buffer.clear(); buffer = signalList("", pattern, debug); // append to the vector of histograms to be rescaled for(std::vector<std::string>::const_iterator elem=buffer.begin(); elem!=buffer.end(); ++elem){ histnames.push_back(*elem); } if(debug>1){ std::cout << "added " << buffer.size() << " elements to histnames [" << histnames.size() << "] for file head" << std::endl; } for(std::vector<std::string>::const_iterator hist=histnames.begin(); hist!=histnames.end(); ++hist){ file->cd(); TH1F* h = (TH1F*)file->Get(hist->c_str()); std::string histName; if(hist->find("/")!=std::string::npos){ histName = hist->substr(hist->find("/")+1); } else{ histName = *hist; } TH1F* hout = (TH1F*)h->Clone(histName.c_str()); if(debug>1){ std::cout << "...folder : " << hist->substr(0, hist->find("/")).c_str() << std::endl; std::cout << "...histogram : " << hout->GetName () << " / " << hist->c_str() << std::endl; std::cout << "...old scale : " << hout->Integral() << std::endl; } hout->Scale(scale); if(match(pattern, "data")){ //make sure to have an integer integral when rescaling data yields hout->Scale(int(hout->Integral())/hout->Integral()); } if(debug>1){ std::cout << "...new scale : " << hout->Integral() << std::endl; } if(armed){ if(hist->find("/")!=std::string::npos){ file->cd(hist->substr(0, hist->find("/")).c_str()); } else{ file->cd(); } std::cout << "writing to file: " << hout->GetName() << std::endl; hout->Write(hist->substr(hist->find("/")+1).c_str(), TObject::kOverwrite); } } file->Close(); return; }
void rescale2SM4(bool armed, const char* filename, double ecms=7., double mass=-1) { unsigned int debug = 1; std::vector<std::string> histnames; histnames.clear(); if( debug>0 ){ std::cout << "file = " << filename << std::setw(10); std::cout << "mass = " << mass << std::setw(10); std::cout << "armed = " << armed << std::endl; } TFile* file = new TFile(filename, "update"); TIter nextDirectory(file->GetListOfKeys()); std::vector<std::string> buffer; TKey* idir; while((idir = (TKey*)nextDirectory())){ buffer.clear(); if( idir->IsFolder() ){ file->cd(); // make sure to start in directory head if( debug>1 ){ std::cout << "Found directory: " << idir->GetName() << std::endl; } if( file->GetDirectory(idir->GetName()) ){ file->cd(idir->GetName()); // change to sub-directory buffer = signalList(idir->GetName(), "", debug); } // append to the vector of histograms to be rescaled for(std::vector<std::string>::const_iterator elem=buffer.begin(); elem!=buffer.end(); ++elem){ histnames.push_back(*elem); } if(debug>1){ std::cout << "added " << buffer.size() << " elements to histnames [" << histnames.size() << "] for directory " << idir->GetName() << std::endl; } } } // pick up histograms which are not kept in an extra folder file->cd(); buffer.clear(); buffer = signalList("", "", debug); // append to the vector of histograms to be rescaled for(std::vector<std::string>::const_iterator elem=buffer.begin(); elem!=buffer.end(); ++elem){ histnames.push_back(*elem); } if(debug>1){ std::cout << "added " << buffer.size() << " elements to histnames [" << histnames.size() << "] for file head" << std::endl; } HiggsCSandWidth smx; HiggsCSandWidthSM4 sm4; for(std::vector<std::string>::const_iterator hist=histnames.begin(); hist!=histnames.end(); ++hist){ int type = 0; // determine mass from hostogram name std::string strippedName = (hist->find("/")!=std::string::npos ? hist->substr(hist->find("/")+1) : *hist); std::string massName; if(strippedName.find("ggH")!=std::string::npos) { massName = strippedName.substr(3, 3); type = 1; } if(strippedName.find("qqH")!=std::string::npos) { massName = strippedName.substr(3, 3); type = 2; } if(strippedName.find("VH" )!=std::string::npos) { massName = strippedName.substr(2, 3); type = 3; } if( type==0 ) { std::cout << "not supported process" << std::endl; continue; } else { file->cd(); float mdx = atof(massName.c_str()); TH1F* h = (TH1F*)file->Get(hist->c_str()); float smxXS = type==1 ? smx.HiggsCS(type, mdx, ecms, true) : 0.; float smxBR = smx.HiggsBR(2, mdx, true); float sm4XS = type==1 ? sm4.HiggsCS(type, mdx, ecms, true) : 0.; float sm4BR = sm4.HiggsBR(2, mdx, true); if( debug>1 ){ std::cout << " -- hist = " << std::setw(10) << h->GetName() << std::endl << " -- type = " << std::setw(10) << type << std::endl << " -- mass = " << std::setw(10) << mdx << std::endl << " -- SM = " << std::setw(10) << smxXS*smxBR << " (BR = " << smxBR << ")" << std::endl << " -- SM4 = " << std::setw(10) << sm4XS*sm4BR << " (BR = " << sm4BR << ")" << std::endl << " -- scale = " << std::setw(10) << (type==1 ? sm4XS*sm4BR/(smxXS*smxBR) : 0) << std::endl << std::endl; } if( type==1 ){ h->Scale(sm4XS*sm4BR/(smxXS*smxBR)); } //scaling old style //if( type==2 ){ h->Scale(sm4BR/smxBR); } //if( type==3 ){ h->Scale(sm4BR/smxBR); } // scaling new style if( type==2 ){ h->Scale(0.); } if( type==3 ){ h->Scale(0.); } if(armed){ if(hist->find("/")!=std::string::npos){ file->cd(hist->substr(0, hist->find("/")).c_str()); } else{ file->cd(); } h->Write(strippedName.c_str(), TObject::kOverwrite); } } } file->Close(); return; }
void loadHist(const char* filename, const char* pfx, const char* pat, Bool_t doAdd, Double_t scaleFactor) { cout << " Reading histograms from file: " << filename << endl << flush ; TFile inf(filename) ; //inf.ReadAll() ; TList* list = inf.GetListOfKeys() ; TIterator* iter = list->MakeIterator(); TRegexp re(pat,kTRUE) ; std::cout << "pat = " << pat << std::endl ; gDirectory->cd("Rint:") ; TObject* obj ; TKey* key ; std::cout << "doAdd = " << (doAdd?"T":"F") << std::endl ; std::cout << "loadHist: reading." ; while((key=(TKey*)iter->Next())) { Int_t ridx = TString(key->GetName()).Index(re) ; if (ridx==-1) { continue ; } obj = inf.Get(key->GetName()) ; TObject* clone ; if (pfx) { // Find existing TH1-derived objects TObject* oldObj = 0 ; if (doAdd){ oldObj = gDirectory->Get(Form("%s_%s",pfx,obj->GetName())) ; if (oldObj && !oldObj->IsA()->InheritsFrom(TH1::Class())) { oldObj = 0 ; } } if (oldObj) { clone = oldObj ; if ( scaleFactor > 0 ) { ((TH1*)clone)->Sumw2() ; ((TH1*)clone)->Add((TH1*)obj, scaleFactor) ; } else { ((TH1*)clone)->Add((TH1*)obj) ; } } else { clone = obj->Clone(Form("%s_%s",pfx,obj->GetName())) ; } } else { // Find existing TH1-derived objects TObject* oldObj = 0 ; if (doAdd){ oldObj = gDirectory->Get(key->GetName()) ; if (oldObj && !oldObj->IsA()->InheritsFrom(TH1::Class())) { oldObj = 0 ; } } if (oldObj) { clone = oldObj ; if ( scaleFactor > 0 ) { ((TH1*)clone)->Sumw2() ; ((TH1*)clone)->Add((TH1*)obj, scaleFactor) ; } else { ((TH1*)clone)->Add((TH1*)obj) ; } } else { clone = obj->Clone() ; } } if ( scaleFactor > 0 && !doAdd ) { ((TH1*) clone)->Sumw2() ; ((TH1*) clone)->Scale(scaleFactor) ; } if (!gDirectory->GetList()->FindObject(clone)) { gDirectory->Append(clone) ; } std::cout << "." ; std::cout.flush() ; } std::cout << std::endl; inf.Close() ; delete iter ; }
void loopPlot(){ gErrorIgnoreLevel=kFatal;//suppresses all info messages setTDRStyle();//TDR style //#####################EDIT THE OPTIONS############################## /// Boolean flags to steer the histogram making bool wantElectrons = false; // Will make histograms for electrons bool wantMuons = true; // Will make histograms for muons bool wantSideband = false; // Will make histograms for sideband region bool wantSignal = true; // Will make histograms for signal region bool wantFullRange = false; // Will not check signal or sideband, ie, pick all jet mass range int wantNXJets = 1; // Will make histograms for 1 or 2 jet topology int isZZchannel = 1; //plot label for zz (1) or ww (0) int flavour = 0; if(wantElectrons) flavour=11; if(wantMuons) flavour=13; /// Luminosity value in pb^-1 //double lumiValue = 19531.85;// for singleEle2012 // double lumiValue = 19747; // for doubleMu2012 //double lumiValue = 19788; // for doubleEle2012 double lumiValue = 19768.0; /// Should we scale the histograms to data? bool scaleToData = false; // Should we scale only wjets to make total MC = DATA? bool scaleOnlyWJets = false; /// Should we plot the Data/Bkg and Data-Bkg/Error ratios? bool makeRatio = false; /// Should we REDO histograms? bool redoHistograms = true; /// Should we put the signal MC stacked on top of the background (or just plot the signal alone)? bool isSignalStackOnBkg = false; /// Path to wherever the files with the trees are. //CA8 (cmgTuple_08032013_CA8) std::string pathToTrees="/afs/cern.ch/user/b/bonato/scratch0/PhysAnalysis/EXOVV_2012/analyzer_trees/productionv2i/fullsig/"; /// Path to wherever you want to put the histograms (figures) in. std::string outputDir = "./plots_productionv2i_fullsig_1JLP_MU"; /// Setup names of data files for trees. const int nDATA=4; std::string dataLabels[nDATA]={"DoubleMu_Run2012A_22Jan2013", "DoubleMuParked_Run2012B_22Jan2013", "DoubleMuParked_Run2012C_22Jan2013", "DoubleMuParked_Run2012D_22Jan2013"}; /* const int nDATA=4;//set to zero if you don't want to plot std::string dataLabels[nDATA]={"Photon_Run2012A_22Jan2013", "DoublePhotonHighPt_Run2012B_22Jan2013", "DoublePhotonHighPt_Run2012C_22Jan2013", "DoublePhotonHighPt_Run2012D_22Jan2013" }; */ /* const int nDATA=8;//set to zero if you don't want to plot std::string dataLabels[nDATA]={"DoubleMu_Run2012A_22Jan2013", "DoubleMuParked_Run2012B_22Jan2013", "DoubleMuParked_Run2012C_22Jan2013", "DoubleMuParked_Run2012D_22Jan2013", "Photon_Run2012A_22Jan2013", "DoublePhotonHighPt_Run2012B_22Jan2013", "DoublePhotonHighPt_Run2012C_22Jan2013", "DoublePhotonHighPt_Run2012D_22Jan2013" }; */ /* const int nDATA=7;//set to zero if you don't want to plot std::string dataLabels[nDATA]={"SingleElectron_Run2012A_13Jul2012_xww", "SingleElectron_Run2012A_recover_xww", "SingleElectron_Run2012B_13Jul2012_xww", "SingleElectron_Run2012C_24Aug2012_xww", "SingleElectron_Run2012C_PromptReco_xww", "SingleElectron_Run2012C_EcalRecove_xww", "SingleElectron_Run2012D_PromptReco_xww"}; const int nDATA=7;//set to zero if you don't want to plot std::string dataLabels[nDATA]={"SingleMu_Run2012A_13Jul2012_xww", "SingleMu_Run2012A_recover_xww", "SingleMu_Run2012B_13Jul2012_xww", "SingleMu_Run2012C_24Aug2012_xww", "SingleMu_Run2012C_PromptReco_xww", "SingleMu_Run2012C_EcalRecove_xww", "SingleMu_Run2012D_PromptReco_xww"}; */ /* const int nDATA=1;//set to zero if you don't want to plot std::string dataLabels[nDATA]={"data_xww"}; */ /* const int nDATA=0;//set to zero if you don't want to plot std::string dataLabels[nDATA]={}; */ std::vector<std::string> fData; for(int ii=0;ii<nDATA;ii++){ fData.push_back(pathToTrees+"treeEDBR_"+dataLabels[ii]+".root"); } /// Setup names of MC files for trees. const int nMC=6;//set to zero if you don't want to plot std::string mcLabels[nMC]={"TTBARpowheg", "WW", "WZ", "ZZ", "DYJetsPt70To100", "DYJetsPt100", }; double kFactorsMC_array[nMC] = {1, 1, 1, 1, 1, 1}; /* const int nMC=7;//set to zero if you don't want to plot std::string mcLabels[nMC]={"TTBARpowheg", "WW", "WZ", "ZZ", "DYJetsPt50To70", "DYJetsPt70To100", "DYJetsPt100"}; double kFactorsMC_array[nMC] = {1., 1., 1., 1., 1., 1., 1.}; */ /* const int nMC=5;//set to zero if you don't want to plot std::string mcLabels[nMC]={//"TTBAR_xww", "TTBARpowheg_xww", //"SingleTopBarTWchannel_xww", //"SingleTopTWchannel_xww", //"SingleTopBarSchannel_xww", //"SingleTopSchannel_xww", //"SingleTopBarTchannel_xww", //"SingleTopTchannel_xww", "SingleTop_xww", //"WW_xww", //"WZ_xww", //"ZZ_xww", "VV_xww", //"DYJetsPt50To70_xww", //"DYJetsPt70To100_xww", //"DYJetsPt100_xww", "DYJets_xww", //"WJetsPt50To70_xww", //"WJetsPt70To100_xww", // "WJetsPt180_xww", "WJetsPt100_xww", }; */ //WW, muon channel //double kFactorsMC_array[nMC] = {1, 1., 1., 1., 1.3}; //WW, electron channel std::vector<std::string> fMC; for(int ii=0;ii<nMC;ii++){ fMC.push_back(pathToTrees+"treeEDBR_"+mcLabels[ii]+".root"); } std::vector<double> kFactorsMC; //std::cout << "The contents of kFactorsMC are:" << std::endl; for (int index=0; index<nMC; index++) { //std::cout << kFactorsMC_array[index] << std::endl; kFactorsMC.push_back( kFactorsMC_array[index] ); } /// Setup names of MC signal files for trees. const int nMCSig=1;//set to zero if you don't want to plot std::string mcLabelsSig[nMCSig]={"BulkG_ZZ_lljj_c0p2_M1000" //"BulkG_WW_lvjj_c0p2_M1000_xww", //"BulkG_WW_lvjj_c0p2_M2000_xww" }; double kFactorsSig_array[nMCSig] = {1000.0}; std::vector<double> kFactorsMCSig; for (int index=0; index<nMCSig; index++) { kFactorsMCSig.push_back( kFactorsSig_array[index] ); } /* const int nMCSig=1;//set to zero if you don't want to plot std::string mcLabelsSig[nMCSig]={"BulkG_ZZ_lljj_c1p0_M1500"}; */ std::vector<std::string> fMCSig; for(int ii=0;ii<nMCSig;ii++){ fMCSig.push_back(pathToTrees+"treeEDBR_"+mcLabelsSig[ii]+".root"); } /// Setup names of files for histograms (data and MC) std::vector<std::string> fHistosData; std::vector<std::string> fHistosMC; std::vector<std::string> fHistosMCSig; char buffer[256]; printf("All strings set\n"); /// ---------------------------------------------------------------- /// This first part is the loop over trees to create histogram files /// ---------------------------------------------------------------- /// The EDBRHistoMaker, for reference /// ///EDBRHistoMaker::EDBRHistoMaker(TTree* tree, /// bool wantElectrons, /// bool wantMuons, /// bool wantSideband, /// bool wantSignal, /// int wantNXJets, /// bool isZZchannel) printf("\nStart making histograms\n\n"); //loop over data files and make histograms individually for each of them for(int i=0;i<nDATA;i++){ std::cout<<"\n-------\nRunning over "<<dataLabels[i].c_str()<<std::endl; std::cout<<"The file is " <<fData.at(i)<<std::endl; sprintf(buffer,"histos_%s.root",dataLabels[i].c_str()); fHistosData.push_back(buffer); if(redoHistograms) { TFile *fileData = TFile::Open(fData.at(i).c_str()); TTree *treeData = (TTree*)fileData->Get("SelectedCandidates"); EDBRHistoMaker* maker = new EDBRHistoMaker(treeData, wantElectrons, wantMuons, wantSideband, wantSignal, wantFullRange, wantNXJets, isZZchannel); maker->setUnitaryWeights(true); maker->Loop(buffer); //delete maker; // This class is badly written and deleting it isn't safe! fileData->Close(); } }//end loop on data files printf("Loop over data done\n"); //loop over MC files and make histograms individually for each of them for(int i=0;i<nMC;i++){ std::cout<<"\n-------\nRunning over "<<mcLabels[i].c_str()<<std::endl; std::cout<<"The file is " <<fMC.at(i)<<std::endl; sprintf(buffer,"histos_%s.root",mcLabels[i].c_str()); fHistosMC.push_back(buffer); if(redoHistograms){ TFile *fileMC = TFile::Open(fMC.at(i).c_str()); TTree *treeMC = (TTree*)fileMC->Get("SelectedCandidates"); EDBRHistoMaker* maker = new EDBRHistoMaker(treeMC, wantElectrons, wantMuons, wantSideband, wantSignal, wantFullRange, wantNXJets, isZZchannel); maker->setUnitaryWeights(false); maker->Loop(buffer); //delete maker; // This class is badly written and deleting it isn't safe! fileMC->Close(); } }//end loop on MC files printf("Loop over MC done\n"); //loop over MC signal files and make histograms individually for each of them for(int i=0;i<nMCSig;i++){ std::cout<<"\n-------\nRunning over "<<mcLabelsSig[i].c_str()<<std::endl; std::cout<<"The file is " <<fMCSig.at(i)<<std::endl; sprintf(buffer,"histos_%s.root",mcLabelsSig[i].c_str()); fHistosMCSig.push_back(buffer); if(redoHistograms){ TFile *fileMCSig = TFile::Open(fMCSig.at(i).c_str()); TTree *treeMCSig = (TTree*)fileMCSig->Get("SelectedCandidates"); EDBRHistoMaker* maker = new EDBRHistoMaker(treeMCSig, wantElectrons, wantMuons, wantSideband, wantSignal, wantFullRange, wantNXJets, isZZchannel); maker->setUnitaryWeights(false); maker->Loop(buffer); //delete maker; // This class is badly written and deleting it isn't safe! fileMCSig->Close(); } }//end loop on MC files printf("Loop over MC signal done\n"); /// ------------------------------------------------------------------ /// This second part is the loop over histograms to create stack plots /// ------------------------------------------------------------------ // EDBRHistoMaker::EDBRHistoMaker(TTree* tree, // bool wantElectrons, // bool wantMuons, // bool wantSideband, // bool wantSignal, // int wantNXJets, // bool isZZchannel){ printf("\nStart looping over histograms\n\n"); //make nice plots std::vector<std::string> listOfHistos; if(nMC>0){ // Open one of the histogram files just to get the list of histograms // produced, then loop over all the histograms inheriting // from TH1 contained in the file. sprintf(buffer,"histos_%s.root",mcLabels[0].c_str()); std::cout<<"Opening "<<buffer<<std::endl; TFile* oneFile = TFile::Open(buffer); TIter next(oneFile->GetListOfKeys()); TKey *key; while ((key = (TKey*)next())) { TClass *cl = gROOT->GetClass(key->GetClassName()); if (!cl->InheritsFrom("TH1")) continue; TH1 *hTMP = (TH1*)key->ReadObj(); std::string hName=hTMP->GetName(); // printf("Histogram found: %s\n",hName.c_str()); if(hName=="h_mj_vs_mzz")continue;//skip 2D histos bool isMJJhisto=(hName.find("mJJ")!=std::string::npos); bool isMZZhisto=(hName.find("mZZ")!=std::string::npos); if( !isMJJhisto && !isMZZhisto)continue;//skip all histos except MJJ and MZZ listOfHistos.push_back(hName); }//end while loop oneFile->Close(); }//end if fmc size >0 EDBRHistoPlotter *plotter=new EDBRHistoPlotter("./", fHistosData, fHistosMC, fHistosMCSig, lumiValue, wantNXJets, flavour, isZZchannel, scaleToData, scaleOnlyWJets, makeRatio, isSignalStackOnBkg, kFactorsMC,kFactorsMCSig); std::cout<<"Set output dir"<<std::endl; plotter->setOutDir(outputDir); plotter->setDebug(false); //colors are assigned in the same order of mcLabels //For ZZ ////// {"TTBAR","WW","WZ","ZZ","DYJetsPt50To70","DYJetsPt70To100","DYJetsPt100","WJetsPt50To70","WJetsPt70To100","WJetsPt100"}; std::vector<int> fColorsMC; fColorsMC.push_back(kGreen-3); //fColorsMC.push_back(kYellow-9); //fColorsMC.push_back(kYellow-6); //fColorsMC.push_back(kYellow-3); //fColorsMC.push_back(kYellow+3); //fColorsMC.push_back(kYellow+6); //fColorsMC.push_back(kYellow+9); fColorsMC.push_back(kMagenta-9); fColorsMC.push_back(kMagenta-6); fColorsMC.push_back(kMagenta-3); //fColorsMC.push_back(kBlue-3); fColorsMC.push_back(kBlue-6); fColorsMC.push_back(kBlue-9); //fColorsMC.push_back(kRed+3); //fColorsMC.push_back(kRed); //fColorsMC.push_back(kRed-4); //For WW //{ "TTBARpowheg_xww", "SingleTop_xww", "VV_xww", "DYJets_xww", "WJetsPt100_xww"} //std::vector<int> fColorsMC; //fColorsMC.push_back(kGreen-3); //fColorsMC.push_back(kYellow-9); //fColorsMC.push_back(kMagenta-9); //fColorsMC.push_back(kBlue-3); //fColorsMC.push_back(kRed-4); ////// {"BulkG_WW_lvjj_c1p0_M600_xww","BulkG_WW_lvjj_c1p0_M1000_xww","BulkG_WW_lvjj_c1p0_M1500_xww"}; std::vector<int> fColorsMCSig; // fColorsMCSig.push_back(kPink); fColorsMCSig.push_back(kOrange+7); fColorsMCSig.push_back(kMagenta); fColorsMCSig.push_back(kBlue+3); plotter->setFillColor(fColorsMC); plotter->setLineColor(fColorsMCSig); int numOfHistos = listOfHistos.size(); for(int i = 0; i != numOfHistos; ++i) plotter->makeStackPlots(listOfHistos.at(i)); printf("Plotting done\n"); delete plotter; }//end main
prepDataFiles(){ // TDirectory *theDr = (TDirectory*) myFile->Get("eleIDdir");///denom_pt/fit_eff_plots"); //theDr->ls(); int myIndex; 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("mc")) { ofstream myfile; TFile *myFile = new TFile(fname); TIter nextkey(myFile->GetListOfKeys()); TKey *key; while (key = (TKey*)nextkey()) { TString theTypeClasse = key->GetClassName(); TString theNomClasse = key->GetTitle(); if ( theTypeClasse == "TDirectoryFile"){ TDirectory *theDr = (TDirectory*) myFile->Get(theNomClasse); TIter nextkey2(theDr->GetListOfKeys()); TKey *key2; while (key2 = (TKey*)nextkey2()) { TString theTypeClasse2 = key2->GetClassName(); TString theNomClasse2 = key2->GetTitle(); myfile.open (theNomClasse2+".info"); if ( theTypeClasse == "TDirectoryFile"){ cout << "avant " << endl; TDirectory *theDr2 = (TDirectory*) myFile->Get(theNomClasse+"/"+theNomClasse2); cout << "apres " << endl; TIter nextkey3(theDr2->GetListOfKeys()); TKey *key3; while (key3 = (TKey*)nextkey3()) { TString theTypeClasse3 = key3->GetClassName(); TString theNomClasse3 = key3->GetTitle(); if ((theNomClasse3.Contains("FromMC"))) { TString localClasse3 = theNomClasse3; localClasse3.ReplaceAll("__","%"); cout << "apres " << localClasse3 << endl; TObjArray* listBin = localClasse3.Tokenize('%'); TString first = ((TObjString*)listBin->At(0))->GetString(); TString second = ((TObjString*)listBin->At(2))->GetString(); myfile << first; myfile << " " << second << " "; cout << "coucou la on va récupérer le rooFitResult " << endl; RooFitResult *theResults = (RooFitResult*) myFile->Get(theNomClasse+"/"+theNomClasse2+"/"+theNomClasse3+"/fitresults"); theResults->Print(); RooArgList theParam = theResults->floatParsFinal(); int taille = theParam.getSize(); for (int m = 0 ; m < taille ; m++){ cout << "m=" << m << endl; RooAbsArg *theArg = (RooAbsArg*) theParam.at(m); RooAbsReal *theReal = (RooAbsReal*) theArg; myfile << theReal->getVal() << " " ; } myfile << "\n"; } } } myfile.close(); } } } delete myFile; } } }
void recurseOverKeys(TDirectory *target, TString imageType) { // TString path( (char*)strstr( target->GetPath(), ":" ) ); // path.Remove( 0, 2 ); // cout << path << endl; // sourceFile->cd( path ); target->cd(); TDirectory *current_sourcedir = gDirectory; TKey *key; TIter nextkey(current_sourcedir->GetListOfKeys()); TCanvas *canvasDefault = new TCanvas(); while ( (key = (TKey*)nextkey() ) ) { TObject* obj = key->ReadObj(); if (obj->IsA()->InheritsFrom("TH1") ) { // ************************** // Plot & Save this Histogram TH1* h = (TH1*)obj; h->SetStats(displayStatsBox); TString histName = h->GetName(); // Now to label the X-axis! // if (autoLabelXaxis) { // if ( histName.Contains("Phi") ) { // h->GetXaxis()->SetTitle("#phi"); // } else if ( histName.Contains("Eta") ) { // h->GetXaxis()->SetTitle("#eta"); // } else if ( histName.Contains("Pt") ) { // h->GetXaxis()->SetTitle("p_{T} (GeV)"); // } else if ( histName.Contains("Et") ) { // h->GetXaxis()->SetTitle("E_{T} (GeV)"); // } // } // h->SetLineColor(lineColor); // h->SetLineWidth(lineWidth); // ******************************** // A trick to decide whether to have log or no-log y axis // get hist max y value if (autoLogYaxis) { Double_t testYvalue = h->GetMaximum(); //cout << testYvalue << endl; if (testYvalue > 1.0) { Double_t maxy = log10(testYvalue); // get hist min y value Double_t miny = log10(h->GetMinimum(1.0)); // log scale if more than 3 powers of 10 between low and high bins if ( (maxy-miny) > 3.0 ) { canvasDefault->SetLogy(1); } } } // End of log or no-log y axis decision // ******************************** h->Draw(drawOptions1D); canvasDefault->Modified(); canvasDefault->Update(); // gPad->Print(outputFolder+path+"/"+histName+outputType); TString outputFolder = "images/"; gPad->Print(outputFolder+histName+"."+imageType); // To store the root file name in image file name: //canvasDefault->Print(outputFolder+histFileName+histName+outputType); // if (printOutput) cout << outputFolder+path+"/"+histName+outputType << endl; canvasDefault->SetLogy(0); // reset to no-log - prevents errors // ************************** } else if ( obj->IsA()->InheritsFrom( "TDirectory" ) ) { // it's a subdirectory cout << "Found subdirectory " << obj->GetName() << endl; // gSystem->MakeDirectory(outputFolder+path+"/"+obj->GetName()); // obj is now the starting point of another round of merging // obj still knows its depth within the target file via // GetPath(), so we can still figure out where we are in the recursion recurseOverKeys((TDirectory*)obj, imageType); } // end of IF a TDriectory } // end of LOOP over keys }