For loop through directory of histograms

Hello,
I am trying to overlap histograms in three different files and in three different directories. I can read all the histograms, but i need to run the for loop simulataneously for all the three directories, which is where I am stuck now. Below is a snippet of the code -

TFile *_file0 = TFile::Open(“MyTest/hist-mc_sig_new.root”);
TFile *_file1 = TFile::Open(“MyTest/hist-mc_bkg_new.root”);
TFile *_file3 = TFile::Open(“MyTest/hist_dR_lead_sublead.root”);
TDirectory *d0 = nullptr;
TDirectory *d1 = nullptr;
TDirectory *d3 = nullptr;
TDirectory *d4 = nullptr;
TString tdir = “LHAlg/LHAlg_h_el_LHDiscriminant_et_eta”;
TString tdir1 = “LHAlg/LHAlg_th_LH_lead_et_eta”;
TString tdir2 = “LHAlg/LHAlg_th_LH_sublead_et_eta”;
_file0->GetObject(tdir, d0);
_file3->GetObject(tdir1, d3);
_file3->GetObject(tdir2, d4);

now I need to loop over the contents of all the directories. At the moment, I can loop over one directory by doing -
for (TObject* keyAsObj : (d0->GetListOfKeys()){
auto key = dynamic_cast<TKey
>(keyAsObj);
TH1D h_sig = (TH1D) key->ReadObj();
TString histName = TString(h_sig->GetName()); … this part works, if I just call one directory and make plots.
}
Any assistance with the syntax will be helpful !
Thank you

Hi,

a solution could consist in saving in a container the “full path” names of all the objects you need and then open and act on them in a nested loop (one over the names, one over the files).

Cheers,
D

Hello,
Thank you for the idea. I am now trying to do the following -
for (TObject* keyAsObj : (d0->GetListOfKeys())){
auto key = dynamic_cast<TKey
>(keyAsObj);
if((TString)key->GetClassName() == “TH2D”) continue;
h_sig = (TH1D*) key->ReadObj();
histName = TString(h_sig->GetName());
h_bkg = (TH1D*)_file1->Get(tdir+"/"+histName);
std::cout<<“histname “<<histName<<std::endl;
h_beek_l = (TH1D*)_file3->Get(tdir1+”/”+histName1);
h_beek_sl = (TH1D*)_file3->Get(tdir2+"/"+histName2);
Draw all these 4 hists
}

I am looping over a separate for loop to get all the histName1 and histName2 for the two other directories as the one shown below -
for (TObject* keyAsObj1 : (d3->GetListOfKeys())){
auto key1 = dynamic_cast<TKey
>(keyAsObj1);
if((TString)key1->GetClassName() == “TH2D”) continue;

    h_beek_lead = (TH1D*) key1->ReadObj();
    histName1 = TString(h_beek_lead->GetName());

std::cout<<"histname1 "<<histName1<<std::endl;

}

But, unfortunately it is not working, am I doing the right thing in saving the histName1 and histName2, is it similar to what you have mentioned above ?

Thank you
Shreya

Hi Shreya,

my proposal is to save in a container, e.g. a std::vector, the names. Then compose them with the different paths, that you call tdir, tdir1 and tdir2.

Cheers,
D

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.