Example #1
0
/// 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);
}
Example #2
0
vector<TString> getAliasNames(TTree *t) {

  vector<TString> v_aliasnames;
  
  TList *t_list =  t->GetListOfAliases();
  for(int i = 0; i < t_list->GetSize(); i++) {
    TString aliasname(t_list->At(i)->GetName());
    TBranch *branch = t->GetBranch(t->GetAlias(aliasname.Data()));
    TString branchname(branch->GetName());
    TString branchtitle(branch->GetTitle());
    if(branchname.BeginsWith("intss") ||
       branchname.BeginsWith("floatss") ||
       branchname.BeginsWith("doubless") ||
       branchname.Contains("LorentzVectorss") ||
       branchname.Contains("timestamp") ) {
      
      cout << "Sorry, I dont know about vector of vectors of objects. " 
	   << "Will be skipping " << aliasname << endl;
      
      continue;
    }

    if(branchname.Contains("TString") ) {
      cout << "Sorry, I don't know how to graphically represent TStrings in only 3 dimensions" 
	   << " Put in a feature request. Will be skipping " << aliasname << endl;
      continue;
    }
    v_aliasnames.push_back(aliasname);
  }

  sort(v_aliasnames.begin(), v_aliasnames.end());
  
  return v_aliasnames;
}
Example #3
0
void OnlineGUI::GetTreeVars() 
{
  // Utility to find all of the variables (leaf's/branches) within a
  // Specified TTree and put them within the treeVars vector.
  treeVars.clear();
  TObjArray *branchList;
  vector <TString> currentTree;

  for(UInt_t i=0; i<fRootTree.size(); i++) {
    currentTree.clear();
    branchList = fRootTree[i]->GetListOfBranches();
    TIter next(branchList);
    TBranch *brc;

    while((brc=(TBranch*)next())!=0) {
      TString found = brc->GetName();
      // Not sure if the line below is so smart...
      currentTree.push_back(found);
    }
    treeVars.push_back(currentTree);
  }
#ifdef DEBUG2
  for(UInt_t iTree=0; iTree<treeVars.size(); iTree++) {
  cout << "In Tree " << iTree << ": " << endl;
    for(UInt_t i=0; i<treeVars[iTree].size(); i++) {
      cout << treeVars[iTree][i] << endl;
    }
  }
#endif
}
void scanDiffRecoTracks(std::string eName, std::string eoName,
			std::string branchReg = "recoTracks_*"){
  gSystem->Load("libFWCoreFWLite");
  gROOT->ProcessLine("AutoLibraryLoader::enable();");
  TChain* e = new TChain("Events");
  e->SetScanField(0);

  e->Add(eName.c_str());

  TChain* eo = new TChain("Events");
  eo->SetScanField(0);

  eo->Add(eoName.c_str());
  e->AddFriend(eo, "eo");

  TRegexp regg(branchReg.c_str(), kTRUE);

  TChain* tc = e ;
  TObjArray* tl = tc->GetListOfBranches();
 
  Int_t nBr = tl->GetSize();
  for (int iB=0;iB<nBr;++iB){
    TBranch* br = (TBranch*)(tl->At(iB)); 
    TString ts(br->GetName()); 
    if(ts.Index(regg)>=0){
      std::cout<<ts.Data()<<std::endl;
      tc->Scan(Form("Sum$(%s.obj.pt()>0):Sum$(eo.%s.obj.pt()>0):Sum$(%s.obj.pt()):Sum$(%s.obj.pt())-Sum$(eo.%s.obj.pt())",
 		    ts.Data(), ts.Data(), ts.Data(), ts.Data(), ts.Data()),"", "");
    }
  } //> e.tecoTracks.recoT0.txt

}
Example #5
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!");
}
void printTreeSummary(TTree *t)
{
   cout << "The TTree \"" << t->GetName() << "\" takes " << sizeOnDisk(t) << " bytes on disk\n";
   size_t n = t->GetListOfBranches()->GetEntries();
   for( size_t i = 0; i < n; ++ i ) {
      TBranch *br =dynamic_cast<TBranch*>(t->GetListOfBranches()->At(i));
      cout << "  It's branch \"" << br->GetName() << "\" takes " << sizeOnDisk(br,true) << " bytes on disk\n";
   }
}
void printBranchSummary(TBranch *br)
{
   cout << "The branch \"" << br->GetName() << "\" takes " << sizeOnDisk(br,true) << " bytes on disk\n";
   size_t n = br->GetListOfBranches()->GetEntries();
   for( size_t i = 0; i < n; ++ i ) {
      TBranch *subbr = dynamic_cast<TBranch*>(br->GetListOfBranches()->At(i));
      cout << "  It's sub-branch \"" << subbr->GetName() << "\" takes " << sizeOnDisk(subbr,true) << " bytes on disk\n";
   }   
}
Example #8
0
 mTree(TTree *t){
     name=t->GetName();
     entries=(long)t->GetEntries();
     totSize=t->GetZipBytes();
     leaves=t->GetListOfBranches()->GetEntriesFast();
     for (int i=0; i<leaves; i++) {
         TBranch* branch = (TBranch*)t->GetListOfBranches()->UncheckedAt(i);
         branch->SetAddress(0);
         // cout <<i<<"\t"<<branch->GetName()<<"\t BS: "<< branch->GetBasketSize()<<"\t size: "<< branch->GetTotalSize()<< "\ttotbytes: "<<branch->GetTotBytes() << endl;
         branchSizes.insert(std::pair<string,long>(branch->GetName(),branch->GetZipBytes())); 
     }
 }
