Example #1
0
File: store.C Project: XuQiao/HI
void store(){
	 if (!TClass::GetDict("NBD")) {
                gROOT->ProcessLine(".L /afs/cern.ch/user/q/qixu/CMSSW_6_2_5/src/Centrality/NBD_Glauber_fit/NBD/NBDclass.C+");
        }
	TH1::AddDirectory(kFALSE); 
	int Gth=atoi(getenv("GTH"));
	int sth=atoi(getenv("STH"));
	NBD *l;
	struct para1 var;
        if(sth==0){TString dirname = "std"; var = var1; if(Gth<nGlau) l = new NBD(datafile,stdGlaulist[Gth],histoname);else l = new NBD(datafile,stdGlaulist[0],histoname);}
        else if(sth==1){TString dirname ="Gri055"; var = var2; if(Gth<nGlau) l = new NBD(datafile,Gri055Glaulist[Gth],histoname);else l = new NBD(datafile,Gri055Glaulist[0],histoname);}
        else {TString dirname ="Gri101"; var = var3; if(Gth<nGlau) l = new NBD(datafile,Gri101Glaulist[Gth],histoname);else l = new NBD(datafile,Gri101Glaulist[0],histoname);}
	l->initmu(var.mumin,var.mumax,var.mustep);
     	l->initk(var.kmin,var.kmax,var.kstep);
	if(Gth<nGlau)
        	l->initx(var.xmin,var.xmax);
	else if(Gth-nGlau==0)
		l->initx(var.xmin-binshift,var.xmax);
	else
		l->initx(var.xmin+binshift,var.xmax);
//	l->fit();

 	if(sth==0) l->assign(bestlist1[Gth].mubest,bestlist1[Gth].kbest);
	else if(sth==1) l->assign(bestlist2[Gth].mubest,bestlist2[Gth].kbest);
	else l->assign(bestlist3[Gth].mubest,bestlist3[Gth].kbest);

        l->initN(bin,N,method);
        l->calcvar();
	TFile *outfile = new TFile(outG,"Update");
	if(Gth==0 && sth==0){
	l->dataname.Write("dataname",TObject::kOverwrite);
	l->histoname.Write("histoname",TObject::kOverwrite);
	}
	TDirectory *dir = outfile->GetDirectory(dirname);
	if (!dir) {outfile->mkdir(dirname);	TDirectory *dir = outfile->GetDirectory(dirname);}
	dir->cd();
	TString name;
	if(Gth==0)
		name = "G0";
	else if(Gth<nGlau)
		name = Form("Glau_%d",Gth);
	else
		name = Form("bin_%d",Gth-nGlau+1);
	TDirectory *subdir = dir->GetDirectory(name);
	if(!subdir) {dir->mkdir(name);	TDirectory *subdir = dir->GetDirectory(name);}
	subdir->cd();
	l->method.Write("method",TObject::kOverwrite);
	l->Glaubername.Write("Glaubername",TObject::kOverwrite);
	l->xmin.Write("xmin",TObject::kOverwrite);l->xmax.Write("xmax",TObject::kOverwrite);
	l->mubest.Write("mubest",TObject::kOverwrite);l->kbest.Write("kbest",TObject::kOverwrite);
	l->chis.Write("chis",TObject::kOverwrite);l->Ndf.Write("Ndf",TObject::kOverwrite);
	l->NcollAver.Write("NcollAver",TObject::kOverwrite);l->NpartAver.Write("NpartAver",TObject::kOverwrite);l->BAver.Write("BAver",TObject::kOverwrite);
	l->centbin.Write("centbin",TObject::kOverwrite);	l->kpoint.Write("kpoint",TObject::kOverwrite);
	l->centbin_.Write("centbin_",TObject::kOverwrite);	l->kpoint_.Write("kpoint_",TObject::kOverwrite);
	l->Npartdis->Write();
        l->Grgrid->Write("Grgrid",TObject::kOverwrite);
        outfile->Close();

}
Example #2
0
void compareHistos( char *Current, char *Reference=0 ) {

    TText* te = new TText();
    te->SetTextSize(0.1);

    TFile * curfile = new TFile( TString(Current)+".root" );
    TFile * reffile = curfile;
    if (Reference) reffile = new TFile(TString(Reference)+".root");


    char * prefix="DQMData/MixingV/Mixing";
//1-Dimension Histogram
    TDirectory * refDir=reffile->GetDirectory(prefix);
    TDirectory * curDir=curfile->GetDirectory(prefix);
    TList* list = refDir->GetListOfKeys();
    TObject*  object = list->First();
    int iHisto = 0;
    char title[50];
    while (object) {
        // find histo objects
        std::cout << " object :" << object->GetName() << std::endl;
        TProfile * h1 = dynamic_cast<TProfile*>( refDir->Get(object->GetName()));
        TProfile * h2 = dynamic_cast<TProfile*>( curDir->Get(object->GetName()));
        bool isHisto = (refDir->Get(object->GetName()))->InheritsFrom("TProfile");
        std::cout << " isHisto = " << isHisto << std::endl;
        if (isHisto && h1 && h2 && *h1->GetName()== *h2->GetName()) {
            iHisto++;
            char title[50];
            // draw and  compare
            std::cout << " Start draw and compare" << std::endl;
            TCanvas c1;
            TProfile htemp2;
            h2->Copy(htemp2);// to keep 2 distinct histos

            h1->SetLineColor(2);
            htemp2.SetLineColor(3);
            h1->SetLineStyle(3);
            h1->SetMarkerColor(3);
            htemp2.SetLineStyle(5);
            htemp2.SetMarkerColor(5);
            TLegend leg(0.1, 0.15, 0.2, 0.25);
            leg.AddEntry(h1, "Reference", "l");
            leg.AddEntry(&htemp2, "New ", "l");

            h1->Draw();
            htemp2.Draw("Same");
            leg.Draw();
            sprintf(title,"%s%s", object->GetName(),".gif");
            c1.Print(title);
        }

        // go to next object
        object = list->After(object);
    }
}
Example #3
0
void DoCompare( char *Current, char *Reference=0 ){

 TText* te = new TText();
 te->SetTextSize(0.1);
 
 gROOT->ProcessLine(".x HistoCompare.C");
 HistoCompare * myPV = new HistoCompare();

 TFile * curfile = new TFile( TString(Current)+".root" );
 TFile * reffile = curfile;
 if (Reference) reffile = new TFile(TString(Reference)+".root");


 char * prefix="DQMData/MixingV/";
 //1-Dimension Histogram
 TDirectory * refDir=reffile->GetDirectory(prefix);
 TDirectory * curDir=curfile->GetDirectory(prefix);
 TList* list = refDir->GetListOfKeys();  
 TObject*  object = list->First();
 int iHisto = 0; char title[50];
 while (object) {
   // find histo objects
   TH1F * h1 = dynamic_cast<TH1F*>( refDir->Get(object->GetName()));
   TH1F * h2 = dynamic_cast<TH1F*>( curDir->Get(object->GetName()));
   bool isHisto = (refDir->Get(object->GetName()))->InheritsFrom("TH1F");
   if (isHisto && h1 && h2 && *h1->GetName()== *h2->GetName()) {
     iHisto++;
      char title[50];
      // draw and  compare
   TCanvas c1;
   TH1F htemp2;
   h2->Copy(htemp2);// to keep 2 distinct histos

   h1->SetLineColor(2);
   htemp2.SetLineColor(3);
   h1->SetLineStyle(3);
   htemp2.SetLineStyle(5);
   TLegend leg(0.1, 0.15, 0.2, 0.25);
   leg.AddEntry(h1, "Reference", "l");
   leg.AddEntry(&htemp2, "New ", "l");

   h1->Draw();
   htemp2.Draw("Same"); 
   leg.Draw();
   myPV->PVCompute(h1,&htemp2, te);
   sprintf(title,"%s%s", object->GetName(),".eps");
   c1.Print(title);
   }
   // go to next object
   object = list->After(object);
   }
}
Example #4
0
void FileSaver::writeObjsInFolder(string folder, bool recreate)
{
	cout<<"*** Updating "<<filename.c_str()<<" file in "<< folder << endl;
	TFile * fileFinalPlots;

	if(recreate) fileFinalPlots=TFile::Open(filename.c_str(), "RECREATE");
	else fileFinalPlots=TFile::Open(filename.c_str(), "UPDATE");

	if (!fileFinalPlots->GetDirectory(folder.c_str()))
		fileFinalPlots->mkdir(folder.c_str());
	fileFinalPlots->cd   (folder.c_str());
	cout<<"vrce: "<<fArr->At(0)<<endl;
	if(fArr->At(0)){
		cout<<fArr->At(0)->GetName()<<endl; 	
		for (int i = 0; i <= fArr->GetLast(); i++){
			cout<<fArr->At(i)<<" "<<fArr->At(i)->GetName()<<endl;
			fArr->At(i)->Write(fArr->At(i)->GetName(),2);
			cout<<"Object saved ..."<<endl;
		}
	}
	fileFinalPlots->Flush();
	fileFinalPlots->Write();
        fileFinalPlots->Close();
        fArr->Clear();
        return;
}
Example #5
0
void create_module_info(TString dir = "/castor/cern.ch/user/r/rougny/vcalH2L_7/GainRun_173484"){
  ofstream t;
  t.open("module_info.txt");
  if(! t.is_open()){
    cout << "[create_module_info] Could not open output txt file. Exiting ..." << endl;
    exit(1);
  }

  for(int i=0 ; i<40 ; ++i){
    ostringstream f_str("");
    f_str << "rfio://" << dir << "/" << i << ".root";
    cout << "Opening file : " << f_str.str() << endl;
    TFile* f = TFile::Open(f_str.str().c_str() , "READ");
    vector<TString> dir_list = makedirlist(f , "Module");
    
    for(int m = 0 ; m < dir_list.size() ; ++m){
      
      TDirectory* dir = f->GetDirectory(dir_list[m]);
      int detid = getDetId(((TH1*) dir->Get(((TKey*) dir->GetListOfKeys()->At(0))->GetName()))->GetName());
    
      t << detid << "  " << i << "  " << dir_list[m].Remove(0,dir_list[m].First('y')+2) << endl;
    
    }


    f->Close();
  
  }

  t.close();

}
Example #6
0
void FitOmega_OneTarget(char *rootFile, char* fDir="ReconCuts", Int_t iRun=0, Int_t iTgt=0, Int_t iCut=0, Int_t iFit=3, Int_t iClose=1)
{
	Int_t i;
	Float_t yield;

	TH1D *hist; // original histogram

    char hname[50];
	char plotFilePrefix[100];
    
	// data files contain the trees
	printf("Analyzing file %s\n",rootFile);  
	TFile *fd = new TFile(rootFile,"READ"); // open up the ROOT file

    TDirectory *tmp = fd->GetDirectory(fDir);
	
    sprintf(hname,"%s",HistName[iCut]);
    cout << hname << endl;
	hist = (TH1D*)tmp->Get(hname); // get the histogram from the ROOT file

    sprintf(plotFilePrefix,"FitOmega_%s_%s",RunName[iRun],hname);
    
    yield = FitOmega(hist,plotFilePrefix);//, iFit, iClose);

	// open text file for the yields
	char OutFile[100];
	sprintf(OutFile,"%s.yld",plotFilePrefix);
	ofstream fout(OutFile);
    
	fout<<RunName[iRun]<<"\t"<<TgtName[iTgt]<<"\t"<<yield<<"\t"<<sqrt(yield)<<endl;

	fout.close(); // close the text file
//	fd->Close();  // close ROOT file
}
Example #7
0
std::pair<TH3F*,TH3F*> getEffHists(const char *file, const char *dirC, 
				     const char *histN, const char *histD){

     TFile *efile = new TFile(file,"read");
     TDirectoryFile *efileDIR = (TDirectoryFile*) efile->GetDirectory(dirC);

     TIter next(efileDIR->GetListOfKeys());
     TKey *key;

     Char_t name[100];

     TH3F *hpneff3d=0;
     TH3F *hpdeff3d=0;

     while ((key=(TKey*)next())) {
	sprintf(name,"%s",key->GetName());
	if(strcmp((key->GetName()),(histN))==0){
	  //cout<<"[getEffHists] Your numerator for Eff "<<name<<endl; 
	   hpneff3d = (TH3F*) efileDIR->Get(name);
	}
	if(strcmp((key->GetName()),(histD))==0){
	  //cout<<"[getEffHists] Your denominator for Eff "<<name<<endl; 
	   hpdeff3d = (TH3F*) efileDIR->Get(name);
	}
     }

     //efileDIR->Close(); 
     //efile->Close(); 
     return std::pair<TH3F*,TH3F*>(hpneff3d,hpdeff3d);
  }
