Exemplo n.º 1
0
/// Load the specified event
Int_t DDG4EventHandler::ReadEvent(Long64_t event_number)   {
    m_data.clear();
    m_hasEvent = false;
    if ( hasFile() )  {
        if ( event_number >= m_file.second->GetEntries() )  {
            event_number = m_file.second->GetEntries()-1;
            printout(ERROR,"DDG4EventHandler","+++ ReadEvent: Cannot read across End-of-file! Reading last event:%d.",event_number);
        }
        else if ( event_number < 0 )  {
            event_number = 0;
            printout(ERROR,"DDG4EventHandler","+++ nextEvent: Cannot read across Start-of-file! Reading first event:%d.",event_number);
        }

        Int_t nbytes = m_file.second->GetEntry(event_number);
        if ( nbytes >= 0 )   {
            printout(ERROR,"DDG4EventHandler","+++ ReadEvent: Read %d bytes of event data for entry:%d",nbytes,event_number);
            for(Branches::const_iterator i=m_branches.begin(); i != m_branches.end(); ++i)  {
                TBranch* b = (*i).second.first;
                std::vector<void*>* ptr_data = *(std::vector<void*>**)b->GetAddress();
                m_data[b->GetClassName()].push_back(make_pair(b->GetName(),ptr_data->size()));
            }
            m_hasEvent = true;
            return nbytes;
        }
        printout(ERROR,"DDG4EventHandler","+++ ReadEvent: Cannot read event data for entry:%d",event_number);
        throw runtime_error("+++ EventHandler::readEvent: Failed to read event");
    }
    throw runtime_error("+++ EventHandler::readEvent: No file open!");
}
Exemplo n.º 2
0
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;
}
Exemplo n.º 3
0
//-------------------------------------------------------------------------------------------------
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)
 
}
Exemplo n.º 4
0
void qaitsAddMetadata(TTree*tree, Int_t verbose){
  //
  // Set metadata infomation 
  //
  if (tree==NULL) {
    ::Error("qaitsAddMetadata","Start processing. Emtpy tree");
    return;
  }
  ::Info("qaitsAddMetadata","Start processing Tree %s",tree->GetName());
  TObjArray * branches=tree->GetListOfBranches();
  // Clasigication of variables
  //   regular expression to defined automaticaly some variables following naming conventions - used to define classes/Axis/legends 
  //           default description
  //   regular expression used can be tested on site https://regex101.com/
  //           hovewer root (perl)  regular expression looks to be in some cases different - in some case double escape had to be used
  //           e.g to math c.  expression c\\. has to be used
  //   variables
  const TString kineVariableClass[11]={"X", "Y","Z", "Phi", "Theta", "Pt", "QOverPt"};
  const TString kineVariableAxisTitle[11]={"x(cm)", "y(cm)","z(cm)", "#phi", "#Theta", "p_{T}", "q/p_{T}(c/GeV)"};
  const TString kineVariableLegend[11]={"x", "y","z", "#phi", "#Theta", "p_{T}", "q/p_{T}"};
  const TString kineVariableTitle[11]={"x", "y","z", "#phi", "#Theta", "p_{T}", "q/p_{T}"};
  TPRegexp regKineVariables[11];
  regKineVariables[0]=TPRegexp("^x|x$");               // X - varaible begining on X
  regKineVariables[1]=TPRegexp("(^y|^infoy|y$)");      // Y - 
  regKineVariables[2]=TPRegexp("(^z|^infoz|z$)");      // Z
  regKineVariables[3]=TPRegexp("(phi|infophi)");              // phi
  regKineVariables[4]=TPRegexp("(theta|lambda|infolambda)");   // theta
  regKineVariables[5]=TPRegexp("(^pt)");           // pt
  regKineVariables[6]=TPRegexp("qoverpt");          // qoverPt
  //
  //   QA variables  
  const TString qaVariableClass[11]={"Frac", "$","dEdx","ChargeRatio"};
  const TString qaVariableAxisTitle[11]={"Frac","$","dEdx","ChargeRatio"};
  const TString qaVariableLegend[11]={"Frac","$","dEdx","ChargeRatio"};
  const TString qaVariableTitle[11]={"Frac","$","dEdx","ChargeRatio"};
  TPRegexp regQAVariable[11];
  regQAVariable[0]=TPRegexp("frac");              // Frac
  regQAVariable[1]=TPRegexp("(eff[0-9]|effone|^eff)");          // eff layer?
  regQAVariable[2]=TPRegexp("(mpv|dedx)");         // dEdx 
  regQAVariable[3]=TPRegexp("chargeratio");        // ChargeRatio

 
  //
  // statistic
  //
  const TString statClass[10]={"Constrain", "Mean","Delta","Median", "RMS","Pull", "Err","Chi2", "StatInfo[]","FitInfo[]"};
  const TString statAxisTitle[10]={"Constrain", "mean","#Delta","med.", "rms","pull", "#sigma"," #chi2","stat[]","fit[]"};
  const TString statTitle[10]={"Constrain", "mean","#Delta","med.", "rms","pull", "#sigma"," #chi2","stat[]","fit[]" };
  TPRegexp regStat[10];
  regStat[0]=TPRegexp("constrain");        // constrain
  regStat[1]=TPRegexp("^mean");            // mean
  regStat[2]=TPRegexp("^delta");           // delta
  regStat[3]=TPRegexp("^median");          // median variable
  regStat[4]=TPRegexp("(^rms|resolution|sigma)");// rms resolution        
  regStat[5]=TPRegexp("pull");             // pull
  regStat[6]=TPRegexp("err");              // error
  regStat[7]=TPRegexp("chi2");             // chi2
  regStat[8]=TPRegexp("^info");            // stat info array 
  regStat[9]=TPRegexp("^fit");             // fit info  array
  //
  // 
  const TString categoryClass[10]={"Vertex","$1","$1"};
  const TString categoryLegend[10]={"Vertex","$1","$1"};
  const TString categoryTitle[10]={"Vertex","$1","$1"};
  TPRegexp regCategory[10];   // proper parsing of layer numbers to be added
  regCategory[0]=TPRegexp("(vertex|vtx)");             //
  regCategory[1]=TPRegexp("s(p|d|d)d[0-2]?");    // reg.exp match silical layers+number 
  regCategory[2]=TPRegexp("pt[0-9]+");         // pt bin
  


  for (Int_t ibr=0; ibr<branches->GetEntriesFast(); ibr++){
    TBranch * branch = (TBranch*)branches->At(ibr);
    TString matchClass="";   // class match
    TString brClass="";
    TString brAxisTitle="";
    TString brTitle="";
    TString brLegend="";
    //
    TString brNameCase(branches->At(ibr)->GetName());
    brNameCase.ToLower();
    //
    // define met
    brClass="ITS";
    brAxisTitle="";
    // stat
    for (Int_t ivar=0; ivar<11; ivar++) if  (brNameCase.Contains( regStat[ivar])) { 
      brClass+=" "+statClass[ivar];
      brTitle+=statTitle[ivar];
    }
    // kine variables
    for (Int_t ivar=0; ivar<7; ivar++) if  (brNameCase.Contains( regKineVariables[ivar])) {
      brClass+=" "+kineVariableClass[ivar];      
      brAxisTitle+=" "+kineVariableAxisTitle[ivar];
      brTitle+=" "+kineVariableTitle[ivar];
      brLegend+=" "+kineVariableLegend[ivar];
    }
    // QA variables
    for (Int_t ivar=0; ivar<5; ivar++) if  (brNameCase.Contains( regQAVariable[ivar])) {
      if ( qaVariableClass[ivar].Contains("$")==kFALSE){
	brClass+=" "+ qaVariableClass[ivar];
	brLegend+=" "+ qaVariableLegend[ivar];
	brTitle+=" "+ qaVariableTitle[ivar];
      }else{
	TObjArray *amatch=regQAVariable[ivar].MatchS(brNameCase);
	if (amatch){
	  TString match=amatch->At(0)->GetName();
	  brClass+=" "+match;
	  brLegend+=" "+match;
	  brTitle+=" "+match;
	}
      }
    }
    // category
    for (Int_t ivar=0; ivar<3; ivar++) if  (brNameCase.Contains(regCategory[ivar])) {
      if (categoryClass[ivar].Contains("$")==kFALSE){
	brClass+=" "+categoryClass[ivar];
	brLegend+=" "+categoryLegend[ivar];
	brTitle+=" "+categoryTitle[ivar];
      }else{
	TObjArray *amatch=regCategory[ivar].MatchS(brNameCase);
	if (amatch){
	  TString match=amatch->At(0)->GetName();
	  brClass+=" "+match;
	  brLegend+=" "+match;
	  brTitle+=" "+match;
	}
      }
    }
    if (branch!=NULL && branch->GetClassName()!=NULL && strlen(branch->GetClassName())>0){
      brClass+=" Class:";
      brClass+=branch->GetClassName();
    }
    
    //
    TStatToolkit::AddMetadata(tree,TString::Format("%s.Description",branches->At(ibr)->GetName()).Data(),
			      TString::Format("ITS standard QA variables.  Class %s", brClass.Data()).Data());
    TStatToolkit::AddMetadata(tree,TString::Format("%s.class",branches->At(ibr)->GetName()).Data(),brClass.Data());    
    TStatToolkit::AddMetadata(tree,TString::Format("%s.AxisTitle",branches->At(ibr)->GetName()).Data(),brAxisTitle.Data());    
    TStatToolkit::AddMetadata(tree,TString::Format("%s.Title",branches->At(ibr)->GetName()).Data(),brTitle.Data());    
    TStatToolkit::AddMetadata(tree,TString::Format("%s.Legend",branches->At(ibr)->GetName()).Data(),brLegend.Data());    
    if (verbose&4) printf("Class %s: \t%s\n", branches->At(ibr)->GetName(),brClass.Data());
    if (verbose&8) printf("Axis title %s: \t%s\n", branches->At(ibr)->GetName(),brAxisTitle.Data());
    if (verbose&16) printf("Title %s: \t%s\n", branches->At(ibr)->GetName(),brTitle.Data());
    if (verbose&32) printf("Legend %s: \t%s\n", branches->At(ibr)->GetName(),brLegend.Data());

    
  }

  // Fill Based and  custom metadata
  //
  // Index
  TStatToolkit::AddMetadata(tree,"run.class","Base Index");
  TStatToolkit::AddMetadata(tree,"run.Title","run");
  TStatToolkit::AddMetadata(tree,"run.AxisTitle","run");
  //
  TList * mlist = (TList*)(tree->GetUserInfo()->FindObject("metaTable"));
  mlist->Sort();
  if ((verbose&1)>0){
    mlist->Print();
  }
  if ((verbose&2)>0){
    AliTreePlayer::selectMetadata(tree, "[class==\"\"]",0)->Print();
  }
  ::Info("qaitsAddMetadata","End");

}
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;
}