Example #9
0
void getlist(ostream& out, TBranch* branch, int depth=0)
{
  TObjArray* array = branch->GetListOfBranches();
  if ( ! array ) return;
  if ( depth > 10 ) return;

  string name;
  int nitems = array->GetEntries();

  for (int i = 0; i < nitems; i++)
	{
	  TBranch* b = (TBranch*)((*array)[i]);
      if ( ! b ) continue;

      string branchname(b->GetName());
      out << SPACE.substr(0,4*depth) << branchname << endl;
 
      TObjArray* a = b->GetListOfLeaves();
      if ( a )
        {
          int n = a->GetEntries();
          {
              for (int j = 0; j < n; j++)
                {
                  TLeaf* leaf = (TLeaf*)((*a)[j]);
                  int count = 0;
                  int ndata = 0;
                  TLeaf* leafc = leaf->GetLeafCounter(count);
                  if ( ! leafc)
                    ndata = leaf->GetLen();
                  else
                    ndata = leafc->GetMaximum();

                  string leafname(leaf->GetName());
                  out << SPACE.substr(0,4*(depth+1)) 
                      << ndata << " " << leafname << endl;
                }
          }
//           else if ( n == 1 )
//             {
//               TBranch* bc = (TBranch*)((*a)[j]);
//               string leafname(bc->GetName());
//               if ( leafname != branchname )
//               out << SPACE.substr(0,4*(depth+1)) << leafname << endl;
//             }
        }
      getlist(out, b, depth+1);
    }
}
void GAInputTreeData::SetAllBranches(){
    TObjArray* ArrayOfBranches = fTTree->GetListOfBranches();
    Int_t n_branch = ArrayOfBranches->GetEntries();
    cout << "[GAInputTreeData-M]:Loading " << n_branch << " branches from "
        << fTTree->GetName() << endl;
    for(int i_branch=0; i_branch<n_branch; i_branch++){
        TBranch* Branch = (TBranch*)ArrayOfBranches->At(i_branch);
        string branch_name = Branch->GetName();
        TLeaf *leaf = (TLeaf*)Branch->GetListOfLeaves()->At(0);//(branch_name.c_str());
        Int_t n_data = leaf->GetNdata();
        string type_name = leaf->GetTypeName();
        fBranchName.push_back(branch_name);
        fEventDataHolderManager->AddDetector(type_name, branch_name, n_data);
        cout << "[GAInputTreeData-M]:Loading branch " << branch_name
            << " (" << type_name << "[" << n_data << "])" << endl;
    }
}
Example #11
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;
}
Example #12
0
void doSinglePlots(vector <std::string> branches, bool isNew, TTree* tree){

  TH1F* empty = new TH1F("","", 1, 0, 1);

  for (unsigned int i = 0; i < branches.size(); i++){  

    //isLorentz
    TBranch *branch = tree->GetBranch(tree->GetAlias(branches[i].c_str()));
    TString branchname(branch->GetName());
    bool isLorentz = branchname.Contains("p4") || branchname.Contains("MathLorentzVectors"); 

    //Draw
    string alias = branches.at(i);

    //Table of contents
    myfile << "\\subsection*{" << alias << "}\\addcontentsline{toc}{subsection}{" << alias << "}" << endl;

    tree->Draw(Form("%s%s>>hist", branches[i].c_str(), isLorentz ? ".Pt()" : ""), "", "", max_events); 
    TH1F *hist = (TH1F*)gDirectory->Get("hist");
    if(hist==NULL){
      cout << "********** Branch " << branches.at(i) << " exists, but is undrawable for some reason. Skipping this branch" << endl;
      continue; 
    }

    //Scale
    hist->Scale(1./hist->GetEntries());

    //Print plot, update ToC
    vector<TH1F*> hvec;
    hvec.push_back(hist);
    vector<string> titles;
    titles.push_back(isNew ? "New" : "Old");
    dataMCplotMaker(empty, hvec, titles, "", alias, Form("--isLinear --noDivisionLabel --xAxisOverride --outputName hists/uncommon%d", plotNum));
    myfile << "\\begin{figure}[H]" << endl
           << Form("\\includegraphics[width=0.6\\textwidth]{./hists/uncommon%d.pdf}", plotNum) << endl
           << "\\end{figure}" << endl;
    plotNum++;
    delete hist;
  }

  delete empty;
}
////////////////////////////////////////////////////////////
// names -- get the names of the branches and their details
SEXP RootChainManager::names() const {
	
  // Advance to the first entry
  //m_chain->GetEntry(0);
  // Above commented out 20090616 - for TMBTrees this crashed root 
	// on an unresolved symbol for allocator<char>. 
	
  // Get the branches
  TObjArray* branches = m_chain->GetListOfBranches();
	
  // How many?
  unsigned int nBranches = branches->GetEntriesFast();
	
  // Make the R list for returning the list of branch and detail names
  SEXP rBranchList, rBranchListNames;
  PROTECT(rBranchList = NEW_LIST(nBranches));
  PROTECT(rBranchListNames = NEW_CHARACTER(nBranches));
	
  // Loop over the branches in the tree
  for ( unsigned int branchIter = 0; branchIter < nBranches; ++branchIter ) {
		
    // Get the branch
    TBranch* branch = (TBranch*) branches->UncheckedAt(branchIter);
		
    // Save away the name of this branch for use as an attribute
    SET_STRING_ELT(rBranchListNames, branchIter, mkChar(branch->GetName()));
		
    SEXP details = NEW_CHARACTER(1);
    SET_ELEMENT(rBranchList, branchIter, details);
    
    SET_STRING_ELT(details, 0, mkChar( branch->GetTitle() ) );

  } // for over branches
	
  // Set the names attribute
  SET_NAMES(rBranchList, rBranchListNames);
	
  // Release rBranchList and rBranchListNames
  UNPROTECT(2);
	
  return rBranchList;
}
Example #14
0
vector<std::string> getAliasNames(TTree *t){

  //Vector to return results
  vector<std::string> v_aliasnames;
  
  //Skip if no entries
  if (t->GetEntriesFast() == 0) return v_aliasnames;

  //Get list of aliases
  TList *t_list =  t->GetListOfAliases();

  //Loop over list, skip entries that are vectors of vectors, or strings
  for(int i = 0; i < t_list->GetSize(); i++) {
    std::string aliasname(t_list->At(i)->GetName());
    TBranch *branch = t->GetBranch(t->GetAlias(aliasname.c_str()));
    std::string branchname(branch->GetName());
    std::string branchtitle(branch->GetTitle());

    if(branchname.find("intss") == 0 || branchname.find("floatss") == 0 || branchname.find("doubless") == 0 || branchname.find("LorentzVectorss") < branchname.length() || branchname.find("timestamp") < branchname.length() || branchname.find("selectedPatJets") < branchname.length()){
      cout << "Sorry, I dont know about vector of vectors of objects. Will be skipping " << aliasname << endl;
      continue;
    }

    if(branchname.find("std::string") < branchname.length() || branchname.find("TStrings") < branchname.length()){
      cout << "Sorry, I don't know how to graphically represent std::strings in only 3 dimensions." << " Put in a feature request. Will be skipping " << aliasname << endl;
      continue;
    }

    v_aliasnames.push_back(aliasname);
  }

  //Sort alias names alphabetically
  sort(v_aliasnames.begin(), v_aliasnames.end());
  
  //Return aliases names
  return v_aliasnames;
}
Example #15
0
void checkTrgMatch::get_trg_info(TTree* T) 
{
    reset();

    TObjArray *branches = (TObjArray *)T->GetListOfBranches();
    TIter branch_iter(branches); 
    TBranch* branch = 0;
    while ((branch = (TBranch *)branch_iter.Next())) {  
        TString branch_name = branch->GetName();
        for(int it = 0; it<n_trg; it++) {
            if (branch_name.Contains(trg_name[it])){
                if(branch_name.Contains("Prescl")) {
                    T->SetBranchAddress(branch_name.Data(), &prscl[it]);
                } else if(branch_name.Contains("trigObject")) {
                    T->SetBranchAddress(branch_name.Data(), &trg_obj[it]);
                } else {
                    T->SetBranchAddress(branch_name.Data(), &trg[it]);
                } 

                break;
            } 
        }
    }
}
void plotTree(TTree *tree_, std::string whichfit, std::string selectString){

	// Create a map for plotting the pullsummaries:
	std::map < const char*, std::pair <double,double> > pullSummaryMap;
	int nPulls=0;

	TObjArray *l_branches = tree_->GetListOfBranches();
	int nBranches = l_branches->GetEntries();

	TCanvas *c = new TCanvas("c","",960,800);

	std::string treename = tree_->GetName();
	c->SaveAs(Form("%s.pdf[",treename.c_str()));

	for (int iobj=0;iobj<nBranches;iobj++){

		TBranch *br =(TBranch*) l_branches->At(iobj);

		// Draw the normal histogram
		const char* name = br->GetName();
		bool fitPull=false;
		bool plotLH=false;

		TGraph *gr=0;
		double p_mean =0;
		double p_err  =0;

		int nToysInTree = tree_->GetEntries();
		if (doPull && findNuisancePre(name)){
			
			p_mean = bfvals_[name].first;	// toy constrainits thrown about best fit to data
			p_err  = prevals_[name].second; // uncertainties taken from card

			const char* drawInput = Form("(%s-%f)/%f",name,p_mean,p_err);
			tree_->Draw(Form("%s>>%s",drawInput,name),"");
			tree_->Draw(Form("%s>>%s_fail",drawInput,name),selectString.c_str(),"same");
			fitPull = true;
			if (doLH) {
			  gr = graphLH(name,p_err,whichfit);
			  plotLH=true;
			}
			
		}

		else{
			tree_->Draw(Form("%s>>%s",name,name),"");
			tree_->Draw(Form("%s>>%s_fail",name,name),"mu<0","same");
		}
		
		TH1F* bH  = (TH1F*) gROOT->FindObject(Form("%s",name))->Clone();
		TH1F* bHf = (TH1F*) gROOT->FindObject(Form("%s_fail",name))->Clone();
		bHf->SetLineColor(2);
		bH->GetXaxis()->SetTitle(bH->GetTitle());
		bH->GetYaxis()->SetTitle(Form("no toys (%d total)",nToysInTree));
		bH->GetYaxis()->SetTitleOffset(1.32);
		
		bH->SetTitle("");	

		if (fitPull) bH->Fit("gaus");
	
		c->Clear();
		TPad pad1("t1","",0.01,0.02,0.59,0.98);
		TPad pad2("t2","",0.59,0.04,0.98,0.62);
		TPad pad3("t3","",0.59,0.64,0.98,0.90);

		pad1.SetNumber(1); pad2.SetNumber(2); pad3.SetNumber(3);
		pad1.Draw(); pad2.Draw();pad3.Draw();
		pad2.SetGrid(true);

		c->cd(1); bH->Draw(); bHf->Draw("same");
		TLatex *titletext = new TLatex();titletext->SetNDC();titletext->SetTextSize(0.04); titletext->DrawLatex(0.1,0.95,name);
		TLegend *legend = new TLegend(0.6,0.8,0.9,0.89);
		legend->SetFillColor(0);
		legend->AddEntry(bH,"All Toys","L");
		legend->AddEntry(bHf,selectString.c_str(),"L");
		legend->Draw();

		if (doPull && plotLH) {
			c->cd(2); gr->Draw("ALP");
		}
		if (fitPull){
			c->cd(3);
			TLatex *tlatex = new TLatex(); tlatex->SetNDC(); tlatex->SetTextSize(0.12);
			tlatex->DrawLatex(0.15,0.75,Form("Mean    : %.3f #pm %.3f",bH->GetFunction("gaus")->GetParameter(1),bH->GetFunction("gaus")->GetParError(1)));
			tlatex->DrawLatex(0.15,0.60,Form("Sigma   : %.3f #pm %.3f",bH->GetFunction("gaus")->GetParameter(2),bH->GetFunction("gaus")->GetParError(2)));
			tlatex->DrawLatex(0.15,0.35,Form("Pre-fit : %.3f ",prevals_[name].first));
			tlatex->DrawLatex(0.15,0.2,Form("Best-fit (B)  : %.3f ",p_mean));
			tlatex->DrawLatex(0.15,0.05,Form("Best-fit (S+B): %.3f ",bfvals_sb_[name].first));
			
			pullSummaryMap[name]=std::make_pair<double,double>(bH->GetFunction("gaus")->GetParameter(1),bH->GetFunction("gaus")->GetParameter(2));
			nPulls++;

		}

		c->SaveAs(Form("%s.pdf",treename.c_str()));
	}
	
	if (doPull && nPulls>0){
	   
	    int nRemainingPulls = nPulls;
	    TCanvas *hc = new TCanvas("hc","",3000,2000); hc->SetGrid(0);
	    std::map < const char*, std::pair <double,double> >::iterator pull_it = pullSummaryMap.begin();
	    std::map < const char*, std::pair <double,double> >::iterator pull_end = pullSummaryMap.end();

	    while (nRemainingPulls > 0){

		int nThisPulls = min(15,nRemainingPulls);

		TH1F pullSummaryHist("pullSummary","",nThisPulls,0,nThisPulls);
		for (int pi=1;pull_it!=pull_end && pi<=nThisPulls ;pull_it++,pi++){
			pullSummaryHist.GetXaxis()->SetBinLabel(pi,(*pull_it).first);
			pullSummaryHist.SetBinContent(pi,((*pull_it).second).first);
			pullSummaryHist.SetBinError(pi,((*pull_it).second).second);
			nRemainingPulls--;
		}		

		pullSummaryHist.SetMarkerStyle(21);pullSummaryHist.SetMarkerSize(1.5);pullSummaryHist.SetMarkerColor(2);pullSummaryHist.SetLabelSize(0.018);
		pullSummaryHist.GetYaxis()->SetRangeUser(-3,3);pullSummaryHist.GetYaxis()->SetTitle("pull summary");pullSummaryHist.Draw("E1");
		hc->SaveAs(Form("%s.pdf",treename.c_str()));
	   }

	    delete hc;
	}

	c->SaveAs(Form("%s.pdf]",treename.c_str()));

	delete c;
	return;


}
Example #17
0
int plotAll(){

  TFile *file = new TFile("/hadoop/cms/store/group/snt/phys14/TTJets_MSDecaysCKM_central_Tune4C_13TeV-madgraph-tauola_Phys14DR-PU20bx25_PHYS14_25_V1-v1/V07-02-08/merged_ntuple_4.root");
  TTree *tree = (TTree*)file->Get("Events");

  int nEntries = tree->GetEntries();

  TList *t_list = tree->GetListOfAliases();

  for(int i = 0; i < t_list->GetSize(); i++) {
    TString aliasname(t_list->At(i)->GetName());
    cout << aliasname.Data() << endl;
    TString command = aliasname;

    //Support Lorentz Vectors
    TBranch *branch = tree->GetBranch(tree->GetAlias(aliasname.Data()));
    TString branchname(branch->GetName());
    if( branchname.Contains("LorentzVector") ) {
      command.Append(".Pt()");
    }
 
    //Don't support vectors of vectors
    if(branchname.BeginsWith("intss") || branchname.BeginsWith("floatss") || branchname.BeginsWith("doubless") || branchname.Contains("LorentzVectorss") || branchname.Contains("timestamp") ){
      cout << "Sorry, I dont support vector of vectors of objects, will be skipping " << aliasname << endl;
      continue;
    }

    //Don't support TStrings
    if(branchname.Contains("TString") ) {
      cout << "Sorry, I dont support strings, will be skipping " << aliasname << endl;
      continue;
    }

    TString histname = "hist_" + aliasname + ".pdf";
    TH1F* null = new TH1F("","",1,0,1);
    command.Append(">>hist");
    tree->Draw(command.Data(), (aliasname)+"!=-9999 &&"+(aliasname)+"!=-999");
    TH1F *hist = (TH1F*)gDirectory->Get("hist");
    if (hist->Integral() == 0) tree->Draw(command.Data());
    hist = (TH1F*)gDirectory->Get("hist");
    vector <TH1F*> hists; 
    hists.push_back(hist);
    vector <string> titles;
    titles.push_back("");
  
    //Overflow and Underflow
    hist->SetBinContent(1, hist->GetBinContent(1)+hist->GetBinContent(0));
    hist->SetBinContent(hist->GetNbinsX(), hist->GetBinContent(hist->GetNbinsX())+hist->GetBinContent(hist->GetNbinsX()+1));

    if (hist->GetXaxis()->GetXmax() == hist->GetXaxis()->GetXmin()){
      ofstream myfile;
      myfile.open("names.txt", ios_base::app);
      myfile << aliasname.Data() << "\n"; 
      myfile.close();  
    }

    float max = hist->GetMaximum()*100;

    string subtitle = aliasname.Data();
    string histname2 = histname.Data(); 

    dataMCplotMaker(null, hists, titles, subtitle, "CMS3 4.02 Validation", Form("--outputName %s --noFill --noLegend --setMaximum %f --energy 13 --lumi 0 --xAxisLabel %s --noXaxisUnit --noDivisionLabel", subtitle.c_str(), max, histname2.c_str())); 

  }
 
  system("mkdir plots");
  system("mv *.pdf plots/"); 
  system("gs -sDEVICE=pdfwrite     -dNOPAUSE -dBATCH -dSAFER     -sOutputFile=merged.pdf  plots/*pdf"); 

  return 0;

}
Example #18
0
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;
}
Example #19
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)
 
}
Example #20
0
void compareNtuples(TString file1, TString file2, bool doNotSaveSameHistos="true", bool drawWithErrors="true") {
  
  //TDirectory *rootdir = gDirectory->GetDirectory("Rint:");
  
  TFile *f1 = TFile::Open(file1.Data(), "READ");
  if(f1 == NULL) {
    cout << "Exiting" << endl;
    return;
  }
  TTree *tree1 = (TTree*)f1->Get("Events");
  if(tree1 == NULL) {
    cout << "Can't find the tree \"Events\" in " << file1 << " Exiting " << endl;
    return;
  }

  TFile *f2 = TFile::Open(file2.Data(), "READ");
  if(f2 == NULL) {
    cout << "Exiting" << endl;
    return;
  }
  TTree *tree2 = (TTree*)f2->Get("Events");
  if(tree2 == NULL) {
    cout << "Can't find the tree \"Events\" in " << file2 << " Exiting " << endl;
    return;
  }

  TObjArray *objArray= file1.Tokenize("/");
  TString fname1 = "";
  TString fname2 = "";
  for(unsigned int i = 0; i < objArray->GetSize(); i++) {
    if(fname1 != "")
      continue;
    cout << TString(objArray->At(i)->GetName()) << endl;
    if(TString(objArray->At(i)->GetName()).Contains("root")) {
      fname1 = TString(objArray->At(i)->GetName());
      continue;
    }
  }
  objArray = file2.Tokenize("/"); 
  for(unsigned int i = 0; i < objArray->GetSize(); i++) {
    if(fname2 != "")
      continue;
    cout << TString(objArray->At(i)->GetName()) << endl;
    if(TString(objArray->At(i)->GetName()).Contains("root")) {
      fname2 = TString(objArray->At(i)->GetName());
      continue;
    }
  }
  
  vector<TString> t1_aliasnames = getAliasNames(tree1);
  vector<TString> t2_aliasnames = getAliasNames(tree2);
  vector<TString> v_commonBranches;
  vector<TString> v1_notCommonBranches;
  vector<TString> v2_notCommonBranches;
  
  for(vector<TString>::iterator it = t1_aliasnames.begin(); 
      it != t1_aliasnames.end(); it++) {
    
    if(find(t2_aliasnames.begin(), t2_aliasnames.end(), *it) != t2_aliasnames.end())
      v_commonBranches.push_back(*it);
  }

  //figure out which branches are not common so you can output their names 
  //and draw them last
  v1_notCommonBranches = getUncommonBranches(t1_aliasnames, v_commonBranches);
  v2_notCommonBranches = getUncommonBranches(t2_aliasnames, v_commonBranches);

  TCanvas *c1 = new TCanvas();
  

  for(unsigned int i = 0; i < v1_notCommonBranches.size(); i++) {
    
    TString alias = v1_notCommonBranches.at(i);
    cout << "Branch: " << alias << " was found in " 
	 << file1 << " but not in " << file2 << endl;
    TString histname = "h1_"+(alias);
    TString command  = (alias) + ">>" + histname;
    TBranch *branch = tree1->GetBranch(tree1->GetAlias(alias));
    TString branchname(branch->GetName());
    
    if( branchname.Contains("LorentzVector") ) {
      histname = "h1_"+ alias + "_pt";
      command  = alias + ".Pt()>>" + histname;      
    }
    tree1->Draw(command.Data());
    TH1F *h1 = (TH1F*)c1->GetPrimitive(histname.Data());

    if(h1==NULL) {
      cout << "********** Branch " << v1_notCommonBranches.at(i) 
	   << " in file " << file1 << "exists, but is undrawable for some reason. " 
	   << "Skipping this branch" << endl;
      c1->Clear();
      continue; 
    }
    c1->Clear();

    if(drawWithErrors)
      h1->TH1F::Sumw2();


    h1->Scale(1./h1->GetEntries());
    
    if(!drawWithErrors) {
	h1->SetLineColor(0);
	h1->SetMarkerSize(1.1);
	h1->SetMarkerStyle(3);
    } else {
	h1->SetMarkerSize(1.3);
	h1->SetMarkerStyle(3);
    }
    TString histtitle = alias + ", " + fname1;
    h1->SetTitle(histtitle.Data());
    h1->Draw();
    c1->SaveAs("diff.eps(");
  }



  for(unsigned int i = 0; i < v2_notCommonBranches.size(); i++) {
    
    TString alias = v2_notCommonBranches.at(i);
    cout << "Branch: " << alias << " was found in " 
	 << file1 << " but not in " << file2 << endl;
    TString histname = "h2_"+(alias);
    TString command  = (alias) + ">>" + histname;
    TBranch *branch = tree2->GetBranch(tree2->GetAlias(alias));
    TString branchname(branch->GetName());
    
    if( branchname.Contains("LorentzVector") ) {
      histname = "h2_"+ alias + "_pt";
      command  = alias + ".Pt()>>" + histname;      
    }
    tree2->Draw(command.Data());
    TH1F *h2 = (TH1F*)c1->GetPrimitive(histname.Data());
    if(h2==NULL) {
      cout << "********** Branch " << v2_notCommonBranches.at(i) 
	   << " in file " << file2 << "exists, but is undrawable for some reason. " 
	   << "Skipping this branch" << endl;
      c1->Clear();
      continue; 
    }
    c1->Clear();

    if(drawWithErrors)
      h2->TH1F::Sumw2();


    h2->Scale(1./h2->GetEntries());
    
    if(!drawWithErrors) {
      h2->SetLineColor(kRed);
      h2->SetLineStyle(7);
    } else {
      h2->SetMarkerSize(1.1);
      h2->SetMarkerStyle(8);
      h2->SetMarkerColor(kRed);
    }
    TString histtitle = alias + ", " + fname2;
    h2->SetTitle(histtitle.Data());
    h2->Draw();
    c1->SaveAs("diff.eps(");
  }




  for(unsigned int i =  0; i < v_commonBranches.size(); i++) {
        
    TString alias = v_commonBranches.at(i);
    cout << "Comparing Branch: " << alias << endl;
    TString hist1name = "h1_"+(alias);
    TString hist2name = "h2_"+(alias);
    TString command1 = (alias)+">>"+hist1name;
    TString command2 = (alias)+">>"+hist2name;
    TBranch *branch = tree2->GetBranch(tree2->GetAlias(alias));
    TString branchname(branch->GetName());
        
    if(branchname.Contains("p4") ) {
      hist1name = "h1_"+ alias + "_Pt";
      hist2name = "h2_"+ alias + "_Pt";
      command1 = alias + ".Pt()>>"+hist1name;
      command2 = alias + ".Pt()>>"+hist2name;
    }
    
    tree1->Draw(command1.Data());
    TH1F *h1 = (TH1F*)c1->GetPrimitive(hist1name.Data());
    if(h1==NULL) {
      cout << "********** Branch " << v_commonBranches.at(i) 
	   << " in file " << file1 << "exists, but is undrawable for some reason. " 
	   << "Skipping this branch" << endl;
      c1->Clear();
      continue; 
    }
    //set the Overflow at the last bin
    tree2->Draw(command2.Data());
    TH1F *h2 = (TH1F*)c1->GetPrimitive(hist2name.Data());
    if(h2==NULL) {
      cout << "********** Branch " << v_commonBranches.at(i) 
	   << " in file " << file2 << "exists, but is undrawable for some reason. " 
	   << "Skipping this branch" << endl;
      c1->Clear();
      continue;  
    }
    c1->Clear();

    if(areHistosTheSame(h1, h2) && doNotSaveSameHistos)
      continue;
    
    if(drawWithErrors) {
      h1->TH1F::Sumw2();
      h2->TH1F::Sumw2();
    }


    h1->Scale(1./h1->GetEntries());
    h2->Scale(1./h2->GetEntries());


    if(h1->GetNbinsX() != h2->GetNbinsX() ) {
      cout << "Branch " << v_commonBranches.at(i) << " not the same between the 2 files" 
	   << ". They will be drawn side by side" << endl;
      
      c1->Divide(2,1);
      h2->SetTitle(fname2);
      h1->SetTitle(fname1);
      if(!drawWithErrors) {
	h1->SetLineColor(0);
	h1->SetMarkerSize(1.1);
	h1->SetMarkerStyle(3);
	h2->SetLineColor(kRed);
	h2->SetLineStyle(7);
	c1->cd(1);
	h1->Draw();
	c1->cd(2);
	h2->Draw();
      } else {
	h1->SetMarkerSize(1.3);
	h1->SetMarkerStyle(3);
	h2->SetMarkerSize(1.1);
	h2->SetMarkerStyle(8);
	h2->SetMarkerColor(kRed);
	c1->cd(1);
	h1->Draw("e");
	c1->cd(2);
	h2->Draw("e");
      }
            
      if(i < v_commonBranches.size() - 1)
	c1->SaveAs("diff.eps(");
      else {
	cout << "done" << endl;
	c1->SaveAs("diff.eps)");
      }
      continue;
    }       
            
    if(h1->GetMaximum() >= h2->GetMaximum()) {
      
      double max = 1.1*h1->GetMaximum();
      h1->SetMaximum(max);
      h2->SetMaximum(max);
      
      if(!drawWithErrors) {
	h1->SetLineColor(0);
	h1->SetMarkerSize(1.1);
	h1->SetMarkerStyle(3);
	h2->SetLineColor(kRed);
	h2->SetLineStyle(7);
	h2->Draw();
	h1->Draw("samesh*");
      } else {
	h1->SetMarkerSize(1.3);
	h1->SetMarkerStyle(3);
	h2->SetMarkerSize(1.1);
	h2->SetMarkerStyle(8);
	h2->SetMarkerColor(kRed);
	h2->Draw("e");
	h1->Draw("samese");
      }
      
    } else {
      double max = 1.1*h2->GetMaximum();
      
      h1->SetMaximum(max);
      h2->SetMaximum(max);
      
       if(!drawWithErrors) {
	h1->SetLineColor(0);
	h1->SetMarkerSize(1.1);
	h1->SetMarkerStyle(3);
	h2->SetLineColor(kRed);
	h2->SetLineStyle(7);
	TString histtitle = fname1+" (black) " + fname2 + " (red)";
	h2->SetTitle(histtitle.Data());
	h1->SetTitle(histtitle.Data());
	h1->Draw();
	h2->Draw("samesh*");
      } else {
	h1->SetMarkerSize(1.3);
	h1->SetMarkerStyle(3);
	h2->SetMarkerSize(1.1);
	h2->SetMarkerStyle(8);
	h2->SetMarkerColor(kRed);
	TString histtitle = fname1+" (black) " + fname2 + " (red)";
	h2->SetTitle(histtitle.Data());
	h1->SetTitle(histtitle.Data());
	h1->Draw("e");
	h2->Draw("samese");
      }


    }
        
    if(i < v_commonBranches.size() - 1)
      c1->SaveAs("diff.eps(");
    else {
      cout << "done" << endl;
      c1->Clear();
      c1->SaveAs("diff.eps)");
    }
    
  }//for loop
    

  cout << c1->GetListOfPrimitives()->GetSize() << endl;

    
}
bool TreeReader::Initialize(vector <string> br, string opt)
{
	if(!init)
	{
	    if( !fChain )
		{
		        cout << endl;
			cout << "No tree to initialize" << endl;
			cout << endl;
			return false;
		}

		TObjArray *fileElements = fChain->GetListOfFiles();
		if( !fileElements || ( fileElements->GetEntries() == 0 ))
		{
		        cout << endl;
			cout << "No file(s) to initialize" << endl;
			cout << endl;
			return false;
		}
	}

	varList.clear();

	TObjArray* branches = fChain->GetListOfBranches();
	int nBranches = branches->GetEntries();

	for (int i = 0; i < nBranches; ++i)
	{
		TBranch* branch = (TBranch*)branches->At(i);
		string brname = branch->GetName();
		TLeaf* leaf = branch->GetLeaf(branch->GetName());

		if ( leaf == 0 )  // leaf name is different from branch name
		{
			TObjArray* leafs = branch->GetListOfLeaves();
			leaf = (TLeaf*)leafs->At(0);
		}

		string curtype = leaf->GetTypeName();
        int id = TypeDB::getType(curtype.c_str());
		int arreysize = 1;
		string title = leaf->GetTitle();
        //cout << curtype << "   " << title << endl;

		// Find out whether we have array by inspecting leaf title
		if ( title.find("[")!=std::string::npos )
		{
			TLeaf * nelem = leaf->GetLeafCounter(arreysize);
			if(arreysize == 1 && nelem != NULL) arreysize = nelem->GetMaximum() + 1; //search for maximum value of the lenght
		}


		if(id >= 0)
		{
			bool addVar = true;
			if(br.size()>0)
			{
				addVar = false;
				for(unsigned b = 0; b < br.size(); b++)
				{
					if(opt == "names" || opt == "except")
					{
						if(br[b] == brname) { addVar = true; break;}
					}
					else if(opt.find("contains")!=string::npos)
					{
						if((string(brname)).find(br[b])!=string::npos) { addVar = true; break;}
					}
					else if(opt.find("except")==string::npos) cout << "Option " << opt << " not found" << endl;
				}

				if(opt.find("except")!=string::npos) addVar = !addVar;
			}

			if(addVar)
			{
				variable * tmpVar = new variable(id,arreysize);

				tmpVar->name = leaf->GetName();
				tmpVar->bname = branch->GetName();
				tmpVar->title = title;

				varList.push_back(tmpVar);
				fChain->SetBranchAddress(tmpVar->bname,tmpVar->value.address);
			}
		}
		else
		{
			cout << curtype << ": type not found" << endl;
			exit(1);
			return false;
		}
	}

	init = true;
	continueSorting = true;
	if(pmode=="v") cout << endl << "Set up " << varList.size() << " / " << nBranches << " branches" << endl;

	return true;
}
void classesFromBranch(TBranch *tbranch, TClass *tclass, std::vector<ClassStructure> &classes, int prefix, std::set<std::string> &includes) {
  std::string className = tclass->GetName();

  if (className == std::string("TObject"))
    includes.insert("#include \"TObject.h\"");
  else if (className == std::string("TRef"))
    includes.insert("#include \"TRef.h\"");
  else if (className == std::string("TRefArray"))
    includes.insert("#include \"TRefArray.h\"");
  else if (className == std::string("TH1"))
    includes.insert("#include \"TH1.h\"");
  else if (className == std::string("TBits")) {
    includes.insert("#include \"TBits.h\"");
  }
  else {
    bool classSeen = false;
    for (int i = 0;  i < classes.size();  i++)
      if (classes[i].fullName == className)
        classSeen = true;

    if (!classSeen) {
      TVirtualStreamerInfo *tVirtualStreamerInfo = tclass->GetStreamerInfo();
      int version = tVirtualStreamerInfo->GetClassVersion();

      ClassStructure classStructure(tclass, version);

      if (tVirtualStreamerInfo->GetElements()->GetEntries() == 1  &&
          ((TStreamerElement*)(tVirtualStreamerInfo->GetElements()->First()))->IsBase()  &&
          std::string(tVirtualStreamerInfo->GetElements()->First()->GetName()) == std::string("TObjArray")) {

        TVirtualStreamerInfo *substreamer = ((TBranchElement*)tbranch)->GetInfo();

        if (std::string(substreamer->GetName()) == std::string("TClonesArray")) {
          ROOT::Internal::TTreeGeneratorBase ttreeGenerator(tbranch->GetTree(), "");
          TString className = ttreeGenerator.GetContainedClassName((TBranchElement*)tbranch, (TStreamerElement*)(substreamer->GetElements()->First()), true);
          classesFromBranch(tbranch, TClass::GetClass(className), classes, prefix + std::string(tbranch->GetName()).size() + 1, includes);
        }
      }

      TIter elements = tVirtualStreamerInfo->GetElements();
      for (TStreamerElement *tStreamerElement = (TStreamerElement*)elements.Next();  tStreamerElement != nullptr;  tStreamerElement = (TStreamerElement*)elements.Next()) {
        std::string streamerName = tStreamerElement->GetName();

        if (tStreamerElement->IsBase()) {
          TClass *elementClass = tStreamerElement->GetClassPointer();
          std::string type = elementClass->GetName();

          if (type == std::string("TObject")) {
            classStructure.bases.push_back(type);
            includes.insert(std::string("#include \"") + type + std::string(".h\""));
          }
        }

        else {
          TIter listOfBranches = tbranch->GetListOfBranches();
          TBranch *subbranch;
          for (subbranch = (TBranch*)listOfBranches.Next();  subbranch != nullptr;  subbranch = (TBranch*)listOfBranches.Next()) {
            std::string branchName = subbranch->GetName();
            branchName = branchName.substr(prefix, std::string::npos);
            int firstDot = branchName.find('.');
            int firstBracket = branchName.find('[');
            if (firstDot != std::string::npos  &&  firstBracket != std::string::npos)
              branchName = branchName.substr(0, firstDot < firstBracket ? firstDot : firstBracket);
            else if (firstDot != std::string::npos)
              branchName = branchName.substr(0, firstDot);
            else if (firstBracket != std::string::npos)
              branchName = branchName.substr(0, firstBracket);
            if (branchName == streamerName)
              break;
          }
          if (subbranch == nullptr)
            continue;

          std::string branchName = subbranch->GetName();

          std::string variable = tStreamerElement->GetName();
          std::string variableWithArray = subbranch->GetName();
          variableWithArray = variableWithArray.substr(prefix, std::string::npos);
          variableWithArray = variableWithArray.substr(0, variableWithArray.find('.'));

          std::string comment = tStreamerElement->GetTitle();

          std::string type;
          Bool_t pointer = false;
          switch (tStreamerElement->GetType()) {

          case TVirtualStreamerInfo::kOffsetP + TVirtualStreamerInfo::kBool:
            pointer = true;
          case TVirtualStreamerInfo::kOffsetL + TVirtualStreamerInfo::kBool:
          case TVirtualStreamerInfo::kBool:
            type = "Bool_t";
            break;

          case TVirtualStreamerInfo::kOffsetP + TVirtualStreamerInfo::kChar:
            pointer = true;
          case TVirtualStreamerInfo::kOffsetL + TVirtualStreamerInfo::kChar:
          case TVirtualStreamerInfo::kChar:
            type = "Char_t";
            break;

          case TVirtualStreamerInfo::kOffsetP + TVirtualStreamerInfo::kShort:
            pointer = true;
          case TVirtualStreamerInfo::kOffsetL + TVirtualStreamerInfo::kShort:
          case TVirtualStreamerInfo::kShort:
            type = "Short_t";
            break;

          case TVirtualStreamerInfo::kOffsetP + TVirtualStreamerInfo::kInt:
            pointer = true;
          case TVirtualStreamerInfo::kOffsetL + TVirtualStreamerInfo::kInt:
          case TVirtualStreamerInfo::kInt:
            type = "Int_t";
            break;

          case TVirtualStreamerInfo::kOffsetP + TVirtualStreamerInfo::kLong:
            pointer = true;
          case TVirtualStreamerInfo::kOffsetL + TVirtualStreamerInfo::kLong:
          case TVirtualStreamerInfo::kLong:
            type = "Long_t";
            break;

          case TVirtualStreamerInfo::kOffsetP + TVirtualStreamerInfo::kLong64:
            pointer = true;
          case TVirtualStreamerInfo::kOffsetL + TVirtualStreamerInfo::kLong64:
          case TVirtualStreamerInfo::kLong64:
            type = "Long64_t";
            break;

          case TVirtualStreamerInfo::kOffsetP + TVirtualStreamerInfo::kFloat:
            pointer = true;
          case TVirtualStreamerInfo::kOffsetL + TVirtualStreamerInfo::kFloat:
          case TVirtualStreamerInfo::kFloat:
            type = "Float_t";
            break;

          case TVirtualStreamerInfo::kOffsetP + TVirtualStreamerInfo::kFloat16:
            pointer = true;
          case TVirtualStreamerInfo::kOffsetL + TVirtualStreamerInfo::kFloat16:
          case TVirtualStreamerInfo::kFloat16:
            type = "Float16_t";
            break;

          case TVirtualStreamerInfo::kOffsetP + TVirtualStreamerInfo::kDouble:
            pointer = true;
          case TVirtualStreamerInfo::kOffsetL + TVirtualStreamerInfo::kDouble:
          case TVirtualStreamerInfo::kDouble:
            type = "Double_t";
            break;

          case TVirtualStreamerInfo::kOffsetP + TVirtualStreamerInfo::kDouble32:
            pointer = true;
          case TVirtualStreamerInfo::kOffsetL + TVirtualStreamerInfo::kDouble32:
          case TVirtualStreamerInfo::kDouble32:
            type = "Double32_t";
            break;

          case TVirtualStreamerInfo::kOffsetP + TVirtualStreamerInfo::kUChar:
            pointer = true;
          case TVirtualStreamerInfo::kOffsetL + TVirtualStreamerInfo::kUChar:
          case TVirtualStreamerInfo::kUChar:
            type = "UChar_t";
            break;

          case TVirtualStreamerInfo::kOffsetP + TVirtualStreamerInfo::kUShort:
            pointer = true;
          case TVirtualStreamerInfo::kOffsetL + TVirtualStreamerInfo::kUShort:
          case TVirtualStreamerInfo::kUShort:
            type = "UShort_t";
            break;

          case TVirtualStreamerInfo::kOffsetP + TVirtualStreamerInfo::kUInt:
            pointer = true;
          case TVirtualStreamerInfo::kOffsetL + TVirtualStreamerInfo::kUInt:
          case TVirtualStreamerInfo::kUInt:
            type = "UInt_t";
            break;

          case TVirtualStreamerInfo::kOffsetP + TVirtualStreamerInfo::kULong:
            pointer = true;
          case TVirtualStreamerInfo::kOffsetL + TVirtualStreamerInfo::kULong:
          case TVirtualStreamerInfo::kULong:
            type = "ULong_t";
            break;

          case TVirtualStreamerInfo::kOffsetP + TVirtualStreamerInfo::kULong64:
            pointer = true;
          case TVirtualStreamerInfo::kOffsetL + TVirtualStreamerInfo::kULong64:
          case TVirtualStreamerInfo::kULong64:
            type = "ULong64_t";
            break;

          case TVirtualStreamerInfo::kOffsetP + TVirtualStreamerInfo::kBits:
            pointer = true;
          case TVirtualStreamerInfo::kOffsetL + TVirtualStreamerInfo::kBits:
          case TVirtualStreamerInfo::kBits:
            type = "UInt_t";
            break;

          case TVirtualStreamerInfo::kCharStar:
            type = "Char_t*";
            break;

          case TVirtualStreamerInfo::kCounter:
            type = "Int_t";
            break;

          case TVirtualStreamerInfo::kOffsetL + TVirtualStreamerInfo::kObjectp:
          case TVirtualStreamerInfo::kOffsetL + TVirtualStreamerInfo::kObjectP:
          case TVirtualStreamerInfo::kObjectp:
          case TVirtualStreamerInfo::kObjectP:
          case TVirtualStreamerInfo::kAnyp:
          case TVirtualStreamerInfo::kAnyP:
          case TVirtualStreamerInfo::kSTL + TVirtualStreamerInfo::kObjectp:
          case TVirtualStreamerInfo::kSTL + TVirtualStreamerInfo::kObjectP:
            pointer = true;

          case TVirtualStreamerInfo::kOffsetL + TVirtualStreamerInfo::kObject:
          case TVirtualStreamerInfo::kObject:
          case TVirtualStreamerInfo::kTString:
          case TVirtualStreamerInfo::kTNamed:
          case TVirtualStreamerInfo::kTObject:
          case TVirtualStreamerInfo::kAny:
          case TVirtualStreamerInfo::kBase:
          case TVirtualStreamerInfo::kSTL:
            TClass *elementClass = tStreamerElement->GetClassPointer();
            type = elementClass->GetName();

            if (elementClass == TClonesArray::Class()) {
              ROOT::Internal::TTreeGeneratorBase ttreeGenerator(tbranch->GetTree(), "");
              TString className = ttreeGenerator.GetContainedClassName((TBranchElement*)subbranch, tStreamerElement, pointer);
              if (className != nullptr) {
                TClass *otherClass = TClass::GetClass(className);
                classesFromBranch(subbranch, otherClass, classes, variableWithArray.size() + 1, includes);
                includes.insert("#include \"TClonesArray.h\"");
              }
            }

            else if (elementClass->GetCollectionProxy() != nullptr  &&  elementClass->GetCollectionProxy()->GetValueClass() != nullptr) {
              TClass *otherClass = elementClass->GetCollectionProxy()->GetValueClass();
              classesFromBranch(subbranch, otherClass, classes, variableWithArray.size() + 1, includes);
              includes.insert(std::string("#include <") + type.substr(0, type.find('<')) + std::string(">"));
            }

            else
              classesFromBranch(subbranch, elementClass, classes, variableWithArray.size() + 1, includes);

          }
          classStructure.members.push_back(MemberStructure(type, pointer, variable, variableWithArray, comment));
        }
      }

      if (!classStructure.members.empty())
        classes.push_back(classStructure);
    }
  }
}
void plotTree(TTree *tree_, std::string whichfit, std::string selectString){

	// Create a map for plotting the pullsummaries:
	std::map < const char*, std::pair <double,double> > pullSummaryMap;
	int nPulls=0;

	TObjArray *l_branches = tree_->GetListOfBranches();
	int nBranches = l_branches->GetEntries();

	gStyle->SetPadTopMargin(0.01);

	TCanvas *c = new TCanvas("c","",960,800);

	std::string treename = tree_->GetName();
	c->SaveAs(Form("%s.pdf[",treename.c_str()));
	// File to store plots in 
	TFile *fOut = new TFile(Form("%s.root",treename.c_str()),"RECREATE");

	for (int iobj=0;iobj<nBranches;iobj++){

		TBranch *br =(TBranch*) l_branches->At(iobj);

		// Draw the normal histogram
		const char* name = br->GetName();

                // names with - are not allowed
                string namestr(name);
                if(namestr.find("-")!=string::npos) {
                  std::cout << "Variable " << name << " contains a bad character: -. Skipping. " << std::endl;
                  continue;
                }
		bool fitPull=false;
		bool fitPullf=false;

		bool plotLH=false;

		TGraph *gr=NULL;
		double p_mean =0;
		double p_err  =0;

		int nToysInTree = tree_->GetEntries();
		// Find out if paramter is fitted value or constraint term
		bool isFitted = findNuisancePre(name);
		if (doPull && isFitted){
			
			p_mean = bfvals_[name].first;	// toy constrainits thrown about best fit to data
			if(namestr.find("n_exp")==string::npos) p_err  = prevals_[name].second; // uncertainties taken from card
			std::cout << "******* "<< name << " *******"<<std::endl;
			std::cout << p_mean <<  " " << p_err << std::endl;
			std::cout << "******************************" <<std::endl;

			const char* drawInput;
                        // if the parameter is a normalization, the error is not available. Do the residual instead of the pull
                        if(namestr.find("n_exp")!=string::npos) drawInput = Form("(%s-%f)/%f",name,p_mean,p_mean);
                        else drawInput = Form("(%s-%f)/%f",name,p_mean,p_err);
			tree_->Draw(Form("%s>>%s",drawInput,name),"");
			tree_->Draw(Form("%s>>%s_fail",drawInput,name),selectString.c_str(),"same");
			fitPull  = true;
			fitPullf = true;
			if (doLH) {
			  gr = graphLH(name,p_err,whichfit);
			  if (gr) plotLH=true;
			}
			
		}

		else{
			tree_->Draw(Form("%s>>%s",name,name),"");
			tree_->Draw(Form("%s>>%s_fail",name,name),selectString.c_str(),"same");
		}
		

		TH1F* bH  = (TH1F*) gROOT->FindObject(Form("%s",name))->Clone();
		TH1F* bHf = (TH1F*) gROOT->FindObject(Form("%s_fail",name))->Clone();
		bHf->SetLineColor(2);
		bH->GetXaxis()->SetTitle(bH->GetTitle());
		bH->GetYaxis()->SetTitle(Form("no toys (%d total)",nToysInTree));
		bH->GetYaxis()->SetTitleOffset(1.05);
		bH->GetXaxis()->SetTitleOffset(0.9);
		bH->GetYaxis()->SetTitleSize(0.05);
		bH->GetXaxis()->SetTitleSize(0.05);
		if (isFitted) {bH->GetXaxis()->SetTitle(Form("(%s-#theta_{B})/#sigma_{#theta}",name));}
		else {bH->GetXaxis()->SetTitle(Form("%s",name));}
		
		bH->SetTitle("");	

		if ( bH->Integral() <=0 )  fitPull = false;
		if (fitPull) {bH->Fit("gaus"); bH->GetFunction("gaus")->SetLineColor(4);}
		
		if ( bHf->Integral() <=0 )  fitPullf = false;
		if (fitPullf) {bHf->Fit("gaus"); bHf->GetFunction("gaus")->SetLineColor(2);}

		c->Clear();
		//TPad pad1("t1","",0.01,0.02,0.59,0.98);
		// Pad 1 sizes depend on the parameter type ...
		double pad1_x1,pad1_x2,pad1_y1,pad1_y2;
		if ( !isFitted ) {
			 pad1_x1 = 0.01; 
			 pad1_x2 = 0.98; 
			 pad1_y1 = 0.045; 
			 pad1_y2 = 0.98; 
		} else {
			 pad1_x1 = 0.01; 
			 pad1_x2 = 0.59; 
			 pad1_y1 = 0.56; 
			 pad1_y2 = 0.98; 
		}
		
		TPad pad1("t1","",pad1_x1,pad1_y1,pad1_x2,pad1_y2);
		TPad pad1a("t1a","",0.01,0.045,0.59,0.522);
		TPad pad2("t2","",0.59,0.04,0.98,0.62);
		TPad pad3("t3","",0.55,0.64,0.96,0.95);

		pad1.SetNumber(1); pad2.SetNumber(2); pad3.SetNumber(3); pad1a.SetNumber(4);

		if ( isFitted ) {pad1a.Draw();pad2.Draw();pad3.Draw();}

		pad1.Draw();
		pad2.SetGrid(true);


		TLatex *titletext = new TLatex();titletext->SetNDC();

		if ( isFitted ){
			c->cd(4); 
			tree_->Draw(Form("%s:%s_In>>%s_%s_2d",name,name,name,tree_->GetName()),""); 
			//TH2D *h2d_corr = (TH2D*)gROOT->FindObject(Form("%s_2d",name));
			//h2d_corr->SetMarkerColor(4);
			//h2d_corr->SetTitle("");
			//h2d_corr->GetXaxis()->SetTitle(Form("%s_In",name));
			//h2d_corr->GetYaxis()->SetTitle(Form("%s",name));
			titletext->SetTextAlign(11);
			titletext->SetTextSize(0.05);
			titletext->DrawLatex(0.05,0.02,Form("%s_In",name));
			titletext->SetTextAngle(90);
			titletext->DrawLatex(0.04,0.06,Form("%s",name));
			titletext->SetTextAngle(0);
		}

		
		c->cd(1); bH->Draw(); bHf->Draw("same");
		TLegend *legend = new TLegend(0.6,0.8,0.9,0.89);
		legend->SetFillColor(0);
		legend->AddEntry(bH,"All Toys","L");
		legend->AddEntry(bHf,selectString.c_str(),"L");
		legend->Draw();

		if (doPull && plotLH) {
			c->cd(2); gr->Draw("ALP");
		}

		if (fitPull){
			c->cd(3);
			double gap;
			TLatex *tlatex = new TLatex(); tlatex->SetNDC(); 
			if (fitPullf) {tlatex->SetTextSize(0.09); gap=0.12;}
			else  {tlatex->SetTextSize(0.11);gap=0.14;}

			tlatex->SetTextColor(4);
			tlatex->DrawLatex(0.11,0.80,Form("Mean    : %.3f #pm %.3f",bH->GetFunction("gaus")->GetParameter(1),bH->GetFunction("gaus")->GetParError(1)));
			tlatex->DrawLatex(0.11,0.80-gap,Form("Sigma   : %.3f #pm %.3f",bH->GetFunction("gaus")->GetParameter(2),bH->GetFunction("gaus")->GetParError(2)));

			if (fitPullf){ 
				tlatex->SetTextColor(2);
				tlatex->DrawLatex(0.11,0.60,Form("Mean    : %.3f #pm %.3f",bHf->GetFunction("gaus")->GetParameter(1),bHf->GetFunction("gaus")->GetParError(1)));
				tlatex->DrawLatex(0.11,0.60-gap,Form("Sigma   : %.3f #pm %.3f",bHf->GetFunction("gaus")->GetParameter(2),bHf->GetFunction("gaus")->GetParError(2)));
			}

			tlatex->SetTextSize(0.10);
			tlatex->SetTextColor(1);
				
                        if(namestr.find("n_exp")!=string::npos) tlatex->DrawLatex(0.11,0.33,Form("Pre-fit: %.3f",prevals_[name].first));
			else tlatex->DrawLatex(0.11,0.33,Form("Pre-fit #pm #sigma_{#theta}: %.3f #pm %.3f",prevals_[name].first, p_err));
			tlatex->DrawLatex(0.11,0.18,Form("Best-fit (#theta_{B})  : %.3f ",p_mean));
			tlatex->DrawLatex(0.11,0.03,Form("Best-fit (#theta_{S+B}): %.3f ",bfvals_sb_[name].first));
			
			pullSummaryMap[name]=std::make_pair<double,double>(bH->GetFunction("gaus")->GetParameter(1),bH->GetFunction("gaus")->GetParameter(2));
			nPulls++;

		}

		double titleSize = isFitted ? 0.1 : 0.028;
		titletext->SetTextSize(titleSize);titletext->SetTextAlign(21); titletext->DrawLatex(0.55,0.92,name);
		c->SaveAs(Form("%s.pdf",treename.c_str()));
		fOut->WriteObject(c,Form("%s_%s",treename.c_str(),name));
		//c->SaveAs(Form("%s_%s.pdf",treename.c_str(),name));
	}
	
	if (doPull && nPulls>0){
	  
	    std::cout << "Generating Pull Summaries" <<std::endl; 
	    int nRemainingPulls = nPulls;
	    TCanvas *hc = new TCanvas("hc","",3000,2000); hc->SetGrid(0);
	    std::map < const char*, std::pair <double,double> >::iterator pull_it = pullSummaryMap.begin();
	    std::map < const char*, std::pair <double,double> >::iterator pull_end = pullSummaryMap.end();

	    int pullPlots = 1;
	    while (nRemainingPulls > 0){

		int nThisPulls = min(maxPullsPerPlot,nRemainingPulls);

		TH1F pullSummaryHist("pullSummary","",nThisPulls,0,nThisPulls);
		for (int pi=1;pull_it!=pull_end && pi<=nThisPulls ;pull_it++,pi++){
			pullSummaryHist.GetXaxis()->SetBinLabel(pi,(*pull_it).first);
			pullSummaryHist.SetBinContent(pi,((*pull_it).second).first);
			pullSummaryHist.SetBinError(pi,((*pull_it).second).second);
			nRemainingPulls--;
		}		

		pullSummaryHist.SetMarkerStyle(21);pullSummaryHist.SetMarkerSize(1.5);pullSummaryHist.SetMarkerColor(2);pullSummaryHist.SetLabelSize(pullLabelSize);
		pullSummaryHist.GetYaxis()->SetRangeUser(-3,3);pullSummaryHist.GetYaxis()->SetTitle("pull summary (n#sigma)");pullSummaryHist.Draw("E1");
		hc->SaveAs(Form("%s.pdf",treename.c_str()));
		fOut->WriteObject(hc,Form("comb_pulls_%s_%d",treename.c_str(),pullPlots));
	//	hc->SaveAs(Form("comb_pulls_%s_%d.pdf",treename.c_str(),pullPlots));
		pullPlots++;
	   }

	    delete hc;
	}

	c->SaveAs(Form("%s.pdf]",treename.c_str()));
	fOut->Close();
	delete c;
	return;


}
void plotTreeNorms(TTree *tree_, std::string selectString, bool do7TeV){

	// Create a map for plotting the pullsummaries:
	std::map < const char*, std::pair <double,double> > pullSummaryMap;
	int nPulls=0;

	TObjArray *l_branches = tree_->GetListOfBranches();
	int nBranches = l_branches->GetEntries();

	gStyle->SetPadTopMargin(0.01);

	TCanvas *c = new TCanvas("c","",960,800);

	std::string treename = tree_->GetName();
	c->SaveAs(Form("%s_normresiduals.pdf[",treename.c_str()));
	// File to store plots in 
	TFile *fOut = new TFile(Form("%s_normresiduals.root",treename.c_str()),"RECREATE");

        TH1F *bHd = new TH1F("bHd","",50,-1.0,1.0);
        TH1F *bHfd = new TH1F("bHfd","",50,-1.0,1.0);

	for (int iobj=0;iobj<nBranches;iobj++){

		TBranch *br =(TBranch*) l_branches->At(iobj);

		// Draw the normal histogram
		const char* name = br->GetName();

                // select only the normalizations
                string namestr(name);
                if(namestr.find("n_exp")==string::npos) continue;

                bool fitPull=true;
                bool fitPullf=true;

		double p_mean =0;

		int nToysInTree = tree_->GetEntries();
		// Find out if paramter is fitted value or constraint term.
                bool isFitted = true;
			
                p_mean = prenorms_[name].first;	// toy initial parameters from the datacards
                std::cout << "******* "<< name << " *******"<<std::endl;
                std::cout << p_mean << std::endl;
                std::cout << "******************************" <<std::endl;

                TH1F* bH = (TH1F*)bHd->Clone(Form("%s",name));
                TH1F* bHf = (TH1F*)bHfd->Clone(Form("%s_fail",name));
                
                const char* drawInput = Form("(%s-%f)/%f",name,p_mean,p_mean);
                tree_->Draw(Form("%s>>%s",drawInput,name),"");
                tree_->Draw(Form("%s>>%s_fail",drawInput,name),selectString.c_str(),"same");
                fitPull  = true;
                fitPullf = true;
                  
		bHf->SetLineColor(2);
		bH->GetXaxis()->SetTitle(bH->GetTitle());
		bH->GetYaxis()->SetTitle(Form("no toys (%d total)",nToysInTree));
		bH->GetYaxis()->SetTitleOffset(1.05);
		bH->GetXaxis()->SetTitleOffset(0.9);
		bH->GetYaxis()->SetTitleSize(0.05);
		bH->GetXaxis()->SetTitleSize(0.05);
		bH->GetXaxis()->SetTitle(Form("%s",name));
                
		
		bH->SetTitle("");	

		if ( bH->Integral() <=0 )  fitPull = false;
		if (fitPull) {bH->Fit("gaus"); bH->GetFunction("gaus")->SetLineColor(4);}
		
		if ( bHf->Integral() <=0 )  fitPullf = false;
		if (fitPullf) {bHf->Fit("gaus"); bHf->GetFunction("gaus")->SetLineColor(2);}

		c->Clear();
		
 		TPad pad1("t1","",0.01,0.01,0.66,0.95);
 		TPad pad2("t2","",0.70,0.20,0.98,0.80);

		pad1.SetNumber(1); pad2.SetNumber(2);

                if ( isFitted ) {pad2.Draw();}

		pad1.Draw();
		pad1.SetGrid(true);


		TLatex *titletext = new TLatex();titletext->SetNDC();

		
		c->cd(1); bH->Draw(); bHf->Draw("same");
		TLegend *legend = new TLegend(0.6,0.8,0.9,0.89);
		legend->SetFillColor(0);
		legend->AddEntry(bH,"All Toys","L");
		legend->AddEntry(bHf,selectString.c_str(),"L");
		legend->Draw();

		if (fitPull){
			c->cd(2);
			double gap;
			TLatex *tlatex = new TLatex(); tlatex->SetNDC(); 
			if (fitPullf) {tlatex->SetTextSize(0.09); gap=0.12;}
			else  {tlatex->SetTextSize(0.11);gap=0.14;}

			tlatex->SetTextColor(4);
			tlatex->DrawLatex(0.11,0.80,Form("Mean    : %.3f #pm %.3f",bH->GetFunction("gaus")->GetParameter(1),bH->GetFunction("gaus")->GetParError(1)));
			tlatex->DrawLatex(0.11,0.80-gap,Form("Sigma   : %.3f #pm %.3f",bH->GetFunction("gaus")->GetParameter(2),bH->GetFunction("gaus")->GetParError(2)));

			if (fitPullf){ 
				tlatex->SetTextColor(2);
				tlatex->DrawLatex(0.11,0.60,Form("Mean    : %.3f #pm %.3f",bHf->GetFunction("gaus")->GetParameter(1),bHf->GetFunction("gaus")->GetParError(1)));
				tlatex->DrawLatex(0.11,0.60-gap,Form("Sigma   : %.3f #pm %.3f",bHf->GetFunction("gaus")->GetParameter(2),bHf->GetFunction("gaus")->GetParError(2)));
			}

			tlatex->SetTextSize(0.10);
			tlatex->SetTextColor(1);
				
                        tlatex->DrawLatex(0.11,0.33,Form("Pre-fit: %.3f",p_mean));
			
			pullSummaryMap[name]=std::make_pair<double,double>(bH->GetFunction("gaus")->GetParameter(1),bH->GetFunction("gaus")->GetParameter(2));
			nPulls++;

		}

		// double titleSize = isFitted ? 0.1 : 0.028;
		//titletext->SetTextSize(titleSize);titletext->SetTextAlign(21); titletext->DrawLatex(0.55,0.92,name);
		c->SaveAs(Form("%s_normresiduals_%s.pdf",treename.c_str(),(do7TeV ? "7TeV": "8TeV")));
                c->SaveAs(Form("mlfit/%s_residual_%s_%s.pdf",name,treename.c_str(),(do7TeV ? "7TeV": "8TeV")));
		fOut->WriteObject(c,Form("%s_%s",treename.c_str(),name));
	}
	
	if (nPulls>0){
	  
	    std::cout << "Generating Pull Summaries" <<std::endl; 
	    int nRemainingPulls = nPulls;
	    TCanvas *hc = new TCanvas("hc","",3000,2000); hc->SetGrid(0);
	    std::map < const char*, std::pair <double,double> >::iterator pull_it = pullSummaryMap.begin();
	    std::map < const char*, std::pair <double,double> >::iterator pull_end = pullSummaryMap.end();

	    int pullPlots = 1;
	    while (nRemainingPulls > 0){

		int nThisPulls = min(maxPullsPerPlot,nRemainingPulls);

		TH1F pullSummaryHist("pullSummary","",nThisPulls,0,nThisPulls);
		for (int pi=1;pull_it!=pull_end && pi<=nThisPulls ;pull_it++,pi++){
			pullSummaryHist.GetXaxis()->SetBinLabel(pi,(*pull_it).first);
			pullSummaryHist.SetBinContent(pi,((*pull_it).second).first);
			pullSummaryHist.SetBinError(pi,((*pull_it).second).second);
			nRemainingPulls--;
		}		

		pullSummaryHist.SetMarkerStyle(21);pullSummaryHist.SetMarkerSize(1.5);pullSummaryHist.SetMarkerColor(2);pullSummaryHist.SetLabelSize(pullLabelSize);
		pullSummaryHist.GetYaxis()->SetRangeUser(-1,1);pullSummaryHist.GetYaxis()->SetTitle("residual summary (relative)");pullSummaryHist.Draw("E1");
		hc->SaveAs(Form("%s_normresiduals_%s.pdf",treename.c_str(),(do7TeV ? "7TeV": "8TeV")));
                hc->SaveAs(Form("mlfit/residual_summary_%d_%s_%s.pdf",pullPlots,treename.c_str(),(do7TeV ? "7TeV": "8TeV")));
		fOut->WriteObject(hc,Form("comb_pulls_%s_%d",treename.c_str(),pullPlots));
	//	hc->SaveAs(Form("comb_pulls_%s_%d.pdf",treename.c_str(),pullPlots));
		pullPlots++;
	   }

	    delete hc;
	}

	c->SaveAs(Form("%s_normresiduals_%s.pdf]",treename.c_str(),(do7TeV ? "7TeV": "8TeV")));
	fOut->Close();
	delete c;
	return;


}
void makeAndImportDataSets(TFile *fin, RooWorkspace *wspace, RooRealVar &x){

   // Get TTrees from input files and fill RooDataSets!
   //const char *name = x.GetName();
   
   RooRealVar weight("weight","weight",0,100);
   weight.removeRange();

   RooArgSet treevariables(x,weight);
   // List all branches in the tree and add them as variables 
   TObjArray *branches = (TObjArray*) ((TTree*)fin->Get("data_obs"))->GetListOfBranches();
   TIter next(branches);
   TBranch *br;
   while ( (br = (TBranch*)next()) ){
	const char *brname = br->GetName();
	std::cout << brname << std::endl;
	if ( *brname==*weight.GetName() ) continue; 
	if ( *brname==*x.GetName() ) continue;
	RooRealVar *vartmp = new RooRealVar(brname,brname,0,1); vartmp->removeRange();
	treevariables.add(*vartmp);
   }

 //  RooRealVar cvar(cutvar.c_str(),cutvar.c_str(),0,100);
 //  cvar.removeRange();
    
   std::cout << "Building RooDataSets " << std::endl; 
   treevariables.Print("V");
   //assert(0);
   // Zvv Signal region MC sample 
   RooDataSet zvv("DY","DY",treevariables,RooFit::Import(*((TTree*)fin->Get("DY"))),RooFit::Cut(cutstring.c_str()),RooFit::WeightVar("weight"));

   // Zvv Control sample 
   // Data ... (double mu)  Zvv_control
   RooDataSet zvvcontrol("Zvv_control","Zvv_control",treevariables,RooFit::Import(*((TTree*)fin->Get("Zvv_control"))),RooFit::Cut(cutstring.c_str()));

   // Backgrounds ...	    Zvv_control_bkg_mc
   RooDataSet zvvcontrolbkgmc("Zvv_control_bkg_mc","Zvv_control_bkg_mc",treevariables,RooFit::Import(*((TTree*)fin->Get("T_control_bkg_mc"))),RooFit::Cut(cutstring.c_str()),RooFit::WeightVar("weight"));
   RooDataSet zvvcontrolbkgmc_1("1","1",treevariables,RooFit::Import(*(TTree*)fin->Get("TT_control_bkg_mc")),RooFit::Cut(cutstring.c_str()),RooFit::WeightVar("weight"));
   RooDataSet zvvcontrolbkgmc_2("2","2",treevariables,RooFit::Import(*(TTree*)fin->Get("WW_control_bkg_mc")),RooFit::Cut(cutstring.c_str()),RooFit::WeightVar("weight"));
   RooDataSet zvvcontrolbkgmc_3("3","3",treevariables,RooFit::Import(*(TTree*)fin->Get("WZ_control_bkg_mc")),RooFit::Cut(cutstring.c_str()),RooFit::WeightVar("weight"));
   RooDataSet zvvcontrolbkgmc_4("4","4",treevariables,RooFit::Import(*(TTree*)fin->Get("ZZ_control_bkg_mc")),RooFit::Cut(cutstring.c_str()),RooFit::WeightVar("weight"));
   zvvcontrolbkgmc.append(zvvcontrolbkgmc_1);
   zvvcontrolbkgmc.append(zvvcontrolbkgmc_2);
   zvvcontrolbkgmc.append(zvvcontrolbkgmc_3);
   zvvcontrolbkgmc.append(zvvcontrolbkgmc_4);

   // MC ...		    Zvv_control_mc
   RooDataSet zvvcontrolmc("Zvv_control_mc","Zvv_control_mc",treevariables,RooFit::Import(*((TTree*)fin->Get("Zvv_control_mc"))),RooFit::Cut(cutstring.c_str()),RooFit::WeightVar("weight"));
   std::cout << " Weighs of datasets "  << std::endl;
   std::cout << " Zvv_control " << zvvcontrol.sumEntries() << std::endl;
   std::cout << " Zvv_control_mc " << zvvcontrolmc.sumEntries() << std::endl;

   // Wlv Control sample (single mu)
   // Data ... (double mu)
   // Backgrounds ...
   //.append()
   // MC ...

   // Store these to the output workspace  
   wspace->import(zvvcontrol);
   wspace->import(zvvcontrolmc);
   wspace->import(zvvcontrolbkgmc);
   wspace->import(zvv);


   // Wlv Signal region MC sample 
   RooDataSet wlv("W","W",treevariables,RooFit::Import(*((TTree*)fin->Get("W"))),RooFit::Cut(cutstring.c_str()),RooFit::WeightVar("weight"));
   RooDataSet wlv_ht("WHT","WHT",treevariables,RooFit::Import(*((TTree*)fin->Get("WHT"))),RooFit::Cut(cutstring.c_str()),RooFit::WeightVar("weight"));
   wlv.append(wlv_ht);

   // Wlv Control sample 
   // Data ... (single mu)  Wlv_control
   RooDataSet wlvcontrol("Wlv_control","Wlv_control",treevariables,RooFit::Import(*((TTree*)fin->Get("Wlv_control"))),RooFit::Cut(cutstring.c_str()));

   // Backgrounds ...	    Wlv_control_bkg_mc
   RooDataSet wlvcontrolbkgmc("Wlv_control_bkg_mc","Wlv_control_bkg_mc",treevariables,RooFit::Import(*((TTree*)fin->Get("T_sl_control_bkg_mc"))),RooFit::Cut(cutstring.c_str()),RooFit::WeightVar("weight"));
   RooDataSet wlvcontrolbkgmc_1("1","1",treevariables,RooFit::Import(*(TTree*)fin->Get("TT_sl_control_bkg_mc")),RooFit::Cut(cutstring.c_str()),RooFit::WeightVar("weight"));
   RooDataSet wlvcontrolbkgmc_2("2","2",treevariables,RooFit::Import(*(TTree*)fin->Get("DY_sl_control_bkg_mc")),RooFit::Cut(cutstring.c_str()),RooFit::WeightVar("weight"));
   RooDataSet wlvcontrolbkgmc_3("3","3",treevariables,RooFit::Import(*(TTree*)fin->Get("WZ_sl_control_bkg_mc")),RooFit::Cut(cutstring.c_str()),RooFit::WeightVar("weight"));
   RooDataSet wlvcontrolbkgmc_4("4","4",treevariables,RooFit::Import(*(TTree*)fin->Get("ZZ_control_bkg_mc")),RooFit::Cut(cutstring.c_str()),RooFit::WeightVar("weight"));
   RooDataSet wlvcontrolbkgmc_5("5","5",treevariables,RooFit::Import(*(TTree*)fin->Get("WW_control_bkg_mc")),RooFit::Cut(cutstring.c_str()),RooFit::WeightVar("weight"));
   wlvcontrolbkgmc.append(wlvcontrolbkgmc_1);
   wlvcontrolbkgmc.append(wlvcontrolbkgmc_2);
   wlvcontrolbkgmc.append(wlvcontrolbkgmc_3);
   wlvcontrolbkgmc.append(wlvcontrolbkgmc_4);
   wlvcontrolbkgmc.append(wlvcontrolbkgmc_5);

   // MC ...		    Zvv_control_mc
   RooDataSet wlvcontrolmc("Wlv_control_mc","Wlv_control_mc",treevariables,RooFit::Import(*((TTree*)fin->Get("Wlv_control_mc_1"))),RooFit::Cut(cutstring.c_str()),RooFit::WeightVar("weight"));
   RooDataSet wlvcontrolmc_2("Wlv_control_mc_2","Wlv_control_mc_2",treevariables,RooFit::Import(*((TTree*)fin->Get("Wlv_control_mc_2"))),RooFit::Cut(cutstring.c_str()),RooFit::WeightVar("weight"));
   wlvcontrolmc.append(wlvcontrolmc_2);
   std::cout << " Weighs of datasets "  << std::endl;
   std::cout << " Wlv_control "    << wlvcontrol.sumEntries() << std::endl;
   std::cout << " Wlv_control_mc " << wlvcontrolmc.sumEntries() << std::endl;

   // Wlv Control sample (single mu)
   // Data ... (double mu)
   // Backgrounds ...
   //.append()
   // MC ...

   // Store these to the output workspace  
   wspace->import(wlvcontrol);
   wspace->import(wlvcontrolmc);
   wspace->import(wlvcontrolbkgmc);
   wspace->import(wlv);

}
Example #26
0
void test(){

  //Put in the files you want to compare here
  string filename_new = "/home/users/namin/sandbox/CMSSW_8_0_20/src/CMS3/NtupleMaker/test/ntuple_new.root";
  string filename_old = "/home/users/namin/sandbox/beforelumi/CMSSW_8_0_20/src/CMS3/NtupleMaker/test/ntuple_old.root";

  //Load files
  file_old = new TFile(filename_old.c_str());
  file_new = new TFile(filename_new.c_str());

  //Load trees
  TTree *tree_old = (TTree*)file_old->Get("Events");
  TTree *tree_new = (TTree*)file_new->Get("Events");

  //LaTeX stuff
  myfile.open("overview.tex"); 
  myfile << "\\documentclass{article}" << endl
         << "\\usepackage{fullpage}" << endl
         << "\\usepackage{graphicx}" << endl
         << "\\usepackage{float}" << endl
         << "\\usepackage{listings}" << endl
         << "\\usepackage{hyperref}" << endl << endl
         << "\\begin{document}" << endl << endl
         << "\\begin{center}" << endl
         << "\\LARGE \\bf Compare Ntuples for CMS3" << endl
         << "\\end{center}" << endl
         << "\\vspace{0.5cm}" << endl << endl
         << "{\\noindent\\Large\\bf Files that are compared here:}" << endl
         << "\\begin{lstlisting}[breaklines] "  << endl
         << "OLD: " << filename_old << endl
         << "NEW: " << filename_new << endl
         << "\\end{lstlisting}" << endl
         << "\\vspace{0.5cm}" << endl << endl 
         << "\\tableofcontents" << endl 
         << "\\section*{Branches in OLD but not in NEW}\\addcontentsline{toc}{section}{Branches in Old but not in New}" 
         << endl;

  //Get aliases in both trees
  vector<std::string> oldAliasNames = getAliasNames(tree_old);
  vector<std::string> newAliasNames = getAliasNames(tree_new);

  //Holders for common and notCommonBranches
  vector<std::string> commonBranches;
  vector<std::string> oldOnlyBranches;
  vector<std::string> newOnlyBranches;
  
  //Figure out common branches
  for(vector<std::string>::iterator it = oldAliasNames.begin(); it != oldAliasNames.end(); it++) {
    if(find(newAliasNames.begin(), newAliasNames.end(), *it) != newAliasNames.end()) commonBranches.push_back(*it);
  }

  //Figure out uncommon branches 
  oldOnlyBranches = getUncommonBranches(oldAliasNames, commonBranches);
  newOnlyBranches = getUncommonBranches(newAliasNames, commonBranches);

  //Number of plots drawn
  plotNum = 0;

  //Record chi2 of each plot
  vector<trifecta> chi2pair;

  //Loop over non-common branches, update ToC for LaTeX
  doSinglePlots(oldOnlyBranches, 0, tree_old);
  myfile << "\\section*{Branches in NEW but not in OLD}\\addcontentsline{toc}{section}{Branches in New but not in Old}" << endl;
  doSinglePlots(newOnlyBranches, 1, tree_new);

  //Reinitialize number of plots drawn
  plotNum = 0;

  //Loop over common branches, test for sameness
  for (unsigned int i = 0; i < commonBranches.size(); i++){

    //Status
    cout << "Working on " << commonBranches[i] << endl;

    //Identical plots should be suppressed
    int suppress = false;

    //Determine if it's a LorentzVector
    TBranch *branch = tree_new->GetBranch(tree_new->GetAlias(commonBranches[i].c_str()));
    TString branchname(branch->GetName()); 
    bool isLorentz = branchname.Contains("p4") || branchname.Contains("MathLorentzVectors"); 

    //Make plot
    tree_old->Draw(Form("%s%s>>hist_old", commonBranches[i].c_str(), isLorentz ? ".Pt()" : ""), "", "", max_events); 
    tree_new->Draw(Form("%s%s>>hist_new", commonBranches[i].c_str(), isLorentz ? ".Pt()" : ""), "", "", max_events); 

    //Retrieve plot (this will use default binning)
    TH1F *hist_old = (TH1F*)gDirectory->Get("hist_old");
    TH1F *hist_new = (TH1F*)gDirectory->Get("hist_new");

    //Give both histos the same binning, if not already done
    int old_min = hist_old->GetXaxis()->GetBinLowEdge(1);
    int old_max = hist_old->GetXaxis()->GetBinLowEdge( hist_old->GetNbinsX() ) + hist_old->GetXaxis()->GetBinWidth( hist_old->GetNbinsX() );
    int old_nbins = hist_old->GetNbinsX();
    int new_min = hist_new->GetXaxis()->GetBinLowEdge(1);
    int new_max = hist_new->GetXaxis()->GetBinLowEdge( hist_new->GetNbinsX() ) + hist_new->GetXaxis()->GetBinWidth( hist_new->GetNbinsX() );
    int new_nbins = hist_new->GetNbinsX();
    int nbins = std::max(old_nbins, new_nbins); 
    float min = std::min(old_min, new_min); 
    float max = std::max(old_max, new_max); 
    if (old_min != new_min || old_max != new_max || old_nbins != new_nbins){
      delete hist_old;
      delete hist_new;
      hist_old = new TH1F("hist_old", "hist_old", nbins, min, max); 
      hist_new = new TH1F("hist_new", "hist_new", nbins, min, max); 
      tree_old->Draw(Form("%s%s>>hist_old", commonBranches[i].c_str(), isLorentz ? ".Pt()" : ""), "", "", max_events); 
      tree_new->Draw(Form("%s%s>>hist_new", commonBranches[i].c_str(), isLorentz ? ".Pt()" : ""), "", "", max_events); 
    }

    //If it's being f*****g stupid and putting everything in 1 bin, redraw yet again.  Lowest & Highest bins shouldn't be empty
    bool keepGoing = ((std::min(hist_old->GetBinContent(1), hist_new->GetBinContent(1)) == 0) || (std::min(hist_old->GetBinContent(nbins), hist_new->GetBinContent(nbins)) == 0));
 
    //Keep track of number of iterations so it doesn't get stuck
    int niter = 0;

    //Keep looping until lowest & highest bins aren't empty
    while (keepGoing == true && niter < 15){
      //Determine highest/lowest bins that are filled
      for (int j = 1; j < nbins; j++){
        if (hist_old->GetBinContent(j) != 0){ min = hist_old->GetXaxis()->GetBinLowEdge(j); break; } 
        if (hist_new->GetBinContent(j) != 0){ min = hist_new->GetXaxis()->GetBinLowEdge(j); break; } 
      }
      for (int j = nbins; j > 0; j--){
        if (hist_old->GetBinContent(j) != 0){ max = hist_old->GetXaxis()->GetBinLowEdge(j) + 2*hist_old->GetXaxis()->GetBinWidth(j); break; } 
        if (hist_new->GetBinContent(j) != 0){ max = hist_new->GetXaxis()->GetBinLowEdge(j) + 2*hist_new->GetXaxis()->GetBinWidth(j); break; } 
      }
      //Redraw using the above bins
      delete hist_old;
      delete hist_new;
      hist_old = new TH1F("hist_old", "hist_old", nbins, min, max); 
      hist_new = new TH1F("hist_new", "hist_new", nbins, min, max); 
      tree_old->Draw(Form("%s%s>>hist_old", commonBranches[i].c_str(), isLorentz ? ".Pt()" : ""), "", "", max_events); 
      tree_new->Draw(Form("%s%s>>hist_new", commonBranches[i].c_str(), isLorentz ? ".Pt()" : ""), "", "", max_events); 

      //Decide if we fixed the problem or if we need to try again
      niter++;
      keepGoing = ((std::max(hist_old->GetBinContent(1), hist_new->GetBinContent(1)) == 0) || (std::max(hist_old->GetBinContent(nbins), hist_new->GetBinContent(nbins)) == 0));

      //No need to try again if the second-highest bin is filled (close enough, often saves a step)
     if (keepGoing && (std::max(hist_old->GetBinContent(1), hist_new->GetBinContent(1)) != 0) && (std::max(hist_old->GetBinContent(nbins-1), hist_new->GetBinContent(nbins-1)) != 0)) keepGoing = false;
    
     //No need to try again if max and min are f*****g close (this will avoid problems if everything is in one bin)
     if ( (max-min)/max < .001){ keepGoing = false; suppress = true;} 
    }

    //Normalize both histos
    hist_old->Scale(1./hist_old->GetEntries());
    hist_new->Scale(1./hist_new->GetEntries());

    //Figure out chi2, decide if you want to suppress
    float chi2test = hist_new->Chi2Test(hist_old, "CHI2/NDFWWOFUF");
    if (chi2test*100 < 0.2) suppress = true;

    //Print histogram, update LaTeX stuff if not suppressed
    if (suppress) cout << " --> Suppressed!" << endl;
    if (!suppress){ 
      vector<TH1F*> old_vector;
      old_vector.push_back(hist_old);
      vector<string> titles;
      titles.push_back("Old");
      dataMCplotMaker(hist_new, old_vector, titles, Form("%.2f", chi2test*100), commonBranches[i].c_str(), Form("--noErrBars --isLinear --dataName New --topYaxisTitle New/Old --xAxisOverride --noDivisionLabel --outputName hists/diff%i", plotNum));
      trifecta chi2pair_;
      chi2pair_.plotName = commonBranches[i];
      chi2pair_.plotNumber = plotNum;
      chi2pair_.chi2 = chi2test; 
      chi2pair.push_back(chi2pair_);
      plotNum++;
    }

    //Memory management
    delete hist_old;
    delete hist_new;

  }

  //ToC stuff
  myfile << "\\section*{Branches in Common}\\addcontentsline{toc}{section}{Branches in Common}" << endl;

  //Put worst plots first
  std::sort(chi2pair.begin(), chi2pair.end(), comparePair);

  //LaTeX stuff
  for(unsigned int i = 0; i < chi2pair.size(); i++){
    myfile << "\\subsection*{" << chi2pair[i].plotName << "}\\addcontentsline{toc}{subsection}{" << chi2pair[i].plotName << "}" << endl
           << "\\begin{figure}[H]" << endl
           << Form("\\includegraphics[width=0.9\\textwidth]{./hists/diff%i.pdf}", chi2pair[i].plotNumber) << endl
           << "\\end{figure}" << endl;
    myfile << "The $\\chi^2$ test value between the Old and New is: " << chi2pair[i].chi2 << endl;
  }

  myfile << "\\end{document}" << endl;

}
Example #27
0
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;
}
Example #28
0
UInt_t OnlineGUI::GetTreeIndex(TString var) {
  // Utility to find out which Tree (in fRootTree) has the specified
  // variable "var".  If the variable is a collection of Tree
  // variables (e.g. bcm1:lumi1), will only check the first
  // (e.g. bcm1).  
  // Returns the correct index.  if not found returns an index 1
  // larger than fRootTree.size()

  //  This is for 2d draws... look for the first only
  if(var.Contains(":")) {
    TString first_var = fConfig->SplitString(var,":")[0];
    var = first_var;
  }
  if(var.Contains("-")) {
    TString first_var = fConfig->SplitString(var,"-")[0];
    var = first_var;
  }
  if(var.Contains("/")) {
    TString first_var = fConfig->SplitString(var,"/")[0];
    var = first_var;
  }
  if(var.Contains("*")) {
    TString first_var = fConfig->SplitString(var,"*")[0];
    var = first_var;
  }
  if(var.Contains("+")) {
    TString first_var = fConfig->SplitString(var,"+")[0];
    var = first_var;
  }
  if(var.Contains("(")) {
    TString first_var = fConfig->SplitString(var,"(")[0];
    var = first_var;
  }
  //  This is for variables with multiple dimensions.
  if(var.Contains("[")) {
    TString first_var = fConfig->SplitString(var,"[")[0];
    var = first_var;
  }

#ifdef OLD_GETTREEINDEX
  TObjArray *branchList;

  for(UInt_t i=0; i<fRootTree.size(); i++) {
    branchList = fRootTree[i]->GetListOfBranches();
    TIter next(branchList);
    TBranch *brc;

    while((brc=(TBranch*)next())!=0) {
      TString found = brc->GetName();
      if (found == var) {
	return i;
      }
    }
  }
#else
  for(UInt_t iTree=0; iTree<treeVars.size(); iTree++) {
    for(UInt_t ivar=0; ivar<treeVars[iTree].size(); ivar++) {
      if(var == treeVars[iTree][ivar]) return iTree;
    }
  }

#endif
  return fRootTree.size()+1;
}
Example #29
0
void Example_tags(TString topDir = "/star/rcf/GC/daq/tags")
{
//////////////////////////////////////////////////////////////////////////
//                                                                      //
// Example_tags.C                                                       //
//                                                                      //
// shows how to use the STAR tags files                                 //
// Input: top level directory                                           //
//                                                                      //
// what it does:                                                        //
// 1. creates TChain from all tags files down from the topDir           //
// 2. loops over all events in the chain                                //
//                                                                      //
// owner: Alexandre V. Vaniachine <*****@*****.**>                //
//////////////////////////////////////////////////////////////////////////

  gSystem->Load("libTable");
  gSystem->Load("St_base");
  // start benchmarks
  gBenchmark = new TBenchmark();
  gBenchmark->Start("total");
   
  // set loop optimization level
  gROOT->ProcessLine(".O4");
  // gather all files from the same top directory into one chain
  // topDir must end with "/"
  topDir +='/';
  St_FileSet dirs(topDir);
  St_DataSetIter next(&dirs,0);
  St_DataSet *set = 0; 
  TChain chain("Tag");
  while ( (set = next()) ) {           
    if (strcmp(set->GetTitle(),"file") || 
	!(strstr(set->GetName(),".tags.root"))) continue;
    chain.Add(gSystem->ConcatFileName(topDir,set->Path()));
  }
  UInt_t nEvents = chain->GetEntries();
  cout<<"chained "<<nEvents<<" events "<<endl;

  TObjArray *files = chain.GetListOfFiles();
  UInt_t nFiles = files->GetEntriesFast();
  cout << "chained " << nFiles << " files from " << topDir << endl;

  TObjArray *leaves = chain.GetListOfLeaves();
  Int_t nleaves = leaves->GetEntriesFast();

  TString tableName = " ";
  TObjArray *tagTable = new TObjArray;

  Int_t tableCount = 0;
  Int_t *tableIndex = new Int_t[nleaves];
  Int_t tagCount = 0;

  // decode tag table names
  for (Int_t l=0;l<nleaves;l++) {
    TLeaf *leaf = (TLeaf*)leaves->UncheckedAt(l);
    tagCount+=leaf->GetNdata();
    TBranch *branch = leaf->GetBranch();
    // new tag table name
    if ( strstr(branch->GetName(), tableName.Data()) == 0 ) {
      tableName = branch->GetName();
      // the tableName is encoded in the branch Name before the "."
      tableName.Resize(tableName->Last('.'));
      tagTable->AddLast(new TObjString(tableName.Data()));
      tableCount++;
    }
    tableIndex[l]=tableCount-1;
  }
  cout << " tot num tables, tags = " << tableCount << "   " 
       << tagCount << endl << endl;

  //EXAMPLE 1: how to print out names of all tags and values for first event
  for (l=0;l<nleaves;l++) {
    leaf = (TLeaf*)leaves->UncheckedAt(l);
    branch = leaf->GetBranch();
    branch->GetEntry();
    // tag comment is in the title
    TString Title = leaf->GetTitle();
    Int_t dim = leaf->GetNdata();
    if (dim==1) {
      Title.ReplaceAll('['," '"); 
      Title.ReplaceAll(']',"'"); 
    }
    cout << "\n Table: ";
    cout.width(10);
    cout << ((TObjString*)tagTable->UncheckedAt(tableIndex[l]))->GetString()
	 <<" -- has tag: " << Title << endl;
    for (Int_t i=0;i<dim;i++) {
      cout <<"                               "<< leaf->GetName();
      if (dim>1) cout << '['<<i<<']';
      cout << " = " << leaf->GetValue(i) << endl; 
    }
  }

  // EXAMPLE 2: how to make a plot
  c1 = new TCanvas("c1","Beam-Gas Rejection",600,1000);
  gStyle->SetMarkerStyle(8);
  chain->Draw("n_trk_tpc[0]:n_trk_tpc[1]");

  // EXAMPLE 3: how to make a selection (write selected event numbers on the plot)
  Int_t ncoll=0;
  char aevent[10];
  TText t(0,0,"a");
  t.SetTextFont(52);
  t.SetTextSize(0.02);
  Float_t cut = 0.35;
  cout <<"\n Events with ntrk>400 and |asim|<"<<cut<<endl;
  //loop over all events: READ ONLY n_trk_tpc AND mEventNumber BRANCHES!
  gBenchmark->Start("loop");
  for (Int_t i=0;i<nFiles;i++) {
    chain.LoadTree(*(chain.GetTreeOffset()+i));
    TTree *T = chain.GetTree();
    //must renew leaf pointer for each tree
    TLeaf *ntrk = T->GetLeaf("n_trk_tpc");
    TLeaf *run = T->GetLeaf("mRunNumber");
    TLeaf *event = T->GetLeaf("mEventNumber");
    for (Int_t j=0; j<T->GetEntries(); j++){
      ntrk->GetBranch()->GetEntry(j);
      event->GetBranch()->GetEntry(j);
      run->GetBranch()->GetEntry(j);
      Int_t Nm=ntrk->GetValue(0);
      Int_t Np=ntrk->GetValue(1);
      Int_t Ntrk = Np+Nm;
      // avoid division by 0
      Float_t asim = Np-Nm;
      if (Ntrk>0) asim /= Ntrk;
      if (-cut < asim&&asim < cut && Ntrk>400) {
	cout<<"   Run "<<(UInt_t)run->GetValue()
	    <<", Event "<<event->GetValue() <<endl;
	ncoll++;
	sprintf(aevent,"%d",event->GetValue());
	t.DrawText(Np+10,Nm+10,aevent);
      }
    }
  }
  gBenchmark->Stop("loop");
  t.SetTextSize(0.05);
  t.DrawText(50,2550,"ntrk>400 and |(Np-Nm)/(Np+Nm)| < 0.35 ");
  t.DrawText(500,-300,"Ntrk with tanl<0 ");
  cout << " Selected " << ncoll << " collision candidates out of "
       << nEvents << " events" << endl;
  // stop timer and print benchmarks
  gBenchmark->Print("loop");  
  gBenchmark->Stop("total");
  gBenchmark->Print("total");  
}
Example #30
0
void compareNtuples(TString file1, TString file2, bool doNotSaveSameHistos="true", bool drawWithErrors="true",
		    double ksMinThreshold = 0.001) {
  
  //TDirectory *rootdir = gDirectory->GetDirectory("Rint:");
  
  TFile *f1 = TFile::Open(file1.Data(), "READ");
  if(f1 == NULL) {
    cout << "Exiting" << endl;
    return;
  }
  TTree *tree1 = (TTree*)f1->Get("Events");
  if(tree1 == NULL) {
    cout << "Can't find the tree \"Events\" in " << file1 << " Exiting " << endl;
    return;
  }

  TFile *f2 = TFile::Open(file2.Data(), "READ");
  if(f2 == NULL) {
    cout << "Exiting" << endl;
    return;
  }
  TTree *tree2 = (TTree*)f2->Get("Events");
  if(tree2 == NULL) {
    cout << "Can't find the tree \"Events\" in " << file2 << " Exiting " << endl;
    return;
  }

  TObjArray *objArray= file1.Tokenize("/");
  TString fname1 = "";
  TString fname2 = "";
  for(int i = 0; i < objArray->GetSize(); i++) {
    if(fname1 != "")
      continue;
    cout << TString(objArray->At(i)->GetName()) << endl;
    if(TString(objArray->At(i)->GetName()).Contains("root")) {
      fname1 = TString(objArray->At(i)->GetName());
      continue;
    }
  }
  objArray = file2.Tokenize("/"); 
  for(int i = 0; i < objArray->GetSize(); i++) {
    if(fname2 != "")
      continue;
    cout << TString(objArray->At(i)->GetName()) << endl;
    if(TString(objArray->At(i)->GetName()).Contains("root")) {
      fname2 = TString(objArray->At(i)->GetName());
      continue;
    }
  }
  
  vector<TString> t1_aliasnames = getAliasNames(tree1);
  vector<TString> t2_aliasnames = getAliasNames(tree2);
  vector<TString> v_commonBranches;
  vector<TString> v1_notCommonBranches;
  vector<TString> v2_notCommonBranches;
  
  for(vector<TString>::iterator it = t1_aliasnames.begin(); 
      it != t1_aliasnames.end(); it++) {
    
    if(find(t2_aliasnames.begin(), t2_aliasnames.end(), *it) != t2_aliasnames.end())
      v_commonBranches.push_back(*it);
  }

  //figure out which branches are not common so you can output their names 
  //and draw them last
  v1_notCommonBranches = getUncommonBranches(t1_aliasnames, v_commonBranches);
  v2_notCommonBranches = getUncommonBranches(t2_aliasnames, v_commonBranches);

  TCanvas *c1 = new TCanvas();
  

  for(unsigned int i = 0; i < v1_notCommonBranches.size(); i++) {
    
    TString alias = v1_notCommonBranches.at(i);
    cout << "Branch: " << alias << " was found in " 
	 << file1 << " but not in " << file2 << endl;
    TString histname = "h1_"+(alias);
    TString command  = (alias) + ">>" + histname;
    TBranch *branch = tree1->GetBranch(tree1->GetAlias(alias));
    TString branchname(branch->GetName());
    
    if( branchname.Contains("LorentzVector") ) {
      histname = "h1_"+ alias + "_pt";
      command  = alias + ".Pt()>>" + histname;      
    }
    tree1->Draw(command.Data());
    TH1F *h1 = (TH1F*)gDirectory->Get(histname.Data());
    if(h1==NULL) {
      cout << "********** Branch " << v1_notCommonBranches.at(i) 
	   << " in file " << file1 << "exists, but is undrawable for some reason. " 
	   << "Skipping this branch" << endl;
      c1->Clear();
      continue; 
    }
    c1->Clear();

    if(drawWithErrors)
      h1->TH1F::Sumw2();
    

    h1->Scale(1./h1->GetEntries());
    if(!drawWithErrors) {
      h1->SetLineColor(0);
      h1->SetMarkerSize(1.1);
      h1->SetMarkerStyle(3);
    } else {
      h1->SetMarkerSize(1.3);
      h1->SetMarkerStyle(3);
    }
    
    TString histtitle = alias + ", " + fname1;
    h1->SetTitle(histtitle.Data());
    h1->Draw();
    c1->SaveAs("diff.ps(");
    c1->SetLogy();
    
    //if the canvas has been divided, want to set the logy
    for(int ii = 0; ii < c1->GetListOfPrimitives()->GetSize(); ii++) {
      if(string(c1->GetListOfPrimitives()->At(ii)->ClassName()) != "TVirtualPad")
	continue;
      TVirtualPad *vPad = (TVirtualPad*)(c1->GetListOfPrimitives()->At(ii));
      if(vPad != NULL) {
	vPad->SetLogy();
      }
    }
    c1->SaveAs("diff.ps(");
    c1->SetLogy(0);
  }

  for(unsigned int i = 0; i < v2_notCommonBranches.size(); i++) {
    
    TString alias = v2_notCommonBranches.at(i);
    cout << "Branch: " << alias << " was found in " 
	 << file1 << " but not in " << file2 << endl;
    TString histname = "h2_"+(alias);
    TString command  = (alias) + ">>" + histname;
    TBranch *branch = tree2->GetBranch(tree2->GetAlias(alias));
    TString branchname(branch->GetName());
    
    if( branchname.Contains("LorentzVector") ) {
      histname = "h2_"+ alias + "_pt";
      command  = alias + ".Pt()>>" + histname;      
    }
    tree2->Draw(command.Data());
    TH1F *h2 = (TH1F*)gDirectory->Get(histname.Data());
    if(h2==NULL) {
      cout << "********** Branch " << v2_notCommonBranches.at(i) 
	   << " in file " << file2 << "exists, but is undrawable for some reason. " 
	   << "Skipping this branch" << endl;
      c1->Clear();
      continue; 
    }
    c1->Clear();

    if(drawWithErrors)
      h2->TH1F::Sumw2();


    h2->Scale(1./h2->GetEntries());
    
    if(!drawWithErrors) {
      h2->SetLineColor(kRed);
      h2->SetLineStyle(7);
    } else {
      h2->SetMarkerSize(1.1);
      h2->SetMarkerStyle(8);
      h2->SetMarkerColor(kRed);
    }
    TString histtitle = alias + ", " + fname2;
    h2->SetTitle(histtitle.Data());
    h2->Draw();
    c1->SaveAs("diff.ps(");
    c1->SetLogy();
    //if the canvas has been divided, want to set the logy
    for(int ii = 0; ii < c1->GetListOfPrimitives()->GetSize(); ii++) {
      if(string(c1->GetListOfPrimitives()->At(ii)->ClassName()) != "TVirtualPad")
	continue;
      TVirtualPad *vPad = (TVirtualPad*)c1->GetListOfPrimitives()->At(ii);
      if(vPad != NULL)
	vPad->SetLogy();
    }
    c1->SaveAs("diff.ps(");
    c1->SetLogy(0);
  }




  for(unsigned int i =  0; i < v_commonBranches.size(); i++) {
        
    TString alias = v_commonBranches.at(i);
    cout << "Comparing Branch: " << alias << endl;
    TString hist1name = "h1_"+ alias;
    TString hist2name = "h2_"+ alias;
    TString command1 = (alias)+"+9990.*((abs("+alias +"+9999)<1)*1.)>>"+hist1name;
    TString command2 = (alias)+"+9990.*((abs("+alias +"+9999)<1)*1.)>>"+hist2name;
    TBranch *branch = tree2->GetBranch(tree2->GetAlias(alias));
    TString branchname(branch->GetName());
        
    if(branchname.Contains("p4") ) {
      hist1name = "h1_"+ alias + "_Pt";
      hist2name = "h2_"+ alias + "_Pt";
      command1 = alias + ".pt()+14130.*((abs("+alias+".pt()-14140.7)<1)*1.)>>"+hist1name;
      command2 = alias + ".pt()+14130.*((abs("+alias+".pt()-14140.7)<1)*1.)>>"+hist2name;
    }
    
    tree1->Draw(command1.Data());
    //TH1F *h1 = (TH1F*)c1->GetPrimitive(hist1name.Data());
    TH1F *h1 = (TH1F*)gDirectory->Get(hist1name.Data());
    if(h1==NULL) {
      cout << "********** Branch " << v_commonBranches.at(i) 
	   << " in file " << file1 << " exists, but is undrawable for some reason. " 
	   << "Skipping this branch" << endl;
      c1->Clear();
      continue; 
    }
    //set the Overflow at the last bin
    tree2->Draw(command2.Data());
    //TH1F *h2 = (TH1F*)c1->GetPrimitive(hist2name.Data());
    TH1F *h2 = (TH1F*)gDirectory->Get(hist2name.Data());
    if(h2==NULL) {
      cout << "********** Branch " << v_commonBranches.at(i) 
	   << " in file " << file2 << "exists, but is undrawable for some reason. " 
	   << "Skipping this branch" << endl;
      c1->Clear();
      continue;  
    }
    c1->Clear();

    bool histos_theSame = areHistosTheSame(h1, h2);
    if(histos_theSame && doNotSaveSameHistos)
      continue;
    
    if (! histos_theSame){
      double min1 = h1->GetXaxis()->GetXmin();
      double min2 = h2->GetXaxis()->GetXmin(); 
      double max1 = h1->GetXaxis()->GetXmax();
      double max2 = h2->GetXaxis()->GetXmax();

      double hmin = min1 > min2 ? min2 : min1;
      double hmax = max1 > max2 ? max1 : max2;

      command1 += Form("_fix(100,%f,%f)", hmin, hmax);
      command2 += Form("_fix(100,%f,%f)", hmin, hmax);
      hist1name += "_fix";
      hist2name += "_fix";
      tree1->Draw(command1.Data());
      tree2->Draw(command2.Data());
      h1 = (TH1F*)gDirectory->Get(hist1name.Data());
      h2 = (TH1F*)gDirectory->Get(hist2name.Data());
   }

    if(drawWithErrors) {
      h1->TH1F::Sumw2();
      h2->TH1F::Sumw2();
    }


    h1->Scale(1./h1->GetEntries());
    h2->Scale(1./h2->GetEntries());


    double bDiff = 0;
    unsigned int nX1 = h1->GetNbinsX();
    for(unsigned int iB=0; iB<=nX1+1; ++iB){
      if(h1->GetBinError(iB)==0 && h1->GetBinContent(iB)!=0) h1->SetBinError(iB,1e-3*fabs(h1->GetBinContent(iB)));
      if(h2->GetBinError(iB)==0 && h2->GetBinContent(iB)!=0) h2->SetBinError(iB,1e-3*fabs(h2->GetBinContent(iB)));
      bDiff +=fabs(h1->GetBinContent(iB) - h2->GetBinContent(iB));
    }
    double ksProb = 0;
    if (bDiff == 0) ksProb = 1;
    else ksProb = h1->KolmogorovTest(h2);

    if (bDiff ==0 || ksProb > ksMinThreshold ) continue;

    if(h1->GetNbinsX() != h2->GetNbinsX() ) {
      cout << "Branch " << v_commonBranches.at(i) << " not the same between the 2 files" 
	   << ". They will be drawn side by side" << endl;
      
      c1->Divide(2,1);
      h2->SetTitle(fname2);
      h1->SetTitle(fname1);
      if(!drawWithErrors) {
	h1->SetLineColor(0);
	h1->SetMarkerSize(1.1);
	h1->SetMarkerStyle(3);
	h2->SetLineColor(kRed);
	h2->SetLineStyle(7);
	c1->cd(1);
	h1->Draw();
	c1->cd(2);
	h2->Draw();
      } else {
	h1->SetMarkerSize(1.3);
	h1->SetMarkerStyle(3);
	h2->SetMarkerSize(1.1);
	h2->SetMarkerStyle(8);
	h2->SetMarkerColor(kRed);
	c1->cd(1);
	h1->Draw("e");
	c1->cd(2);
	h2->Draw("e");
      }
      TPaveText ksPt(0,0, 0.35, 0.05, "NDC");
      ksPt.AddText(Form("P(KS)=%g, diffBins=%g, eblk %g ered %g",ksProb, bDiff, h1->GetEntries(), h2->GetEntries()));
      ksPt.Draw();


      if(i < v_commonBranches.size() - 1) {
	c1->SaveAs("diff.ps(");
	c1->SetLogy();
	//if the canvas has been divided, want to set the logy
	for(int ii = 0; ii < c1->GetListOfPrimitives()->GetSize(); ii++) {
	  if(string(c1->GetListOfPrimitives()->At(ii)->ClassName()) != "TVirtualPad")
	    continue;
	  TVirtualPad *vPad = (TVirtualPad*)c1->GetListOfPrimitives()->At(ii);
	  if(vPad != NULL)
	    vPad->SetLogy();
	}
	c1->SaveAs("diff.ps(");
	c1->SetLogy(0);
      } else {
	cout << "done" << endl;
	c1->SaveAs("diff.ps(");
	c1->SetLogy();
	for(int ii = 0; ii < c1->GetListOfPrimitives()->GetSize(); ii++) {
	  if(string(c1->GetListOfPrimitives()->At(ii)->ClassName()) != "TVirtualPad")
	    continue;
	  TVirtualPad *vPad = (TVirtualPad*)c1->GetListOfPrimitives()->At(ii);
	  if(vPad != NULL)
	    vPad->SetLogy();
	}
	c1->SaveAs("diff.ps)");
	c1->SetLogy(0);
      } 
      continue;
    }
            
      if(h1->GetMaximum() >= h2->GetMaximum()) {
      
	double max = 1.1*h1->GetMaximum();
	h1->SetMaximum(max);
	h2->SetMaximum(max);
      
	if(!drawWithErrors) {
	  h1->SetLineColor(0);
	  h1->SetMarkerSize(1.1);
	  h1->SetMarkerStyle(3);
	  h2->SetLineColor(kRed);
	  h2->SetLineStyle(7);
	  h2->Draw();
	  h1->Draw("samesh*");
	} else {
	  h1->SetMarkerSize(1.3);
	  h1->SetMarkerStyle(3);
	  h2->SetMarkerSize(1.1);
	  h2->SetMarkerStyle(8);
	  h2->SetMarkerColor(kRed);
	  h2->Draw("e");
	  h1->Draw("samese");
	}
      
      } else {
	double max = 1.1*h2->GetMaximum();
      
	h1->SetMaximum(max);
	h2->SetMaximum(max);
      
	if(!drawWithErrors) {
	  h1->SetLineColor(0);
	  h1->SetMarkerSize(1.1);
	  h1->SetMarkerStyle(3);
	  h2->SetLineColor(kRed);
	  h2->SetLineStyle(7);
	  TString histtitle = fname1+" (black) " + fname2 + " (red)";
	  h2->SetTitle(histtitle.Data());
	  h1->SetTitle(histtitle.Data());
	  h1->Draw();
	  h2->Draw("samesh*");
	} else {
	  h1->SetMarkerSize(1.3);
	  h1->SetMarkerStyle(3);
	  h2->SetMarkerSize(1.1);
	  h2->SetMarkerStyle(8);
	  h2->SetMarkerColor(kRed);
	  TString histtitle = fname1+" (black) " + fname2 + " (red)";
	  h2->SetTitle(histtitle.Data());
	  h1->SetTitle(histtitle.Data());
	  h1->Draw("e");
	  h2->Draw("samese");
	}

      }
      TPaveText ksPt(0,0, 0.35, 0.05, "NDC");
      ksPt.AddText(Form("P(KS)=%g, diffBins=%g, eblk %g ered %g",ksProb, bDiff, h1->GetEntries(), h2->GetEntries()));
      ksPt.Draw();
      
        
      if(i < v_commonBranches.size() - 1) {
	c1->SaveAs("diff.ps(");
	c1->SetLogy();
	//if the canvas has been divided, want to set the logy
	for(int ii = 0; ii < c1->GetListOfPrimitives()->GetSize(); ii++) {
	  if(string(c1->GetListOfPrimitives()->At(ii)->ClassName()) != "TVirtualPad")
	    continue;
	  TVirtualPad *vPad = (TVirtualPad*)c1->GetListOfPrimitives()->At(ii);
	  if(vPad != NULL)
	    vPad->SetLogy();
	}
	c1->SaveAs("diff.ps(");
	c1->SetLogy(0);
      } else {
	cout << "done" << endl;
	c1->SaveAs("diff.ps(");
	c1->SetLogy();
	for(int ii = 0; ii < c1->GetListOfPrimitives()->GetSize(); ii++) {
	  if(string(c1->GetListOfPrimitives()->At(ii)->ClassName()) != "TVirtualPad")
	    continue;
	  TVirtualPad *vPad = (TVirtualPad*)c1->GetListOfPrimitives()->At(ii);
	  if(vPad != NULL)
	    vPad->SetLogy();
	}
	c1->SaveAs("diff.ps)");
	c1->SetLogy(0);
      }
    
  }//for loop
   
  //c1->SaveAs("diff.ps)");  
}