int produceEnergyHistos(CSPrereqs& csp)
{
    cout << endl << "Mapping " << csp.name << " TOF histogram to energy domain..." << endl;

    // open input file
    TFile* inputFile = new TFile(inputFileName.c_str(),"READ");
    if(!inputFile->IsOpen())
    {
        cerr << "Error: failed to open " << inputFileName << "  to fill histos." << endl;
        return 1;
    }

    // create output file
    TFile* outputFile = new TFile(outputFileName.c_str(),"RECREATE");

    for(auto& channelName : config.cs.DETECTOR_NAMES)
    {
        TDirectory* detectorDirectory = inputFile->GetDirectory(channelName.c_str());
        if(!detectorDirectory)
        {
            cerr << "Error: failed to find " << channelName << " directory in " << inputFileName << "." << endl;
            return 1;
        }

        TDirectory* outputDirectory = outputFile->mkdir(channelName.c_str(),channelName.c_str());

        // find TOF histograms in input file
        for(int i=0; i<config.target.TARGET_ORDER.size(); i++)
        {
            string targetName = config.target.TARGET_ORDER[i];
            string TOFHistoName = targetName + "TOFCorrected";

            detectorDirectory->cd();

            TH1D* TOF = (TH1D*)detectorDirectory->Get(TOFHistoName.c_str());
            if(!TOF)
            {
                cerr << "Error: failed to open " << TOFHistoName << " in " << inputFileName << endl;
                return 1;
            }

            outputDirectory->cd();

            TH1D* correctedEnergy = convertTOFtoEnergy(TOF, targetName + "Energy");
            TOF->Write();
            correctedEnergy->Write();
        }
    }

    outputFile->Close();
    inputFile->Close();

    return 0;
}
Example #9
0
void Histogrammer::write_histograms(std::string folderS, std::vector<TH1F*> histVector){

	TFile* outFile = new TFile((folderS+"/hist_"+title+".root").c_str(), "RECREATE");
	
	for( std::map< std::string, TH1F* >::iterator it = hists.begin(); it != hists.end(); ++it){
		it->second->SetDirectory(outFile->GetDirectory(""));
		it->second->Write();
		it->second->SetDirectory(0);
	}

	for( std::vector<TH1F*>::iterator it = histVector.begin(); it != histVector.end(); ++it){
		(*it)->SetDirectory(outFile->GetDirectory(""));
		(*it)->Write();
		(*it)->SetDirectory(0);
	}

	for( std::map< std::string, TH2F* >::iterator it = hists2d.begin(); it != hists2d.end(); ++it){
		it->second->SetDirectory(outFile->GetDirectory(""));
		it->second->Write();
		it->second->SetDirectory(0);
	}

	outFile->Close();
}
void CompareCFLADiffCuts()
{
  TFile newFile("~/Analysis/lambda/AliAnalysisLambda/Results/2016-01/15-NoOppChargeCut/All/CFs.root");
  TDirectory *newDir = newFile.GetDirectory("Merged");
  vector<TH1D*> newCFs;
  newCFs.push_back((TH1D*)newDir->Get("CFLamALam010"));
  newCFs.push_back((TH1D*)newDir->Get("CFLamALam1030"));
  newCFs.push_back((TH1D*)newDir->Get("CFLamALam3050"));

  TFile oldFile("~/Analysis/lambda/AliAnalysisLambda/Results/2016-01/08-NewAvgSepCuts/All/CFs.root");
  TDirectory *oldDir = oldFile.GetDirectory("Merged");
  vector<TH1D*> oldCFs;
  oldCFs.push_back((TH1D*)oldDir->Get("CFLamALam010"));
  oldCFs.push_back((TH1D*)oldDir->Get("CFLamALam1030"));
  oldCFs.push_back((TH1D*)oldDir->Get("CFLamALam3050"));

  TFile *compareFile = new TFile("Compare.root","update");
  TDirectory *dir = compareFile->GetDirectory("Delta");
  if(!dir) dir = compareFile->mkdir("Delta");
  for(UInt_t i = 0; i < newCFs.size(); i++) {
    // TH1D *ratio = (TH1D*)newCFs[i]->Clone();
    // TString name = ratio->GetName();
    // ratio->SetName(name + "Ratio");
    // ratio->SetTitle(name + "Ratio");
    // ratio->Divide(oldCFs[i]);

    // TH1D *barlowRatio = ComputeRogerBarlowRatio(newCFs[i], oldCFs[i]);
    // barlowRatio->SetName(name + "BarlowRatio");
    // barlowRatio->SetTitle(name + "BarlowRatio");

    TString name = newCFs[i]->GetName();
    TH1D *barlowDifference = ComputeRogerBarlowDifference(newCFs[i], oldCFs[i]);
    barlowDifference->SetName(name + "BarlowDifference");
    barlowDifference->SetTitle(name + "BarlowDifference");
    
    dir->cd();
    // ratio->Write();
    // barlowRatio->Write();
    barlowDifference->Write(barlowDifference->GetName(), TObject::kOverwrite);
    Chi2TestWithZero(barlowDifference);
    FitWithConstant(barlowDifference, compareFile);
    // LookAtMean(barlowDifference);
    RebinHist(barlowDifference, compareFile);
    ManuallyRebin(barlowDifference, compareFile);
  }
    
  compareFile->Close();
}
void CalibrationScanAnalysis::getSummaries(FileList::const_iterator file) {
  std::cout << "." << std::flush;
  std::vector<TH1*> result;  
  TFile* input = file->second;
  TDirectory* directory = input->GetDirectory(HISTOPATH);
  TList* histograms = directory->GetListOfKeys();
  TIter next(histograms);
  TKey* key = NULL;
  while ((key = (TKey*)next())) {
    if(TClass(key->GetClassName()).InheritsFrom("TH1")) {
      TH1* h = (TH1*)key->ReadObj();
      result.push_back(h);
    }
  }
  summaries_[file->first] = result;
}
Example #12
0
//
// OverlayEC_xy_local - overlay histogram of EC x vs y
//
//                  fAna = output from eg2a DMS
//                  fDir = ROOT directory
//                  HistName1 = 1st histogram name
//                  HistName2 = 2nd histogram name
//                  target = target name
//
void OverlayEC_xy_local(char *fAna="Ana.root", char *fDir, char *HistName1, char *HistName2, char *target)
{
	Int_t i;
    TH2D *hist1[6];
    TH2D *hist2[6];

    // Canvas to plot histogram
	TCanvas *c1 = new TCanvas("c1","c1",0,0,1200,800);
	c1->SetBorderMode(1);  //Bordermode (-1=down, 0 = no border, 1=up)
	c1->SetBorderSize(5);
	gStyle->SetOptStat(1111);
	c1->SetFillStyle(4000);
    c1->Divide(3,2);
    
	// data files contain the trees
	printf("Analyzing file %s\n",fAna);
	TFile *fm = new TFile(fAna,"READ");
    TDirectory *tmp = fm->GetDirectory(fDir);
    
    for(i=0; i<NSECTORS; i++){
        gPad->SetLeftMargin(Lmar);
        gPad->SetRightMargin(Rmar);
        gPad->SetFillColor(0);
        
        c1->cd(i+1);
        sprintf(hname,"EC_XvsY_local_%s%i",HistName1,i+1);
        hist1[i] = (TH2D*)tmp->Get(hname);
        sprintf(htitle,"Sector %i, %s",i+1,target);
        hist1[i]->SetTitle(htitle);
        hist1[i]->GetXaxis()->CenterTitle();
        hist1[i]->GetYaxis()->CenterTitle();
        hist1[i]->GetYaxis()->SetTitleOffset(yoff);
        hist1[i]->Draw("colz");
        
        sprintf(hname,"EC_XvsY_local_%s%i",HistName2,i+1);
        hist2[i] = (TH2D*)tmp->Get(hname);
        hist2[i]->SetMarkerColor(1);
        hist2[i]->Draw("same");

    }
    
    sprintf(OutCan,"OL_EC_XvsY_local_%s_VS_%s_%s.gif",HistName1,HistName2,target);
    c1->Print(OutCan);
    sprintf(OutCan,"OL_EC_XvsY_local_%s_VS_%s_%s.eps",HistName1,HistName2,target);
    c1->Print(OutCan);
}
void addAndWeight(TString directory, TString plot, TFile& outputfile, double scalingFactor)
{
  // get the histograms, erase existing at the beginning
  hists_.clear();
  loadingHists(directory+"/"+plot);  
  // normalize to luminosity (and add samples)
  combineFiles(scalingFactor);
  // define output plot
  TH1F* weightedPlot=(TH1F*)hists_[files_.size()]->Clone(); 
  // write output to directory
  if(outputfile.GetDirectory(directory)==0){
    outputfile.mkdir(directory);
    outputfile.cd(directory);
  }
  weightedPlot->Write(plot);
  std::cout << " " << plot;
}
Example #14
0
File: merge.C Project: XuQiao/HI
void merge(){
	if (!TClass::GetDict("NBD")) {
		gROOT->ProcessLine(".L /afs/cern.ch/user/q/qixu/CMSSW_6_2_5/src/Centrality/NBD_Glauber_fit/NBD/NBDclass.C++");
	}

	TFile *f;
	f=TFile::Open(Form("G.root"),"ReadOnly");
	TFile *fg = new TFile("graph.root","Update");
	TDirectory *dir;
	TList *def, *tl;
	TKey *key;
	TString dirname;
	for(int sth=0; sth<3; sth++){
	if(sth==0) dirname = "std";
        else if(sth==1) dirname ="Gri055";
        else  dirname ="Gri101";
	dir = f->GetDirectory(dirname);
	def = new TList();
	int iGlau=0;
	//int iGlau=atoi(getenv("GTH"));
	tl = dir->GetListOfKeys();
	for(iGlau=0; iGlau<nGlau; iGlau++){
		key = ((TKey*) tl->At(iGlau));
		NBD* temp = (NBD*)key->ReadObj();
		def->Add(temp);
	}
	
	NBD *n0 = (NBD*)def->At(0);
	n0->calcsys(def);
	TString op;
	for(int option=0;option<3;option++){
	if(option==0) op=Form("%s_Ncoll",dirname.Data());
	else if(option==1) op=Form("%s_Npart",dirname.Data());
	else op=Form("%s_B",dirname.Data());
	TGraphErrors* gr = n0->DrawGraph(option);
	gr->Write(op);
	}
	}
	fg->Close();
	f->Close();
}
void rescale2SM4(bool armed, const char* filename, double ecms=7., double mass=-1)
{
  unsigned int debug = 1;
  std::vector<std::string> histnames; histnames.clear();
  if( debug>0 ){
    std::cout << "file  = " << filename << std::setw(10);
    std::cout << "mass  = " << mass     << std::setw(10);
    std::cout << "armed = " << armed    << std::endl;
  }
  TFile* file = new TFile(filename, "update");
  TIter nextDirectory(file->GetListOfKeys());
  std::vector<std::string> buffer; TKey* idir;
  while((idir = (TKey*)nextDirectory())){
    buffer.clear();
    if( idir->IsFolder() ){
      file->cd(); // make sure to start in directory head 
      if( debug>1 ){ std::cout << "Found directory: " << idir->GetName() << std::endl; }
      if( file->GetDirectory(idir->GetName()) ){
	file->cd(idir->GetName()); // change to sub-directory
	buffer = signalList(idir->GetName(), "", debug);
      }
      // append to the vector of histograms to be rescaled
      for(std::vector<std::string>::const_iterator elem=buffer.begin(); elem!=buffer.end(); ++elem){
	histnames.push_back(*elem);
      }
      if(debug>1){
	std::cout << "added " << buffer.size() << " elements to histnames [" << histnames.size() << "] for directory " << idir->GetName() << std::endl;
      }
    }
  }
  // pick up histograms which are not kept in an extra folder
  file->cd(); buffer.clear();
  buffer = signalList("", "", debug);
  // append to the vector of histograms to be rescaled
  for(std::vector<std::string>::const_iterator elem=buffer.begin(); elem!=buffer.end(); ++elem){
    histnames.push_back(*elem);
  }
  if(debug>1){
    std::cout << "added " << buffer.size() << " elements to histnames [" << histnames.size() << "] for file head" << std::endl;
  }

  HiggsCSandWidth smx; HiggsCSandWidthSM4 sm4;
  for(std::vector<std::string>::const_iterator hist=histnames.begin(); hist!=histnames.end(); ++hist){
    int type = 0;
    // determine mass from hostogram name
    std::string strippedName = (hist->find("/")!=std::string::npos ? hist->substr(hist->find("/")+1) : *hist);
    std::string massName;
    if(strippedName.find("ggH")!=std::string::npos) {
      massName = strippedName.substr(3, 3); type = 1;
    }
    if(strippedName.find("qqH")!=std::string::npos) {
      massName = strippedName.substr(3, 3); type = 2;
    }
    if(strippedName.find("VH" )!=std::string::npos) {
      massName = strippedName.substr(2, 3); type = 3;
    }
    if( type==0 ) { 
      std::cout << "not supported process" << std::endl; 
      continue; 
    }
    else {
      file->cd();
      float mdx = atof(massName.c_str());
      TH1F* h = (TH1F*)file->Get(hist->c_str());
      float smxXS = type==1 ? smx.HiggsCS(type, mdx, ecms, true) : 0.; float smxBR = smx.HiggsBR(2, mdx, true); 
      float sm4XS = type==1 ? sm4.HiggsCS(type, mdx, ecms, true) : 0.; float sm4BR = sm4.HiggsBR(2, mdx, true);
      if( debug>1 ){
	std::cout << "  --  hist  = " << std::setw(10) << h->GetName() << std::endl
		  << "  --  type  = " << std::setw(10) << type << std::endl
		  << "  --  mass  = " << std::setw(10) << mdx << std::endl
		  << "  --  SM    = " << std::setw(10) << smxXS*smxBR << " (BR = " << smxBR << ")"  << std::endl
		  << "  --  SM4   = " << std::setw(10) << sm4XS*sm4BR << " (BR = " << sm4BR << ")"  << std::endl
		  << "  --  scale = " << std::setw(10) << (type==1 ? sm4XS*sm4BR/(smxXS*smxBR) : 0) << std::endl
		  << std::endl;
      }
      if( type==1 ){ h->Scale(sm4XS*sm4BR/(smxXS*smxBR)); }
      //scaling old style
      //if( type==2 ){ h->Scale(sm4BR/smxBR); }
      //if( type==3 ){ h->Scale(sm4BR/smxBR); }
      // scaling new style
      if( type==2 ){ h->Scale(0.); }
      if( type==3 ){ h->Scale(0.); }
      if(armed){
	if(hist->find("/")!=std::string::npos){
	  file->cd(hist->substr(0, hist->find("/")).c_str());
	}
	else{
	  file->cd();
	}
	h->Write(strippedName.c_str(), TObject::kOverwrite); 
      }
    }
  }
  file->Close();
  return;
}
Example #16
0
void noise_plots(char* newFile="DQM_fastsim.root",char* refFile="DQM_fullsim.root") {

  gROOT ->Reset();
  gROOT ->SetBatch();

  //=========  settings ====================
  gROOT->SetStyle("Plain");
  gStyle->SetPadGridX(kTRUE);
  gStyle->SetPadGridY(kTRUE);
  gStyle->SetPadRightMargin(0.07);
  gStyle->SetPadLeftMargin(0.13);
  char* refLabel("reference histogram");
  char* newLabel("new histogram");

  delete gROOT->GetListOfFiles()->FindObject(refFile);
  delete gROOT->GetListOfFiles()->FindObject(newFile); 
  
  TText* te = new TText();
  TFile * sfile = new TFile(newFile);
  TDirectory * sdir=gDirectory;
  TFile * rfile = new TFile(refFile);
  TDirectory * rdir=gDirectory;

  if(sfile->GetDirectory("DQMData/Run 1/HcalRecHitsV")) sfile->cd("DQMData/Run 1/HcalRecHitsV/Run summary/HcalRecHitTask");
  else if(sfile->GetDirectory("DQMData/HcalRecHitsV/HcalRecHitTask"))sfile->cd("DQMData/HcalRecHitsV/HcalRecHitTask");
  sdir=gDirectory;
  TList *sl= sdir->GetListOfKeys();

  if(rfile->GetDirectory("DQMData/Run 1/HcalRecHitsV")) rfile->cd("DQMData/Run 1/HcalRecHitsV/Run summary/HcalRecHitTask");
  else if(rfile->GetDirectory("DQMData/HcalRecHitsV/HcalRecHitTask"))rfile->cd("DQMData/HcalRecHitsV/HcalRecHitTask");
  rdir=gDirectory;
  TList *rl= rdir->GetListOfKeys();

  TCanvas *canvas;

  TH1F *sh1,*rh1;
  TH1F *sh2,*rh2;
  TH1F *sh3,*rh3;
  TH1F *sh4,*rh4;
  TH1F *sh5,*rh5;
  

  rdir->GetObject("e_hb",rh1);
  sdir->GetObject("e_hb",sh1);
  rdir->GetObject("e_he",rh2);
  sdir->GetObject("e_he",sh2);
  rdir->GetObject("e_hfl",rh3);
  sdir->GetObject("e_hfl",sh3);
  rdir->GetObject("e_hfs",rh4);
  sdir->GetObject("e_hfs",sh4);
  rdir->GetObject("e_ho",rh5);
  sdir->GetObject("e_ho",sh5);

  rh1->GetXaxis()->SetTitle("E");
  rh1->GetYaxis()->SetTitleSize(0.05);
  rh1->GetYaxis()->SetTitleOffset(1.2);
  //  rh1->GetYaxis()->SetRangeUser(0.4,1.);
  //  sh1->GetYaxis()->SetRangeUser(0.4,1.);
  //  rh1->Rebin(5);
  //  sh1->Rebin(5);
  NormalizeHistograms(rh1,sh1);
  double maxH = max(rh1,sh1)*1.1;
  rh1->GetYaxis()->SetRangeUser(0.,maxH);
  sh1->GetYaxis()->SetRangeUser(0.,maxH);

  rh2->GetXaxis()->SetTitle("E");
  rh2->GetYaxis()->SetTitleSize(0.05);
  rh2->GetYaxis()->SetTitleOffset(1.2);
  //  rh2->GetYaxis()->SetRangeUser(0.4,1.);
  //  sh2->GetYaxis()->SetRangeUser(0.4,1.);
  //  rh2->Rebin(5);
  //  sh2->Rebin(5);
  NormalizeHistograms(rh2,sh2);
  double maxH = max(rh2,sh2)*1.1;
  rh2->GetYaxis()->SetRangeUser(0.,maxH);
  sh2->GetYaxis()->SetRangeUser(0.,maxH);

  rh3->GetXaxis()->SetTitle("E");
  rh3->GetYaxis()->SetTitleSize(0.05);
  rh3->GetYaxis()->SetTitleOffset(1.2);
  NormalizeHistograms(rh3,sh3);
  double maxH = max(rh3,sh3)*1.1;
  rh3->GetYaxis()->SetRangeUser(0.,maxH);
  sh3->GetYaxis()->SetRangeUser(0.,maxH);

  rh4->GetXaxis()->SetTitle("E");
  rh4->GetYaxis()->SetTitleSize(0.05);
  rh4->GetYaxis()->SetTitleOffset(1.2);
  NormalizeHistograms(rh4,sh4);
  double maxH = max(rh4,sh4)*1.1;
  rh4->GetYaxis()->SetRangeUser(0.,maxH);
  sh4->GetYaxis()->SetRangeUser(0.,maxH);

  rh5->GetXaxis()->SetTitle("E");
  rh5->GetYaxis()->SetTitleSize(0.05);
  rh5->GetYaxis()->SetTitleOffset(1.2);
  NormalizeHistograms(rh5,sh5);
  double maxH = max(rh5,sh5)*1.1;
  rh5->GetYaxis()->SetRangeUser(0.,maxH);
  sh5->GetYaxis()->SetRangeUser(0.,maxH);

  canvas = new TCanvas("Noise","Noise",1000,1400);


  TH1F * r[5]={rh1,rh2,rh3,rh4,rh5};
  TH1F * s[5]={sh1,sh2,sh3,sh4,sh5};
  plotBuilding(canvas,s, r,5,
	       te,"UU",-1);//, 1, true, 0);

  canvas->cd();
  l = new TLegend(0.50,0.14,0.90,0.19);
  l->SetTextSize(0.016);
  l->SetLineColor(1);
  l->SetLineWidth(1);
  l->SetLineStyle(1);
  l->SetFillColor(0);
  l->SetBorderSize(3);
  l->AddEntry(rh1,refLabel,"LPF");
  l->AddEntry(sh1,newLabel,"LPF");
  l->Draw();
  TString namepdf = "hcal_noise.pdf";
  canvas->Print(namepdf);   
  delete l;

  delete canvas;

}
Example #17
0
// 
// PlotOmega_CutIndex - plot omega inv. mass for a specific cut selection
//                  
//                  fAna = output from eg2a DMS
//                  tgtIndex = target index
//                  bankIndex = bank name
//                  chanLo = lower bin
//                  chanHi = upper bin
//
void PlotOmega_CutIndex(char *fAna, Int_t histIndex =0, Int_t tgtIndex = 0, Int_t bankIndex = 0, Int_t chanLo = 0, Int_t chanHi=0)
{
    Int_t i;
    char OutCan[100];
    char strname[100];
    char hname[50];
    char title[100];
    char strname[100];
    char legLabel[50];
    
    TH1D *h1D[10];
    
    Check_HistIndex(histIndex);
    Check_TgtIndex(tgtIndex);
    Check_BankIndex(bankIndex);
    Check_CutIndex(chanLo);
    Check_CutIndex(chanHi);
    Check_CutLoHi(chanLo,chanHi);
    
	// Canvas to plot histogram
	TCanvas *c1 = new TCanvas("c1","c1",0,0,600,600);
	c1->SetBorderMode(1);  //Bordermode (-1=down, 0 = no border, 1=up)
	c1->SetBorderSize(5); 
	gStyle->SetOptStat(0);
	c1->SetFillStyle(4000);
	
	// data files contain the trees
	printf("Analyzing file %s\n",fAna);  
	TFile *fm = new TFile(fAna,"READ");
    TDirectory *tmp = fm->GetDirectory(TgtName[tgtIndex]);
    
	c1->cd();
	gPad->SetLeftMargin(Lmar);
	gPad->SetRightMargin(Rmar);
	gPad->SetFillColor(0);
    
    TLegend *leg = new TLegend(0.6,0.5,1.0,0.875);
    
    sprintf(hname,"%s%s",HistName[histIndex],TgtName[tgtIndex]);
	TH2D *h2D = (TH2D*)tmp->Get(hname);
    
    for(i=chanLo; i<chanHi+1; i++){
        sprintf(strname,"%s_%i",hname,i);
        h1D[i] = (TH1D*)h2D->ProjectionX(strname,i+1,i+1,"");
    
        sprintf(title,"Target: %s",TgtName[tgtIndex]);
        h1D[i]->SetTitle(title);
        h1D[i]->GetXaxis()->CenterTitle();
        h1D[i]->GetYaxis()->CenterTitle();
        h1D[i]->GetYaxis()->SetTitle("Counts");
        h1D[i]->GetYaxis()->SetTitleOffset(yoff);
        h1D[i]->SetLineWidth(2);
        if(chanLo!=chanHi) h1D[i]->SetLineColor(lcol[i]);
        h1D[i]->Draw(fSame[i]);
        
        sprintf(legLabel,"%s",CutName[i]);
        leg->AddEntry(h1D[i],legLabel,"l");
    }
    
    leg->SetLineColor(0);
    leg->SetFillStyle(0);
    leg->SetHeader(legHeader[histIndex]);
    leg->Draw();
    
	sprintf(OutCan,"PlotOmega_%s_%s_%i_%i.gif",hname,BankName[bankIndex],chanLo,chanHi);
	c1->Print(OutCan);
	sprintf(OutCan,"PlotOmega_%s_%s_%i_%i.eps",hname,BankName[bankIndex],chanLo,chanHi);
	c1->Print(OutCan);
}
Example #18
0
File: store.C Project: XuQiao/HI
void store(int type, int sth=0, int Gth=0){
	TH1::AddDirectory(kFALSE); 
	NBD *l;
	struct para1 var;
        TString dirname;
        double sss=0.1;
	if(sth==0){
	dirname = "std";
	if(Gth<nGlau)
            l = new NBD(datafile,stdGlaulist[Gth],histoname);
	else
            l = new NBD(datafile,stdGlaulist[0],histoname);
	var = var1[Gth];
	l->initmu(bestlist1[Gth].mubest-sss,bestlist1[Gth].mubest+sss,sss/5);
	l->initk(bestlist1[Gth].kbest-sss,bestlist1[Gth].kbest+sss,sss/5);
	l->initf(bestlist1[Gth].fbest-sss,bestlist1[Gth].fbest+sss,sss/5);
	}
        
	else if(sth==1){
	dirname ="Gri055"; 
	if(Gth<nGlau)
            l = new NBD(datafile,Gri055Glaulist[Gth],histoname);
	else
            l = new NBD(datafile,Gri055Glaulist[0],histoname);
	var = var2[Gth];
	l->initmu(bestlist2[Gth].mubest-sss,bestlist2[Gth].mubest+sss,sss/5);
	l->initk(bestlist2[Gth].kbest-sss,bestlist2[Gth].kbest+sss,sss/5);
	l->initf(bestlist2[Gth].fbest-sss,bestlist2[Gth].fbest+sss,sss/5);
	}
        
	else {
	dirname ="Gri101";
	if(Gth<nGlau)
            l = new NBD(datafile,Gri101Glaulist[Gth],histoname);
	else
            l = new NBD(datafile,Gri101Glaulist[0],histoname);
        var = var3[Gth];
	l->initmu(bestlist3[Gth].mubest-sss,bestlist3[Gth].mubest+sss,sss/5);
	l->initk(bestlist3[Gth].kbest-sss,bestlist3[Gth].kbest+sss,sss/5);
	l->initf(bestlist3[Gth].fbest-sss,bestlist3[Gth].fbest+sss,sss/5);
	}

	//l->initmu(var.mumin,var.mumax,var.mustep);
    	//l->initk(var.kmin,var.kmax,var.kstep);
    	//l->initf(var.fmin,var.fmax,var.fstep);
	if(Gth<nGlau)
        	l->initx(var.xmin,var.xmax);
	else if(Gth-nGlau==0)
		l->initx(var.xmin-binshift,var.xmax);
	else
		l->initx(var.xmin+binshift,var.xmax);
if(type==0)
	l->fit();	
if(type==1){
 	if(sth==0) l->assign(bestlist1[Gth].mubest,bestlist1[Gth].kbest,bestlist1[Gth].fbest);
	else if(sth==1) l->assign(bestlist2[Gth].mubest,bestlist2[Gth].kbest,bestlist2[Gth].fbest);
	else l->assign(bestlist3[Gth].mubest,bestlist3[Gth].kbest,bestlist3[Gth].fbest);

        l->initN(bin,N,method);
        l->calcvar();
	TFile *outfile = new TFile(outG,"Update");
	if(Gth==0 && sth==0){
	l->dataname.Write("dataname",TObject::kOverwrite);
	l->histoname.Write("histoname",TObject::kOverwrite);
	}
	TDirectory *dir = (TDirectory*)outfile->GetDirectory(dirname);
	if (!dir) {outfile->mkdir(dirname);	dir = (TDirectory*)outfile->GetDirectory(dirname);}
	dir->cd();
	TString name;
	if(Gth==0)
		name = "G0";
	else if(Gth<nGlau)
		name = Form("Glau_%d",Gth);
	else
		name = Form("bin_%d",Gth-nGlau+1);
	TDirectory *subdir = (TDirectory*)dir->GetDirectory(name);
	if(!subdir) {dir->mkdir(name);	subdir = (TDirectory*)dir->GetDirectory(name);}
	subdir->cd();
	l->method.Write("method",TObject::kOverwrite);
	l->Glaubername.Write("Glaubername",TObject::kOverwrite);
	l->xmin.Write("xmin",TObject::kOverwrite);l->xmax.Write("xmax",TObject::kOverwrite);
	l->mubest.Write("mubest",TObject::kOverwrite);l->kbest.Write("kbest",TObject::kOverwrite);l->fbest.Write("fbest",TObject::kOverwrite);
	l->chis.Write("chis",TObject::kOverwrite);l->Ndf.Write("Ndf",TObject::kOverwrite);
	l->NcollAver.Write("NcollAver",TObject::kOverwrite);l->NpartAver.Write("NpartAver",TObject::kOverwrite);l->BAver.Write("BAver",TObject::kOverwrite);
	l->centbin.Write("centbin",TObject::kOverwrite);	l->kpoint.Write("kpoint",TObject::kOverwrite);
	l->centbin_.Write("centbin_",TObject::kOverwrite);	l->kpoint_.Write("kpoint_",TObject::kOverwrite);
	l->Npartdis->Write("Npartdis",TObject::kSingleKey | TObject::kOverwrite);
	l->Grgrid->Write("Grgrid",TObject::kOverwrite);
        outfile->Close();
}
}
void changeAxis(bool armed, TString iExprMatch,float iMin, const char* filename, const char* pattern="", unsigned int debug=0)
{
  std::vector<std::string> histnames; histnames.clear();
  if( debug>0 ){
    std::cout << "file  = " << filename             << std::endl;
    std::cout << "old   = " << iExprMatch.Data()    << std::endl;    
    std::cout << "armed = " << armed                << std::endl;
  }
  TFile* file = new TFile(filename, "update");
  TIter nextDirectory(file->GetListOfKeys());
  std::vector<std::string> buffer;
  TKey* idir;
  while((idir = (TKey*)nextDirectory())){
    buffer.clear();
    if( idir->IsFolder() ){
      file->cd(); // make sure to start in directory head 
      if( debug>0 ){ std::cout << "Found directory: " << idir->GetName() << std::endl; }
      if( file->GetDirectory(idir->GetName()) ){
	file->cd(idir->GetName()); // change to sub-directory
	buffer = signalList(idir->GetName(), pattern,iExprMatch.Data(), debug);
      }
      // append to the vector of histograms to be rescaled
      for(std::vector<std::string>::const_iterator elem=buffer.begin(); elem!=buffer.end(); ++elem){
	histnames.push_back(*elem);
      }
      if(debug>1){
	std::cout << "added " << buffer.size() << " elements to histnames [" << histnames.size() << "] for directory " << idir->GetName() << std::endl;
      }
    }
  }
  // pick up files which are not kept in an extra folder
  file->cd(); buffer.clear();
  buffer = signalList("", pattern,iExprMatch.Data(), debug);
  // append to the vector of histograms to be rescaled
  for(std::vector<std::string>::const_iterator elem=buffer.begin(); elem!=buffer.end(); ++elem){
    histnames.push_back(*elem);
  }
  if(debug>1){
    std::cout << "added " << buffer.size() << " elements to histnames [" << histnames.size() << "] for file head" << std::endl;
  }

  for(std::vector<std::string>::const_iterator hist=histnames.begin(); hist!=histnames.end(); ++hist){
    file->cd();
    TH1F* h = (TH1F*)file->Get(hist->c_str());
    std::string histName;
    if(hist->find("/")!=std::string::npos){
      histName = hist->substr(hist->find("/")+1);
    }
    else{
      histName = *hist;
    }
    TH1F* hout = (TH1F*)h->Clone(histName.c_str());
    if(debug>1){
      std::cout << "...folder    : " << hist->substr(0, hist->find("/")).c_str() << std::endl;
      std::cout << "...histogram : " << hout->GetName () << " / " << hist->c_str() << std::endl; 
    }
    for(int i0 = 0; i0 < hout->GetNbinsX()+1; i0++) if(hout->GetXaxis()->GetBinCenter(i0) < iMin) hout->SetBinContent(i0,0);
    if(debug>1){ 
      std::cout << "...new name  : " << hout->GetName() << std::endl; 
      std::cout << "...new title : " << hout->GetTitle() << std::endl; 
    }
    if(armed){
      if(hist->find("/")!=std::string::npos){
	file->cd(hist->substr(0, hist->find("/")).c_str());
      }
      else{
	file->cd();
      }
      std::cout << "writing to file: " << hout->GetName() << " -- " << hist->substr(hist->find("/")+1).c_str() << std::endl;
      hout->Write(hist->substr(hist->find("/")+1).c_str(), TObject::kOverwrite); 
    }
  }
  file->Close();
  return;
}
Example #20
0
void poisson(std::map< TString, std::map <unsigned int, TH1F*> > histo_, std::vector<TString> plotList_, const std::string decayChannel, TFile& outputfile, int luminosity, const unsigned int verbose, bool smear, bool useReweightedTop, double avReweight, bool useZprime, double zPrimeLumiWeight){
  unsigned int kCombined=111;
  
  if(verbose>1){
    std::cout << "running function poisson" << std::endl;
    std::cout << "-----------------------------" << std::endl;
    std::cout << "luminosity: " << luminosity << std::endl;
    std::cout << "decayChannel: " << decayChannel << std::endl;
    std::cout << "smear: " << smear << std::endl;
    std::cout << "useReweightedTop: " << useReweightedTop << std::endl;
    std::cout << "avReweight: " << avReweight << std::endl;
    std::cout << "useZprime: " << useZprime << std::endl;
    std::cout << "zPrimeLumiWeight: " << zPrimeLumiWeight << std::endl;
    sleep(5);
  }
  // upper bound for looping events: in/exclude zprime
  int kLast  =kSAToptW;
  int kZprime=kLast+1;
  if(useZprime) kLast=kZprime;

  // go to output file
  outputfile.cd();
  //  ---
  //     combine plot from all files   
  //  ---
  if(verbose>0) std::cout << "start to combine plots " << std::endl;
  // loop plots
  for(unsigned int plot=0; plot<plotList_.size(); ++plot){
    if(verbose>1){
      std::cout << "plot " << plotList_[plot] << std::endl;
      std::cout << "considered samples: " << std::endl;
    }
    // indicate first plot existing in sample
    bool first=true;
    // loop samples
    for(int sample = kSig; sample<=kLast; sample++){
      // check if plot exists
      if((histo_.count(plotList_[plot])>0)&&(histo_[plotList_[plot]].count(sample))){
	// take care of non existing plots
	if(!(useZprime&&sample==kZprime&&plotList_[plot].Contains("PUControlDistributions"))){
	  // do lumiweighting
	  if     (useZprime       &&sample==kZprime) histo_[plotList_[plot]][sample]->Scale(zPrimeLumiWeight);
	  else histo_[plotList_[plot]][sample]->Scale(lumiweight(sample, luminosity, sysNo, decayChannel));
	  // for reweighted ttbar: weight to keep same normalization
	  if(useReweightedTop&&(sample==kSig||sample==kBkg)) histo_[plotList_[plot]][sample]->Scale(1.0/avReweight);
	  // first subsample (should be ttbar signal)
	  // -> create histogram map entry
	  if(first){ 
	    histo_[plotList_[plot]][kCombined] = (TH1F*)(histo_[plotList_[plot]][sample]->Clone());
	    first=false;
	  }
	  // add other subsample
	  else{ 
	    histo_[plotList_[plot]][kCombined]->Add((TH1F*)(histo_[plotList_[plot]][sample]->Clone()),1.0);
	  }
	  if(verbose>1){ 
	    if(useZprime&&sample==kZprime) std::cout << "z prime, weight " << zPrimeLumiWeight << std::endl;
	    else if(useReweightedTop&&(sample==kSig||sample==kBkg))  std::cout << "reweighted "+sampleLabel(sample,decayChannel)+", weight " << 1.0/avReweight << std::endl;
	    else std::cout << sampleLabel(sample,decayChannel) << ", weight " << lumiweight(sample, luminosity, sysNo, decayChannel) << std::endl;
	  }
	}
      }
    }
  }

  //  ---
  //     poisson smearing   
  //  ---
  if(verbose>0) std::cout << "start to do the poisson smearing plots " << std::endl;
  // loop plots
  for(unsigned int plot=0; plot<plotList_.size(); ++plot){
    // check if plot exists
    if((histo_.count(plotList_[plot])>0)&&(histo_[plotList_[plot]].count(kCombined))){
      if(verbose>1) std::cout << "plot " << plotList_[plot] << std::endl;
      // do the poisson smearing
      if(smear){
	TRandom3 rnd(0);
	for(int ibin=0; ibin<=histo_[plotList_[plot]][kCombined]->GetNbinsX()+1; ++ibin){
	  int evts=histo_[plotList_[plot]][kCombined]->GetBinContent(ibin);
	  evts=rnd.Poisson(histo_[plotList_[plot]][kCombined]->GetBinContent(ibin));
	  histo_[plotList_[plot]][kCombined]->SetBinContent(ibin, evts);
	  histo_[plotList_[plot]][kCombined]->SetBinError(ibin, sqrt(evts));
	}
      }
      // do the saving
      // use the same directory as in the input files
      TString directory=getStringEntry(plotList_[plot], 1);
      TString plotName=getStringEntry(plotList_[plot], 2);
      if(verbose>1) std::cout << "check existence of directory " << directory << std::endl;
      if((outputfile.GetDirectory(directory)!=0)&&(verbose>1)) std::cout << "already existing" << std::endl;
      if(outputfile.GetDirectory(directory)==0){
	if(verbose>1) std::cout << "not existing - will create it" << directory << std::endl;
	outputfile.mkdir(directory);
      }
      outputfile.cd(directory);
      if(verbose>1) std::cout << "save plot" << directory << std::endl;
      // save plot
      histo_[plotList_[plot]][kCombined]->Write(plotName);
    }
  }
}
Int_t VisualizeSurface()
{

    std::string gfname;
    std::cout << "\nFor the graph ";
    ListAllFilesInDirOfType (".",".root");
    std::cout << "\nEnter filename : ";
    std::getline(std::cin, gfname);

    TGraphErrors* mygr = GetGraph(gfname);
    mygr->SetMarkerColor(kRed);
    mygr->SetLineColor(kRed);
    mygr->SetMarkerStyle(20);

    std::cout << "\nBegin setup of eta function" << std::endl;
    std::string rfname = GetROOTFile();
    TFile *fle = new TFile(rfname.data());
    if (!fle->IsOpen()) return -1;

    Eta2C eta(fle);
    AngMarginalEta2C marg_eta(eta);
    std::cout << "\neta function set up complete" << std::endl;

    std::cout << "\nBegin setup of denominators" << std::endl;
    std::string parfname = GetParamFile();
    std::ifstream pfile(parfname.data());
    Parameters params(pfile);
    if (! params.KeysAreSensible()) return -1;
    AngDistC W(params, 0, ELECTRIC);

    std::cout << params << std::endl;
    std::cout << "\ndenominator set up complete" << std::endl;

    std::cout << "\nSetting up numerator " << std::endl;
    PolPartAngDistC polpart(1, ELECTRIC);
    std::cout << "\nNumerator setup complete" << std::endl;

    std::cout << "\nBegin setup of h function" << std::endl;

    rfname = GetROOTFile();
    TFile *file = new TFile(rfname.data());
    if (!file->IsOpen()) return -1;

    TDirectory* dir = file->GetDirectory("SolidAnglePDFGeneratorCOutput");
    if (dir==0) return -3;
    std::vector<TH2*> solang_hists = ROOTUtils::GetAllTH2InDirectory(dir);

    std::cout << "h function set up" << std::endl;

    std::vector<UInt_t> indices(32);
    for (UInt_t i=0; i<indices.size(); i++)
    {
        indices[i] = i;
    }

    Phase2ChiSqC FUNC(mygr, W, polpart, marg_eta, solang_hists , indices);
    std::cout << "\nang dist set up" << std::endl;

    Double_t par[] = {params.at(0)->GetValue(),
                       params.at(1)->GetValue(),
                       params.at(2)->GetValue(),
                       params.at(3)->GetValue()};
//    FUNC.SetAllIntegrandParameters(par);
    Double_t chisq_pdf = FUNC(par);

    std::vector<Double_t> ratios = FUNC.GetComputedRatios();

    TGraph* gr = new TGraph(ratios.size());
    gr->SetMarkerColor(kBlue);
    gr->SetLineColor(kBlue);
    gr->SetMarkerStyle(20);

    for (UInt_t i=0; i<ratios.size(); i++)
    {
        gr->SetPoint(i, mygr->GetX()[i], ratios[i]);
    }

    std::cout << "\n Phase2ChiSqC setup completed " << std::endl;

//    Int_t strip;
//    std::cout << "\nEnter desired strip : ";
//    std::cin >> strip;

//    std::shared_ptr<ROOT::Math::IBaseFunctionMultiDim> pi = FUNC.GetDenominator(strip);
//    ParamFunctorAdapter *pfa = new ParamFunctorAdapter(*pi);
//
//    std::cout << "\nSetting up the function" << std::endl;
//    ROOT::Math::ParamFunctor pf;
//    pf.SetFunction(pfa);
//    TF2* f = new TF2("f", pf, -1, 1, -1.0*CLHEP::pi,CLHEP::pi,0);
//    Double_t pars[] = {params[0]->GetValue(),
//                       params[1]->GetValue(),
//                       params[2]->GetValue(),
//                       params[3]->GetValue()};
//    //f->SetParameters(pars);
//    f->SetNpx(50);
//    f->SetNpy(50);

    TPaveText* pt = new TPaveText(0.5, 0.75, 0.8, 0.95);
    std::ostringstream os("", std::ios::out|std::ios::app);
    os << "a = " << params[0]->GetValue();
    pt->AddText(os.str().data());
    os.str("b = ");
    os << params[1]->GetValue();
    pt->AddText(os.str().data());
    os.str("c = ");
    os << params[2]->GetValue();
    pt->AddText(os.str().data());
    os.str("d = ");
    os << params[3]->GetValue();
    pt->AddText(os.str().data());

    TCanvas* c = new TCanvas("c");
    gr->Draw("ALP");
    mygr->Draw("LP");

    return 0;
}
int doHistAnalysis () {
    
    // plot options
    gStyle->SetOptFit(111111111);
    gStyle->SetOptStat(11111111);
    
    // paths to files
    string Bfile_path = "rootfiles/DataScouting_V00-01-06_Run2012B_runrange_193752-197044_dijet_alfaT_razor_dijetpairs_trijetpairs.root";
    string Cfile_path = "rootfiles/DataScouting_V00-01-06_Run2012C_runrange_197885-203755_dijet_alfaT_razor_dijetpairs_trijetpairs.root";
    string Dfile_path = "rootfiles/DataScouting_V00-01-06_Run2012D_runrange_203773-208686_dijet_alfaT_razor_dijetpairs_trijetpairs.root";
    string BCDfile_path = "rootfiles/DataScouting_V00-01-06_Run2012B_Run2012C_Run2012D_runrange_193752-208686_dijet_alfaT_razor_dijetpairs_trijetpairs.root";
    string histPath = "DQMData/Run 999999/DataScouting/Run summary/DiJet";
    string mjj_histName = "h1_MjjWide_finalSel_varbin;1"; // use VARIABLE BINS
    //string mjj_histName = "h1_MjjWide_finalSel;1"; // use 1 GEV BINS
    
    // luminosities, as given on the twiki
    double BLum_fb = 4.445, CLum_fb = 6.806, DLum_fb = 7.384; // in inverse fb
    double BCDLum_fb = BLum_fb + CLum_fb + DLum_fb;
    double BLum_pb = BLum_fb * 1e3;
    double CLum_pb = CLum_fb * 1e3;
    double DLum_pb = DLum_fb * 1e3;
    double BCDLum_pb = BCDLum_fb * 1e3; // converts to inverse pb
    
    // read in the files and get histograms
    TFile * Bfile = new TFile (Bfile_path.c_str());
    TDirectory * BHistDir = Bfile->GetDirectory(histPath.c_str());
    TH1D * BmjjHist = (TH1D*)BHistDir->Get(mjj_histName.c_str());
    BmjjHist->SetName("RunB dijet mass");
    BmjjHist->SetTitle("RunB dijet mass");
    
    TFile * Cfile = new TFile (Cfile_path.c_str());
    TDirectory * CHistDir = Cfile->GetDirectory(histPath.c_str());
    TH1D * CmjjHist = (TH1D*)CHistDir->Get(mjj_histName.c_str());
    CmjjHist->SetName("RunC dijet mass");
    CmjjHist->SetTitle("RunC dijet mass");
    
    TFile * Dfile = new TFile (Dfile_path.c_str());
    TDirectory * DHistDir = Dfile->GetDirectory(histPath.c_str());
    TH1D * DmjjHist = (TH1D*)DHistDir->Get(mjj_histName.c_str());
    DmjjHist->SetName("RunD dijet mass");
    DmjjHist->SetTitle("RunD dijet mass");
    
    TFile * BCDfile = new TFile (BCDfile_path.c_str());
    TDirectory * BCDHistDir = BCDfile->GetDirectory(histPath.c_str());
    TH1D * BCDmjjHist = (TH1D*)BCDHistDir->Get(mjj_histName.c_str());
    BCDmjjHist->SetName("RunsBCD dijet mass");
    BCDmjjHist->SetTitle("RunsBCD dijet mass");
    
    // read out into memory and close the files
    TFile * writefile = new TFile("fTestHists.root","recreate");
    BmjjHist->SetDirectory(writefile);
    CmjjHist->SetDirectory(writefile);
    DmjjHist->SetDirectory(writefile);
    BCDmjjHist->SetDirectory(writefile);
    Bfile->Close();
    Cfile->Close();
    Dfile->Close();
    BCDfile->Close();
    
    // normalise histograms
    NormaliseByLuminosity(BmjjHist, BLum_pb);
    NormaliseByBinWidth(BmjjHist);
    NormaliseByLuminosity(CmjjHist, CLum_pb);
    NormaliseByBinWidth(CmjjHist);
    NormaliseByLuminosity(DmjjHist, DLum_pb);
    NormaliseByBinWidth(DmjjHist);
    NormaliseByLuminosity(BCDmjjHist, BCDLum_pb);
    NormaliseByBinWidth(BCDmjjHist);
    
    // make ratio histograms
    TH1D * BCratio = (TH1D*)BmjjHist->Clone();
    BCratio->Divide(CmjjHist);
    BCratio->SetName("B/C ratio");
    BCratio->SetTitle("B/C ratio");
    
    TH1D * BDratio = (TH1D*)BmjjHist->Clone();
    BDratio->Divide(DmjjHist);
    BDratio->SetName("B/D ratio");
    BDratio->SetTitle("B/D ratio");
    
    TH1D * CDratio = (TH1D*)CmjjHist->Clone();
    CDratio->Divide(DmjjHist);
    CDratio->SetName("C/D ratio");
    CDratio->SetTitle("C/D ratio");
    
    // choose the range to do the fit in
    Float_t fitRangeLow = 270.;
    Float_t fitRangeHigh = 3000.;
    
    // set plot ranges
    BmjjHist->SetAxisRange(500, 3000, "X");
    CmjjHist->SetAxisRange(500, 3000, "X");
    DmjjHist->SetAxisRange(500, 3000, "X");
    BCDmjjHist->SetAxisRange(fitRangeLow, fitRangeHigh, "X");
    
    // write these histograms to file
    writefile->Write();
    
    // F-test loop
    // repeat until the F-test is satisfied
    int nBasePars = 4;
    int nExtraPars = 0;
    float RSSold = 0;
    float RSS = 0;
    int stopTest = 0;
    while (stopTest == 0) {
        // get number of fit parameters
        // (one of the parameters holds the number of parameters... tricky!)
        int nTotalPars = 1 + nBasePars + nExtraPars;

        // set the name of the fit/histogram
        std::ostringstream s;
        s << "FTest" << nExtraPars;
        string fitNameStr = s.str();
        
        // make a canvas to put fit and residual on
        TCanvas* canvas = new TCanvas((fitNameStr + "-canv").c_str(), (fitNameStr + "-canv").c_str(), 800, 600);
        canvas->cd();
        
        //create 3 pads in the canvas
        TPad* fPads1 = NULL;
        TPad* fPads2 = NULL;

        fPads1 = new TPad("pad1", "", 0.00, 0.20, 0.99, 0.99);
        fPads2 = new TPad("pad3", "", 0.00, 0.00, 0.99, 0.20);
        fPads1->SetFillColor(0);
        fPads1->SetLineColor(0);
        fPads2->SetFillColor(0);
        fPads2->SetLineColor(0);
        fPads1->Draw();
        fPads2->Draw();
        
        // make a new histogram to do the fit on
        fPads1->cd();
        TH1D * fitHist = new TH1D;
        fitHist = BCDmjjHist;
        fitHist->SetName(fitNameStr.c_str());

        // set up the background fit
        TF1 *bkfit = new TF1(fitNameStr.c_str(),BackgroundShape, fitRangeLow, fitRangeHigh, nTotalPars);
        bkfit->SetParName(0,"nPar");
        for (int i=1;i<nTotalPars;++i) {
            std::ostringstream p;
            p << "P" << i-1;
            string parNameStr = p.str();
            bkfit->SetParName(i,parNameStr.c_str());
        }
        
        // set the initial parameter values
        bkfit->FixParameter(0,nTotalPars*1.); // number of parameters does not change!
        bkfit->SetParameter(0+1,2.6e-06); // P0
        bkfit->SetParameter(1+1,5.8); // P1
        bkfit->SetParameter(2+1,6.7); // P2
        bkfit->SetParameter(3+1,0.3); // P3
        for (int i=nBasePars+1;i<nTotalPars;++i) {
            // all others to zero
            bkfit->SetParameter(i+1,0.0);
        }
        
        // Fit and get parameters
        fitHist->Fit(bkfit,"IM"); // MRQ (M=improve, R=use fn range, Q=quiet, I=integral, L=likelihood)
        Double_t * params = bkfit->GetParameters();
        fitHist->Write();
        fitHist->SetDirectory(0);
        
        // Make new TGraph for the residual plot
        fPads2->cd();
        TVectorD nsigma_x(fitHist->GetNbinsX()); 
        TVectorD nsigma_y(fitHist->GetNbinsX()); 
      
        for(int i = 1; i <= fitHist->GetNbinsX(); ++i) {
            double binLow = fitHist->GetXaxis()->GetBinLowEdge(i);
            double binHigh = fitHist->GetXaxis()->GetBinUpEdge(i);
            double exp = fitHist->GetBinContent(i);
            double obs = bkfit->Integral(binLow, binHigh, params) / (binHigh - binLow);
            double error = fitHist->GetBinError(i);
            double x = fitHist->GetBinCenter(i);
            
            double diff = obs - exp;
            double sigma = sqrt(error*error);
        
            if (sigma != 0.0 && obs != 0.0 ) {
                nsigma_x[i] = x;
                nsigma_y[i] = diff / sigma;
            } else {
                nsigma_x[i] = +999999;
                nsigma_y[i] = 0;
            }       
        }
        
        // plot the graph of residuals 
        if (nsigma_x.GetNoElements() != 0 ) {
            TGraph *nsigmaGraph = new TGraph(nsigma_x,nsigma_y);
            nsigmaGraph->SetName((fitNameStr+"-resid").c_str());
            nsigmaGraph->SetTitle("");
            nsigmaGraph->GetYaxis()->SetRangeUser(-5,5);
            nsigmaGraph->GetYaxis()->SetTitle("(Data-Fit)/#sigma");
            nsigmaGraph->GetYaxis()->SetTitleOffset(0.1);
            nsigmaGraph->GetYaxis()->SetTitleSize(0.15);
            nsigmaGraph->GetYaxis()->SetLabelSize(0.07);
            nsigmaGraph->GetXaxis()->SetTitle("");
            nsigmaGraph->GetXaxis()->SetLimits(fitRangeLow, fitRangeHigh);
            nsigmaGraph->GetXaxis()->SetRangeUser(fitRangeLow, fitRangeHigh);
            nsigmaGraph->GetXaxis()->SetTitleOffset(0.01);
            nsigmaGraph->GetXaxis()->SetLabelSize(0.09);
            nsigmaGraph->SetMarkerStyle(8);
            nsigmaGraph->SetMarkerSize(0.8);
            nsigmaGraph->Draw("AP");
            nsigmaGraph->Write();
        }
        
        canvas->Write();
        
        // Get degrees of freedom
        int dof = GetNBinsInRange(fitHist, fitRangeLow, fitRangeHigh) - nTotalPars + 1;
        cout << dof << endl;
        
        // Get the RSS value between fit and histogram
        RSSold = RSS;
        RSS = GetResidualSumSquares(BCDmjjHist, bkfit, params, fitRangeLow, fitRangeHigh);
        cout << nExtraPars << endl;
        cout << RSSold << endl;
        cout << RSS << endl;
        
        if (RSSold==0) {
            // we must do it again with an extra parameter before we can do the f-test
            nExtraPars += 1;
            continue;
        }
        
        // otherwise, do a F-test
        const double alphaFTest=0.05;
        cout << "Starting F-Test evaluation with alpha = " << alphaFTest << endl;
        double fTestVal = (RSSold-RSS) * dof / RSS;
        if (fTestVal < 0) {
            // the fit got WORSE - try again!
            
            // TODO: probably look at this, as at present it will add an extra parameter
            // any time the fit worsens from the last time, even slightly.
            // Really we should only do this if the fit is significantly worse. 
            
            cout << "Fit worsened; automatically trying extra parameter\n";
            nExtraPars += 1;
            continue;
        }
        cout  << "F-test value = " << fTestVal << endl;
        double goodCL =  1.-TMath::FDistI(fTestVal,1,dof);
        cout  << "F-test CL = " << goodCL << endl;
        
        if (goodCL > alphaFTest) {
            // the fit got better but not by much - stop here
            cout << "Requires " << nExtraPars-1 << " extra parameters.\n";
            stopTest = 1;
        } else if (nExtraPars == 10) {
            // 10 extra parameters is enough for anyone
            cout << "Reached 10 extra parameters without success - aborting\n";
            stopTest = 1;
        } else {
            // it got significantly better - try still more parameters
            cout << "F-test failed; trying more parameters\n";
            nExtraPars += 1;
        }
    }
    
    // finish up
    writefile->Close();
    
    return 1;
}
void rescaleSignal(bool armed, double scale, const char* filename, const char* pattern="", unsigned int debug=0)
{
  std::vector<std::string> histnames; histnames.clear();
  if( debug>0 ){
    std::cout << "file  = " << filename << std::endl;
    std::cout << "scale = " << scale    << std::endl;
    std::cout << "armed = " << armed    << std::endl;
  }
  TFile* file = new TFile(filename, "update");
  TIter nextDirectory(file->GetListOfKeys());
  std::vector<std::string> buffer;
  TKey* idir;
  while((idir = (TKey*)nextDirectory())){
    buffer.clear();
    if( idir->IsFolder() ){
      file->cd(); // make sure to start in directory head 
      if( debug>0 ){ std::cout << "Found directory: " << idir->GetName() << std::endl; }
      if( file->GetDirectory(idir->GetName()) ){
	file->cd(idir->GetName()); // change to sub-directory
	buffer = signalList(idir->GetName(), pattern, debug);
      }
      // append to the vector of histograms to be rescaled
      for(std::vector<std::string>::const_iterator elem=buffer.begin(); elem!=buffer.end(); ++elem){
	histnames.push_back(*elem);
      }
      if(debug>1){
	std::cout << "added " << buffer.size() << " elements to histnames [" << histnames.size() << "] for directory " << idir->GetName() << std::endl;
      }
    }
  }
  // pick up files which are not kept in an extra folder
  file->cd(); buffer.clear();
  buffer = signalList("", pattern, debug);
  // append to the vector of histograms to be rescaled
  for(std::vector<std::string>::const_iterator elem=buffer.begin(); elem!=buffer.end(); ++elem){
    histnames.push_back(*elem);
  }
  if(debug>1){
    std::cout << "added " << buffer.size() << " elements to histnames [" << histnames.size() << "] for file head" << std::endl;
  }

  for(std::vector<std::string>::const_iterator hist=histnames.begin(); hist!=histnames.end(); ++hist){
    file->cd();
    TH1F* h = (TH1F*)file->Get(hist->c_str());
    std::string histName;
    if(hist->find("/")!=std::string::npos){
      histName = hist->substr(hist->find("/")+1);
    }
    else{
      histName = *hist;
    }
    TH1F* hout = (TH1F*)h->Clone(histName.c_str());
    if(debug>1){
      std::cout << "...folder    : " << hist->substr(0, hist->find("/")).c_str() << std::endl;
      std::cout << "...histogram : " << hout->GetName () << " / " << hist->c_str() << std::endl; 
      std::cout << "...old scale : " << hout->Integral() << std::endl; 
    }
    hout->Scale(scale);
    if(match(pattern, "data")){
      //make sure to have an integer integral when rescaling data yields
      hout->Scale(int(hout->Integral())/hout->Integral());
    }
    if(debug>1){ 
      std::cout << "...new scale : " << hout->Integral() << std::endl; 
    }
    if(armed){
      if(hist->find("/")!=std::string::npos){
	file->cd(hist->substr(0, hist->find("/")).c_str());
      }
      else{
	file->cd();
      }
      std::cout << "writing to file: " << hout->GetName() << std::endl;
      hout->Write(hist->substr(hist->find("/")+1).c_str(), TObject::kOverwrite); 
    }
  }
  file->Close();
  return;
}
void waveform(string inFileName, string outFileName, vector<string>channelMap, string mode)
{
    TFile* inFile = new TFile(inFileName.c_str(),"READ");
    if(!inFile->IsOpen())
    {
        cerr << "Error: failed to open sorted.root" << endl;
        exit(1);
    }

    TFile* outFile = new TFile(outFileName.c_str(),"RECREATE");

    for(int i=0; i<channelMap.size(); i++)
    {
        if(channelMap[i]!="lowThresholdDet"/* && channelMap[i]!="monitor"*/)
        {
            continue;
        }

        string treeName;

        if(mode=="DPP")
        {
            treeName = channelMap[i];
        }

        else if(mode=="waveform")
        {
            treeName = channelMap[i]+"W";
        }

        else
        {
            cerr << "Error: digitizer mode was " << mode << "; only possible options are 'DPP' or 'waveform'. Exiting..." << endl;
            exit(1);
        }

        TTree* treeToSort = (TTree*)inFile->Get(treeName.c_str());
        
        if(!treeToSort)
        {
            cerr << "Error: couldn't find channel " << i << " tree when attempting to assign macropulses. Exiting... " << endl;
            exit(1);
        }

        outFile->cd("/");
        outFile->mkdir(channelMap[i].c_str(),channelMap[i].c_str());
        outFile->GetDirectory(channelMap[i].c_str())->cd();

        vector<Plots> targetPlots;

        // Extract triggers from waveforms
        for(unsigned int i=0; i<tarGates.size()-1; i++)
        {
            string name = TARGET_ORDER[i];
            if(name=="")
            {
                continue;
            }

            targetPlots.push_back(Plots(name.c_str()));
        }

        processWaveforms(treeToSort, targetPlots, outFile, mode);

        /*int totalEntries = ch4TreeWaveform->GetEntries();

        // total number of micropulses processed per target (for performing dead time
        // calculation)
        vector<long> microsPerTargetWaveform(6,0);

        for(int i=0; i<totalEntries; i++)
        {
        ch4TreeWaveform->GetEntry(i);

        if(procEvent.targetPos==0)
        {
        continue;
        }
        microsPerTargetWaveform[procEvent.targetPos-1] += SAMPLE_PERIOD*procEvent.waveform->size()/(double)MICRO_LENGTH;
        }

        // perform a manual dead-time correction
        //calculateDeadtime(microsPerTargetWaveform,plots);

        // Calculate cross-sections from waveforms' trigger time data
        //calculateCS(targets, waveformFile);

        int totalMicros = 0;
        for(int i=0; (size_t)i<microsPerTargetWaveform.size(); i++)
        {
        totalMicros += microsPerTargetWaveform[i];
        }

        for(Plots* p : plots)
        {
        numberTotalTriggers += p->getTOFHisto()->GetEntries();
        }

        cout << "Total micros on ch. : " << totalMicros << endl;
        cout << "Total number of triggers on ch. : " << numberTotalTriggers << endl;
        cout << "Triggers/micropulse: " << numberTotalTriggers/(double)totalMicros << endl;
        */
    }

    inFile->Close();
    outFile->Close();
    return;
}
Example #25
0
//
// Plot_ECvsP - plot the EC/P vs P distributions with cuts
//
//                  fAna = output from eg2a DMS
//                  target = target name
//
void Plot_ECvsP(char *fAna="Ana.root", char *fitParams="ECvsP_Fit.dat", char *target)
{
    Int_t i, j;
    Int_t iSector;
    
    const Int_t NPARAM = 3;
    TF1 *fitMean[NSECTORS];
    TF1 *fitCut[NSECTORS];
    TH2D *h2D[NSECTORS];
    
    char funcName[50];
    
    Double_t a, b, c, d, f;
    Double_t parMean[5];
    Double_t parSigma[2];
    
    // open text file for fit parameters
    ifstream fin(fitParams);

    // data files contain the trees
    printf("Analyzing file %s\n",fAna);
    TFile *fm = new TFile(fAna,"READ");
    TDirectory *tmp = fm->GetDirectory("ElectronID");
    
    // Canvas to plot histogram
    TCanvas *c1 = new TCanvas("c1","c1",0,0,1200,800);
    c1->SetBorderMode(1);  //Bordermode (-1=down, 0 = no border, 1=up)
    c1->SetBorderSize(5);
    gStyle->SetOptStat(1111);
    c1->SetFillStyle(4000);
    c1->Divide(3,2);
    
    for(j=0; j<NSECTORS; j++){
        sprintf(hname,"ECtotP_VS_P_Sector%i",j+1);
        h2D[j] = (TH2D*)tmp->Get(hname);
        
        c1->cd(j+1);
        gPad->SetLeftMargin(Lmar);
        gPad->SetRightMargin(Rmar);
        gPad->SetFillColor(0);
        
        h2D[j]->GetXaxis()->CenterTitle();
        h2D[j]->GetYaxis()->CenterTitle();
        h2D[j]->GetYaxis()->SetTitleOffset(yoff);
        
        h2D[j]->SetAxisRange(0.0,3.0,"X");
        h2D[j]->Draw("colz");
        
        fin >> iSector >> a >> b >> c >> d >> f;
        parMean[0] = a;
        parMean[1] = b;
        parMean[2] = c;
        parMean[3] = d;
        parMean[4] = f;
        
        sprintf(funcName,"fitMean%i",j+1);
        fitMean[j] = new TF1(funcName,polFit,0.0,3.0,3);
        fitMean[j]->SetParameters(&parMean[0]);
        fitMean[j]->SetLineWidth(2);
        fitMean[j]->Draw("same");
        
        sprintf(funcName,"fitCut%i",j+1);
        fitCut[j] = new TF1(funcName,CutBelow,0.0,3.0,5);
        fitCut[j]->SetParameters(parMean);
        fitCut[j]->SetLineColor(4);
        fitCut[j]->SetLineWidth(2);
        fitCut[j]->Draw("same");
        
        sprintf(funcName,"fitCut%i",j+1);
        fitCut[j] = new TF1(funcName,CutAbove,0.0,3.0,5);
        fitCut[j]->SetParameters(parMean);
        fitCut[j]->SetLineColor(4);
        fitCut[j]->SetLineWidth(2);
        fitCut[j]->Draw("same");
    }
    sprintf(OutCan,"Plot_ECvsP_%s.gif",target);
    c1->Print(OutCan);
    sprintf(OutCan,"Plot_ECvsP_%s.eps",target);
    c1->Print(OutCan);
    
    fin.close();
}
Example #26
0
void blindData(const char* filename, const char* background_patterns="Fakes, EWK, ttbar, Ztt", const char* signal_patterns="ggH125, qqH125, VH125", const char* directory_patterns="*", bool armed=false, int rnd=-1, float signal_scale=1., const char* outputLabel="", unsigned int debug=1)
{
  /// prepare input parameters
  std::vector<std::string> signals;
  string2Vector(cleanupWhitespaces(signal_patterns), signals);
  std::vector<std::string> samples;
  string2Vector(cleanupWhitespaces(background_patterns), samples);
  samples.insert(samples.end(), signals.begin(), signals.end());

  // check if mssm or sm input file
  bool sm=true;
  if(std::string(filename).find("mssm") != std::string::npos){
    sm=false;
    std::cerr << "INFO  : MSSM File " << std::endl;
  }
  
  // in case data_obs is supposed to be written to an extra output file
  // open the file, otherwise the data_obs in the input file will be
  // overwritten
  string used_filename=string(filename);
  TFile* outputFile = 0; 
  if(!std::string(outputLabel).empty()){
    std::string out = std::string(used_filename); 
    if(std::string(outputLabel).find("MSSM") != std::string::npos){
      outputFile = new TFile((out.substr(0, out.rfind("."))+".root").c_str(), "update"); 
    }
    // make sure data_obs in correct file for MSSM injection is changed
    // this is the old file which is overwritten 
    else{
      outputFile = new TFile((out.substr(0, out.rfind("."))+"_"+outputLabel+".root").c_str(), "update"); 
    }
  }

  TKey* idir;
  TH1F* buffer = 0;
  TH1F* blind_data_obs = 0;
  TFile* file = new TFile(used_filename.c_str(), "update");
  TIter nextDirectory(file->GetListOfKeys());
  while((idir = (TKey*)nextDirectory())){
    if( idir->IsFolder() ){
      file->cd(); // make sure to start in directory head 
      if( debug>0 ){ std::cerr << "Found directory: " << idir->GetName() << std::endl; }
      // check if we want to muck w/ this directory. For the vhtt case, we 
      // have different background types in the same root file, so we have 
      // to run blindData twice.
      if (!inPatterns(std::string(idir->GetName()), directory_patterns)) {
        if( debug>0 ){ 
	  std::cerr << "WARNING: Skipping directory: " << idir->GetName() << std::endl;
	  std::cerr << "         No match found in pattern: " << directory_patterns << std::endl; 
	}
        continue;
      }
      if( file->GetDirectory(idir->GetName()) ){
	file->cd(idir->GetName()); // change to sub-directory
	buffer = (TH1F*)file->Get((std::string(idir->GetName())+"/data_obs").c_str());
	if(!buffer){
	  std::cout << "WARNING: Did not find histogram data_obs in directory: " << idir->GetName() << std::endl;
	  std::cout << "         Will skip directory: " << std::endl;
	  continue;
	}
        blind_data_obs = (TH1F*)buffer->Clone("data_obs"); 
	if(!samples.empty()){
	  blind_data_obs->Reset();
	  std::cout << "INFO  : Blinding datacads now." << std::endl;
	  for(std::vector<std::string>::const_iterator sample = samples.begin(); sample!=samples.end(); ++sample){
	    if( debug>0 ){ std::cerr << "Looking for histogram: " << (std::string(idir->GetName())+"/"+(*sample)) << std::endl; }
	    // add special treatment for et/mt ZLL,ZJ,ZL here. You can run the
	    // macro with ZLL, ZL, ZJ in the background samples. Those samples,
	    // which do not apply for one or the other event category are 
	    // skipped here.
	    if(sm==true){
	      if(std::string(idir->GetName()).find("vbf") != std::string::npos  && (*sample == std::string("ZL") || *sample == std::string("ZJ"))){
		continue;
	      }
	      else if(std::string(idir->GetName()).find("vbf") == std::string::npos  && *sample == std::string("ZLL")){
		continue;
	      }
	    }
	    else{
	      if(std::string(idir->GetName()).find("nobtag") == std::string::npos && (*sample == std::string("ZL") || *sample == std::string("ZJ"))){
	      continue;
	      }
	      else if(std::string(idir->GetName()).find("nobtag") != std::string::npos && *sample == std::string("ZLL")){
	      continue;
	      }  
	    }
	    buffer = (TH1F*)file->Get((std::string(idir->GetName())+"/"+(*sample)).c_str()); 
	    if (!buffer) {
	      std::cerr << "ERROR : Could not get histogram from: " << std::string(idir->GetName())+"/"+(*sample) << std::endl;
	      std::cerr << "        Histogram will be skipped   : " << std::string(idir->GetName())+"/"+(*sample) << std::endl;
	      continue;
	    }
	    if(inPatterns(*sample, signal_patterns)) {
	      if( debug>1 ){
		std::cerr << "INFO  : Scale signal sample " << *sample << " by scale " << signal_scale << std::endl;
	      }
	      buffer->Scale(signal_scale);
	    }
	    blind_data_obs->Add(buffer);
	    if (debug > 1){
	      std::cerr << "INFO  : Adding: " << buffer->GetName() << " -- " << buffer->Integral() << " --> New value: " << blind_data_obs->Integral() << std::endl;
	    }
	  }
	}
	else{
	  std::cout << "INFO  : Data are not blinded." << std::endl;
	}
	if(rnd>=0){
	  // randomize histogram; this will automatically have integer integral
	  std::cerr << "-- R A N D O M I Z I N G --" << std::endl;
	  randomize(blind_data_obs, rnd, debug);
	}
	else{
	  // use expected mean with signal injected
	  blind_data_obs->Scale(TMath::Nint(blind_data_obs->Integral())/blind_data_obs->Integral());
	  // adjust uncertaintie
	  adjustUncerts(blind_data_obs);
	}
	std::cout << "INFO  : New data_obs yield: " << idir->GetName() << "   " << TMath::Nint(blind_data_obs->Integral()) << std::endl;
	if(armed){
          if (debug > 1){
            std::cerr << "INFO  : Writing to file: " << blind_data_obs->GetName() << std::endl;
	  }
	  if(outputFile){
	    // write to a dedicated new file with name output in case output has been specified
	    // make sure data_obs in correct file for MSSM injection is changed
	    // this is the old file which is overwritten 
	    if(std::string(outputLabel).find("MSSM") != std::string::npos){
	      outputFile->cd(idir->GetName());
	      blind_data_obs->Write("data_obs", TObject::kOverwrite);
	    }
	    else{
	      outputFile->mkdir(idir->GetName()); outputFile->cd(idir->GetName());
	      blind_data_obs->Write("data_obs"); 
	    }
	  }
	  else{
	    // override old data_obs in the inputfile otherwise
	    file->cd(idir->GetName());
	    blind_data_obs->Write("data_obs", TObject::kOverwrite); 
	  }
	}
      }
    }
  }
  file->Close();
  if(outputFile){
    outputFile->Close();
  }
  return;
}
Example #27
0
Int_t MakeTrendingITSQA(TString qafilename ="QAresults.root",       //full path of the QA output; set IsOnGrid to prepend "alien://"
                        Int_t runNumber= 133005,          // run number
                        Bool_t isMC=kFALSE,       //MC flag, to disable meaningless checks
                        Bool_t canvasE = kFALSE,  //enable display plots on canvas and save png
                        Bool_t IsOnGrid = kFALSE, //set to kTRUE to access files on the grid
                        TString ocdbStorage = "raw://") //set the default ocdb storage
{
    // macro to generate tree with ITS QA trending variables
    // access qa PWGPP output files
    if (!qafilename) {
        Printf("Error - Invalid input file");
        return 1;
    }



    char defaultQAoutput[30]="QAresults.root";
    char * treePostFileName="trending.root";

    if (IsOnGrid) TGrid::Connect("alien://");
    TFile * fin = TFile::Open(qafilename,"r");
    if (!fin) {
        Printf("ERROR: QA output not found. Exiting...\n");
        return -1;
    } else {
        Printf("INFO: QA output file %s open. \n",fin->GetName());
    }

    TFile * trendFile = new TFile(treePostFileName,"recreate");


    ///// SDD Variables
    
    Int_t nrun,nEvents, nEventsTriggered;
    Float_t minDrTime,errminDrTime,meanDrTime,errmeanDrTime;
    Float_t fracTrackWithClu1,fracTrackWithClu2,errfracTrackWithClu1,errfracTrackWithClu2;
    Float_t fracTrackWithClu3,fracTrackWithClu4,errfracTrackWithClu3,errfracTrackWithClu4;
    Float_t fracTrackWithClu5,fracTrackWithClu6,errfracTrackWithClu5,errfracTrackWithClu6;
    Float_t fracExtra,errfracExtra;
    Float_t fracT[6]={0.,0.,0.,0.,0.,0.};
    Float_t efracT[6]={0.,0.,0.,0.,0.,0.};
    Int_t nTotEvents;
    Int_t nTrigEvents;
    Double_t averPoints=0.;
    Double_t cntBins=0.;
    Float_t minTime=-999.;
    Float_t errMinTime=0.;
    Float_t MPVdEdxLay3,errMPVdEdxLay3,MPVdEdxLay4,errMPVdEdxLay4;
    Float_t MPVdEdxTB0,errMPVdEdxTB0,MPVdEdxTB5,errMPVdEdxTB5;

    
    //// Vertex Variables
    
    Float_t meanVtxTRKx,meanVtxTRKy,meanVtxTRKz;
    Float_t meanVtxSPDx,meanVtxSPDy,meanVtxSPDz;
    Float_t sigmaVtxTRKx,sigmaVtxTRKy,sigmaVtxTRKz;
    Float_t sigmaVtxSPDx,sigmaVtxSPDy,sigmaVtxSPDz;
    Float_t meanVtxTRKxErr,meanVtxTRKyErr,meanVtxTRKzErr;
    Float_t meanVtxSPDxErr,meanVtxSPDyErr,meanVtxSPDzErr;
    Float_t sigmaVtxTRKxErr,sigmaVtxTRKyErr,sigmaVtxTRKzErr;
    Float_t sigmaVtxSPDxErr,sigmaVtxSPDyErr,sigmaVtxSPDzErr;
    
    
    ///// SSD Variables
    
    
    Float_t MPVL5,MPVErrL5;
    Float_t MPVL6,MPVErrL6;
    Float_t ChargeRatioL5,ChargeRatioErrL5;
    Float_t ChargeRatioL6,ChargeRatioErrL6;
    Float_t EmptyModulesSDD;


    ///// Matching Variables
    


    Float_t FracSPD1;
    Float_t errFracSPD1;
    Float_t FracSPD2;
    Float_t errFracSPD2;
    Float_t Eff6Pt02;
    Float_t errEff6Pt02;
    Float_t Eff6Pt1;
    Float_t errEff6Pt1;
    Float_t Eff6Pt10;
    Float_t errEff6Pt10;
    Float_t Eff5Pt02;
    Float_t errEff5Pt02;
    Float_t Eff5Pt1;
    Float_t errEff5Pt1;
    Float_t Eff5Pt10;
    Float_t errEff5Pt10;
    Float_t Eff4Pt02;
    Float_t errEff4Pt02;
    Float_t Eff4Pt1;
    Float_t errEff4Pt1;
    Float_t Eff4Pt10;
    Float_t errEff4Pt10;
    Float_t Eff3Pt02;
    Float_t errEff3Pt02;
    Float_t Eff3Pt1;
    Float_t errEff3Pt1;
    Float_t Eff3Pt10;
    Float_t errEff3Pt10;
    Float_t Eff2Pt02;
    Float_t errEff2Pt02;
    Float_t Eff2Pt1;
    Float_t errEff2Pt1;
    Float_t Eff2Pt10;
    Float_t errEff2Pt10;
    Float_t EffSPDPt02;
    Float_t errEffSPDPt02;
    Float_t EffSPDPt1;
    Float_t errEffSPDPt1;
    Float_t EffSPDPt10;
    Float_t errEffSPDPt10;
    Float_t EffoneSPDPt02;
    Float_t errEffoneSPDPt02;
    Float_t EffoneSPDPt1;
    Float_t errEffoneSPDPt1;
    Float_t EffoneSPDPt10;
    Float_t errEffoneSPDPt10;
    Float_t EffTOTPt02;
    Float_t errEffTOTPt02;
    Float_t EffTOTPt1;
    Float_t errEffTOTPt1;
    Float_t EffTOTPt10;
    Float_t errEffTOTPt10;
    
    

    
    
    TTree * ttree=new TTree("trending","tree of trending variables");
    ttree->Branch("nrun",&nrun,"nrun/I");
    ttree->Branch("nEvents",&nEvents,"nEvents/I");
    ttree->Branch("nEventsTriggered",&nEventsTriggered,"nEventsTriggered/I");
    ttree->Branch("minDrTime",&minDrTime,"minDrTime/F");
    ttree->Branch("errminDrTime",&errminDrTime,"errminDrTime/F");
    ttree->Branch("meanDrTime",&meanDrTime,"meanDrTime/F");
    ttree->Branch("errmeanDrTime",&errmeanDrTime,"errmeanDrTime/F"); //mean time
    ttree->Branch("fracTrackWithClu1",&fracTrackWithClu1,"fracTrackWithClu1/F"); //fraction of tracks with cluster in layer 1

    ttree->Branch("errfracTrackWithClu1",&errfracTrackWithClu1,"errfracTrackWithClu1/F"); //error fraction of tracks with cluster in layer 1
    ttree->Branch("fracTrackWithClu2",&fracTrackWithClu2,"fracTrackWithClu2/F"); //
    ttree->Branch("errfracTrackWithClu2",&errfracTrackWithClu2,"errfracTrackWithClu2/F"); //
    ttree->Branch("fracTrackWithClu3",&fracTrackWithClu3,"fracTrackWithClu3/F");
    ttree->Branch("errfracTrackWithClu3",&errfracTrackWithClu3,"errfracTrackWithClu3/F");
    ttree->Branch("fracTrackWithClu4",&fracTrackWithClu4,"fracTrackWithClu4/F");
    ttree->Branch("errfracTrackWithClu4",&errfracTrackWithClu4,"errfracTrackWithClu4/F");
    ttree->Branch("fracTrackWithClu5",&fracTrackWithClu5,"fracTrackWithClu5/F");
    ttree->Branch("errfracTrackWithClu5",&errfracTrackWithClu5,"errfracTrackWithClu5/F");
    ttree->Branch("fracTrackWithClu6",&fracTrackWithClu6,"fracTrackWithClu6/F");
    ttree->Branch("errfracTrackWithClu6",&errfracTrackWithClu6,"errfracTrackWithClu6/F");


    
    ttree->Branch("meanVtxTRKx",&meanVtxTRKx,"meanVtxTRKx/F"); // mean of tracks vertex position - x
    ttree->Branch("meanVtxTRKy",&meanVtxTRKy,"meanVtxTRKy/F"); // mean of tracks vertex position - y
    ttree->Branch("meanVtxTRKz",&meanVtxTRKz,"meanVtxTRKz/F"); // mean of tracks vertex position - z
    ttree->Branch("meanVtxTRKxErr",&meanVtxTRKxErr,"meanVtxTRKxErr/F"); // error mean of tracks vertex position - x
    ttree->Branch("meanVtxTRKyErr",&meanVtxTRKyErr,"meanVtxTRKyErr/F"); // error mean of tracks vertex position - y
    ttree->Branch("meanVtxTRKzErr",&meanVtxTRKzErr,"meanVtxTRKzErr/F"); // error mean of tracks vertex position - z

    ttree->Branch("meanVtxSPDx",&meanVtxSPDx,"meanVtxSPDx/F"); // mean of SPD vertex position - x
    ttree->Branch("meanVtxSPDy",&meanVtxSPDy,"meanVtxSPDy/F"); // mean of SPD vertex position - y
    ttree->Branch("meanVtxSPDz",&meanVtxSPDz,"meanVtxSPDz/F"); // mean of SPD vertex position - z
    ttree->Branch("meanVtxSPDxErr",&meanVtxSPDxErr,"meanVtxSPDxErr/F"); // error mean of SPD vertex position - x
    ttree->Branch("meanVtxSPDyErr",&meanVtxSPDyErr,"meanVtxSPDyErr/F"); // error mean of SPD vertex position - y
    ttree->Branch("meanVtxSPDzErr",&meanVtxSPDzErr,"meanVtxSPDzErr/F"); // error mean of SPD vertex position - z

    ttree->Branch("sigmaVtxTRKx",&sigmaVtxTRKx,"sigmaVtxTRKx/F"); // sigma of tracks vertex position - x
    ttree->Branch("sigmaVtxTRKy",&sigmaVtxTRKy,"sigmaVtxTRKy/F"); // sigma of tracks vertex position - y
    ttree->Branch("sigmaVtxTRKz",&sigmaVtxTRKz,"sigmaVtxTRKz/F"); // sigma of tracks vertex position - z
    ttree->Branch("sigmaVtxTRKxErr",&sigmaVtxTRKxErr,"sigmaVtxTRKxErr/F"); // error sigma of tracks vertex position - x
    ttree->Branch("sigmaVtxTRKyErr",&sigmaVtxTRKyErr,"sigmaVtxTRKyErr/F"); // error sigma of tracks vertex position - y
    ttree->Branch("sigmaVtxTRKzErr",&sigmaVtxTRKzErr,"sigmaVtxTRKzErr/F"); // error sigma of tracks vertex position - z

    ttree->Branch("sigmaVtxSPDx",&sigmaVtxSPDx,"sigmaVtxSPDx/F"); // sigma of tracks vertex position - x
    ttree->Branch("sigmaVtxSPDy",&sigmaVtxSPDy,"sigmaVtxSPDy/F"); // sigma of tracks vertex position - y
    ttree->Branch("sigmaVtxSPDz",&sigmaVtxSPDz,"sigmaVtxSPDz/F"); // sigma of tracks vertex position - z
    ttree->Branch("sigmaVtxSPDxErr",&sigmaVtxSPDxErr,"sigmaVtxSPDxErr/F"); // error sigma of tracks vertex position - x
    ttree->Branch("sigmaVtxSPDyErr",&sigmaVtxSPDyErr,"sigmaVtxSPDyErr/F"); // error sigma of tracks vertex position - y
    ttree->Branch("sigmaVtxSPDzErr",&sigmaVtxSPDzErr,"sigmaVtxSPDzErr/F"); // error sigma of tracks vertex position - z
    
    
    
    ttree->Branch("MPVL5",&MPVL5,"MPVL5/F"); // Most Probable Value dEdx Layer 5
    ttree->Branch("MPVErrL5",&MPVErrL5,"MPVErrL5/F"); // Most Probable Value error dEdx Layer 5

    ttree->Branch("MPVL6",&MPVL6,"MPVL6/F"); // Most Probable Value dEdx Layer 6
    ttree->Branch("MPVErrL6",&MPVErrL6,"MPVErrL6/F"); // Most Probable Value error dEdx Layer 6

    ttree->Branch("ChargeRatioL5",&ChargeRatioL5,"ChargeRatioL5/F"); // Charge ratio (2 sides of SSD) Layer 5
    ttree->Branch("ChargeRatioErrL5",&ChargeRatioErrL5,"ChargeRatioErrL5/F"); // Charge ratio error (2 sides of SSD) Layer 5

    ttree->Branch("ChargeRatioL6",&ChargeRatioL6,"ChargeRatioL6/F"); // Charge ratio (2 sides of SSD) Layer 6
    ttree->Branch("ChargeRatioErrL6",&ChargeRatioErrL6,"ChargeRatioErrL6/F"); // Charge ratio error(2 sides of SSD) Layer 6

    ttree->Branch("EmptyModulesSDD",&EmptyModulesSDD,"EmptyModulesSDD/F"); // Number of empty SSD  modules


    
    ttree->Branch("fracExtra",&fracExtra,"fracExtra/F"); // fraction of extra clusters in SDD
    ttree->Branch("errfracExtra",&errfracExtra,"errfracExtra/F"); // fraction of extra clusters in SDD
    
    ttree->Branch("minTime",&minTime,"minTime/F"); // minimum drift time SDD
    ttree->Branch("errMinTime",&errMinTime,"errMinTime/F"); //  error on minimum drift time SDD
    
    ttree->Branch("MPVdEdxLay3",&MPVdEdxLay3,"MPVdEdxLay3/F"); // most probable value of dE/Fx distribution of SDD Layer 3
    ttree->Branch("errMPVdEdxLay3",&errMPVdEdxLay3,"errMPVdEdxLay3/F"); // error  most probable value of dE/Fx distribution of SDD Layer 3

    ttree->Branch("MPVdEdxLay4",&MPVdEdxLay4,"MPVdEdxLay4/F"); // most probable value of dE/Fx distribution of SDD Layer 4
    ttree->Branch("errMPVdEdxLay4",&errMPVdEdxLay4,"errMPVdEdxLay4/F"); // error  most probable value of dE/Fx distribution of SDD Layer 4

    ttree->Branch("MPVdEdxTB0",&MPVdEdxTB0,"MPVdEdxTB0/F"); // most probable value of dE/Fx distribution of SDD - small drift time
    ttree->Branch("errMPVdEdxTB0",&errMPVdEdxTB0,"errMPVdEdxTB0/F"); // most probable value of dE/Fx distribution of SDD - small drift time

    ttree->Branch("MPVdEdxTB5",&MPVdEdxTB5,"MPVdEdxTB5/F"); // most probable value of dE/Fx distribution of SDD - large drift time
    ttree->Branch("errMPVdEdxTB5",&errMPVdEdxTB5,"errMPVdEdxTB5/F"); // most probable value of dE/Fx distribution of SDD - large drift time


    
    
    ttree->Branch("Eff6Pt02",&Eff6Pt02,"Eff6Pt02/F"); // matching efficiency low pt 6 clusters
    ttree->Branch("errEff6Pt02",&errEff6Pt02,"errEff6Pt02/F"); // error matching efficiency low pt 6 clusters
    ttree->Branch("Eff5Pt02",&Eff5Pt02,"Eff5Pt02/F"); // matching efficiency low pt 5 clusters
    ttree->Branch("errEff5Pt02",&errEff5Pt02,"errEff5Pt02/F"); // error matching efficiency low pt 5 clusters
    ttree->Branch("Eff4Pt02",&Eff4Pt02,"Eff4Pt02/F"); // matching efficiency low pt 4 clusters
    ttree->Branch("errEff4Pt02",&errEff4Pt02,"errEff4Pt02/F"); // error matching efficiency low pt 4 clusters
    ttree->Branch("Eff3Pt02",&Eff3Pt02,"Eff3Pt02/F"); // matching efficiency low pt 3 clusters
    ttree->Branch("errEff3Pt02",&errEff3Pt02,"errEff3Pt02/F"); // error matching efficiency low pt 3 clusters
    ttree->Branch("Eff2Pt02",&Eff2Pt02,"Eff2Pt02/F"); // matching efficiency low pt 2 clusters
    ttree->Branch("errEff2Pt02",&errEff2Pt02,"errEff2Pt02/F"); // error matching efficiency low pt 2 clusters
    ttree->Branch("EffSPDPt02",&EffSPDPt02,"EffSPDPt02/F"); // matching efficiency low pt 2 SPD
    ttree->Branch("errEffSPDPt02",&errEffSPDPt02,"errEffSPDPt02/F"); // error matching efficiency low pt 2 SPD
    ttree->Branch("EffoneSPDPt02",&EffoneSPDPt02,"EffoneSPDPt02/F"); // matching efficiency low pt 6 one SPD
    ttree->Branch("errEffoneSPDPt02",&errEffoneSPDPt02,"errEffoneSPDPt02/F"); // error matching efficiency low pt one SPD
    ttree->Branch("EffTOTPt02",&EffTOTPt02,"EffTOTPt02/F"); // matching efficiency low pt
    ttree->Branch("errEffTOTPt02",&errEffTOTPt02,"errEffTOTPt02/F"); // error matching efficiency low pt
    
    

    
    
    ttree->Branch("Eff6Pt1",&Eff6Pt1,"Eff6Pt1/F"); // matching efficiency mid pt 6 clusters
    ttree->Branch("errEff6Pt1",&errEff6Pt1,"errEff6Pt1/F"); // error matching efficiency mid pt 6 clusters
    ttree->Branch("Eff5Pt1",&Eff5Pt1,"Eff5Pt1/F"); // matching efficiency mid pt 5 clusters
    ttree->Branch("errEff5Pt1",&errEff5Pt1,"errEff5Pt1/F"); // error matching efficiency mid pt 5 clusters
    ttree->Branch("Eff4Pt1",&Eff4Pt1,"Eff4Pt1/F"); // matching efficiency mid pt 4 clusters
    ttree->Branch("errEff4Pt1",&errEff4Pt1,"errEff4Pt1/F"); // error matching efficiency mid pt 4 clusters
    ttree->Branch("Eff3Pt1",&Eff3Pt1,"Eff3Pt1/F"); // matching efficiency mid pt 3 clusters
    ttree->Branch("errEff3Pt1",&errEff3Pt1,"errEff3Pt1/F"); // error matching efficiency mid pt 3 clusters
    ttree->Branch("Eff2Pt1",&Eff2Pt1,"Eff2Pt1/F"); // matching efficiency mid pt 2 clusters
    ttree->Branch("errEff2Pt1",&errEff2Pt1,"errEff2Pt1/F"); // error matching efficiency mid pt 2 clusters
    ttree->Branch("EffSPDPt1",&EffSPDPt1,"EffSPDPt1/F"); // matching efficiency mid pt 2 SPD
    ttree->Branch("errEffSPDPt1",&errEffSPDPt1,"errEffSPDPt1/F"); // error matching efficiency mid pt 2 SPD
    ttree->Branch("EffoneSPDPt1",&EffoneSPDPt1,"EffoneSPDPt1/F"); // matching efficiency mid pt 6 one SPD
    ttree->Branch("errEffoneSPDPt1",&errEffoneSPDPt1,"errEffoneSPDPt1/F"); // error matching efficiency mid pt one SPD
    ttree->Branch("EffTOTPt1",&EffTOTPt1,"EffTOTPt1/F"); // matching efficiency mid pt
    ttree->Branch("errEffTOTPt1",&errEffTOTPt1,"errEffTOTPt1/F"); // error matching efficiency mid pt




    ttree->Branch("Eff6Pt10",&Eff6Pt10,"Eff6Pt10/F"); // matching efficiency high pt 6 clusters
    ttree->Branch("errEff6Pt10",&errEff6Pt10,"errEff6Pt10/F"); // error matching efficiency high pt 6 clusters
    ttree->Branch("Eff5Pt10",&Eff5Pt10,"Eff5Pt10/F"); // matching efficiency high pt 5 clusters
    ttree->Branch("errEff5Pt10",&errEff5Pt10,"errEff5Pt10/F"); // error matching efficiency high pt 5 clusters
    ttree->Branch("Eff4Pt10",&Eff4Pt10,"Eff4Pt10/F"); // matching efficiency high pt 4 clusters
    ttree->Branch("errEff4Pt10",&errEff4Pt10,"errEff4Pt10/F"); // error matching efficiency high pt 4 clusters
    ttree->Branch("Eff3Pt10",&Eff3Pt10,"Eff3Pt10/F"); // matching efficiency high pt 3 clusters
    ttree->Branch("errEff3Pt10",&errEff3Pt10,"errEff3Pt10/F"); // error matching efficiency high pt 3 clusters
    ttree->Branch("Eff2Pt10",&Eff2Pt10,"Eff2Pt10/F"); // matching efficiency high pt 2 clusters
    ttree->Branch("errEff2Pt10",&errEff2Pt10,"errEff2Pt10/F"); // error matching efficiency high pt 2 clusters
    ttree->Branch("EffSPDPt10",&EffSPDPt10,"EffSPDPt10/F"); // matching efficiency high pt 2 SPD
    ttree->Branch("errEffSPDPt10",&errEffSPDPt10,"errEffSPDPt10/F"); // error matching efficiency high pt 2 SPD
    ttree->Branch("EffoneSPDPt10",&EffoneSPDPt10,"EffoneSPDPt10/F"); // matching efficiency high pt 6 one SPD
    ttree->Branch("errEffoneSPDPt10",&errEffoneSPDPt10,"errEffoneSPDPt10/F"); // error matching efficiency high pt one SPD
    ttree->Branch("EffTOTPt10",&EffTOTPt10,"EffTOTPt10/F"); // matching efficiency high pt
    ttree->Branch("errEffTOTPt10",&errEffTOTPt10,"errEffTOTPt10/F"); // error matching efficiency high pt

    
    
    ttree->Branch("FracSPD1",&FracSPD1,"FracSPD1/F"); // fraction SPD layers active on 1 layer
    ttree->Branch("errFracSPD1",&errFracSPD1,"errFracSPD1/F");

    ttree->Branch("FracSPD2",&FracSPD2,"FracSPD2/F"); // fraction SPD layers active on 1 layer
    ttree->Branch("errFracSPD2",&errFracSPD2,"errFracSPD2/F");
    
    
    ///////////////   Vertex part
    nrun=runNumber;
    
    
    char VertexDirName[25]="Vertex_Performance";
    
    char VertexListName[25]="cOutputVtxESD";
    
    TDirectoryFile * VertexQAdir=(TDirectoryFile*)fin->Get(VertexDirName);
    if (!VertexQAdir) {
        Printf("ERROR: Vertex QA directory not present in input file.\n");
        return -1;
    }
    TList * VertxList=(TList*)VertexQAdir->Get(VertexListName);
    
    
    if (!VertxList) Printf("WARNING: Vertex QA histograms absent or not accessible\n");
    
    
    
    
    Printf("Vertex - QA");
    
    
    Int_t iRun=runNumber;

    TH1F *xVtxTRK = (TH1F*)VertxList->FindObject("fhTRKVertexX");
    
    
    TH1F *yVtxTRK = (TH1F*)VertxList->FindObject("fhTRKVertexY");
    

    
    TH1F *zVtxTRK = (TH1F*)VertxList->FindObject("fhTRKVertexZ");
    
    
    TH1F *xVtxSPD = (TH1F*)VertxList->FindObject("fhSPDVertexX");
    
    if(xVtxSPD->GetEntries()==0){
        printf("Run %d xVtxSOD EMPTY -> Return\n",iRun);
        

    }
    
    TH1F *yVtxSPD = (TH1F*)VertxList->FindObject("fhSPDVertexY");
    
    if(yVtxSPD->GetEntries()==0){
        printf("Run %d yVtxSPD EMPTY -> Return\n",iRun);
        

    }
    
    TH1F *zVtxSPD = (TH1F*)VertxList->FindObject("fhSPDVertexZ");
    
    if(zVtxSPD->GetEntries()==0){
        printf("Run %d zVtxSPD EMPTY -> Return\n",iRun);
        

    }
    
    TF1 *fxTRK = new TF1("gausx", "gaus", -1, 1);
    xVtxTRK->Fit("gausx", "NQRL");
    
    TF1 *fyTRK = new TF1("gausy", "gaus", -1, 1);
    yVtxTRK->Fit("gausy","NQLR");
    
    TF1 *fzTRK = new TF1("gausz", "gaus", -1, 1);
    zVtxTRK->Fit("gausz","NQRL");
    TF1 *fxSPD = new TF1("gausxSPD", "gaus", -1, 1);
    xVtxSPD->Fit("gausxSPD", "NQRL");
    
    TF1 *fySPD = new TF1("gausySPD", "gaus", -1, 1);
    yVtxSPD->Fit("gausySPD","NQLR");
    
    TF1 *fzSPD = new TF1("gauszSPD", "gaus", -1, 1);
    zVtxSPD->Fit("gauszSPD","NQRL");


    meanVtxTRKx=(Float_t)fxTRK->GetParameter(1);
    meanVtxTRKxErr=(Float_t)fxTRK->GetParError(1);
    sigmaVtxTRKx=(Float_t)fxTRK->GetParameter(2);
    sigmaVtxTRKxErr=(Float_t)fxTRK->GetParError(2);
    meanVtxTRKy=(Float_t)fyTRK->GetParameter(1);
    meanVtxTRKyErr=(Float_t)fyTRK->GetParError(1);
    sigmaVtxTRKy=(Float_t)fyTRK->GetParameter(2);
    sigmaVtxTRKyErr=(Float_t)fyTRK->GetParError(2);
    meanVtxTRKz=(Float_t)fzTRK->GetParameter(1);
    meanVtxTRKzErr=(Float_t)fzTRK->GetParError(1);
    sigmaVtxTRKz=(Float_t)fzTRK->GetParameter(2);
    sigmaVtxTRKzErr=(Float_t)fzTRK->GetParError(2);
    meanVtxSPDx=(Float_t)fxSPD->GetParameter(1);
    meanVtxSPDxErr=(Float_t)fxSPD->GetParError(1);
    sigmaVtxSPDx=(Float_t)fxSPD->GetParameter(2);
    sigmaVtxSPDxErr=(Float_t)fxSPD->GetParError(2);
    meanVtxSPDy=(Float_t)fySPD->GetParameter(1);
    meanVtxSPDyErr=(Float_t)fySPD->GetParError(1);
    sigmaVtxSPDy=(Float_t)fySPD->GetParameter(2);
    sigmaVtxSPDyErr=(Float_t)fySPD->GetParError(2);
    meanVtxSPDz=(Float_t)fzSPD->GetParameter(1);
    sigmaVtxSPDzErr=(Float_t)fzSPD->GetParError(1);
    sigmaVtxSPDz=(Float_t)fzSPD->GetParameter(2);
    sigmaVtxSPDzErr=(Float_t)fzSPD->GetParError(2);
    
    
    /////////// end of vertex part
    
    
    ///////////////////////  SSD Part
    char SSDDirName[25]="PWGPPdEdxSSDQA";
    
    char SSDListName[25]="SSDdEdxQA";
    
    TDirectoryFile * SSDQAdir=(TDirectoryFile*)fin->Get(SSDDirName);
    if (!SSDQAdir) {
        Printf("ERROR: SSD QA directory not present in input file.\n");
        return -1;
    }
    TList * SSDList=(TList*)SSDQAdir->Get(SSDListName);
    
    
    if (!SSDList) Printf("WARNING: SSD QA histograms absent or not accessible\n");
    
    
    
    
    Printf("SSD - QA");
    

    MPVL5=0;
    MPVErrL5=0;
    MPVL6=0;
    MPVErrL6=0;
    ChargeRatioL5=0;
    ChargeRatioErrL5=0;
    ChargeRatioL6=0;
    ChargeRatioErrL6=0;
    EmptyModulesSDD=0;
    
    
    TH2F* QAchargeRatio=(TH2F*)SSDList->FindObject("QAChargeRatio");
    
    if(QAchargeRatio->GetEntries()==0){
        printf("Run %d QAchargeRatio EMPTY -> Return\n",iRun);
    }
    
    TH2F* QAcharge=(TH2F*)SSDList->FindObject("QACharge");
    
    if(QAcharge->GetEntries()==0){
        printf("Run %d QAcharge EMPTY -> Return\n",iRun);
        
    }
    
    if((QAcharge)&&(QAchargeRatio)&&(QAcharge->GetEntries()>10)&&(QAchargeRatio->GetEntries()>10)){

        Int_t biny = QAcharge->GetXaxis()->FindBin(747);
        Int_t maxy = QAcharge->GetXaxis()->GetXmax();

        Int_t  contEmpty=0;
        Int_t  contFull=0;

        TH1D *hChargeL5=QAcharge->ProjectionY("hChargeL5",0,biny);
        TH1D *hChargeL6=QAcharge->ProjectionY("hChargeL6",biny,maxy);



        TH1D *hChargeRatioL5=QAchargeRatio->ProjectionY("hChargeRatioL5",0,biny);
        TH1D *hChargeRatioL6=QAchargeRatio->ProjectionY("hChargeRatioL6",biny,maxy);


        if(QAcharge->GetEntries()< 45000)
            contEmpty=1;

        else{
            for(Int_t i =0;i<1698;i++){

                TString tmpQ("Q");
                tmpQ+=i;

                TH1D* fHist1DQ= QAcharge->ProjectionY(tmpQ,i+1,i+1);
                Double_t mean=fHist1DQ->GetMean();

                if(TMath::Abs(mean)<1.0 ||fHist1DQ->GetEntries()<10)
                    contEmpty++;

                else
                    contFull++;

            }
        }
        
        TF1 *lfunLay5 = new TF1("LangausFunLay5",LangausFun,50.,300.,4);
        lfunLay5->SetParameter(0,5.);
        lfunLay5->SetParameter(1,80.);
        lfunLay5->SetParameter(2,hChargeL5->GetEntries()/10.);
        lfunLay5->SetParameter(3,10.);
        lfunLay5->SetParLimits(3,0.,20);
        hChargeL5->Fit(lfunLay5,"NQLR");
        TF1 *lfunLay6 = new TF1("LangausFunLay6",LangausFun,50.,300.,4);
        lfunLay6->SetParameter(0,5.);
        lfunLay6->SetParameter(1,80.);
        lfunLay6->SetParameter(2,hChargeL6->GetEntries()/10.);
        lfunLay6->SetParameter(3,10.);
        lfunLay6->SetParLimits(3,0.,20);
        hChargeL6->Fit(lfunLay6,"NQLR");
        





        MPVL5=(Float_t)lfunLay5->GetParameter(1);
        MPVErrL5=(Float_t)lfunLay5->GetParError(1);
        MPVL6=(Float_t)lfunLay6->GetParameter(1);
        MPVErrL6=(Float_t)lfunLay6->GetParError(1);
        ChargeRatioL5=(Float_t)hChargeRatioL5->GetMean();
        ChargeRatioErrL5=(Float_t)hChargeRatioL5->GetMeanError();
        ChargeRatioL6=(Float_t)hChargeRatioL6->GetMean();
        ChargeRatioErrL6=(Float_t)hChargeRatioL6->GetMeanError();
        EmptyModulesSDD=(Float_t)contEmpty;

    }

    /////////// end of SSD part
    
    
    
    
    
    
    
    
    
    
    
    
    
    ///////////////////////  SDD Part
    char SDDDirName[25]="SDD_Performance";
    
    char SDDListName[15]="coutputRP";
    
    TDirectoryFile * SDDQAdir=(TDirectoryFile*)fin->Get(SDDDirName);
    if (!SDDQAdir) {
        Printf("ERROR: SDD QA directory not present in input file.\n");
        return -1;
    }
    TList * SDDList=(TList*)SDDQAdir->Get(SDDListName);
    
    
    if (!SDDList) Printf("WARNING: SDD QA histograms absent or not accessible\n");
    
    
    
    
    Printf("SDD - QA");
    
    
    TH1F* hcllay=(TH1F*)SDDList->FindObject("hCluInLay");
    
    


    if(hcllay->GetBinContent(1)>0){
        for(Int_t iLay=0; iLay<6; iLay++){
            fracT[iLay]=hcllay->GetBinContent(iLay+2)/hcllay->GetBinContent(1);
            efracT[iLay]=TMath::Sqrt(fracT[iLay]*(1-fracT[iLay])/hcllay->GetBinContent(1));
        }
    }

    fracTrackWithClu1=fracT[0];
    errfracTrackWithClu1=efracT[0];
    fracTrackWithClu2=fracT[1];
    errfracTrackWithClu2=efracT[1];
    fracTrackWithClu3=fracT[2];
    errfracTrackWithClu3=efracT[2];
    fracTrackWithClu4=fracT[3];
    errfracTrackWithClu4=efracT[3];
    fracTrackWithClu5=fracT[4];
    errfracTrackWithClu5=efracT[4];
    fracTrackWithClu6=fracT[5];
    errfracTrackWithClu6=efracT[5];
    
    cout<<endl<<errfracTrackWithClu6<<endl;

    TH1F* hmodT=(TH1F*)SDDList->FindObject("hTPMod");

    
    TH1F* hgamod=(TH1F*)SDDList->FindObject("hGAMod");
    


    
    TH1F* hev=(TH1F*)SDDList->FindObject("hNEvents");

    nTotEvents=hev->GetBinContent(2);
    nTrigEvents=hev->GetBinContent(3);
    nEvents=nTotEvents;


    
    TH1F* htimT=(TH1F*)SDDList->FindObject("hDrTimTPAll");

    
    TH1F* htimTe=(TH1F*)SDDList->FindObject("hDrTimTPExtra");
    

    if(htimT->GetEntries()>0){
        fracExtra=htimTe->GetEntries()/htimT->GetEntries();
        errfracExtra=TMath::Sqrt(htimTe->GetEntries())/htimT->GetEntries();
    }

    for(Int_t iBin=1; iBin<=htimT->GetNbinsX(); iBin++){
        Float_t tim=htimT->GetBinCenter(iBin);
        if(tim>2000. && tim<4000.){
            averPoints+=htimT->GetBinContent(iBin);
            cntBins+=1;
        }
    }

    if(cntBins>0){
        averPoints/=cntBins;
        for(Int_t iBin=1; iBin<=htimT->GetNbinsX(); iBin++){
            if(htimT->GetBinContent(iBin)>0.5*averPoints){
                minDrTime=htimT->GetBinCenter(iBin);
                errminDrTime=0.5*htimT->GetBinWidth(iBin);
                break;
            }
        }
    }
    meanDrTime=htimT->GetMean();
    errmeanDrTime=htimT->GetMeanError();
    TH2F* hdedxmod=(TH2F*)SDDList->FindObject("hdEdxVsMod");
    
    
    TH1D* hdedxLay3=hdedxmod->ProjectionY("hdedxLay3",1,84);
    TH1D* hdedxLay4=hdedxmod->ProjectionY("hdedxLay4",85,260);
    
    TH1F* hSigTim0=(TH1F*)SDDList->FindObject("hSigTimeInt0");

    
    TH1F* hSigTim5=(TH1F*)SDDList->FindObject("hSigTimeInt5");

    //Fitting the same distributions in order to have the MPV
    TF1 *lfunLay3 = new TF1("LangausFunLay3",LangausFun,50.,300.,4);
    lfunLay3->SetParameter(0,5.);
    lfunLay3->SetParameter(1,80.);
    lfunLay3->SetParameter(2,hdedxLay3->GetEntries()/10.);
    lfunLay3->SetParameter(3,10.);
    lfunLay3->SetParLimits(3,0.,20);
    hdedxLay3->Fit(lfunLay3,"NQLR");
    TF1 *lfunLay4 = new TF1("LangausFunLay4",LangausFun,50.,300.,4);
    lfunLay4->SetParameter(0,5.);
    lfunLay4->SetParameter(1,80.);
    lfunLay4->SetParameter(2,hdedxLay4->GetEntries()/10.);
    lfunLay4->SetParameter(3,10.);
    lfunLay4->SetParLimits(3,0.,20);
    hdedxLay4->Fit(lfunLay4,"NQLR");
    TF1 *lfunTim0 = new TF1("LangausFunTim0",LangausFun,50.,300.,4);
    lfunTim0->SetParameter(0,5.);
    lfunTim0->SetParameter(1,80.);
    lfunTim0->SetParameter(2,hSigTim0->GetEntries()/10.);
    lfunTim0->SetParameter(3,10.);
    lfunTim0->SetParLimits(3,0.,20);
    hSigTim0->Fit(lfunTim0,"NQLR");
    TF1 *lfunTim5 = new TF1("LangausFunTim5",LangausFun,50.,300.,4);
    lfunTim5->SetParameter(0,5.);
    lfunTim5->SetParameter(1,80.);
    lfunTim5->SetParameter(2,hSigTim5->GetEntries()/10.);
    lfunTim5->SetParameter(3,10.);
    lfunTim5->SetParLimits(3,0.,20);
    hSigTim5->Fit(lfunTim5,"NQLR");
    
    




    MPVdEdxLay3=lfunLay3->GetParameter(1);
    errMPVdEdxLay3=lfunLay3->GetParError(1);
    MPVdEdxLay4=lfunLay4->GetParameter(1);
    errMPVdEdxLay4=lfunLay4->GetParError(1);
    MPVdEdxTB0=lfunTim0->GetParameter(1);
    errMPVdEdxTB0=lfunTim0->GetParError(1);
    MPVdEdxTB5=lfunTim5->GetParameter(1);
    errMPVdEdxTB5=lfunTim5->GetParError(1);
    
    

    
    /////////// end of SDD part
    
    
    // Matching Part
    
    cout<<"Tracking"<<endl;
    
    TDirectoryFile *dirMatch=(TDirectoryFile*)fin->GetDirectory("ITS_Performance");
    TList *list=NULL;
    TList *listSPD=NULL;
    
    if(dirMatch) {

        list = (TList*)dirMatch->Get("cOutputITS"); // LHC12e
    }
    dirMatch=(TDirectoryFile*)fin->GetDirectory("SPD_Performance");
    if(dirMatch) listSPD = (TList*)dirMatch->Get("coutput1");
    
    // if(!list) return kFALSE;
    
    Float_t ioValues[30];
    Float_t ioErrors[30];
    for(Int_t jj=0;jj<30;jj++){
        ioValues[jj]=0.;
        ioErrors[jj]=0.;
    }
    
    Float_t ptbin=0;
    
    TH1F *hFiredChip = (TH1F*)listSPD->FindObject("hFiredChip");
    
    if(hFiredChip->GetEntries()==0){
        printf("Run %d hFiredChip EMPTY -> Return\n",iRun);
        
    }
    
    Int_t nHSsInner=0,nHSsOuter=0;
    for(Int_t i=0;i<400;i++) if(hFiredChip->GetBinContent(i)>0) nHSsInner++;
    for(Int_t i=400;i<1200;i++) if(hFiredChip->GetBinContent(i)>0) nHSsOuter++;
    nHSsInner = (Int_t)(nHSsInner/10);
    nHSsOuter = (Int_t)(nHSsOuter/10);
    
    ioValues[0]=(Float_t)nHSsInner/40.;
    ioValues[1]=(Float_t)nHSsOuter/80.;
    
    TH1F *fHistPtTPCInAcc = (TH1F*)list->FindObject("fHistPtTPCInAcc");
    Int_t check1=0;
    
    if(fHistPtTPCInAcc->GetEntries()==0){
        check1=1;
        printf("Run %dfHistPtTPCInAcc  EMPTY -> Return\n",iRun);
    }
    
    TH1F *fHistPtITSMI6InAcc = (TH1F*)list->FindObject("fHistPtITSMI6InAcc");

    
    TH1F *fHistPtITSMI5InAcc = (TH1F*)list->FindObject("fHistPtITSMI5InAcc");
    
    TH1F *fHistPtITSMI4InAcc = (TH1F*)list->FindObject("fHistPtITSMI4InAcc");
    
    TH1F *fHistPtITSMI3InAcc = (TH1F*)list->FindObject("fHistPtITSMI3InAcc");

    TH1F *fHistPtITSMI2InAcc = (TH1F*)list->FindObject("fHistPtITSMI2InAcc");
    
    TH1F *fHistPtITSMISPDInAcc = (TH1F*)list->FindObject("fHistPtITSMISPDInAcc");
    
    TH1F *fHistPtITSMIoneSPDInAcc = (TH1F*)list->FindObject("fHistPtITSMIoneSPDInAcc");
    
    
    
    TH1F *fHistPtITSMIge2InAcc = (TH1F*)fHistPtITSMI6InAcc->Clone("fHistPtITSMIge2InAcc");
    fHistPtITSMIge2InAcc->Add(fHistPtITSMI5InAcc);
    fHistPtITSMIge2InAcc->Add(fHistPtITSMI4InAcc);
    fHistPtITSMIge2InAcc->Add(fHistPtITSMI3InAcc);
    fHistPtITSMIge2InAcc->Add(fHistPtITSMI2InAcc);
    
    
    
    fHistPtITSMI6InAcc->Divide(fHistPtITSMI6InAcc,fHistPtTPCInAcc,1,1,"B");
    ptbin=fHistPtITSMI6InAcc->FindBin(0.201);
    ioValues[2]=fHistPtITSMI6InAcc->GetBinContent(ptbin);
    ioErrors[2]=fHistPtITSMI6InAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMI6InAcc->FindBin(1.001);
    ioValues[3]=fHistPtITSMI6InAcc->GetBinContent(ptbin);
    ioErrors[3]=fHistPtITSMI6InAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMI6InAcc->FindBin(10.001);
    ioValues[4]=fHistPtITSMI6InAcc->GetBinContent(ptbin);
    ioErrors[4]=fHistPtITSMI6InAcc->GetBinError(ptbin);
    
    fHistPtITSMI5InAcc->Divide(fHistPtITSMI5InAcc,fHistPtTPCInAcc,1,1,"B");
    
    ptbin=fHistPtITSMI5InAcc->FindBin(0.201);
    ioValues[5]=fHistPtITSMI5InAcc->GetBinContent(ptbin);
    ioErrors[5]=fHistPtITSMI5InAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMI5InAcc->FindBin(1.001);
    ioValues[6]=fHistPtITSMI5InAcc->GetBinContent(ptbin);
    ioErrors[6]=fHistPtITSMI5InAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMI5InAcc->FindBin(10.001);
    ioValues[7]=fHistPtITSMI5InAcc->GetBinContent(ptbin);
    ioErrors[7]=fHistPtITSMI5InAcc->GetBinError(ptbin);
    
    fHistPtITSMI4InAcc->Divide(fHistPtITSMI4InAcc,fHistPtTPCInAcc,1,1,"B");
    
    ptbin=fHistPtITSMI4InAcc->FindBin(0.201);
    ioValues[9]=fHistPtITSMI4InAcc->GetBinContent(ptbin);
    ioErrors[9]=fHistPtITSMI4InAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMI4InAcc->FindBin(1.001);
    ioValues[10]=fHistPtITSMI4InAcc->GetBinContent(ptbin);
    ioErrors[10]=fHistPtITSMI4InAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMI4InAcc->FindBin(10.001);
    ioValues[11]=fHistPtITSMI4InAcc->GetBinContent(ptbin);
    ioErrors[11]=fHistPtITSMI4InAcc->GetBinError(ptbin);
    
    fHistPtITSMI3InAcc->Divide(fHistPtITSMI3InAcc,fHistPtTPCInAcc,1,1,"B");
    
    ptbin=fHistPtITSMI3InAcc->FindBin(0.201);
    ioValues[12]=fHistPtITSMI3InAcc->GetBinContent(ptbin);
    ioErrors[12]=fHistPtITSMI3InAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMI3InAcc->FindBin(1.001);
    ioValues[13]=fHistPtITSMI3InAcc->GetBinContent(ptbin);
    ioErrors[13]=fHistPtITSMI3InAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMI3InAcc->FindBin(10.001);
    ioValues[14]=fHistPtITSMI3InAcc->GetBinContent(ptbin);
    ioErrors[14]=fHistPtITSMI3InAcc->GetBinError(ptbin);
    
    fHistPtITSMI2InAcc->Divide(fHistPtITSMI2InAcc,fHistPtTPCInAcc,1,1,"B");
    
    ptbin=fHistPtITSMI2InAcc->FindBin(0.201);
    ioValues[15]=fHistPtITSMI2InAcc->GetBinContent(ptbin);
    ioErrors[15]=fHistPtITSMI2InAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMI2InAcc->FindBin(1.001);
    ioValues[16]=fHistPtITSMI2InAcc->GetBinContent(ptbin);
    ioErrors[16]=fHistPtITSMI2InAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMI2InAcc->FindBin(10.001);
    ioValues[17]=fHistPtITSMI2InAcc->GetBinContent(ptbin);
    ioErrors[17]=fHistPtITSMI2InAcc->GetBinError(ptbin);
    
    fHistPtITSMISPDInAcc->Divide(fHistPtITSMISPDInAcc,fHistPtTPCInAcc,1,1,"B");
    ptbin=fHistPtITSMISPDInAcc->FindBin(0.201);
    ioValues[18]=fHistPtITSMISPDInAcc->GetBinContent(ptbin);
    ioErrors[18]=fHistPtITSMISPDInAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMISPDInAcc->FindBin(1.001);
    ioValues[19]=fHistPtITSMISPDInAcc->GetBinContent(ptbin);
    ioErrors[19]=fHistPtITSMISPDInAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMISPDInAcc->FindBin(10.001);
    ioValues[20]=fHistPtITSMISPDInAcc->GetBinContent(ptbin);
    ioErrors[20]=fHistPtITSMISPDInAcc->GetBinError(ptbin);
    
    fHistPtITSMIoneSPDInAcc->Divide(fHistPtITSMIoneSPDInAcc,fHistPtTPCInAcc,1,1,"B");
    
    ptbin=fHistPtITSMIoneSPDInAcc->FindBin(0.201);
    ioValues[21]=fHistPtITSMIoneSPDInAcc->GetBinContent(ptbin);
    ioErrors[21]=fHistPtITSMIoneSPDInAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMIoneSPDInAcc->FindBin(1.001);
    ioValues[22]=fHistPtITSMIoneSPDInAcc->GetBinContent(ptbin);
    ioErrors[22]=fHistPtITSMIoneSPDInAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMIoneSPDInAcc->FindBin(10.001);
    ioValues[23]=fHistPtITSMIoneSPDInAcc->GetBinContent(ptbin);
    ioErrors[23]=fHistPtITSMIoneSPDInAcc->GetBinError(ptbin);
    
    
    fHistPtITSMIge2InAcc->Divide(fHistPtITSMIge2InAcc,fHistPtTPCInAcc,1,1,"B");
    ptbin=fHistPtITSMIge2InAcc->FindBin(0.201);
    ioValues[24]=fHistPtITSMIge2InAcc->GetBinContent(ptbin);
    ioErrors[24]=fHistPtITSMIge2InAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMIge2InAcc->FindBin(1.001);
    ioValues[25]=fHistPtITSMIge2InAcc->GetBinContent(ptbin);
    ioErrors[25]=fHistPtITSMIge2InAcc->GetBinError(ptbin);
    ptbin=fHistPtITSMIge2InAcc->FindBin(10.001);
    ioValues[26]=fHistPtITSMIge2InAcc->GetBinContent(ptbin);
    ioErrors[26]=fHistPtITSMIge2InAcc->GetBinError(ptbin);
    
    FracSPD1=ioValues[0];
    errFracSPD1=ioErrors[0];
    FracSPD2=ioValues[1];
    errFracSPD2=ioErrors[1];
    Eff6Pt02=ioValues[2];
    errEff6Pt02=ioErrors[2];
    Eff6Pt1=ioValues[3];
    errEff6Pt1=ioErrors[3];
    Eff6Pt10=ioValues[4];
    errEff6Pt10=ioErrors[4];
    Eff5Pt02=ioValues[5];
    errEff5Pt02=ioErrors[5];
    Eff5Pt1=ioValues[6];
    errEff5Pt1=ioErrors[6];
    Eff5Pt10=ioValues[7];
    errEff5Pt10=ioErrors[7];
    Eff4Pt02=ioValues[8];
    errEff4Pt02=ioErrors[8];
    Eff4Pt1=ioValues[9];
    errEff4Pt1=ioErrors[9];
    Eff4Pt10=ioValues[10];
    errEff4Pt10=ioErrors[10];
    Eff3Pt02=ioValues[11];
    errEff3Pt02=ioErrors[11];
    Eff3Pt1=ioValues[12];
    errEff3Pt1=ioErrors[12];
    Eff3Pt10=ioValues[13];
    errEff3Pt10=ioErrors[13];
    Eff2Pt02=ioValues[14];
    errEff2Pt02=ioErrors[14];
    Eff2Pt1=ioValues[15];
    errEff2Pt1=ioErrors[15];
    Eff2Pt10=ioValues[16];
    errEff2Pt10=ioErrors[16];
    EffSPDPt02=ioValues[17];
    errEffSPDPt02=ioErrors[17];
    EffSPDPt1=ioValues[18];
    errEffSPDPt1=ioErrors[18];
    EffSPDPt10=ioValues[19];
    errEffSPDPt10=ioErrors[19];
    EffoneSPDPt02=ioValues[20];
    errEffoneSPDPt02=ioErrors[20];
    EffoneSPDPt1=ioValues[21];
    errEffoneSPDPt1=ioErrors[21];
    EffoneSPDPt10=ioValues[22];
    errEffoneSPDPt10=ioErrors[22];
    EffTOTPt02=ioValues[23];
    errEffTOTPt02=ioErrors[23];
    EffTOTPt1=ioValues[24];
    errEffTOTPt1=ioErrors[24];
    EffTOTPt10=ioValues[25];
    errEffTOTPt10=ioErrors[25];
    
    
    
    
    
    
    
    


    ttree->Fill();
    printf("==============  Saving trending quantities in tree for run %i ===============\n",runNumber);
    trendFile->cd();
    ttree->Write();
    trendFile->Close();


    return  1;
}
void IterTrackValHistoPublisher(char* newFile="NEW_FILE",char* refFile="REF_FILE")
{
  //gROOT->ProcessLine(".x HistoCompare_Tracks.C");
 gROOT ->Reset();
 gROOT ->SetBatch();

 //=========  settings ====================
 gROOT->SetStyle("Plain");
 gStyle->SetPadGridX(kTRUE);
 gStyle->SetPadGridY(kTRUE);
 gStyle->SetPadRightMargin(0.07);
 gStyle->SetPadLeftMargin(0.13);
 //gStyle->SetTitleXSize(0.07); 
 //gStyle->SetTitleXOffset(0.6); 
 //tyle->SetTitleYSize(0.3);
 //gStyle->SetLabelSize(0.6) 
 //gStyle->SetTextSize(0.5);
 char* refLabel("REF_LABEL, REF_RELEASE REFSELECTION");
 char* newLabel("NEW_LABEL, NEW_RELEASE NEWSELECTION");


 //=============================================


 delete gROOT->GetListOfFiles()->FindObject(refFile);
 delete gROOT->GetListOfFiles()->FindObject(newFile); 

 TText* te = new TText();
 TFile * sfile = new TFile(newFile);
 TDirectory * sdir=gDirectory;
 TFile * rfile = new TFile(refFile);
 TDirectory * rdir=gDirectory;

 if(sfile->GetDirectory("DQMData/Run 1/RecoTrackV")) sfile->cd("DQMData/Run 1/RecoTrackV/Run summary/Track");
 else if(sfile->GetDirectory("DQMData/RecoTrackV/Track"))sfile->cd("DQMData/RecoTrackV/Track");
 else if(sfile->GetDirectory("DQMData/Run 1/Tracking")) sfile->cd("DQMData/Run 1/Tracking/Run summary/Track");
 else if(sfile->GetDirectory("DQMData/Tracking/Track"))sfile->cd("DQMData/Tracking/Track");
 sdir=gDirectory;
 TList *sl= sdir->GetListOfKeys();
 TString collname2 =sl->At(0)->GetName(); 

 // select generalTracks to make the usual validation plots for
 int num_col = sl->GetSize();
 for(int i=0; i<num_col;i++){
   collname2 =sl->At(i)->GetName();
   if(collname2.Contains("general")) break;
 }
 //cout << "collname2 = " << collname2 << endl;

 if(rfile->GetDirectory("DQMData/Run 1/RecoTrackV")) rfile->cd("DQMData/Run 1/RecoTrackV/Run summary/Track");
 else if(rfile->GetDirectory("DQMData/RecoTrackV/Track"))rfile->cd("DQMData/RecoTrackV/Track");
 else if(rfile->GetDirectory("DQMData/Run 1/Tracking")) rfile->cd("DQMData/Run 1/Tracking/Run summary/Track");
 else if(rfile->GetDirectory("DQMData/Tracking/Track"))rfile->cd("DQMData/Tracking/Track");
 rdir=gDirectory;
 TList *rl= rdir->GetListOfKeys();
 TString collname1=rl->At(0)->GetName(); 

 num_col = rl->GetSize();
 for(int i=0; i<num_col;i++){
   collname1 =rl->At(i)->GetName();
   if(collname1.Contains("general")) break;
 }
 //cout << "collname1 = " << collname1 << endl;
 //int num_col = rl->GetSize();
 //for(int i=0; i<num_col;i++){
 //  cout << " >>>>>>>>>dir " << i << " name = " << rl->At(i)->GetName() << endl;
 //}

 //HistoCompare_Tracks * myPV = new HistoCompare_Tracks();

 TCanvas *canvas;

 TH1F *sh1,*rh1;
 TH1F *sh2,*rh2;
 TH1F *sh3,*rh3;
 TH1F *sh4,*rh4;
 TH1F *sh5,*rh5;
 TH1F *sh6,*rh6;

 TH1F *sc1,*rc1;
 TH1F *sc2,*rc2;
 TH1F *sc3,*rc3;

 bool hit=1;
 bool chi2=1;
 bool ctf=1;
 bool rs=0;


 //////////////////////////////////////
 /////////// CTF //////////////////////
 //////////////////////////////////////
 if (ctf){
   //===== building
   rdir->GetObject(collname1+"/effic",rh1);
   sdir->GetObject(collname2+"/effic",sh1);
   rh1->GetYaxis()->SetRangeUser(MINEFF,MAXEFF);
   sh1->GetYaxis()->SetRangeUser(MINEFF,MAXEFF);
   rh1->GetXaxis()->SetTitle("#eta");
   rh1->GetYaxis()->SetTitle("efficiency vs #eta");
   rh1->GetYaxis()->SetTitleSize(0.05);
   rh1->GetYaxis()->SetTitleOffset(1.2);
//   rh1->GetYaxis()->SetRangeUser(0.5,1.025);
//   sh1->GetYaxis()->SetRangeUser(0.5,1.025);
   rdir->GetObject(collname1+"/fakerate",rh2);
   sdir->GetObject(collname2+"/fakerate",sh2);
   rh2->GetYaxis()->SetRangeUser(0.,MAXFAKE);
   sh2->GetYaxis()->SetRangeUser(0.,MAXFAKE);
   rh2->GetXaxis()->SetTitle("#eta");
   rh2->GetYaxis()->SetTitle("fakerate vs #eta");
   rh2->GetYaxis()->SetTitleSize(0.05);
   rh2->GetYaxis()->SetTitleOffset(1.2);
//   rh2->GetYaxis()->SetRangeUser(0.,.70);
//   sh2->GetYaxis()->SetRangeUser(0.,.70);


   rdir->GetObject(collname1+"/efficPt",rh3);
   sdir->GetObject(collname2+"/efficPt",sh3);
   rh3->GetXaxis()->SetRangeUser(0,300);
   sh3->GetXaxis()->SetRangeUser(0,300);
   rh3->GetXaxis()->SetTitle("p_{t}");
   rh3->GetYaxis()->SetTitle("efficiency vs p_{t}");
   rh3->GetYaxis()->SetTitleSize(0.05);
   rh3->GetYaxis()->SetTitleOffset(1.2);
   rh3->SetTitle("");
   rdir->GetObject(collname1+"/fakeratePt",rh4);
   sdir->GetObject(collname2+"/fakeratePt",sh4);
   rh4->SetTitle("");
   rh4->GetXaxis()->SetTitle("p_{t}");
   rh4->GetYaxis()->SetTitle("fakrate vs p_{t}");
   rh4->GetYaxis()->SetTitleSize(0.05);
   rh4->GetYaxis()->SetTitleOffset(1.2);
   rh4->GetYaxis()->SetRangeUser(0.,.80);
   sh4->GetYaxis()->SetRangeUser(0.,.80);
   rh4->GetXaxis()->SetRangeUser(0.2,300);
   sh4->GetXaxis()->SetRangeUser(0.2,300);


   rdir->GetObject(collname1+"/effic_vs_hit",rh5);
   sdir->GetObject(collname2+"/effic_vs_hit",sh5);
   rh5->GetXaxis()->SetTitle("hits");
   rh5->GetYaxis()->SetTitle("efficiency vs hits");
   rh5->GetYaxis()->SetTitleSize(0.05);
   rh5->GetYaxis()->SetTitleOffset(1.2);
   //rh3->GetXaxis()->SetRangeUser(0,30);
   //sh3->GetXaxis()->SetRangeUser(0,30);
   rdir->GetObject(collname1+"/fakerate_vs_hit",rh6);
   sdir->GetObject(collname2+"/fakerate_vs_hit",sh6);
   rh6->GetYaxis()->SetRangeUser(0.,1.0);
   rh6->GetYaxis()->SetRangeUser(0.,1.0);
   rh6->GetXaxis()->SetTitle("hits");
   rh6->GetYaxis()->SetTitle("fakerate vs hits");
   rh6->GetYaxis()->SetTitleSize(0.05);
   rh6->GetYaxis()->SetTitleOffset(1.2);

   //rdir->GetObject(collname1+"/num_reco_pT",rh6);
   //sdir->GetObject(collname2+"/num_reco_pT",sh6);



   canvas = new TCanvas("Tracks","Tracks: efficiency & fakerate",1000,1400);


   //NormalizeHistograms(rh2,sh2);
   //NormalizeHistograms(rh6,sh6);
   //rh1->GetYaxis()->SetRangeUser(8,24);
   //sh1->GetYaxis()->SetRangeUser(8,24);

   //rh6->GetXaxis()->SetRangeUser(0,10);
   //sh6->GetXaxis()->SetRangeUser(0,10);

   TH1F * r[6]={rh1,rh2,rh3,rh4,rh5,rh6};
   TH1F * s[6]={sh1,sh2,sh3,sh4,sh5,sh6};

   plotBuilding(canvas,s, r,6,
		te,"UU",-1, 1, false, 0xC);

   canvas->cd();
   //TPaveText* text = new TPaveText(0.25,0.72,0.75,0.77,"prova");
   //text->SetFillColor(0);
   //text->SetTextColor(1);
   //text->Draw();
   l = new TLegend(0.10,0.64,0.90,0.69);
   l->SetTextSize(0.016);
   l->SetLineColor(1);
   l->SetLineWidth(1);
   l->SetLineStyle(1);
   l->SetFillColor(0);
   l->SetBorderSize(3);
   l->AddEntry(rh1,refLabel,"LPF");
   l->AddEntry(sh1,newLabel,"LPF");
   l->Draw();
   canvas->Print("building.pdf");   
   delete l;


   // ====== hits and pt
   rdir->GetObject(collname1+"/nhits_vs_eta_pfx",(TProfile*)rh1);                                                                                                                                                                                
   sdir->GetObject(collname2+"/nhits_vs_eta_pfx",(TProfile*)sh1);                                                                                                                                                                                
   rdir->GetObject(collname1+"/hits",rh2);                                                                                                                                                                                    
   sdir->GetObject(collname2+"/hits",sh2);         
   
   rdir->GetObject(collname1+"/num_simul_pT",rh3);
   sdir->GetObject(collname2+"/num_simul_pT",sh3);
   rdir->GetObject(collname1+"/num_reco_pT",rh4);
   sdir->GetObject(collname2+"/num_reco_pT",sh4);
   
   canvas = new TCanvas("Tracks1","Tracks: hits and Pt",1000,1050);
   
   rh1->GetYaxis()->SetRangeUser(8,24);
   sh1->GetYaxis()->SetRangeUser(8,24);
   rh1->GetXaxis()->SetTitle("#eta");
   rh1->GetYaxis()->SetTitle("<hits> vs #eta");
   rh2->GetXaxis()->SetRangeUser(0,30);
   sh2->GetXaxis()->SetRangeUser(0,30);
   rh2->GetXaxis()->SetTitle("hits");


   rh3->GetXaxis()->SetRangeUser(0,10);
   sh3->GetXaxis()->SetRangeUser(0,10);
   rh3->GetXaxis()->SetTitle("p_{t}");
   rh4->GetXaxis()->SetRangeUser(0,10);
   sh4->GetXaxis()->SetRangeUser(0,10);
   rh4->GetXaxis()->SetTitle("p_{t}");
   NormalizeHistograms(rh3,sh3);
   NormalizeHistograms(rh4,sh4);
   
   plot4histos(canvas,
	      sh1,rh1,sh2,rh2,
	      sh3,rh3,sh4,rh4,
	      te,"UU",-1);
   
   canvas->cd();
   
   l = new TLegend(0.20,0.49,0.90,0.54);
   l->SetTextSize(0.016);
   l->SetLineColor(1);
   l->SetLineWidth(1);
   l->SetLineStyle(1);
   l->SetFillColor(0);
   l->SetBorderSize(3);
   l->AddEntry(rh1,refLabel,"LPF");
   l->AddEntry(sh1,newLabel,"LPF");
   l->Draw();
   canvas->Print("hitsAndPt.pdf");
   delete l;


   //===== tuning
   rdir->GetObject(collname1+"/chi2",rh1);
   sdir->GetObject(collname2+"/chi2",sh1);
   rdir->GetObject(collname1+"/chi2_prob",rh2);
   sdir->GetObject(collname2+"/chi2_prob",sh2);
   rdir->GetObject(collname1+"/chi2_vs_eta_pfx",(TProfile*)rh3);
   sdir->GetObject(collname2+"/chi2_vs_eta_pfx",(TProfile*)sh3);

   rdir->GetObject(collname1+"/ptres_vs_eta_Mean",rh4);
   sdir->GetObject(collname2+"/ptres_vs_eta_Mean",sh4);


   canvas = new TCanvas("Tracks2","Tracks: chi2 & chi2 probability",1000,1050);

   NormalizeHistograms(rh1,sh1);
   NormalizeHistograms(rh2,sh2);
   fixRangeY(rh1,sh1);
   fixRangeY(rh2,sh2);
   rh1->GetXaxis()->SetTitle("#chi^{2}");
   rh2->GetXaxis()->SetTitle("Prob(#chi^{2})");
   
   rh3->GetYaxis()->SetRangeUser(0,2.5);
   sh3->GetYaxis()->SetRangeUser(0,2.5);


   rh3->SetTitle("");
   rh3->GetYaxis()->SetTitleSize(0.05);
   rh3->GetYaxis()->SetTitleOffset(1.2);
   rh3->GetYaxis()->SetTitle("<  #chi^{2} / ndf >");
   rh3->GetXaxis()->SetTitleSize(0.07);
   rh3->GetXaxis()->SetTitleOffset(0.6);
   rh3->GetXaxis()->SetTitle("#eta");

   rh4->Scale(100.);
   sh4->Scale(100.);
   rh4->GetYaxis()->SetRangeUser(-1.5,1.5);
   sh4->GetYaxis()->SetRangeUser(-1.5,1.5);
   rh4->SetTitle("");
   rh4->GetYaxis()->SetTitleSize(0.05);
   rh4->GetYaxis()->SetTitleOffset(1.2);
   rh4->GetYaxis()->SetTitle("< #delta p_{t} / p_{t} > [%]");
   rh4->GetXaxis()->SetTitleSize(0.07);
   rh4->GetXaxis()->SetTitleOffset(0.6);
   rh4->GetXaxis()->SetTitle("#eta");

     
   plot4histos(canvas,
	       sh1,rh1,sh2,rh2,
	       sh3,rh3,sh4,rh4,    
	       te,"UU",-1);
   
   canvas->cd();   
   l = new TLegend(0.20,0.48,0.90,0.53);
   l->SetTextSize(0.016);
   l->SetLineColor(1);
   l->SetLineWidth(1);
   l->SetLineStyle(1);
   l->SetFillColor(0);
   l->SetBorderSize(3);
   l->AddEntry(rh1,refLabel,"LPF");
   l->AddEntry(sh1,newLabel,"LPF");
   l->Draw();
   canvas->Print("tuning.pdf");
   delete l;
   

   //===== pulls
   rdir->GetObject(collname1+"/pullPt",rh1);
   sdir->GetObject(collname2+"/pullPt",sh1);

   rdir->GetObject(collname1+"/pullQoverp",rh2);
   sdir->GetObject(collname2+"/pullQoverp",sh2);

   rdir->GetObject(collname1+"/pullPhi",rh3);

   sdir->GetObject(collname2+"/pullPhi",sh3);

   rdir->GetObject(collname1+"/pullTheta",rh4);
   sdir->GetObject(collname2+"/pullTheta",sh4);

   rdir->GetObject(collname1+"/pullDxy",rh5);
   sdir->GetObject(collname2+"/pullDxy",sh5);

   rdir->GetObject(collname1+"/pullDz",rh6);
   sdir->GetObject(collname2+"/pullDz",sh6);


   canvas = new TCanvas("Tracks4","Tracks: pull of Pt, Qoverp and Phi",1000,1400);

   NormalizeHistograms(rh1,sh1);
   NormalizeHistograms(rh2,sh2);
   NormalizeHistograms(rh3,sh3);
   NormalizeHistograms(rh4,sh4);
   NormalizeHistograms(rh5,sh5);
   NormalizeHistograms(rh6,sh6);

   rh1->GetXaxis()->SetRangeUser(-10,10);
   sh1->GetXaxis()->SetRangeUser(-10,10);
   rh2->GetXaxis()->SetRangeUser(-10,10);
   sh2->GetXaxis()->SetRangeUser(-10,10);
   rh3->GetXaxis()->SetRangeUser(-10,10);
   sh3->GetXaxis()->SetRangeUser(-10,10);
   rh4->GetXaxis()->SetRangeUser(-10,10);
   sh4->GetXaxis()->SetRangeUser(-10,10);
   rh5->GetXaxis()->SetRangeUser(-10,10);
   sh5->GetXaxis()->SetRangeUser(-10,10);
   rh6->GetXaxis()->SetRangeUser(-10,10);
   sh6->GetXaxis()->SetRangeUser(-10,10);


   plotPulls(canvas,
	     sh1,rh1,sh2,rh2,
	     sh3,rh3,sh4,rh4,
	     sh5,rh5,sh6,rh6,
	     te,"UU",-1);

   canvas->cd();

   l = new TLegend(0.20,0.655,0.80,0.69);
   l->SetTextSize(0.016);
   l->SetLineColor(1);
   l->SetLineWidth(1);
   l->SetLineStyle(1);
   l->SetFillColor(0);
   l->SetBorderSize(3);
   l->AddEntry(rh1,refLabel,"LPF");
   l->AddEntry(sh1,newLabel,"LPF");
   l->Draw();
   canvas->Print("pulls.pdf");
   delete l;




   

   //===== resolutions vs eta
   rdir->GetObject(collname1+"/phires_vs_eta_Sigma",rh1);
   sdir->GetObject(collname2+"/phires_vs_eta_Sigma",sh1);

   rdir->GetObject(collname1+"/cotThetares_vs_eta_Sigma",rh2);
   sdir->GetObject(collname2+"/cotThetares_vs_eta_Sigma",sh2);

   rdir->GetObject(collname1+"/dxyres_vs_eta_Sigma",rh3);
   sdir->GetObject(collname2+"/dxyres_vs_eta_Sigma",sh3);

   rdir->GetObject(collname1+"/dzres_vs_eta_Sigma",rh4);
   sdir->GetObject(collname2+"/dzres_vs_eta_Sigma",sh4);

   rdir->GetObject(collname1+"/ptres_vs_eta_Sigma",rh5);
   sdir->GetObject(collname2+"/ptres_vs_eta_Sigma",sh5);



   canvas = new TCanvas("Tracks7","Tracks: Dxy, Dz, Theta resolution",1000,1400);

   plotResolutions(canvas,
		   sh1,rh1,sh2,rh2,
		   sh3,rh3,sh4,rh4,
		   sh5,rh5,sh6,rh6,
		   te,"UU",-1);
   
   // new general range
   rh1->GetYaxis()->SetRangeUser(0.000009,0.01);
   sh1->GetYaxis()->SetRangeUser(0.000009,0.01);

   rh1->SetTitle(""); 
   rh1->GetYaxis()->SetTitleSize(0.05);
   rh1->GetYaxis()->SetTitleOffset(1.2);
   //   rh1->GetYaxis()->SetTitleColor(2);
   rh1->GetYaxis()->SetTitle("#sigma(#delta #phi) [rad]");
   rh1->GetXaxis()->SetTitleSize(0.07);
   rh1->GetXaxis()->SetTitleOffset(0.6);
   rh1->GetXaxis()->SetTitle("#eta");


   // new general range
   rh2->GetYaxis()->SetRangeUser(0.00009,0.03);
   sh2->GetYaxis()->SetRangeUser(0.00009,0.03);
   // for multi-track samples
   //rh2->GetYaxis()->SetRangeUser(0.0009,0.01);
   //sh2->GetYaxis()->SetRangeUser(0.0009,0.01);
   // for single particle pt 10
   //rh2->GetYaxis()->SetRangeUser(0.00009,0.01);
   //sh2->GetYaxis()->SetRangeUser(0.00009,0.01);
   // for single particle pt 1
   //rh2->GetYaxis()->SetRangeUser(0.0009,0.01);
   //sh2->GetYaxis()->SetRangeUser(0.0009,0.01);
   rh2->SetTitle("");
   rh2->GetYaxis()->SetTitleSize(0.05);
   rh2->GetYaxis()->SetTitleOffset(1.2);
   rh2->GetYaxis()->SetTitle("#sigma(#delta cot(#theta)) ");
   rh2->GetXaxis()->SetTitleSize(0.07);
   rh2->GetXaxis()->SetTitleOffset(0.6);
   rh2->GetXaxis()->SetTitle("#eta");


   // new general range
   rh3->GetYaxis()->SetRangeUser(0.00009,0.05);  
   sh3->GetYaxis()->SetRangeUser(0.00009,0.05);
   // for multi-track samples
   //rh3->GetYaxis()->SetRangeUser(0.0009,0.02);  
   //sh3->GetYaxis()->SetRangeUser(0.0009,0.02);
   //rh3->GetYaxis()->SetRangeUser(0.0009,0.02);
   //sh3->GetYaxis()->SetRangeUser(0.0009,0.02);
   // for single particle pt 100    
   //rh3->GetYaxis()->SetRangeUser(0.00009,0.002);
   //sh3->GetYaxis()->SetRangeUser(0.00009,0.002);
   rh3->SetTitle("");
   rh3->GetYaxis()->SetTitleSize(0.05);
   rh3->GetYaxis()->SetTitleOffset(1.2);
   rh3->GetYaxis()->SetTitle("#sigma(#delta d_{0}) [cm]");
   rh3->GetXaxis()->SetTitleSize(0.07);
   rh3->GetXaxis()->SetTitleOffset(0.6);
   rh3->GetXaxis()->SetTitle("#eta"); 


   // new general range
   rh4->GetYaxis()->SetRangeUser(0.0009,0.1);  
   sh4->GetYaxis()->SetRangeUser(0.0009,0.1);
   // for multi-track samples
   //rh4->GetYaxis()->SetRangeUser(0.0009,0.08);
   //sh4->GetYaxis()->SetRangeUser(0.0009,0.08);

   rh4->SetTitle("");
   rh4->GetYaxis()->SetTitleSize(0.05);
   rh4->GetYaxis()->SetTitleOffset(1.2);
   rh4->GetYaxis()->SetTitle("#sigma(#delta z_{0}) [cm]");
   rh4->GetXaxis()->SetTitleSize(0.07);
   rh4->GetXaxis()->SetTitleOffset(0.6);
   rh4->GetXaxis()->SetTitle("#eta");

   rh5->SetTitle("");
   rh5->GetYaxis()->SetTitleSize(0.05);
   rh5->GetYaxis()->SetTitleOffset(1.2);
   rh5->GetYaxis()->SetTitle("#sigma(#delta p_{t}/p_{t}) ");
   rh5->GetXaxis()->SetTitleSize(0.07);
   rh5->GetXaxis()->SetTitleOffset(0.6);
   rh5->GetXaxis()->SetTitle("#eta");



   /* plotResolutions(canvas,
	     sh1,rh1,sh2,rh2,
	     sh3,rh3,sh4,rh4,
	     sh5,rh5,sh6,rh6,
	     te,"UU",-1);
   */
   canvas->cd();

   l = new TLegend(0.10,0.63,0.90,0.67);
   l->SetTextSize(0.016);
   l->SetLineColor(1);
   l->SetLineWidth(1);
   l->SetLineStyle(1);
   l->SetFillColor(0);
   l->SetBorderSize(3);
   l->AddEntry(rh1,refLabel,"LPF");
   l->AddEntry(sh1,newLabel,"LPF");
   l->Draw();
   canvas->Print("resolutionsEta.pdf");
   delete l;

   //===== resolutions vs pt
   rdir->GetObject(collname1+"/phires_vs_pt_Sigma",rh1);
   sdir->GetObject(collname2+"/phires_vs_pt_Sigma",sh1);

   rdir->GetObject(collname1+"/cotThetares_vs_pt_Sigma",rh2);
   sdir->GetObject(collname2+"/cotThetares_vs_pt_Sigma",sh2);


   rdir->GetObject(collname1+"/dxyres_vs_pt_Sigma",rh3);
   sdir->GetObject(collname2+"/dxyres_vs_pt_Sigma",sh3);

   rdir->GetObject(collname1+"/dzres_vs_pt_Sigma",rh4);
   sdir->GetObject(collname2+"/dzres_vs_pt_Sigma",sh4);

   rdir->GetObject(collname1+"/ptres_vs_pt_Sigma",rh5);
   sdir->GetObject(collname2+"/ptres_vs_pt_Sigma",sh5);


   rh1->SetTitle("");
   rh1->GetYaxis()->SetTitleSize(0.05);
   rh1->GetYaxis()->SetTitleOffset(1.2);
   rh1->GetYaxis()->SetTitle("#sigma(#delta #phi) [rad]");
   rh1->GetXaxis()->SetTitleSize(0.055);
   rh1->GetXaxis()->SetTitleOffset(0.8);
   rh1->GetXaxis()->SetTitle("p_{t}");
   rh1->GetXaxis()->SetRangeUser(0,1000.);
   sh1->GetXaxis()->SetRangeUser(0,1000.);
 

   rh2->SetTitle("");
   rh2->GetYaxis()->SetTitleSize(0.05);
   rh2->GetYaxis()->SetTitleOffset(1.2);
   rh2->GetYaxis()->SetTitle("#sigma(#delta cot(#theta)) ");
   rh2->GetXaxis()->SetTitleSize(0.055);
   rh2->GetXaxis()->SetTitleOffset(0.8);
   rh2->GetXaxis()->SetTitle("p_{t}");

   rh2->GetXaxis()->SetRangeUser(0,1000.);
   sh2->GetXaxis()->SetRangeUser(0,1000.);

   rh3->SetTitle("");
   rh3->GetYaxis()->SetTitleSize(0.05);
   rh3->GetYaxis()->SetTitleOffset(1.2);
   rh3->GetYaxis()->SetTitle("#sigma(#delta d_{0}) [cm]");
   rh3->GetXaxis()->SetTitleSize(0.055);
   rh3->GetXaxis()->SetTitleOffset(0.8);
   rh3->GetXaxis()->SetTitle("p_{t}");


   rh3->GetXaxis()->SetRangeUser(0,1000.);
   sh3->GetXaxis()->SetRangeUser(0,1000.);


   rh4->SetTitle("");
   rh4->GetYaxis()->SetTitleSize(0.05);
   rh4->GetYaxis()->SetTitleOffset(1.2);
   rh4->GetYaxis()->SetTitle("#sigma(#delta z_{0}) [cm]");
   rh4->GetXaxis()->SetTitleSize(0.055);
   rh4->GetXaxis()->SetTitleOffset(0.8);
   rh4->GetXaxis()->SetTitle("p_{t}");

   rh4->GetXaxis()->SetRangeUser(0,1000.);
   sh4->GetXaxis()->SetRangeUser(0,1000.);


   rh5->SetTitle("");
   rh5->GetYaxis()->SetTitleSize(0.05);
   rh5->GetYaxis()->SetTitleOffset(1.2);
   rh5->GetYaxis()->SetTitle("#sigma(#delta p_{t}/p_{t}) ");
   rh5->GetXaxis()->SetTitleSize(0.055);
   rh5->GetXaxis()->SetTitleOffset(0.8);
   rh5->GetXaxis()->SetTitle("p_{t}");


   rh5->GetXaxis()->SetRangeUser(0,1000.);
   sh5->GetXaxis()->SetRangeUser(0,1000.);


   rh6->GetXaxis()->SetRangeUser(0,1000.);
   sh6->GetXaxis()->SetRangeUser(0,1000.);


   canvas = new TCanvas("Tracks7b","Tracks: Dxy, Dz, Theta resolution",1000,1400);

   plotResolutions(canvas,
	     sh1,rh1,sh2,rh2,
	     sh3,rh3,sh4,rh4,
	     sh5,rh5,sh6,rh6,
		   te,"UU",-1, true);

   canvas->cd();

   l = new TLegend(0.10,0.63,0.90,0.67);
   l->SetTextSize(0.016);
   l->SetLineColor(1);
   l->SetLineWidth(1);
   l->SetLineStyle(1);
   l->SetFillColor(0);
   l->SetBorderSize(3);
   l->AddEntry(rh1,refLabel,"LPF");
   l->AddEntry(sh1,newLabel,"LPF");
   l->Draw();
   canvas->Print("resolutionsPt.pdf");
   delete l;


    //===== building 2
   rdir->GetObject(collname1+"/effic_vs_phi",rh1);
   sdir->GetObject(collname2+"/effic_vs_phi",sh1);
   rh1->GetYaxis()->SetRangeUser(MINEFF,MAXEFF);
   sh1->GetYaxis()->SetRangeUser(MINEFF,MAXEFF);
   rh1->GetXaxis()->SetTitle("#phi");
   rh1->GetYaxis()->SetTitle("efficiency vs #phi");
   rh1->GetYaxis()->SetTitleSize(0.05);
   rh1->GetYaxis()->SetTitleOffset(1.2);
   rdir->GetObject(collname1+"/fakerate_vs_phi",rh2);
   sdir->GetObject(collname2+"/fakerate_vs_phi",sh2);
   rh2->GetXaxis()->SetTitle("#phi");
   rh2->GetYaxis()->SetTitle("fakerate vs #phi");
   rh2->GetYaxis()->SetRangeUser(0.,MAXFAKE);
   sh2->GetYaxis()->SetRangeUser(0.,MAXFAKE);
   rh2->GetYaxis()->SetTitleSize(0.05);
   rh2->GetYaxis()->SetTitleOffset(1.2);



   rdir->GetObject(collname1+"/effic_vs_dxy",rh3);
   sdir->GetObject(collname2+"/effic_vs_dxy",sh3);
   rh3->GetXaxis()->SetTitle("dxy");
   rh3->GetYaxis()->SetTitle("efficiency vs dxy");
   rh3->GetYaxis()->SetRangeUser(MINEFF,MAXEFF);
   sh3->GetYaxis()->SetRangeUser(MINEFF,MAXEFF);
   rh3->GetYaxis()->SetTitleSize(0.05);
   rh3->GetYaxis()->SetTitleOffset(1.2);
   rh3->SetTitle("");
   rdir->GetObject(collname1+"/fakerate_vs_dxy",rh4);
   sdir->GetObject(collname2+"/fakerate_vs_dxy",sh4);
   rh4->SetTitle("");
   rh4->GetXaxis()->SetTitle("dxy");
   rh4->GetYaxis()->SetTitle("fakerate vs dxy");
   rh4->GetYaxis()->SetTitleSize(0.05);
   rh4->GetYaxis()->SetTitleOffset(1.2);
   rh4->GetYaxis()->SetRangeUser(0.,MAXFAKE);
   sh4->GetYaxis()->SetRangeUser(0.,MAXFAKE);


   rdir->GetObject(collname1+"/effic_vs_dz",rh5);
   sdir->GetObject(collname2+"/effic_vs_dz",sh5);
   rh5->GetXaxis()->SetTitle("dz");
   rh5->GetYaxis()->SetTitle("efficiency vs dz");
   rh5->GetYaxis()->SetTitleSize(0.05);
   rh5->GetYaxis()->SetTitleOffset(1.2);
   rh5->GetYaxis()->SetRangeUser(MINEFF,MAXEFF);
   sh5->GetYaxis()->SetRangeUser(MINEFF,MAXEFF);
   rdir->GetObject(collname1+"/fakerate_vs_dz",rh6);
   sdir->GetObject(collname2+"/fakerate_vs_dz",sh6);
   rh6->GetYaxis()->SetRangeUser(0.,1.0);
   rh6->GetYaxis()->SetRangeUser(0.,1.0);
   rh6->GetXaxis()->SetTitle("dz");
   rh6->GetYaxis()->SetTitle("fakerate vs dz");
   rh6->GetYaxis()->SetTitleSize(0.05);
   rh6->GetYaxis()->SetTitleOffset(1.2);

   canvas = new TCanvas("Tracks8","Tracks: efficiency & fakerate",1000,1400);

   TH1F * r[6]={rh1,rh2,rh3,rh4,rh5,rh6};
   TH1F * s[6]={sh1,sh2,sh3,sh4,sh5,sh6};

   plotBuilding(canvas,s, r,6,
		te,"UU",-1);

   canvas->cd();
   l = new TLegend(0.10,0.64,0.90,0.69);
   l->SetTextSize(0.016);
   l->SetLineColor(1);
   l->SetLineWidth(1);
   l->SetLineStyle(1);
   l->SetFillColor(0);
   l->SetBorderSize(3);
   l->AddEntry(rh1,refLabel,"LPF");
   l->AddEntry(sh1,newLabel,"LPF");
   l->Draw();
   canvas->Print("building2.pdf");   
   delete l;

    //===== building 3
   rdir->GetObject(collname1+"/effic_vs_vertpos",rh1);
   sdir->GetObject(collname2+"/effic_vs_vertpos",sh1);
   rh1->GetYaxis()->SetRangeUser(MINEFF,MAXEFF);
   sh1->GetYaxis()->SetRangeUser(MINEFF,MAXEFF);
   rh1->GetXaxis()->SetTitle("TP vert xy pos");
   rh1->GetYaxis()->SetTitle("efficiency vs vert xy pos");
   rh1->GetYaxis()->SetTitleSize(0.05);
   rh1->GetYaxis()->SetTitleOffset(1.2);

   rdir->GetObject(collname1+"/effic_vs_zpos",rh2);
   sdir->GetObject(collname2+"/effic_vs_zpos",sh2);
   rh2->GetXaxis()->SetTitle("TP vert z pos");
   rh2->GetYaxis()->SetTitle("efficiency vs  vert z pos");
   rh2->GetYaxis()->SetRangeUser(MINEFF,MAXEFF);
   sh2->GetYaxis()->SetRangeUser(MINEFF,MAXEFF);
   rh2->GetYaxis()->SetTitleSize(0.05);
   rh2->GetYaxis()->SetTitleOffset(1.2);
   rh2->SetTitle("");

   canvas = new TCanvas("Tracks9","Tracks: efficiency & fakerate",1000,1400);

   TH1F * r[2]={rh1,rh2};
   TH1F * s[2]={sh1,sh2};

   plotBuilding(canvas,s, r,2,
		te,"UU",-1);

   canvas->cd();
   l = new TLegend(0.10,0.14,0.90,0.19);
   l->SetTextSize(0.016);
   l->SetLineColor(1);
   l->SetLineWidth(1);
   l->SetLineStyle(1);
   l->SetFillColor(0);
   l->SetBorderSize(3);
   l->AddEntry(rh1,refLabel,"LPF");
   l->AddEntry(sh1,newLabel,"LPF");
   l->Draw();
   canvas->Print("building3.pdf");   
   delete l;

   //======== plots of eff, fake rates for various iterative tracking steps
   //== we assume that the ref and new have the same histogram list! (and there are 6!)
   // HERE
//   TString refcollname=rl->At(0)->GetName();
//   TString newcollname=sl->At(0)->GetName();
//   num_col = rl->GetSize();
   TH1F * r[6];
   TH1F * s[6];
//   // eff vs eta
//   for(int i=0; i<num_col;i++){
//     refcollname =rl->At(i)->GetName();
//     newcollname =sl->At(i)->GetName();
//     rdir->GetObject(refcollname+"/effic",r[i]);
//     sdir->GetObject(newcollname+"/effic",s[i]);
//     //r[i]->GetYaxis()->SetRangeUser(MINEFF,MAXEFF);
//     //s[i]->GetYaxis()->SetRangeUser(MINEFF,MAXEFF);
//     r[i]->GetYaxis()->SetRangeUser(0.,MAXEFF);
//     s[i]->GetYaxis()->SetRangeUser(0.,MAXEFF);
//     r[i]->GetXaxis()->SetTitle("#eta");
//     r[i]->GetYaxis()->SetTitle("efficiency vs #eta");
//     r[i]->GetYaxis()->SetTitleSize(0.05);
//     r[i]->GetYaxis()->SetTitleOffset(1.2);
//     r[i]->SetTitle(refcollname);
//     if(i==2 || i==3) {
//       //r[i]->SetTitleY(0.);
//       //r[i]->SetTitle("");
//       r[i]->SetTitleOffset(-1.,"HIST");
//     }
//   }
   // fill with the histos we want for eff
   fillStepHisto(rdir, sdir, rl, sl, r, s, "/effic", "#eta", "efficiency vs #eta", 0., MAXEFF);
   // rearrange to a more natural order for plotting
   TH1F * rr[6]={r[5],r[2],r[0],r[3],r[4],r[1]};
   TH1F * ss[6]={s[5],s[2],s[0],s[3],s[4],s[1]};

   canvas = new TCanvas("Tracks10","Tracks: efficiency for each step",1000,1400);

   plotBuilding(canvas,ss, rr,6,
		te,"UU",-69);

   canvas->cd();
   l = new TLegend(0.10,0.64,0.90,0.69);
   l->SetTextSize(0.016);
   l->SetLineColor(1);
   l->SetLineWidth(1);
   l->SetLineStyle(1);
   l->SetFillColor(0);
   l->SetBorderSize(3);
   l->AddEntry(r[0],refLabel,"LPF");
   l->AddEntry(s[0],newLabel,"LPF");
   l->Draw();
   canvas->Print("steps_eff.pdf");   
   delete l;

   // fill with the histos we want for fake rate
   fillStepHisto(rdir, sdir, rl, sl, r, s, "/fakerate", "#eta", "fakerate vs #eta", 0., MAXFAKE);
   // rearrange to a more natural order for plotting
   TH1F * rr[6]={r[5],r[2],r[0],r[3],r[4],r[1]};
   TH1F * ss[6]={s[5],s[2],s[0],s[3],s[4],s[1]};

   canvas = new TCanvas("Tracks11","Tracks: fakerate for each step",1000,1400);

   plotBuilding(canvas,ss, rr,6,
		te,"UU",-69);

   canvas->cd();
   l = new TLegend(0.10,0.64,0.90,0.69);
   l->SetTextSize(0.016);
   l->SetLineColor(1);
   l->SetLineWidth(1);
   l->SetLineStyle(1);
   l->SetFillColor(0);
   l->SetBorderSize(3);
   l->AddEntry(r[0],refLabel,"LPF");
   l->AddEntry(s[0],newLabel,"LPF");
   l->Draw();
   canvas->Print("steps_fakerate.pdf");   
   delete l;

   // fill with the histos we want for eff vs pT
   fillStepHisto(rdir, sdir, rl, sl, r, s, "/efficPt", "p_{t}", "efficiency vs p_{t}", 0., MAXEFF);
   // rearrange to a more natural order for plotting
   TH1F * rr[6]={r[5],r[2],r[0],r[3],r[4],r[1]};
   TH1F * ss[6]={s[5],s[2],s[0],s[3],s[4],s[1]};

   canvas = new TCanvas("Tracks12","Tracks: efficiency for each step",1000,1400);

   plotBuilding(canvas,ss, rr,6,
		te,"UU",-69, 1, false, 127);

   canvas->cd();
   l = new TLegend(0.10,0.64,0.90,0.69);
   l->SetTextSize(0.016);
   l->SetLineColor(1);
   l->SetLineWidth(1);
   l->SetLineStyle(1);
   l->SetFillColor(0);
   l->SetBorderSize(3);
   l->AddEntry(r[0],refLabel,"LPF");
   l->AddEntry(s[0],newLabel,"LPF");
   l->Draw();
   canvas->Print("steps_effpt.pdf");   
   delete l;

   fillStepHisto(rdir, sdir, rl, sl, r, s, "/fakeratePt", "p_{t}", "fakerate vs p_{t}", 0., MAXFAKE);
   // rearrange to a more natural order for plotting
   TH1F * rr[6]={r[5],r[2],r[0],r[3],r[4],r[1]};
   TH1F * ss[6]={s[5],s[2],s[0],s[3],s[4],s[1]};

   canvas = new TCanvas("Tracks13","Tracks: fakerate for each step",1000,1400);

   plotBuilding(canvas,ss, rr,6,
		te,"UU",-69, 1, false, 127);

   canvas->cd();
   l = new TLegend(0.10,0.64,0.90,0.69);
   l->SetTextSize(0.016);
   l->SetLineColor(1);
   l->SetLineWidth(1);
   l->SetLineStyle(1);
   l->SetFillColor(0);
   l->SetBorderSize(3);
   l->AddEntry(r[0],refLabel,"LPF");
   l->AddEntry(s[0],newLabel,"LPF");
   l->Draw();
   canvas->Print("steps_fakeratePt.pdf");   
   delete l;

   // fill with the histos we want for eff
   fillStepHisto(rdir, sdir, rl, sl, r, s, "/effic_vs_hit", "hits", "efficiency vs hits", 0., MAXEFF);
   // rearrange to a more natural order for plotting
   TH1F * rr[6]={r[5],r[2],r[0],r[3],r[4],r[1]};
   TH1F * ss[6]={s[5],s[2],s[0],s[3],s[4],s[1]};

   canvas = new TCanvas("Tracks14","Tracks: efficiency for each step",1000,1400);

   plotBuilding(canvas,ss, rr,6,
		te,"UU",-69);

   canvas->cd();
   l = new TLegend(0.10,0.64,0.90,0.69);
   l->SetTextSize(0.016);
   l->SetLineColor(1);
   l->SetLineWidth(1);
   l->SetLineStyle(1);
   l->SetFillColor(0);
   l->SetBorderSize(3);
   l->AddEntry(r[0],refLabel,"LPF");
   l->AddEntry(s[0],newLabel,"LPF");
   l->Draw();
   canvas->Print("steps_effhits.pdf");   
   delete l;

   // fill with the histos we want for fake rate
   fillStepHisto(rdir, sdir, rl, sl, r, s, "/fakerate_vs_hit", "hits", "fakerate vs hits", 0., MAXFAKE);
   // rearrange to a more natural order for plotting
   TH1F * rr[6]={r[5],r[2],r[0],r[3],r[4],r[1]};
   TH1F * ss[6]={s[5],s[2],s[0],s[3],s[4],s[1]};

   canvas = new TCanvas("Tracks15","Tracks: fakerate for each step",1000,1400);

   plotBuilding(canvas,ss, rr,6,
		te,"UU",-69);

   canvas->cd();
   l = new TLegend(0.10,0.64,0.90,0.69);
   l->SetTextSize(0.016);
   l->SetLineColor(1);
   l->SetLineWidth(1);
   l->SetLineStyle(1);
   l->SetFillColor(0);
   l->SetBorderSize(3);
   l->AddEntry(r[0],refLabel,"LPF");
   l->AddEntry(s[0],newLabel,"LPF");
   l->Draw();
   canvas->Print("steps_fakeratehits.pdf");   
   delete l;

 }
}
Example #29
0
int analysis(char* filename)
{
    // char* filename = "combined.root";
    // Read in the file
    TFile* f = new TFile(filename);
    TDirectory* hists  = f->GetDirectory("hists;1");
    TDirectory* tuples = f->GetDirectory("tuples;1");

    TTree* accum = tuples->GetObjectUnchecked("AccumulatedEnergy;1");
    TLeaf* einit = accum->GetLeaf("Einit");
    TLeaf* edepo = accum->GetLeaf("Edep");

    TTree* edeps = tuples->GetObjectUnchecked("EnergyDepositions;1");

    TTree* secs  = tuples->GetObjectUnchecked("SecondarySpectrum;1");
    TLeaf* secsenergy = secs->GetLeaf("KineticEnergy");

    double ein = 0;
    double eout = 0;



    int nevents = accum->GetEntries();
    cout << "Making Summary\n";
    FILE* summary = fopen("summ.txt", "a+");

    for (int ii = 0; ii<nevents; ii++)
    {
        accum->GetEntry(ii);
        ein+=einit->GetValue();
        eout+=edepo->GetValue();
    }

    FILE* summary = fopen("summ.txt", "a+");

    time_t t = time(NULL);
    char* c_time_string = ctime(&t);
    char* mytime[20];
    strncpy(mytime, c_time_string, 19);
    mytime[ strlen(mytime) - 1 ] = '\0';

    fprintf(summary, "%s,%s,%e,%e\n", mytime, filename, ein, eout);//*c_time_string, *filename, ein, eout);
    //cout << *c_time_string << "," << *filename << "," << ein << "," << eout << "\n";
    fclose(summary);

    // Print out or save these values
    cout << "Making Histogram\n";

    nevents = secs->GetEntries();
    TH1F* secondaries = new TH1F("secondaries", "Secondary Electrons <100 keV", 92, 0.010, 0.102);

    for (int ii = 0; ii<nevents; ii++)
    {
        secs->GetEntry(ii);
        secondaries->Fill(secsenergy->GetValue());
    }

    char* suffix = ".secondaryhisto";

    cout << "Making Filenames\n";


    char* outfilename = malloc(strlen(filename) + strlen(suffix) + 1);
    strcpy(outfilename, filename);
    strcat(outfilename, suffix);

    printf("Saving Histogram: %s \n", outfilename);
    h12ascii(secondaries, outfilename);

    return 0;

}
Example #30
0
void makeJetP4(TString InRootFile, double Rparam=0.5) { 
    
    cout << " ... Processing file = " << InRootFile << endl;
    cout << " ... Rparam = " << Rparam << endl;
    cout << " ................................................................." << endl; 
    
    // 
    // Get tree from a cfA ntuple 
    // 
    TFile *f = TFile::Open("../cfA/"+InRootFile, "UPDATE");
    TDirectory* dir = f->GetDirectory("configurableAnalysis");
    dir->cd();
    TTree *eventB = (TTree*)dir->Get("eventB");
    
    // 
    // set address of variables to read 
    // 
    UInt_t   event_ = 0;
    eventB->SetBranchAddress("event", &event_);
    UInt_t   run_ = 0;
    eventB->SetBranchAddress("run", &run_);
    UInt_t   lumiblock_ = 0;
    eventB->SetBranchAddress("lumiblock", &lumiblock_);
    vector<float>   *fastjets_AK5PF_px_ = 0;
    eventB->SetBranchAddress("jets_AK5PF_px", &fastjets_AK5PF_px_);
    vector<float>   *fastjets_AK5PF_py_ = 0;
    eventB->SetBranchAddress("jets_AK5PF_py", &fastjets_AK5PF_py_);
    vector<float>   *fastjets_AK5PF_pz_ = 0;
    eventB->SetBranchAddress("jets_AK5PF_pz", &fastjets_AK5PF_pz_);
    vector<float>   *fastjets_AK5PF_energy_ = 0;
    eventB->SetBranchAddress("jets_AK5PF_energy", &fastjets_AK5PF_energy_);
    vector<float>   *fastjets_AK5PF_phi_ = 0;
    eventB->SetBranchAddress("jets_AK5PF_phi", &fastjets_AK5PF_phi_);
    vector<float>   *fastjets_AK5PF_eta_ = 0;
    eventB->SetBranchAddress("jets_AK5PF_eta", &fastjets_AK5PF_eta_);
    
    // 
    // Define new variables to write 
    // 
    // need this line because ROOT does not know vector<float>
    // one needs to generate dictionary using rootcint or 
    // just include this line 
    // [ref] http://root.cern.ch/phpBB3/viewtopic.php?t=8467
    gROOT->ProcessLine("#include <vector>"); 
    vector<float>   *fastjets_AK5PF_R1p2_px = 0;
    TBranch *pxb =  eventB->Branch(Form("fastjets_AK5PF_R1p2_pT%i_px",R0p5JetpTcut), &fastjets_AK5PF_R1p2_px);
    vector<float>   *fastjets_AK5PF_R1p2_py = 0;
    TBranch *pyb = eventB->Branch(Form("fastjets_AK5PF_R1p2_pT%i_py",R0p5JetpTcut), &fastjets_AK5PF_R1p2_py);
    vector<float>   *fastjets_AK5PF_R1p2_pz = 0;
    TBranch *pzb = eventB->Branch(Form("fastjets_AK5PF_R1p2_pT%i_pz",R0p5JetpTcut), &fastjets_AK5PF_R1p2_pz);
    vector<float>   *fastjets_AK5PF_R1p2_energy = 0;
    TBranch *energyb = eventB->Branch(Form("fastjets_AK5PF_R1p2_pT%i_energy",R0p5JetpTcut), &fastjets_AK5PF_R1p2_energy);
    vector<float>   *fastjets_AK5PF_R1p2_phi = 0;
    TBranch *phib = eventB->Branch(Form("fastjets_AK5PF_R1p2_pT%i_phi",R0p5JetpTcut), &fastjets_AK5PF_R1p2_phi);
    vector<float>   *fastjets_AK5PF_R1p2_eta = 0;
    TBranch *etab = eventB->Branch(Form("fastjets_AK5PF_R1p2_pT%i_eta",R0p5JetpTcut), &fastjets_AK5PF_R1p2_eta);

    // 
    // Histgrom : to draw eta-phi plot of energy deposit 
    //  (1) Bin size is 0.087x0.087 to mimic the size of hcal tower
    //  (2) Bin Entry is the sum over energies of PF candidates in a given bin  
    // 
    TH2F *h2 = new TH2F("h2","h2", 115, -5.0, 5.0, 72, -3.141592, 3.141592);
    
    // 
    // Loop over entries
    // 
    Int_t nentries = (Int_t)eventB->GetEntries();
    if(DEBUG) nentries = 10;
    cout<<"The number of entries is: "<<nentries<<endl;

    // main event loop
    for(int ib = 0; ib<nentries; ib++) {
      
        // Counting to see progress
        if(ib%100==0) cout << " ...... " << ib << " events processed "<< endl; 

        // get the entry of event ib
        eventB->GetEntry(ib);
        
        // ---------------------------------------
        //          Block 1 
        // ---------------------------------------
        
        // Open a text file to write information about PF candidates  
        ofstream fout;
        fout.open(Form("OneEvent_FastjetsR0p5_tmp_%i.dat", ib));
        
        // loop over Fastjets with R=0.5
        for(int ifastjets = 0; ifastjets < (int)fastjets_AK5PF_px_->size(); ifastjets++) {
            
            if(TMath::Sqrt( fastjets_AK5PF_px_->at(ifastjets)*fastjets_AK5PF_px_->at(ifastjets) 
                           +fastjets_AK5PF_py_->at(ifastjets)*fastjets_AK5PF_py_->at(ifastjets)) < R0p5JetpTcut) continue; 

            fout.width(15); fout << fastjets_AK5PF_px_->at(ifastjets) << "\t";
            fout.width(15); fout << fastjets_AK5PF_py_->at(ifastjets) << "\t";
            fout.width(15); fout << fastjets_AK5PF_pz_->at(ifastjets) << "\t";
            fout.width(15); fout << fastjets_AK5PF_energy_->at(ifastjets) << endl;
           
            float pt = TMath::Sqrt(fastjets_AK5PF_px_->at(ifastjets)*fastjets_AK5PF_px_->at(ifastjets) 
                                  +fastjets_AK5PF_py_->at(ifastjets)*fastjets_AK5PF_py_->at(ifastjets));
            h2->Fill( fastjets_AK5PF_eta_->at(ifastjets), fastjets_AK5PF_phi_->at(ifastjets), pt);
        }
        fout.close();




        // ---------------------------------------
        //          Block 2 
        // ---------------------------------------

        //
        // Run Fastjet to reconstuct jets 
        //
        // Using the example code "fastjet_example.cc" 
        // It takes OneEvent_PFCands_tmp_%i.dat as an input 
        // and writes p4 of reconstructed jets in  OneEvent_PFJets_tmp_%i.dat. 
        // For the details about the code, take a look at fastjet_example.cc.
        gSystem->Exec(Form("../fastjet_example %f < OneEvent_FastjetsR0p5_tmp_%i.dat > OneEvent_FastjetsR1p2_tmp_%i.dat", Rparam, ib, ib));

        // ---------------------------------------
        //          Block 3 
        // ---------------------------------------

        // 
        // Get p4 of the reconstructed jets  
        //
        string line;
        double id, px, py , pz, energy, eta, phi, ncand;
        ifstream fin(Form("OneEvent_FastjetsR1p2_tmp_%i.dat", ib)); 
        if(fin.is_open()) { 
            while(fin.good()){

                // get a line from fin
                getline(fin, line);
                if(line=="") break; // need this to avoid line without entry 
                // Store each element in the line to the defined variables
                stringstream stream(line);
                stream >> id >> px >> py >> pz >> energy >> eta >> phi >> ncand; 
               
                // store only when pT > 3 GeV 
                // (same as CMS jet reconstruction cut)
                if(TMath::Sqrt(px*px+py*py)>(DEBUG?30:3)) {
                    fastjets_AK5PF_R1p2_px->push_back(px);
                    fastjets_AK5PF_R1p2_py->push_back(py);
                    fastjets_AK5PF_R1p2_pz->push_back(pz);
                    fastjets_AK5PF_R1p2_energy->push_back(energy);
                    fastjets_AK5PF_R1p2_eta->push_back(eta);
                    fastjets_AK5PF_R1p2_phi->push_back(phi); 

                    if(DEBUG) {
                        cout << event_ << " " 
                             << id << " " 
                             << TMath::Sqrt(px*px+py*py) << " " 
                             << eta << " " 
                             << phi << " "  
                             << endl; 
                    }
                }
            }
        }
        // Fill the branches 
        pxb->Fill();
        pyb->Fill();
        pzb->Fill();
        energyb->Fill();
        phib->Fill();
        etab->Fill();
        
        // 
        // Draw a lego plot (eta, phi) 
        //
        if(DEBUG) {
            TCanvas *c = new TCanvas();
            c->cd(1);
            h2->Draw("colz");
            h2->SetTitle(Form("run=%i lumi=%i event=%i R=%.1f", run_, lumiblock_, event_, Rparam));
            h2->SetMaximum(50); 
            h2->SetStats(0); 
            h2->SetXTitle("#eta"); 
            h2->SetYTitle("#phi"); 

            //Draw circles around jets
            TEllipse *cone[fastjets_AK5PF_R1p2_eta->size()]; 
            for(int ijets=0; ijets<(int)fastjets_AK5PF_R1p2_eta->size(); ijets++){
                cone[ijets] = new TEllipse(fastjets_AK5PF_R1p2_eta->at(ijets), fastjets_AK5PF_R1p2_phi->at(ijets), Rparam, Rparam);
                cone[ijets]->SetFillStyle(3003);
                cone[ijets]->SetFillColor(kYellow);
                cone[ijets]->Draw();
            }

            c->SaveAs(Form("EtaPhiViewPFCand_Run%i_Lumi%i_Event%i_R%.1f_usingR0p5.pdf", 
                        run_, lumiblock_, event_, Rparam));
            h2->Reset(); 
            for(int ijets=0; ijets<(int)fastjets_AK5PF_R1p2_eta->size(); ijets++) delete cone[ijets];

        } 
   
        // Clear vectors for the next event 
        fastjets_AK5PF_R1p2_px->clear();
        fastjets_AK5PF_R1p2_py->clear();
        fastjets_AK5PF_R1p2_pz->clear();
        fastjets_AK5PF_R1p2_energy->clear();
        fastjets_AK5PF_R1p2_eta->clear();
        fastjets_AK5PF_R1p2_phi->clear();
        
        // remove text files
        if(!DEBUG) gSystem->Exec("'rm' OneEvent_Fastjets*.dat");
    
    } // event loop

    // update the tree and close file
    if(!DEBUG) eventB->Write();
    f->Close();
    
    //
    // cleanup
    //
    delete f;
}