Exemple #1
0
void covertQuan(){
    TFile *fin = TFile::Open("pPb.root");
//    TFile *fout = new TFile("pPb_xq.root","Recreate");
    int mult[4] = {120,150,185,220};
    int n[4] = {2,4,6,8};
    for(int i=0;i<4;i++){
    for(int j=0;j<4;j++){
        TGraphErrors *g = (TGraphErrors*)fin->Get(Form("v2Pt_%d_%d",n[j],mult[i]));
        if(n[j]==4){
        cout<<mult[i]<<endl;
        for(int ibin=0;ibin<g->GetN();ibin++){
            cout<<g->GetX()[ibin]<<",";
        }
        cout<<endl;
        for(int ibin=0;ibin<g->GetN();ibin++){
            cout<<g->GetY()[ibin]<<",";
        }
        cout<<endl;
        for(int ibin=0;ibin<g->GetN();ibin++){
            cout<<g->GetEY()[ibin]<<",";
        }
        cout<<endl;
        }
       // fout->cd();
       // g->Write("AP");
       // g1->Write();
    }
    }
}
Exemple #2
0
void add_point( double coefover, double sigma, double dsigma ){//============================================================


      TGraphErrors *fisig;
      if ( gROOT->GetListOfSpecials()->FindObject("fisig")!=NULL ){
	fisig=(TGraphErrors*) gROOT->GetListOfSpecials()->FindObject("fisig");
	printf("fisig exists\n%s","");
      }else{

	printf("\n\n NO fisig exists NONONO \n\n\n%s","");

	fisig=new TGraphErrors();
	fisig->SetTitle("fisig");
	fisig->SetName("fisig");
	gROOT->GetListOfSpecials()->Add( fisig );// TRICK TO KEEP IT
	gDirectory->Add( fisig );
	fisig->SetMarkerStyle(7);
      }


      int n=fisig->GetN();
      fisig->SetPoint(n,coefover,sigma);
      fisig->SetPointError(n,0.0,dsigma);
      //      fisig->Print(); // too many data 

     char text[100];
      sprintf(text,"%.3f ... %d",coefover, fisig->GetN()  );

      //      TText *t=new TText(from,0,text ); 
      //      t->SetTextSize(0.08);t->Draw();
 

}//============================================================
void JEC_fit_Uncertainty(int N)
{
  TF1 *func[1000];
  TFile *inf = new TFile("L3Graphs_test_Icone5.root");
  TGraphErrors *g = (TGraphErrors*)inf->Get("Correction_vs_CaloPt");
  TGraphErrors *vg[1000];
  int i,k;
  double x[20],y[20],ex[20],ey[20];
  double vx[20],vy[20],vex[20],vey[20];
  for(i=0;i<g->GetN();i++)
    {
      g->GetPoint(i,x[i],y[i]);
      ex[i]=g->GetErrorX(i);
      ey[i]=g->GetErrorY(i); 
    }  
  TRandom *rnd = new TRandom();
  rnd->SetSeed(0);
  for(k=0;k<N;k++)
    {
      for(i=0;i<g->GetN();i++)
        {	
          vx[i] = rnd->Gaus(x[i],ex[i]);
          //vx[i] = x[i];
          vy[i] = rnd->Gaus(y[i],ey[i]);
          vex[i] = ex[i];
          vey[i] = ey[i];
        }
      vg[k] = new TGraphErrors(g->GetN(),vx,vy,vex,vey);
      func[k] = new TF1("func","[0]+[1]/(pow(log10(x),[2])+[3])",1,2000);
      func[k]->SetParameters(1,3,6,5);
      vg[k]->Fit(func[k],"RQ");     	
    }
  
  TCanvas *c = new TCanvas("c","c");
  gPad->SetLogx();
  g->SetMarkerStyle(20);
  g->SetMaximum(3.5);
  g->Draw("AP");
  for(k=0;k<N;k++)
    {
      func[k]->SetLineColor(5);
      func[k]->SetLineWidth(1);
      cout<<func[k]->GetChisquare()<<endl;
      vg[k]->SetMarkerColor(2);
      vg[k]->SetLineColor(2);
      vg[k]->SetMarkerStyle(21);
      //if (func[k]->GetChisquare()<0.1)
        //vg[k]->Draw("sameP");
      func[k]->Draw("same");  
    }  	 
}  
int RampCorrellation_single(std::string file_name, TGraphErrors &graph, TGraphErrors &graph2, vector<double> &vec_errors)
{

	TTree *t = new TTree();
	const std::string file_path = "/home/jlab/github/MagCloak_Analysis/calibration/data-calib/DATA_MegaVIEW/";
//	std::string file_name = "DataFile_2016-12-08_06-59-11.csv";
	std::string file = file_path+file_name;

	t->ReadFile(file.c_str());
//	t->Print();

	TCanvas *c = new TCanvas();
	t->Draw("TMath::Abs(B1/B2):time");
	TGraph *gh = (TGraph*)c->GetListOfPrimitives()->FindObject("Graph");
	double ratio_mean = gh->GetMean(2);
	double ratio_std = gh->GetRMS(2);

	t->Draw("Bnom:time");
	TGraph *gh1 = (TGraph*)c->GetListOfPrimitives()->FindObject("Graph");
	double nom_mean = gh1->GetMean(2);
	double nom_std = 0;

//	cout << "At " << nom_mean << " mT, B1/B2 is: " << ratio_mean << " +/- " << ratio_std << endl;
	
	c->Close();

	int n = graph.GetN();
	graph.SetPoint(n,nom_mean,ratio_mean);
	graph.SetPointError(n,nom_std,ratio_std);

//-------------------------------------------------------------------------------

	TCanvas *c2 = new TCanvas();
	t->Draw("B3:time");
	TGraph *gh2 = (TGraph*)c2->GetListOfPrimitives()->FindObject("Graph");
	double B3_mean = -1*(gh2->GetMean(2));
	double B3_std = gh2->GetRMS(2);
	
	int n2 = graph2.GetN();
	graph2.SetPoint(n2, nom_mean, B3_mean);
	graph2.SetPointError(n2, nom_std, B3_std);
	
	c2->Close();

	if(nom_mean < 500) vec_errors.push_back(B3_std);

	return 0;
}
Exemple #5
0
void draw() {

  gStyle->SetOptStat(0000);

  TGraphErrors* gr = new TGraphErrors("papel_um.txt", "%lg %lg %lg %lg");
  gr->Draw("A");

  gr->GetXaxis()->SetTitle("Diametro (mm)");
  gr->GetYaxis()->SetTitle("Massa (u.m.)");
  gr->SetTitle("Dimensao Fractal - Papel");
  gr->SetMarkerStyle(20);
  gr->SetMarkerSize(gr->GetMarkerSize()/2.);

  TCanvas* c1 = new TCanvas();
  gr->Draw("AP");
  c1->Print("gr1.png");


  TGraphErrors* grlog = new TGraphErrors();
  for (int i=0; i<gr->GetN(); i++) {
    grlog->SetPoint(i, TMath::Log(gr->GetX()[i]), TMath::Log(gr->GetY()[i]));
    grlog->SetPointError(i, gr->GetEX()[i]/gr->GetX()[i], 0.0);
  }
  grlog->Draw("A");
  grlog->GetXaxis()->SetTitle("Logaritmo do diametro (diametro em mm)");
  grlog->GetYaxis()->SetTitle("Logaritmo da massa (massa em unidade arbitraria)");
  grlog->SetTitle("Dimensao Fractal - Papel");
  grlog->SetMarkerStyle(20);
  //  grlog->SetMarkerSize(gr->GetMarkerSize()/2.);
  grlog->Fit("pol1");
  TCanvas* c2 = new TCanvas();
  grlog->Draw("AP");
  c2->Print("gr2.png");

}
Exemple #6
0
void InitSummaryTrending(TTree * tree){
  //
  // Init drawing for the <detector> QA
  // Detector specific qaConfig() has to be called before invoking this function
  //    0.) Make descriptor 
  //    1.) Make default canvas - addopt canvas width to the number of entries to draw
  //    3.) compute detector  status graphs

  //
  //   0.) Make descriptor 
  //
  TLatex *latex= new TLatex;
  latex->SetX(0.11);
  latex->SetY(0.8);
  latex->SetTextSize(0.03);
  descriptionQA = GetTexDescription(latex);
  //
  //   1.) Make default canvas - addopt canvas width to the number of entries to draw
  //
  TGraphErrors *gr = (TGraphErrors*) TStatToolkit::MakeGraphSparse(tree,"resolution:tagID","");
  Int_t numberOfTags = gr->GetN();
  cout<<"number of graph entries: "<<numberOfTags<<endl;
  double SpaceForLegend = 0.;
  Int_t canvas_width  = SpaceForLegend + (numberOfTags+5)*30;
  Int_t canvas_height = 600; 
  if ( canvas_width>kMaxCanvasWidth)   canvas_width=kMaxCanvasWidth;
  canvasQA = new TCanvas("canvasQA","canvasQA",canvas_width,canvas_height);
  canvasQA->SetGrid(3);
  canvasQA->cd();
  gPad->SetTicks(1,2);
  // canvasQA->SetRightMargin(SpaceForLegend/canvas_width);
  double leftlegend  = 1 - 180./canvasQA->GetWw();
  double rightlegend = 1 - 10./canvasQA->GetWw();
  //
  // 2.) process config file qaConfig.C to initialize status aliases (outliers etc.), status bar criteria, status lines, ...
  //
  TString sStatusbarVars  = statusDescription[0];
  TString sStatusbarNames = statusDescription[1];
  TString sCriteria       = statusDescription[2];
  cout << "sStatusbarVars = " << sStatusbarVars.Data() << endl;
  cout << "sCriteria      = " << sCriteria.Data() << endl;
  //
  // 3.) compute detector status graphs
  //
  TObjArray* oaStatusbarVars = sStatusbarVars.Tokenize(";");
  TObjArray* oaStatusbarNames = sStatusbarNames.Tokenize(";");
  oaMultGr = new TObjArray();
  int igr=0;
  for (Int_t vari=oaStatusbarVars->GetEntriesFast()-1; vari>=0; vari--){ // invert the order of the status graphs
    TString sVar = Form("%s:tagID", oaStatusbarVars->At(vari)->GetName()); //e.g. -> dcar:run
    oaMultGr->Add( TStatToolkit::MakeStatusMultGr(tree, sVar.Data(),  "", sCriteria.Data(), igr) );
    TString sYtitle = oaStatusbarNames->At(vari)->GetName(); // set better name for y axis of statuspad
    ((TMultiGraph*) oaMultGr->At(igr))->SetTitle(sYtitle.Data());
    igr++;
  }
}
Exemple #7
0
void points(TString filename) {

	
	TString cmssw;
	// 167
	
	cmssw = "$1.6.7$";
	
	TFile *f = TFile::Open(filename);

	std::vector< TString > taggers;
	taggers.push_back( "gTC2_udsg" );
	taggers.push_back( "gTC3_udsg" );
	taggers.push_back( "gTP_udsg" );
	taggers.push_back( "gJBP_udsg" );
 	taggers.push_back( "gSSV_udsg" );
 	taggers.push_back( "gCSV_udsg" );

	std::vector< TString > discriminators;
	discriminators.push_back( "discTC2_udsg" );
	discriminators.push_back( "discTC3_udsg" );
	discriminators.push_back( "discTP_udsg" );
	discriminators.push_back( "discJBP_udsg" );
 	discriminators.push_back( "discSSV_udsg" );
 	discriminators.push_back( "discCSV_udsg" );

	//TCanvas *cv_TC = new TCanvas("cv_TC","cv_TC",700,700);
	//TCanvas *cv_TP = new TCanvas("cv_TP","cv_TP",700,700);

	std::cout << "Tagger & Point & Discriminator & light mistag & b-efficiency \\\\ \\hline" << std::endl;
	for ( size_t itagger = 0; itagger < taggers.size(); ++itagger ) {

		TString tag = taggers[itagger];
		TGraphErrors *agraph = (TGraphErrors*) gDirectory->Get("Histograms/MCtruth/"+tag);

		//if (taggers == "gTC2_udsg" || taggers =
		
		TGraph *dgraph = (TGraph*) gDirectory->Get("Histograms/MCtruth/"+discriminators[itagger]);
		dgraph->Sort();

		TGraphErrors *g = new TGraphErrors(agraph->GetN(),agraph->GetY(),agraph->GetX(),agraph->GetEY(),agraph->GetEX());
		g->Sort();
		
		//cv[itagger] = new TCanvas("cv","cv",600,600);
		//g->Draw("ACP");
		TString se = " & ";
		
		
		std::cout << tag << se << "Loose" << se << std::setprecision(3) << dgraph->Eval(0.1) << se << "0.1" << se << std::setprecision(2) << g->Eval(0.1) << "\\\\" << std::endl;
		std::cout << tag << se << "Medium" << se << std::setprecision(3) << dgraph->Eval(0.01) << se << "0.01" << se << std::setprecision(2) << g->Eval(0.01) << "\\\\" << std::endl;
		std::cout << tag << se << "Tight" << se << std::setprecision(3) << dgraph->Eval(0.001) << se << "0.001" << se << std::setprecision(2) << g->Eval(0.001) << "\\\\ \\hline" << std::endl;
		
	}

	
}
Exemple #8
0
TGraphErrors *tools::makeGraph(TH1 *hx, TH1 *hy, double scale ) {

  assert(hx->GetNbinsX()==hy->GetNbinsX());

  TGraphErrors *g = new TGraphErrors(0);
  for (int i = 1; i != hx->GetNbinsX()+1; ++i) {

    assert(hx->GetBinLowEdge(i)==hy->GetBinLowEdge(i));
    int n = g->GetN();
    SetPoint(g, n, hx->GetBinContent(i), scale*hy->GetBinContent(i),
	     hx->GetBinError(i), scale*hy->GetBinError(i));
  }

  return g;
}
double ll_matrix::matrix_calibration::get_min_mass( TGraphErrors & graph )
{
    double m_min_x = graph.GetX()[0] , m_min_y = graph.GetY()[0];
    for( int i = 0 ; i < graph.GetN() ; i++ )
    {
        if( graph.GetY()[i] < m_min_y )
        {
            if( graph.GetX()[i] < LOWEST_MASS || graph.GetX()[i] > HIGHEST_MASS ) 
                continue;
            m_min_x = graph.GetX()[i];
            m_min_y = graph.GetY()[i];
        }
    }
    return m_min_x;
}
Exemple #10
0
printgraph(const char* file, const char* graphname, const char* graphname_syst, bool reverseta=false, double scale=1./34.62)
{
   TFile * f = new TFile(file);
   TGraphErrors *gr = (TGraphErrors*) f->Get(graphname);
   TGraphErrors *grsyst = (TGraphErrors*) f->Get(graphname_syst);

   int nbins = gr->GetN();
   double *x = new double[nbins];
   if (reverseta)
      for (int i=0; i<nbins; i++)
         x[i] = gr->GetX()[nbins-i-1];
   else 
      x = gr->GetX();

   double *y = gr->GetY();
   double *ey = gr->GetEY();
   double *ey_syst = grsyst->GetEY();

   for (int i=0; i<nbins; i++)
      cout << x[i] << ": " << y[i]*scale << "+-" << ey[i]*scale << "(stat.) +-" << ey_syst[i]*scale << "(syst.)" << endl;
}
Exemple #11
0
TGraphErrors *tools::ratioGraphs(TGraphErrors *g1, TGraphErrors *g2,
				 double erry) {

  assert(g1); assert(g2);
  TGraphErrors *g = new TGraphErrors(0);
  g->SetName(Form("ratio_%s_%s",g1->GetName(),g2->GetName()));
  g->SetMarkerStyle(g1->GetMarkerStyle());
  g->SetMarkerColor(g1->GetMarkerColor());
  g->SetLineColor(g1->GetLineColor());

  // take ratio only of points that are closer to each other than any others
  for (int i = 0, j = 0; (i != g1->GetN() && j != g2->GetN());) {
    
    double x1m, x1p, x2m, x2p, y, ex, ey;
    GetPoint(g1, max(i-1,0), x1m, y, ex, ey);
    GetPoint(g1, min(i+1,g1->GetN()-1), x1p, y, ex, ey);
    GetPoint(g2, max(j-1,0), x2m, y, ex, ey);
    GetPoint(g2, min(j+1,g2->GetN()-1), x2p, y, ex, ey);
    double x1, y1, ex1, ey1;
    GetPoint(g1, i, x1, y1, ex1, ey1);
    double x2, y2, ex2, ey2;
    GetPoint(g2, j, x2, y2, ex2, ey2);

    if (fabs(x1-x2)<=fabs(x1-x2m) && fabs(x1-x2)<=fabs(x1-x2p) &&
	fabs(x1-x2)<=fabs(x2-x1m) && fabs(x1-x2)<=fabs(x2-x1p)) {

      int n = g->GetN();
      SetPoint(g, n, 0.5*(x1+x2), (y2 ? y1/y2 : 0.), 0.5*fabs(x1-x2),
	       oplus(ey1/y1, ey2/y2) * fabs(y2 ? y1/y2 : 0.) * erry); 
      ++i, ++j;
    }
    else
      (x1<x2 ? ++i : ++j);
  } // for i, j

  return g;
} // ratioGraphs
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::string parfname = GetParamFile();
    std::ifstream pfile(parfname.data());
    Parameters params(pfile);
    if (! params.KeysAreSensible()) return -1;
    AngDistC W(params, 1, ELECTRIC);

    std::cout << params << std::endl;

    TGraph* gr = new TGraph(mygr->GetN());
    gr->SetMarkerColor(kBlue);
    gr->SetLineColor(kBlue);
    gr->SetMarkerStyle(20);

    Double_t num, denom;
    Double_t ratio;
    Double_t x[2];
    for (UInt_t i=0; i<mygr->GetN(); i++)
    {
        x[0] = mygr->GetX()[i];
        x[1] = 0;
        num = W(x);

        x[1] = TMath::Pi()/2.;
        denom = W(x);
        ratio = num/denom;
        gr->SetPoint(i, mygr->GetX()[i], TMath::Abs(ratio));
    }

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

    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());

    TH1* h = new TH2D("Ratio Comparison", "", 10, -1,1, 500, 0,100);
    h->SetStats(0);

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

    gPad->Modified();
    c->Update();


    TLegend *leg = new TLegend(0.5, 0.75, 0.8, 0.95);
    leg->AddEntry(gr, "Fit", "PL");
    leg->AddEntry(mygr, "Data", "PL");
    leg->Draw();

    return 0;
}
void AnalyzeClipping(TString inputWaveName = "sum trigger input ch5 960mV",
TString outputWaveName = "sum trigger output ch5 - 2V clip - 960mV input", 
Double_t inputDelay = 1.1E-8, Double_t lowerCut = 16E-9, Double_t upperCut = 23E-9,
const char *inFile = "Data.root",const char *WaveformsFile = "Waveforms.root") {
	
	//try to access data file and in case of failure return
	if(gSystem->AccessPathName(inFile,kFileExists)) {
		cout << "Error: file " << inFile << " does not exsist. Run .x DataParse.C to create it" << endl;
		return;
	}

	TFile *f = TFile::Open(inFile);
	TFolder *dataSet;
	
	TString dataFolderS = "SumTriggerBoardData";
	dataFolderS.Append(";1");

	dataSet = (TFolder*)f->Get(dataFolderS);
	
	cout << dataSet << endl;

	cout << dataSet->GetName() << endl;
	
	Int_t nScope = 150; // number of measurements done by the scope evey time
	
	//try to access waveforms file and in case of failure return
	if(gSystem->AccessPathName(WaveformsFile,kFileExists)) {
		cout << "Error: file " << WaveformsFile << " does not exsist. Run .x WaveformsFileMaker.C to create it" << endl;
		return;
	}
	
	TFile *f = TFile::Open(WaveformsFile);
	TList *listOfKeys = f->GetListOfKeys();
	Int_t numberOfKeys = listOfKeys->GetEntries();
	TList *listOfGraphs = new TList();
	
	// if the waveform file name begins with the string "comparator" it goes in this list
	TList *listOfCompWaves = new TList();
	// if the waveform file name begins with the string "sum output" it goes in this list
	TList *listOfAdderWaves = new TList();

	for(Int_t i = 0; i < numberOfKeys; i++) {
		TString *keyName = new TString(listOfKeys->At(i)->GetName());
		TTree *tree = (TTree*)f->Get(keyName->Data());
		Float_t x = 0;
		Float_t y = 0;
		tree->SetBranchAddress("x",&x);
		tree->SetBranchAddress("y",&y);
		Int_t nentries = tree->GetEntries();

		TString *gName = new TString(keyName->Data());
		gName->Append(" graph");
		TGraphErrors *gWave = new TGraphErrors(nentries);
		gWave->SetName(gName->Data());
		gWave->SetTitle(gName->Data());
		gWave->GetXaxis()->SetTitle("Time");
		gWave->GetYaxis()->SetTitle("Voltage");

		for (Int_t j = 0; j < nentries; j++) {
			tree->GetEntry(j);
			gWave->SetPoint(j,x,y);
		}

		listOfGraphs->Add(gWave);
	}
	
	// Global variables
	
	Double_t *xInput, *xOutput, *yInput, *yOutput;
	
	// V input 960 mV
	
	TString path = "Clipping/Output width analysis/Channel 5/V input 960mV/";
	
	TGraphErrors *gClip960mV = TBGraphErrors(dataSet,path,"V clip","Output FWHM",1,nScope);
	
	gClip960mV->SetMarkerStyle(20);
	gClip960mV->SetMarkerSize(0.8);
	gClip960mV->GetXaxis()->SetTitle("V clipping (mV)");
	gClip960mV->GetYaxis()->SetTitle("Output FWHM (ns)");
	
	TCanvas *cClip960mV = new TCanvas("cClip960mV","Output FWHM in function of V clipping",800,600);
	gClip960mV->Draw("APEL");
	
	// Expected output FWHM
	
	TGraphErrors *gInput960mV = listOfGraphs->FindObject("sum trigger input ch5 960mV graph");
	
	Double_t *xClip = gClip960mV->GetX();
	Int_t nClip = gClip960mV->GetN();
	cout << "nClip = " << nClip << endl;
	Long64_t graphPoints = gInput960mV->GetN();
	yInput = gInput960mV->GetY();
	xInput = gInput960mV->GetX();
	
	vector<double> xFirst(nClip);
	vector<double> xLast(nClip);
	Double_t half;
	
	Int_t flag = 0;
	
	vector<double> yConv(graphPoints);
	for(Int_t i = 0; i < graphPoints; i++) {
		yConv[i] = -(yInput[i]);
		yConv[i] *= 1000;
		if(xInput[i] + inputDelay < lowerCut || xInput[i] + inputDelay > upperCut) 
			yConv[i] = 0;
	}
	
	Double_t yInput960mVMax = TMath::MaxElement(graphPoints,&yConv[0]);
	
	for(Int_t i = 0; i < nClip; i++) {
		if(xClip[i] > yInput960mVMax) half = yInput960mVMax;
		else half = xClip[i];
		
		half /=2;
		cout << half << endl;
		
		flag = 0;
		
		for(Int_t j = 0; j < graphPoints - 3; j++) {
			if((yConv[j + 1] - half)*(yConv[j] - half) < 0 && flag == 0) {
				xFirst[i] = xInput[j];
				flag = 1;
				cout << "found first point! " << xFirst[i] << endl;
				continue;
			}
			if((yConv[j + 1] - half)*(yConv[j] - half) < 0 && flag == 1) {
				xLast[i] = xInput[j];
				cout << "found last point! " << xLast[i] << endl;
				break;
			}
		}
	}
	
	vector<double> expectedFWHM960mV(nClip);
	for(Int_t i = 0; i < expectedFWHM960mV.size(); i++) {
		expectedFWHM960mV[i] = xLast[i] - xFirst[i];
		// convert from seconds to nanoseconds
		expectedFWHM960mV[i] *= 10E8;
		cout << "expectedFWHM960mV[" << i << "] = " << expectedFWHM960mV[i] << endl;
	}
	
	// expected FWHM 960 mV graph
	
	TGraphErrors *gExpClip960mV = new TGraphErrors(nClip,xClip,&expectedFWHM960mV[0],0,0);
	gExpClip960mV->SetLineStyle(7);
	gExpClip960mV->SetMarkerStyle(20);
	gExpClip960mV->SetMarkerSize(0.8);
	
	// V input 1.9 V
	
	path = "Clipping/Output width analysis/Channel 5/V input 1.9V/";
	
	TGraphErrors *gClip1Point9V = TBGraphErrors(dataSet,path,"V clip","Output FWHM",1,nScope);
	
	gClip1Point9V->SetMarkerStyle(20);
	gClip1Point9V->SetMarkerSize(0.8);
	gClip1Point9V->SetLineColor(kRed);
	gClip1Point9V->GetXaxis()->SetTitle("V clipping (mV)");
	gClip1Point9V->GetYaxis()->SetTitle("Output FWHM (ns)");
	TCanvas *cClip1Point9V = new TCanvas("cClip1Point9V","Output FWHM in function of V clipping",800,600);
	gClip1Point9V->Draw("APEL");
	
	// Expected output FWHM
	
	TGraphErrors *gInput1Point9V = listOfGraphs->FindObject("sum trigger input ch5 1900mV graph");
	
	xClip = gClip1Point9V->GetX();
	nClip = gClip1Point9V->GetN();
	cout << "nClip = " << nClip << endl;
	graphPoints = gInput1Point9V->GetN();
	yInput = gInput1Point9V->GetY();
	xInput = gInput1Point9V->GetX();
	
	vector<double> xFirst(nClip);
	vector<double> xLast(nClip);
	
	flag = 0;
	
	vector<double> yConv(graphPoints);
	for(Int_t i = 0; i < graphPoints; i++) {
		yConv[i] = -(yInput[i]);
		yConv[i] *= 1000;
		if(xInput[i] + inputDelay < lowerCut || xInput[i] + inputDelay > upperCut) yConv[i] = 0;
	}
	
	Double_t yInput1Point9VMax = TMath::MaxElement(graphPoints,&yConv[0]);
	
	for(Int_t i = 0; i < nClip; i++) {
		if(xClip[i] > yInput1Point9VMax) half = yInput1Point9VMax;
		else half = xClip[i];
		
		half /= 2;
		cout << half << endl;
		
		flag = 0;
		
		for(Int_t j = 0; j < graphPoints - 3; j++) {
			if((yConv[j + 1] - half)*(yConv[j] - half) < 0 && flag == 0) {
				xFirst[i] = xInput[j];
				flag = 1;
				cout << "found first point! " << xFirst[i] << endl;
				continue;
			}
			if((yConv[j + 1] - half)*(yConv[j] - half) < 0 && flag == 1) {
				xLast[i] = xInput[j];
				cout << "found last point! " << xLast[i] << endl;
				break;
			}
		}
	}
	
	vector<double> expectedFWHM1Point9V(nClip);
	for(Int_t i = 0; i < expectedFWHM1Point9V.size(); i++) {
		expectedFWHM1Point9V[i] = xLast[i] - xFirst[i];
		// convert from seconds to nanoseconds
		expectedFWHM1Point9V[i] *= 10E8;
		cout << "expectedFWHM1Point9V[" << i << "] = " << expectedFWHM1Point9V[i] << endl;
	}
	
	// expected FWHM 960 mV graph
	
	TGraphErrors *gExpClip1Point9V = new TGraphErrors(nClip,xClip,&expectedFWHM1Point9V[0],0,0);
	gExpClip1Point9V->SetLineStyle(7);
	gExpClip1Point9V->SetLineColor(kRed);
	gExpClip1Point9V->SetMarkerStyle(20);
	gExpClip1Point9V->SetMarkerSize(0.8);
	
	// Collection of Output FWHM graphs, 2 amplitudes, serveral V clipping
	
	TMultiGraph *mgClipOutputFWHM = new TMultiGraph();
	mgClipOutputFWHM->SetTitle("Collection of Output FWHM graphs, 2 amplitudes, serveral V clipping");
	
	mgClipOutputFWHM->Add(gClip1Point9V);
	mgClipOutputFWHM->Add(gClip960mV);
	mgClipOutputFWHM->Add(gExpClip960mV);
	mgClipOutputFWHM->Add(gExpClip1Point9V);
	
	
	TCanvas *cmgClipOutputFWHM = new TCanvas("cmgClipOutputFWHM","Collection of Output FWHM graphs, 2 amplitudes, serveral V clipping");
	mgClipOutputFWHM->Draw("APEL");
	
	cmgClipOutputFWHM->Modified();
	mgClipOutputFWHM->GetXaxis()->SetTitle("V clipping (mV)");
	mgClipOutputFWHM->GetYaxis()->SetTitle("Output FWHM (ns)");
	cmgClipOutputFWHM->Update();
		
	legend = new TLegend(0.6,0.67,0.89,0.86,"V input");
	legend->AddEntry(gClip1Point9V, "1.9 V", "lp");
	legend->AddEntry(gClip960mV, "960 mV", "lp");
	legend->AddEntry(gExpClip960mV, "Exp 960 mV", "lp");
	legend->AddEntry(gExpClip1Point9V, "Exp 1.9 V", "lp");
	legend->SetTextSize(0.04);
	legend->SetMargin(0.5);
	legend->Draw();
	
	// Hysteresis plot: V output (t) in function of V input (t) for several clipping values
	
	// variables used in the analysis
	
	Long64_t iInputMax, iOutputMax;
	Float_t xInputMax, xOutputMax, xInputHalf, xOutputHalf;
	Double_t InputMax, OutputMax, InputHalf, OutputHalf;
	
	Long64_t firstIndex = 0;
	Long64_t lastIndex = 0;
	Long64_t inputGraphPoints = 0;
	Long64_t outputGraphPoints = 0;
	
	// hard coded values to cut the x axis of both waves
	// Input wave
	
	inputWaveName += " graph";
	
	TGraphErrors *gInput = listOfGraphs->FindObject(inputWaveName);
	gInput->SetLineColor(kRed);
	gInput->SetLineWidth(2);
	
	xInput = gInput->GetX();
	yInput = gInput->GetY();
	inputGraphPoints = gInput->GetN();
	
	cout << inputGraphPoints << endl;
	
	// Invert the input wave
	
	for(Int_t i = 0; i < inputGraphPoints; i++) {
		yInput[i] = -(yInput[i]);
	}
	
	// find the x at which the graph reaches the max value
	
	iInputMax = TMath::LocMax(inputGraphPoints, yInput);
	xInputMax = xInput[iInputMax];
	cout << "iInputMax = " << iInputMax << endl;
	cout << "xInputMax = " << xInputMax << endl;
	InputMax = gInput->Eval(xInput[iInputMax]);
	cout << "InputMax = " << InputMax << endl;
	
	// Output wave
	
	outputWaveName += " graph";
	
	TGraphErrors *gOutput = listOfGraphs->FindObject(outputWaveName);
	gOutput->SetLineWidth(2);
	
	xOutput = gOutput->GetX();
	yOutput = gOutput->GetY();
	outputGraphPoints = gOutput->GetN();
	
	// find the x at which the graph reaches the max value
	
	iOutputMax = TMath::LocMax(outputGraphPoints, yOutput);
	xOutputMax = xOutput[iOutputMax];
	cout << "iOutputMax = " << iOutputMax << endl;
	cout << "xOutputMax = " << xOutputMax << endl;
	OutputMax = gOutput->Eval(xOutput[iOutputMax]);
	cout << "OutputMax = " << OutputMax << endl;
	
	// compute x delay between max points
	
	Double_t delay = xOutputMax - xInputMax;
	cout << "delay = " << delay << endl;
	
	// Shift the x axis of the input graph and create a new graph with only a portion of the first graph
	
	for(Int_t i = 0; i < inputGraphPoints; i++) {
		xInput[i] += inputDelay;
		
		if(xInput[i] >= lowerCut) {
			if(firstIndex == 0) firstIndex = i;
		}

		if(xInput[i] <= upperCut)
			lastIndex = i;
	}
	
	cout << "firstIndex = " << firstIndex << endl;
	cout << "lastIndex = " << lastIndex << endl;
	cout << "xInput[firstIndex] = " << xInput[firstIndex] << endl;
	cout << lastIndex - firstIndex << endl;
	
	Long64_t input2GraphPoints = lastIndex - firstIndex;
	
	TGraphErrors *gInput2 = new TGraphErrors(input2GraphPoints);
	gInput2->SetTitle(inputWaveName);
	
	for(Int_t i = firstIndex; i <= lastIndex; i++) {
		gInput2->SetPoint(i - firstIndex,xInput[i],yInput[i]);
	}
	
	TCanvas *cgInput2 = new TCanvas("cgInput2", "cgInput2", 1200,800);
	gInput2->Draw("AL");
	
	// create a new graph with only a portion of the first graph
	
	firstIndex = 0;
	lastIndex = 0;
	
	for(Int_t i = 0; i < outputGraphPoints; i++) {
		if(xOutput[i] >= lowerCut) {
			if(firstIndex == 0) firstIndex = i;
		}

		if(xOutput[i] <= upperCut)
			lastIndex = i;
	}
	
	cout << "firstIndex = " << firstIndex << endl;
	cout << "lastIndex = " << lastIndex << endl;
	cout << "xOutput[firstIndex] = " << xOutput[firstIndex] << endl;
	cout << lastIndex - firstIndex << endl;
	
	Long64_t output2GraphPoints = lastIndex - firstIndex;
	
	TGraphErrors *gOutput2 = new TGraphErrors(output2GraphPoints);
	gOutput2->SetTitle(outputWaveName);
	
	for(Int_t i = firstIndex; i <= lastIndex; i++) {
		gOutput2->SetPoint(i - firstIndex,xOutput[i],yOutput[i]);
	}
	
	TCanvas *cgOutput2 = new TCanvas("cgOutput2", "cgOutput2", 1200,800);
	gOutput2->Draw("AL");
	
	// first hysteresis plot
	
	Double_t step;
	
	Double_t *xInput2;
	xInput2 = gInput2->GetX();
	
	cout << "xInput2[input2GraphPoints - 1] = " << xInput2[input2GraphPoints - 1] << endl;
	cout << "xInput2[0] = " << xInput2[0] << endl;
	
	step = (xInput2[input2GraphPoints - 1] - xInput2[0])/output2GraphPoints;
	
	cout << "step = " << step << endl;
	
	// in case gInput2 and gOutput2 contain a different number of points create the hysteresis plot with gOutput2 points
	// and modify the yInput2 to match the number of points of yOutput2
	
	vector<double> yInput2;
	
	for(Int_t i = 0; i < output2GraphPoints; i++) {
		yInput2.push_back(gInput2->Eval(xInput2[0] + i*step));
	}
	
	Double_t *yOutput2;
	yOutput2 = gOutput2->GetY();
	
	TGraphErrors *gHyst = new TGraphErrors(output2GraphPoints, &yInput2.at(0),yOutput2);
	gHyst->SetTitle("Hysteresis plot");
	
	gHyst->GetXaxis()->SetTitle("Vin(t) [mV]");
	gHyst->GetYaxis()->SetTitle("Vout(t) [mV]");
	gHyst->GetYaxis()->SetTitleOffset(1.4);
	
	TCanvas *cgHyst = new TCanvas("cgHyst", "cgHyst", 1200,800);
	cgHyst->SetLeftMargin(0.12);
	gHyst->Draw("AL");
	
	// collection of graphs
	
	TMultiGraph *mgInputOutput = new TMultiGraph();
	mgInputOutput->Add(gInput);
	mgInputOutput->Add(gOutput);
	mgInputOutput->SetTitle("Input and output");
	
	TCanvas *cmgInputOutput = new TCanvas("cmgInputOutput", "Input and output", 1200,800);
	mgInputOutput->Draw("AL");
	cmgInputOutput->Update();
	legend = new TLegend(0.65,0.68,0.86,0.86);
	legend->AddEntry(gInput, "Input", "lp");
	legend->AddEntry(gOutput, "Output", "lp");
	legend->SetMargin(0.4);
	legend->SetTextSize(0.04);
	legend->Draw();
	cmgInputOutput->Modified();

	
}
Exemple #14
0
// Soft radiation corrections for L3Res
void softrad(double etamin=0.0, double etamax=1.3, bool dodijet=false) {

  setTDRStyle();
  writeExtraText = false; // for JEC paper CWR

  TDirectory *curdir = gDirectory;

  // Open jecdata.root produced by reprocess.C
  TFile *fin = new TFile("rootfiles/jecdata.root","UPDATE");
  assert(fin && !fin->IsZombie());
  
  const int ntypes = 3;
  const char* types[ntypes] = {"data", "mc", "ratio"};
  const int nmethods = 2;
  const char* methods[nmethods] = {"mpfchs1", "ptchs"};
  const int nsamples = (dodijet ? 4 : 3);
  const char* samples[4] = {"gamjet", "zeejet", "zmmjet", "dijet"};
  string sbin = Form("eta%02.0f-%02.0f",10*etamin,10*etamax);
  const char* bin = sbin.c_str();
  const int nalphas = 4;
  const int alphas[nalphas] = {30, 20, 15, 10};

  // Z+jet bins
  const double ptbins1[] = {30, 40, 50, 60, 75, 95, 125, 180, 300, 1000};
  const int npt1 = sizeof(ptbins1)/sizeof(ptbins1[0])-1;
  TH1D *hpt1 = new TH1D("hpt1","",npt1,&ptbins1[0]);
  TProfile *ppt1 = new TProfile("ppt1","",npt1,&ptbins1[0]);

  // gamma+jet bins
  const double ptbins2[] = {30, 40, 50, 60, 75, 100, 125, 155, 180,
			    210, 250, 300, 350, 400, 500, 600, 800};
  const int npt2 = sizeof(ptbins2)/sizeof(ptbins2[0])-1;
  TH1D *hpt2 = new TH1D("hpt2","",npt2,&ptbins2[0]);
  TProfile *ppt2 = new TProfile("ppt2","",npt2,&ptbins2[0]);

  // dijet bins
  const double ptbins4[] = {20, 62, 107, 175, 242, 310, 379, 467,
			    628, 839, 1121, 1497, 2000};
  const int npt4 = sizeof(ptbins4)/sizeof(ptbins4[0])-1;
  TH1D *hpt4 = new TH1D("hpt4","",npt4,&ptbins4[0]);
  TProfile *ppt4 = new TProfile("ppt4","",npt4,&ptbins4[0]);

  TLatex *tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSize(0.045);

  map<string,const char*> texlabel;
  texlabel["gamjet"] = "#gamma+jet";
  texlabel["zeejet"] = "Z#rightarrowee+jet";
  texlabel["zmmjet"] = "Z#rightarrow#mu#mu+jet";
  texlabel["dijet"] = "Dijet";
  texlabel["ptchs"] = "p_{T} balance (CHS)";
  texlabel["mpfchs"] = "MPF raw (CHS)";
  texlabel["mpfchs1"] = "MPF type-I (CHS)";

  // overlay of various alpha values
  TCanvas *c1 = new TCanvas("c1","c1",ntypes*400,nmethods*400);
  c1->Divide(ntypes,nmethods);

  TH1D *h1 = new TH1D("h1",";p_{T} (GeV);Response",1270,30,1300);

  // extrapolation vs alpha for each pT bin
  vector<TCanvas*> c2s(ntypes*nmethods);
  for (unsigned int icanvas = 0; icanvas != c2s.size(); ++icanvas) {
    TCanvas *c2 = new TCanvas(Form("c2_%d",icanvas),Form("c2_%d",icanvas),
			      1200,1200);
    c2->Divide(3,3);
    c2s[icanvas] = c2;
  }

  TH1D *h2 = new TH1D("h2",";#alpha;Response",10,0.,0.4);
  h2->SetMaximum(1.08);
  h2->SetMinimum(0.88);

  // krad corrections
  TCanvas *c3 = new TCanvas("c3","c3",ntypes*400,nmethods*400);
  c3->Divide(ntypes,nmethods);

  TH1D *h3 = new TH1D("h3",";p_{T,ref} (GeV);FSR sensitivity: -dR/d#alpha [%]",
		      1270,30,1300);

  cout << "Reading in data" << endl << flush;
  // Read in plots vs pT (and alpha)
  map<string, map<string, map<string, map<int, TGraphErrors*> > > > gemap;
  map<string, map<string, map<string, map<int, TGraphErrors*> > > > gamap;
  for (int itype = 0; itype != ntypes; ++itype) {
    for (int  imethod = 0; imethod != nmethods; ++imethod) {
      for (int  isample = 0; isample != nsamples; ++isample) {

	for (int  ialpha = 0; ialpha != nalphas; ++ialpha) {

	  fin->cd();
	  assert(gDirectory->cd(types[itype]));
	  assert(gDirectory->cd(bin));
	  TDirectory *d = gDirectory;

	  const char *ct = types[itype];
	  const char *cm = methods[imethod];
	  const char *cs = samples[isample];
	  const int a = alphas[ialpha];
	  // Get graph made vs pT
	  string s = Form("%s/%s/%s_%s_a%d",types[itype],bin,cm,cs,a);
	  TGraphErrors *g = (TGraphErrors*)fin->Get(s.c_str());
	  if (!g) cout << "Missing " << s << endl << flush;
	  assert(g);

	  // Clean out empty points
	  // as well as trigger-biased ones for dijets
	  // as well as weird gamma+jet high pT point
	  for (int i = g->GetN()-1; i != -1; --i) {
	    if (g->GetY()[i]==0 || g->GetEY()[i]==0 ||
		(string(cs)=="dijet" && g->GetX()[i]<70.) ||
		(string(cs)=="gamjet" && g->GetX()[i]>600. && etamin!=0))
	      g->RemovePoint(i);
	  }

	  gemap[ct][cm][cs][a] = g;
	  
	  // Sort points into new graphs vs alpha
	  TH1D *hpt = (isample==0 ? hpt2 : hpt1);
	  TProfile *ppt = (isample==0 ? ppt2 : ppt1);
	  if (isample==3) { hpt = hpt4; ppt = ppt4; } // pas-v6
	  for (int i = 0; i != g->GetN(); ++i) {
	    
	    double pt = g->GetX()[i];
	    ppt->Fill(pt, pt);
	    int ipt = int(hpt->GetBinLowEdge(hpt->FindBin(pt))+0.5);
	    //int ipt = int(pt+0.5);
	    TGraphErrors *ga = gamap[ct][cm][cs][ipt];
	    if (!ga) {
	      ga = new TGraphErrors(0);
	      ga->SetMarkerStyle(g->GetMarkerStyle());
	      ga->SetMarkerColor(g->GetMarkerColor());
	      ga->SetLineColor(g->GetLineColor());
	      gamap[ct][cm][cs][ipt] = ga;
	    }
	    int n = ga->GetN();
	    ga->SetPoint(n, 0.01*a, g->GetY()[i]);
	    ga->SetPointError(n, 0, g->GetEY()[i]);
	  } // for i 

	} // for ialpha

      } // for isample
    } // for imethod
  } // for itype

  cout << "Drawing plots vs pT for each alpha" << endl << flush;

  // 2x6 plots
  for (int itype = 0; itype != ntypes; ++itype) {
    for (int  imethod = 0; imethod != nmethods; ++imethod) {

      const char *ct = types[itype];
      const char *cm = methods[imethod];

      int ipad = ntypes*imethod + itype + 1; assert(ipad<=6);
      c1->cd(ipad);
      gPad->SetLogx();
      h1->SetMaximum(itype<2 ? 1.15 : 1.08);
      h1->SetMinimum(itype<2 ? 0.85 : 0.93);
      h1->SetYTitle(Form("Response (%s)",ct));
      h1->DrawClone("AXIS");
      tex->DrawLatex(0.20,0.85,texlabel[cm]);
      tex->DrawLatex(0.20,0.80,"|#eta| < 1.3, #alpha=0.1--0.3");
      TLegend *leg = tdrLeg(0.60,0.75,0.90,0.90);

      for (int  isample = 0; isample != nsamples; ++isample) {
	for (int  ialpha = 0; ialpha != nalphas; ++ialpha) {

	  const char *cs = samples[isample];
	  const int a = alphas[ialpha];
	  TGraphErrors *g = gemap[ct][cm][cs][a]; assert(g);

	  // Clean out points with very large uncertainty for plot readability
	  for (int i = g->GetN()-1; i != -1; --i) {
	    if (g->GetEY()[i]>0.02) g->RemovePoint(i);
	  }

	  g->Draw("SAME Pz");

	  if (ialpha==0) leg->AddEntry(g,texlabel[cs],"P");
	}
      } // for isample

      // Individual plots for JEC paper
      if ( true ) { // paper

	TH1D *h = new TH1D(Form("h_5%s_%s",ct,cm),
			   Form(";p_{T} (GeV);Response (%s)",ct),
			   1270,30,1300);
	h->GetXaxis()->SetMoreLogLabels();
	h->GetXaxis()->SetNoExponent();
	h->SetMinimum(0.88);
	h->SetMaximum(1.13);

	writeExtraText = true;
	extraText = (string(ct)=="mc" ? "Simulation" : "");
	lumi_8TeV = (string(ct)=="mc" ? "" : "19.7 fb^{-1}");
	TCanvas *c0 = tdrCanvas(Form("c0_%s_%s",cm,ct), h, 2, 11, true);
	c0->SetLogx();
	

	TLegend *leg = tdrLeg(0.55,0.68,0.85,0.83);
	tex->DrawLatex(0.55,0.85,texlabel[cm]);
	tex->DrawLatex(0.55,0.18,"|#eta| < 1.3, #alpha=0.3");
	//tex->DrawLatex(0.55,0.18,"Anti-k_{T} R=0.5");

	// Loop over Z+jet and gamma+jet (only, no dijet/multijet)
	for (int  isample = 0; isample != min(3,nsamples); ++isample) {
	  
	  const char *cs = samples[isample];
	  TGraphErrors *g = gemap[ct][cm][cs][30]; assert(g);
	  g->Draw("SAME Pz");
	  
	  leg->AddEntry(g,texlabel[cs],"P");
	} // for isample

	if (etamin==0) {
	  c0->SaveAs(Form("pdf/paper_softrad_%s_%s_vspt.pdf",ct,cm));
	  c0->SaveAs(Form("pdfC/paper_softrad_%s_%s_vspt.C",ct,cm));
	}
	else {
	  c0->SaveAs(Form("pdf/an_softrad_%s_%s_eta%1.0f-%1.0f_vspt.pdf",
			  ct,cm,10*etamin,10*etamax));
	}
      } // paper

    } // for imethod
  } // for itype
  
  c1->cd(0);
  //cmsPrel(_lumi, true);
  CMS_lumi(c1, 2, 33);
  c1->SaveAs("pdf/softrad_2x6_vspt.pdf");


  cout << "Drawing plots vs alpha for each pT" << endl << flush;
  cout << "...and fitting slope vs alpha" << endl << flush;

  map<string, map<string, map<string, TGraphErrors* > > > gkmap;

  // 2x6 plots
  for (int itype = 0; itype != ntypes; ++itype) {
    for (int  imethod = 0; imethod != nmethods; ++imethod) {
      
      int icanvas = nmethods*imethod + itype; assert(icanvas<=6);
      TCanvas *c2 = c2s[icanvas]; assert(c2);

      const char *ct = types[itype];
      const char *cm = methods[imethod];

      const int npads = 9;
      for (int ipad = 0; ipad != npads; ++ipad) {
	c2->cd(ipad+1);
	h2->SetYTitle(Form("Response (%s)",ct));
	h2->DrawClone("AXIS");
	tex->DrawLatex(0.20,0.85,texlabel[cm]);
	tex->DrawLatex(0.20,0.80,"|#eta| < 1.3");
	tex->DrawLatex(0.20,0.75,Form("%1.0f < p_{T} < %1.0f GeV",
				      hpt1->GetBinLowEdge(ipad+1),
				      hpt1->GetBinLowEdge(ipad+2)));
	TLegend *leg = tdrLeg(0.65,0.75,0.90,0.90);
	leg->AddEntry(gemap[ct][cm]["gamjet"][30], texlabel["gamjet"], "P");
	leg->AddEntry(gemap[ct][cm]["zeejet"][30], texlabel["zeejet"], "P");
	leg->AddEntry(gemap[ct][cm]["zmmjet"][30], texlabel["zmmjet"], "P");
	leg->AddEntry(gemap[ct][cm]["dijet"][30], texlabel["dijet"], "P");
      }

      for (int  isample = 0; isample != nsamples; ++isample) {

	const char *cs = samples[isample];

	map<int, TGraphErrors*> &gam = gamap[ct][cm][cs];
	map<int, TGraphErrors*>::iterator itpt;
	for (itpt = gam.begin(); itpt != gam.end(); ++itpt) {

	  int ipt = itpt->first;
	  int jpt = hpt1->FindBin(ipt);
	  if (jpt>npads) continue;
	  assert(jpt<=npads);
	  c2->cd(jpt);
	  
	  TGraphErrors *ga = itpt->second; assert(ga);
	  
	  ga->Draw("SAME Pz");

	  // Fit slope
	  TF1 *f1 = new TF1(Form("f1_%s_%s_%s_%d",ct,cm,cs,ipt),
			    "(x<1)*([0]+[1]*x) + (x>1 && x<2)*[0] +"
			    "(x>2)*[1]",-1,1);
	  f1->SetLineColor(ga->GetLineColor());
	  f1->SetParameters(1,0);
	  const double minalpha = (isample==0 ? 10./ipt : 5./ipt);
	  // Constrain slope to within reasonable values
	  // in the absence of sufficient data using priors
	  if (true) { // use priors
	    int n = ga->GetN();
	    // For response, limit to 1+/-0.02 (we've corrected for L3Res
	    ga->SetPoint(n, 1.5, 1);
	    ga->SetPointError(n, 0, 0.02);
	    n = ga->GetN();
	    if (imethod==1) { // pT balance
	      // For pT balance, estimate slope of <vecpT2>/alpha from data
	      // => 7.5%/0.30 = 25%
	      // Approximate uncertainty on this to be
	      // 0.5%/0.30 ~ 1.5% for data, 0.5%/0.30 ~ 1.5% for Z+jet MC, and
	      // 2%/0.30 ~ 6% for gamma+jet MC (same as slope)
	      if (itype==0)               ga->SetPoint(n, 2.5, -0.250); // DT
	      if (itype==1 && isample!=0) ga->SetPoint(n, 2.5, -0.250); // MC
	      if (itype==1 && isample==0) ga->SetPoint(n, 2.5, -0.190);
	      if (itype==2 && isample!=0) ga->SetPoint(n, 2.5, -0.000); // rt
	      if (itype==2 && isample==0) ga->SetPoint(n, 2.5, -0.060); 
	      //
	      // BUG: found 2015-01-08 (no effect on ratio)
	      //if (itype==1)               ga->SetPointError(n, 0, -0.015);
	      if (itype==0)               ga->SetPointError(n, 0, -0.015); // DT
	      if (itype==1 && isample!=0) ga->SetPointError(n, 0, -0.015); // MC
	      if (itype==1 && isample==0) ga->SetPointError(n, 0, -0.060);
	      if (itype==2 && isample!=0) ga->SetPointError(n, 0, -0.015); // rt
	      if (itype==2 && isample==0) ga->SetPointError(n, 0, -0.060); 
	    }
	    if (imethod==0) { // MPF
	      // For MPF, expectation is no slope
	      // Maximal slope would be approximately
	      // (<vecpT2>/alpha ~ 25% from pT balance) times
	      // (response difference between pT1 and vecpT2~10%)
	      // => 0.25*0.10 = 2.5%
	      // For data/MC, estimate uncertainty as half of this
	      // => 1.25%
	      ga->SetPoint(n, 2.5, 0.);
	      if (itype!=2) ga->SetPointError(n, 0, 0.025);
	      if (itype==2) ga->SetPointError(n, 0, 0.0125);
	    } // MPF
	  } // use priors

	  if (ga->GetN()>2) {

	    f1->SetRange(minalpha, 3.);
	    ga->Fit(f1,"QRN");

	    if (f1->GetNDF()>=0) {
	      f1->DrawClone("SAME");
	      f1->SetRange(0,0.4);
	      f1->SetLineStyle(kDashed);
	      f1->DrawClone("SAME");

	      // Store results
	      TGraphErrors *gk = gkmap[ct][cm][cs];
	      if (!gk) {
		gk = new TGraphErrors(0);
		gk->SetMarkerStyle(ga->GetMarkerStyle());
		gk->SetMarkerColor(ga->GetMarkerColor());
		gk->SetLineColor(ga->GetLineColor());
		gkmap[ct][cm][cs] = gk;
	      }
	      int n = gk->GetN();
	      TProfile *ppt = (isample==0 ? ppt2 : ppt1);
	      if (isample==3) { ppt = ppt4; } // pas-v6
	      double pt = ppt->GetBinContent(ppt->FindBin(ipt));
	      gk->SetPoint(n, pt, f1->GetParameter(1));
	      gk->SetPointError(n, 0, f1->GetParError(1));
	    } // f1->GetNDF()>=0
	  } // ga->GetN()>2
	} // for itpt
	
      } // for isample
      
      c2->SaveAs(Form("pdf/softrad_3x3_%s_%s_vsalpha.pdf",ct,cm));
      
    }
  }


  cout << "Drawing plots of kFSR vs pT" << endl;

  // 2x6 plots
  for (int itype = 0; itype != ntypes; ++itype) {
    for (int  imethod = 0; imethod != nmethods; ++imethod) {

      const char *ct = types[itype];
      const char *cm = methods[imethod];

      TMultiGraph *mgk = new TMultiGraph();

      int ipad = ntypes*imethod + itype + 1; assert(ipad<=6);
      c3->cd(ipad);
      gPad->SetLogx();
      h3->SetMaximum(imethod==0 ? 0.05 : (itype!=2 ? 0.1 : 0.25));
      h3->SetMinimum(imethod==0 ? -0.05 : (itype!=2 ? -0.4 : -0.25));
      h3->SetYTitle(Form("k_{FSR} = dR/d#alpha (%s)",ct));
      h3->DrawClone("AXIS");
      tex->DrawLatex(0.20,0.85,texlabel[cm]);
      tex->DrawLatex(0.20,0.80,"|#eta| < 1.3");
      TLegend *leg = tdrLeg(0.60,0.75,0.90,0.90);

      for (int  isample = 0; isample != nsamples; ++isample) {

	const char *cs = samples[isample];
	TGraphErrors *gk = gkmap[ct][cm][cs]; assert(gk);
	
	leg->AddEntry(gk,texlabel[cs],"P");

	// Fit each sample separately for pT balance
	if (true) {

	  TF1 *fk = new TF1(Form("fk_%s_%s_%s",ct,cm,cs),
			    "[0]+[1]*log(0.01*x)+[2]*pow(log(0.01*x),2)",
			    30,1300);
	  fk->SetParameters(-0.25,-0.5);
	  fk->SetLineColor(gk->GetLineColor());
	  gk->Fit(fk, "QRN");

	  tex->SetTextColor(fk->GetLineColor());
	  tex->DrawLatex(0.55,0.27-0.045*isample,
			 Form("#chi^{2}/NDF = %1.1f / %d",
			      fk->GetChisquare(), fk->GetNDF()));
	  tex->SetTextColor(kBlack);

	  // Error band
	  const int n = fk->GetNpar();
	  TMatrixD emat(n,n);
	  gMinuit->mnemat(emat.GetMatrixArray(), n);
	  TF1 *fke = new TF1(Form("fk_%s_%s_%s",ct,cm,cs),
			     sr_fitError, 30, 1300, 1);
	  _sr_fitError_func = fk;
	  _sr_fitError_emat = &emat;

	  fke->SetLineStyle(kSolid);
	  fke->SetLineColor(fk->GetLineColor()-10);
	  fke->SetParameter(0,-1);
	  fke->DrawClone("SAME");
	  fke->SetParameter(0,+1);
	  fke->DrawClone("SAME");

	  fk->DrawClone("SAME");
	  gk->DrawClone("SAME Pz");

	  // Store soft radiation corrections in fsr subdirectory
	  assert(fin->cd(ct));
	  assert(gDirectory->cd(bin));
	  if (!gDirectory->FindObject("fsr")) gDirectory->mkdir("fsr");
	  assert(gDirectory->cd("fsr"));

	  TH1D *hk = (TH1D*)(isample==0 ? hpt2->Clone() : hpt1->Clone());
	  hk->SetName(Form("hkfsr_%s_%s",cm,cs));
	  TProfile *ppt = (isample==0 ? ppt2 : ppt1);
	  if (isample==3) { ppt = ppt4; } // pas-v6
	  for (int i = 1; i != hk->GetNbinsX()+1; ++i) {
	    double pt = ppt->GetBinContent(i);
	    if (pt>30 && pt<1300) {
	      hk->SetBinContent(i, fk->Eval(pt));
	      hk->SetBinError(i, fabs(fke->Eval(pt)-fk->Eval(pt)));
	    }
	    else {
	      hk->SetBinContent(i, 0);
	      hk->SetBinError(i, 0);
	    }
	  }
	  
	  hk->Write(hk->GetName(), TObject::kOverwrite);

	  // Factorize error matrix into eigenvectors
	  // Remember: A = Q*Lambda*Q^-1, where
	  // A is emat, Q is eigmat, and Lambda is a diagonal matrix with
	  // eigenvalues from eigvec on the diagonal. For eigenmatrix
	  // Q^-1 = Q^T, i.e. inverse matrix is the original transposed
	  TVectorD eigvec(n);
	  TMatrixD eigmat = emat.EigenVectors(eigvec);

	  // Eigenvectors are the columns and sum of eigenvectors squared
	  // equals original uncertainty. Calculate histograms from the
	  // eigenvectors and store them
	  TF1 *fkeig = (TF1*)fk->Clone(Form("%s_eig",fk->GetName()));
	  fkeig->SetLineStyle(kDotted);
	  for (int ieig = 0; ieig != n; ++ieig) {

	    // Eigenvector functions
	    for (int i = 0; i != n; ++i) {
	      fkeig->SetParameter(i, fk->GetParameter(i)
				  + eigmat[i][ieig] * sqrt(eigvec[ieig]));
	    }
	    fkeig->DrawClone("SAMEL");

	    // Eigenvector histograms evaluated at bin mean pT
	    TH1D *hke = (TH1D*)hk->Clone(Form("%s_eig%d",hk->GetName(),ieig));
	    hke->Reset();

	    for (int i = 0; i != gk->GetN(); ++i) {

	      double pt = gk->GetX()[i];
	      int ipt = hke->FindBin(pt);
	      // Need to store central value as well, because
	      // uncertainty sources are signed
	      hke->SetBinContent(ipt, fkeig->Eval(pt)-fk->Eval(pt));
	      hke->SetBinError(ipt, fabs(fkeig->Eval(pt)-fk->Eval(pt)));
	    }
	    hke->Write(hke->GetName(), TObject::kOverwrite);
	  }

	  cout << "." << flush;
	} // if tree
      } // for isample
    } // for imethod
  } // for itype
  
  c3->cd(0);
  //cmsPrel(_lumi, true);
  CMS_lumi(c3, 2, 33);
  c3->SaveAs("pdf/softrad_2x6_kfsr.pdf");

  fin->Close();
  curdir->cd();
} // softrad
Exemple #15
0
void DrawKinvarPlot(TString filename="kinvarset/FMSOR_Pt_vs_run.root",
                    TString classname="pi0") {
  TFile * infile = new TFile(filename.Data(),"READ");

  char trig[32];
  char typ[32];
  char tmp[128];
  TString tmpstr = filename;
  tmpstr.ReplaceAll("_"," ");
  TRegexp re("^.*\/");
  tmpstr(re) = "";
  cout << tmpstr << endl;
  sscanf(tmpstr.Data(),"%s %s",trig,typ);
  printf("%s %s\n",trig,typ);

  TString hname = "h2_"+classname;
  TH2D * h = (TH2D*)infile->Get(hname.Data());
  TString gname = "g_"+classname;
  TGraphErrors * g = (TGraphErrors*)infile->Get(gname.Data());
  TString gtname = "gt_"+classname;
  TGraphErrors * gt;
  if(!strcmp(typ,"Pt")) gt = (TGraphErrors*)infile->Get(gtname.Data());
  
  char htitle[256];
  char hnewtitle[512];
  strcpy(htitle,h->GetTitle());
  sprintf(hnewtitle,"%s -- %s triggers",htitle,trig);
  h->SetTitle(hnewtitle);

  h->SetMinimum(0.001);

  if(!strcmp(typ,"Pt")) {
    gt->SetLineWidth(2);
    gt->SetLineColor(kBlack);
  };

  // temporary hack to cut out fluctuations of pt_thresh vs. run to 0
  Double_t xx,yy;
  Int_t gtn = gt->GetN();
  for(int ii=0; ii<gtn; ii++) {
    gt->GetPoint(ii,xx,yy);
    printf("xx=%f yy=%f\n",xx,yy);
    if(yy<0.001) gt->RemovePoint(ii);
  };
   
  // drawing range
  Float_t xmin = h->GetXaxis()->GetXmin();
  Float_t xmax = h->GetXaxis()->GetXmax();
  xmax = 515;
  if(xmax<gtn) { 
    fprintf(stderr,"\nWARNING: xmax < gt->GetN(); graphs will be cut off!\n\n");
  };
  
  TCanvas * c = new TCanvas("c","c",1500,700);
  c->Divide(1,2);
  gStyle->SetOptStat(0);
  for(int x=1; x<=2; x++) c->GetPad(x)->SetGrid(1,1);
  c->cd(1);
  c->GetPad(1)->SetLogz();
  h->GetXaxis()->SetRangeUser(xmin,xmax);
  h->Draw("colz");
  if(!strcmp(typ,"Pt")) gt->Draw("LX");
  c->cd(2);
  g->SetFillColor(kGray);
  printf("%f %f\n",xmin,xmax);
  g->GetXaxis()->SetLimits(xmin,xmax);
  g->GetXaxis()->SetRangeUser(xmin,xmax);
  /*
  g->Draw("A3");
  g->Draw("PLX");
  */
  g->Draw("APLX");
  
  TString outname = filename.ReplaceAll(".root"," "+classname);
  outname = outname+".png";
  c->Print(outname.Data(),"png");
};
void AnalyzeWaveforms(char *WaveformsFile = "Waveforms.root", const int nAddedChannels = 5) {
	
	//try to access waveforms file and in case of failure return
	if(gSystem->AccessPathName(WaveformsFile,kFileExists)) {
		cout << "Error: file " << WaveformsFile << " does not exsist. Run .x WaveformsFileMaker.C to create it" << endl;
		return;
	}
	//	gStyle->SetOptFit(111);
	//	gStyle->SetStatFormat("1.3E");
	//	gStyle->SetFitFormat("1.3E");
	
	// fetch the list of trees contained in the waveforms file
	// for every tree generate a waveform graph

	TFile *f = TFile::Open(WaveformsFile);
	TList *listOfKeys = f->GetListOfKeys();
	Int_t numberOfKeys = listOfKeys->GetEntries();
	TList *listOfGraphs = new TList();
	
	// if the waveform file name begins with the string "comparator" it goes in this list
	TList *listOfCompWaves = new TList();
	// if the waveform file name begins with the string "sum output" it goes in this list
	TList *listOfAdderWaves = new TList();

	for(Int_t i = 0; i < numberOfKeys; i++) {
		TString *keyName = new TString(listOfKeys->At(i)->GetName());
		TTree *tree = (TTree*)f->Get(keyName->Data());
		Float_t x = 0;
		Float_t y = 0;
		tree->SetBranchAddress("x",&x);
		tree->SetBranchAddress("y",&y);
		Int_t nentries = tree->GetEntries();

		TString *gName = new TString(keyName->Data());
		gName->Append(" graph");
		TGraphErrors *gWave = new TGraphErrors(nentries);
		gWave->SetName(gName->Data());
		gWave->SetTitle(gName->Data());
		gWave->GetXaxis()->SetTitle("Time");
		gWave->GetYaxis()->SetTitle("Voltage");
	//	gWave->SetBit(TH1::kCanRebin);

		for (Int_t j = 0; j < nentries; j++) {
			tree->GetEntry(j);
			gWave->SetPoint(j,x,y);
		}

		listOfGraphs->Add(gWave);

		if(keyName->BeginsWith("comparator"))
			listOfCompWaves->Add(gWave);

		if(keyName->BeginsWith("sum output"))
			listOfAdderWaves->Add(gWave);

	/*	TString *cName = new TString(keyName->Data());
		cName->Append(" canvas");
		TCanvas *cy = new TCanvas(cName->Data(),cName->Data(),800,600);
		gWave->Draw("AL"); */
	}
	
	cout << listOfAdderWaves->GetEntries() << endl;

	// analysis for waves with no delay

	// global variables

	Double_t xMin,xMax,yStart,yEnd;
	Int_t graphPoints;
	Double_t step;

	// comparator outputs waves sum

	TGraphErrors *gFirstCompWave = (TGraphErrors *)listOfCompWaves->First();

	graphPoints = gFirstCompWave->GetN();
	gFirstCompWave->GetPoint(0,xMin,yStart);
	gFirstCompWave->GetPoint(graphPoints - 1,xMax,yEnd); 

	step = (xMax - xMin)/graphPoints;
	cout << gFirstCompWave->GetName() << endl;
	cout << "xMin = " << xMin << "  xMax = " << xMax << "  graphPoints = " << graphPoints << endl;

	TGraphErrors *gCompSum = new TGraphErrors(graphPoints);
	gCompSum->SetLineColor(kBlue);
	gCompSum->SetLineWidth(2);
	gCompSum->SetName("Comparator Outputs Sum");
	gCompSum->SetTitle("Comparator Outputs Sum");
	Int_t nCompWaves = listOfCompWaves->GetEntries();
	Float_t gx,gy = 0;
	
	// Alpha coefficiens are now written "hard coded" here
	Float_t alphaArray[3] = {0.199,0.201,0.197};
	
	// Deleays coming from the multiplexer are written "hard coded" here
	Float_t muxDelayArray[3] = {0,77.14E-12,192.01E-12};

	for(Int_t i = 0; i < graphPoints; i++) {
		for(Int_t j = 0; j < nCompWaves; j++) {
			TGraphErrors *gCompWave = (TGraphErrors *)listOfCompWaves->At(j);
			gy += (gCompWave->Eval(xMin + i*step + muxDelayArray[j]))*alphaArray[j];
		}
		gCompSum->SetPoint(i,xMin + i*step,gy);
		gy = 0;
	}
	
	// note that there is a manual correction on the x axis for the comparator waves sum to compare them better in the multigraph
	
	Double_t *xArray = gCompSum->GetX();
	for(Int_t i = 0; i < graphPoints; i++) {
		xArray[i] += 5.6E-9;
	}

//	TCanvas *cCompSum = new TCanvas("cCompSum","Comparator Outputs Sum",800,600);
//	gCompSum->Draw("AL");

	// adder outputs waves sum
	
	// THE ANALYSIS FOR THE ADDER OUTPUT WITH NOT DELAY AND 3 CHANNELS ADDED IS DEPRECATED.
	// THERE WAS A MISTAKE IN THE DATA TAKING
	// I'LL KEEP THE CODE HERE FOR FURTHER REFERENCE

/*
	TGraphErrors *gFirstAdderWave = (TGraphErrors *)listOfAdderWaves->First();

	graphPoints = gFirstAdderWave->GetN();
	gFirstAdderWave->GetPoint(0,xMin,yStart);
	gFirstAdderWave->GetPoint(graphPoints - 1,xMax,yEnd);

	step = (xMax - xMin)/graphPoints;
	cout << gFirstAdderWave->GetName() << endl;
	cout << "xMin : " << xMin << "  xMax : " << xMax << endl;

	TGraphErrors *gAdderSum = new TGraphErrors(graphPoints);
	gAdderSum->SetLineWidth(2);
//	gAdderSum->SetLineColor(kGreen);
	gAdderSum->SetLineStyle(9);
	gAdderSum->SetName("Sum of the adder outputs with no delay");
	gAdderSum->SetTitle("Sum of the adder outputs with no delay");
	Int_t nAdderWaves = listOfAdderWaves->GetEntries();
	gy = 0;

	for(Int_t i = 0; i < graphPoints; i++) {
		for(Int_t j = 0; j < nAdderWaves; j++) {
			TGraphErrors *gAdderWave = (TGraphErrors *)listOfAdderWaves->At(j);
			gy += gAdderWave->Eval(xMin + i*step);
		} 
		gAdderSum->SetPoint(i,xMin + i*step,gy);
		gy = 0;
	}

//	TCanvas *cAdderSum = new TCanvas("cAdderSum","Sum of the adder outputs",800,600);
//	gAdderSum->Draw("AL"); 
	
	TGraphErrors *g3ChannelsSumNoDelay = listOfGraphs->FindObject("sum_output_3_channels_(3) graph");
	g3ChannelsSumNoDelay->SetLineColor(kRed);
	g3ChannelsSumNoDelay->SetLineWidth(2);
	
	// note that there is a manual correction on the x axis for the adder output to compare it better in the multigraph
	
	Double_t *xArray = g3ChannelsSumNoDelay->GetX();
	graphPoints = g3ChannelsSumNoDelay->GetN();
	
	for(Int_t i = 0; i < graphPoints; i++) {
		xArray[i] -= 600E-12;
	}
	
	// comparison among the computed adder output ,the real one and the sum of the comparator outputs with alpha coefficients correction
	
	TMultiGraph *mgSumNoDelay = new TMultiGraph();
	mgSumNoDelay->Add(g3ChannelsSumNoDelay);
	mgSumNoDelay->Add(gAdderSum);
	mgSumNoDelay->Add(gCompSum);
	mgSumNoDelay->SetTitle("Collection of graphs for 3 channels sum with no delay");
	
	TCanvas *cmgSumNoDelay = new TCanvas("cmgSumNoDelay", "Collection of graphs for 3 channels sum with no delay", 1200,800);
	cmgSumNoDelay->Update();
	mgSumNoDelay->Draw("AL");
	
	legend = new TLegend(0.6,0.78,0.99,0.99);
	legend->AddEntry(g3ChannelsSumNoDelay, "Actual sum done by the adder", "lp");
	legend->AddEntry(gAdderSum, "Sum of the adder outputs", "lp");
	legend->AddEntry(gCompSum, "Sum of the comparator outputs","lp");
	legend->Draw();
	
	mgSumNoDelay->GetXaxis()->SetTitle("Seconds");
	mgSumNoDelay->GetYaxis()->SetTitle("Volts");
	TPaveText *title = (TPaveText*)cmgSumNoDelay->GetPrimitive("title");
	title->SetX1NDC(0.009);
	title->SetY1NDC(0.94);
	title->SetX2NDC(0.56);
	title->SetY2NDC(0.99);
	cmgSumNoDelay->Modified();
*/
	
	
	// analysis for delayed adder outputs
	
	Int_t nAdderWaves = listOfAdderWaves->GetEntries();

	TGraphErrors *g3ChannelsSumDelay = listOfGraphs->FindObject("sum_output_3_channels_(1-1-1) graph");
	g3ChannelsSumDelay->SetLineColor(kRed);
	g3ChannelsSumDelay->SetLineWidth(2);

	// Delay coming from cables are written "hard coded" here
	Float_t cablesDelayArray[3] = {0,1.45E-9,3.21E-9};
	
	graphPoints = g3ChannelsSumDelay->GetN();
	//g3ChannelsSumDelay->GetPoint(0,xMin,yStart);
	//g3ChannelsSumDelay->GetPoint(graphPoints - 1,xMax,yEnd);
	xMin = 6E-9;
	xMax = 16E-9;
	step = (xMax - xMin)/graphPoints;
	cout << "Sum of the adder outputs with delay" << endl;
	cout << "xMin : " << xMin << "  xMax : " << xMax << endl;

	TGraphErrors *gAdderSumDelay = new TGraphErrors(graphPoints);
	gAdderSumDelay->SetLineColor(kBlue);
	gAdderSumDelay->SetLineWidth(2);
	gAdderSumDelay->SetName("Sum of the adder outputs with delay");
	gAdderSumDelay->SetTitle("Sum of the adder outputs with delay");

	gy = 0;
	
	// note that there is a manual correction on the delay of 500E-12 to compare the adder output better in the multigraph

	for(Int_t i = 0; i < graphPoints; i++) {
		for(Int_t j = 0; j < nAdderWaves; j++) {
			TGraphErrors *gAdderWave = (TGraphErrors *)listOfAdderWaves->At(j);
			gy += gAdderWave->Eval(xMin + i*step + cablesDelayArray[j] - 500E-12);
		} 
		gAdderSumDelay->SetPoint(i,xMin + i*step,gy);
		gy = 0;
	}

	//	TCanvas *cSumSumDelay = new TCanvas("cSumSumDelay","Sum of the sum outputs with delay",800,600);
	//	gAdderSumDelay->Draw("APEL");

	TMultiGraph *mg3ChannelsSumDelay = new TMultiGraph();
	mg3ChannelsSumDelay->Add(gAdderSumDelay);
	mg3ChannelsSumDelay->Add(g3ChannelsSumDelay);
	mg3ChannelsSumDelay->SetTitle("Collection of graphs for 3 channels sum with delay");

	TCanvas *cmg3ChannelsSumDelay = new TCanvas("cmg3ChannelsSumDelay", "Collection of graphs for 3 channels sum with delay", 1200, 800);
	cmg3ChannelsSumDelay->Update();
	
	legend = new TLegend(0.6,0.78,0.99,0.99);
	legend->AddEntry(g3ChannelsSumDelay, "Actual sum done by the adder", "lp");
	legend->AddEntry(gAdderSumDelay, "Sum of the delayed adder outputs", "lp");
	mg3ChannelsSumDelay->Draw("AL");
	legend->Draw();
	
	mg3ChannelsSumDelay->GetXaxis()->SetTitle("Seconds");
	mg3ChannelsSumDelay->GetYaxis()->SetTitle("Volts");
	
	TPaveText *title = (TPaveText*)cmg3ChannelsSumDelay->GetPrimitive("title");
	title->SetX1NDC(0.009);
	title->SetY1NDC(0.94);
	title->SetX2NDC(0.56);
	title->SetY2NDC(0.99);
	
	cmg3ChannelsSumDelay->Modified();

/*
	// delay test just to try a different method

	TMultiGraph *mgDelayTest = new TMultiGraph();
	Double_t gxTest,gyTest;

	TGraphErrors *gDelayTest0 = new TGraphErrors(((TGraphErrors *)listOfAdderWaves->At(0))->GetN());
	for(Int_t j = 0; j < gDelayTest0->GetN(); j++) {
		((TGraphErrors *)listOfAdderWaves->At(0))->GetPoint(j,gxTest,gyTest);
		gDelayTest0->SetPoint(j,gxTest - cablesDelayArray[0],gyTest);
	}
	mgDelayTest->Add(gDelayTest0);

	TGraphErrors *gDelayTest1 = new TGraphErrors(((TGraphErrors *)listOfAdderWaves->At(1))->GetN());
	for(Int_t j = 0; j < gDelayTest1->GetN(); j++) {
		((TGraphErrors *)listOfAdderWaves->At(1))->GetPoint(j,gxTest,gyTest);
		gDelayTest1->SetPoint(j,gxTest - cablesDelayArray[1],gyTest);
	}
	mgDelayTest->Add(gDelayTest1);

	TGraphErrors *gDelayTest2 = new TGraphErrors(((TGraphErrors *)listOfAdderWaves->At(2))->GetN());
	for(Int_t j = 0; j < gDelayTest2->GetN(); j++) {
		((TGraphErrors *)listOfAdderWaves->At(2))->GetPoint(j,gxTest,gyTest);
		gDelayTest2->SetPoint(j,gxTest - cablesDelayArray[2],gyTest);
	}
	mgDelayTest->Add(gDelayTest2);

//	TCanvas *cmgDelayTest = new TCanvas("cmgDelayTest", "cmgDelayTest", 800,600);
//	mgDelayTest->Draw("APEL");

	graphPoints = 12000;
	xMin = 2E-9;
	xMax = 22E-9;
	step = (xMax - xMin)/graphPoints;
	cout << "xMin : " << xMin << "  xMax : " << xMax << endl;

	Double_t delayTest0xMin,delayTest0xMax,delayTest1xMin,delayTest1xMax,delayTest2xMin,delayTest2xMax;
	gDelayTest0->GetPoint(0,delayTest0xMin,gyTest);
	gDelayTest0->GetPoint(gDelayTest0->GetN() - 1,delayTest0xMax,gyTest);
	gDelayTest1->GetPoint(0,delayTest1xMin,gyTest);
	gDelayTest1->GetPoint(gDelayTest1->GetN() - 1,delayTest1xMax,gyTest);
	gDelayTest2->GetPoint(0,delayTest2xMin,gyTest);
	gDelayTest2->GetPoint(gDelayTest2->GetN() - 1,delayTest2xMax,gyTest);

	cout << delayTest0xMin << endl;

	TGraphErrors *gAdderSumDelayV2 = new TGraphErrors(graphPoints);
	for(Int_t i = 0; i < graphPoints; i++) {
		gyTest = gDelayTest0->Eval(xMin + i*step);
		gyTest += gDelayTest1->Eval(xMin + i*step);
		gyTest += gDelayTest2->Eval(xMin + i*step);
		gAdderSumDelayV2->SetPoint(i,xMin + i*step+ 500E-12,gyTest);
	} 
	
	gAdderSumDelayV2->SetLineColor(kGreen);
	gAdderSumDelayV2->SetLineWidth(2);
	mg3ChannelsSumDelay->Add(gAdderSumDelayV2);
	c3ChannelsSumDelay->Modified();

	TCanvas *cAdderSumDelayV2 = new TCanvas("cAdderSumDelayV2","cAdderSumDelayV2",800,600);
	gAdderSumDelayV2->Draw("APL");
*/

	// List of waves representing the adder output with 5,4,3,2,1 channels in input

	TGraphErrors *gAdder5Channels = listOfGraphs->FindObject("adder output 5 channels v2 graph");
	TGraphErrors *gAdder4Channels = listOfGraphs->FindObject("adder output 4 channels v2 graph");
	TGraphErrors *gAdder3Channels = listOfGraphs->FindObject("adder output 3 channels v2 graph");
	TGraphErrors *gAdder2Channels = listOfGraphs->FindObject("adder output 2 channels v2 graph");
	TGraphErrors *gAdder1Channel = listOfGraphs->FindObject("adder output 1 channel v2 graph");
	
	TGraphErrors *gAdderSingleCh0 = listOfGraphs->FindObject("single sum output ch 0 input 500 mV DT 100 mV graph");
	TGraphErrors *gAdderSingleCh1 = listOfGraphs->FindObject("single sum output ch 1 input 500 mV DT 100 mV graph");
	TGraphErrors *gAdderSingleCh4 = listOfGraphs->FindObject("single sum output ch 4 input 500 mV DT 100 mV graph");
	TGraphErrors *gAdderSingleCh5 = listOfGraphs->FindObject("single sum output ch 5 input 500 mV DT 100 mV graph");
	TGraphErrors *gAdderSingleCh7 = listOfGraphs->FindObject("single sum output ch 7 input 500 mV DT 100 mV graph");
	
	TMultiGraph *mgAdder54321Channels = new TMultiGraph();
	mgAdder54321Channels->SetTitle("Collection of graphs for different numbers of added channels");
	mgAdder54321Channels->Add(gAdder5Channels);
	mgAdder54321Channels->Add(gAdder4Channels);
	mgAdder54321Channels->Add(gAdder3Channels);
	mgAdder54321Channels->Add(gAdder2Channels);
	mgAdder54321Channels->Add(gAdder1Channel);
	
	TCanvas *cmgAdder54321Channels = new TCanvas("cmgAdder54321Channels", "Collection of graphs for different numbers of added channels",1200,800);
	mgAdder54321Channels->Draw("AL");
	cmgAdder54321Channels->Update();
	mgAdder54321Channels->GetXaxis()->SetTitle("seconds");
	mgAdder54321Channels->GetYaxis()->SetTitle("Volts");	
	cmgAdder54321Channels->Modified();
	
	// analysis of the linearity of the adder
	
	Double_t addedVMax[nAddedChannels];
	addedVMax[0] = TMath::MaxElement(gAdder1Channel->GetN(), gAdder1Channel->GetY());
	addedVMax[1] = TMath::MaxElement(gAdder2Channels->GetN(), gAdder2Channels->GetY());
	addedVMax[2] = TMath::MaxElement(gAdder3Channels->GetN(), gAdder3Channels->GetY());
	addedVMax[3] = TMath::MaxElement(gAdder4Channels->GetN(), gAdder4Channels->GetY());
	addedVMax[4] = TMath::MaxElement(gAdder5Channels->GetN(), gAdder5Channels->GetY());
	
	Double_t singleVMax[nAddedChannels];
	singleVMax[0] = TMath::MaxElement(gAdderSingleCh0->GetN(), gAdderSingleCh0->GetY());
	singleVMax[1] = TMath::MaxElement(gAdderSingleCh1->GetN(), gAdderSingleCh1->GetY());
	singleVMax[2] = TMath::MaxElement(gAdderSingleCh4->GetN(), gAdderSingleCh4->GetY());
	singleVMax[3] = TMath::MaxElement(gAdderSingleCh5->GetN(), gAdderSingleCh5->GetY());
	singleVMax[4] = TMath::MaxElement(gAdderSingleCh7->GetN(), gAdderSingleCh7->GetY());
	
	vector<double> expectedVMax(nAddedChannels);
	Double_t previousVmax = 0;
	for(Int_t i = 0; i < expectedVMax.size(); i++) {
		expectedVMax[i] = singleVMax[i] + previousVmax;
		previousVmax = expectedVMax[i];
		cout << "singleVMax[" <<i <<"] = " << singleVMax[i] <<  endl;
		cout << "addedVMax[" <<i <<"] = " << addedVMax[i] <<  endl;
		cout << "expectedVMax[" <<i <<"] = " << expectedVMax[i] <<  endl;
	}
	
	TGraph *gAdderLinearity = new TGraph(expectedVMax.size(),&expectedVMax[0],addedVMax);
	gAdderLinearity->SetTitle("Linearity of the adder");
	gAdderLinearity->GetXaxis()->SetTitle("Expected amplitude value (V)");
	gAdderLinearity->GetYaxis()->SetTitle("Actual amplitude value (V)");
	gAdderLinearity->GetYaxis()->SetTitleOffset(1.3);
	
	TCanvas *cgAdderLinearity = new TCanvas("cgAdderLinearity","Linearity of the adder",800,600);
	cgAdderLinearity->SetGrid();
	cgAdderLinearity->Update();
	gAdderLinearity->SetMarkerStyle(20);
	gAdderLinearity->SetMarkerSize(0.8);
	//gAdderLinearity->Fit("pol1","Q+","",expectedVMax[0],expectedVMax[2]);
	TF1 *line = new TF1("line","x",expectedVMax.back(),expectedVMax.front());
	gAdderLinearity->Draw("APEL");
	line->Draw("SAME");
	//gAdderLinearity->GetFunction("pol1")->SetRange(expectedVMax.back(),expectedVMax.front());;
	cgAdderLinearity->SetLeftMargin(0.13);
	cgAdderLinearity->Modified();
	
	f->Close();


}
int evaluate( std::string filelist, std::string outfile )
{
  gStyle->SetOptStat(0);

  TCanvas *ctemp = new TCanvas();

  TCanvas *cres = new TCanvas("TimeDependence");
  TH1F* hres = new TH1F("hres","",100,0,650);
  hres->GetYaxis()->SetRangeUser(0,50);
  hres->SetTitle("");
  hres->GetXaxis()->SetTitle("time (s)");
  hres->GetYaxis()->SetTitle("B_{int} (mT)");
  hres->Draw();
  leg = new TLegend(0.2,0.6,0.9,0.9);
//  leg->SetHeader("The Legend Title"); // option "C" allows to center the header
  leg->SetNColumns(5);

  vector< double > v_Bint;
  vector< double > v_BintErr;
  vector< double > v_Bext;
  vector< double > v_BextErr;

  /* Loop over all lines in input file */
  std::ifstream infilelist(filelist);
  std::string line;

  unsigned colorcounter=38;

  while (std::getline(infilelist, line))
  {
    // skip lines with '#' and empty lines
    if ( line.find("#") != string::npos )
      {
        cout << "Skip line " << line << endl;
        continue;
      }

    if ( line == "" )
      continue;

    //cout << "Processing file " << line << endl;


    TString infilename("data_calib/");
    infilename.Append(line);

    TFile *fin = new TFile( infilename );
    TTree *tin = (TTree*)fin->Get("t");

    ctemp->cd();
    tin->Draw("Bi:time");
    TGraph *gtime = new TGraph(tin->GetEntries(), &(tin->GetV2()[0]), &(tin->GetV1()[0]));
    gtime->SetLineColor(colorcounter);
    colorcounter++;

    TH1F* hBext = new TH1F("hBext","",100,0,1000);
    tin->Draw("Bo >> hBext");

    cres->cd();
    gtime->Draw("lsame");

    double Bext_i = hBext->GetMean();
    double BextErr_i = hBext->GetRMS();

    double Bint_i = gtime->Eval(590);
    double BintErr_i = 0;

    /* add legend entry */
    TString legname("B_ext ~ ");
    legname += (int)Bext_i;
    leg->AddEntry(gtime,legname,"l");

    cout << "B_ext: " << Bext_i << " \t B_int: " << Bint_i << endl;

    v_Bint.push_back(Bint_i);
    v_BintErr.push_back(BintErr_i);
    v_Bext.push_back(Bext_i);
    v_BextErr.push_back(BextErr_i);

  }

  cres->cd();
  leg->Draw();

  TGraphErrors *gfinal = new TGraphErrors(v_Bext.size(), &(v_Bext[0]), &(v_Bint[0]), &(v_BextErr[0]), &(v_BintErr[0]));
  gfinal->Sort();
  gfinal->SetName("Bint_Vs_Bext");
  gfinal->SetTitle("");
  gfinal->GetXaxis()->SetTitle("B_{ext} (mT)");
  gfinal->GetYaxis()->SetTitle("B_{int} (mT)");

  TCanvas *cfinal = new TCanvas();
  gfinal->Draw("APL");

  /* Save output graph */
  TString outfilename("output/");
  outfilename.Append(outfile);
  TFile *fout = new TFile(outfilename,"RECREATE");

  cres->Write();
  gfinal->Write();

  fout->Close();

  /* Write result to txt output file */
  TString outfilenametxt = outfilename;
  outfilenametxt.ReplaceAll(".root",".txt");

  ofstream foutxt;
  foutxt.open( outfilenametxt );
  foutxt <<  "# Bo sig_Bo Bi sig_Bi shield sig_shield sf sig_sf time_dependent" << endl;

  for ( int i = 0; i < gfinal->GetN(); i++ )
  {
    double Bo = gfinal->GetX()[i];
    double sig_Bo = gfinal->GetEX()[i];
    double Bi = gfinal->GetY()[i];
    double sig_Bi = gfinal->GetEY()[i];
    double shield = 0;
    double sig_shield = 0;
    double sf = 0;
    double sig_sf = 0;
    double time_dependent = 0;

    foutxt <<  Bo << " " << sig_Bo << " " << Bi << " " << sig_Bi << " "
         << shield << " " << sig_shield << " " << sf << " " << sig_sf
         << " " << time_dependent << endl;
  }

  return 0;
}
Exemple #18
0
void pointsed(TString filename = "btagpatanalyzerpy.root", TString check="") {
	TString cmssw;
	// 167
	
	cmssw = "$3.1.0_pre9$";
	
	TFile *f = TFile::Open(filename);
/////////////////////////////////////////////////////////////////////////////////////////
	std::vector< TString > checks;
	checks.push_back("");
	checks.push_back("Corr30_");
	checks.push_back("Corr30t0_");
	checks.push_back("Corr30t1_");
	checks.push_back("Corr30t2_");
	checks.push_back("Corr30t0_nConstituent_");
	checks.push_back("Corr30t1_nConstituent_");
	checks.push_back("Corr30t2_nConstituent_");
	checks.push_back("Uncor10_");
	checks.push_back("Uncor10t0_");
	checks.push_back("Uncor10t1_");
	checks.push_back("Uncor10t2_");
	checks.push_back("Uncor10t0_nConstituent_");
	checks.push_back("Uncor10t1_nConstituent_");
	checks.push_back("Uncor10t2_nConstituent_");
/////////////////////////////////////////////////////////////////////////////////////////
	std::vector< TString > taggers;
	std::vector< TString > labeltag;
        std::vector< int> colorlines;
	taggers.push_back( "TC2" );colorlines.push_back( 1 );labeltag.push_back( "TCHE");
	taggers.push_back( "TC3" );colorlines.push_back( 2 );labeltag.push_back( "TCHP");
	taggers.push_back( "TP"  );colorlines.push_back( 3 );labeltag.push_back( "JP");
	taggers.push_back( "SSV" );colorlines.push_back( 4 );labeltag.push_back( "SSV");
	taggers.push_back( "CSV" );colorlines.push_back( 5 );labeltag.push_back( "CSV");
	taggers.push_back( "MSV" );colorlines.push_back( 6 );labeltag.push_back( "CSVMVAB");
	taggers.push_back( "SMT" );colorlines.push_back( 8 );labeltag.push_back( "SMT");
	taggers.push_back( "BTP" );colorlines.push_back( 9 );labeltag.push_back( "JBP");
	taggers.push_back( "SMTbyIP3d" );colorlines.push_back( 11 );labeltag.push_back( "SMTByIP3d");
	taggers.push_back( "SMTbyPt" );colorlines.push_back( 12 );labeltag.push_back( "SMTByPt");
	taggers.push_back( "SETbyIP3d" );colorlines.push_back( 13 );labeltag.push_back( "SETByIP3d");
	taggers.push_back( "SETbyPt" );colorlines.push_back( 14 );labeltag.push_back( "SETByPt");
//	taggers.push_back( "IPM" );colorlines.push_back( 11 );labeltag.push_back( "IPMVAB");
//	taggers.push_back( "SMNIPT" );colorlines.push_back( 12 );labeltag.push_back( "SMTNoIP");

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
//ed	for ( size_t ichks = 0; ichks < checks.size(); ++ichks ) {
//ed		TString check = checks[ichks];
	
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
        TString PerfTitle= check;
        if (check == "") PerfTitle="uncorr pt>30";
	if (check == "Corr30_") PerfTitle="pt>30";
	if (check == "Corr30t0_") PerfTitle="pt>30, #tracks > 0";
	if (check == "Corr30t1_") PerfTitle="pt>30, #tracks > 1";
	if (check == "Corr30t2_") PerfTitle="pt>30, #tracks > 2";
	if (check == "Corr30t0_nConstituent_") PerfTitle="pt>30, #tracks > 0 & nConstituents >1";
	if (check == "Corr30t1_nConstituent_") PerfTitle="pt>30, #tracks > 1 & nConstituents >1";
	if (check == "Corr30t2_nConstituent_") PerfTitle="pt>30, #tracks > 2 & nConstituents >1";
	if (check == "Uncor10_") PerfTitle="uncorr pt>10";
	if (check == "Uncor10t0_") PerfTitle="uncorr pt>10 #tracks > 0";
	if (check == "Uncor10t1_") PerfTitle="uncorr pt>10 #tracks > 1";
	if (check == "Uncor10t2_") PerfTitle="uncorr pt>10 #tracks > 2";
	if (check == "Uncor10t0_nConstituent_") PerfTitle="uncorr pt>10 #tracks > 0 & nConstituents >1";
	if (check == "Uncor10t1_nConstituent_") PerfTitle="uncorr pt>10 #tracks > 1 & nConstituents >1";
	if (check == "Uncor10t2_nConstituent_") PerfTitle="uncorr pt>10 #tracks > 2 & nConstituents >1";

	std::vector< TString > discriminators;
        for ( size_t itagger = 0; itagger < taggers.size(); ++itagger ) {
  		discriminators.push_back( check+"disc"+taggers[itagger]+"_udsg" );
	}
//	discriminators.push_back( "discTC3_udsg" );
//	discriminators.push_back( "discTP_udsg" );

	TCanvas *cv = new TCanvas("cv","cv",900,900);
	TMultiGraph *mg =new TMultiGraph();
	TLegend *legend0 = new TLegend(0.68,0.12,0.88,0.32);
        // inverted axis
	TMultiGraph *mginv =new TMultiGraph();
	TLegend *legend1 = new TLegend(0.65,0.18,0.85,0.48);
	std::ofstream salida("BTagPATop3"+check+".txt");
	
	for ( size_t itagger = 0; itagger < taggers.size(); ++itagger ) {

		TString tag    = check+"g"+taggers[itagger]+"_udsg";
		TGraphErrors *agraph = (TGraphErrors*) gDirectory->Get("BTagPATAnalyzer"+taggers[itagger]+"/"+taggers[itagger]+"/"+tag);

		
		TGraph *dgraph = (TGraph*) gDirectory->Get("BTagPATAnalyzer"+taggers[itagger]+"/"+taggers[itagger]+"/"+discriminators[itagger]);
//		TGraph *udsgvsdgraph = new TGraph(dgraph->GetN(),dgraph->GetY(),dgraph->GetX());
		dgraph->Sort();
//		udsgvsdgraph->Sort();

		TGraphErrors *g = new TGraphErrors(agraph->GetN(),agraph->GetY(),agraph->GetX(),agraph->GetEY(),agraph->GetEX());
		g->Sort();
		g->SetLineColor(itagger+1);
                legend0 -> AddEntry(g,taggers[itagger],"l");
		mg->Add(g);

                //inverted axis
		TGraphErrors *ginv = new TGraphErrors(agraph->GetN(),agraph->GetX(),agraph->GetY(),agraph->GetEX(),agraph->GetEY());
		ginv->Sort();
		ginv->SetLineColor(colorlines[itagger]);
		ginv->SetMarkerStyle(8);
		ginv->SetMarkerColor(colorlines[itagger]);
                legend1 -> AddEntry(ginv,labeltag[itagger],"l");
		mginv->Add(ginv);

		std::cout << " Tagger: " << tag << std::endl;
		std::cout << " Loose(10%): " << " cut > " << std::setprecision(4) << dgraph->Eval(0.1) << " b-eff = " << g->Eval(0.1) << std::endl;
		std::cout << " Medium(1%):  " << " cut > " << std::setprecision(4) << dgraph->Eval(0.01) << " b-eff = " << g->Eval(0.01) << std::endl;
		std::cout << " Tight(0.1%) = " << " cut > " << std::setprecision(4) << dgraph->Eval(0.001) << " b-eff = " << g->Eval(0.001) << std::endl;
                salida << " " << taggers[itagger] << endl;
	        salida << " #bin \t b-eff  \t err-beff \t  non-beff \t err-non-b"<< endl;
        	for ( size_t i=0;i< agraph->GetN();i++){ 
			salida	<< "  " << (i+1) << " \t "
				<< agraph->GetX()[i] <<" \t " 
				<< agraph->GetEX()[i]<<" \t "
				<< agraph->GetY()[i] <<" \t "
				<< agraph->GetEY()[i]
                       		<< " "<< endl;
		}

	}
//	cv->SetLogx();
	mg->Draw("ALP");
	mg->GetYaxis()->SetTitle("b-eff");
	mg->GetXaxis()->SetTitle("udsg-mistagging");
	legend0 -> Draw();
        cv-> SetGrid();
	cv-> Print ("BTagPATop"+check+".eps");
	cv-> Print ("BTagPATop"+check+".png");
	cv->cd(0);
	cv->SetLogx();
	mg->Draw("ALP");
	legend0 -> Draw();
	cv-> Print ("BTagPATop1"+check+".eps");
	cv-> Print ("BTagPATop1"+check+".png");
        //inverted axis
	TCanvas *cvinv = new TCanvas("cvinv","cvinv",700,700);
        cvinv->SetLogy(0);
	mginv->Draw("ALP");
	mginv->GetXaxis()->SetTitle("b-eff");
	mginv->GetYaxis()->SetTitle("udsg-mistagging");
	legend1 -> Draw();
        cvinv->SetGrid();
	cvinv-> Print ("BTagPATop2"+check+".eps");
	cvinv-> Print ("BTagPATop2"+check+".png");
	cvinv->cd(0);
//	cvinv->Update();
//	cvinv->SetLogx();
//	mginv->SetXmin(10^-4);
//      axis range using a histogram helper
    TH2D*hpx = new TH2D("hpx",PerfTitle,200,0.0,1.005,200,0.00002,1.05);
        hpx->SetStats(kFALSE);
		hpx->Draw();
	hpx->GetXaxis()->SetTitle("b-eff");
	hpx->GetYaxis()->SetTitle("udsg-mistagging");
	cvinv->SetLogy(1);
	mginv->Draw("AP");
	legend1 -> Draw();
	cvinv-> Print ("BTagPATop3"+check+".eps");
	cvinv-> Print ("BTagPATop3"+check+".png");
	//ed}
}
Exemple #19
0
void theoryBin(TDirectory *din, TDirectory *dth, TDirectory *dout) {

  float etamin, etamax;
  assert(sscanf(din->GetName(),"Eta_%f-%f",&etamin,&etamax)==2);
  sscanf(din->GetName(),"Eta_%f-%f",&etamin,&etamax);
  int ieta = int((0.5*(etamin+etamax))/0.5);
  int jeta = (_jp_algo=="AK7" ? min(4,ieta) : ieta);

  // inclusive jets
  TH1D *hpt = (TH1D*)din->Get("hpt"); assert(hpt);

  // theory curves
  // http://www-ekp.physik.uni-karlsruhe.de/~rabbertz/fastNLO_LHC/InclusiveJets/
  // -> fnl2342_cteq66_aspdf_full.root
  // Numbering scheme explained in
  // https://twiki.cern.ch/twiki/bin/view/CMS/CMSfastNLO
  // 2-point to 6-point theory uncertainty:
  // h200X00->h300X09, h400X00->h300X08
  TH1D *hnlo(0);//, *hpdfup(0), *hpdfdw(0), *hscup(0), *hscdw(0);//, *herr(0);

  cout << din->GetName() << " ieta="<<ieta<< " jeta="<<jeta << endl;

  TH1D *hmc = (TH1D*)dth->Get("hpt_g0tw");
  assert(hmc);
  
  /*
  int S = (_jp_algo=="AK7" ? 1 : 3);
  TH1D *hnlo_cteq = (TH1D*)dnlo0->Get(Form("h%d00%d00",S,jeta+1));
  assert(hnlo_cteq);

  hnlo_cteq->Scale(1000.);

  // CTEQ10
  TH1D *hnlo_ct10 = (TH1D*)dnlo1->Get(Form("h300%d00",jeta+1));
  TH1D *hpdfup_ct10 = (TH1D*)dnlo1->Get(Form("h300%d02",jeta+1));
  TH1D *hpdfdw_ct10 = (TH1D*)dnlo1->Get(Form("h300%d01",jeta+1));
  TH1D *hscup_ct10 = (TH1D*)dnlo1->Get(Form("h300%d09",jeta+1));
  TH1D *hscdw_ct10 = (TH1D*)dnlo1->Get(Form("h300%d08",jeta+1));
  assert(hnlo_ct10); assert(hpdfup_ct10); assert(hpdfdw_ct10);
  assert(hscup_ct10); assert(hscdw_ct10);

  hnlo_ct10->Scale(1000.);
  hpdfup_ct10->Scale(1./1.65);
  hpdfdw_ct10->Scale(1./1.65);

  // MSTW2008
  TH1D *hnlo_mstw = (TH1D*)dnlo2->Get(Form("h%d00%d00",S,jeta+1));
  assert(hnlo_mstw);

  hnlo_mstw->Scale(1000.);

  // NNPDF2010
  TH1D *hnlo_nnpdf = (TH1D*)dnlo3->Get(Form("h%d00%d00",S,jeta+1));
  assert(hnlo_nnpdf);

  hnlo_nnpdf->Scale(1000.);

  // HERA10
  TH1D *hnlo_hera = (TH1D*)dnlo4->Get(Form("h%d00%d00",S,jeta+1));
  TH1D *hpdfup_hera = (TH1D*)dnlo4->Get(Form("h%d00%d02",S,jeta+1));
  TH1D *hpdfdw_hera = (TH1D*)dnlo4->Get(Form("h%d00%d01",S,jeta+1));
  assert(hnlo_hera); assert(hpdfup_hera); assert(hpdfdw_hera);

  hnlo_hera->Scale(1000.);

  // alpha-S
  TH1D *hasup = (TH1D*)das->Get(Form("h300%d02",ieta+1));
  TH1D *hasdw = (TH1D*)das->Get(Form("h300%d01",ieta+1));
  assert(hasup); assert(hasdw);

  TH1D *hnp = (TH1D*)dnp->Get(Form("corr%d",min(int(etamin/0.5+0.5),5)));

  if (!hnp) cout << "eta: " << etamin << " " << etamax << endl;
  assert(hnp);
  */


  // make sure new histograms get created in the output file
  dout->cd();

  /*
  TH1D *hnpup(0), *hnpdw(0), *hsysup(0), *hsysdw(0);
  {
    // Move CTEQ6.6
    hnlo_cteq = (TH1D*)hnlo_cteq->Clone("hnlo0_ct10k");
    hnlo_ct10 = (TH1D*)hnlo_ct10->Clone("hnlo0_ct10");
    hnlo_mstw = (TH1D*)hnlo_mstw->Clone("hnlo0_mstw");
    hnlo_nnpdf = (TH1D*)hnlo_nnpdf->Clone("hnlo0_nnpdf");
    hnlo_hera = (TH1D*)hnlo_hera->Clone("hnlo0_hera");
    
    // Determine PDF4LHC from CT10, MSTW08, NNPDF10
    hnlo = (TH1D*)hnlo_ct10->Clone("hnlo0"); // central PDF again later
    hpdfup = (TH1D*)hpdfup_ct10->Clone("hpdfup"); // central PDF
    hpdfdw = (TH1D*)hpdfdw_ct10->Clone("hpdfdw"); // central PDF
    for (int i = 1; i != hnlo->GetNbinsX()+1; ++i) {
      
      // Sanity checks
      assert(hpdfup_ct10->GetBinContent(i)>=0);
      assert(hpdfdw_ct10->GetBinContent(i)<=0);
    }
    hscup = (TH1D*)hscup_ct10->Clone("hscup"); // central PDF
    hscdw = (TH1D*)hscdw_ct10->Clone("hscdw"); // central PDF
    hasup = (TH1D*)hasup->Clone("hasup");
    hasdw = (TH1D*)hasdw->Clone("hasdw");
    
    hnp = (TH1D*)hnp->Clone("hnpcorr");
    
    hnpup = (TH1D*)hnlo->Clone("hnpup");
    hnpdw = (TH1D*)hnlo->Clone("hnpdw");
    
    hsysup = (TH1D*)hnlo->Clone("hsysup");
    hsysdw = (TH1D*)hnlo->Clone("hsysdw");
  }
  */

  /*
  // Patch up the hnp to adapt the wrong binning at low pT
  if (true) { // patch hnp

    TH1D *hnp_tmp = (TH1D*)hnlo->Clone("hnp_tmp");
    for (int i = 1; i != hnlo->GetNbinsX()+1; ++i) {

      double x = hnlo->GetBinCenter(i);
      int j1 = hnp->FindBin(x);
      double x1 = hnp->GetBinCenter(j1);
      double y1 = hnp->GetBinContent(j1);
      double ey1 = hnp->GetBinError(j1);
      int j2 = (x>x1? j1+1 : j1-1);
      double x2 = hnp->GetBinCenter(j2);
      double y2 = hnp->GetBinContent(j2);
      double ey2 = hnp->GetBinError(j2);
      double y = y1 + (y2-y1) / (x2-x1) * (x-x1);
      double ey = ey1 + (ey2-ey1) / (x2-x1) * (x-x1);
      hnp_tmp->SetBinContent(i, y); 
      hnp_tmp->SetBinError(i, ey); 
    } // for i
    delete hnp;
    hnp = hnp_tmp;
    hnp->SetName("hnpcorr");
  } // patch hnp
  */

  /*
  // Turn NP uncertainty into uncertainty histogram
  for (int i = 1; i != hnlo->GetNbinsX()+1; ++i) {

    int j = hnp->FindBin(hnlo->GetBinCenter(i));
    hnpup->SetBinContent(i, +hnp->GetBinError(j)/hnp->GetBinContent(j));
    hnpup->SetBinError(i, 0.);
    hnpdw->SetBinContent(i, -hnp->GetBinError(j)/hnp->GetBinContent(j));
    hnpdw->SetBinError(i, 0.);
    if (!(hnp->GetBinLowEdge(j)>=hnlo->GetBinLowEdge(i)) ||
	!(hnp->GetBinLowEdge(j+1)<=hnlo->GetBinLowEdge(i+1))) {
      cout << Form("hnlo = [%1.0f,%1.0f]; hnp = [%1.0f,%1.0f]",
		   hnlo->GetBinLowEdge(i), hnlo->GetBinLowEdge(i+1),
		   hnp->GetBinLowEdge(j), hnp->GetBinLowEdge(j+1)) << endl;
      if (hnlo->GetBinLowEdge(i)>100 && hnlo->GetBinLowEdge(i)<2500.) {
	assert(hnp->GetBinLowEdge(j)>=hnlo->GetBinLowEdge(i));
	assert(hnp->GetBinLowEdge(j+1)<=hnlo->GetBinLowEdge(i+1));
      }
    }
  } // for i
  */

  /*
  for (int i = 1; i != hnlo->GetNbinsX()+1; ++i) {

    double x = hnlo->GetBinCenter(i);
    int i1 = hnpup->FindBin(x);
    double y1a = hnpup->GetBinContent(i1);
    double y1b = hnpdw->GetBinContent(i1);
    int i2 = hscup->FindBin(x);
    double y2a = hscup->GetBinContent(i2);
    double y2b = hscdw->GetBinContent(i2);
    int i3 = hpdfup->FindBin(x);
    double y3a = hpdfup->GetBinContent(i3);
    double y3b = hpdfdw->GetBinContent(i3);
    int i4 = hasup->FindBin(x);
    double y4a = hasup->GetBinContent(i4);
    double y4b = hasdw->GetBinContent(i4);
    double errup = sqrt(pow(max3(y1a,y1b,0),2) + pow(max3(y2a,y2b,0),2)
			+ pow(max3(y3a,y3b,0),2) + pow(max3(y4a,y4b,0),2));
    double errdw = sqrt(pow(min3(y1a,y1b,0),2) + pow(min3(y2a,y2b,0),2)
			+ pow(min3(y3a,y3b,0),2) + pow(min3(y4a,y4b,0),2));
    hsysup->SetBinContent(i, errup);
    hsysup->SetBinError(i, 0.);
    hpdfup->SetBinError(i, 0.);
    hscup->SetBinError(i, 0.);
    hasup->SetBinError(i, 0);
    hsysdw->SetBinContent(i, -errdw);
    hsysdw->SetBinError(i, 0.);
    hpdfdw->SetBinError(i, 0.);
    hscdw->SetBinError(i, 0.);
    hasdw->SetBinError(i, 0);
  } // for i
  */

  /*
  for (int i = 1; i != hnlo_ct10->GetNbinsX()+1; ++i) {

    double x = hnlo_ct10->GetBinCenter(i);
    int jnp = hnp->FindBin(x);
    double np = hnp->GetBinContent(jnp);
    int j = hnlo_ct10->FindBin(x);
    hnlo->SetBinContent(j, 1e-3*hnlo->GetBinContent(j)*np);
    int jc = hnlo_ct10->FindBin(x);
    hnlo_ct10->SetBinContent(jc, 1e-3*hnlo_ct10->GetBinContent(jc)*np);
    int jk = hnlo_cteq->FindBin(x);
    hnlo_cteq->SetBinContent(jk, 1e-3*hnlo_cteq->GetBinContent(jk)*np);
    int jm = hnlo_mstw->FindBin(x);
    hnlo_mstw->SetBinContent(jm, 1e-3*hnlo_mstw->GetBinContent(jm)*np);
    int jn = hnlo_nnpdf->FindBin(x);
    hnlo_nnpdf->SetBinContent(jn, 1e-3*hnlo_nnpdf->GetBinContent(jn)*np);
    int jh = hnlo_hera->FindBin(x);
    hnlo_hera->SetBinContent(jh, 1e-3*hnlo_hera->GetBinContent(jh)*np);
    //
    hnlo->SetBinError(j, 0.);
    hnlo_ct10->SetBinError(jc, 0.);
    hnlo_cteq->SetBinError(jk, 0.);
    hnlo_mstw->SetBinError(jm, 0.);
    hnlo_nnpdf->SetBinError(jn, 0.);
    hnlo_hera->SetBinError(jh, 0.);
  }
  */

  // initial fit of the NLO curve
  TF1 *fnlo = new TF1("fnlo",
		      "[0]*exp([1]/x)*pow(x,[2])"
		      "*pow(1-x*cosh([4])/3500.,[3])", 10., 1000.);
  fnlo->SetParameters(2e14,-18,-5.2,8.9,0.5*ieta);
  fnlo->FixParameter(4,0.5*ieta);

  hnlo = hmc;
  hnlo->Fit(fnlo,"QRN");
  
  // Graph of theory points with centered bins
  const double minerr = 0.02;
  TGraphErrors *gnlo = new TGraphErrors(0);
  TGraphErrors *gnlo2 = new TGraphErrors(0); // above + minerr
  TGraphErrors *gnlocut = new TGraphErrors(0); // only up to expected pT
  gnlo->SetName("gnlo");
  gnlo2->SetName("gnlo2");
  gnlocut->SetName("gnlocut");
  for (int i = 1; i != hnlo->GetNbinsX()+1; ++i) {

    double y = hnlo->GetBinContent(i);
    double dy = hnlo->GetBinError(i);
    double ptmin = hnlo->GetBinLowEdge(i);
    double ptmax = hnlo->GetBinLowEdge(i+1);

    double y0 = fnlo->Integral(ptmin, ptmax) / (ptmax - ptmin);
    double x = fnlo->GetX(y0, ptmin, ptmax);

    int n = gnlo->GetN();
    tools::SetPoint(gnlo, n, x, y, 0, dy);
    tools::SetPoint(gnlo2, n, x, y, 0, tools::oplus(dy, minerr*y));
    if (y*(ptmax-ptmin) > 0.0001) { // for 10/fb
      int m = gnlocut->GetN();
      tools::SetPoint(gnlocut, m, x, y, 0, 0);
    }
  }

  gnlo2->Fit(fnlo,"QRN");

  // Divide graph with fit to check stability
  TGraphErrors *gnlofit = new TGraphErrors(0);
  gnlofit->SetName("gnlofit");
  for (int i = 0; i != gnlo->GetN(); ++i) {
    
    double x, y, ex, ey;
    tools::GetPoint(gnlo, i, x, y, ex, ey);
    double f = fnlo->Eval(x);
    tools::SetPoint(gnlofit, i, x, y/f, ex, ey/f);
  }

  // Rebin theory to match data bins
  TH1D *hnlo0 = hnlo;
  hnlo0->SetName("hnlo0");
  hnlo = tools::Rebin(hnlo0, hpt);
  hnlo->SetName("hnlo");

  // Same for earlier 2010 and 2011 studies to get a matching theory set
  // (moved from PDF4LHC to CT10 since 2010)
  if (false) {

    // Match this to drawSummary.C inputs
    TDirectory *curdir = gDirectory;
    TFile *fin2010 = new TFile("../pfjet/output-DATA-4c.root","READ");
    assert(fin2010 && !fin2010->IsZombie());
    assert(fin2010->cd("Standard"));
    fin2010->cd("Standard");
    assert(gDirectory->cd(din->GetName()));
    gDirectory->cd(din->GetName());
    TDirectory *din2010 = gDirectory;
    TH1D *hpt2010 = (TH1D*)din2010->Get("hpt");
    curdir->cd();
    TH1D *hnlo2010 = tools::Rebin(hnlo0, hpt2010);
    hnlo2010->SetName("hnlo2010");
    hnlo2010->Write();
  }
  if (false) {
    // Match this to drawSummary.C inputs
    TDirectory *curdir = gDirectory;
    TFile *fin2011 = new TFile("backup/oct26/output-DATA-4c.root","READ");
    assert(fin2011 && !fin2011->IsZombie());
    assert(fin2011->cd("Standard"));
    fin2011->cd("Standard");
    assert(gDirectory->cd(din->GetName()));
    gDirectory->cd(din->GetName());
    TDirectory *din2011 = gDirectory;
    TH1D *hpt2011 = (TH1D*)din2011->Get("hpt");
    curdir->cd();
    TH1D *hnlo2011 = tools::Rebin(hnlo0, hpt2011);
    hnlo2011->SetName("hnlo2011");
    hnlo2011->Write();
  }

  /*
  {
    TH1D *hnlo0_cteq = hnlo_cteq;
    hnlo0_cteq->SetName("hnlo0_ct10k");
    hnlo_cteq = tools::Rebin(hnlo0_cteq, hpt);
    hnlo_cteq->SetName("hnlo_ct10k");
    //
    TH1D *hnlo0_ct10 = hnlo_ct10;
    hnlo0_ct10->SetName("hnlo0_ct10");
    hnlo_ct10 = tools::Rebin(hnlo0_ct10, hpt);
    hnlo_ct10->SetName("hnlo_ct10");
    //
    TH1D *hnlo0_mstw = hnlo_mstw;
    hnlo0_mstw->SetName("hnlo0_mstw");
    hnlo_mstw = tools::Rebin(hnlo0_mstw, hpt);
    hnlo_mstw->SetName("hnlo_mstw");
    //
    TH1D *hnlo0_nnpdf = hnlo_nnpdf;
    hnlo0_nnpdf->SetName("hnlo0_nnpdf");
    hnlo_nnpdf = tools::Rebin(hnlo0_nnpdf, hpt);
    hnlo_nnpdf->SetName("hnlo_nnpdf");
    //
    TH1D *hnlo0_hera = hnlo_hera;
    hnlo0_hera->SetName("hnlo0_hera");
    hnlo_hera = tools::Rebin(hnlo0_hera, hpt);
    hnlo_hera->SetName("hnlo_hera");
  }
  */

  dout->cd();
  gnlo->Write();
  gnlocut->Write();
  gnlofit->Write();
  fnlo->Write();

  din->cd();
} // theoryBin
double FitCurve(TGraphErrors* g, int debug=0)
{
  
  double vdep=0;
  if(!g) return vdep;
  
  
  TF1* f3 = new TF1("fp1", "pol1", 20, 360);
  f3->SetLineColor(4);
  
  double y;
  double xlow=350;
  double ymax=0;
  double vdep1=0;
  // prendre le point le plus haut est robuste et marche bien pour les hauts vdep
  TGraphErrors *gsmooth = MedianFilter(g);
  gsmooth = MedianFilter(gsmooth);
  for(int ipt=0; ipt<gsmooth->GetN(); ipt++)
  {
    gsmooth->GetPoint(ipt, xlow, y);
	if(y>ymax) {ymax=y; vdep1=xlow;}
  }
  
  //g=gsmooth;
  int npt = g->GetN()-5;
  xlow=350;
  double chi2=0;
  int status = 0;
  while(chi2<5. && xlow>100 && npt>=0)
  {
    g->GetPoint(npt, xlow, y);
    f3->SetRange(xlow, 350);
    status = g->Fit("fp1", "rqn");
    chi2 = f3->GetChisquare()/f3->GetNDF();
    if(debug>=1) cout<<"xlow "<<xlow<<" chi2 "<<chi2<<endl;
	npt--;
  }
  g->GetPoint(npt+2, xlow, y);
  f3->SetRange(xlow, 350);
  g->Fit("fp1", "rqn");
  vdep = xlow;
  
  //if(vdep>230) vdep = vdep1;
  //else if(fabs(vdep-vdep1)>40) vdep = vdep1;
  //vdep=vdep1;

  cout<<" Vdepl = "<<vdep<<endl;
  
  
  
  TF1* f1 = new TF1("fitsigmo", fitsigmo, 50, 350, 5);
  f1->SetParameter(0, 3.);
  f1->SetParameter(1, 0.02);
  f1->SetParameter(2, vdep);
  f1->SetParameter(3, -10.);
  f1->SetParameter(4, -0.00001);
  f1->SetParLimits(2, 100., 300.);
  f1->SetParLimits(4, -0.1, 0);
  
  
  
  
  TF1* f2 = new TF1("fitpol", fitpol, 20, 360, 6);
  f2->SetParLimits(4, 100., 300.);
  f2->SetParLimits(5, -0.1, 0);
  
 /* xlow = 30;
  chi2 = 100;
  double xmin = xlow;
  double chi2min = chi2;
  string opt="rq";
  if(debug>=2) opt="r";
  while(chi2>0.1 && xlow<vdep-80)
  {
    f2->SetParameter(0, 1.);
    f2->SetParameter(1, 0.005);
    f2->SetParameter(2, 0.0001);
    f2->SetParameter(3, 0.);
    f2->SetParameter(4, vdep);
    f2->SetParameter(5, -0.00001);
    f2->SetRange(xlow, 350);
    status = g->Fit("fitpol", opt.c_str());
    if(status!=0) status = g->Fit("fitpol", opt.c_str());
    chi2 = f2->GetChisquare()/f2->GetNDF();
    if(debug>=1) cout<<"xlow "<<xlow<<" chi2 "<<chi2<<endl;
    if(debug>=2) cout<<" chi2 "<<f2->GetChisquare()<<" ndf "<<f2->GetNDF()<<endl;
	if(chi2<chi2min) {chi2min=chi2; xmin=xlow;}
	xlow+=10;
  }
  f2->SetParameter(0, 1.);
  f2->SetParameter(1, 0.005);
  f2->SetParameter(2, 0.0001);
  f2->SetParameter(3, 0.);
  f2->SetParameter(4, vdep);
  f2->SetParameter(5, -0.00001);
  f2->SetRange(xmin, 350);
  status = g->Fit("fitpol", opt.c_str());
  if(status!=0) status = g->Fit("fitpol", opt.c_str());
  vdep = f2->GetParameter(4);
  cout<<" Vdepl2 = "<<vdep<<" xmin "<<xmin<<endl;
  if(fabs(vdep-vdep1)>30) vdep = vdep1;
*/




      TGraphErrors* gmedian;
      gmedian = MedianFilter( g );
      int nfilt=1;
      /*while (!IsMonoton(gmedian) && nfilt<4) {
        gmedian = MedianFilter( gmedian );
        nfilt++;
      }*/
      gmedian = HanningFilter(gsmooth);
      cout<<nfilt<<" median filter applied"<<endl;

      TGraphErrors* gscurv = GetCurvatureGraph( gmedian );
      gscurv->SetMarkerStyle(20);
      TGraph* g3pts = new TGraph();
      float xopt = GetOptimalMinNPts(gscurv, g3pts);

      vdep = xopt;

      cout<<" Kink = "<<xopt<<endl;


  TCanvas *c1;
  TCanvas *c2;
  if(debug>=1)
  {
    c1 = new TCanvas();
    g->Draw("AP");
    f2->Draw("same");
    f3->Draw("same");
	//gsmooth->SetMarkerColor(17);
	//gsmooth->Draw("P");
//gmedian->SetMarkerColor(4);
//gmedian->Draw("P");	
	TLine *l = new TLine(vdep,2, vdep, ymax+0.1);
	l->SetLineStyle(3);
	l->Draw();
 
    c1->Modified();
    c1->Update();

    string detid = g->GetTitle();
    detid.erase(0,6);
    //c1->Print(Form("ClusterWidthVsVbias_detid_%s_run203832.eps", detid.c_str()));

    c2 = new TCanvas;
    gscurv->Draw("AP");
    g3pts->Draw("P");
    g3pts->Fit("pol2", "q");
    c2->Modified();
    c2->Update();

    //c2->Print(Form("ClusterWidthVsVbias_detid_%s_curv_run203832.eps", detid.c_str()));

    getchar();
    c1->Close();
    c2->Close();
  }

  return vdep;
}
Exemple #21
0
void DrawCosmicResult(){
  
  TFile* tf = new TFile("Cosmic3Out.root");
  TTree* trin = (TTree*)tf->Get("trOut");


  const int nCSI = 2716;
  Int_t    RunNumber;
  Int_t    EventNumber;
  Double_t ScintiSignal = 0;
  Double_t ScintiHHTime = -500.;
  Double_t ScintiTime   =-500.;
  Int_t    nCSIDigi     = 0;
  Double_t CSIDigiE[nCSI];//nCSIDigi
  Double_t CSIDigiTime[nCSI];//nCSIDigi
  Double_t CSIDigiHHTime[nCSI];//nCSIDigi
  Int_t    CSIDigiID[nCSI];//nCSIDigi
  Double_t CSIDigiSignal[nCSI];//nCSIDigi
  Double_t FitP0[2];
  Double_t FitP1[2];
  Double_t FitChisq[2];
  Double_t CSIDigiDeltaT0[nCSI];//nCSIDigi
  Double_t CSIDigiDeltaT1[nCSI];//nCSIDigi
  Int_t    CosmicTrigUp;
  Int_t    CosmicTrigDn;
  Double_t Roh;
  Double_t Theta;

  trin->SetBranchAddress( "RunNumber"     , &RunNumber      );
  trin->SetBranchAddress( "EventNumber"   , &EventNumber    );
  trin->SetBranchAddress( "ScintiSignal"  , &ScintiSignal   );
  trin->SetBranchAddress( "ScintiHHTimne" , &ScintiHHTime   );
  trin->SetBranchAddress( "ScintiTime"    , &ScintiTime     );
  trin->SetBranchAddress( "nCSIDigi"      , &nCSIDigi       );
  trin->SetBranchAddress( "CSIDigiE"      , CSIDigiE        );
  trin->SetBranchAddress( "CSIDigiTime"   , CSIDigiTime     );
  trin->SetBranchAddress( "CSIDigiHHTime" , CSIDigiHHTime   );
  trin->SetBranchAddress( "CSIDigiID"     , CSIDigiID       );
  trin->SetBranchAddress( "CSIDigiSignal" , CSIDigiSignal   );
  trin->SetBranchAddress( "CSIDigiDeltaT0" , CSIDigiDeltaT0 );
  trin->SetBranchAddress( "CSIDigiDeltaT1" , CSIDigiDeltaT1 );
  trin->SetBranchAddress( "FitP0"         , FitP0           );
  trin->SetBranchAddress( "FitP1"         , FitP1           );
  trin->SetBranchAddress( "FitChisq"      , FitChisq        );
  trin->SetBranchAddress( "CosmicTrigUp"  , &CosmicTrigUp   );
  trin->SetBranchAddress( "CosmicTrigDn"  , &CosmicTrigDn   );
  trin->SetBranchAddress( "Roh"           , &Roh            );
  trin->SetBranchAddress( "Theta"         , &Theta          );

  TFile* tfout = new TFile("CosmicOut_hist3.root", "recreate");
  TH2D* hisDeltaChannel = new TH2D("hisDeltaChannel","hisDeltaChannel",2716,0,2716,100,-10,10);
  TH1D* hisDelta[2716];
  TGraphErrors* grDelta = new TGraphErrors();
  TGraphErrors* grRES   = new TGraphErrors(); 
  TCanvas *can = new TCanvas("can","",800,800);


  for( int i = 0; i< 2716; i++){
    hisDelta[i] = new TH1D(Form("hisDelta%d",i ),Form("hisDelta%d",i),100,-10,10);
  }

  for( int ievent = 0; ievent < trin->GetEntries(); ievent++){

    trin->GetEntry(ievent);
    
    for( int idigi = 0; idigi < nCSIDigi ; idigi++){
      hisDelta[ CSIDigiID[ idigi ] ]->Fill( CSIDigiDeltaT1[ idigi ] );
      hisDeltaChannel->Fill( CSIDigiID[ idigi  ] , CSIDigiDeltaT1[ idigi ] );
      //std::cout  << CSIDigiID[ idigi ] << std::endl;
    }
  }
  for( int i = 0; i< 2716; i++){
    //std::cout << hisDelta[i]->GetEntries() << std::endl;
    if( hisDelta[i]->GetEntries() > 10){
      int rst = hisDelta[i]->Fit("gaus","Q","",hisDelta[i]->GetBinCenter( hisDelta[i]->GetMaximumBin() ) - 3, hisDelta[i]->GetBinCenter( hisDelta[i]->GetMaximumBin() )+3);
      TF1* func = NULL;
      func = hisDelta[i]->GetFunction("gaus");
      if( func != NULL ){
	grDelta->SetPoint( grDelta->GetN(), i, func->GetParameter(1));
	grDelta->SetPointError( grDelta->GetN()-1, 0, func->GetParError(2));
	grRES->SetPoint( grRES->GetN() , i , func->GetParameter(2));
      }
    }
    /*
    hisDelta[i]->Draw();
    can->Modified();
    can->Update();
    getchar();
    */
    hisDelta[ i ]  ->Write(); 
  }

  std::ofstream ofs("TimeResolutionCosmic3.dat");
  int    ID[2716];
  double Delta[2716];
  double Resolution[2716];
  for( int i = 0; i< 2716; i++){
    Resolution[i] = 0xFFFF;
    Delta[i]      = 0xFFFF;
  }
  for( int i = 0; i< grRES->GetN(); i++){
    Delta[(int)(grDelta->GetX()[i])] = grDelta->GetY()[i];
    Resolution[(int)(grRES->GetX()[i])] = grRES->GetY()[i] ;
  }
  for( int i = 0; i< 2716; i++){
    ofs << i             << "\t" 
	<< Delta[i]      << "\t"
	<< Resolution[i] << "\n";
  }
  
  grDelta->SetNameTitle("grDelta","grDelta");
  grRES->SetNameTitle("grRES","grRES");
  grDelta->Write();
  grRES->Write();
  hisDeltaChannel->Write();
  tfout->Close();
  ofs.close();
}
Exemple #22
0
TGraphErrors *ReadMWGraph(const char *name, Int_t flag)
{
  Double_t xreject = 0.49;

  TGraphErrors *g = new TGraphErrors(name);
  if (g->IsZombie()) return 0;
  while (g->GetX()[0] < xreject)
    g->RemovePoint(0);

  TGraphErrors *g2 = new TGraphErrors(name);
  if (g2->IsZombie()) return 0;
  while (g2->GetX()[0] < xreject)
    g2->RemovePoint(0);
  g2->SetMarkerStyle(4);
  g2->SetMarkerSize(1.00);
  g2->SetMarkerColor(kBlack);
  g2->SetLineColor(kBlack);

  TGraphErrors *gsys = new TGraphErrors(name, "%lg %lg %lg %*lg %lg");
  if (gsys->IsZombie()) return 0;
  while (gsys->GetX()[0] < xreject)
    gsys->RemovePoint(0);
  for (Int_t i = 0; i < gsys->GetN(); i++)
    gsys->SetPointError(i, gsys->GetErrorX(i)*0.75, gsys->GetErrorY(i));
  gsys->SetFillColor(kGray+2);
  gsys->SetLineColor(kGray+2);
  gsys->SetFillStyle(3000);

  if (flag == 1 || flag == 3) {
    TGraphErrors *gt = new TGraphErrors(Form("%s_%s", name, "trues"));
    if (gt->IsZombie()) return 0;
    while (gt->GetX()[0] < xreject)
      gt->RemovePoint(0);
    gt->SetMarkerStyle(20);
    gt->SetMarkerSize(0.75);
    gt->SetMarkerColor(kGreen+1);
    gt->SetLineColor(kGreen+1);

    TGraphErrors *gbw = new TGraphErrors(Form("%s_%s", name, "gen"));
    if (gbw->IsZombie()) return 0;
    while (gbw->GetX()[0] < xreject)
      gbw->RemovePoint(0);
    gbw->SetMarkerStyle(20);
    gbw->SetMarkerSize(0.75);
    gbw->SetMarkerColor(kBlue+1);
    gbw->SetLineColor(kBlue+1);

    for (Int_t i = 0; i < g->GetN(); i++) {
      g->SetPointError(i, g->GetEX()[i], 0.);
      gt->SetPointError(i, gt->GetEX()[i], 0.);
      gbw->SetPointError(i, gbw->GetEX()[i], 0.);
    }

    for (Int_t i = 0; i < g2->GetN(); i++) {
      g2->SetPoint(i, g2->GetX()[i], g2->GetY()[i] - gt->GetY()[i] + gbw->GetY()[i]);
      g2->SetPointError(i, g2->GetEX()[i], TMath::Sqrt(g2->GetEY()[i]*g2->GetEY()[i] + gt->GetEY()[i]*gt->GetEY()[i] +
                                                       gbw->GetEY()[i]*gbw->GetEY()[i]));

      //      g2->SetPoint(i, g2->GetX()[i], g2->GetY()[i] - gt->GetY()[i] + 1.01947);
      //      g2->SetPointError(i, g2->GetEX()[i], TMath::Sqrt(g2->GetEY()[i]*g2->GetEY()[i] + gt->GetEY()[i]*gt->GetEY()[i] +
      //                                                       7.78680e-06*7.78680e-06));

      gsys->SetPoint(i, gsys->GetX()[i], g2->GetY()[i]);
    }
  }

  g->SetTitle();
  g->SetName(name);
  g->GetXaxis()->SetTitle("p_{T}, GeV/c");
  g->SetMarkerStyle(20);
  g->SetMarkerSize(0.95);
  g->SetMarkerColor(kRed+1);
  g->SetLineColor(kRed+1);

  const Double_t mass = 1.019455;
  const Double_t mass_delta = 0.000020;
  const Double_t width = 0.00426;
  const Double_t width_delta = 0.00004;
  if (flag == 1) { // mass
    g->GetYaxis()->SetTitleOffset(1.50);
    g->GetYaxis()->SetTitle("mass, GeV/c^{2}");
    g->SetMaximum(mass+0.0015);
    g->SetMinimum(mass-0.0015);
    TBox *box = new TBox(g->GetXaxis()->GetXmin(), mass - mass_delta, g->GetXaxis()->GetXmax(), mass + mass_delta);
    box->SetFillColor(kGray+1);
    box->SetFillStyle(3001);
    g->GetListOfFunctions()->Add(box);
    g->GetListOfFunctions()->Add(g2, "CP");
    g->GetListOfFunctions()->Add(gt, "CP");
    g->GetListOfFunctions()->Add(gbw, "CP");
  }
  else if (flag == 3) { // mass simple
    g2->SetTitle();
    g2->SetName(Form("%s_only", name));
    g2->GetXaxis()->SetTitle("p_{T}, GeV/c");
    g2->SetMarkerStyle(20);
    g2->SetMarkerSize(0.75);
    g2->SetMarkerColor(kBlack);
    g2->SetLineColor(kBlack);
    g2->GetYaxis()->SetTitleOffset(1.50);
    g2->GetYaxis()->SetTitle("mass, GeV/c^{2}");
    g2->SetMaximum(mass+0.0015);
    g2->SetMinimum(mass-0.0015);
    TBox *box = new TBox(g->GetXaxis()->GetXmin(), mass - mass_delta, g2->GetXaxis()->GetXmax(), mass + mass_delta);
    box->SetFillColor(kGray+1);
    box->SetFillStyle(3001);
    g2->GetListOfFunctions()->Add(box);
    g2->GetListOfFunctions()->Add(gsys, "E5");
    return g2;
  }
  else if (flag == 2) { // width
    g->SetTitle();
    g->SetName(name);
    g->GetXaxis()->SetTitle("p_{T}, GeV/c");
    g->SetMarkerStyle(20);
    g->SetMarkerSize(0.75);
    g->SetMarkerColor(kBlack);
    g->SetLineColor(kBlack);
    g->GetYaxis()->SetTitleOffset(1.50);
    g->GetYaxis()->SetTitle("width, GeV/c^{2}");
    g->SetMaximum(0.01);
    g->SetMinimum(0.0);
    TBox *box = new TBox(g->GetXaxis()->GetXmin(), width - width_delta, g->GetXaxis()->GetXmax(), width + width_delta);
    box->SetFillColor(kGray+1);
    box->SetFillStyle(3001);
    g->GetListOfFunctions()->Add(box);
    g->GetListOfFunctions()->Add(gsys, "E5");
  }

  return g;
}
// /r06/lc/sg568/HCAL_Optimisation_Studies/EnergyResolutionResults/Detector_Model_103/Reco_Stage_38/Photon
// EnergyResolution_PandoraSettingsDefault_DetectorModel_103_ReconstructionVariant_38_Photon.root
void DrawNumLayers() 
{
    const int recoVar(71);
    const int energy(100);

    std::vector<int> detectorModels;
    detectorModels.push_back(96);
    detectorModels.push_back(97);
    detectorModels.push_back(98);
    detectorModels.push_back(99);

    std::map<int, int> detModelToLayerNumber;
    detModelToLayerNumber[96] = 30;
    detModelToLayerNumber[97] = 26;
    detModelToLayerNumber[98] = 20;
    detModelToLayerNumber[99] = 16;

    TCanvas *pTCanvas = new TCanvas();

    TGraphErrors *pTGraphErrors = new TGraphErrors("EResVsLayer","EResVsLayer");

    for (std::vector<int>::iterator it = detectorModels.begin(); it != detectorModels.end(); it++)
    {
        const int detModel(*it);
        const int layerNumber(detModelToLayerNumber.find(detModel)->second);

        std::string rootFile("/r06/lc/sg568/HCAL_Optimisation_Studies/EnergyResolutionResults/Detector_Model_" + NumberToString(detModel) + "/Reco_Stage_" + NumberToString(recoVar) + "/Photon/EnergyResolution_PandoraSettingsDefault_DetectorModel_" + NumberToString(detModel) + "_ReconstructionVariant_" + NumberToString(recoVar) + "_Photon.root");
        std::cout << rootFile << std::endl;
        TFile *pTFile = new TFile(rootFile.c_str());

        std::string histogramName("Resolution_DetectorModel_" + NumberToString(detModel) + "_ReconstructionVariant_" + NumberToString(recoVar) + "/PFOEnergyHistogram_DetectorModel_" + NumberToString(detModel) + "_ReconstructionVariant_" + NumberToString(recoVar) + ";4");

        std::cout << histogramName << std::endl;
 
        TH1F *pTH1F = (TH1F*)pTFile->Get(histogramName.c_str());

        std::string fitTitle = "PFOEnergyHistogramGaussianFit_DetectorModel_" + NumberToString(detModel) + "_ReconstructionVariant_" + NumberToString(recoVar) + "_Energy" + NumberToString(energy) + "GeV";
        TF1 *pGaussianFit = new TF1(fitTitle.c_str(),"gaus",0,1000);

        pTH1F->Fit(fitTitle.c_str());
        const float fitAmplitude(pGaussianFit->GetParameter(0));
        const float fitMean(pGaussianFit->GetParameter(1));
        const float fitStdDev(pGaussianFit->GetParameter(2));
        const float energyResolution(fitStdDev/fitMean);

        const float meanError(pGaussianFit->GetParError(1));
        const float meanFracError(meanError / fitMean);
        const float stdDevError(pGaussianFit->GetParError(2));
        const float stdDevFracError(stdDevError / fitStdDev);

        const float energyResolutionError = energyResolution * std::pow( (meanFracError*meanFracError) + (stdDevFracError*stdDevFracError) ,0.5);

        pTGraphErrors->SetPoint(pTGraphErrors->GetN(),layerNumber,energyResolution*100.f);
        pTGraphErrors->SetPointError(pTGraphErrors->GetN()-1,0,energyResolutionError*100.f);

        std::cout << "For energy : " << energy << std::endl;
        std::cout << "Amplitude          : " << fitAmplitude << std::endl;
        std::cout << "Mean               : " << fitMean << std::endl;
        std::cout << "Standard Deviation : " << fitStdDev << std::endl;
        std::cout << "Det model " << detModel << std::endl;
        std::cout << "Energy Resolution  : " << energyResolution*100 << std::endl;
    }

    TH2F *pAxes = new TH2F("axesEj","",100,14,32,1000,2.5,3.5);
    pAxes->SetTitle("100 GeV Photon Energy Resolution vs Number of Layers in ECal (Si)");
    pAxes->GetYaxis()->SetTitle("#sigma_{Reco} / E_{Reco}");
    pAxes->GetXaxis()->SetTitle("Number of ECal Layers");
    pAxes->Draw();

    pTGraphErrors->Draw("same PL");
}
Exemple #24
0
void disceff(TString filename) {
	gROOT->SetStyle("Plain");
	
	TString cmssw;
	// 167
	
	cmssw = "$3.1.0_pre9$";
		
	TFile *f = TFile::Open(filename);

	std::vector< TString > taggers;
	taggers.push_back( "TC2" );
	taggers.push_back( "TC3" );
	taggers.push_back( "TP" );
	taggers.push_back( "BTP" );
	taggers.push_back( "SSV" );
	taggers.push_back( "CSV" );
	taggers.push_back( "MSV" );
	taggers.push_back( "SMT" );
	taggers.push_back( "SETbyIP3d" );
	taggers.push_back( "SETbyPt" );
	taggers.push_back( "SMTbyIP3d" );
	taggers.push_back( "SMTbyPt" );

	std::vector< TString > discriminators;
	for ( size_t itagger = 0; itagger < taggers.size(); ++itagger ) {
		discriminators.push_back( "disc"+taggers[itagger]+"_udsg" );
	}
//	discriminators.push_back( "discTC3_udsg" );
//	discriminators.push_back( "discTP_udsg" );

	const int dim=taggers.size();
        TCanvas *cv[dim];
	TMultiGraph* mg[dim];
	for ( size_t itagger = 0; itagger < taggers.size(); ++itagger ) {
		TString tag = "g"+taggers[itagger]+"_udsg";
		TString tagb = "g"+taggers[itagger]+"_b";
		TString tagc = "g"+taggers[itagger]+"_c";
		cv[itagger] = new TCanvas("cv_"+taggers[itagger],"cv_"+taggers[itagger],700,700);
		TLegend *legend0 = new TLegend(0.68,0.70,0.88,0.90);

		TGraphErrors *agraph = (TGraphErrors*) gDirectory->Get("BTagPATAnalyzer"+taggers[itagger]+"/"+taggers[itagger]+"/"+tag);
		TGraphErrors *bgraph = (TGraphErrors*) gDirectory->Get("BTagPATAnalyzer"+taggers[itagger]+"/"+taggers[itagger]+"/"+tagb);
		TGraphErrors *cgraph = (TGraphErrors*) gDirectory->Get("BTagPATAnalyzer"+taggers[itagger]+"/"+taggers[itagger]+"/"+tagc);

		TGraph *dgraph = (TGraph*) gDirectory->Get("BTagPATAnalyzer"+taggers[itagger]+"/"+taggers[itagger]+"/"+discriminators[itagger]);
		TGraph *bvsdgraph = new TGraph(dgraph->GetN(),dgraph->GetY(),bgraph->GetY());
		TGraph *cvsdgraph = new TGraph(dgraph->GetN(),dgraph->GetY(),cgraph->GetY());
		TGraph *lvsdgraph = new TGraph(dgraph->GetN(),dgraph->GetY(),agraph->GetY());
		TGraph *udsgvsdgraph = new TGraph(dgraph->GetN(),dgraph->GetY(),dgraph->GetX());
		dgraph->Sort();
//		udsgvsdgraph->Sort();
//		udsgvsdgraph->SetLineColor(1);
//              legend0 -> AddEntry(udsgvsdgraph,"control","l");
		lvsdgraph->Sort();
		lvsdgraph->SetLineColor(2);
                legend0 -> AddEntry(lvsdgraph,tag,"l");
		cvsdgraph->Sort();
		cvsdgraph->SetLineColor(3);
                legend0 -> AddEntry(cvsdgraph,tagc,"l");
		bvsdgraph->Sort();
		bvsdgraph->SetLineColor(4);
                legend0 -> AddEntry(bvsdgraph,tagb,"l");
		mg[itagger]= new TMultiGraph();
//		mg[itagger]->Add(udsgvsdgraph);
		mg[itagger]->Add(lvsdgraph);
		mg[itagger]->Add(cvsdgraph);
		mg[itagger]->Add(bvsdgraph);
//		mg[itagger]->Add(dgraph);

		cv[itagger]->cd(1);
		mg[itagger]->Draw("ALP");
		mg[itagger]->GetYaxis()->SetTitle("eff");
		mg[itagger]->GetXaxis()->SetTitle("discriminant");
		legend0 -> Draw();
		cv[itagger]->Update();
	        cv[itagger]->cd(0);
		cv[itagger]-> Print ("BTagPATeff_vs_disc"+taggers[itagger]+".eps");
		cv[itagger]-> Print ("BTagPATeff_vs_disc"+taggers[itagger]+".ps");

		TGraphErrors *g = new TGraphErrors(agraph->GetN(),agraph->GetY(),agraph->GetX(),agraph->GetEY(),agraph->GetEX());
		g->Sort();
		g->SetLineColor(itagger+1);

		std::cout << " Tagger: " << tag << std::endl;
		std::cout << " Loose(10%): " << " cut > " << std::setprecision(4) << dgraph->Eval(0.1) << " b-eff = " << g->Eval(0.1) << std::endl;
		std::cout << " Medium(1%):  " << " cut > " << std::setprecision(4) << dgraph->Eval(0.01) << " b-eff = " << g->Eval(0.01) << std::endl;
		std::cout << " Tight(0.1%) = " << " cut > " << std::setprecision(4) << dgraph->Eval(0.001) << " b-eff = " << g->Eval(0.001) << std::endl;

	}//end for
 
	
}
void getCalibrationResults(TString url="TopMassCalibration.root",int nCategs=4)
{
  TString mpts[]={"161.5","163.5","166.5","169.5","172.5","175.5","178.5","181.5","184.5"};
  const size_t nmpts=sizeof(mpts)/sizeof(TString);

  std::vector<TString> labels;
  if(nCategs==2)
    {
      labels.push_back("1 b-tags");
      labels.push_back("#geq 2 b-tags");
    }
  else if(nCategs==4)
    {
      labels.push_back("1 b-tags (ee+#mu#mu)");
      labels.push_back("#geq 2 b-tags (ee+#mu#mu)");
      labels.push_back("1 b-tags (e#mu)");
      labels.push_back("#geq 2 b-tags (e#mu)");
    }
  else 
    {
      labels.push_back("1 b-tags (ee)");
      labels.push_back("#geq 2 b-tags (ee)");
      labels.push_back("1 b-tags (#mu#mu)");
      labels.push_back("#geq 2 b-tags (#mu#mu)");
      labels.push_back("1 b-tags (e#mu)");
      labels.push_back("#geq 2 b-tags (e#mu)");
    }
  
  TString outDir=gSystem->DirName(url);
  report << "Plots will be stored at @ " << outDir << endl;

  TGraphErrors *lingr = new TGraphErrors;  
  lingr->SetMarkerStyle(20);
  TGraphErrors *biasgr = new TGraphErrors; 
  biasgr->SetMarkerStyle(20);
  std::vector<TGraphErrors *> categbiasgr;
  for(int icat=0; icat<nCategs; icat++) categbiasgr.push_back( new TGraphErrors );
  TObjArray statUncResults;
  TObjArray pullResults;

  //get results from file
  TFile *fin=TFile::Open(url);
  for(size_t i=0; i<nmpts; i++)
    {
      Float_t trueMass=mpts[i].Atof();
      
      TH1D *massFitH=(TH1D *)fin->Get(mpts[i]+"/massfit");
      if(massFitH==0) continue;

      TF1 *ffunc=massFitH->GetFunction("gaus");
      float avgMass=ffunc->GetParameter(1);
      float avgMassErr=ffunc->GetParError(1);
      int ipt=lingr->GetN();
      lingr->SetPoint(ipt,trueMass,avgMass);
      lingr->SetPointError(ipt,0,avgMassErr);

      for(int icat=0; icat<=nCategs;icat++)
	{
	  TString postfix("");
	  TGraphErrors *gr=biasgr;
	  if(icat<nCategs){ postfix ="_"; postfix +=( icat+1); gr=categbiasgr[icat]; }
	  TH1D *biasH=(TH1D *)fin->Get(mpts[i]+"/bias"+postfix);
	  ffunc=biasH->GetFunction("gaus");
	  float avgBias=ffunc->GetParameter(1);
	  float avgBiasErr=ffunc->GetParError(1);   
	  ipt=gr->GetN();
	  gr->SetPoint(ipt,trueMass,avgBias);
	  gr->SetPointError(ipt,0,avgBiasErr);
	
	  if(trueMass==172.5) 
	    { 
	      TH1D *h=(TH1D *)fin->Get(mpts[i]+"/statunc"+postfix); 
	      h->SetDirectory(0);
	      h->SetLineColor(icat==nCategs? 1 : icat+2); 
	      h->SetMarkerColor(icat==nCategs? 1 : icat+2); 
	      h->SetMarkerStyle(1);
	      h->SetLineWidth(2);
	      statUncResults.Add(h);
	    }  
	}



      TH1D *pullH=(TH1D *)fin->Get(mpts[i]+"/pull");
      pullH->SetDirectory(0);
      pullResults.Add(pullH);
    }
  fin->Close();


  //plot results
  setStyle();
  gStyle->SetOptFit(0);

  TCanvas *c=new TCanvas("linc","linc",600,600);
  c->SetWindowSize(600,600);
  c->Divide(1,2);
  TPad *p=(TPad *)c->cd(1);
  p->SetPad(0,0.3,1.0,1.0);
  lingr->Draw("ap");
  lingr->GetXaxis()->SetTitle("Generated m_{top} [GeV/c^{2}]");
  lingr->GetXaxis()->SetTitle("Fitted m_{top} [GeV/c^{2}]");

  TLine *l=new TLine(lingr->GetXaxis()->GetXmin(),lingr->GetYaxis()->GetXmin(),
		     lingr->GetXaxis()->GetXmax(),lingr->GetYaxis()->GetXmax());
  l->SetLineColor(kGray);
  l->SetLineStyle(6);
  l->Draw("same");
  TLegend *leg = p->BuildLegend();
  formatForCmsPublic(p,leg,"CMS simulation",3);
  leg->Delete();


  p=(TPad *)c->cd(2);
  p->SetPad(0,0.0,1.0,0.28);
  p->SetTopMargin(0);
  p->SetBottomMargin(0.5);
  float yscale = (1.0-0.3)/(0.28-0);
  biasgr->Draw("ap");
  biasgr->GetXaxis()->SetTitle("Generated m_{top} [GeV/c^{2}]");
  biasgr->GetYaxis()->SetTitle("Bias");
  biasgr->GetYaxis()->SetRangeUser(-5.2,5.2);
  biasgr->GetXaxis()->SetTitleOffset(0.85);
  biasgr->GetXaxis()->SetLabelSize(0.04 * yscale);
  biasgr->GetXaxis()->SetTitleSize(0.05 * yscale);
  biasgr->GetXaxis()->SetTickLength( 0.03 * yscale );
  biasgr->GetYaxis()->SetTitleOffset(0.5);
  biasgr->GetYaxis()->SetLabelSize(0.04 * yscale);
  biasgr->GetYaxis()->SetTitleSize(0.04 * yscale);
  biasgr->Fit("pol1");
  float a=biasgr->GetFunction("pol1")->GetParameter(1);
  float b=biasgr->GetFunction("pol1")->GetParameter(0);
  report << "[Inclusive bias correction] resslope:" << (a+1.) << " resbias:" << b << endl;
  c->Modified();
  c->Update();
  c->SaveAs(outDir+"/TopMassCalibrationResults.C");
  c->SaveAs(outDir+"/TopMassCalibrationResults.png");
  c->SaveAs(outDir+"/TopMassCalibrationResults.pdf");
  //  delete c;
  
  //biases per category
  c=new TCanvas("biasc","biasc",600,600);
  c->SetWindowSize(600,600);
  c->Divide(1,nCategs+1);
  c->cd(nCategs+1)->Delete();
  float ystep=(1.0)/(nCategs+1);
  for(int icat=nCategs-1; icat>=0; --icat)
    {
      TGraphErrors *gr=categbiasgr[icat];
      gr->SetMarkerStyle(20);
      TPad *p=(TPad *)c->cd(icat+1);
      p->SetFillStyle(1001);
      p->SetFillColor(0);
      float ymin=(icat+1)*ystep-0.05;
      float ymax=(icat+2)*ystep-0.05;
      if(icat==0)
	{
	  ymin=icat*ystep;
	}
      p->SetPad(0,ymin,1.0,ymax);
      p->SetTopMargin(0.0);
      p->SetBottomMargin(icat==0?0.4:0.0);
      gr->Draw("ap");
      float yscale = (0.95-ystep)/(ystep-0.0);
      if(icat==0) yscale=(0.95-2*ystep)/(1.2*ystep-0);
      if(icat==0) gr->GetXaxis()->SetTitle("Generated m_{top} [GeV/c^{2}]");
      else gr->GetXaxis()->SetNdivisions(0);
      gr->GetYaxis()->SetTitle("Bias");
      gr->GetYaxis()->SetRangeUser(-5.2,5.2);
      gr->GetXaxis()->SetTitleOffset(0.85);
      gr->GetXaxis()->SetLabelSize(0.04 * yscale);
      gr->GetXaxis()->SetTitleSize(0.05 * yscale);
      gr->GetXaxis()->SetTickLength( 0.03 * yscale );
      gr->GetYaxis()->SetTitleOffset(icat==0?0.5:0.3);
      gr->GetYaxis()->SetLabelSize(0.04 * yscale);
      gr->GetYaxis()->SetTitleSize(0.04 * yscale);
      gr->Fit("pol1");
      float a=gr->GetFunction("pol1")->GetParameter(1);
      float b=gr->GetFunction("pol1")->GetParameter(0);
      report << "[Bias correction #" << icat+1 << "] resslope:" << (a+1.) << " resbias:" << b << endl;
      
      //prepare label
      TPaveText *pave = new TPaveText(0.70,0.65,0.8,0.92,"NDC");
      pave->SetTextFont(42);
      pave->SetFillStyle(0);
      pave->SetBorderSize(0);
      pave->AddText( labels[icat] )->SetTextAlign(11);
      pave->Draw();

      if(icat==nCategs-1)
	{
	  pave = new TPaveText(0.2,0.75,0.45,0.92,"NDC");
	  pave->SetTextFont(42);
	  pave->SetFillStyle(0);
	  pave->SetBorderSize(0);
	  pave->AddText( "CMS simulation" )->SetTextAlign(11);
	  pave->Draw();
	}
    }
  c->Modified();
  c->Update();
  c->SaveAs(outDir+"/TopMassCalibrationBiases.C");
  c->SaveAs(outDir+"/TopMassCalibrationBiases.png");
  c->SaveAs(outDir+"/TopMassCalibrationBiases.pdf");
  //delete c;

  //stat uncertainty
  c=new TCanvas("statc","statc",600,600);
  c->SetWindowSize(600,600);
  for(int i=0; i<statUncResults.GetEntriesFast(); i++)
    {
      int idx=statUncResults.GetEntriesFast()-1-i;
      statUncResults.At(idx)->Draw(i==0?"hist":"histsame");
      ((TH1*)statUncResults.At(idx))->SetTitle( i==0 ? "combined" :labels[idx] );
    }
  leg = c->BuildLegend();
  formatForCmsPublic(c,leg,"CMS simulation",3);  c->Modified();
  c->Update();
  c->SaveAs(outDir+"/TopMassCalibrationStat.C");
  c->SaveAs(outDir+"/TopMassCalibrationStat.png");
  c->SaveAs(outDir+"/TopMassCalibrationStat.pdf");
  //delete c;
  
  //pulls
  TGraphErrors *avgPull = new TGraphErrors;   avgPull->SetMarkerStyle(20);
  TGraphErrors *sigmaPull = new TGraphErrors; sigmaPull->SetMarkerStyle(20);
  c=new TCanvas("pullsc","pullsc",1600,(pullResults.GetEntriesFast()/4+1)*400);
  c->SetWindowSize(1600,(pullResults.GetEntriesFast()/4+1)*400);
  c->Divide(4,pullResults.GetEntriesFast()/4+1);
  for(int i=0; i<pullResults.GetEntriesFast(); i++)
    {
      TPad *p=(TPad *)c->cd(i+1);
      TH1 *pullH=(TH1 *)pullResults.At(i);
      pullH->Draw("e1");

      Float_t trueMass=mpts[i].Atof();
      TF1 *gaus=pullH->GetFunction("gaus");
      avgPull->SetPoint(i,trueMass,gaus->GetParameter(1));
      avgPull->SetPointError(i,0,gaus->GetParError(1));
      sigmaPull->SetPoint(i,trueMass,gaus->GetParameter(2));
      sigmaPull->SetPointError(i,0,gaus->GetParError(2));

      if(i==0)
	{
	  leg = p->BuildLegend();
	  formatForCmsPublic(p,leg,"CMS simulation",3);
	  leg->Delete();
	}
      
      TPaveText *pave = new TPaveText(0.2,0.8,0.35,0.88,"NDC");
      pave->SetTextFont(42);
      pave->SetFillStyle(0);
      pave->SetBorderSize(0);
      pave->AddText( mpts[i] )->SetTextAlign(11);
      pave->Draw();

    }
  c->Modified();
  c->Update();
  c->SaveAs(outDir+"/TopMassCalibrationPulls.C");
  c->SaveAs(outDir+"/TopMassCalibrationPulls.png");
  c->SaveAs(outDir+"/TopMassCalibrationPulls.pdf");
  //delete c;

  //pull momenta
  c=new TCanvas("pullsmomc","pullsmomc",600,600);
  c->SetWindowSize(600,600);
  c->Divide(1,2);
  p=(TPad *)c->cd(1);
  avgPull->Draw("ap");
  avgPull->GetYaxis()->SetRangeUser(-3,3);
  avgPull->GetXaxis()->SetTitle("Generated m_{top} [GeV/c^{2}]");
  avgPull->GetYaxis()->SetTitle("Average pull");
  leg = p->BuildLegend();
  formatForCmsPublic(p,leg,"CMS simulation",3);
  leg->Delete();
  c->cd(2);
  sigmaPull->GetYaxis()->SetRangeUser(0.9,1.2);
  sigmaPull->Draw("ap");
  sigmaPull->GetXaxis()->SetTitle("Generated m_{top} [GeV/c^{2}]");
  sigmaPull->GetYaxis()->SetTitle("Pull width");
  c->Modified();
  c->Update();
  c->SaveAs(outDir+"/TopMassCalibrationPullsMomenta.C");
  c->SaveAs(outDir+"/TopMassCalibrationPullsMomenta.png");
  c->SaveAs(outDir+"/TopMassCalibrationPullsMomenta.pdf");
  //delete c;

  cout << report.str() << endl;


}
void get_nn_ptpt_FROM_FB_TREE() // TString inputFileName = "MergedOutput.root")
{
    //            TFile *myFile = new TFile( "/Users/macbook/alice/aliceAnalysis/results/task_2016_02_09_PbPb_Data_AOD_3etaWins_phi1_pt02_20_FB_TREE_blocks123/block1/AnalysisResults.139465.root" );
    TFile *myFile = new TFile( "/Users/macbook/alice/aliceAnalysis/results/task_2016_02_21_PbPb_Data_AOD_3etaWins_phi1_pt02_20_FB_TREE_TEST_NEW_DATA_5_02TeV_tryAOD2/MergedOutput.root" );
    if (!myFile)
    {
        cout << "No input file!" << endl;
        return;
    }
    myFile->ls();
    TList *listKeys = myFile->GetListOfKeys();
    cout << "going into list: " << listKeys->At(1)->GetName() << endl;

    //return;
    myFile->cd( listKeys->At(1)->GetName() );
    TList *listKeys2 = gDirectory->GetListOfKeys();
    TList *myTask = (TList*) gDirectory->Get( listKeys2->At(0)->GetName() );
    TTree *t1 = (TTree*)  myTask->FindObject( "treeFB" );


    //    cout << t1->GetEntries() << endl;
    //t1->Print();
    //return;
    //    TFile *f = new TFile( "file_event_tree_merged_impPar_2files.root" );
    //    TTree *t1 = (TTree*) f->Get( "t1" );

    //    TFile *f = new TFile( "output_1_list.grid.root" );
    //    TList *list = (TList*) f->Get( "coutput_V0_mult_0.000000_100000.000000" );
    //    TTree *t1 = (TTree*) list->FindObject( "t1" );

    //other vars:
    //    const int nVars = 3;
    //    TString strVarName[] = {
    //        "centr_V0M" ,
    //        "centr_CL1" ,
    //        "centr_ZEMvsZDC"     ,
    //    };
    //    Float_t varBranch[nVars];

    //    for(Int_t var = 0; var < nVars; var++)
    //        t1->SetBranchAddress(strVarName[var],&varBranch[var]);

    Float_t brV0M;
    //    t1->SetBranchAddress( "centr_V0M", &brV0M );
    t1->SetBranchAddress( "centrV0M_NEW_MULT_SEL", &brV0M );

    Float_t brZEMvsZDC;
    t1->SetBranchAddress( "centr_ZEMvsZDC", &brZEMvsZDC );

    //        const int nCW = 1; //nCentrWidths
    //        const double cWidths[nCW] = { 10 }; //width of the centrality bins
    //        const double cStep[nCW] = { 5 }; //centrality bins step
    //        const int nCentrBins[nCW] = { 17 }; //n centrality bins

//    const int nCW = 2; //nCentrWidths
//    const double cWidths[nCW] = { 10, 5.001 }; //width of the centrality bins
//    const double cStep[nCW] = { 5, 2.5 }; //centrality bins step
//    const int nCentrBins[nCW] = { 17, 35 }; //n centrality bins

    const int nCW = 2; //nCentrWidths
    const double cWidths[nCW] = { 10, 5 }; //width of the centrality bins
    const double cStep[nCW] = { 10, 5 }; //centrality bins step
    const int nCentrBins[nCW] = { 9, 18 }; //n centrality bins


    //    const int nCW = 5; //nCentrWidths
    //    const double cWidths[nCW] = { 10, 5, 2.5, 1.0, 0.5 }; //width of the centrality bins
    //    const double cStep[nCW] = { 5, 2.5, 2.5, 1.0, 1.0 }; //centrality bins step
    //    const int nCentrBins[nCW] = { 17, 35, 36, 90, 90 }; //n centrality bins

    const int nEtaWins = 3;
    const int nPhiWins = 1;

    const int maxNCentrBins = 100; //TMath::MaxElement(nCW, &nCentrBins);
    WinPair wins[nCW][maxNCentrBins][nEtaWins][nPhiWins];
    CentralityOccupancy cOccupancy[nCW][maxNCentrBins];

    for ( int cW = 0; cW < nCW; cW++ )
        for ( int cBin = 0; cBin < nCentrBins[cW]; cBin++ )
        {
            float cBinMin = cStep[cW] * cBin;
            float cBinMax = cWidths[cW] + cStep[cW] * cBin;

            cOccupancy[cW][cBin].cBinMin = cBinMin;
            cOccupancy[cW][cBin].cBinMax = cBinMax;

            for ( int etaW = 0; etaW < nEtaWins; etaW++ )
                for ( int phiW = 0; phiW < nPhiWins; phiW++ )
                    wins[cW][cBin][etaW][phiW].init(cBinMin, cBinMax, etaW, phiW);
        }


    BranchFB br[nEtaWins][nPhiWins];

    for ( int etaW = 0; etaW < nEtaWins; etaW++ )
        for ( int phiW = 0; phiW < nPhiWins; phiW++ )
        {
            int ptW = 0;
            TString brNamePostfix = Form("eta_%d_phi%d_pt_%d"
                                         , etaW, phiW, ptW );
            t1->SetBranchAddress( Form("nF_%s", brNamePostfix.Data() ),  &br[etaW][phiW].nF );
            t1->SetBranchAddress( Form("nB_%s", brNamePostfix.Data() ),  &br[etaW][phiW].nB );
            t1->SetBranchAddress( Form("PtF_%s", brNamePostfix.Data() ), &br[etaW][phiW].PtF );
            t1->SetBranchAddress( Form("PtB_%s", brNamePostfix.Data() ), &br[etaW][phiW].PtB );
        }



    TH1D *hist1D_QA_percentilesEstimator = new TH1D( "hist1D_QA_percentilesEstimator", "hist1D_QA_percentilesEstimator;percentile;entries", 3001, -0.5, 300.5);
    TH1D *hist1D_QA_multALL = new TH1D( "hist1D_QA_multALL", "hist1D_QA_multALL;mult;entries", 3001, -0.5, 3000.5);


    // ##### prepare for tree loop
    int nEvents = t1->GetEntries();
    cout <<"nEvents = " << nEvents << endl;

    //    float **BS_Nf = new float*[nPhiWins];
    //    float **BS_Nb = new float*[nPhiWins];
    //    for ( int w = 0; w < nPhiWins; w++ )
    //    {
    //        BS_Nf[w] = new float[nEvents];
    //        BS_Nb[w] = new float[nEvents];
    //    }

    // ##### main loop over events
    int flag_V0M_ZDC = 0;//1;
    int nAccepted = 0;
    for (Long64_t i=0; i < nEvents; i++)
    {
        if ( i % 100000 == 0 )
            cout << "getting " << (int)i << endl;
        //                cout <<"getting " << (int)i << "\r"; cout.flush();

        t1->GetEntry( i );
        //            t1->GetEntry( TMath::Nint( gRandom->Uniform(-0.5,nEvents-0.5) ) );

        float cEstimator = -1;
        if ( flag_V0M_ZDC==0 )
        {
            if ( brV0M > 90 ) //V0M cut
                continue;
            cEstimator = brV0M;
        }
        else
        {
            if ( brZEMvsZDC > 50 ) //ZDCvsZEM cut
                continue;
            cEstimator = brZEMvsZDC;
        }
        hist1D_QA_percentilesEstimator->Fill(cEstimator);


        //calc mult in whole TPC using wins:
        int multTPC = 0;
        for ( int phiW = 0; phiW < nPhiWins; phiW++ )
            multTPC += (br[0][phiW].nF + br[2][phiW].nF) + (br[0][phiW].nB + br[2][phiW].nB);
        hist1D_QA_multALL->Fill(multTPC);


        //        for ( int w = 0; w < nPhiWins; w++ )
        //        {
        //            BS_Nf[w][nAccepted] = Nf[w];
        //            BS_Nb[w][nAccepted] = Nb[w];
        //        }

        for ( int cW = 0; cW < nCW; cW++ )
            for ( int cBin = 0; cBin < nCentrBins[cW]; cBin++ )
            {
                cOccupancy[cW][cBin].fill(brV0M, brZEMvsZDC);
                for ( int etaW = 0; etaW < nEtaWins; etaW++ )
                    for ( int phiW = 0; phiW < nPhiWins; phiW++ )
                        wins[cW][cBin][etaW][phiW].fill( cEstimator, br[etaW][phiW].nF, br[etaW][phiW].nB, br[etaW][phiW].PtF, br[etaW][phiW].PtB );
            }

        nAccepted++;


    } // end of events
    cout << "nAccepted = " << nAccepted << endl;
    cout << "nAccepted/nAll = " << (float)nAccepted/nEvents << endl;


    // ########## QA PLOTTING:
    TCanvas *canv_estimatorPercentiles_QA_all = new TCanvas("canv_estimatorPercentiles_QA_all","canv_estimatorPercentiles_QA_all",0,0,700,600 );
    hist1D_QA_percentilesEstimator->DrawCopy();

    TCanvas *canv_hist1D_QA_multALL = new TCanvas("canv_hist1D_QA_multALL","canv_hist1D_QA_multALL",50,50,700,600 );
    hist1D_QA_multALL->DrawCopy();


    // MULT BINNING:
    int nCentrBinsMult = 10;
    cout << "nCentrBins=" << nCentrBinsMult << endl;
    double *estBounds = new double[nCentrBinsMult]; // array to contain the quantiles
    getQuantiles(hist1D_QA_multALL, nCentrBinsMult, estBounds);
    drawCanvasWithClasses( hist1D_QA_multALL, "byMultTPC", nCentrBinsMult, estBounds );




    // ##########MAIN PLOTTING FOR CORRS:

    TGraphErrors *grNN [nCW][nEtaWins];
    TGraphErrors *grPtPt[nCW][nEtaWins];
    TGraphErrors *grPtN[nCW][nEtaWins];

    TGraphErrors *grFractEstByV0M[nCW];
    TGraphErrors *grFractEstByZDC[nCW];

    for ( int cW = 0; cW < nCW; cW++ )
    {
        grFractEstByV0M[cW] = new TGraphErrors;
        grFractEstByZDC[cW] = new TGraphErrors;
        for ( int etaW = 0; etaW < nEtaWins; etaW++ )
        {
            grNN[cW][etaW] = new TGraphErrors;
            grPtPt[cW][etaW] = new TGraphErrors;
            grPtN[cW][etaW] = new TGraphErrors;
        }
    }


    //calc (1) - occupancies in centr bins, (2) - corr coeffs
    for ( int cW = 0; cW < nCW; cW++ )
        for ( int cBin = 0; cBin < nCentrBins[cW]; cBin++ )
        {
            if ( cOccupancy[cW][cBin].nEventsV0M > 0 )
            {
                CentralityOccupancy *c = &cOccupancy[cW][cBin];
                float centr = c->cBinMin + (c->cBinMax - c->cBinMin)/2;
                float cRatio = 0;
                if (c->nEventsV0M>0)
                    cRatio = (float)c->nEventsV0M_and_ZDCZEM / c->nEventsV0M;
                grFractEstByV0M[cW]->SetPoint(grFractEstByV0M[cW]->GetN(), centr, cRatio);
                if (c->nEventsZDCZEM>0)
                    cRatio = (float)c->nEventsV0M_and_ZDCZEM / c->nEventsZDCZEM;
                grFractEstByZDC[cW]->SetPoint(grFractEstByZDC[cW]->GetN(), centr, cRatio);
            }
            for ( int etaW = 0; etaW < nEtaWins; etaW++ )
                for ( int phiW = 0; phiW < nPhiWins; phiW++ )
                {
                    WinPair *w = &wins[cW][cBin][etaW][phiW];
                    float centr = w->cBinMin + (w->cBinMax - w->cBinMin)/2;
                    w->calcCorrCoeffs();
                    if(0)cout << "cMin=" << w->cBinMin << ", cMax=" << w->cBinMax << ", etaW=" << etaW
                              << ", NN_bCorr= " << w->NN_bCorr
                              << ", PtPt_bCorr= " << w->PtPt_bCorr
                              << endl;

                    //fill graphs
                    TGraphErrors *gr;
                    //gr NN
                    gr = grNN[cW][etaW];
                    if ( fabs(w->NN_bCorr) < 10 )
                        gr->SetPoint(gr->GetN(), centr, w->NN_bCorr);
                    //gr PtPt
                    gr = grPtPt[cW][etaW];
                    if ( fabs(w->PtPt_bCorr) < 10 )
                        gr->SetPoint(gr->GetN(), centr, w->PtPt_bCorr);
                    //gr PtN
                    gr = grPtN[cW][etaW];
                    if ( fabs(w->PtN_bCorr) < 10 )
                        gr->SetPoint(gr->GetN(), centr, w->PtN_bCorr);

                }
        }

    int colors[] = { kBlack, kBlack, kBlue, kRed, kMagenta };
    int markers[] = { 20, 24, 5, 2, 21 };

    // NN
    TCanvas *canv_grNN = new TCanvas("canv_grNN","canv_grNN",20,50,700,600 );
    tuneCanvas(canv_grNN);
    grNN[0][0]->SetTitle( ";centrality percentile;b_{corr}" ); //C_{2}
    tuneGraphAxisLabels(grNN[0][0]);


    //centr 10
    drawGraph(grNN[0][0], 20, kBlack, "AP");
    //    drawGraph(grNN[0][1], 21, kBlack, "P");
    //    drawGraph(grNN[0][2], 22, kBlack, "P");

    for ( int cW = 1; cW < nCW; cW++ )
        drawGraph(grNN[cW][0], markers[cW], colors[cW], "P");

    grNN[0][0]->SetMinimum( 0 );

    TLegend *leg = new TLegend(0.65,0.65,0.999,0.95);
    leg->SetFillColor(kWhite);
    leg->SetFillStyle(0);
    leg->SetBorderSize(0);
    for ( int cW = 0; cW < nCW; cW++ )
        leg->AddEntry(grNN[cW][0], Form("class width %.1f", cWidths[cW]), "p");
    leg->Draw();

    TLatex *tex = new TLatex(0.7,0.4, "#eta_{gap}=0.8, #delta#eta=0.4");
    drawTex(tex, 0.045);

    tex = new TLatex(0.4,0.89, "NN");
    drawTex(tex, 0.045);


    TString strPostfix;

    if (flag_V0M_ZDC==0)
        strPostfix = Form("V0M.eps");
    else
        strPostfix = Form("ZDCZEM.eps");

    canv_grNN->SaveAs( Form("NN_%s", strPostfix.Data() ) );

    // PtPt
    TCanvas *canv_grPtPt = new TCanvas("canv_grPtPt","canv_grPtPt",250,50,700,600 );
    tuneCanvas(canv_grPtPt);
    grPtPt[0][0]->SetTitle( ";centrality percentile;b_{corr}" ); //C_{2}
    tuneGraphAxisLabels(grPtPt[0][0]);


    //centr 10
    drawGraph(grPtPt[0][0], 20, kBlack, "AP");
    //    drawGraph(grPtPt[0][1], 21, kBlack, "P");
    //    drawGraph(grPtPt[0][2], 22, kBlack, "P");

    for ( int cW = 1; cW < nCW; cW++ )
        drawGraph(grPtPt[cW][0], markers[cW], colors[cW], "P");

    grPtPt[0][0]->SetMinimum( 0 );

    leg = new TLegend(0.65,0.65,0.999,0.95);
    leg->SetFillColor(kWhite);
    leg->SetFillStyle(0);
    leg->SetBorderSize(0);
    for ( int cW = 0; cW < nCW; cW++ )
        leg->AddEntry(grPtPt[cW][0], Form("class width %.1f", cWidths[cW]), "p");
    leg->Draw();

    tex = new TLatex(0.7,0.4, "#eta_{gap}=0.8, #delta#eta=0.4");
    drawTex(tex, 0.045);

    tex = new TLatex(0.4,0.89, "PtPt");
    drawTex(tex, 0.045);


    canv_grNN->SaveAs( Form("PtPt_%s", strPostfix.Data() ) );

    // PtN
    TCanvas *canv_grPtN = new TCanvas("canv_grPtN","canv_grPtN",450,50,700,600 );
    tuneCanvas(canv_grPtN);
    grPtN[0][0]->SetTitle( ";centrality percentile;b_{corr}" ); //C_{2}
    tuneGraphAxisLabels(grPtN[0][0]);


    //centr 10
    drawGraph(grPtN[0][0], 20, kBlack, "AP");
    //    drawGraph(grPtN[0][1], 21, kBlack, "P");
    //    drawGraph(grPtN[0][2], 22, kBlack, "P");

    for ( int cW = 1; cW < nCW; cW++ )
        drawGraph(grPtN[cW][0], markers[cW], colors[cW], "P");

    grPtN[0][0]->SetMinimum( 0 );
    leg = new TLegend(0.65,0.65,0.999,0.95);
    leg->SetFillColor(kWhite);
    leg->SetFillStyle(0);
    leg->SetBorderSize(0);
    for ( int cW = 0; cW < nCW; cW++ )
        leg->AddEntry(grPtN[cW][0], Form("class width %.1f", cWidths[cW]), "p");
    leg->Draw();

    tex = new TLatex(0.7,0.4, "#eta_{gap}=0.8, #delta#eta=0.4");
    drawTex(tex, 0.045);

    tex = new TLatex(0.4,0.89, "PtN");
    drawTex(tex, 0.045);


    canv_grNN->SaveAs( Form("PtN_%s", strPostfix.Data() ) );



    TCanvas *canv_grPtN_2D = new TCanvas("canv_grPtN_2D","canv_grPtN_2D",450,50,700,600 );
    tuneCanvas(canv_grPtN_2D);


    //    wins[0][0][0][0].hist2D_PtN->DrawCopy();
    wins[0][0][0][0].hist2D_PtN->ProfileX()->DrawCopy();



    // CENTR ESTIMATOR EVENT RATIO:
    TCanvas *canv_grCentrRatio = new TCanvas("canv_grCentrRatio","canv_grCentrRatio",450,250,700,600 );
    tuneCanvas(canv_grCentrRatio);
    grFractEstByV0M[0]->SetTitle(";centrality percentile;ratio");
    tuneGraphAxisLabels(grFractEstByV0M[0]);
    //centr 10
    drawGraph(grFractEstByV0M[0], 20, kBlack, "AP");
    //    drawGraph(grFractEstByZDC[0], 20, kBlack, "L");

    for ( int cW = 1; cW < nCW; cW++ )
        drawGraph(grFractEstByV0M[cW], markers[cW], colors[cW], "P");

    leg = new TLegend(0.65,0.65,0.999,0.95,"ratio #frac{V0M-and-ZEMZDC}{V0M}");
    leg->SetFillColor(kWhite);
    leg->SetFillStyle(0);
    leg->SetBorderSize(0);

    for ( int cW = 0; cW < nCW; cW++ )
        leg->AddEntry(grFractEstByV0M[cW], Form("class width %.1f", cWidths[cW]), "p");
    leg->Draw();
    //    leg->SetHeader("ratio #frac{V0M-and-ZEMZDC}/{V0M}");

    canv_grCentrRatio->SaveAs("ratio_V0M-and-ZEMZDC_by_V0M.eps");

    // CENTR ESTIMATOR PERCENTILES QA:
    TCanvas *canv_estimatorPercentiles_QA = new TCanvas("canv_estimatorPercentiles_QA","canv_estimatorPercentiles_QA",50,350,700,600 );
    for ( int cBin = 0; cBin < nCentrBins[0]; cBin++ )
    {
        TH1D *h = wins[0][cBin][0][0].hist1D_EstimatorEntries;
        h->SetLineColor(kOrange-9+cBin);
        if ( cBin == 0 )
            h->DrawCopy();
        else
            h->DrawCopy("same");
    }


    // MULT F IN CENTR CLASSES QA:
    TCanvas *canv_mult_F_in_centr_QA = new TCanvas("canv_mult_F_in_centr_QA","canv_mult_F_in_centr_QA",50,400,700,600 );
    gPad->SetLogy();
    for ( int cBin = 0; cBin < nCentrBins[0]; cBin++ )
    {
        TH1D *h = wins[0][cBin][0][0].hist1D_multDistrF;
        h->SetLineColor(kOrange-9+cBin);

        if ( cBin == 0 )
        {
            h->SetLineColor(kRed);
            h->GetYaxis()->SetRangeUser(1,100000);
        }

        if ( cBin == 0 )
            h->DrawCopy();
        else
            h->DrawCopy("same");
    }


    // Check entries in centrality bins:
    for ( int cW = 0; cW < nCW; cW++ )
    {
        cout << " ###### cW = " << cW << endl;
        for ( int cBin = 0; cBin < nCentrBins[cW]; cBin++ )
        {
            TH1D *h = wins[cW][cBin][0][0].hist1D_multDistrF;
            cout << "cBin = " << h->GetEntries() << endl;
//            h->SetLineColor(kOrange-9+cBin);
//            if ( cBin == 0 )
//                h->DrawCopy();
//            else
//                h->DrawCopy("same");
        }
    }

    return;
}
Exemple #27
0
void DrawVelocity() {
  gStyle->SetOptFit(11111111);

  TFile* tfCosmic = new TFile("CosmicOut_V4.root");
  TTree* trCosmic = (TTree*)tfCosmic->Get("trOut");
  
  Double_t FitP1[2];
  Double_t FitP0[2];
  Double_t FitChisq[2];
  Int_t    CosmicTrigUp;
  Int_t    CosmicTrigDn;
  Double_t Theta;
  Double_t Roh;

  trCosmic->SetBranchAddress("FitP1"       ,FitP1 );
  trCosmic->SetBranchAddress("FitP0"       ,FitP0 );
  trCosmic->SetBranchAddress("FitChisq"    ,FitChisq);
  trCosmic->SetBranchAddress("CosmicTrigUp",&CosmicTrigUp);
  trCosmic->SetBranchAddress("CosmicTrigDn",&CosmicTrigDn);
  trCosmic->SetBranchAddress("Theta"       ,&Theta);
  trCosmic->SetBranchAddress("Roh"         ,&Roh);
  
  std::cout<< "Output" << std::endl;
  //TFile* tfHist = new TFile("CosmicOut_V4_TrigHist.root","recreate");
  TH1D* CosmicP1UpTrig[5];
  TH1D* CosmicP1Trig[5][5];
  TH1D* CosmicP1TrigLarge[5][5];

  for( int i = 0; i< 5; i++){
    CosmicP1UpTrig[i] = new TH1D( Form("CosmicP1UpTrig%d",i),
				  Form("CosmicP1UpTrig%d",i),
				  100,-0.01,0.01);
    for( int j = 0; j< 5; j++){
      CosmicP1Trig[i][j] = new TH1D( Form("CosmicP1_%d_%d",i,j),
				     Form("CosmicP1_%d_%d",i,j),
				     100,-0.01,0.01);
      CosmicP1TrigLarge[i][j] = new TH1D( Form("CosmicP1Large_%d_%d",i,j),
					  Form("CosmicP1Large_%d_%d",i,j),
					  100,-0.01,0.01);
    }
  }

  std::cout<< "LOOP" << std::endl;
  for( int ievent  = 0; ievent < trCosmic->GetEntries(); ievent++){
    trCosmic->GetEntry(ievent);
    if( TMath::Abs(Theta) < 5 ){ continue; }
    if( FitChisq[1] > 10 ){ continue; }
    CosmicP1UpTrig[ CosmicTrigUp ]->Fill( FitP1[1]*TMath::Cos(Theta*TMath::Pi()/180.));
    CosmicP1Trig[CosmicTrigUp][CosmicTrigDn]->Fill( FitP1[1]*TMath::Cos(Theta*TMath::Pi()/180.) );
    if( Roh > 600){
      CosmicP1TrigLarge[CosmicTrigUp][CosmicTrigDn]->Fill( FitP1[1]*TMath::Cos(Theta*TMath::Pi()/180.) );
    }
  }

  std::cout <<  "Draw" << std::endl;
  TGraphErrors* grSlope = new TGraphErrors();
  TGraphErrors* grDelta = new TGraphErrors();
  TGraphErrors* grSlopeLarge = new TGraphErrors();
  grSlope->SetMarkerStyle( 7 );
  grDelta->SetMarkerStyle( 7 );
  grSlopeLarge->SetMarkerStyle( 7 );
  TCanvas* can = new TCanvas("can","",1200,800);
  can->Divide(3,2);

  for( int i = 0; i< 5; i++){
    for( int j = 0; j< 5; j++){
      CosmicP1Trig[i][j]->Fit("gaus","Q","",
			      CosmicP1Trig[i][j]->GetMean()-CosmicP1Trig[i][j]->GetRMS(), 
			      CosmicP1Trig[i][j]->GetMean()+CosmicP1Trig[i][j]->GetRMS());
      TF1* func = CosmicP1Trig[i][j]->GetFunction("gaus");
      grSlope->SetPoint( grSlope->GetN(),i*5+j+1, func->GetParameter(1));
      grSlope->SetPointError( grSlope->GetN()-1, 0, func->GetParameter(2));
      CosmicP1TrigLarge[i][j]->Fit("gaus","Q","",
				   CosmicP1Trig[i][j]->GetMean()-1.5*CosmicP1Trig[i][j]->GetRMS(), 
				   CosmicP1Trig[i][j]->GetMean()+1.5*CosmicP1Trig[i][j]->GetRMS());
      func = CosmicP1TrigLarge[i][j]->GetFunction("gaus");
      grSlopeLarge->SetPoint( grSlopeLarge->GetN(), i*5+j+1, func->GetParameter(1));
      grSlopeLarge->SetPointError( grSlopeLarge->GetN()-1,0,func->GetParameter(2));
    }
  }

  for( int i = 0; i< 5; i++){
    can->cd( i +1 );
    CosmicP1UpTrig[i]->Draw();
    for( int j = 0; j < 5; j++){
      CosmicP1Trig[i][j]->SetLineColor(j+1);
      CosmicP1Trig[i][j]->Draw("same");
      CosmicP1TrigLarge[i][j]->Draw("same");
    }
  }
  double sol = 299.97;//[mm/ns]
  TLine* solLine = new TLine( -1, -1./sol, 25, -1./sol);
  //can->cd( 6 );


  TCanvas* can1 = new TCanvas("can1","",800,400);
  can1->Divide( 2,1);
  can1->cd(1);
  grSlope->GetXaxis()->SetRangeUser( -1, 25);  
  grSlope->Draw("AP");
  solLine->SetLineStyle(2);
  solLine->Draw("same");
  TCanvas* can2 = new TCanvas("can2","",1200,800);
  can2->Divide(3,2);
  for( int i = 0; i< 5; i++){
    can2->cd( i+1 );
    CosmicP1TrigLarge[i][0]->Draw();
    for( int j = 0; j< 5; j++){
      CosmicP1TrigLarge[i][j]->Draw("same");
    }
  }
  can2->cd(6);
  grSlopeLarge->Draw("AP");

  
  Double_t H_trig = 2800;
  Double_t R      = 1200;
  TGraph* grDelta1 = new TGraph();
  TGraph* grDelta2 = new TGraph();

  TGraphErrors * grVCluster = new TGraphErrors();

  for( int i = 0; i< 5; i++){
    for( int j  =0; j< 5; j++){
      Double_t iv_0 = TMath::Abs(grSlope->GetY()[ i*5 +j ]);
      Double_t ive_0 = grSlope->GetEY()[ i*5 + j];
      

      Double_t deltaZ = (i-j)*100*R/H_trig;//mm            

      Double_t EdeltaZ = TMath::Sqrt(2)*50*R/H_trig;

      Double_t l  = TMath::Sqrt( R*R + deltaZ*deltaZ);
      Double_t El = deltaZ*EdeltaZ/TMath::Sqrt( R*R + deltaZ*deltaZ); 
      Double_t delta_t0 = l/sol;
      Double_t delta_t1 = iv_0*R - delta_t0;
      Double_t Edelta_t1 = QuadSum(ive_0*R, El/sol);
      
      Double_t V_CsI = deltaZ / delta_t1;
      Double_t EV_CsI = QuadSum( EdeltaZ / delta_t1, Edelta_t1/delta_t1);

      Double_t delta_t1_adj = deltaZ/70.;
      Double_t delta_t1_adj1 = deltaZ/80.;
      Double_t delta_t1_adj2 = deltaZ/90.;
      
      grDelta->SetPoint(grDelta->GetN(), (delta_t0+delta_t1_adj)/R , iv_0);
      grDelta1->SetPoint(grDelta1->GetN(), (delta_t0+delta_t1_adj1)/R , iv_0);
      grDelta2->SetPoint(grDelta2->GetN(), (delta_t0+delta_t1_adj2)/R , iv_0);
      
      if( TMath::Abs(deltaZ) <= 2*EdeltaZ ){ continue; }
      grVCluster->SetPoint( grVCluster->GetN(), i*5+j+1 , V_CsI);
      grVCluster->SetPointError( grVCluster->GetN()-1 , 0, EV_CsI);
      
    }
  }
  can1->cd(2);
  grVCluster->SetMarkerStyle( 6);
  grVCluster->Draw("AP");
  
  grVCluster->Fit("pol0","","",0,26);
  /*
  grDelta1->SetMarkerColor(2);
  grDelta2->SetMarkerColor(3);
  grDelta1->SetMarkerStyle(6);
  grDelta2->SetMarkerStyle(6);


  can1->cd(2);
  grDelta->Draw("AP");
  grDelta1->Draw("P");
  grDelta2->Draw("P");
  
  TF1* func = new TF1("func","x",0,0.1);
  func->Draw("same");

  */


  /*
  for( int i = 0; i< 5; i++){
    CosmicP1UpTrig[i]->Write();
    for( int j  =0 ;j < 5; j++){
      CosmicP1Trig[i][j]->Write();
    }
  }

  tfHist->Close();
  */
}
int postprocessingSysError(){

  cout<<endl<<endl<<endl<<"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Postproccess all systematic uncertainties! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"<<endl<<endl;
  gErrorIgnoreLevel = 1001;

  const TString method  = "RMS99";
  const TString type    = "PFCHS";

  const int nEta =4;
  double eta_bins[5] = {0., 0.5, 1.1, 1.7, 2.3};
  // For looking at different systematic uncertainties independently
  const bool QCD    = true;
  const bool JEC    = true;
  const bool flavor = true;
  const bool PU     = true;
  const bool MC     = true;
  

  TString etaString, filename;   

  TString rootFiles, AuxString;  
  TString JetType = "PFCHS";
  TString Method  = "RMS99";   

  double *ratioEtaBinnedX  = new double[nEta];
  double *ratioEtaBinnedY  = new double[nEta];
  double *ratioEtaBinnedEX = new double[nEta];
  double *ratioEtaBinnedEY = new double[nEta];

  double *ratioEtaBinnedQCDUpY   = new double[nEta];
  double *ratioEtaBinnedQCDDownY = new double[nEta];

  TF1 *QCDuncertainty;

  if(QCD){
    rootFiles   = (TString) "scripts/plotsQCD/FinalErrorsQCD_" + type + (TString) "_" + method + (TString) ".root";
    TFile *_file = TFile::Open(rootFiles);    
    _file->GetObject("function",QCDuncertainty);
  }
  
  for(int eta = 0; eta < nEta; eta++){
    
    //cout<< endl<<endl<<endl<<eta+1<<". eta Bin!!"<<endl;

    // Read the MC and data results 
    rootFiles = (TString) "root_files_FINAL_data/Resolution_for_" + (long) (eta+1) + (TString) "_eta_bin_" + JetType + (TString) "_data_" + Method + (TString) ".root";
    TGraphErrors* JERData = readTGraphErrors(rootFiles,"Graph;1","Graph");
    rootFiles = (TString) "root_files_FINAL_mc/Resolution_for_" + (long) (eta+1) + (TString) "_eta_bin_" + JetType + (TString) "_mc_" + Method + (TString) ".root";
    TGraphErrors* JERMC = readTGraphErrors(rootFiles,"Graph","Graph");
    
    if(eta+1 == 1) etaString = Form("JER for |#eta| < %4.1f",etaBins[eta+1]);
    else           etaString = Form("JER for %4.1f <|#eta|< %4.1f",etaBins[eta+1],etaBins[eta+2]);
 
    //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    // 1.) Calculate the ratio w/o systematic Uncertainties  


    int nData    = JERData->GetN();

    double *dataX  = JERData->GetX();
    double *dataY  = JERData->GetY();
    double *dataEX = JERData->GetEX();
    double *dataEY = JERData->GetEY();
    
    double *mcX  = new double[nData];
    double *mcY  = new double[nData];
    double *mcEX = new double[nData];
    double *mcEY = new double[nData];
    
    double *ratioX  = new double[nData];
    double *ratioY  = new double[nData];
    double *ratioEX = new double[nData];
    double *ratioEY = new double[nData];


    //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    // Initialize some stuff for QCD uncertainty
    double *ratioQCDUpY    = new double[nData];
    double *ratioQCDDownY  = new double[nData];    
    //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

 
    int idx = 0;
    for(int i=0; i<nData; i++){

      JERMC   -> GetPoint(idx,mcX[i],mcY[i]);
      mcEX[i] = JERMC -> GetErrorX(idx);
      mcEY[i] = JERMC -> GetErrorY(idx);

      idx += 1;

      if(TMath::Abs(dataX[i]/mcX[i] - 1.) > 0.1){
	i -= 1;
	continue;
      }
     
      ratioX[i]  = 1./2.*(dataX[i] + mcX[i]);
      ratioY[i]  = dataY[i]/mcY[i];
      ratioEX[i] = 1./2.*TMath::Sqrt(TMath::Power(dataEX[i],2)+TMath::Power(mcEX[i],2));
      ratioEY[i] = TMath::Sqrt(TMath::Power((1./mcY[i]),2)*TMath::Power(dataEY[i],2)+TMath::Power((dataY[i]/(TMath::Power(mcY[i],2))),2)*TMath::Power(mcEY[i],2));
      if(QCD){
	// For QCD
	ratioQCDUpY[i]   = ratioY[i]*(1. + QCDuncertainty->Eval(ratioX[i]));
	ratioQCDDownY[i] = ratioY[i]*(1. - QCDuncertainty->Eval(ratioX[i]));
	//cout<<"QCDuncertainty->Eval(ratioX[i]) = "<<QCDuncertainty->Eval(ratioX[i])<<endl;
      }
    }
    
    TGraphErrors *Ratio = new TGraphErrors(nData,ratioX,ratioY,ratioEX,ratioEY);


    // For QCD
    TGraphErrors *QCDUp   = new TGraphErrors(nData,ratioX,ratioQCDUpY,ratioEX,ratioEY);
    TGraphErrors *QCDDown = new TGraphErrors(nData,ratioX,ratioQCDDownY,ratioEX,ratioEY);
    

    if(eta+1 == 1 ) AuxString = Form("Ratio between Data and MC for |#eta| < %4.1f",etaBins[eta+1]);
    else            AuxString = Form("Ratio between Data and MC for %4.1f <|#eta|<%4.1f",etaBins[eta+1],etaBins[eta+2]);
 
    Ratio -> SetTitle(AuxString); 
    Ratio -> GetXaxis() -> SetTitle("Photon pT");
    Ratio -> GetXaxis() -> SetTitleOffset(1.1); 
    Ratio -> GetYaxis() -> SetTitle("Ratio of JER (DATA/MC)");
    Ratio -> GetYaxis() -> SetTitleOffset(1.2);   
    Ratio -> GetXaxis() -> SetLimits(0,600);
    TF1* f1 = new TF1("name","pol0",0,600);   
    Ratio -> Fit("name","QR");
    

    TF1* fitQCDUp  = new TF1("fitQCDUp","pol0",0,600); 
    TF1* fitQCDDown = new TF1("fitQCDDown","pol0",0,600); 
    if(QCD){
      // For QCD
      QCDUp   -> Fit("fitQCDUp","QR");
      QCDDown -> Fit("fitQCDDown","QR");
    }
    
    TLegend *legend  = 0;
    legend = new TLegend(0.55,0.8,0.9,0.9);
    legend -> SetFillColor(0);

    legend -> SetHeader(Form(" %4.3f #pm %4.3f", f1 -> GetParameter(0), f1->GetParError(0)));
    TCanvas *c11 = new TCanvas("c11",AuxString,200,10,500,500);
    c11 -> cd();
    Ratio -> SetMinimum(0.5);
    Ratio -> SetMaximum(2.0);
  
    Ratio  -> Draw("AP"); 
    legend -> Draw("same");
  
    TLatex*  info   = new TLatex();
    info-> SetNDC();
    info->SetTextSize(0.045); 
    info->DrawLatex(0.22,0.84,Form("#splitline{#chi^{2} = %4.2f}{dof = %i}",f1 -> GetChisquare(),f1 -> GetNDF()));
  
    filename = (TString) "plots/Ratio_Resolution_for_" + (long) (eta+1) + (TString) "_eta_bin_" + type + (TString) "_data_comparison_" + method + (TString) ".pdf";
    c11 -> SaveAs(filename);
    delete c11;
    
    ratioEtaBinnedX[eta]  = (eta_bins[eta+1] + eta_bins[eta])/2.; 
    ratioEtaBinnedY[eta]  = f1 -> GetParameter(0);
    ratioEtaBinnedEX[0]=0.25;
    ratioEtaBinnedEX[1]=0.3;
    ratioEtaBinnedEX[2]=0.3;
    ratioEtaBinnedEX[3]=0.3;
    ratioEtaBinnedEY[eta] = f1->GetParError(0);

    if(QCD){
      ratioEtaBinnedQCDUpY[eta]  = fitQCDUp   -> GetParameter(0);
      ratioEtaBinnedQCDDownY[eta]= fitQCDDown -> GetParameter(0);



      // Some additional stuff for QCD uncertainty
      TCanvas *plotsQCD = new TCanvas("plotsQCD","plotsQCD",200,10,500,500);
      plotsQCD -> cd();

      Ratio -> SetMarkerColor(1);
      Ratio -> SetLineColor(1);
      Ratio -> SetMarkerStyle(20);
      Ratio -> GetFunction("name")->SetLineColor(1);
      QCDUp -> SetMarkerColor(3);
      QCDDown -> SetMarkerColor(3);
      QCDUp  -> SetLineColor(3);
      QCDDown  -> SetLineColor(3);
      QCDUp -> SetMarkerStyle(20);
      QCDDown -> SetMarkerStyle(20);
      QCDUp -> SetMarkerSize(0.8);
      QCDDown -> SetMarkerSize(0.8);
      QCDUp   -> GetFunction("fitQCDUp")->SetLineColor(3);
      QCDDown -> GetFunction("fitQCDDown")->SetLineColor(3);
      Ratio -> Draw("AP");
      QCDUp -> Draw("sameP");
      QCDDown -> Draw("sameP");

      delete legend;
      legend = new TLegend(0.4,0.8,0.9,0.9);
      legend -> SetFillColor(0);
      legend -> SetTextSize(0.045);
      legend -> AddEntry(Ratio,"Central Value","l");
      legend -> AddEntry(QCDUp,Form("Upward variation: + %4.3f",abs(ratioEtaBinnedQCDUpY[eta]/ratioEtaBinnedY[eta]-1.)),"l");
      legend -> AddEntry(QCDDown,Form("Downward variation: - %4.3f",abs(ratioEtaBinnedQCDDownY[eta]/ratioEtaBinnedY[eta]-1.)),"l");
   
      legend -> Draw("same");
      filename = (TString) "plots/plotsQCD_for_" + (long) (eta+1) + (TString) "_bin_"  + type + (TString) "_" + method + (TString) ".pdf";
      plotsQCD -> SaveAs(filename);
      delete plotsQCD;
    }


  }

  TGraphErrors* ratioEtaBinned = new TGraphErrors(nEta,ratioEtaBinnedX,ratioEtaBinnedY,ratioEtaBinnedEX,ratioEtaBinnedEY);
  filename = (TString) "plots/RatioEtaBinned_" + type + (TString) "_" + method + (TString) ".root";
  TFile *f = new TFile(filename,"RECREATE");
  f -> WriteTObject(ratioEtaBinned,"Graph");
  f->Close();
  delete f;

  //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  // 1.) Calculate sys Error from QCD contamination
  //cout<<endl;
    
  double deltaRatioUpQCD[nEta]      = {0.};
  double deltaRatioDownQCD[nEta]    = {0.};
 
  if(QCD){
    
    for(int eta = 0; eta<nEta; eta++){

      deltaRatioUpQCD[eta]     = abs(ratioEtaBinnedQCDUpY[eta]/ratioEtaBinnedY[eta]-1.); 
      deltaRatioDownQCD[eta]   = abs(ratioEtaBinnedQCDDownY[eta]/ratioEtaBinnedY[eta]-1.); 
      
      //cout<<"ratioEtaBinnedQCDDownY[eta]"<<ratioEtaBinnedQCDDownY[eta]<<endl;
      //cout<<"ratioEtaBinnedY[eta]"<<ratioEtaBinnedY[eta]<<endl;
      //cout<<"deltaRatioUpQCD["<<eta<<"] = "<<deltaRatioUpQCD[eta]<<endl;
      //cout<<"deltaRatioDownQCD["<<eta<<"] = "<<deltaRatioDownQCD[eta]<<endl;
    }

  } 
  
  

  //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  // 2.) Calculate sys Error from JEC uncertainty (percentage change of MC result)
  //cout<<endl;

  double deltaRatioUpJEC[nEta]      = {0.};
  double deltaRatioDownJEC[nEta]    = {0.};
    
  if(JEC){

    rootFiles                          = (TString) "scripts/plotsJEC/FinalEtaBinnedErrorsJECUp_" + type + (TString) "_" + method + (TString) ".root"; 
    TGraphErrors *JECuncertaintyUp  = readTGraphErrors(rootFiles,"graph","Graph");
    double       *sysRelJECUp       = JECuncertaintyUp -> GetY();

    rootFiles                          = (TString) "scripts/plotsJEC/FinalEtaBinnedErrorsJECLow_" + type + (TString) "_" + method + (TString) ".root"; 
    TGraphErrors *JECuncertaintyLow = readTGraphErrors(rootFiles,"graph","Graph");
    double       *sysRelJECLow      = JECuncertaintyLow -> GetY();
      
    for(int eta = 0; eta<nEta; eta++){

      deltaRatioUpJEC[eta]   = sysRelJECUp[eta];
      deltaRatioDownJEC[eta] = sysRelJECLow[eta];

      //cout<<"deltaRatioUpJEC["<<eta<<"] = "<<deltaRatioUpJEC[eta]<<endl;
      //cout<<"deltaRatioDownJEC["<<eta<<"] = "<<deltaRatioDownJEC[eta]<<endl;     

    }

  }
 
  //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  // 3.) Calculate sys Error from Flavor uncertainty (percentage change of MC result)
  //cout<<endl;
  
  // Multiply on mc (as symmetric Error)
  // ratioUp  = 1/(1 - delta) * ratio
  // ratioLow = 1/(1 + delta) * ratio

  double deltaRatioUpFlavor[nEta]      = {0.};
  double deltaRatioDownFlavor[nEta]    = {0.};

  if(flavor){

    rootFiles                          = (TString) "scripts/plotsFlavor/FinalEtaBinnedErrorsFlavorUp_" + type + (TString) "_" + method + (TString) ".root"; 
    TGraphErrors *FlavoruncertaintyUp  = readTGraphErrors(rootFiles,"graph","Graph");
    double       *sysRelFlavorUp       = FlavoruncertaintyUp -> GetY();
    
    rootFiles                          = (TString) "scripts/plotsFlavor/FinalEtaBinnedErrorsFlavorLow_" + type + (TString) "_" + method + (TString) ".root"; 
    TGraphErrors *FlavoruncertaintyLow = readTGraphErrors(rootFiles,"graph","Graph");
    double       *sysRelFlavorLow      = FlavoruncertaintyLow -> GetY();
  
    
    for(int eta = 0; eta<nEta; eta++){

      deltaRatioUpFlavor[eta]   = sysRelFlavorUp[eta];
      deltaRatioDownFlavor[eta] = sysRelFlavorLow[eta];

      //cout<<"deltaRatioUpFlavor["<<eta<<"] = "<<deltaRatioUpFlavor[eta]<<endl;
      //cout<<"deltaRatioDownFlavor["<<eta<<"] = "<<deltaRatioDownFlavor[eta]<<endl;
    }

  }
 
  //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  // 4.) Calculate sys Error from PU uncertainty (percentage change of MC result)
  //cout<<endl;

  double deltaRatioUpPU[nEta]      = {0.};
  double deltaRatioDownPU[nEta]    = {0.};
  
  if(PU){
    
    rootFiles                          = (TString) "scripts/plotsPU/FinalEtaBinnedErrorsPUUp_" + type + (TString) "_" + method + (TString) ".root"; 
    TGraphErrors *PUuncertaintyUp  = readTGraphErrors(rootFiles,"graph","Graph");
    double       *sysRelPUUp       = PUuncertaintyUp -> GetY();

    rootFiles                          = (TString) "scripts/plotsPU/FinalEtaBinnedErrorsPULow_" + type + (TString) "_" + method + (TString) ".root"; 
    TGraphErrors *PUuncertaintyLow = readTGraphErrors(rootFiles,"graph","Graph");
    double       *sysRelPULow      = PUuncertaintyLow -> GetY();
  
    // Multiply on mc (as symmetric Error)
    // ratioUp = 1/(1 - delta) * ratio
    // ratioUp = 1/(1 + delta) * ratio
        
    for(int eta = 0; eta<nEta; eta++){
    
      deltaRatioUpPU[eta]   = sysRelPUUp[eta];
      deltaRatioDownPU[eta] = sysRelPULow[eta];

      //cout<<"deltaRatioUpPU["<<eta<<"] = "<<deltaRatioUpPU[eta]<<endl;
      //cout<<"deltaRatioDownPU["<<eta<<"] = "<<deltaRatioDownPU[eta]<<endl;
    }

  } 
  
  //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  // 5.) Calculate sys Error from Out-of Cone showering simulation (percentage change of full ratio result)
  //cout<<endl;
  
  double deltaRatioUpMC[nEta]      = {0.};
  double deltaRatioDownMC[nEta]    = {0.};
  

  if(MC){

    rootFiles                   = (TString) "scripts/plotsMC/FinalErrorsMC_" + type + (TString) "_" + method + (TString) ".root";  
    TGraphErrors *MCuncertainty = readTGraphErrors(rootFiles,"graph","Graph");
    double       *sysRelMC      = MCuncertainty -> GetY();
  
    // Percentage change is only in one direction, to take this into account keep deltaRatioDownMC = 0

    for(int eta = 0; eta<nEta; eta++){

      deltaRatioUpMC[eta]   = sysRelMC[eta];
      deltaRatioDownMC[eta] = sysRelMC[eta];

      //cout<<"deltaRatioUpMC["<<eta<<"] = "<<deltaRatioUpMC[eta]<<endl;
      //cout<<"deltaRatioDownMC["<<eta<<"] = "<<deltaRatioDownMC[eta]<<endl;
    }

  } 
  
  //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  // Take all systematic Uncertainties together and plot
  //cout<<endl;

  double *deltaTotalSysUp   = new double[nEta];
  double *deltaTotalSysDown = new double[nEta];
  double *DeltaTotalSysUp   = new double[nEta];
  double *DeltaTotalSysDown = new double[nEta];
  double *DeltaTotalDown = new double[nEta];
  double *DeltaTotalUp = new double[nEta];
  for(int eta = 0; eta<nEta; eta++){

    // Add all systematic Uncertainties in quadrature (delta is relative Uncertainty)
    deltaTotalSysUp[eta]   = sqrt(TMath::Power(deltaRatioUpJEC[eta],2)   + TMath::Power(deltaRatioUpFlavor[eta],2)   + TMath::Power(deltaRatioUpPU[eta],2)   +                                                               TMath::Power(deltaRatioUpMC[eta],2)    + TMath::Power(deltaRatioUpQCD[eta],2));
    deltaTotalSysDown[eta] = sqrt(TMath::Power(deltaRatioDownJEC[eta],2) + TMath::Power(deltaRatioDownFlavor[eta],2) + TMath::Power(deltaRatioDownPU[eta],2) +                                                               TMath::Power(deltaRatioDownMC[eta],2)  + TMath::Power(deltaRatioDownQCD[eta],2));

    // Calculation of the absolute Uncertainty with Delta = ratio * delta
    DeltaTotalSysUp[eta]   = deltaTotalSysUp[eta] * ratioEtaBinnedY[eta];
    DeltaTotalSysDown[eta] = deltaTotalSysDown[eta] * ratioEtaBinnedY[eta];

    // Calculate Systematic plus staistical Uncertainty
    DeltaTotalUp[eta] = sqrt(pow(DeltaTotalSysUp[eta],2) + pow(ratioEtaBinnedEY[eta],2));
    DeltaTotalDown[eta] = sqrt(pow(DeltaTotalSysDown[eta],2) + pow(ratioEtaBinnedEY[eta],2));

    cout<<endl<<"relative: deltaTotalSysUp["<<eta<<"]   = "<<fixed<<setprecision(3)<<deltaTotalSysUp[eta]<<endl;
    cout<<"relative: deltaTotalSysDown["<<eta<<"] = "<<deltaTotalSysDown[eta]<<endl;

    cout<<endl<<"absolute: DeltaTotalSysUp["<<eta<<"]   = "<<DeltaTotalSysUp[eta]<<endl;
    cout<<"absolute: DeltaTotalSysDown["<<eta<<"] = "<<DeltaTotalSysDown[eta]<<endl;


  }

  double ex[nEta] ={0.25,0.3,0.3,0.3};

  TGraphAsymmErrors* ratioEtaBinnedSys = new TGraphAsymmErrors(nEta,ratioEtaBinnedX,ratioEtaBinnedY,ex,ex,DeltaTotalSysDown,DeltaTotalSysUp);

  double *TotalSysUp   = new double[nEta];
  double *TotalSysDown = new double[nEta];
 

  for(int i=0; i<nEta; i++){
    TotalSysUp[i]   = ratioEtaBinnedY[i]+DeltaTotalSysUp[i];
    TotalSysDown[i] = ratioEtaBinnedY[i]-DeltaTotalSysDown[i];
  }

  TGraph* ratioSysBorderUp   = new TGraph(nEta, ratioEtaBinnedX, TotalSysUp);
  TGraph* ratioSysBorderDown = new TGraph(nEta, ratioEtaBinnedX, TotalSysDown);

  TGraph* ratioRelativeErrorsUp   = new TGraph(nEta,ratioEtaBinnedX,deltaTotalSysUp);
  TGraph* ratioRelativeErrorsDown = new TGraph(nEta,ratioEtaBinnedX,deltaTotalSysDown);


  TGraphErrors* ratioEtaBinnedStat = new TGraphErrors(nEta,ratioEtaBinnedX,ratioEtaBinnedY,ratioEtaBinnedEX,ratioEtaBinnedEY);
  TGraphAsymmErrors* ratioEtaBinnedStatPlusSys = new TGraphAsymmErrors(nEta,ratioEtaBinnedX,ratioEtaBinnedY,ex,ex,DeltaTotalDown,DeltaTotalUp);
  
  TCanvas *cFinal = new TCanvas("cFinal","cFinal",200,10,500,500);
  cFinal -> cd();  
  
  ratioEtaBinnedSys -> GetYaxis() -> SetTitle("Data/MC ratio for JER");
  ratioEtaBinnedSys -> GetXaxis() -> SetTitle("|#eta|");

  if(PU  && flavor  && JEC  && MC && QCD)    etaString  = "All sys. Uncertainties";
  else if(PU  && !flavor && !JEC && !MC && !QCD)  etaString = "Only PU uncert.";
  else if(!PU && flavor  && !JEC && !MC && !QCD)  etaString = "Only flavor uncert.";
  else if(!PU && !flavor && JEC  && !MC && !QCD)  etaString = "Only JEC uncert.";
  else if(!PU && !flavor && !JEC && MC && !QCD)   etaString = "Only Out-of-Cone sim. uncert.";
  else if(!PU && !flavor && !JEC && MC && !QCD)   etaString = "Only Out-of-Cone sim. uncert.";
  else if(!PU && !flavor && !JEC && !MC && QCD)   etaString = "Only QCD uncert.";
  else if(PU && flavor && JEC && !MC && QCD)      etaString = "All besides MC uncertainty.";
  else etaString = "Strange set of systematic uncertainties.";
  cout<<endl<<etaString<<endl<<endl;
  
  ratioEtaBinnedSys -> SetMarkerStyle(20);
  ratioEtaBinnedSys -> SetMarkerSize(1.4);
  ratioEtaBinnedSys -> SetFillColor(kGray);
  ratioEtaBinnedSys -> SetFillStyle(3001);
  ratioEtaBinnedSys -> SetLineColor(kGray);
  ratioEtaBinnedSys -> SetMinimum(0.8);
  ratioEtaBinnedSys -> SetMaximum(1.5);
  ratioEtaBinnedSys -> GetXaxis() -> SetLimits(0., 2.3);
  ratioEtaBinnedSys -> GetXaxis() -> SetNdivisions(6,6,0, "X");
  ratioEtaBinnedSys -> DrawClone("Ae3p");
  
  //ratioEtaBinnedSys -> SetPointError(0, 0., 0., 0., 0.);
  //ratioEtaBinnedSys -> SetPointError(1, 0., 0., 0., 0.);
  //ratioEtaBinnedSys -> SetPointError(2, 0., 0., 0., 0.);
  //ratioEtaBinnedSys -> SetPointError(3, 0., 0., 0., 0.);
  //ratioEtaBinnedSys -> SetPointError(4, 0., 0., 0., 0.);


  ratioEtaBinnedStat -> SetMarkerStyle(20);
  ratioEtaBinnedStat -> SetMarkerSize(1.4);
  ratioEtaBinnedStat -> SetFillColor(kGray);
  ratioEtaBinnedStat -> SetFillStyle(3001);
  ratioEtaBinnedStat -> SetLineColor(1);
  ratioEtaBinnedStat -> Draw("psame");
  
 
  TLatex *infoFinal   = new TLatex();
  infoFinal -> SetTextFont(132);
  infoFinal -> SetNDC();
  infoFinal -> SetTextSize(0.045);
  infoFinal -> DrawLatex(0.2,0.8,etaString);

  filename = (TString) "plots/FinalErrorPlot_" + type + (TString) "_" + method + (TString) ".pdf";
  cFinal -> Print(filename,"pdf");
  filename = (TString) "plots/FinalErrorPlot_" + type + (TString) "_" + method + (TString) ".pdf";
  cFinal -> SaveAs(filename,"pdf");
  delete cFinal;


  filename = (TString) "plots/FinalRelativeErrorsUp_" + type + (TString) "_" + method + (TString) ".root"; 
  f = new TFile(filename,"RECREATE");
  f -> WriteTObject(ratioRelativeErrorsUp,"graph");
  f->Close();
  delete f;
  filename = (TString) "plots/FinalRelativeErrorsLow_" + type + (TString) "_" + method + (TString) ".root"; 
  f = new TFile(filename,"RECREATE");
  f -> WriteTObject(ratioRelativeErrorsDown,"graph");
  f->Close();
  delete f;

  
  ofstream RelativeErrors;
  RelativeErrors.open("plots/Errors.txt");
  
  RelativeErrors<<"Relative Errors: "<<endl;
  for(int i=0; i<nEta; i++){
    RelativeErrors<<i+1<<". Eta bin:    "<<"-"<<fixed<<setprecision(3)<<(deltaTotalSysDown[i]*100)<<"% / +"<<(deltaTotalSysUp[i]*100)<<"%"<<endl;
  }

  RelativeErrors<<endl<<"Absolute Errors: "<<endl;
  for(int i=0; i<nEta; i++){
    RelativeErrors<<i+1<<". Eta bin:    "<<"-"<<(DeltaTotalSysDown[i])<<" / +"<<(DeltaTotalSysUp[i])<<endl;
  }

  RelativeErrors<<endl<<endl<<"Relative Errors JEC: "<<endl;
  for(int i=0; i<nEta; i++){
    RelativeErrors<<i+1<<". Eta bin:    "<<"-"<<(deltaRatioDownJEC[i]*100)<<"% / +"<<(deltaRatioUpJEC[i]*100)<<"%"<<endl;
  }
  RelativeErrors<<endl<<endl<<"Relative Errors Flavor: "<<endl;
  for(int i=0; i<nEta; i++){
    RelativeErrors<<i+1<<". Eta bin:    "<<"-"<<(deltaRatioDownFlavor[i]*100)<<"% / +"<<(deltaRatioUpFlavor[i]*100)<<"%"<<endl;
  }
  RelativeErrors<<endl<<endl<<"Relative Errors Out-of-Cone showering simulation: "<<endl;
  for(int i=0; i<nEta; i++){
    RelativeErrors<<i+1<<". Eta bin:    "<<"-"<<(deltaRatioDownMC[i]*100)<<"% / +"<<(deltaRatioUpMC[i]*100)<<"%"<<endl;
  }
  RelativeErrors<<endl<<endl<<"Relative Errors QCD: "<<endl;
  for(int i=0; i<nEta; i++){
    RelativeErrors<<i+1<<". Eta bin:    "<<"-"<<(deltaRatioDownQCD[i]*100)<<"% / +"<<(deltaRatioUpQCD[i]*100)<<"%"<<endl;
  }
  RelativeErrors<<endl<<endl<<"Relative Errors PU reweighing: "<<endl;
  for(int i=0; i<nEta; i++){
    RelativeErrors<<i+1<<". Eta bin:    "<<"-"<<(deltaRatioDownPU[i]*100)<<"% / +"<<(deltaRatioUpPU[i]*100)<<"%"<<endl;
  }

  RelativeErrors<<endl<<endl<<"Central values and statistical Uncertainty: "<<endl;
  for(int i=0; i<nEta; i++){
    RelativeErrors<<i+1<<". Eta bin:    "<<"-"<<(ratioEtaBinnedY[i])<<" +/- "<<ratioEtaBinnedEY[i]<<endl;
  }

  RelativeErrors.close();

 
  // Write directly full latex table with systematic and statistical unceratinty

  ofstream latexTable;
  latexTable.open("plots/latexTable.txt");


  latexTable<<"\\renewcommand{\\arraystretch}{2.0}"<<endl;
  latexTable<<"\\begin{center}"<<endl;
  latexTable<<"\\begin{tabular}{ | c | c   c c| }"<<endl;
  latexTable<<"$|\\eta^{\\text{Jet}}|$ & Ratio &  stat.      & sys.  \\\\\\hline"<<endl;
  for(int z=0;z<nEta;z++){
    latexTable<<"$"<<fixed<<setprecision(1)<<etaBins[z]<<" - "<<etaBins[z+1]<<"$ &"<<fixed<<setprecision(3)<<ratioEtaBinnedY[z]<<" & $\\pm "<<ratioEtaBinnedEY[z]<<"$ & $^{+"<<DeltaTotalSysUp[z]<<"}_{-"<<DeltaTotalSysDown[z]<<"}$ \\\\"<<endl;
  }
  latexTable<<"\\hline"<<endl;
  latexTable<<"\\end{tabular}"<<endl;
  latexTable<<"\\end{center}"<<endl<<endl<<endl<<endl<<endl;

 


  
  latexTable<<"\\begin{center}"<<endl;
  latexTable<<"\\begin{tabular}{ l| c | c | c | c |}"<<endl;
  latexTable<<"\\multicolumn{1}{c}{} & \\multicolumn{4}{c}{$|\\eta^{\\text{Jet}}|$}\\\\\\hline"<<endl<<fixed<<setprecision(1);
  for(int z=0;z<nEta;z++) latexTable<<"& \\textbf{"<<etaBins[z]<<" - "<<etaBins[z+1]<<"}";
  latexTable<<"\\\\\\hline"<<endl;
  latexTable<<"\\multirow{2}{*}{\\textbf{Multijet contamination}}";
  for(int z=0;z<nEta;z++) latexTable<<"& $+"<<deltaRatioUpQCD[z]*100<<" \\% $ ";
  latexTable<<"\\\\"<<endl;
  for(int z=0;z<nEta;z++) latexTable<<"& $-"<<deltaRatioDownQCD[z]*100<<" \\% $ ";
  latexTable<<"\\\\\\hline"<<endl;
  latexTable<<"\\multirow{2}{*}{\\textbf{Flavor uncertainty}}";
  for(int z=0;z<nEta;z++) latexTable<<"& $+"<<deltaRatioUpFlavor[z]*100<<" \\% $ ";
  latexTable<<"\\\\"<<endl;
  for(int z=0;z<nEta;z++) latexTable<<"& $"<<deltaRatioDownFlavor[z]*100<<" \\% $ ";
latexTable<<"\\\\\\hline"<<endl;
  latexTable<<"\\multirow{2}{*}{\\textbf{JEC uncertainty}}";
  for(int z=0;z<nEta;z++) latexTable<<"& $+"<<deltaRatioUpJEC[z]*100<<" \\% $ ";
  latexTable<<"\\\\"<<endl;
  for(int z=0;z<nEta;z++) latexTable<<"& $"<<deltaRatioDownJEC[z]*100<<" \\% $ ";
latexTable<<"\\\\\\hline"<<endl;
  latexTable<<"\\multirow{2}{*}{\\textbf{Out-of-Cone showering simulation}}";
  for(int z=0;z<nEta;z++) latexTable<<"& $+"<<deltaRatioUpMC[z]*100<<" \\% $ ";
  latexTable<<"\\\\"<<endl;
  for(int z=0;z<nEta;z++) latexTable<<"& $-"<<deltaRatioDownMC[z]*100<<" \\% $ ";
  latexTable<<"\\\\\\hline"<<endl;
  latexTable<<"\\multirow{2}{*}{\\textbf{PU uncertainty}}";
  for(int z=0;z<nEta;z++) latexTable<<"& $+"<<deltaRatioUpPU[z]*100<<" \\% $ ";
  latexTable<<"\\\\"<<endl;
  for(int z=0;z<nEta;z++) latexTable<<"& $"<<deltaRatioDownPU[z]*100<<" \\% $ ";
  latexTable<<"\\\\\\hline\\hline"<<endl;
  latexTable<<"\\multirow{2}{*}{\\textbf{Total}}";
  for(int z=0;z<nEta;z++) latexTable<<"& $+"<<deltaTotalSysUp[z]*100<<" \\% $ ";
  latexTable<<"\\\\"<<endl;
  for(int z=0;z<nEta;z++) latexTable<<"& $-"<<deltaTotalSysDown[z]*100<<" \\% $ ";
  latexTable<<"\\\\\\hline"<<endl;

  latexTable<<"\\end{tabular}"<<endl;
  latexTable<<"\\end{center}"<<endl;


 latexTable.close();





  //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  // Comparison to 2011 Data 
  cout<<endl; 

  gROOT->LoadMacro("tdrstyle_mod14.C");
  setTDRStyle();

  gROOT->LoadMacro("CMS_lumi.C");

  writeExtraText = true;       // if extra text
  extraText  = "Preliminary";  // default extra text is "Preliminary"
  lumi_8TeV  = "19.7 fb^{-1}"; // default is "19.7 fb^{-1}"
  lumi_7TeV  = "4.9 fb^{-1}";  // default is "5.1 fb^{-1}"

  int iPeriod = 2;    // 1=7TeV, 2=8TeV, 3=7+8TeV, 7=7+8+13TeV 
  
  gStyle->SetHatchesLineWidth(1);
  gStyle->SetHatchesSpacing(2.2);   
  //-----------------------------------------------------

  TCanvas *cFinal2 = new TCanvas("cFinal2","cFinal2",200,10,1000,1000);
  cFinal2 -> cd();  

  double x_2011[4];
  x_2011[0]=0.25;
  x_2011[1]=0.80;
  x_2011[2]=1.40;
  x_2011[3]=2.00;
  double y_2011[4];
  y_2011[0]=1.052;
  y_2011[1]=1.057;
  y_2011[2]=1.096;
  y_2011[3]=1.134;
  double yErrStat_2011[4];
  yErrStat_2011[0]=0.012;
  yErrStat_2011[1]=0.012;
  yErrStat_2011[2]=0.017;
  yErrStat_2011[3]=0.035;
  double yErrSysHigh_2011[4];
  yErrSysHigh_2011[0]=0.062;
  yErrSysHigh_2011[1]=0.056;
  yErrSysHigh_2011[2]=0.063;
  yErrSysHigh_2011[3]=0.087;
  double yErrSysLow_2011[4];
  yErrSysLow_2011[0]=0.061;
  yErrSysLow_2011[1]=0.055;
  yErrSysLow_2011[2]=0.062;
  yErrSysLow_2011[3]=0.085;
  double xErrLow_2011[4];
  xErrLow_2011[0]=0.25;
  xErrLow_2011[1]=0.3;
  xErrLow_2011[2]=0.3;
  xErrLow_2011[3]=0.3;
  double xErrHigh_2011[4];
  xErrHigh_2011[0]=0.25;
  xErrHigh_2011[1]=0.3;
  xErrHigh_2011[2]=0.3;
  xErrHigh_2011[3]=0.3;

  double yErrTotalHigh_2011[4];
  double yErrTotalLow_2011[4];

  for(int i=0; i<4; i++){

    yErrTotalHigh_2011[i]=sqrt(pow(yErrStat_2011[i],2) + pow(yErrSysHigh_2011[i],2));
    yErrTotalLow_2011[i]=sqrt(pow(yErrStat_2011[i],2) + pow(yErrSysLow_2011[i],2));


  }

  TGraphAsymmErrors *Res_2011_stat = new TGraphAsymmErrors(4,x_2011,y_2011,xErrLow_2011,xErrHigh_2011,yErrStat_2011,yErrStat_2011);
  Res_2011_stat->SetName("Res_2011_stat");
  TGraphAsymmErrors *Res_2011_sys  = new TGraphAsymmErrors(4,x_2011,y_2011,xErrLow_2011,xErrHigh_2011,yErrSysLow_2011,yErrSysHigh_2011);
  Res_2011_sys->SetName("Res_2011_sys");
  TGraphAsymmErrors *Res_2011_total  = new TGraphAsymmErrors(4,x_2011,y_2011,xErrLow_2011,xErrHigh_2011,yErrTotalLow_2011,yErrTotalHigh_2011);
  Res_2011_sys->SetName("Res_2011_total");
  
  //-----------------------------------------------------
  ratioEtaBinnedStatPlusSys -> GetXaxis() -> SetTitle("|#eta|");
  ratioEtaBinnedStatPlusSys -> GetXaxis() -> SetRangeUser(0., 2.3);
  ratioEtaBinnedStatPlusSys -> GetYaxis() -> SetTitle("Data/MC ratio for JER");
  ratioEtaBinnedSys -> GetXaxis() -> SetTitle("|#eta|");
  ratioEtaBinnedSys -> GetXaxis() -> SetRangeUser(0., 2.3);
  ratioEtaBinnedSys -> GetYaxis() -> SetTitle("Data/MC ratio for JER");
  ratioEtaBinnedStat -> GetXaxis() -> SetTitle("|#eta|");
  ratioEtaBinnedStat -> GetXaxis() -> SetRangeUser(0., 2.3);
  ratioEtaBinnedStat -> GetYaxis() -> SetTitle("Data/MC ratio for JER");
  ratioEtaBinnedStat -> GetYaxis() -> SetRangeUser(0.8, 1.6);
  Res_2011_stat -> GetXaxis() -> SetTitle("|#eta|");
  Res_2011_stat -> GetXaxis() -> SetLimits(0., 2.3);
  Res_2011_stat -> GetXaxis() -> SetNdivisions(505, "X");
  Res_2011_stat -> GetYaxis() -> SetTitle("Data/MC ratio for JER");
  Res_2011_sys -> GetXaxis() -> SetTitle("|#eta|");
  Res_2011_sys -> GetXaxis() -> SetLimits(0., 2.3);
  Res_2011_sys -> GetXaxis() -> SetNdivisions(505, "X");
  Res_2011_sys -> GetYaxis() -> SetTitle("Data/MC ratio for JER");
  Res_2011_total -> GetXaxis() -> SetTitle("|#eta|");
  Res_2011_total -> GetXaxis() -> SetLimits(0., 2.3);
  Res_2011_total -> GetXaxis() -> SetNdivisions(505, "X");
  Res_2011_total -> GetYaxis() -> SetTitle("Data/MC ratio for JER");
  Res_2011_total -> GetYaxis() -> SetRangeUser(0.8, 1.5);


  ratioEtaBinnedStatPlusSys -> SetMarkerStyle(20); 
  ratioEtaBinnedStatPlusSys -> SetMarkerSize(2.0);
  ratioEtaBinnedStatPlusSys -> SetLineColor(kPink-8);
  ratioEtaBinnedStatPlusSys -> SetLineWidth(2);
  ratioEtaBinnedStatPlusSys -> SetMarkerColor(kPink-8);
  ratioEtaBinnedStatPlusSys -> SetFillColor(kPink-8);
  ratioEtaBinnedStatPlusSys -> SetName("statPlusSys_2012");
  
  ratioEtaBinnedStat -> SetMarkerStyle(20); 
  ratioEtaBinnedStat -> SetMarkerSize(2.0);
  ratioEtaBinnedStat -> SetLineColor(kPink-8);
  ratioEtaBinnedStat -> SetLineWidth(2);
  ratioEtaBinnedStat -> SetMarkerColor(kPink-8);
  ratioEtaBinnedStat -> SetFillColor(kPink-8);
  ratioEtaBinnedStat -> SetName("Stat_2012");

  ratioEtaBinnedStatPlusSys -> SetFillStyle(3244);
  ratioEtaBinnedStat        -> SetFillStyle(3144);

  Res_2011_stat->SetMarkerStyle(24);
  Res_2011_stat->SetMarkerSize(2.0);
  Res_2011_stat->SetLineColor(kGray+2);
  Res_2011_stat->SetLineWidth(2);
  Res_2011_stat->SetLineWidth(2);
  Res_2011_stat->SetFillStyle(1001);

  Res_2011_total->SetMarkerStyle(24);
  Res_2011_total->SetMarkerSize(2.0);
  Res_2011_total->SetLineColor(1);
  Res_2011_total->SetLineWidth(2);
  Res_2011_total->SetFillColor(kGray);
  Res_2011_total->SetFillStyle(1001);
  Res_2011_total->SetLineColor(kGray+2);

  Res_2011_total->Draw("a2");
  Res_2011_stat->Draw("esame");
  
  ratioEtaBinnedStatPlusSys -> Draw("2same");
  Res_2011_stat->Draw("pXsame");
  Res_2011_stat->SetMarkerSize(1.9);
  Res_2011_stat->Draw("pXsame");
  Res_2011_stat->SetMarkerSize(1.7);
  Res_2011_stat->Draw("pXsame");
  ratioEtaBinnedStatPlusSys -> Draw("pXsame");
  ratioEtaBinnedStat        -> Draw("esame");
  
  TLegend *leg = new TLegend(0.18, 0.60, 0.55, 0.75);
  leg->SetBorderSize(0);
  leg->SetFillColor(0);
  leg->SetFillStyle(0);
  leg->SetTextFont(42);
  leg->SetTextSize(0.045);
  
  leg->AddEntry(Res_2011_total,"5/fb (7 TeV)", "pfl");
  leg->AddEntry(ratioEtaBinnedStatPlusSys,"20/fb (8 TeV)", "pfl");
     
  leg->Draw("same");

  TLatex *info = new TLatex();
  info->SetNDC();
  info->DrawLatex(0.67,0.83,"Anti-k_{T} R=0.5");
  info->DrawLatex(0.67,0.77,"PF+CHS");

  CMS_lumi( cFinal2, iPeriod, 11 );
  cFinal2->Print("plots/resultsComparisonFINAL.pdf","pdf");
  cFinal2->SaveAs("plots/resultsComparisonFINAL.C");


  return 0;

}
void profileDistributions(TString dist)
{
  gStyle->SetOptStat(0);
  gStyle->SetOptTitle(0);
  gStyle->SetPalette(1);

  TFile *inF=TFile::Open("~/work/top_539/plotter.root");
  TFile *inSystF=TFile::Open("~/work/top_539/plotter_syst.root");

  bool isPhi(dist.Contains("phi"));
  TString profs[]={dist,
		   dist+"toward",
		   dist+"transverse",
		   dist+"away"};
  const size_t nprofs= isPhi ? 1 : sizeof(profs)/sizeof(TString);


  Int_t colors[]={1,kBlue,kRed,kGreen-3};

  TString cats[]={"inclusive","away","transverse","toward"};

  /*
  TFile *inNomF=inF;
  TString nomTTbar="t#bar{t}";
  TString nomTTbarTitle="MG+PY";
  
  //TString systList[]={"t#bar{t}systmcatnlo"};
  //TString systLabels[]={"MC@NLO+HW"};
  
  //TString systList[]={"t#bar{t}systq2down","t#bar{t}systq2up"};
  //TString systLabels[]={"-Q^{2}","+Q^{2}"};

  //TString systList[]={"t#bar{t}systmepsdown","t#bar{t}systmepsup"};
  // TString systLabels[]={"-ME-PS","+ME-PS"};
  */

  TFile *inNomF=inSystF;
  TString nomTTbar="t#bar{t}systtunep11";
  TString nomTTbarTitle="P11";
  TString systList[]={"t#bar{t}systtunep11nocr","t#bar{t}systtunep11tev"};
  TString systLabels[]={"P11-noCR","P11TeV"};


  Int_t systColors[]={1,kAzure,kRed-6,kGreen+3};

  const size_t nSysts=sizeof(systList)/sizeof(TString);

  TString ch[]={"emu"};
  const size_t nch=sizeof(ch)/sizeof(TString);
  
  for(size_t ich=0; ich<nch; ich++)
    {
      TCanvas *c=new TCanvas("c"+ch[ich]+dist,"c"+ch[ich]+dist,800,800); c->SetTopMargin(0); c->SetBottomMargin(0);
      c->Divide(1,nprofs);
      
      TCanvas *cratios=new TCanvas("cratios"+ch[ich]+dist,"cratios"+ch[ich]+dist,800,800); cratios->SetTopMargin(0); cratios->SetBottomMargin(0);
      cratios->Divide(1,nprofs);

      TCanvas *cproj=new TCanvas("cproj"+ch[ich]+dist,"cproj"+ch[ich]+dist,600,600);
      TLegend *dataprojLeg=new TLegend(0.5,0.9,0.6,0.7,"Data","brNDC");
      TLegend *mcprojLeg=new TLegend(0.7,0.9,0.92,0.7,"MC","brNDC");
      
      for(size_t i=0; i<nprofs; i++)
	{
	  TH2 *bckgMC   = (TH2 *) inF->Get("Z#rightarrow ll/"+ch[ich]+"_"+profs[i]); 
	  bckgMC->Add( (TH2 *) inF->Get("VV/"+ch[ich]+"_"+profs[i]) );
	  bckgMC->Add( (TH2 *) inF->Get("Single top/"+ch[ich]+"_"+profs[i]) );
	  bckgMC->Add( (TH2 *) inF->Get("W+jets-multijets/"+ch[ich]+"_"+profs[i]) );
	  
	  //build the total MC with signal alternatives
	  TH2 *MC = (TH2 *) inNomF->Get(nomTTbar+"/"+ch[ich]+"_"+profs[i]) ; 
	  Double_t totalTTbar(MC->Integral());
	  MC->Add(bckgMC);
	  MC->SetDirectory(0);
	  MC->Sumw2();	  
	  
	  std::vector<TH2 *> systMC;
	  for(size_t isyst=0; isyst<nSysts; isyst++)
	    {
	      TH2F *h=(TH2F *)inSystF->Get(systList[isyst]+"/"+ch[ich]+"_"+profs[i]) ;
	      h->Scale(totalTTbar/h->Integral());
	      h->Add(bckgMC);
	      h->Sumw2();
	      h->SetDirectory(0);
	      systMC.push_back(h);
	    }
		

	  //get the data
	  TH2 *Data = (TH2 *) inF->Get("data/"+ch[ich]+"_"+profs[i]);            
	  Data->SetDirectory(0);
	  Data->Sumw2();

	  TGraphErrors *MCProf   = new TGraphErrors(MC->ProfileX());    MCProf->SetMarkerStyle(24);   MCProf->SetFillStyle(0); MCProf->SetName(ch[ich]+profs[i]+"mc");
	  TGraphErrors *DataProf = new TGraphErrors(Data->ProfileX());  DataProf->SetMarkerStyle(20); DataProf->SetFillStyle(0); DataProf->SetName(ch[ich]+profs[i]+"data");
	  
	  //build data/MC scale factors
	  std::vector<TGraphErrors *> data2mcProfs;
	  for(size_t isyst=0; isyst<=systMC.size(); isyst++)
	    {
	      TGraphErrors *prof= (isyst==0 ? MCProf : new TGraphErrors(systMC[isyst-1]->ProfileX()));
	      TString baseName(ch[ich]+profs[i]);
	      if(isyst) baseName += systList[isyst];
	      prof = (TGraphErrors *) prof->Clone(baseName+"data2mc");
	      for(int ip=0; ip<DataProf->GetN(); ip++)
		{
		  Double_t x,y,ydata,y_err,ydata_err;
		  prof->GetPoint(ip,x,y);         y_err=prof->GetErrorY(ip);
		  DataProf->GetPoint(ip,x,ydata); ydata_err=DataProf->GetErrorY(ip);
		  if(y<=0) continue;
		  prof->SetPoint(ip,x,ydata/y);
		  prof->SetPointError(ip,0,sqrt(pow(ydata*y_err,2)+pow(ydata_err*y,2))/pow(y,2));
		}
	      prof->SetFillColor(systColors[isyst]);
	      prof->SetFillStyle(3001+isyst%2);
	      prof->SetTitle( isyst==0 ? nomTTbarTitle : systLabels[isyst-1] );
	      //prof->SetMarkerStyle(24);   prof->SetFillStyle(3001); prof->SetMarkerColor(1+isyst); prof->SetMarkerColor(1+isyst); prof->SetLineColor(1+isyst);
	      data2mcProfs.push_back(prof);
	    }

	  
	  TH1D *MCProjY=MC->ProjectionY();
	  MCProjY->Scale(1./MCProjY->Integral()); 
	  TGraphErrors *MCProj   = new TGraphErrors(MCProjY);    MCProj->SetMarkerStyle(24); MCProj->SetFillStyle(0);  MCProj->SetName(ch[ich]+profs[i]+"projmc");
	  TH1D *DataProjY=Data->ProjectionY();
	  DataProjY->Scale(1./DataProjY->Integral());
	  TGraphErrors *DataProj = new TGraphErrors(DataProjY);  DataProj->SetMarkerStyle(20); DataProj->SetFillStyle(0); DataProj->SetName(ch[ich]+profs[i]+"projdata");
	  MCProj->SetLineColor(colors[i]);   MCProj->SetMarkerColor(colors[i]);   MCProj->SetFillColor(colors[i]); MCProj->SetFillStyle(1001);
	  DataProj->SetLineColor(colors[i]); DataProj->SetMarkerColor(colors[i]);   DataProj->SetFillColor(colors[i]);
	  
	  TPad *p=(TPad *)cproj->cd();
	  p->SetLeftMargin(0.15);
	  p->SetRightMargin(0.02);
	  p->SetTopMargin(0.05);
	  p->SetLogy();
	  MCProj->SetFillStyle(0);
	  MCProj->Draw(i==0 ? "al3" : "l3");
	  MCProj->GetYaxis()->SetRangeUser(1e-5,1.0);
	  MCProj->GetXaxis()->SetTitle( MC->GetYaxis()->GetTitle() );
	  MCProj->GetYaxis()->SetTitle( "1/N dN/dx" );
	  MCProj->GetYaxis()->SetTitleOffset(1.8);
	  DataProj->Draw("p");
	  std::pair<float,int> chi2=computeChiSquareFor(DataProj,MCProj);
	  char buf[200];
	  sprintf(buf,"#scale[0.7]{#chi^{2}/ndof=%3.1f}", chi2.first/chi2.second );
	  dataprojLeg->AddEntry(DataProj,buf,"p");
	  mcprojLeg->AddEntry(MCProj,cats[i],"l");
	  if(i==0) drawCMSHeader(ch[ich]);
	  

	  p=(TPad *)c->cd(i+1);
	  if(i<nprofs-1) p->SetBottomMargin(0.01);
	  if(i>0) p->SetTopMargin(0);
	  if(i==0)p->SetTopMargin(0.1);
	  if(i==nprofs-1) p->SetBottomMargin(0.15);
	  TGraphErrors *frame=DataProf;
	  frame->Draw("ap");
	  //frame->GetYaxis()->SetRangeUser(0.54,1.46);
	  frame->GetXaxis()->SetTitle(MC->GetXaxis()->GetTitle());
	  //frame->GetXaxis()->SetRangeUser(0,4.75);
	  TString yTit("<"); yTit+=MC->GetYaxis()->GetTitle(); yTit +=">";
	  frame->GetYaxis()->SetTitle(yTit);
	  frame->GetYaxis()->SetLabelSize(0.07);
	  frame->GetYaxis()->SetTitleSize(0.09);
	  frame->GetYaxis()->SetTitleOffset(0.5);
	  frame->GetXaxis()->SetLabelSize(0.07);
	  frame->GetXaxis()->SetTitleSize(0.09);
	  frame->GetXaxis()->SetTitleOffset(0.7);
	  //p->SetGridy();
	  //DataProf->Draw("p");
	  MCProf->Draw("p");
	  if(i==0)
	    {
	      drawCMSHeader(ch[ich],0.08);

	      TLegend *leg=new TLegend(0.6,0.95,1.0,0.99);
	      leg->SetBorderSize(0);
	      leg->SetFillStyle(0);
	      leg->SetTextFont(42);
	      leg->SetTextSize(0.09);
	      leg->AddEntry(DataProf,"data","p");
	      leg->AddEntry(MCProf,"simulation","p");
	      leg->SetNColumns(2);
	      leg->Draw();
	    }

	  TPaveText *pt=new TPaveText(0.15,0.5,0.8,0.85,"brNDC");
	  pt->SetBorderSize(0);
	  pt->SetFillStyle(0);
	  pt->SetTextAlign(13);
	  pt->SetTextFont(42);
	  pt->SetTextColor(kBlue);
	  pt->SetTextSize(0.08);
	  pt->AddText("[ "+cats[i]+" ]");
	  if(i==0)
	    {
	      pt->AddText("p_{T}>0.5 GeV");
	      pt->AddText("|#eta|<2.1");
	    }
	  pt->Draw();


	  p=(TPad *) cratios->cd(i+1);
	  if(i<nprofs-1) p->SetBottomMargin(0.01);
	  if(i>0) p->SetTopMargin(0);
	  if(i==0)p->SetTopMargin(0.1);
	  if(i==nprofs-1) p->SetBottomMargin(0.15);
	  frame=data2mcProfs[0];
	  frame->Draw("a3");
	  TLine *l=new TLine(frame->GetXaxis()->GetXmin(),1,frame->GetXaxis()->GetXmax(),1);
	  l->Draw();
	  frame->GetYaxis()->SetRangeUser(0.54,1.46);
	  frame->GetXaxis()->SetTitle(MC->GetXaxis()->GetTitle());
	  frame->GetYaxis()->SetTitle("Data/Simulation");
	  frame->GetYaxis()->SetLabelSize(0.07);
	  frame->GetYaxis()->SetTitleSize(0.09);
	  frame->GetYaxis()->SetTitleOffset(0.5);
	  frame->GetXaxis()->SetLabelSize(0.07);
	  frame->GetXaxis()->SetTitleSize(0.09);
	  frame->GetXaxis()->SetTitleOffset(0.7);
	  //p->SetGridy();
	  for(size_t ip=1; ip<data2mcProfs.size(); ip++) data2mcProfs[ip]->Draw("3");
	  if(i==0)
	    {
	      drawCMSHeader(ch[ich],0.08);

	      TLegend *leg=new TLegend(0.6,0.94,1.0,0.98);
	      leg->SetBorderSize(0);
	      leg->SetFillStyle(0);
	      leg->SetTextFont(42);
	      leg->SetTextSize(0.09);
	      leg->SetNColumns(data2mcProfs.size());
	      for(size_t ip=0; ip<data2mcProfs.size(); ip++)
		leg->AddEntry(data2mcProfs[ip],data2mcProfs[ip]->GetTitle(),"f");
	      leg->Draw();
	    }
	  
	  pt=new TPaveText(0.12,0.65,0.8,0.9,"brNDC");
	  pt->SetBorderSize(0);
	  pt->SetFillStyle(0);
	  pt->SetTextAlign(13);
	  pt->SetTextFont(42);
	  pt->SetTextColor(kBlue);
	  pt->SetTextSize(0.08);
	  pt->AddText("[ "+cats[i]+" ]");
	  if(i==0)
	    {
	      pt->AddText("p_{T}>0.5 GeV");
	      pt->AddText("|#eta|<2.1");
	    }
	  pt->Draw();
	}

      cproj->cd();
      dataprojLeg->SetFillStyle(0);
      dataprojLeg->SetBorderSize(0);
      dataprojLeg->SetTextFont(42);
      dataprojLeg->SetTextSize(0.03);
      dataprojLeg->Draw();
      mcprojLeg->SetFillStyle(0);
      mcprojLeg->SetBorderSize(0);
      mcprojLeg->SetTextFont(42);
      mcprojLeg->SetTextSize(0.03);
      mcprojLeg->Draw();


      TString pf(".png");
      c->SaveAs(outDir+c->GetName()+pf);
      cproj->SaveAs(outDir+cproj->GetName()+pf);
      cratios->SaveAs(outDir+cratios->GetName()+pf);

    }

  inF->Close();
  inSystF->Close();
}
int main (int argc, char **argv) {
 
 /// Input File MCTruth IC Map , RECO IC map, MC IC set after calibration (Usually set with miscalibration 5%)
 /// and StatPrecision IC coefficient obtained from DrawCalibrationPlotsEE.C

 if(argc != 2){
 std::cerr << ">>>>> analysis.cpp::usage: " << argv[0] << " configFileName" << std::endl ;
 return 1;
 }

 parseConfigFile (argv[1]) ;

 std::string inputFile = gConfigParser -> readStringOption("Input::inputFile");  
 std::string inputMomentumScale =  gConfigParser -> readStringOption("Input::inputMomentumScale");
 std::string fileMCTruth = gConfigParser -> readStringOption("Input::fileMCTruth");  
 std::string fileMCRecoIC = gConfigParser -> readStringOption("Input::fileMCRecoIC");  
 std::string fileStatPrecision = gConfigParser -> readStringOption("Input::fileStatPrecision");  
 
 std::string outputFile = gConfigParser -> readStringOption("Output::outputFile");  
 

 TApplication* theApp = new TApplication("Application",&argc, argv);

 TFile *f1 = TFile::Open(fileMCTruth.c_str());
 TFile *f2 = TFile::Open(fileMCRecoIC.c_str());  
 /// L3 result MC endcap
 TFile *f3 = TFile::Open(inputFile.c_str());  
 /// File form momentum scale correction
 TFile* input = new TFile(inputMomentumScale.c_str());
 /// Statistical Precision map 
 TFile *f4 =  TFile::Open(fileStatPrecision.c_str());
 
 if(f1==0 || f2==0 || f3==0 || f4==0) return -1; 


 // Set style options
 gROOT->Reset();
 gROOT->SetStyle("Plain");

 gStyle->SetPadTickX(1);
 gStyle->SetPadTickY(1);
 gStyle->SetOptTitle(0); 
 gStyle->SetOptStat(1110); 
 gStyle->SetOptFit(0); 
 gStyle->SetFitFormat("6.3g"); 
 gStyle->SetPalette(1); 
 
 gStyle->SetTextFont(42);
 gStyle->SetTextSize(0.05);
 gStyle->SetTitleFont(42,"xyz");
 gStyle->SetTitleSize(0.05);
 gStyle->SetLabelFont(42,"xyz");
 gStyle->SetLabelSize(0.05);
 gROOT->ForceStyle();


 /// input coeff map for EEP and EEM

 TH2F *hcmapMcT_EEP = (TH2F*)f1->Get("h_scale_EEP");
 TH2F *hcmapMcT_EEM = (TH2F*)f1->Get("h_scale_EEM");
 TH2F *hcmapMcR_EEP = (TH2F*)f2->Get("h_scale_EEP");
 TH2F *hcmapMcR_EEM = (TH2F*)f2->Get("h_scale_EEM");
 
 TH2F * hcmap_EEP = (TH2F*)hcmapMcT_EEP->Clone("hcmap_EEP");
 TH2F * hcmap_EEM = (TH2F*)hcmapMcT_EEM->Clone("hcmap_EEM");
 
 hcmap_EEP->Reset();
 hcmap_EEM->Reset();

 for (int jbin = 1; jbin < hcmap_EEP-> GetNbinsY(); jbin++){
   for (int ibin = 1; ibin < hcmap_EEM-> GetNbinsX()+1; ibin++){
	
     if(hcmapMcT_EEP->GetBinContent(ibin,jbin)!=0 && hcmapMcR_EEP->GetBinContent(ibin,jbin)!=0)
        hcmap_EEP->SetBinContent(ibin,jbin,hcmapMcT_EEP->GetBinContent(ibin,jbin)/hcmapMcR_EEP->GetBinContent(ibin,jbin));
     if(hcmapMcT_EEM->GetBinContent(ibin,jbin)!=0 && hcmapMcR_EEM->GetBinContent(ibin,jbin)!=0)
	hcmap_EEM->SetBinContent(ibin,jbin,hcmapMcT_EEM->GetBinContent(ibin,jbin)/hcmapMcR_EEM->GetBinContent(ibin,jbin));
      }
  }

 /// Scalib and L3 map Normalized for EE+ and EE-
 
 TH2F * miscalib_map_EEP = (TH2F*) f3 -> Get("h_scalib_EEP");
 TH2F * miscalib_map_EEM = (TH2F*) f3 -> Get("h_scalib_EEM");

 TH2F *hcL3_EEP = (TH2F*)f3->Get("h_scale_map_EEP");
 TH2F *hcL3_EEM = (TH2F*)f3->Get("h_scale_map_EEM");
  
 TH2F *hcmap2_EEP = (TH2F*)hcL3_EEP ->Clone("hcmap2_EEP");
 TH2F *hcmap2_EEM = (TH2F*)hcL3_EEM ->Clone("hcmap2_EEM");
  
 hcmap2_EEP->Reset();
 hcmap2_EEM->Reset();


 /// Momentum scale correction
 
 TGraphErrors* g_EoP_EE = (TGraphErrors*) input->Get("g_EoP_EE_0");
 TGraphErrors* PhiProjectionEEp = new TGraphErrors();
 TGraphErrors* PhiProjectionEEm = new TGraphErrors();
 
 PhiProjectionEEp->SetMarkerStyle(20);
 PhiProjectionEEp->SetMarkerSize(1);
 PhiProjectionEEp->SetMarkerColor(kRed);

 PhiProjectionEEm->SetMarkerStyle(20);
 PhiProjectionEEm->SetMarkerSize(1);
 PhiProjectionEEm->SetMarkerColor(kBlue);
 

 TEndcapRings *eRings = new TEndcapRings();
 std::vector<double> vectSum;
 std::vector<double> vectCounter;
 
 vectCounter.assign(g_EoP_EE->GetN(),0.);
 vectSum.assign(g_EoP_EE->GetN(),0.);

 /// EE+ and EE- projection 

 for(int ix=1; ix<hcL3_EEM->GetNbinsX()+1;ix++){
   for(int iy=1; iy<hcL3_EEM->GetNbinsY()+1;iy++){
    if(hcL3_EEM->GetBinContent(ix,iy)==0) continue;
      int iPhi = int(eRings->GetEndcapIphi(ix,iy,-1)/(360./g_EoP_EE->GetN()));
      vectSum.at(iPhi)=vectSum.at(iPhi)+hcL3_EEM->GetBinContent(ix,iy);
      vectCounter.at(iPhi)=vectCounter.at(iPhi)+1;
  }
 }


 for(unsigned int i=0; i<vectCounter.size();i++)
  PhiProjectionEEm->SetPoint(i,int(i*(360./g_EoP_EE->GetN())),vectSum.at(i)/vectCounter.at(i));

 for(unsigned int i=0; i<vectSum.size(); i++){
  vectSum.at(i)=0; vectCounter.at(i)=0;
 }

 for(int ix=1; ix<hcL3_EEP->GetNbinsX()+1;ix++){
   for(int iy=1; iy<hcL3_EEP->GetNbinsY()+1;iy++){
    if(hcL3_EEP->GetBinContent(ix,iy)==0) continue;
     int iPhi = int(eRings->GetEndcapIphi(ix,iy,1)/(360./g_EoP_EE->GetN()));
     vectSum.at(iPhi)=vectSum.at(iPhi)+hcL3_EEP->GetBinContent(ix,iy);
     vectCounter.at(iPhi)=vectCounter.at(iPhi)+1;
  }
 }

 
 for(unsigned int i=0; i<vectCounter.size();i++)
  PhiProjectionEEp->SetPoint(i,int(i*(360./g_EoP_EE->GetN())),vectSum.at(i)/vectCounter.at(i));
 
 for(unsigned int i=0; i<vectSum.size(); i++){
  vectSum.at(i)=0; vectCounter.at(i)=0;
 }

 /// Correction EE+ and EE-

 TH2F* mapMomentumCorrected[2];
 mapMomentumCorrected[0] = (TH2F*) hcL3_EEM->Clone("mapMomentumCorrected_EEM");
 mapMomentumCorrected[1] = (TH2F*) hcL3_EEP->Clone("mapMomentumCorrected_EEP");
 mapMomentumCorrected[0]->Reset();
 mapMomentumCorrected[1]->Reset();

 for(int ix=1; ix<hcL3_EEM->GetNbinsX()+1;ix++){
  for(int iy=1; iy<hcL3_EEM->GetNbinsY()+1;iy++){
   if(hcL3_EEM->GetBinContent(ix,iy)==0) continue;
    int iPhi = int(eRings->GetEndcapIphi(ix,iy,-1));
    double xphi,yphi;
    g_EoP_EE->GetPoint(int(iPhi/(360./PhiProjectionEEm->GetN())),xphi,yphi);
    mapMomentumCorrected[0]->SetBinContent(ix,iy,hcL3_EEM->GetBinContent(ix,iy)*yphi);
  }
 }

 for(int ix=1; ix<hcL3_EEP->GetNbinsX()+1;ix++){
  for(int iy=1; iy<hcL3_EEP->GetNbinsY()+1;iy++){
   if(hcL3_EEP->GetBinContent(ix,iy)==0) continue;
    int iPhi = int(eRings->GetEndcapIphi(ix,iy,1));
    double xphi,yphi; 
    g_EoP_EE->GetPoint(int(iPhi/(360./PhiProjectionEEp->GetN())),xphi,yphi);
    mapMomentumCorrected[1]->SetBinContent(ix,iy,hcL3_EEP->GetBinContent(ix,iy)*yphi);
  }
 }

/// Use momentum map corrected  

 for (int jbin = 1; jbin < mapMomentumCorrected[1]-> GetNbinsY()+1; jbin++){
    for (int ibin = 1; ibin < mapMomentumCorrected[1]-> GetNbinsX()+1; ibin++){
      if(miscalib_map_EEP->GetBinContent(ibin,jbin)!=0 && mapMomentumCorrected[1]->GetBinContent(ibin,jbin)!=0)
      hcmap2_EEP->SetBinContent(ibin,jbin,miscalib_map_EEP->GetBinContent(ibin,jbin)*mapMomentumCorrected[1]->GetBinContent(ibin,jbin));
      if(miscalib_map_EEM->GetBinContent(ibin,jbin)!=0 && mapMomentumCorrected[0]->GetBinContent(ibin,jbin)!=0)
      hcmap2_EEM->SetBinContent(ibin,jbin,miscalib_map_EEM->GetBinContent(ibin,jbin)*mapMomentumCorrected[0]->GetBinContent(ibin,jbin));
      }
    }


 /// output histos

 TH2F * h2_EEP = new TH2F("h2_EEP","h2_EEP",400,0.5,1.5,400,0.5,1.5);
 TH2F * h2_EEM = new TH2F("h2_EEM","h2_EEM",400,0.5,1.5,400,0.5,1.5);

 TH2F * h2diff_EEP = (TH2F*)hcmap_EEP->Clone("h2diff_EEP");
 TH2F * h2diff_EEM = (TH2F*)hcmap_EEM->Clone("h2diff_EEM");

 h2diff_EEP->Reset();
 h2diff_EEM->Reset();
   
 char hname[100];

 TH1F *hspread_EEP[40];
 TH1F *hspread_EEM[40];
 TH1F *hspread_All[40];

 /// ring geometry for the endcap

 TH2F *hrings_EEP;
 TH2F *hrings_EEM;

 hrings_EEP = (TH2F*)hcmap2_EEP->Clone("hringsEEP");
 hrings_EEM = (TH2F*)hcmap2_EEM->Clone("hringsEEM");
 hrings_EEP ->Reset();
 hrings_EEM ->Reset();

 FILE *fRing;
 fRing = fopen("macros/eerings.dat","r");
 int x,y,z,ir;
 while(fscanf(fRing,"(%d,%d,%d) %d \n",&x,&y,&z,&ir) !=EOF ) {
    if(z>0) hrings_EEP->Fill(x,y,ir); 
    if(z<0) hrings_EEM->Fill(x,y,ir);
 }

 /// spread IC histos
 for (int jbin = 0; jbin < 40; jbin++){
    sprintf(hname,"hspread_ring_EEP_%02d",jbin);
    hspread_EEP[jbin]= new TH1F(hname, hname, 75,0.5,1.5);
    sprintf(hname,"hspread_ring_EEM_%02d",jbin);
    hspread_EEM[jbin]= new TH1F(hname, hname, 75,0.5,1.5);
    sprintf(hname,"hspread_ring_All_%02d",jbin);
    hspread_All[jbin]= new TH1F(hname, hname, 75,0.5,1.5);
    
 }
  
 for (int jbin = 1; jbin < hcmap_EEP-> GetNbinsY()+1; jbin++){
   for (int ibin = 1; ibin < hcmap_EEP-> GetNbinsX()+1; ibin++){
      
     int mybin_EEP = hcmap_EEP -> FindBin(ibin,jbin);
     int ring_EEP  = int(hrings_EEP-> GetBinContent(mybin_EEP)); 	
     float c1_EEP = hcmap_EEP->GetBinContent(mybin_EEP);
     float c2_EEP = hcmap2_EEP->GetBinContent(mybin_EEP);
   
     int mybin_EEM = hcmap_EEM -> FindBin(ibin,jbin);
     int ring_EEM  = int(hrings_EEM-> GetBinContent(mybin_EEM)); 
     float c1_EEM = hcmap_EEM->GetBinContent(mybin_EEM);
     float c2_EEM = hcmap2_EEM->GetBinContent(mybin_EEM);
   
     if (c1_EEP!=0 && c2_EEP!=0 ){
        ///Ratio betweem IC and not the difference
 	hspread_EEP[ring_EEP]->Fill(c1_EEP/c2_EEP);
        hspread_All[ring_EEP]->Fill(c1_EEP/c2_EEP);
        
	h2_EEP->Fill(c1_EEP,c2_EEP);
        h2diff_EEP->SetBinContent(ibin,jbin,c1_EEP/c2_EEP); 
     }
     else h2diff_EEP->SetBinContent(ibin,jbin,0);

     if (c1_EEM!=0 && c2_EEM!=0 ){
        hspread_EEM[ring_EEM]->Fill(c1_EEM/c2_EEM);
        hspread_All[ring_EEM]->Fill(c1_EEM/c2_EEM);
        
	h2_EEM->Fill(c1_EEM,c2_EEM);
        h2diff_EEM->SetBinContent(ibin,jbin,c1_EEM/c2_EEM);       
     }
     else h2diff_EEM->SetBinContent(ibin,jbin,0);
    }
  }

 /// TGraphErrors for final plot
 TGraphErrors *sigma_vs_iring_EEP = new TGraphErrors();
 sigma_vs_iring_EEP->SetMarkerStyle(20);
 sigma_vs_iring_EEP->SetMarkerSize(1);
 sigma_vs_iring_EEP->SetMarkerColor(kBlue+2);
  
 TGraphErrors *sigma_vs_iring_EEM = new TGraphErrors();
 sigma_vs_iring_EEM->SetMarkerStyle(20);
 sigma_vs_iring_EEM->SetMarkerSize(1);
 sigma_vs_iring_EEM->SetMarkerColor(kBlue+2);

 TGraphErrors *sigma_vs_iring_All = new TGraphErrors();
 sigma_vs_iring_All->SetMarkerStyle(20);
 sigma_vs_iring_All->SetMarkerSize(1);
 sigma_vs_iring_All->SetMarkerColor(kBlue+2);
  
 TGraphErrors *scale_vs_iring_EEP = new TGraphErrors();
 scale_vs_iring_EEP->SetMarkerStyle(20);
 scale_vs_iring_EEP->SetMarkerSize(1);
 scale_vs_iring_EEP->SetMarkerColor(kBlue+2);

 TGraphErrors *scale_vs_iring_EEM = new TGraphErrors();
 scale_vs_iring_EEM->SetMarkerStyle(20);
 scale_vs_iring_EEM->SetMarkerSize(1);
 scale_vs_iring_EEM->SetMarkerColor(kBlue+2);

 TGraphErrors *scale_vs_iring_All = new TGraphErrors();
 scale_vs_iring_All->SetMarkerStyle(20);
 scale_vs_iring_All->SetMarkerSize(1);
 scale_vs_iring_All->SetMarkerColor(kBlue+2);
 
 /// Gauss function for fit
 TF1 *fgaus_EEP = new TF1("fgaus_EEP","gaus",0.,2.);
 TF1 *fgaus_EEM = new TF1("fgaus_EEM","gaus",0.,2.);
 TF1 *fgaus_All = new TF1("fgaus_All","gaus",0.,2.);
 
 int np_EEP = 0;
 int np_EEM = 0;
 int np_All = 0;
 for (int i = 0; i < 40; i++){
   if ( hspread_EEP[i]->GetEntries() == 0) {sigma_vs_iring_EEP-> SetPoint(np_EEP,i,-100);np_EEP++;continue;}
   if ( hspread_EEM[i]->GetEntries() == 0) {sigma_vs_iring_EEM-> SetPoint(np_EEM,i,-100);np_EEM++;continue;}
   if ( hspread_All[i]->GetEntries() == 0) {sigma_vs_iring_All-> SetPoint(np_All,i,-100);np_All++;continue;}
    
   hspread_EEP[i]->Fit("fgaus_EEP","QRME");
   hspread_EEM[i]->Fit("fgaus_EEM","QRME");
   hspread_All[i]->Fit("fgaus_All","QRME");
   TString Name = Form("c_%d",i);
 
   sigma_vs_iring_EEP-> SetPoint(np_EEP,i,fgaus_EEP->GetParameter(2));
   sigma_vs_iring_EEP-> SetPointError(np_EEP,0,fgaus_EEP->GetParError(2));
  
   scale_vs_iring_EEP-> SetPoint(np_EEP,i,fgaus_EEP->GetParameter(1));
   scale_vs_iring_EEP-> SetPointError(np_EEP,0,fgaus_EEP->GetParError(1));

   np_EEP++;  

   sigma_vs_iring_EEM-> SetPoint(np_EEM,i,fgaus_EEM->GetParameter(2));
   sigma_vs_iring_EEM-> SetPointError(np_EEM,0,fgaus_EEM->GetParError(2));

   scale_vs_iring_EEM-> SetPoint(np_EEM,i,fgaus_EEM->GetParameter(1));
   scale_vs_iring_EEM-> SetPointError(np_EEM,0,fgaus_EEM->GetParError(1));

   np_EEM++;

   sigma_vs_iring_All-> SetPoint(np_All,i,fgaus_All->GetParameter(2));
   sigma_vs_iring_All-> SetPointError(np_All,0,fgaus_All->GetParError(2));

   scale_vs_iring_All-> SetPoint(np_All,i,fgaus_All->GetParameter(1));
   scale_vs_iring_All-> SetPointError(np_All,0,fgaus_All->GetParError(1));

   np_All++;
 }
 
 /// For from statistical precision analysis

 TGraphErrors* gr_stat_prec_EEP = (TGraphErrors*) f4->Get("gr_stat_prec_EEP");
 TGraphErrors* gr_stat_prec_EEM = (TGraphErrors*) f4->Get("gr_stat_prec_EEM");
 TGraphErrors* gr_stat_prec_All = (TGraphErrors*) f4->Get("gr_stat_prec");
 
  /// Residual Plot
 TGraphErrors* residual_EEP = new TGraphErrors();
 TGraphErrors* residual_EEM = new TGraphErrors();
 TGraphErrors* residual_All = new TGraphErrors();

 for(int pp=0; pp< gr_stat_prec_EEP->GetN(); pp++){
    double ring1, ring2,tot, stat, espread, estat,ex,res,eres;
   
    sigma_vs_iring_EEP->GetPoint(pp, ring2, tot);
    espread = sigma_vs_iring_EEP-> GetErrorY(pp);

    gr_stat_prec_EEP->GetPoint(pp,ring1, stat);
    estat = gr_stat_prec_EEP-> GetErrorY(pp);

    ex = gr_stat_prec_EEP-> GetErrorX(pp);  

    if (tot > stat ){res = sqrt( tot*tot - stat*stat );
	             eres = sqrt( pow(tot*espread,2) + pow(stat*estat,2))/res;
	}
     else {res  = -sqrt( fabs(tot*tot - stat*stat) );
	   eres = sqrt( pow(tot*espread,2) + pow(stat*estat,2))/fabs(res);
	  }

    residual_EEP->SetPoint(pp,ring1,res);
    if(eres<0.01) residual_EEP->SetPointError(pp,ex,eres);
    else residual_EEP->SetPointError(pp,ex,0.01);
  }
  
 for(int pp=0; pp< gr_stat_prec_EEM->GetN(); pp++){
    double ring1, ring2,tot, stat, espread, estat,ex,res,eres;
   
    sigma_vs_iring_EEM->GetPoint(pp, ring2, tot);
    espread = sigma_vs_iring_EEM-> GetErrorY(pp);

    gr_stat_prec_EEM->GetPoint(pp,ring1, stat);
    estat = gr_stat_prec_EEM-> GetErrorY(pp);

    ex = gr_stat_prec_EEM-> GetErrorX(pp);  
    if (tot > stat ){res  = sqrt( tot*tot - stat*stat );
	             eres = sqrt( pow(tot*espread,2) + pow(stat*estat,2))/res;
	}
	else {res  = -sqrt( fabs(tot*tot - stat*stat) );
	      eres = sqrt( pow(tot*espread,2) + pow(stat*estat,2))/fabs(res);
	}
    residual_EEM->SetPoint(pp,ring1,res);
    if(eres<0.01) residual_EEM->SetPointError(pp,ex,eres);
    else residual_EEM->SetPointError(pp,ex,0.01);
  }
  
 for(int pp=0; pp< gr_stat_prec_All->GetN(); pp++){
    double ring1, ring2,tot, stat, espread, estat,ex,res,eres;
   
    sigma_vs_iring_All->GetPoint(pp, ring2, tot);
    espread = sigma_vs_iring_All-> GetErrorY(pp);

    gr_stat_prec_All->GetPoint(pp,ring1, stat);
    estat = gr_stat_prec_All-> GetErrorY(pp);

    ex = gr_stat_prec_All-> GetErrorX(pp);  
    if (tot > stat ){ res  = sqrt( tot*tot - stat*stat );
	              eres = sqrt( pow(tot*espread,2) + pow(stat*estat,2))/res;
	}
	else {res  = -sqrt( fabs(tot*tot - stat*stat) );
	      eres = sqrt( pow(tot*espread,2) + pow(stat*estat,2))/fabs(res);
	}

    residual_All->SetPoint(pp,ring1,res);
    if(eres<0.01) residual_All->SetPointError(pp,ex,eres);
    else residual_All->SetPointError(pp,ex,0.01);
  
  }

 /// Final Plot 
 TCanvas *cscale_EEP = new TCanvas("cscale_EEP","cscale_EEP");
 cscale_EEP->SetGridx();
 cscale_EEP->SetGridy();
 scale_vs_iring_EEP->GetHistogram()->GetYaxis()-> SetRangeUser(0.9,1.1);
 scale_vs_iring_EEP->GetHistogram()->GetXaxis()-> SetRangeUser(0,40);
 scale_vs_iring_EEP->GetHistogram()->GetYaxis()-> SetTitle("c_{1}-c_{2}");
 scale_vs_iring_EEP->GetHistogram()->GetXaxis()-> SetTitle("iring");
 scale_vs_iring_EEP->Draw("ap");

 TCanvas *cscale_EEM = new TCanvas("cscale_EEM","cscale_EEM");
 cscale_EEM->SetGridx();
 cscale_EEM->SetGridy();
 scale_vs_iring_EEM->GetHistogram()->GetYaxis()-> SetRangeUser(0.9,1.1);
 scale_vs_iring_EEM->GetHistogram()->GetXaxis()-> SetRangeUser(0,40);
 scale_vs_iring_EEM->GetHistogram()->GetYaxis()-> SetTitle("c_{1}-c_{2}"); 
 scale_vs_iring_EEM->GetHistogram()->GetXaxis()-> SetTitle("iring");
 scale_vs_iring_EEM->Draw("ap");

 TCanvas *cmap2_EEP = new TCanvas("cmap2_EEP","cmap2_EEP",500,500);
 cmap2_EEP->SetGridx();
 cmap2_EEP->SetGridy();
 cmap2_EEP -> cd();
 cmap2_EEP->SetLeftMargin(0.1); 
 cmap2_EEP->SetRightMargin(0.15); 
 h2_EEP->GetXaxis()->SetRangeUser(0.85,1.15);
 h2_EEP->GetYaxis()->SetRangeUser(0.85,1.15);
 h2_EEP->GetXaxis()->SetTitle("C_{1}");
 h2_EEP->GetYaxis()->SetTitle("C_{2}");
 h2_EEP->Draw("colz");
  
 TCanvas *cmap2_EEM = new TCanvas("cmap2_EEM","cmap2_EEM",500,500);
 cmap2_EEM->SetGridx();
 cmap2_EEM->SetGridy();
 cmap2_EEM -> cd();
 cmap2_EEM->SetLeftMargin(0.1); 
 cmap2_EEM->SetRightMargin(0.15); 
 h2_EEM->GetXaxis()->SetRangeUser(0.85,1.15);
 h2_EEM->GetYaxis()->SetRangeUser(0.85,1.15);
 h2_EEM->GetXaxis()->SetTitle("C_{1}");
 h2_EEM->GetYaxis()->SetTitle("C_{2}");
 h2_EEM->Draw("colz");

 TCanvas *cdiff_EEP = new TCanvas("cdiff_EEP","cdiff_EEP",700,500);
 cdiff_EEP->SetGridx();
 cdiff_EEP->SetGridy();
 cdiff_EEP -> cd();
 cdiff_EEP->SetLeftMargin(0.1); 
 cdiff_EEP->SetRightMargin(0.15); 
 h2diff_EEP->GetZaxis()->SetRangeUser(0.5,1.6);
 h2diff_EEP->GetXaxis()->SetTitle("ix");
 h2diff_EEP->GetYaxis()->SetTitle("iy");
 h2diff_EEP->Draw("colz");

 TCanvas *cdiff_EEM = new TCanvas("cdiff_EEM","cdiff_EEM",700,500);
 cdiff_EEM->SetGridx();
 cdiff_EEM->SetGridy();
 cdiff_EEM -> cd();
 cdiff_EEM->SetLeftMargin(0.1); 
 cdiff_EEM->SetRightMargin(0.15); 
 h2diff_EEM->GetZaxis()->SetRangeUser(0.5,1.6);
 h2diff_EEM->GetXaxis()->SetTitle("ix");
 h2diff_EEM->GetYaxis()->SetTitle("iy");
 h2diff_EEM->Draw("colz");

 TCanvas *csigma_EEP = new TCanvas("csigma_EEP","csigma_EEP");
 csigma_EEP->SetGridx();
 csigma_EEP->SetGridy();
 sigma_vs_iring_EEP->GetHistogram()->GetYaxis()-> SetRangeUser(0.00,0.2);
 sigma_vs_iring_EEP->GetHistogram()->GetXaxis()-> SetRangeUser(0,40);
 sigma_vs_iring_EEP->GetHistogram()->GetYaxis()-> SetTitle("#sigma");
 sigma_vs_iring_EEP->GetHistogram()->GetXaxis()-> SetTitle("iring");
 sigma_vs_iring_EEP->Draw("ap");
 gr_stat_prec_EEP->Draw("psame");
    
 TCanvas *csigma_EEM = new TCanvas("csigma_EEM","csigma_EEM");
 csigma_EEM->SetGridx();
 csigma_EEM->SetGridy();
 sigma_vs_iring_EEM->GetHistogram()->GetYaxis()-> SetRangeUser(0.00,0.2);
 sigma_vs_iring_EEM->GetHistogram()->GetXaxis()-> SetRangeUser(0,40);
 sigma_vs_iring_EEM->GetHistogram()->GetYaxis()-> SetTitle("#sigma");
 sigma_vs_iring_EEM->GetHistogram()->GetXaxis()-> SetTitle("iring");
 sigma_vs_iring_EEM->Draw("ap");
 gr_stat_prec_EEM->Draw("psame");
 
 TCanvas *csigma_All= new TCanvas("csigma_All","csigma_Folded");
 csigma_All->SetGridx();
 csigma_All->SetGridy();
 sigma_vs_iring_All->GetHistogram()->GetYaxis()-> SetRangeUser(0.00,0.2);
 sigma_vs_iring_All->GetHistogram()->GetXaxis()-> SetRangeUser(0,40);
 sigma_vs_iring_All->GetHistogram()->GetYaxis()-> SetTitle("#sigma");
 sigma_vs_iring_All->GetHistogram()->GetXaxis()-> SetTitle("iring");
 sigma_vs_iring_All->Draw("ap");
 gr_stat_prec_All->Draw("psame");
 
 TCanvas *cres_EEP = new TCanvas("cres_EEP","cresidual_EEP");
 cres_EEP->SetGridx();
 cres_EEP->SetGridy();
 residual_EEP->GetHistogram()->GetYaxis()-> SetRangeUser(-0.1,0.1);
 residual_EEP->GetHistogram()->GetXaxis()-> SetRangeUser(0,40);
 residual_EEP-> SetTitle("residual EE+");
 residual_EEP-> SetTitle("iring");
 residual_EEP->SetMarkerStyle(20);
 residual_EEP->SetMarkerSize(1);
 residual_EEP->SetMarkerColor(kGreen+2); 
 residual_EEP->Draw("ap");
  
 TCanvas *cres_EEM = new TCanvas("cres_EEM","cresidual_EEM");
 cres_EEM->SetGridx();
 cres_EEM->SetGridy();
 residual_EEM->GetHistogram()->GetYaxis()-> SetRangeUser(-0.1,0.1);
 residual_EEM->GetHistogram()->GetXaxis()-> SetRangeUser(0,40);
 residual_EEM->GetHistogram()->GetYaxis()-> SetTitle("residual EE-");
 residual_EEM->GetHistogram()->GetXaxis()-> SetTitle("iring");
 residual_EEM ->SetMarkerStyle(20);
 residual_EEM->SetMarkerSize(1);
 residual_EEM->SetMarkerColor(kGreen+2); 
 residual_EEM->Draw("ap");

 TCanvas *cres_All = new TCanvas("cres_All","cresidual_Folded");
 cres_All->SetGridx();
 cres_All->SetGridy();
 residual_All->GetHistogram()->GetYaxis()-> SetRangeUser(-0.1,0.1);
 residual_All->GetHistogram()->GetXaxis()-> SetRangeUser(0,40);
 residual_All->GetYaxis()->SetTitle("residual EE Folded");
 residual_All->GetXaxis()->SetTitle("iring");
 residual_All->SetMarkerStyle(20);
 residual_All->SetMarkerSize(1);
 residual_All->SetMarkerColor(kGreen+2); 
 residual_All->Draw("ap");
  
  /// save output result:
  
 TFile* output = new TFile(outputFile.c_str(),"RECREATE");
 output->cd();
 residual_EEM->Write("residual_EEM");
 residual_EEP->Write("residual_EEP");
 residual_All->Write("residual_All");

 output->Close();

 theApp->Run();

 return 0;
  
}