コード例 #1
0
ファイル: branches.C プロジェクト: Amarang/syncfiles
void branches(TString input, TString treeName="Events")
{
    TFile *file = new TFile(input);
    TTree *tree = (TTree*)file->Get(treeName);
    if(treeName.Contains("Events")) {
        for(int i = 0; i < tree->GetListOfAliases()->LastIndex(); i++) 
            std::cout << "branch: " << tree->GetListOfAliases()->At(i)->GetName() << std::endl;
    } else {
        for(int i = 0; i < tree->GetListOfBranches()->LastIndex(); i++) 
            std::cout << "branch: " << tree->GetListOfBranches()->At(i)->GetName() << std::endl;
    }
}
コード例 #2
0
ファイル: DDG4EventHandler.cpp プロジェクト: vvolkl/DD4hep
/// Open new data file
bool DDG4EventHandler::Open(const std::string&, const std::string& name)   {
    if ( m_file.first ) m_file.first->Close();
    m_hasFile = false;
    m_hasEvent = false;
    TFile* f = TFile::Open(name.c_str());
    if ( f && !f->IsZombie() )  {
        m_file.first = f;
        TTree* t = (TTree*)f->Get("EVENT");
        if ( t )   {
            TObjArray* br = t->GetListOfBranches();
            m_file.second = t;
            m_entry = -1;
            m_branches.clear();
            for(Int_t i=0; i<br->GetSize(); ++i)  {
                TBranch* b = (TBranch*)br->At(i);
                if ( !b ) continue;
                m_branches[b->GetName()] = make_pair(b,(void*)0);
                printout(INFO,"DDG4EventHandler::open","+++ Branch %s has %ld entries.",b->GetName(),b->GetEntries());
            }
            for(Int_t i=0; i<br->GetSize(); ++i)  {
                TBranch* b = (TBranch*)br->At(i);
                if ( !b ) continue;
                b->SetAddress(&m_branches[b->GetName()].second);
            }
            m_hasFile = true;
            return true;
        }
        throw runtime_error("+++ Failed to access tree EVENT in ROOT file:"+name);
    }
    throw runtime_error("+++ Failed to open ROOT file:"+name);
}
コード例 #3
0
void GetTreeSize(TString FileName, TString TreeName)
{
  TFile *inf          = TFile::Open(FileName);
  TTree *tr           = (TTree*)inf->Get(TreeName);
  TObjArray *branches = (TObjArray*)tr->GetListOfBranches();
  int size(0);
  cout.setf(ios::right);
  int N(branches->GetEntries());
  TH1F *hSize = new TH1F("size","size",N,0,N);
  for(int ib=0;ib<N;ib++) {
    TString name(branches->At(ib)->GetName());
    TBranch *br = (TBranch*)tr->GetBranch(name);
    hSize->Fill(name,br->GetZipBytes()/1e+3); 
    size += br->GetZipBytes();
  } 
  cout<<"Total size: "<<size<<endl;
  for(int ib=0;ib<N;ib++) {
    TString name(branches->At(ib)->GetName());
    TBranch *br = (TBranch*)tr->GetBranch(name);
    float percent = TMath::Ceil(1000*float(br->GetZipBytes())/float(size))/10;
    cout<<ib<<setw(20)<<name<<setw(15)<<br->GetZipBytes()<<" "<<percent<<"%"<<endl;
  }

  TCanvas *can = new TCanvas("TreeSize","TreeSize",1000,400);
  hSize->GetXaxis()->SetTitle("Branch Name");
  hSize->GetXaxis()->SetLabelSize(0.04);
  hSize->GetYaxis()->SetTitle("Size (KB)");
  hSize->SetFillColor(kGray);
  hSize->Draw();
}
コード例 #4
0
ファイル: VariablePrint.C プロジェクト: lamatko/root_scripts
void VariablePrint1() {
TFile *f = new TFile("/home/francji/data/subsets/small_training_sample/p17_CC_diboson_EqOneTag_EqThreeJet_zero_Topo_small_training_sample.root");
TTree *t = (TTree *) f->Get("TopologicalVariables");
TObjArray *arr = t->GetListOfBranches();
    for (int i = 0; i < arr->GetSize(); i++) {
      char s[1000];
      strcpy(s, arr->At(i)->GetTitle());
      char c = s[strlen(s)-1];
      s[strlen(s)-2] = '\0';
      printf("%i  %s \n", i, s);
    }
}
コード例 #5
0
ファイル: dumpDDG4.C プロジェクト: AIDASoft/DD4hep
int dumpDDG4(const char* fname, int event_num)  {
  TFile* data = TFile::Open(fname);
  if ( !data || data->IsZombie() )   {
    printf("+  File seems to not exist. Exiting\n");
    usage();
    return -1;
  }
  TTree* tree = (TTree*)data->Get("EVENT");
  for(int event=0, num=tree->GetEntries(); event<num; ++event)  {
    TObjArray* arr = tree->GetListOfBranches();
    if ( event_num>= 0 ) event = event_num;
    for(int j=0, nj=arr->GetEntries(); j<nj; ++j)   {
      TBranch* b = (TBranch*)arr->At(j);
      typedef vector<void*> _E;
      _E* e = 0;
      b->SetAddress(&e);
      int nbytes = b->GetEvent(event);
      if ( nbytes > 0 )   {
        if ( e->empty() )    {
          continue;
        }
        string br_name = b->GetName();
        string cl_name = b->GetClassName();
        if ( cl_name.find("dd4hep::sim::Geant4Tracker::Hit") != string::npos )  {
          typedef vector<Geant4Tracker::Hit*> _H;
          printHits(br_name,(_H*)e);
        }
        else if ( cl_name.find("dd4hep::sim::Geant4Calorimeter::Hit") != string::npos )  {
          typedef vector<Geant4Calorimeter::Hit*> _H;
          printHits(br_name,(_H*)e);
        }
        else if ( cl_name.find("dd4hep::sim::Geant4Particle") != string::npos )  {
          typedef vector<Geant4Particle*> _H;
          ::printf("%s\n+    Particle Dump of event %8d  [%8d bytes]        +\n%s\n",
                   line,event,nbytes,line);
          printParticles(br_name,(_H*)e);
        }
      }
    }
    if ( event_num >= 0 ) break;
  }
  delete data;
  return 0;
}
コード例 #6
0
ファイル: VariablesPrint.C プロジェクト: lamatko/root_scripts
void VariablesPrint() {
TFile *f = new TFile("/work/budvar-clued0/francji/subsets/small_training_sample/p17_CC_diboson_EqOneTag_EqThreeJet_zero_Topo_small_training_sample.root");
TTree *t = (TTree *) f->Get("TopologicalVariables");
TObjArray *arr = t->GetListOfBranches();
int j = 1;
for (int i = 0; i < arr->GetSize(); i++) {
      char s[1000];
      strcpy(s, arr->At(i)->GetTitle());
      char c = s[strlen(s)-1];
      s[strlen(s)-2] = '\0';
      if (c == 'D') {
        printf("%5i  D %s \n", j, s);
        j++;
      } else if (c == 'I') {
        printf("%5i  I %s \n", j, s);
        j++;
      } else {};
      }
}
コード例 #7
0
ファイル: removeBranch.cpp プロジェクト: LLRCMS/KLUBAnalysis
int main (int argc, char** argv)
{
  // check number of inpt parameters
  if (argc < 3)
    {
      cerr << argv[0] << " filename branchname" << endl ;
      return 1 ;
    }


   TFile f (argv[1], "update") ;
   TTree *T = (TTree*) f.Get ("HTauTauTree") ;
   TBranch *b = T->GetBranch (argv[2]) ;
   T->GetListOfBranches ()->Remove (b) ;
   T->Write () ;
   f.Close () ;
   
   return 0 ;
}   
コード例 #8
0
ファイル: NTPReplay.C プロジェクト: A2-Collaboration/acqu
NTPReplay( Char_t* fname, Int_t qfRecon = -1 )
{
  // Histogram energies, momenta, from Tree created by kinematics generator
  // AcquMC....ensure physics library is loaded 1st
  gROOT->Reset();
  if (!gROOT->GetClass("TLorentzVector")) gSystem->Load("libPhysics");
  //
  // Tree file contains 4-momenta produced by MCGenerator
  TFile* tFile = new TFile( fname );
  TTree* tree = (TTree*)tFile->Get("h1");
  tree->Print();
  Int_t nbr = tree->GetNbranches();
  Int_t nparticle = (nbr - 3)/5;                  // # particles in reaction
  printf(" %d particles in experiment\n", nparticle );
  TObjArray* leaves = tree->GetListOfBranches(); // linked list of leaves
  printf(" %d leaves in branch\n",nbr);
  TIter nextlf( tree->GetListOfBranches() );
  char** hname = new char*[nbr];               // histogram parameters
  Float_t* p4i = new Float_t[nbr];
  for( Int_t n=0; n<nbr; n++ ){
    TBranch* lf = (TBranch*)nextlf();           // Double_t leaf
    hname[n] = lf->GetName();                 // its name
    tree->SetBranchAddress(hname[n], p4i+n);
  }
  Int_t nevent = tree->GetEntries();           // # events generated
  printf(" %d events started\n", nevent );
  //
  //  Create linked list of 1D histograms
  Int_t i,j,k;
  //  for(i=0,j=0; i<nparticle; i++) if( Track[i] ) j++;  // #particles tracked
  j = nparticle;
  printf(" %d final-state particles tracked\n", j );
  Int_t np4 = j;
  Int_t nhist = 4*j + 7;                              // # 1D histograms
  Int_t nchan = 1000;                                 // 1000 channels each
  Char_t* title;                                      // title is file name
  if( !(title = strrchr(fname,'/')) ) title = fname;
  else title++;
  TList* hl = new TList();
  TList* hAng = new TList();
  TH1F* h;
  for( i=0; i<nhist; i++ ){
    h = new TH1F( hname[i], title, nchan, 0, 0 );
    hl->AddLast(h);
  }
  Char_t angName[256];
  // Angular ranges (deg) for plotting
  Double_t thetaMin[] = {
    0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
    0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
  };
  Double_t thetaMax[] = {
    0.5, 180.0, 180.0, 180.0, 180.0, 180.0, 180.0, 180.0, 180.0, 180.0,
    180.0, 180.0, 180.0, 180.0, 180.0, 180.0, 180.0, 180.0, 180.0, 180.0, 180.0
  };
  Double_t phiMin[] = {
    -200, -200, -200, -200, -200, -200, -200, -200, -200, -200,
    -200, -200, -200, -200, -200, -200, -200, -200, -200, -200, -200
  };
  Double_t phiMax[] = {
    200.0, 200.0, 200.0, 200.0, 200.0, 200.0, 200.0, 200.0, 200.0, 200.0,
    200.0, 200.0, 200.0, 200.0, 200.0, 200.0, 200.0, 200.0, 200.0, 200.0, 200.0
  };
  for( i=0; i<=np4; i++ ){
    sprintf( angName, "Theta_%d", i );
    h = new TH1F( angName, title, 180, thetaMin[i], thetaMax[i] );
    hAng->AddLast(h);
    sprintf( angName, "Phi_%d", i );
    h = new TH1F( angName, title, 180, phiMin[i], phiMax[i] );
    hAng->AddLast(h);
    sprintf( angName, "P_%d", i );
    h = new TH1F( angName, title, 1000, 0, 0 );
    hAng->AddLast(h);
  }    
  TIter next(hl);                             // list iterator
  TIter nextAng(hAng);                       // list iterator
  //
  // For some 4-momentum analysis
  TLorentzVector* P4 = new TLorentzVector[nparticle];
  TLorentzVector P4tot;
  TLorentzVector P4beamQF;
  i = 0;
  TH2F* h2a = new TH2F("Vertex-X-Y",title,300,-3,3,300,-3,3);
  TH2F* h2b = new TH2F("Vertex-Z-R",title,300,-3,3,300,-3,3);
  TH1F* h1a = new TH1F("Momentum-Balance",title,1000,-1,1);
  TH1F* h1b;
  if( qfRecon >= 0 ) h1b = new TH1F("QF-recon-Beam-Energy",title,2000,-5,5);
  //
  // Read events from branch
  Double_t r;
  Float_t* p;
  for(i=0; i<nevent; i++){
    next.Reset();
    nextAng.Reset();
    tree->GetEntry(i);
    p = p4i + 3;
    P4tot.SetXYZT(0,0,0,0);
    if( qfRecon >= 0 )P4beamQF.SetXYZT(0,0,0,0);
    for(j=0; j<=np4; j++,p+=5){
      P4[j].SetXYZT(p[0]*p[3],p[1]*p[3],p[2]*p[3],p[4]);
      if( j )P4tot += P4[j];
      else P4tot -= P4[j];
      if( j >= qfRecon ) P4beamQF += P4[j];
      h = (TH1F*)nextAng();
      h->Fill( P4[j].Theta() * TMath::RadToDeg() );
      h = (TH1F*)nextAng();
      h->Fill( P4[j].Phi() * TMath::RadToDeg() );
      h = (TH1F*)nextAng();
      h->Fill( P4[j].P() );
    }
    //    pi0_01 = *pi0_0 + *pi0_1;
    //    pi0_02 = *pi0_0 + *pi0_2;
    p = p4i;
    h2a->Fill( p4i[0], p4i[1] );
    r = TMath::Sqrt( p4i[0]*p4i[0] + p4i[1]*p4i[1] );
    h2b->Fill( p4i[2],r );
    h1a->Fill( P4tot.P() );
    if( qfRecon >= 0 ) h1b->Fill( P4beamQF.E() );
    while( (h = (TH1F*)next()) ){
      h->Fill(*p);
      p++;
    }
  }
  //
  // Setup of canvases
  Int_t ncanv = np4 + 2;                 // # canvases
  Char_t* cname[] = {                    // names
    "Vertex", "Beam", 
     "Particle_0",  "Particle_1",  "Particle_2",  "Particle_3", 
     "Particle_4",  "Particle_5",  "Particle_6",  "Particle_7", 
     "Particle_8",  "Particle_9", "Particle_10", "Particle_11", 
    "Particle_12", "Particle_13", "Particle_14", "Particle_15", 
    "Particle_16", "Particle_17", "Particle_18", "Particle_19",
  };
  Int_t xplot[] = {
    2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  };
  Int_t yplot[] = {
    3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  };
  Int_t nplot[] = {
    3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  };
  TCanvas* canv;
  next.Reset();                    // start of histogram list
  nextAng.Reset();                 // start of histogram list
  // Draw histograms
  for( i=0; i<ncanv; i++ ){
    canv = new TCanvas(cname[i],"MCtit",240,180,700,900);
    canv->SetFillStyle(4000);
    canv->Divide(xplot[i],yplot[i],0.01,0.01);
    j = 1;
    while( (h = (TH1F*)next()) ){
      canv->cd(j);
      h->Draw();
      if( j >= nplot[i] ) break;
      j++;
    }
    if( i ){
      for( k=0; k<3; k++ ){
	j++;
	h = (TH1F*)nextAng();
	canv->cd(j);
	if( k<2 ) h->Draw();
      }
    }
    else{
      canv->cd(4);
      h1a->Draw();
      canv->cd(5);
      h2a->Draw("colz");
      canv->cd(6);
      h2b->Draw("colz");
    }
  }
  return;
}
コード例 #9
0
ファイル: makeCMS2ClassFiles.C プロジェクト: fgolf/pac
//-------------------------------------------------------------------------------------------------
void makeHeaderFile(TFile *f, const string& treeName, bool paranoid, const string& Classname, const string& nameSpace, const string& objName) {
	
  
  
    headerf << "// -*- C++ -*-" << endl;
    headerf << "#ifndef " << Classname << "_H" << endl;
    headerf << "#define " << Classname << "_H" << endl;
    headerf << "#include \"Math/LorentzVector.h\"" << endl;
    headerf << "#include \"Math/Point3D.h\"" << endl;
    headerf << "#include \"TMath.h\"" << endl;
    headerf << "#include \"TBranch.h\"" << endl;
    headerf << "#include \"TTree.h\"" << endl;
    headerf << "#include \"TH1F.h\""  << endl;
    headerf << "#include \"TFile.h\"" << endl;
    headerf << "#include \"TBits.h\"" << endl;
    headerf << "#include <vector>" << endl;
    headerf << "#include <unistd.h>" << endl;
    headerf << "typedef ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > LorentzVector;" << endl << endl;
    if (paranoid)
        headerf << "#define PARANOIA" << endl << endl;
    headerf << "using namespace std; " << endl;
    headerf << "class " << Classname << " {" << endl;
    headerf << "private: " << endl;
    headerf << "protected: " << endl;
    headerf << "\tunsigned int index;" << endl;
    // TTree *ev = (TTree*)f->Get("Events");
    TList* list_of_keys = f->GetListOfKeys();
    std::string tree_name = "";
    if (treeName.empty()) {
        unsigned int ntrees = 0;
        for (unsigned int idx = 0; idx < (unsigned int)list_of_keys->GetSize(); idx++) {
            const char* obj_name = list_of_keys->At(idx)->GetName();
            TObject* obj = f->Get(obj_name);
            if (obj->InheritsFrom("TTree")) {
                ++ntrees;
                tree_name = obj_name;
            }
        }
        if (ntrees == 0) {
            std::cout << "Did not find a tree. Exiting." << std::endl;
            return;
        }
        if (ntrees > 1) {
            std::cout << "Found more than one tree.  Please specify a tree to use." << std::endl;
            return;
        }
    }
    else
        tree_name = treeName;

    TTree *ev = (TTree*)f->Get(tree_name.c_str());

    TSeqCollection *fullarray = ev->GetListOfAliases();  
    bool have_aliases = true;
    if (!fullarray) {
        have_aliases = false;   
        fullarray = ev->GetListOfBranches();
    }

    // if (have_aliases && fullarray->GetSize() != ev->GetListOfBranches()->GetSize()) {
    //     std::cout << "Tree has " << fullarray->GetSize() << " aliases and " << ev->GetListOfBranches()->GetSize() << " branches. Exiting." << std::endl;
    //     return;
    // }

    TList *aliasarray = new TList();
    
    for(Int_t i = 0; i < fullarray->GetEntries(); ++i) {
        TString aliasname(fullarray->At(i)->GetName());
        // TBranch *branch = ev->GetBranch(ev->GetAlias(aliasname.Data()));
        TBranch *branch = 0;
        if (have_aliases)
            branch = ev->GetBranch(ev->GetAlias(aliasname.Data()));
        else
            branch = (TBranch*)fullarray->At(i);

        TString branchname(branch->GetName());
        TString branchtitle(branch->GetTitle());
        TString branchclass(branch->GetClassName());
        if(!branchname.BeginsWith("int") && 
           !branchname.BeginsWith("uint") && 
           !branchname.BeginsWith("bool") && 
           !branchname.BeginsWith("float") &&
           !branchname.BeginsWith("double") &&
           !branchtitle.EndsWith("/F") && 
           !branchtitle.EndsWith("/I") &&
           !branchtitle.EndsWith("/i") &&
           !branchtitle.EndsWith("/O") &&
           !branchtitle.BeginsWith("TString") &&
           !branchtitle.BeginsWith("TBits") &&
           !branchclass.Contains("LorentzVector") &&
           !branchclass.Contains("int") &&   
           !branchclass.Contains("uint") &&  
           !branchclass.Contains("bool") &&  
           !branchclass.Contains("float") && 
           !branchclass.Contains("double") &&
           !branchclass.Contains("TString"))
            continue;

        // if (branchclass.Contains("TString"))
        // {
        //     std::cout << "Adding branch " << branchtitle.Data() << " to list." << std::endl;
        //     std::cout.flush();
        // }

        aliasarray->Add(fullarray->At(i));
    }
  
    for(Int_t i = 0; i< aliasarray->GetEntries(); ++i) {
    
        //Class name is blank for a int of float
        TString aliasname(aliasarray->At(i)->GetName());
        // TBranch *branch = ev->GetBranch(ev->GetAlias(aliasname.Data()));
        TBranch *branch = 0;
        if (have_aliases)
            branch = ev->GetBranch(ev->GetAlias(aliasname.Data()));
        else
            branch = (TBranch*)aliasarray->At(i);
    
        TString classname = branch->GetClassName();
        TString title     = branch->GetTitle();
        if ( classname.Contains("vector") ) {
            if(classname.Contains("edm::Wrapper<") ) {
                classname = classname(0,classname.Length()-2);
                classname.ReplaceAll("edm::Wrapper<","");
                headerf << "\t" << classname << " " << aliasname << "_;" << endl;
            } 
            //else if (classname.Contains("TString") || classname.Contains("vector<float>")) {
            else if (classname.Contains("TString")) {
                headerf << "\t" << classname << " " << aliasname << "_;" << endl;
            }
            else {
                headerf << "\t" << classname << " *" << aliasname << "_;" << endl;
            }
        } else {
      
            if(classname != "" ) { //LorentzVector
                if(classname.Contains("edm::Wrapper<") ) {
                    classname = classname(0,classname.Length()-1);
                    classname.ReplaceAll("edm::Wrapper<","");
                    headerf << "\t" << classname << " " << aliasname << "_;" << endl;
                }
                //else if (classname.Contains("TString") || classname.Contains("vector<float>")) {
                else if (classname.Contains("TString")) {
                    headerf << "\t" << classname << " " << aliasname << "_;" << endl;
                } 
                else {
                    headerf << "\t" << classname << " *" << aliasname << "_;" << endl;
                }
            } else {
                if(title.EndsWith("/i"))
                    headerf << "\tunsigned int" << "\t" << aliasname << "_;" << endl;
                if(title.EndsWith("/F"))
                    headerf << "\tfloat" << "\t" << aliasname << "_;" << endl;
                if(title.EndsWith("/I"))
                    headerf << "\tint" << "\t" << aliasname << "_;" << endl;
                if(title.EndsWith("/O"))
                    headerf << "\tbool" << "\t" << aliasname << "_;" << endl;
            }
        }
        headerf << "\tTBranch *" << Form("%s_branch",aliasname.Data()) << ";" << endl;
        headerf << "\tbool " << Form("%s_isLoaded",aliasname.Data()) << ";" << endl;
    }
  
  
    headerf << "public: " << endl;
    headerf << "void Init(TTree *tree) {" << endl;
    

    // SetBranchAddresses for LorentzVectors
    // TBits also needs SetMakeClass(0)...
    for(Int_t i = 0; i< aliasarray->GetEntries(); i++) {
        TString aliasname(aliasarray->At(i)->GetName());
        // TBranch *branch = ev->GetBranch(ev->GetAlias(aliasname.Data()));
        TBranch *branch = 0;
        if (have_aliases)
            branch = ev->GetBranch(ev->GetAlias(aliasname.Data()));
        else
            branch = (TBranch*)aliasarray->At(i);

        TString classname = branch->GetClassName();
        TString branch_ptr = Form("%s_branch",aliasname.Data());
        if ( !classname.Contains("vector<vector") ) {
            if ( classname.Contains("Lorentz") || classname.Contains("PositionVector") || classname.Contains("TBits")) {
                headerf << "\t" << Form("%s_branch",aliasname.Data()) << " = 0;" << endl;
                if (have_aliases) {
                    headerf << "\t" << "if (tree->GetAlias(\"" << aliasname << "\") != 0) {" << endl;
                    headerf << "\t\t" << Form("%s_branch",aliasname.Data()) << " = tree->GetBranch(tree->GetAlias(\"" << aliasname << "\"));" << endl;
                    //headerf << "\t\t" << Form("%s_branch",aliasname.Data()) << "->SetAddress(&" << aliasname << "_);" << endl << "\t}" << endl;
                    headerf << Form("\t\tif (%s) {%s->SetAddress(&%s_);}\n\t}", branch_ptr.Data(), branch_ptr.Data(), aliasname.Data()) << endl;
                }
                else {
                    headerf << "\t" << "if (tree->GetBranch(\"" << aliasname << "\") != 0) {" << endl;
                    headerf << "\t\t" << Form("%s_branch",aliasname.Data()) << " = tree->GetBranch(\"" << aliasname << "\");" << endl;
                    //headerf << "\t\t" << Form("%s_branch",aliasname.Data()) << "->SetAddress(&" << aliasname << "_);" << endl << "\t}" << endl;
                    headerf << Form("\t\tif (%s) {%s->SetAddress(&%s_);}\n\t}", branch_ptr.Data(), branch_ptr.Data(), aliasname.Data()) << endl;
                }
            }
        }
    }


    // SetBranchAddresses for everything else
    headerf << "  tree->SetMakeClass(1);" << endl;
    for(Int_t i = 0; i< aliasarray->GetEntries(); i++) {
        TString aliasname(aliasarray->At(i)->GetName());
        // TBranch *branch = ev->GetBranch(ev->GetAlias(aliasname.Data()));
        TBranch *branch = 0;
        if (have_aliases)
            branch = ev->GetBranch(ev->GetAlias(aliasname.Data()));
        else
            branch = (TBranch*)aliasarray->At(i);

        TString classname = branch->GetClassName();
        TString branch_ptr = Form("%s_branch",aliasname.Data());
        if ( ! (classname.Contains("Lorentz") || classname.Contains("PositionVector") || classname.Contains("TBits")) || classname.Contains("vector<vector") ) {
            headerf << "\t" << Form("%s_branch",aliasname.Data()) << " = 0;" << endl;
            if (have_aliases) {
                headerf << "\t" << "if (tree->GetAlias(\"" << aliasname << "\") != 0) {" << endl;
                headerf << "\t\t" << Form("%s_branch",aliasname.Data()) << " = tree->GetBranch(tree->GetAlias(\"" << aliasname << "\"));" << endl;
                //headerf << "\t\t" << Form("%s_branch",aliasname.Data()) << "->SetAddress(&" << aliasname << "_);" << endl << "\t}" << endl;
                headerf << Form("\t\tif (%s) {%s->SetAddress(&%s_);}\n\t}", branch_ptr.Data(), branch_ptr.Data(), aliasname.Data()) << endl;
            }
                else {
                    headerf << "\t" << "if (tree->GetBranch(\"" << aliasname << "\") != 0) {" << endl;
                    headerf << "\t\t" << Form("%s_branch",aliasname.Data()) << " = tree->GetBranch(\"" << aliasname << "\");" << endl;
                    //headerf << "\t\t" << Form("%s_branch",aliasname.Data()) << "->SetAddress(&" << aliasname << "_);" << endl << "\t}" << endl;
                    headerf << Form("\t\tif (%s) {%s->SetAddress(&%s_);}\n\t}", branch_ptr.Data(), branch_ptr.Data(), aliasname.Data()) << endl;
                }
        }
    }

    headerf << "  tree->SetMakeClass(0);" << endl;
    headerf << "}" << endl;

    // GetEntry
    headerf << "void GetEntry(unsigned int idx) " << endl;
    headerf << "\t// this only marks branches as not loaded, saving a lot of time" << endl << "\t{" << endl;
    headerf << "\t\tindex = idx;" << endl;
    for(Int_t i = 0; i< aliasarray->GetEntries(); i++) {
        TString aliasname(aliasarray->At(i)->GetName());
        headerf << "\t\t" << Form("%s_isLoaded",aliasname.Data()) << " = false;" << endl;
    }
    headerf << "\t}" << endl << endl;

    // LoadAllBranches
    headerf << "void LoadAllBranches() " << endl;
    headerf << "\t// load all branches" << endl << "{" << endl;
    for(Int_t i = 0; i< aliasarray->GetEntries(); i++) {
        TString aliasname(aliasarray->At(i)->GetName());
        headerf << "\t" << "if (" << aliasname.Data() <<  "_branch != 0) " << Form("%s();",aliasname.Data()) << endl;
    }
    headerf << "}" << endl << endl;

    // accessor functions
    for (Int_t i = 0; i< aliasarray->GetEntries(); i++) {
        TString aliasname(aliasarray->At(i)->GetName());
        // TBranch *branch = ev->GetBranch(ev->GetAlias(aliasname.Data()));
        TBranch *branch = 0;
        if (have_aliases)
            branch = ev->GetBranch(ev->GetAlias(aliasname.Data()));
        else
            branch = (TBranch*)aliasarray->At(i);

        TString classname = branch->GetClassName();
        TString title = branch->GetTitle();
        bool isSkimmedNtuple = false;
        if(!classname.Contains("edm::Wrapper<") &&
           (classname.Contains("vector") || classname.Contains("LorentzVector") ) )
            isSkimmedNtuple = true;
        if ( classname.Contains("vector") ) {
            if(classname.Contains("edm::Wrapper<") ) {
                classname = classname(0,classname.Length()-2);
                classname.ReplaceAll("edm::Wrapper<","");
            }
            headerf << "\tconst " << classname << " &" << aliasname << "()" << endl;
        } else {
            if(classname.Contains("edm::Wrapper<") ) {
                classname = classname(0,classname.Length()-1);
                classname.ReplaceAll("edm::Wrapper<","");
            }
            if(classname != "" ) {
                headerf << "\t" << classname << " &" << aliasname << "()" << endl;
            } else {
                if(title.EndsWith("/i"))
                    headerf << "\tunsigned int &" << aliasname << "()" << endl;
                if(title.EndsWith("/F"))
                    headerf << "\tfloat &" << aliasname << "()" << endl;
                if(title.EndsWith("/I"))
                    headerf << "\tint &" << aliasname << "()" << endl;
                if(title.EndsWith("/O"))
                    headerf << "\tbool &" << "\t" << aliasname << "()" << endl;
            }
        }
        aliasname = aliasarray->At(i)->GetName();
        headerf << "\t{" << endl;
        headerf << "\t\t" << "if (not " << Form("%s_isLoaded) {",aliasname.Data()) << endl;
        headerf << "\t\t\t" << "if (" << Form("%s_branch",aliasname.Data()) << " != 0) {" << endl;
        headerf << "\t\t\t\t" << Form("%s_branch",aliasname.Data()) << "->GetEntry(index);" << endl;
        if (paranoid) {
            headerf << "\t\t\t\t#ifdef PARANOIA" << endl;
            if (classname == "vector<vector<float> >") {
                if(isSkimmedNtuple) {
                    headerf << "\t\t\t\t" << "for (vector<vector<float> >::const_iterator i = " 
                            << aliasname << "_->begin(); i != "<< aliasname << "_->end(); ++i) {" << endl;
                } else {
                    headerf << "\t\t\t\t" << "for (vector<vector<float> >::const_iterator i = " 
                            << aliasname << "_.begin(); i != "<< aliasname << "_.end(); ++i) {" << endl;
                }
                headerf << "\t\t\t\t\t" << "for (vector<float>::const_iterator j = i->begin(); " 
                    "j != i->end(); ++j) {" << endl;
                headerf << "\t\t\t\t\t\t" << "if (not isfinite(*j)) {" << endl;
                headerf << "\t\t\t\t\t\t\t" << "printf(\"branch " << Form("%s_branch",aliasname.Data()) 
                        << " contains a bad float: %f\\n\", *j);" << endl << "\t\t\t\t\t\t\t" << "exit(1);"
                        << endl;
                headerf << "\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}" << endl;
            } else if (classname == "vector<float>") {
                if(isSkimmedNtuple) {
                    headerf << "\t\t\t\t" << "for (vector<float>::const_iterator i = " 
                            << aliasname << "_->begin(); i != "<< aliasname << "_->end(); ++i) {" << endl;
                } else {
                    headerf << "\t\t\t\t" << "for (vector<float>::const_iterator i = " 
                            << aliasname << "_.begin(); i != "<< aliasname << "_.end(); ++i) {" << endl;
                }
                headerf << "\t\t\t\t\t" << "if (not isfinite(*i)) {" << endl;
                headerf << "\t\t\t\t\t\t" << "printf(\"branch " << Form("%s_branch",aliasname.Data()) 
                        << " contains a bad float: %f\\n\", *i);" << endl << "\t\t\t\t\t\t" << "exit(1);"
                        << endl;
                headerf << "\t\t\t\t\t}\n\t\t\t\t}" << endl;
            } else if (classname == "float") {
                headerf << "\t\t\t\t" << "if (not isfinite(" << aliasname << "_)) {" << endl;
                headerf << "\t\t\t\t\t" << "printf(\"branch " << Form("%s_branch",aliasname.Data()) 
                        << " contains a bad float: %f\\n\", " << aliasname << "_);" << endl 
                        << "\t\t\t\t\t" << "exit(1);"
                        << endl;
                headerf << "\t\t\t\t}" << endl;
            } else if (classname.BeginsWith("vector<vector<ROOT::Math::LorentzVector")) {
                if(isSkimmedNtuple) {
                    headerf << "\t\t\t\t" << "for (" << classname.Data() <<"::const_iterator i = " 
                            << aliasname << "_->begin(); i != "<< aliasname << "_->end(); ++i) {" << endl;
                } else {
                    headerf << "\t\t\t\t" << "for (" << classname.Data() <<"::const_iterator i = " 
                            << aliasname << "_.begin(); i != "<< aliasname << "_.end(); ++i) {" << endl;
                }
                // this is a slightly hacky way to get rid of the outer vector< > ...
                std::string str = classname.Data() + 7;
                str[str.length() - 2] = 0;
                headerf << "\t\t\t\t\t" << "for (" << str.c_str() << "::const_iterator j = i->begin(); " 
                    "j != i->end(); ++j) {" << endl;
                headerf << "\t\t\t\t\t\t" << "int e;" << endl;
                headerf << "\t\t\t\t\t\t" << "frexp(j->pt(), &e);" << endl;
                headerf << "\t\t\t\t\t\t" << "if (not isfinite(j->pt()) || e > 30) {" << endl;
                headerf << "\t\t\t\t\t\t\t" << "printf(\"branch " << Form("%s_branch",aliasname.Data()) 
                        << " contains a bad float: %f\\n\", j->pt());" << endl << "\t\t\t\t\t\t\t" << "exit(1);"
                        << endl;
                headerf << "\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}" << endl;
            } else if (classname.BeginsWith("vector<ROOT::Math::LorentzVector")) {
                if(isSkimmedNtuple) {
                    headerf << "\t\t\t\t" << "for (" << classname.Data() << "::const_iterator i = " 
                            << aliasname << "_->begin(); i != "<< aliasname << "_->end(); ++i) {" << endl;
                } else {
                    headerf << "\t\t\t\t" << "for (" << classname.Data() << "::const_iterator i = " 
                            << aliasname << "_.begin(); i != "<< aliasname << "_.end(); ++i) {" << endl;
                }
                headerf << "\t\t\t\t\t" << "int e;" << endl;
                headerf << "\t\t\t\t\t" << "frexp(i->pt(), &e);" << endl;
                headerf << "\t\t\t\t\t" << "if (not isfinite(i->pt()) || e > 30) {" << endl;
                headerf << "\t\t\t\t\t\t" << "printf(\"branch " << Form("%s_branch",aliasname.Data()) 
                        << " contains a bad float: %f\\n\", i->pt());" << endl << "\t\t\t\t\t\t" << "exit(1);"
                        << endl;
                headerf << "\t\t\t\t\t}\n\t\t\t\t}" << endl;
            } else if (classname.BeginsWith("ROOT::Math::LorentzVector")) {
                headerf << "\t\t\t\t" << "int e;" << endl;
                if(isSkimmedNtuple) {
                    headerf << "\t\t\t\t" << "frexp(" << aliasname << "_->pt(), &e);" << endl;
                    headerf << "\t\t\t\t" << "if (not isfinite(" << aliasname << "_->pt()) || e > 30) {" << endl;
                    headerf << "\t\t\t\t\t" << "printf(\"branch " << Form("%s_branch",aliasname.Data()) 
                            << " contains a bad float: %f\\n\", " << aliasname << "_->pt());" << endl 
                            << "\t\t\t\t\t" << "exit(1);"
                            << endl;
                } else {
                    headerf << "\t\t\t\t" << "frexp(" << aliasname << "_.pt(), &e);" << endl;
                    headerf << "\t\t\t\t" << "if (not isfinite(" << aliasname << "_.pt()) || e > 30) {" << endl;
                    headerf << "\t\t\t\t\t" << "printf(\"branch " << Form("%s_branch",aliasname.Data()) 
                            << " contains a bad float: %f\\n\", " << aliasname << "_.pt());" << endl 
                            << "\t\t\t\t\t" << "exit(1);"
                            << endl;
                }
                headerf << "\t\t\t\t}" << endl;
            }
            headerf << "\t\t\t\t#endif // #ifdef PARANOIA" << endl;
        }
        headerf << "\t\t\t" << "} else { " << endl;
        headerf << "\t\t\t\t" << "printf(\"branch " << Form("%s_branch",aliasname.Data()) 
                << " does not exist!\\n\");" << endl;
        headerf << "\t\t\t\t" << "exit(1);" << endl << "\t\t\t}" << endl;
        headerf << "\t\t\t" << Form("%s_isLoaded",aliasname.Data()) << " = true;" << endl;
        headerf << "\t\t" << "}" << endl;
        if(isSkimmedNtuple) {
            headerf << "\t\t" << "return *" << aliasname << "_;" << endl << "\t}" << endl;
        }
        else if(classname.Contains("vector<TString>") || classname.Contains("vector<float>")) {
            headerf << "\t\t" << "return " << aliasname << "_;" << endl << "\t}" << endl;
        }
        else if(classname == "TString") {
            headerf << "\t\t" << "return *" << aliasname << "_;" << endl << "\t}" << endl;
        }
        else {
            headerf << "\t\t" << "return " << aliasname << "_;" << endl << "\t}" << endl;
        }
    }

    bool haveHLTInfo = false;
    bool haveL1Info  = false;
    bool haveHLT8E29Info = false;
    for(int i = 0; i < aliasarray->GetEntries(); i++) {
        TString aliasname(aliasarray->At(i)->GetName());
        if(aliasname=="hlt_trigNames") 
            haveHLTInfo = true;
        if(aliasname=="l1_trigNames") 
            haveL1Info = true;
        if(aliasname=="hlt8e29_trigNames") 
            haveHLT8E29Info = true;
    }
   
    if(haveHLTInfo) {
        //functions to return whether or not trigger fired - HLT
        headerf << "\t" << "bool passHLTTrigger(TString trigName) {" << endl;
        headerf << "\t\t" << "int trigIndx;" << endl;
        headerf << "\t\t" << "vector<TString>::const_iterator begin_it = hlt_trigNames().begin();" << endl;
        headerf << "\t\t" << "vector<TString>::const_iterator end_it = hlt_trigNames().end();" << endl;
        headerf << "\t\t" << "vector<TString>::const_iterator found_it = find(begin_it, end_it, trigName);" << endl;
        headerf << "\t\t" << "if(found_it != end_it)" << endl;
        headerf << "\t\t\t" << "trigIndx = found_it - begin_it;" << endl;
        headerf << "\t\t" << "else {" << endl;
        headerf << "\t\t\t" << "cout << \"Cannot find Trigger \" << trigName << endl; " << endl;
        headerf << "\t\t\t" << "return 0;" << endl;
        headerf << "\t\t"   << "}" << endl << endl;
        headerf << "\t" << "return hlt_bits().TestBitNumber(trigIndx);" << endl;
        headerf << "\t" << "}" << endl;
    }//if(haveHLTInfo) 

    if(haveHLT8E29Info) {
        //functions to return whether or not trigger fired - HLT
        headerf << "\t" << "bool passHLT8E29Trigger(TString trigName) {" << endl;
        headerf << "\t\t" << "int trigIndx;" << endl;
        headerf << "\t\t" << "vector<TString>::const_iterator begin_it = hlt8e29_trigNames().begin();" << endl;
        headerf << "\t\t" << "vector<TString>::const_iterator end_it = hlt8e29_trigNames().end();" << endl;
        headerf << "\t\t" << "vector<TString>::const_iterator found_it = find(begin_it, end_it, trigName);" << endl;
        headerf << "\t\t" << "if(found_it != end_it)" << endl;
        headerf << "\t\t\t" << "trigIndx = found_it - begin_it;" << endl;
        headerf << "\t\t" << "else {" << endl;
        headerf << "\t\t\t" << "cout << \"Cannot find Trigger \" << trigName << endl; " << endl;
        headerf << "\t\t\t" << "return 0;" << endl;
        headerf << "\t\t"   << "}" << endl << endl;
        headerf << "\t" << "return hlt8e29_bits().TestBitNumber(trigIndx);" << endl;
        headerf << "\t" << "}" << endl;
    }//if(haveHLT8E29Info) 


    if(haveL1Info) {
        //functions to return whether or not trigger fired - L1
        headerf << "\t" << "bool passL1Trigger(TString trigName) {" << endl;
        headerf << "\t\t" << "int trigIndx;" << endl;
        headerf << "\t\t" << "vector<TString>::const_iterator begin_it = l1_trigNames().begin();" << endl;
        headerf << "\t\t" << "vector<TString>::const_iterator end_it = l1_trigNames().end();" << endl;
        headerf << "\t\t" << "vector<TString>::const_iterator found_it = find(begin_it, end_it, trigName);" << endl;
        headerf << "\t\t" << "if(found_it != end_it)" << endl;
        headerf << "\t\t\t" << "trigIndx = found_it - begin_it;" << endl;
        headerf << "\t\t" << "else {" << endl;
        headerf << "\t\t\t" << "cout << \"Cannot find Trigger \" << trigName << endl; " << endl;
        headerf << "\t\t\t" << "return 0;" << endl;
        headerf << "\t\t"   << "}" << endl << endl;
        //get the list of branches that hold the L1 bitmasks
        //store in a set 'cause its automatically sorted
        set<TString> s_L1bitmasks;
        for(int j = 0; j < aliasarray->GetEntries(); j++) {
            TString aliasname(aliasarray->At(j)->GetName());
            // TBranch *branch = ev->GetBranch(ev->GetAlias(aliasname.Data()));
            TBranch *branch = 0;
            if (have_aliases)
                branch = ev->GetBranch(ev->GetAlias(aliasname.Data()));
            else
                branch = (TBranch*)aliasarray->At(j);

            TString classname = branch->GetClassName();
            if(aliasname.Contains("l1_bits") && classname.Contains("int")) {
                s_L1bitmasks.insert(aliasname);
            }
     
        }
        int i = 0;
        for(set<TString>::const_iterator s_it = s_L1bitmasks.begin();
            s_it != s_L1bitmasks.end(); s_it++, i++) {
      
            if(i==0) {
                headerf << "\t\t" << "if(trigIndx <= 31) {" << endl;
                headerf << "\t\t\t" << "unsigned int bitmask = 1;" << endl;
                headerf << "\t\t\t" << "bitmask <<= trigIndx;" << endl;	
                headerf << "\t\t\t" << "return " << *s_it << "() & bitmask;" << endl;
                headerf << "\t\t" << "}" << endl;
                continue;
            }
            headerf << "\t\t" << "if(trigIndx >= " << Form("%d && trigIndx <= %d", 32*i, 32*i+31) << ") {" << endl;
            headerf << "\t\t\t" << "unsigned int bitmask = 1;" << endl;
            headerf << "\t\t\t" << "bitmask <<= (trigIndx - " << Form("%d",32*i) << "); " << endl;	
            headerf << "\t\t\t" << "return " << *s_it << "() & bitmask;" << endl;
            headerf << "\t\t" << "}" << endl;
        }
        headerf << "\t" << "return 0;" << endl;
        headerf << "\t" << "}" << endl;
    }//if(haveL1Info)
    
    headerf << endl;
    headerf << "  static void progress( int nEventsTotal, int nEventsChain ){" << endl;
    headerf << "    int period = 1000;" << endl;
    headerf << "    if(nEventsTotal%1000 == 0) {" << endl;
    headerf << "      // xterm magic from L. Vacavant and A. Cerri" << endl;
    headerf << "      if (isatty(1)) {" << endl;
    headerf << "        if( ( nEventsChain - nEventsTotal ) > period ){" << endl;
    headerf << "          float frac = (float)nEventsTotal/(nEventsChain*0.01);" << endl;
    headerf << "          printf(\"\\015\\033[32m ---> \\033[1m\\033[31m%4.1f%%\"" << endl;
    headerf << "               \"\\033[0m\\033[32m <---\\033[0m\\015\", frac);" << endl;
    headerf << "          fflush(stdout);" << endl;
    headerf << "        }" << endl;
    headerf << "        else {" << endl;
    headerf << "          printf(\"\\015\\033[32m ---> \\033[1m\\033[31m%4.1f%%\"" << endl;
    headerf << "                 \"\\033[0m\\033[32m <---\\033[0m\\015\", 100.);" << endl;
    headerf << "          cout << endl;" << endl;
    headerf << "        }" << endl;
    headerf << "      }" << endl;
    headerf << "    }" << endl;
    headerf << "  }" << endl;
    headerf << "  " << endl;

    headerf << "};" << endl << endl;
    
    headerf << "#ifndef __CINT__" << endl;
    headerf << "extern " << Classname << " " << objName << ";" << endl;
    headerf << "#endif" << endl << endl;

    // Create namespace that can be used to access the extern'd cms2
    // object methods without having to type cms2. everywhere.
    // Does not include cms2.Init and cms2.GetEntry because I think
    // it is healthy to leave those methods as they are
    headerf << "namespace " << nameSpace << " {" << endl;
    implf   << "namespace " << nameSpace << " {" << endl;
    for (Int_t i = 0; i< aliasarray->GetEntries(); i++) {
        TString aliasname(aliasarray->At(i)->GetName());
        // TBranch *branch = ev->GetBranch(ev->GetAlias(aliasname.Data()));
        TBranch *branch = 0;
        if (have_aliases)
            branch = ev->GetBranch(ev->GetAlias(aliasname.Data()));
        else
            branch = (TBranch*)aliasarray->At(i);

        TString classname = branch->GetClassName();
        TString title = branch->GetTitle();
        if ( classname.Contains("vector") ) {
            if(classname.Contains("edm::Wrapper") ) {
                classname = classname(0,classname.Length()-2);
                classname.ReplaceAll("edm::Wrapper<","");
            }
            headerf << "\tconst " << classname << " &" << aliasname << "()";
            implf   << "\tconst " << classname << " &" << aliasname << "()";
        } else {
            if(classname.Contains("edm::Wrapper<") ) {
                classname = classname(0,classname.Length()-1);
                classname.ReplaceAll("edm::Wrapper<","");
            }
            if(classname != "" ) {
                headerf << "\tconst " << classname << " &" << aliasname << "()";
                implf   << "\tconst " << classname << " &" << aliasname << "()";
            } else {
                if(title.EndsWith("/i")){
                    headerf << "\tconst unsigned int &" << aliasname << "()";
                    implf   << "\tconst unsigned int &" << aliasname << "()";
                }
                if(title.EndsWith("/F")){
                    headerf << "\tconst float &" << aliasname << "()";
                    implf   << "\tconst float &" << aliasname << "()";
                }
                if(title.EndsWith("/I")){
                    headerf << "\tconst int &" << aliasname << "()";
                    implf   << "\tconst int &" << aliasname << "()";
                }
                if(title.EndsWith("/O")){
                    headerf << "\tconst bool &" << aliasname << "()";
                    implf   << "\tconst bool &" << aliasname << "()";
                }
            }
        }
        headerf << ";" << endl;
        implf   << " { return " << objName << "." << aliasname << "(); }" << endl;
    }
    if(haveHLTInfo) {
        //functions to return whether or not trigger fired - HLT
        headerf << "\t" << "bool passHLTTrigger(TString trigName);" << endl;
        implf   << "\t" << "bool passHLTTrigger(TString trigName) { return " << objName << ".passHLTTrigger(trigName); }" << endl;
    }//if(haveHLTInfo) 
    if(haveHLT8E29Info) {
        //functions to return whether or not trigger fired - HLT
        headerf << "\t" << "bool passHLT8E29Trigger(TString trigName);" << endl;
        implf   << "\t" << "bool passHLT8E29Trigger(TString trigName) { return " << objName << ".passHLT8E29Trigger(trigName); }" << endl;
    }//if(haveHLT8E29Info) 
    if(haveL1Info) {
        //functions to return whether or not trigger fired - L1
        headerf << "\t" << "bool passL1Trigger(TString trigName);" << endl;
        implf   << "\t" << "bool passL1Trigger(TString trigName) { return " << objName << ".passL1Trigger(trigName); }" << endl;
    }//if(haveL1Info)
 
}
コード例 #10
0
int main(int argc, char** argv){

  // RETRIEVING LIST OF FILENAMES TO CHECK

  if (argc != 3) {

    cout << "Usage: ./TopTreeContentDump --inputfiles file1;file2;fileN\n\n" << endl;

    exit(0);

  } else if (argc == 3 && !strstr(argv[1],"--inputfiles")) {

    cout << "Usage: ./TopTreeContentDump --inputfiles file1;file2;fileN\n\n" << endl;

    exit(0);

  }

  vector<string> fileNames;
  
  Tokenize(argv[2], fileNames, ";");


  // CHECKING THE FILECONTENT FOR FILE 0 AND COUNT EVENTS FOR ALL FILES

  unsigned int nEvents = 0; 

  for (int fileID=0; fileID < fileNames.size(); fileID++) {
  
    //cout << fileNames.at(fileID) << endl;

    TFile* f = TFile::Open(fileNames.at(fileID).c_str());
    
    TTree* runTree = (TTree*) f->Get("runTree");
    TTree* eventTree = (TTree*) f->Get("eventTree");
    
    TBranch* run_br = (TBranch *) runTree->GetBranch("runInfos");
    TRootRun* runInfos = 0;
    run_br->SetAddress(&runInfos);
    
    TBranch* event_br = (TBranch *) eventTree->GetBranch("Event");
    TRootEvent* event = 0;
    event_br->SetAddress(&event);
    
    nEvents += eventTree->GetEntriesFast();

    if (fileID == 0) {

      cout << "* Dumping the event content of the TopTree" << endl;
      
      for (int i=1; i<eventTree->GetListOfBranches()->GetEntriesFast(); i++) {
	
	TBranch * branch = (TBranch *)eventTree->GetListOfBranches()->At(i);
	
	TObject* obj = branch->GetListOfLeaves()->At(0);
	
	std::string ObjName = obj->GetName();
	
	string::size_type position = ObjName.find_last_of("_");
	
	std::string className = "";
	
	if (strstr(ObjName.c_str(),"CaloJet"))
	  className="TopTree::TRootCaloJet";
	else if (strstr(ObjName.c_str(),"PFJet"))
	  className="TopTree::TRootPFJet";
	else if (strstr(ObjName.c_str(),"JPTJet"))
	  className="TopTree::TRootJPTJet";
	else if (strstr(ObjName.c_str(),"GenJet"))
	  className="TopTree::TRootGenJet";
	else if (strstr(ObjName.c_str(),"MCParticles"))
	  className="TopTree::TRootMCParticle";
	else if (strstr(ObjName.c_str(),"NPGenEvent"))
	  className="TopTree::TRootNPGenEvent";
	else if (strstr(ObjName.c_str(),"GenEvent"))
	  className="TopTree::TRootGenEvent";
	else if (strstr(ObjName.c_str(),"Muon"))
	  className="TopTree::TRootMuon";
	else if (strstr(ObjName.c_str(),"Electron"))
	  className="TopTree::TRootElectron";
	else if (strstr(ObjName.c_str(),"TCMET"))
	  className="TopTree::TRootMET";
	else if (strstr(ObjName.c_str(),"CaloMET"))
	  className="TopTree::TRootCaloMET";
	else if (strstr(ObjName.c_str(),"PFMET"))
	  className="TopTree::TRootPFMET";
	else if (strstr(ObjName.c_str(),"MET"))
	  className="TopTree::TRootMET";
	else if (strstr(ObjName.c_str(), "TrackMET"))
	  className="TopTree::TRootTrackMET";  
	else if (strstr(ObjName.c_str(),"MHT"))
	  className="TopTree::TRootMHT";
	else if (strstr(ObjName.c_str(),"PrimaryVertex"))
	  className="TopTree::TRootVertex";
	

	cout << "- " << className << setw(5) << " -> " << "\"" << ObjName.substr(0,position) << "\""  << endl;
   
	    }

     //runinfos

     runTree->GetEvent(0);

     if (runInfos->hltInputTag() != "")
       cout << "- " << "TopTree::TRootRun" << setw(5) << " -> " << "\"" << runInfos->hltInputTag() << "\""  << endl;

    }

  }

  //cout << "\n* The TopTree file contains " << nEvents << " events\n" << endl;


}
コード例 #11
0
Int_t runPrefetchReading(bool caching = false)
{
   //const char *options = 0;
   Int_t freq = 1000; 
   Int_t cachesize = -1;
   Float_t percententries = 1.00;
   Float_t percentbranches = 1.00;
   TStopwatch sw;
   
   //set the reading mode to async prefetching
   gEnv->SetValue("TFile.AsyncPrefetching", 1);

   //enable the local caching of blocks
   TString cachedir="file:/tmp/xcache/";
   // or using xrootd on port 2000
   // TString cachedir="root://localhost:2000//tmp/xrdcache1/";
   if (caching) gEnv->SetValue("Cache.Directory", cachedir.Data());
   
   // open the local if any
   TString filename("atlasFlushed.root");
   if (gSystem->AccessPathName(filename,kReadPermission) && filename.Index(":") == kNPOS) {
      // otherwise open the http file
      filename.Prepend("https://root.cern.ch/files/");
      //filename.Prepend("root://cache01.usatlas.bnl.gov//data/test1/");
      //filename.Prepend( "root://pcitdss1401//tmp/" );
      //filename.Prepend("http://www-root.fnal.gov/files/");
      //filename.Prepend("http://oink.fnal.gov/distro/roottest/");
   }
   
   TString library("atlasFlushed/atlasFlushed");
   fprintf(stderr,"Starting to load the library\n");
   gSystem->Load(library);

   fprintf(stderr,"Starting to open the file\n");
   TFile *file = TFile::Open( filename, "TIMEOUT=30" );
   if (!file || file->IsZombie()) {
      Error("runPrefetchReading","Could not open the file %s within 30s",filename.Data());
      return 1;
   }
   fprintf(stderr,"The file has been opened, setting up the TTree\n");

   // file->MakeProject("atlasFlushed","*","RECREATE+");

   // Try the known names :)
   const char *names [] = { "E","Events","CollectionTree","ntuple","T" };
   TTree *T = NULL;
   for (unsigned int i = 0; i < sizeof(names)/sizeof(names[0]); ++i) {
      file->GetObject(names[i], T);
      if (T) break;
   }
   if (T==0) {
     Error("runPrefetchReading","Could not find a tree which the conventional names in %s.",filename.Data());
     return 2;
   }
   TFile::SetReadaheadSize(0);  // (256*1024);
   Long64_t nentries = T->GetEntries();

   int efirst = 0;
   int elast  = efirst+nentries;
   if (cachesize == -2) {
      gEnv->SetValue("TFile.AsyncReading", 0);
      cachesize = -1;
   }
   T->SetCacheSize(cachesize);

   if (cachesize != 0) {
      T->SetCacheEntryRange(efirst,elast);
      if (percentbranches < 1.00) {
         int nb = T->GetListOfBranches()->GetEntries();
         int incr = nb * percentbranches;
         for(int b=0;b < nb; b += incr) T->AddBranchToCache(((TBranch*)T->GetListOfBranches()->At(b)),kTRUE);
      } else {
         T->AddBranchToCache("*");
      }
      T->StopCacheLearningPhase();
   }

   //...........................................................................
   // First read, with saving the info in cache
   //...........................................................................
   fprintf(stderr,"Setup done. Starting to read the entries\n");
   TRandom r;
   for (Long64_t i = efirst; i < elast; i++) {
     //if (i%100 == 0 || i>2000) fprintf(stderr,"i.debug = %lld\n",i);
     // if (i==2000) gDebug = 7;
     if (i % freq == 0){
       // for (Long64_t i=elast-1;i>=efirst;i--) {
       if (i%freq == 0 || i==(elast-1)) fprintf(stderr,"i = %lld\n",i);
       if (r.Rndm() > percententries) continue; 
       T->LoadTree(i);
       if (percentbranches < 1.00) {
         int nb = T->GetListOfBranches()->GetEntries();
         int incr = nb * percentbranches;
         for(int b=0;b<nb; b += incr) ((TBranch*)T->GetListOfBranches()->At(b))->GetEntry(i);   
         int count = 0;
         int maxcount = 1000 + 100 ;
         for(int x = 0; x < maxcount; ++x ) { /* waste cpu */ count = sin(cos((double)count)); }
       } else {
         T->GetEntry(i);
       }
     }
   }

   fprintf(stderr,"Done reading for the first pass, now closing the file\n");
   file->Close();
   delete file;

   //...........................................................................
   // Second read, actually reading the data from cache
   //...........................................................................
   fprintf(stderr,"Opening the file for the 2nd pass\n");
   file = TFile::Open( filename, "TIMEOUT=30" );
   if (!file || file->IsZombie()) return 1;
 
   fprintf(stderr,"The file has been opened, setting up the TTree\n");
   // Try the known names :)
   for (unsigned int i = 0; i < sizeof(names)/sizeof(names[0]); ++i) {
      file->GetObject(names[i], T);
      if (T) break;
   }
   if (T==0) {
     Error("runPrefetchReading","Could not find a tree which the conventional names in %s.",filename.Data());
     return 2;
   }

   TFile::SetReadaheadSize(0);  // (256*1024);
   nentries = T->GetEntries();

   efirst = 0;
   elast  = efirst+nentries;

   if (cachesize == -2) {
      gEnv->SetValue("TFile.AsyncReading", 0);
      cachesize = -1;
   }
   T->SetCacheSize(cachesize);

   if (cachesize != 0) {
      T->SetCacheEntryRange(efirst,elast);
      if (percentbranches < 1.00) {
         int nb = T->GetListOfBranches()->GetEntries();
         int incr = nb * percentbranches;
         for(int b=0;b < nb; b += incr) T->AddBranchToCache(((TBranch*)T->GetListOfBranches()->At(b)),kTRUE);
      } else {
         T->AddBranchToCache("*");
      }
      T->StopCacheLearningPhase();
   }
      
   fprintf(stderr,"Setup done, starting the 2nd reading.\n");
   for (Long64_t i = efirst; i < elast; i++) {
     if (i % freq == 0){
       // for (Long64_t i=elast-1;i>=efirst;i--) {
       if (i%freq == 0 || i==(elast-1)) fprintf(stderr,"i = %lld\n",i);
       if (r.Rndm() > percententries) continue;
       T->LoadTree(i);
       if (percentbranches < 1.00) {
         int nb = T->GetListOfBranches()->GetEntries();
         int incr = nb * percentbranches;
         
         for(int b=0;b<nb; b += incr) {
           ((TBranch*)T->GetListOfBranches()->At(b))->GetEntry(i);
         }
         
         int count = 0;
         int maxcount = 1000 + 100 ;
         for(int x = 0; x < maxcount; ++x ) {
           /* waste cpu */
           count = sin(cos((double)count));
         }         
       } else {
         T->GetEntry(i);
       }
     }
   }
   fprintf(stderr, "Done with the 2nd reading\n");

   fprintf(stderr, "fPrefetchedBlocks = %lli\n", file->GetCacheRead()->GetPrefetchedBlocks());

   fprintf(stderr, "Delete tmp directory: /tmp/xcache\n" );
   if (caching) system( "rm -r /tmp/xcache" );
   
   file->Close();
   delete file;
   return 0;
}
コード例 #12
0
ファイル: branchSizes.cpp プロジェクト: hroskes/cmssw
int main(int argc, char *argv[]) {
  using namespace boost::program_options;
  using namespace std;

  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")(kAutoLoadCommandOpt,
                                                              "automatic library loading (avoid root warnings)")(
      kDataFileCommandOpt, value<string>(), "data file")(kAlphabeticOrderCommandOpt,
                                                         "sort by alphabetic order (default: sort by size)")(
      kPlotCommandOpt, value<string>(), "produce a summary plot")(
      kPlotTopCommandOpt, value<int>(), "plot only the <arg> top size branches")(
      kSavePlotCommandOpt, value<string>(), "save plot into root file <arg>")(kVerboseCommandOpt, "verbose printout");

  positional_options_description p;

  p.add(kDataFileOpt, -1);

  variables_map vm;
  try {
    store(command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
    notify(vm);
  } catch (const error &) {
    return 7000;
  }

  if (vm.count(kHelpOpt)) {
    cout << desc << std::endl;
    return 0;
  }

  if (!vm.count(kDataFileOpt)) {
    string shortDesc("ConfigFileNotFound");
    cerr << programName << ": no data file given" << endl;
    return 7001;
  }

  gROOT->SetBatch();

  if (vm.count(kAutoLoadOpt) != 0) {
    gSystem->Load("libFWCoreFWLite");
    FWLiteEnabler::enable();
  }

  string fileName = vm[kDataFileOpt].as<string>();
  TFile file(fileName.c_str());
  if (!file.IsOpen()) {
    cerr << programName << ": unable to open data file " << fileName << endl;
    return 7002;
  }

  TObject *o = file.Get("Events");
  if (o == 0) {
    cerr << programName << ": no object \"Events\" found in file: " << fileName << endl;
    return 7003;
  }

  TTree *events = dynamic_cast<TTree *>(o);
  if (events == 0) {
    cerr << programName << ": object \"Events\" is not a TTree in file: " << fileName << endl;
    return 7004;
  }

  TObjArray *branches = events->GetListOfBranches();
  if (branches == 0) {
    cerr << programName << ": tree \"Events\" in file " << fileName << " contains no branches" << endl;
    return 7004;
  }

  bool verbose = vm.count(kVerboseOpt) > 0;

  BranchVector v;
  const size_t n = branches->GetEntries();
  cout << fileName << " has " << n << " branches" << endl;
  for (size_t i = 0; i < n; ++i) {
    TBranch *b = dynamic_cast<TBranch *>(branches->At(i));
    assert(b != 0);
    string name(b->GetName());
    if (name == "EventAux")
      continue;
    size_type s = GetTotalSize(b, verbose);
    v.push_back(make_pair(b->GetName(), s));
  }
  if (vm.count(kAlphabeticOrderOpt)) {
    sort(v.begin(), v.end(), sortByName());
  } else {
    sort(v.begin(), v.end(), sortByCompressedSize());
  }
  bool plot = (vm.count(kPlotOpt) > 0);
  bool save = (vm.count(kSavePlotOpt) > 0);
  int top = n;
  if (vm.count(kPlotTopOpt) > 0)
    top = vm[kPlotTopOpt].as<int>();
  TH1F uncompressed("uncompressed", "branch sizes", top, -0.5, -0.5 + top);
  TH1F compressed("compressed", "branch sizes", top, -0.5, -0.5 + top);
  int x = 0;
  TAxis *cxAxis = compressed.GetXaxis();
  TAxis *uxAxis = uncompressed.GetXaxis();

  for (BranchVector::const_iterator b = v.begin(); b != v.end(); ++b) {
    const string &name = b->first;
    size_type size = b->second;
    cout << size << " " << name << endl;
    if (x < top) {
      cxAxis->SetBinLabel(x + 1, name.c_str());
      uxAxis->SetBinLabel(x + 1, name.c_str());
      compressed.Fill(x, size.second);
      uncompressed.Fill(x, size.first);
      x++;
    }
  }
  //  size_type branchSize = GetTotalBranchSize( events );
  //  cout << "total branches size: " << branchSize.first << " bytes (uncompressed), "
  //       << branchSize.second << " bytes (compressed)"<< endl;
  size_type totalSize = GetTotalSize(events);
  cout << "total tree size: " << totalSize.first << " bytes (uncompressed), " << totalSize.second
       << " bytes (compressed)" << endl;
  double mn = DBL_MAX;
  for (int i = 1; i <= top; ++i) {
    double cm = compressed.GetMinimum(i), um = uncompressed.GetMinimum(i);
    if (cm > 0 && cm < mn)
      mn = cm;
    if (um > 0 && um < mn)
      mn = um;
  }
  mn *= 0.8;
  double mx = max(compressed.GetMaximum(), uncompressed.GetMaximum());
  mx *= 1.2;
  uncompressed.SetMinimum(mn);
  uncompressed.SetMaximum(mx);
  compressed.SetMinimum(mn);
  //  compressed.SetMaximum( mx );
  cxAxis->SetLabelOffset(-0.32);
  cxAxis->LabelsOption("v");
  cxAxis->SetLabelSize(0.03);
  uxAxis->SetLabelOffset(-0.32);
  uxAxis->LabelsOption("v");
  uxAxis->SetLabelSize(0.03);
  compressed.GetYaxis()->SetTitle("Bytes");
  compressed.SetFillColor(kBlue);
  compressed.SetLineWidth(2);
  uncompressed.GetYaxis()->SetTitle("Bytes");
  uncompressed.SetFillColor(kRed);
  uncompressed.SetLineWidth(2);
  if (plot) {
    string plotName = vm[kPlotOpt].as<string>();
    gROOT->SetStyle("Plain");
    gStyle->SetOptStat(kFALSE);
    gStyle->SetOptLogy();
    TCanvas c;
    uncompressed.Draw();
    compressed.Draw("same");
    c.SaveAs(plotName.c_str());
  }
  if (save) {
    string fileName = vm[kSavePlotOpt].as<string>();
    TFile f(fileName.c_str(), "RECREATE");
    compressed.Write();
    uncompressed.Write();
    f.Close();
  }
  return 0;
}
コード例 #13
0
ファイル: KVSimDir.cpp プロジェクト: GiuseppePast/kaliveda
void KVSimDir::AnalyseFile(const Char_t* filename)
{
   // Analyse ROOT file given as argument.
   // If there is a TTree in the file, then we look at all of its branches until we find one
   // containing objects which derive from KVEvent:
   //
   //   -- if they inherit from KVSimEvent, we add the file to the list of simulated data:
   //            * a KVSimFile is created. The title of the TTree where data were found will
   //               be used as 'Information' on the nature of the simulation.
   //   -- if they inherit from KVReconstructedEvent, we add the file to the list of filtered data.
   //            * a KVSimFile is created. Informations on the filtered data are extracted from
   //              TNamed objects in the file with names 'Dataset', 'System', 'Run', 'Geometry'
   //              (type of geometry used, 'ROOT' or 'KV'), 'Origin' (i.e. the name of the simulation
   //              file which was filtered), 'Filter' (type of filter: Geo, GeoThresh or Full).
   //              These objects are automatically created when data is filtered using KVEventFiltering.
   //
   // Analysis of the file stops after the first TTree with a branch satisfying one of the
   // two criteria is found (it is assumed that in each file there is only one TTree containing
   // either simulated or filtered data).

   Info("AnalyseFile", "Analysing file %s...", filename);
   TString fullpath;
   AssignAndDelete(fullpath, gSystem->ConcatFileName(GetDirectory(), filename));
   TFile* file = TFile::Open(fullpath);
   if (!file || file->IsZombie()) return;
   // look for TTrees in file
   TIter next(file->GetListOfKeys());
   TKey* key;
   while ((key = (TKey*)next())) {
      TString cn = key->GetClassName();
      if (cn == "TTree") {
         // look for branch with KVEvent objects
         TTree* tree = (TTree*)file->Get(key->GetName());
         TSeqCollection* branches = tree->GetListOfBranches();
         TIter nextB(branches);
         TBranchElement* branch;
         while ((branch = (TBranchElement*)nextB())) {
            TString branch_classname = branch->GetClassName();
            TClass* branch_class = TClass::GetClass(branch_classname, kFALSE, kTRUE);
            if (branch_class && branch_class->InheritsFrom("KVEvent")) {
               if (branch_class->InheritsFrom("KVSimEvent")) {
                  fSimData.Add(new KVSimFile(this, filename, tree->GetTitle(), tree->GetEntries(), tree->GetName(), branch->GetName()));
                  delete file;
                  return;
               } else if (branch_class->InheritsFrom("KVReconstructedEvent")) {
                  // filtered data. there must be TNamed called 'Dataset', 'System', & 'Run' in the file.
                  TNamed* ds = (TNamed*)file->Get("Dataset");
                  TNamed* orig = (TNamed*)file->Get("Origin");
                  TNamed* sys = (TNamed*)file->Get("System");
                  TNamed* r = (TNamed*)file->Get("Run");
                  TNamed* g = (TNamed*)file->Get("Geometry");
                  TNamed* f = (TNamed*)file->Get("Filter");
                  TString dataset;
                  if (ds) dataset = ds->GetTitle();
                  TString system;
                  if (sys) system = sys->GetTitle();
                  TString run;
                  if (r) run = r->GetTitle();
                  TString origin;
                  if (orig) origin = orig->GetTitle();
                  TString geometry;
                  if (g) geometry = g->GetTitle();
                  TString filter;
                  if (f) filter = f->GetTitle();
                  Int_t run_number = run.Atoi();
                  fFiltData.Add(new KVSimFile(this, filename, tree->GetTitle(), tree->GetEntries(), tree->GetName(), branch->GetName(),
                                              dataset, system, run_number, geometry, origin, filter));
                  delete file;
                  delete ds;
                  delete sys;
                  delete r;
                  delete f;
                  return;
               }
            }
         }
      }
   }
}
コード例 #14
0
std::string generateCodeFromStreamers(std::string url, std::string treeLocation, std::vector<std::string> &classNames, std::string &errorMessage) {
  TFile *tfile = TFile::Open(url.c_str());
  if (tfile == nullptr  ||  !tfile->IsOpen()) {
    errorMessage = std::string("File not found: ") + url;
    return std::string();
  }

  if (tfile->IsZombie()) {
    errorMessage = std::string("Not a ROOT file: ") + url;
    return std::string();
  }

  TTreeReader reader(treeLocation.c_str(), tfile);
  if (reader.IsZombie()) {
    errorMessage = std::string("Not a TTree: ") + treeLocation.c_str() + std::string(" in file: ") + url;
    return std::string();
  }

  TTree *ttree = reader.GetTree();

  std::set<std::string> includes;
  std::vector<ClassStructure> classes;

  TIter listOfBranches = ttree->GetListOfBranches();
  for (TBranch *tbranch = (TBranch*)listOfBranches.Next();  tbranch != nullptr;  tbranch = (TBranch*)listOfBranches.Next()) {
    TClass *tclass = TClass::GetClass(tbranch->GetClassName());
    if (tclass != nullptr  &&  tbranch->GetListOfBranches()->GetEntries() > 0)
      classesFromBranch(tbranch, tclass, classes, 0, includes);
  }

  for (int i = 0;  i < classes.size();  i++)
    classNames.push_back(classes[i].fullName);

  tfile->Close();

  std::string out;

  for (std::set<std::string>::iterator iter = includes.begin();  iter != includes.end();  ++iter)
    out += *iter + "\n";
  out += "\n";
  
  for (std::vector<ClassStructure>::iterator iter = classes.begin();  iter != classes.end();  ++iter) {
    int i = 0;
    for (;  i < iter->splitName.size() - 1;  i++)
      out += std::string(i * 2, ' ') + "namespace " + iter->splitName[i] + " {\n";

    out += std::string(i * 2, ' ') + "class " + iter->splitName.back() + ";\n";
    i--;
    for (;  i >= 0;  i--)
      out += std::string(i * 2, ' ') + "}\n";
  }
  out += "\n";

  for (std::vector<ClassStructure>::iterator iter = classes.begin();  iter != classes.end();  ++iter) {
    int i = 0;
    for (;  i < iter->splitName.size() - 1;  i++)
      out += std::string(i * 2, ' ') + "namespace " + iter->splitName[i] + " {\n";
    out += iter->cpp(i * 2) + "\n";
    i--;
    for (;  i >= 0;  i--)
      out += std::string(i * 2, ' ') + "}\n";
  }

  for (std::vector<ClassStructure>::iterator iter = classes.begin();  iter != classes.end();  ++iter) {
    int i = 0;
    for (;  i < iter->splitName.size() - 1;  i++)
      out += std::string(i * 2, ' ') + "namespace " + iter->splitName[i] + " {\n";
    out += std::string(i * 2, ' ') + "ClassImp(" + iter->splitName.back() + ")\n";
    i--;
    for (;  i >= 0;  i--)
      out += std::string(i * 2, ' ') + "}\n";
  }
  
  return out;
}
コード例 #15
0
ファイル: Test_dpd.C プロジェクト: akanevm/HCCRAB3
void Test_dpd(std::string argStr, int DEBUG, int write_branches){

  //Define number of messages by value of DEBUG; if int DEBUG == 1 print all messages into txt file
  //write_branches == 1 => will write list of branches into txt file list_of_branches.txt

  if (DEBUG != 1) DEBUG = 0;
  if (write_branches != 1) write_branches = 0;

  //First part: Read in file list

  /*
  std::string argStr;

  char buf[256+1];
  unsigned int delpos;
  std::ifstream ifs("input.txt");
  while (true)
    {
      ifs.read(buf,256);
      if (ifs.eof())
        {
          if (ifs.gcount() == 0) break;
          delpos = ifs.gcount()-1;
        }
      else
        {
          delpos = ifs.gcount();
        }
      buf[delpos] = 0x00;
      argStr += buf;
    }
  */
  std::ofstream ofs("output.txt");
  std::ofstream ofs2;
  int error_counter = 0;

  // split by ','
  std::vector<std::string> fileList;
  for (size_t i=0,n; i <= argStr.length(); i=n+1)
    {
      n = argStr.find_first_of(',',i);
      if (n == string::npos)
        n = argStr.length();
      std::string tmp = argStr.substr(i,n-i);
      std::string ttmp;
      for(unsigned int j=0; j<tmp.size(); j++)
	{
	  if(tmp[j]==' ' || tmp[j]=='\n') continue;
	  ttmp+=tmp[j];
	}
      fileList.push_back(ttmp);
    }

  // open input files
  int open_tree = 0;
  TChain * chain = new TChain("susy","");
  for (unsigned int iFile=0; iFile<fileList.size(); ++iFile)
    {
      std::cout << "open " << fileList[iFile].c_str() << std::endl;
      ofs << "open " << fileList[iFile].c_str() << std::endl;
      open_tree = chain->AddFile(fileList[iFile].c_str(),0);
      if (DEBUG==1) cout << "Status of file appened to chain: " << open_tree << endl;
      if (open_tree == 0) {
	ofs << "Error: File cannot be opened or tree \'susy\' does not exist" << endl;
	error_counter++;
      }
    }

  TTree *tree;
  tree = chain;


  Long64_t entries = tree->GetEntries();


  if (DEBUG==1) cout << "Number of entries in tree: " << entries << endl;
  if (DEBUG==1) ofs << "Number of entries in tree: " << entries << endl;
  if (entries ==0) {
    cout << "Error: Tree has no entries" << endl;
    ofs << "Error: Tree has no entries" << endl;
    error_counter++;
  }

  Long64_t b = 0;

  TObjArray * list_of_branches = (TObjArray*)tree->GetListOfBranches();

  int number_of_branches = 0;
  if(write_branches == 1 && !ofs2.is_open()) ofs2.open("list_of_branches.txt");

  for (int j=0; j<=list_of_branches->LastIndex(); j++)
    {
      number_of_branches++;
      std::string tmp_branch = ((TBranch*)list_of_branches->At(j))->GetName(); 
      if(write_branches == 1) ofs2 << tmp_branch << endl; 
      if(tmp_branch!="" && tree->GetBranch(tmp_branch.c_str())) {
	b = (tree->GetBranch(tmp_branch.c_str()))->GetTotalSize();
	if (DEBUG==1) cout << "Size of branch " << tmp_branch << ": " << b << endl;
	if (DEBUG==1) ofs << "Size of branch " << tmp_branch << ": " << b << endl;
	if (b <= 0) {
	  cout << "Error in branch " << tmp_branch << endl;
	  ofs << "Error in branch " << tmp_branch << endl;
	  error_counter++;
	}
      }
      else if(tmp_branch!="" && !(tree->GetBranch(tmp_branch.c_str())))
	{
	  cout << "Error: " << tmp_branch << " does not exist" << endl;
	  ofs << "Error: " << tmp_branch << " does not exist" << endl;
	  error_counter++;
	}
    }
  if (DEBUG==1) cout <<"Number of branches: " << number_of_branches << endl; 
  cout << error_counter << " error(s) was(were) reported." << endl;
}
コード例 #16
0
ファイル: makesigback.C プロジェクト: twighk/gbmsci
int makesigback(){
    
    TFile * infile = new TFile("../root/combo115.root");
//    TFile * infile = new TFile("../root/combo160.root");

    Int_t type1 = 1;
    Int_t type2 = 0;
    Double_t weight;
    Int_t switchpoint;
    TTree * intree = (TTree*)infile->Get("combotree");
    TTree * inmeta = (TTree*)infile->Get("metadata");
    inmeta->SetBranchAddress("BeginIndex", &switchpoint);
    inmeta->GetEntry(2);
    cout << switchpoint << endl;
    
    TObjArray* lob = intree->GetListOfBranches();

    intree->SetBranchStatus("*",0);
    
	for (Int_t i = 0; i < lob->GetEntriesFast(); ++i) {
		TBranch * branch = (TBranch *)lob->At(i);
		string bname = string(branch -> GetName());
        if(string(bname).compare(0,4,"type")){
            if (bname == "weight") {
                continue;
            }
            intree->SetBranchStatus(bname.c_str(),1);

		}
    }
    
    TFile *newfile = new TFile("../root/combo115sb.root","recreate");
    TTree *newtree = intree->CloneTree(0);
    newtree->Branch("type1", &type1);
    newtree->Branch("type2", &type2);
    newtree->Branch("weight", &weight);
    weight = (1. / Double_t(switchpoint) );

    for (UInt_t j = 0; j < intree->GetEntriesFast(); ++j) {
            if (j == switchpoint) {
                type1 = 0;
                type2 = 1;
                weight = (1. / Double_t(intree->GetEntriesFast() - switchpoint) );
            }
             intree->GetEntry(j);
             newtree->Fill();
          }
    
    Int_t newbegin;
    Int_t newend;
    TString newchannelname;
    TTree * newmeta = new TTree("metadata", "metadata");
    newmeta->Branch("BeginIndex", &newbegin);
    newmeta->Branch("EndIndex", &newend);
    newmeta->Branch("ChannelName",&newchannelname,256000,0);
    
    newbegin = 0;
    newend = switchpoint - 1;
    newchannelname = "signal";
    newmeta->Fill();
    
    newbegin = switchpoint;
    newend = (intree->GetEntriesFast()) - 1;
    newchannelname = "backgr";
    newmeta->Fill();

    newfile->Write();
    delete infile;
    delete newfile;
    
//    vector <TFile*> files;
//    vector <TTree*> trees;
//    vector < vector<Double_t> > Int_lum;
//    vector <TFile*> outfiles;
//    vector <TTree*> outtrees;
//    vector <string> names;
    
//    Int_lum.resize(15);
//    Int_lum[0].push_back(7852.);
//    Int_lum[1].push_back(3831.);
//    Int_lum[2].push_back(36823.);
//    Int_lum[3].push_back(11400.);
//    Int_lum[4].push_back(10.4);
//    Int_lum[5].push_back(8.4);
//    Int_lum[6].push_back(47.2);
//    Int_lum[7].push_back(6.28);
//    Int_lum[8].push_back(7.94);
//    Int_lum[9].push_back(18.1);
//    Int_lum[10].push_back(2562.);
//    Int_lum[11].push_back(243.);
//    Int_lum[12].push_back(3483.);
//    Int_lum[13].push_back(3483.);
//    Int_lum[14].push_back(331.);

//    names.push_back("AH115");
//    names.push_back("AH115bb");
//    names.push_back("AH160");
//    names.push_back("AH160bb");
//    names.push_back("QCD_BCtoE_Pt20to30");
//    names.push_back("QCD_BCtoE_Pt30to80");
//    names.push_back("QCD_BCtoE_Pt80to170");
//    names.push_back("QCD_EMenriched_Pt20to30");
//    names.push_back("QCD_EMenriched_Pt30to80");
//    names.push_back("QCD_EMenriched_Pt80to170");
//    names.push_back("TTplusJets");
//    names.push_back("WplusJets");
//    names.push_back("Zbb");
//    names.push_back("Zcc");
//    names.push_back("ZplusJets");

    
//    for (UInt_t i = 0; i < names.size(); ++i) {
//        files.push_back(new TFile( ("../root/oldroot/"+names[i]+".root").c_str() ));
//        trees.push_back( (TTree*)files[i]->Get("bbAHCutTree") );
//        outfiles.push_back(new TFile ( ("../root/"+names[i]+".root").c_str() , "RECREATE"));
//        outtrees.push_back( trees[i]->CloneTree(0) );
//        outtrees[i]->Branch("intlum", &(Int_lum[i]));
//        for (UInt_t j = 0; j < trees[i]->GetEntriesFast(); ++j) {
//            trees[i]->GetEntry(j);
//            outtrees[i]->Fill();
//        }
//        outfiles[i]->Write();
//    }
                           
    return 0;


}
コード例 #17
0
ファイル: PlotOpt.C プロジェクト: crogan/CompressedAnalysis
void PlotOpt(){
  // fixed background uncertainty (%)
  g_deltaNbkg = 20.;
  // integrated luminosity (fb^-1)
  g_lumi = 10.;
  // minimum number of expected background events
  g_minBKG = 0.01;

  TFile* input = new TFile("test.root","READ");

  int ParentMass = 250;
  int LSPMass    = 77;

  double Sscale = 1.;
  double Bscale = 1.;

  string SignalModel = "TT";
  string plot_title = "#tilde{t} #tilde{t} #rightarrow (t #tilde{#chi})(t #tilde{#chi}); m_{#tilde{t}} = ";
  plot_title += to_string(ParentMass)+", m_{#tilde{#chi}} = "+to_string(LSPMass)+" GeV";
  
  TTree* tree  = (TTree*) input->Get("optimization");
  double Nsig, Nbkg;
  vector<double> VAR;
  TBranch *b_Nsig,*b_Nbkg;
  vector<TBranch*> b_VAR;
  //int Ncut = tree->GetNbranches()-2;
  int Ncut = 0;
  TObjArray* branches = tree->GetListOfBranches();
  int Nbranch = branches->GetEntries();
  for(int i = 0; i < Nbranch; i++)
    if(string(branches->At(i)->GetName()).find("var") != string::npos)
      Ncut++;
  tree->SetBranchStatus("*",0);
  string sname = "Nsig_"+SignalModel+"_"+to_string(ParentMass)+"_"+to_string(LSPMass);
  tree->SetBranchStatus(sname.c_str(),"1");
  tree->SetBranchAddress(sname.c_str(),&Nsig,&b_Nsig);
  tree->SetBranchStatus("Nbkg","1");
  tree->SetBranchAddress("Nbkg",&Nbkg,&b_Nbkg);
  for(int i = 0; i < Ncut; i++){
    VAR.push_back(0.);
    b_VAR.push_back(new TBranch());
  }
  for(int i = 0; i < Ncut; i++){
    tree->SetBranchStatus(("var"+to_string(i)).c_str(),"1");
    tree->SetBranchAddress(("var"+to_string(i)).c_str(),&(VAR[i]),&b_VAR[i]);
  }

  int Ncomb = tree->GetEntries();

  vector<vector<double> > VAR_cut;
  for(int i = 0; i < Ncut; i++)
    VAR_cut.push_back(vector<double>());

  // find max metric combination
  int c_max = -1;
  double metric_max = -1.;
  for(int c = 0; c < Ncomb; c++){
    tree->GetEntry(c);
    double metric = 0;
    if(Nsig > 0. && Nbkg > 0. && g_lumi*Nbkg*Bscale > g_minBKG)
       metric = EvaluateMetric(g_lumi*Nsig*Sscale,g_lumi*Nbkg*Bscale);
    if(metric > metric_max && g_lumi*Nbkg*Bscale > g_minBKG){
      metric_max = metric;
      c_max = c;
    }
    for(int i = 0; i < Ncut; i++){
      int N = VAR_cut[i].size();
      bool found = false;
      for(int j = 0; j < N; j++){
	if(VAR_cut[i][j] == VAR[i]){
	  found = true;
	  break;
	}
      }
      if(!found)
	VAR_cut[i].push_back(VAR[i]);
    }
  }
  
  vector<double> VAR_max;
  tree->GetEntry(c_max);
  cout << "Point: " << ParentMass << " " << LSPMass << endl;;
  cout << "Max significance of " << EvaluateMetric(g_lumi*Nsig*Sscale,g_lumi*Nbkg*Bscale);
  cout << " sigma with:" << endl;
  cout << "   Nsig = " << g_lumi*Nsig*Sscale << endl;
  cout << "   Nbkg = " << g_lumi*Nbkg*Bscale << endl;
  for(int i = 0; i < Ncut; i++){
    VAR_max.push_back(VAR[i]);
    cout << "var " << i << " " << VAR[i] << endl;
  }

  vector<vector<double> > VAR_max_fix;
  vector<vector<double> > VAR_max_float;
  for(int i = 0; i < Ncut; i++){
    VAR_max_fix.push_back(vector<double>());
    VAR_max_float.push_back(vector<double>());
    int N = VAR_cut[i].size();
    for(int j = 0; j < N; j++){
      VAR_max_fix[i].push_back(-1.);
      VAR_max_float[i].push_back(-1.);
    }
  }

  for(int c = 0; c < Ncomb; c++){
    tree->GetEntry(c);
    double metric = 0;
    if(Nsig > 0. && Nbkg > 0. && g_lumi*Nbkg*Bscale > g_minBKG)
       metric = EvaluateMetric(g_lumi*Nsig*Sscale,g_lumi*Nbkg*Bscale);
   
    for(int i = 0; i < Ncut; i++){
      int N = VAR_cut[i].size();
      int jcut = -1;
      for(int j = 0; j < N; j++)
	if(VAR[i] == VAR_cut[i][j])
	  jcut = j;
      if(metric > VAR_max_float[i][jcut])
	VAR_max_float[i][jcut] = metric;
      bool fix = true;
      for(int j = 0; j < Ncut; j++){
	if(i == j) continue;
	if(fabs(VAR[j]-VAR_max[j]) > 1e-10){
	  fix = false;
	  break;
	}
      }
      if(!fix)
	continue;
      if(metric > VAR_max_fix[i][jcut]){
	VAR_max_fix[i][jcut] = metric;
      }
    }
  }
  
  TGraph* gr_fix[Ncut];
  TGraph* gr_float[Ncut];
  TMultiGraph* mg[Ncut];
  TCanvas* can[Ncut];
  TLegend* leg;

  for(int icut = 0; icut < Ncut; icut++){
    int Nval = VAR_cut[icut].size();
    double x[Nval];
    double y[2][Nval];
    for(int i = 0; i < Nval; i++){
      x[i] = VAR_cut[icut][i];
      y[0][i] = VAR_max_fix[icut][i];
      y[1][i] = VAR_max_float[icut][i];
    }
    gr_fix[icut] = (TGraph*) new TGraph(Nval,x,y[0]);
    gr_float[icut] = (TGraph*) new TGraph(Nval,x,y[1]);
    gr_fix[icut]->SetLineWidth(4);
    gr_fix[icut]->SetLineColor(kBlue+2);
    gr_fix[icut]->SetFillColor(kWhite);
    gr_fix[icut]->SetMarkerSize(0);
    gr_float[icut]->SetLineWidth(4);
    gr_float[icut]->SetLineStyle(7);
    gr_float[icut]->SetLineColor(kGreen+3);
    gr_float[icut]->SetFillColor(kWhite);
    gr_float[icut]->SetMarkerSize(0);
    mg[icut] = (TMultiGraph*) new TMultiGraph();
    mg[icut]->Add(gr_fix[icut]);
    mg[icut]->Add(gr_float[icut]);

    string scan = "can_"+to_string(icut);
    can[icut] = (TCanvas*) new TCanvas(scan.c_str(),scan.c_str(),600.,500);
    can[icut]->SetLeftMargin(0.15);
    can[icut]->SetRightMargin(0.04);
    can[icut]->SetBottomMargin(0.15);
    can[icut]->SetGridx();
    can[icut]->SetGridy();
    can[icut]->Draw();
    can[icut]->cd();
    mg[icut]->Draw("AL");
    mg[icut]->GetXaxis()->CenterTitle();
    mg[icut]->GetXaxis()->SetTitleFont(132);
    mg[icut]->GetXaxis()->SetTitleSize(0.06);
    mg[icut]->GetXaxis()->SetTitleOffset(1.13);
    mg[icut]->GetXaxis()->SetLabelFont(132);
    mg[icut]->GetXaxis()->SetLabelSize(0.05);
    mg[icut]->GetXaxis()->SetTitle(("Var "+to_string(icut)).c_str());
    mg[icut]->GetYaxis()->CenterTitle();
    mg[icut]->GetYaxis()->SetTitleFont(132);
    mg[icut]->GetYaxis()->SetTitleSize(0.06);
    mg[icut]->GetYaxis()->SetTitleOffset(1.2);
    mg[icut]->GetYaxis()->SetLabelFont(132);
    mg[icut]->GetYaxis()->SetLabelSize(0.05);
    mg[icut]->GetYaxis()->SetTitle("Significance ( Z_{Bi} )");
    
    if(icut == 0){
      leg = (TLegend*) new TLegend(0.688,0.22,0.93,0.42);
      leg->SetTextFont(132);
      leg->SetTextSize(0.06);
      leg->AddEntry(gr_fix[icut],"#vec{c} |_{global max}");
      leg->AddEntry(gr_float[icut],"#vec{c} |_{local max}");
      leg->SetFillColor(kWhite);
      leg->SetLineColor(kWhite);
      leg->SetShadowColor(kWhite);
    } 
    leg->Draw("SAME");

    TLatex l;
    l.SetTextFont(132);	
    l.SetNDC();	
    l.SetTextSize(0.04);
    l.SetTextFont(132);
    l.DrawLatex(0.17,0.855,plot_title.c_str());
    l.SetTextSize(0.04);
    l.SetTextFont(42);
    l.DrawLatex(0.15,0.943,"#bf{#it{ATLAS}} Internal");
    l.SetTextSize(0.045);
    l.SetTextFont(132);
    string bla = "#scale[0.6]{#int} #it{L dt} = "+to_string(int(g_lumi))+" fb^{-1},  #Delta_{N#scale[0.8]{bkg}} = ";
    bla += to_string(int(g_deltaNbkg))+" %";
    l.DrawLatex(0.55,0.943,bla.c_str());
  }
  
}
コード例 #18
0
ファイル: fit1d.C プロジェクト: quittnat/light_diphoton
//get the RooDataSet, multiply each roorealvar by the event_weight
void get_roodset_from_ttree(TDirectoryFile *f, TString treename, RooDataSet* &roodset){
  cout << "Creating roodset from file: " << f->GetName() << " with tree: " << treename.Data() << endl;

  TTree *t = NULL;
  assert(roodset==NULL);
  f->GetObject(treename.Data(),t);
  if (!t) {cout << "Impossible to find TTree " << treename.Data() << endl; return;}
  TObjArray *objs = t->GetListOfBranches();
  //disables all branches
  t->SetBranchStatus("*",0);


  float v_rooisopv1;
  float v_rooisopv2;
  float v_rooisowv1;
  float v_rooisowv2;
  float v_roovar1;
  float v_roovar2;
  float v_roopt1;
  float v_roosieie1;
  float v_rooeta1;
  float v_roopt2;
  float v_roosieie2;
  float v_rooeta2;
  float v_roodiphopt;
  float v_roodiphomass;
  float v_roorho;
  float v_roosigma;
  float v_roonvtx;
  float v_rooweight;

  TBranch *b_roovar1;
  TBranch *b_roovar2;
  TBranch *b_rooisopv1;
  TBranch *b_rooisopv2;
  TBranch *b_rooisowv1;
  TBranch *b_rooisowv2;
  TBranch *b_roopt1;
  TBranch *b_roosieie1;
  TBranch *b_rooeta1;
  TBranch *b_roopt2;
  TBranch *b_roosieie2;
  TBranch *b_rooeta2;
  TBranch *b_roodiphopt;
  TBranch *b_roodiphomass;
  TBranch *b_roorho;
  TBranch *b_roosigma;
  TBranch *b_roonvtx;
  TBranch *b_rooweight;

  const int nvars = 18;
  float* ptrs[nvars]={&v_roovar1,&v_roovar2,&v_rooisopv1,&v_rooisopv2,&v_rooisowv1,&v_rooisowv2,&v_roopt1,&v_roosieie1,&v_rooeta1,&v_roopt2,&v_roosieie2,&v_rooeta2,&v_roodiphopt,&v_roodiphomass,&v_roorho,&v_roosigma,&v_roonvtx,&v_rooweight};
  TBranch** branches[nvars]={&b_roovar1,&b_roovar2,&b_rooisopv1,&b_rooisopv2,&b_rooisowv1,&b_rooisowv2,&b_roopt1,&b_roosieie1,&b_rooeta1,&b_roopt2,&b_roosieie2,&b_rooeta2,&b_roodiphopt,&b_roodiphomass,&b_roorho,&b_roosigma,&b_roonvtx,&b_rooweight};
  RooRealVar* rooptrs[nvars]={roovar1,roovar2,rooisopv1,rooisopv2,rooisowv1,rooisowv2,roopt1,roosieie1,rooeta1,roopt2,roosieie2,rooeta2,roodiphopt,roodiphomass,roorho,roosigma,roonvtx,rooweight};
  bool status[nvars];
  RooArgSet args;
  for (int i=0; i<nvars; i++){ 
    status[i]=0;
    TString name = rooptrs[i]->GetName();
    TObject *obj = objs->FindObject(name.Data());
    if (!obj) continue;
    t->SetBranchStatus(name.Data(),1);
    status[i]=1;
    t->SetBranchAddress(name.Data(),ptrs[i],branches[i]);
 
   args.add(*(rooptrs[i]));
  }

  TString newname = Form("roo_%s",t->GetName());
  roodset = new RooDataSet(newname.Data(),newname.Data(),args,WeightVar(*rooweight) );
  for (int j=0; j<t->GetEntries(); j++){
    t->GetEntry(j);
    for (int i=0; i<nvars; i++){
      if (!status[i]) continue;
      rooptrs[i]->setVal(*(ptrs[i]));
    }
    roodset->add(args,v_rooweight);
  }

  cout << "Imported roodset " << newname.Data() << " from TTree " << t->GetName() << endl;
  roodset->Print();

}