Ejemplo n.º 1
0
int main(int argc, char** argv)
#endif
{
  ifstream filenames("namelist.txt");
  ofstream velfile("datavel.txt");
  velfile << "nomefile\tvelocita\tpunto iniziale\n";
  TF1  *line = new TF1 ("linea", "[0]+[1]*x", 0., 20.);
  line->SetParNames("x_0","v");
  while(!filenames.eof()){
    string fname;
    filenames >> fname;//fname non deve contenere spazi e ".txt"
    
    if(fname.find(".dat")==string::npos)
      fname+=".dat";
    if(fname!=".dat"){
      cout <<"*\n"<< fname << ":" << endl;
      int sets=0;
      sets |= preparedraw::doMax;
      
      preparedraw myData(fname,sets);
      myData.maximum()->Fit(line,"N");
      velfile << fname << "\t" <<line->GetParameter(1)<< "\t"<< line->GetParameter(0)<<endl;
    }
  }
  velfile.close();
}
Ejemplo n.º 2
0
void myfit()
{
   TString dir = gSystem->UnixPathName(__FILE__);
   dir.ReplaceAll("myfit.C","../hsimple.C");
   dir.ReplaceAll("/./","/");
   if (!gInterpreter->IsLoaded(dir.Data())) gInterpreter->LoadMacro(dir.Data());
   TFile *hsimple = (TFile*)gROOT->ProcessLineFast("hsimple(1)");
   if (!hsimple) return;

   TCanvas *c1 = new TCanvas("c1","the fit canvas",500,400);

   TH1F *hpx = (TH1F*)hsimple->Get("hpx");

// Creates a Root function based on function fitf above
   TF1 *func = new TF1("fitf",fitf,-2,2,3);

// Sets initial values and parameter names
   func->SetParameters(100,0,1);
   func->SetParNames("Constant","Mean_value","Sigma");

// Fit histogram in range defined by function
   hpx->Fit(func,"r");

// Gets integral of function between fit limits
   printf("Integral of function = %g\n",func->Integral(-2,2));
}
Ejemplo n.º 3
0
void stubsVSangle(){

	TCanvas *c1 = new TCanvas("c1","c1",800,600);
	c1->SetTickx();
	c1->SetTicky();

	double angle, MV, sigma;
	int n = 11;

	TGraphErrors *g1 = new TGraphErrors();

	ifstream fp; 
	fp.open("stubsVsAngle.txt");


	while(!fp.eof()){
		for (int i = 0 ; i < n ; ++i){
			if(fp >> angle >> MV >> sigma ){
				g1->SetPoint(i,angle*0.0174532925,MV*0.09);
			}
		}
	}


	TF1 *func = new TF1("fit","[0] + [1]*tan([2]+x)");
	func->SetParNames ("shift","spacing","ang0");
	// set starting parameters but not fixing any
	func->SetParameter(0, 0.5);
	func->SetParameter(1, 2.75);
	func->SetParameter(2, 0.02);

	g1->Fit("fit");
	
	fp.close();

	g1->SetMarkerStyle(20);
	g1->SetMarkerColor(1);
	g1->Draw("ap");
	g1->SetMinimum(0);
	//g1->SetMaximum(12);
	g1->GetXaxis()->SetTitle("angle [rad]");
	g1->GetYaxis()->SetTitle("Delta strip (mv)[mm]");
	g1->SetTitle("rotated DUT");

	TLegend* leg = new TLegend(0.3,0.8,0.6,0.9);
	leg->SetFillColor(0);
	//leg->SetLineColor(0);
	leg->AddEntry(g1,"mv","pl");
	leg->AddEntry(func,"Fit","L");
	leg->Draw();

}
Ejemplo n.º 4
0
TF1* fitPixelBeam(TH1D* hist, double pixelWidth, double beamSigma, bool display)
{
  TF1* conv = new TF1("conv",
                      "[2] + [4] * 0.5 * ( TMath::Erf(([0]/2 + [3] - x)/(sqrt(2)*[1])) + TMath::Erf(([0]/2 + [3] + x)/(sqrt(2)*[1])) )");
  conv->SetParNames("Width", "Sigma", "Background", "Offset", "Scale");

  const unsigned int numBins = hist->GetNbinsX();
  const double limitLow = hist->GetXaxis()->GetBinLowEdge(1);
  const double limitHigh = hist->GetXaxis()->GetBinUpEdge(numBins);

  // Estimate the background using the +/- 10% edges of the histogram
  double background = 0;
  const unsigned int numBackgroundBins = numBins * 0.1 + 1;
  for (unsigned int n = 0; n < numBackgroundBins; n++)
  {
    background += hist->GetBinContent(n + 1);
    background += hist->GetBinContent(numBins - n);
  }
  background /= (double)(2 * numBackgroundBins);

  // Estimate the scale
  double scale = 0;
  for (unsigned int bin = 1; bin <= numBins; bin++)
    if (hist->GetBinContent(bin) > scale) scale = hist->GetBinContent(bin);

  double offset = 0;

  conv->SetRange(limitLow, limitHigh);
  conv->SetParameters(pixelWidth, beamSigma, background, offset, scale);
  conv->SetParLimits(0, 0.1 * pixelWidth, 100 * pixelWidth);
  conv->SetParLimits(1, 0, 100 * beamSigma);
  conv->SetParLimits(2, 0, scale);
  conv->SetParLimits(3, -pixelWidth, pixelWidth);
  conv->SetParLimits(4, 0.1 * scale, 10 * scale);
  hist->Fit("conv", "QR0B");

  if (display)
  {
    TCanvas* can = new TCanvas();
    conv->SetLineColor(46);
    conv->SetLineWidth(1);
    hist->Draw();
    conv->Draw("SAME");
    can->Update();
    can->WaitPrimitive();
  }

  return conv;
}
Ejemplo n.º 5
0
Archivo: langaus.C Proyecto: Y--/root
TF1 *langaufit(TH1F *his, Double_t *fitrange, Double_t *startvalues, Double_t *parlimitslo, Double_t *parlimitshi, Double_t *fitparams, Double_t *fiterrors, Double_t *ChiSqr, Int_t *NDF)
{
   // Once again, here are the Landau * Gaussian parameters:
   //   par[0]=Width (scale) parameter of Landau density
   //   par[1]=Most Probable (MP, location) parameter of Landau density
   //   par[2]=Total area (integral -inf to inf, normalization constant)
   //   par[3]=Width (sigma) of convoluted Gaussian function
   //
   // Variables for langaufit call:
   //   his             histogram to fit
   //   fitrange[2]     lo and hi boundaries of fit range
   //   startvalues[4]  reasonable start values for the fit
   //   parlimitslo[4]  lower parameter limits
   //   parlimitshi[4]  upper parameter limits
   //   fitparams[4]    returns the final fit parameters
   //   fiterrors[4]    returns the final fit errors
   //   ChiSqr          returns the chi square
   //   NDF             returns ndf

   Int_t i;
   Char_t FunName[100];

   sprintf(FunName,"Fitfcn_%s",his->GetName());

   TF1 *ffitold = (TF1*)gROOT->GetListOfFunctions()->FindObject(FunName);
   if (ffitold) delete ffitold;

   TF1 *ffit = new TF1(FunName,langaufun,fitrange[0],fitrange[1],4);
   ffit->SetParameters(startvalues);
   ffit->SetParNames("Width","MP","Area","GSigma");

   for (i=0; i<4; i++) {
      ffit->SetParLimits(i, parlimitslo[i], parlimitshi[i]);
   }

   his->Fit(FunName,"RB0");   // fit within specified range, use ParLimits, do not plot

   ffit->GetParameters(fitparams);    // obtain fit parameters
   for (i=0; i<4; i++) {
      fiterrors[i] = ffit->GetParError(i);     // obtain fit parameter errors
   }
   ChiSqr[0] = ffit->GetChisquare();  // obtain chi^2
   NDF[0] = ffit->GetNDF();           // obtain ndf

   return (ffit);              // return fit function

}
Ejemplo n.º 6
0
TF1* linLorentzianFit(TH1* histoY){
  TString name = histoY->GetName() + TString("Fit");

  // Fit slices projected along Y from bins in X 
  TF1 *fit = new TF1(name,lorentzianPlusLinear,70,110,5);
  fit->SetParameters(histoY->GetMaximum(),histoY->GetRMS(),histoY->GetMean(),10,-0.1);
  fit->SetParNames("norm","width","mean","offset","slope");
  fit->SetParLimits(1,-10,10);
  //fit->SetParLimits(2,85,95);
  //fit->SetParLimits(2,90,93);
  fit->SetParLimits(2,2,4);
  fit->SetParLimits(3,0,100);
  fit->SetParLimits(4,-1,0);
  fit->SetLineWidth(2);
  //histoY -> Fit(name,"0","",85,97);
  histoY -> Fit(name,"0","",2,4);
  return fit;
}
Ejemplo n.º 7
0
TF1* lorentzianFit(TH1* histoY, const TString & resonanceType){
  TString name = histoY->GetName() + TString("Fit");

  // Fit slices projected along Y from bins in X 
  TF1 *fit = 0;
  if( resonanceType == "JPsi" || resonanceType == "Psi2S" ) {
    fit = new TF1(name, lorentzian, 3.09, 3.15, 3);
  }
  if( resonanceType.Contains("Upsilon") ) {
    fit = new TF1(name, lorentzian, 9, 10, 3);
  }
  if( resonanceType == "Z" ) {
    fit = new TF1(name, lorentzian, 80, 105, 3);
  }
  fit->SetParameters(histoY->GetMaximum(),histoY->GetRMS(),histoY->GetMean());
  fit->SetParNames("norm","width","mean");
  fit->SetLineWidth(2);
  histoY->Fit( name,"R0" );
  return fit;
}
Ejemplo n.º 8
0
pqPoint HitCollection::drawHits(bool fit, bool draw, bool rz) {
	unsigned int hits_n = hitCollection.size();
	TGraph hits_h(hits_n);
	hits_h.SetTitle("Hits");
	for (unsigned int hit_i = 0; hit_i < hits_n; hit_i++) {
		hits_h.SetPoint(hit_i, hitCollection[hit_i].x, hitCollection[hit_i].y);
	}
	TCanvas c("c", "c", 600, 600);
	hits_h.GetXaxis()->SetLimits(-1.1*zmax, 1.1*zmax);
	hits_h.GetYaxis()->SetRangeUser(0., 1.1*rmax);
	hits_h.GetXaxis()->SetTitle("x[cm]");
	hits_h.GetYaxis()->SetTitle("y[cm]");
	hits_h.Draw("A*");
	pqPoint pqpoint;
	if (fit) {
		gStyle->SetOptFit(10001);
		string pol1("[1]*x + [0]");
		if (rz) pol1 = "1./[1]*x - [0]/[1]";
		TF1 * fitfun = new TF1("fitfun", pol1.c_str());
		fitfun->SetParNames("q","p");
		fitfun->SetParameters(1., 1.);
		hits_h.Fit(fitfun, draw ? "" : "q");
		c.Update();

		pqpoint.p = fitfun->GetParameter("p");
//		pqpoint.p = atan(fun->GetParameter("p"));
		pqpoint.q = fitfun->GetParameter("q");
		pqpoint.w = 1.;
	}
	else pqpoint.w = -1.;
	TPaveStats *st = (TPaveStats*)hits_h.FindObject("stats");
	st->SetY1NDC(0.72);
	st->SetY2NDC(0.87);
	st->SetX1NDC(0.13);
	st->SetX2NDC(0.28);

	if (draw) c.Print(Form("figs/hits_%s.pdf", name.c_str()));

	return pqpoint;
}
Ejemplo n.º 9
0
TF1* gaussianFit(TH1* histoY, const TString & resonanceType){

  TString name = histoY->GetName() + TString("Fit");

  // Fit slices projected along Y from bins in X
  // -------------------------------------------
  TF1 *fit = 0;
  // Set parameters according to the selected resonance
  if( resonanceType == "JPsi" ) {
    fit = new TF1(name,gaussian,2,4,3);
    fit->SetParLimits(2, 3.09, 3.15);
  }
  if( resonanceType.Contains("Upsilon") ) {
    fit = new TF1(name,gaussian,8.5,10.5,3);
    // fit = new TF1(name,gaussian,9,11,3);
    fit->SetParLimits(2, 9.2, 9.6);
    fit->SetParLimits(1, 0.09, 0.1);
  }
  if( resonanceType == "Z" ) {
    fit = new TF1(name,gaussian,80,100,3);
    fit->SetParLimits(2, 80, 100);
    fit->SetParLimits(1, 0.01, 1);
  }
  if( resonanceType == "reso" ) {
    fit = new TF1(name,gaussian,-0.05,0.05,3);
    fit->SetParLimits(2, -0.5, 0.5);
    fit->SetParLimits(1, 0, 0.5);
  }
  fit->SetParameters(histoY->GetMaximum(),histoY->GetRMS(),histoY->GetMean());
  // fit->SetParLimits(1, 0.01, 1);
  //   fit->SetParLimits(1, 40, 60);
  fit->SetParNames("norm","width","mean");
  fit->SetLineWidth(2);

  if( histoY->GetNbinsX() > 1000 ) histoY->Rebin(10);
  histoY->Fit(name,"R0");

  return fit;
}
Ejemplo n.º 10
0
void FitHist(Double_t * d, char * path)
{

TH1D* hist = GetHist(path);
if (hist == NULL )
	{
		d[0]=-1;
	    d[1]=-1;
		d[2]=-1;
		return;
	}
TF1 *func = new TF1 ("fit",DoubleErrf,hist->GetXaxis()->GetXmin(),hist->GetXaxis()->GetXmax(),3);
func->SetParameters(0.,0.1,hist->GetEntries());
func->SetParNames ("Mean_value","Sigma","N");
hist->Fit("fit","Q");
//Double_t d[2];
d[0]=func->GetParameter(0);
d[1]=func->GetParameter(1);
d[2]=func->GetParameter(2);
//return d;
//cout<<endl<<"for "<<path<<endl<<"mean = "<<func->GetParameter(0)<<endl<<"sigma = "<<func->GetParameter(1)<<endl;
}
void myfit()
{
   TFile* hsimple = TFile::Open("hsimple.root");
   if (!hsimple) return;

   TCanvas *c1 = new TCanvas("c1","the fit canvas",500,400);

   TH1F *hpx = (TH1F*)hsimple->Get("hpx");

// Creates a Root function based on function fitf above
   TF1 *func = new TF1("fitf",fitf,-2,2,3);

// Sets initial values and parameter names
   func->SetParameters(100,0,1);
   func->SetParNames("Constant","Mean_value","Sigma");

// Fit histogram in range defined by function
   hpx->Fit(func,"r");

// Gets integral of function between fit limits
   printf("Integral of function = %g\n",func->Integral(-2,2));
}
//*************************************************************
std::pair<std::pair<Double_t,Double_t>, std::pair<Double_t,Double_t>  > fitResidualsCB(TH1 *hist)
//*************************************************************
{
  
  //hist->Rebin(2);

  float mean  = hist->GetMean();
  float sigma = hist->GetRMS();
  //int   nbinsX   = hist->GetNbinsX();
  float nentries = hist->GetEntries();
  float meanerr  = sigma/TMath::Sqrt(nentries);
  float sigmaerr = TMath::Sqrt(sigma*sigma*TMath::Sqrt(2/nentries));

  float lowBound  = hist->GetXaxis()->GetBinLowEdge(1);
  float highBound = hist->GetXaxis()->GetBinLowEdge(hist->GetNbinsX()+1);

  if(TMath::IsNaN(mean) || TMath::IsNaN(sigma)){  
    mean=0;
    sigma= - lowBound + highBound;
  }
  
  TF1 func("tmp", "gaus", mean - 1.*sigma, mean + 1.*sigma); 
  if (0 == hist->Fit(&func,"QNR")) { // N: do not blow up file by storing fit!
    mean  = func.GetParameter(1);
    sigma = func.GetParameter(2);
  }
  
  // first round
  TF1 *doubleCB = new TF1("myDoubleCB",DoubleSidedCB,lowBound,highBound,7);
  doubleCB->SetParameters(mean,sigma,1.5,1.5,2.5,2.5,100);
  doubleCB->SetParLimits(0,mean-meanerr,mean+meanerr);
  doubleCB->SetParLimits(1,0.,sigma+2*sigmaerr);
  doubleCB->SetParLimits(2,0.,30.);
  doubleCB->SetParLimits(3,0.,30.);
  doubleCB->SetParLimits(4,0.,50.);
  doubleCB->SetParLimits(5,0.,50.);
  doubleCB->SetParLimits(6,0.,100*nentries);

  doubleCB->SetParNames("#mu","#sigma","#alpha_{L}","#alpha_{R}","n_{L}","n_{R}","N");
  doubleCB->SetLineColor(kRed);
  doubleCB->SetNpx(1000);
  // doubleCB->SetRange(0.8*lowBound,0.8*highBound);

  hist->Fit(doubleCB,"QM");

  // second round

  float p0 = doubleCB->GetParameter(0);
  float p1 = doubleCB->GetParameter(1);
  float p2 = doubleCB->GetParameter(2);
  float p3 = doubleCB->GetParameter(3);
  float p4 = doubleCB->GetParameter(4);
  float p5 = doubleCB->GetParameter(5);
  float p6 = doubleCB->GetParameter(6);
  
  float p0err = doubleCB->GetParError(0);
  float p1err = doubleCB->GetParError(1);
  float p2err = doubleCB->GetParError(2);
  float p3err = doubleCB->GetParError(3);
  float p4err = doubleCB->GetParError(4);
  float p5err = doubleCB->GetParError(5);
  float p6err = doubleCB->GetParError(6);

  if( (doubleCB->GetChisquare()/doubleCB->GetNDF()) >5){

    std::cout<<"------------------------"<<std::endl;
    std::cout<<"chi2 1st:"<<doubleCB->GetChisquare()<<std::endl;

    //std::cout<<"p0: "<<p0<<"+/-"<<p0err<<std::endl;
    //std::cout<<"p1: "<<p1<<"+/-"<<p1err<<std::endl;
    //std::cout<<"p2: "<<p2<<"+/-"<<p2err<<std::endl;
    //std::cout<<"p3: "<<p3<<"+/-"<<p3err<<std::endl;
    //std::cout<<"p4: "<<p4<<"+/-"<<p4err<<std::endl;
    //std::cout<<"p5: "<<p5<<"+/-"<<p5err<<std::endl;
    //std::cout<<"p6: "<<p6<<"+/-"<<p6err<<std::endl;

    doubleCB->SetParameters(p0,p1,3,3,6,6,p6);
    doubleCB->SetParLimits(0,p0-2*p0err,p0+2*p0err);
    doubleCB->SetParLimits(1,p1-2*p1err,p0+2*p1err);
    doubleCB->SetParLimits(2,p2-2*p2err,p0+2*p2err);
    doubleCB->SetParLimits(3,p3-2*p3err,p0+2*p3err);
    doubleCB->SetParLimits(4,p4-2*p4err,p0+2*p4err);
    doubleCB->SetParLimits(5,p5-2*p5err,p0+2*p5err);
    doubleCB->SetParLimits(6,p6-2*p6err,p0+2*p6err);

    hist->Fit(doubleCB,"MQ");

    //gMinuit->Command("SCAn 1");
    //TGraph *gr = (TGraph*)gMinuit->GetPlot();
    //gr->SetMarkerStyle(21);
    //gr->Draw("alp"); 

    std::cout<<"chi2 2nd:"<<doubleCB->GetChisquare()<<std::endl;
    
  }

  float res_mean  = doubleCB->GetParameter(0);
  float res_width = doubleCB->GetParameter(1);
  
  float res_mean_err  = doubleCB->GetParError(0);
  float res_width_err = doubleCB->GetParError(1);

  std::pair<Double_t,Double_t> resultM;
  std::pair<Double_t,Double_t> resultW;

  resultM = std::make_pair(res_mean,res_mean_err);
  resultW = std::make_pair(res_width,res_width_err);

  std::pair<std::pair<Double_t,Double_t>, std::pair<Double_t,Double_t>  > result;
  
  result = std::make_pair(resultM,resultW);
  return result;

}
Ejemplo n.º 13
0
void UpsilonMassFit_All(int iSpec = 3, int PutWeight=1)
{
  //See pT Cut
  double PtCut= 4.0;
  
  //minbias integrated, |y|<1.2 and |y|\in[1.2,2.4], centrality [0,10][10,20][20,100]%,  pt [0,6.5], [6.5, 10] [10,20]

  gROOT->SetStyle("Plain");
  gStyle->SetPalette(1);
  gStyle->SetFrameBorderMode(0);
  gStyle->SetFrameFillColor(0);
  gStyle->SetCanvasColor(0);
  gStyle->SetTitleFillColor(0);
  gStyle->SetStatColor(0);
  gStyle->SetPadBorderSize(0);
  gStyle->SetCanvasBorderSize(0);
  gStyle->SetOptTitle(1); // at least most of the time
  gStyle->SetOptStat(1); // most of the time, sometimes "nemriou" might be useful to display name, 
  //number of entries, mean, rms, integral, overflow and underflow
  gStyle->SetOptFit(1); // set to 1 only if you want to display fit results
  
  //==================================== Define Histograms====================================================
  ofstream dataFile(Form("Eff_Upsilon.txt"));
  
  TH1D *diMuonsInvMass_Gen = new TH1D("diMuonsInvMass_Gen","diMuonsInvMass_Gen", 100,8.0,12.0);
  TH1D *diMuonsPt_Gen = new TH1D("diMuonsPt_Gen","diMuonsPt_Gen", 100,0,30);
  //Rapidity Gen
  TH1D *diMuonsRap_Gen0 = new TH1D("diMuonsRap_Gen0","diMuonsRap_Gen0", 100,-5,5);
  TH1D *diMuonsRap_Gen1 = new TH1D("diMuonsRap_Gen1","diMuonsRap_Gen1", 100,-5,5);
  TH1D *diMuonsRap_Gen2 = new TH1D("diMuonsRap_Gen2","diMuonsRap_Gen2", 100,-5,5);
  TH1D *diMuonsRap_Gen3 = new TH1D("diMuonsRap_Gen3","diMuonsRap_Gen3", 100,-5,5);
  TH1D *diMuonsRap_Gen4 = new TH1D("diMuonsRap_Gen4","diMuonsRap_Gen4", 100,-5,5);
  TH1D *diMuonsRap_Gen5 = new TH1D("diMuonsRap_Gen5","diMuonsRap_Gen5", 100,-5,5);
  ////Rapidity Reco
  TH1D *diMuonsRap_Rec0 = new TH1D("diMuonsRap_Rec0","diMuonsRap_Rec0", 100,-5,5);
  diMuonsRap_Rec0->SetLineColor(2);
  TH1D *diMuonsRap_Rec1 = new TH1D("diMuonsRap_Rec1","diMuonsRap_Rec1", 100,-5,5);
  diMuonsRap_Rec1->SetLineColor(2);
  TH1D *diMuonsRap_Rec2 = new TH1D("diMuonsRap_Rec2","diMuonsRap_Rec2", 100,-5,5);
  diMuonsRap_Rec2->SetLineColor(2);
  TH1D *diMuonsRap_Rec3 = new TH1D("diMuonsRap_Rec3","diMuonsRap_Rec3", 100,-5,5);
  diMuonsRap_Rec3->SetLineColor(2);
  TH1D *diMuonsRap_Rec4 = new TH1D("diMuonsRap_Rec4","diMuonsRap_Rec4", 100,-5,5);
  diMuonsRap_Rec4->SetLineColor(2);
  TH1D *diMuonsRap_Rec5 = new TH1D("diMuonsRap_Rec5","diMuonsRap_Rec5", 100,-5,5);
  diMuonsRap_Rec5->SetLineColor(2);
  TH1D *Bin_Gen = new TH1D("Bin_Gen","Bin_Gen", 40,0,40);
  
  //==============================================Define AccEff Stuff here===========================================
  // Pt bin sizes
  int Nptbin=1;
  double pt_bound[100] = {0};
  if(iSpec == 1) { 
    Nptbin = 8;
    
   
    //for plots
    pt_bound[0] = 0.0;
    pt_bound[1] = 2.0;
    pt_bound[2] = 4.0;
    pt_bound[3] = 6.0;
    pt_bound[4] = 8.0;
    pt_bound[5] = 10.0;
    pt_bound[6] = 14.0;
    pt_bound[7] = 20.0;
     pt_bound[8] = 30.0;


    //pt_bound[0] = 0;
    //pt_bound[1] = 20.0;
    //pt_bound[2] = 0.0;
    //pt_bound[3] = 6.5;
    //pt_bound[4] = 10.0;
    //pt_bound[5] = 20.0;
    
    
   
  }
  
  if(iSpec == 2) { 
    Nptbin = 8;
    
    pt_bound[0] = -2.4; 
    pt_bound[1] = -1.6; 
    pt_bound[2] = -1.2; 
    pt_bound[3] = -0.8; 
    pt_bound[4] = 0.0; 
    pt_bound[5] = 0.8;
    pt_bound[6] = 1.2; 
    pt_bound[7] = 1.6; 
    pt_bound[8] = 2.4; 


    //pt_bound[0] = 0.0; 
    //pt_bound[1] = 1.2; 
    //pt_bound[2] = 2.4; 
    
   
    
  }
  
  
  if(iSpec == 3) {
    Nptbin = 8;
   
    // pt_bound[0] = 0.0;//0
    //pt_bound[1] = 8.0;//20
    //pt_bound[2] = 24.0;//60
    //pt_bound[3] = 40.0;//100



    //for plots
    pt_bound[0] = 0.0;//0
    pt_bound[1] = 4.0;//10
    pt_bound[2] = 8.0;//20
    pt_bound[3] = 12.0;//25
    pt_bound[4] = 16.0;//50
    pt_bound[5] = 20.0;//100
    pt_bound[6] = 24.0;
    pt_bound[7] = 32.0;
    pt_bound[8] = 40.0;
    
  }
  //X Axis error on Eff graph 
  double PT[100], DelPT[100], mom_err[100];
  for (Int_t ih = 0; ih < Nptbin; ih++) {
    PT[ih] = (pt_bound[ih] + pt_bound[ih+1])/2.0;
    DelPT[ih] = pt_bound[ih+1] - pt_bound[ih];
    mom_err[ih] = DelPT[ih]/2.0;
  }
  
  double genError, recError;
  double gen_pt[100]={0}, gen_ptError[100]={0}; 
  double rec_pt[100]={0}, rec_ptError[100]={0}; 
  double Eff_cat_1[100]={0},Err_Eff_cat_1[100]={0};  
  
  // Histogram arrays
  TH1D *diMuonsInvMass_GenA[10][1000];
  TH1D *diMuonsInvMass_RecA[10][1000];
  TH1D *diMuonsPt_GenA[10][1000];
  TH1D *diMuonsPt_RecA[10][1000];
  char nameGen[10][500], nameRec[10][500], nameGenPt[10][500], nameRecPt[10][500];
 
  
  for (int ifile = 0; ifile <= 5; ifile++) {
    for (Int_t ih = 0; ih < Nptbin; ih++) {
      sprintf(nameGen[ifile],"DiMuonMassGen_pt_%d_%d",ih,ifile);
      sprintf(nameRec[ifile],"DiMuonMassRec_pt_%d_%d",ih,ifile);
      
      sprintf(nameGenPt[ifile],"DiMuonPtGen_pt_%d_%d",ih,ifile);
      sprintf(nameRecPt[ifile],"DiMuonPtRec_pt_%d_%d",ih,ifile);
      
      diMuonsInvMass_GenA[ifile][ih]= new TH1D(nameGen[ifile],nameGen[ifile],  100,8.0,12.0); //for eff Gen;
      diMuonsInvMass_GenA[ifile][ih]->Sumw2();
      diMuonsInvMass_GenA[ifile][ih]->SetMarkerStyle(7);
      diMuonsInvMass_GenA[ifile][ih]->SetMarkerColor(4);
      diMuonsInvMass_GenA[ifile][ih]->SetLineColor(4);
      
      diMuonsInvMass_RecA[ifile][ih] = new TH1D(nameRec[ifile],nameRec[ifile], 100,8.0,12.0); //for eff Rec;
      diMuonsInvMass_RecA[ifile][ih]->Sumw2();
      diMuonsInvMass_RecA[ifile][ih]->SetMarkerStyle(8);
      diMuonsInvMass_RecA[ifile][ih]->SetMarkerColor(4);
      diMuonsInvMass_RecA[ifile][ih]->SetLineColor(4);
      
      
      diMuonsPt_GenA[ifile][ih]= new TH1D(nameGenPt[ifile],nameGenPt[ifile],  100,0,40); //for eff Gen;
      diMuonsPt_RecA[ifile][ih]= new TH1D(nameRecPt[ifile],nameRecPt[ifile],  100,0,40); //for eff Rec;
    }
  }
  
  //===========================================Input Root File============================================================
  char fileName[10][500];
  //0.0380228 	0.0480769 	0.0293255 	0.0125156 	0.00336587 	0.00276319*2/5 = 0.001105276
  //Scales
  double scale[10]={0};  
  
  scale[0]=(6.8802); // pT [0-3]
  scale[1]=(8.6995); // pT [3-6]
  scale[2]=(5.3065); // pT [6-9]
  scale[3]=(2.2647); // pT [9-12] 
  scale[4]=(3.0453); // pT [12-15] 
  scale[5]=(1.0000); // pT [15-30]
  

  
  sprintf(fileName[0],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt03_N.root");
  sprintf(fileName[1],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt36_N.root");
  sprintf(fileName[2],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt69_N.root");
  sprintf(fileName[3],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt912_N.root");
  sprintf(fileName[4],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt1215_N.root");
  sprintf(fileName[5],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt1530_N.root");
  
  TFile *infile;
  TTree *tree;
  TTree *gentree;
  
  //===========File loop ======================
  
  for(int ifile =0; ifile<=5; ifile++){
    
    infile=new TFile(fileName[ifile],"R");
    tree=(TTree*)infile->Get("SingleMuonTree");
    gentree=(TTree*)infile->Get("SingleGenMuonTree");
    
    //Event variables
    int eventNb,runNb,lumiBlock, gbin, rbin;
    //Jpsi Variables
    Double_t JpsiMass,JpsiPt,JpsiRap, JpsiCharge;
    Double_t JpsiVprob;
    //2.) muon variables RECO                                                                       
    double muPosPx, muPosPy, muPosPz,  muPosEta, muPosPt,muPosP;
    double muNegPx, muNegPy, muNegPz,  muNegEta, muNegPt,muNegP;
    //(1).Positive Muon                                     
    double muPos_nchi2In, muPos_dxy, muPos_dz, muPos_nchi2Gl;
    int muPos_found, muPos_pixeLayers, muPos_nValidMuHits,muPos_arbitrated;
    bool muPos_matches,muPos_tracker;
    //(2).Negative Muon                                     
    double muNeg_nchi2In, muNeg_dxy, muNeg_dz, muNeg_nchi2Gl;
    int muNeg_found, muNeg_pixeLayers, muNeg_nValidMuHits,muNeg_arbitrated;
    bool muNeg_matches,muNeg_tracker;
    //Gen Level variables
    //Gen JPsi Variables
    double GenJpsiMass, GenJpsiPt, GenJpsiRap;
    double GenJpsiPx, GenJpsiPy, GenJpsiPz;
    
    //2.) Gen muon variables 
    double GenmuPosPx, GenmuPosPy, GenmuPosPz,  GenmuPosEta, GenmuPosPt;
    double GenmuNegPx, GenmuNegPy, GenmuNegPz,  GenmuNegEta, GenmuNegPt;

    //Event variables
    tree->SetBranchAddress("eventNb",&eventNb);
    tree->SetBranchAddress("runNb",&runNb);
    tree->SetBranchAddress("lumiBlock",&lumiBlock);
    
    //Jpsi Variables
    tree->SetBranchAddress("JpsiCharge",&JpsiCharge);
    tree->SetBranchAddress("JpsiMass",&JpsiMass);
    tree->SetBranchAddress("JpsiPt",&JpsiPt);
    tree->SetBranchAddress("JpsiRap",&JpsiRap);
    tree->SetBranchAddress("JpsiVprob",&JpsiVprob);
    tree->SetBranchAddress("rbin",&rbin);
    
    //muon variable
    tree->SetBranchAddress("muPosPx",&muPosPx);
    tree->SetBranchAddress("muPosPy",&muPosPy);
    tree->SetBranchAddress("muPosPz",&muPosPz);
    tree->SetBranchAddress("muPosEta",&muPosEta);
    tree->SetBranchAddress("muNegPx", &muNegPx);
    tree->SetBranchAddress("muNegPy",    &muNegPy);
    tree->SetBranchAddress("muNegPz",    &muNegPz);
    tree->SetBranchAddress("muNegEta",    &muNegEta);
    //1). Positive Muon
    tree->SetBranchAddress("muPos_nchi2In", &muPos_nchi2In);
    tree->SetBranchAddress("muPos_dxy", &muPos_dxy);
    tree->SetBranchAddress("muPos_dz", &muPos_dz);
    tree->SetBranchAddress("muPos_nchi2Gl", &muPos_nchi2Gl);
    tree->SetBranchAddress("muPos_found", &muPos_found);
    tree->SetBranchAddress("muPos_pixeLayers", &muPos_pixeLayers);
    tree->SetBranchAddress("muPos_nValidMuHits", &muPos_nValidMuHits);
    tree->SetBranchAddress("muPos_matches", &muPos_matches);
    tree->SetBranchAddress("muPos_tracker", &muPos_tracker);
    tree->SetBranchAddress("muPos_arbitrated", &muPos_arbitrated);
    
    //2). Negative Muon                                                                            
    tree->SetBranchAddress("muNeg_nchi2In", &muNeg_nchi2In);
    tree->SetBranchAddress("muNeg_dxy", &muNeg_dxy);
    tree->SetBranchAddress("muNeg_dz", &muNeg_dz);
    tree->SetBranchAddress("muNeg_nchi2Gl", &muNeg_nchi2Gl);
    tree->SetBranchAddress("muNeg_found", &muNeg_found);
    tree->SetBranchAddress("muNeg_pixeLayers", &muNeg_pixeLayers);
    tree->SetBranchAddress("muNeg_nValidMuHits", &muNeg_nValidMuHits);
    tree->SetBranchAddress("muNeg_matches", &muNeg_matches);
    tree->SetBranchAddress("muNeg_tracker", &muNeg_tracker);
    tree->SetBranchAddress("muNeg_arbitrated", &muNeg_arbitrated);
    
    //====================================Gen Variables=========================================================
    //Gen Jpsi Variables
    gentree->SetBranchAddress("GenJpsiMass",   &GenJpsiMass);
    gentree->SetBranchAddress("GenJpsiPt",     &GenJpsiPt);
    gentree->SetBranchAddress("GenJpsiRap",    &GenJpsiRap);
    gentree->SetBranchAddress("GenJpsiPx",     &GenJpsiPx);
    gentree->SetBranchAddress("GenJpsiPy",     &GenJpsiPy);
    gentree->SetBranchAddress("GenJpsiPz",     &GenJpsiPz);
    gentree->SetBranchAddress("gbin",&gbin);
    //muon variable
    gentree->SetBranchAddress("GenmuPosPx",    &GenmuPosPx);
    gentree->SetBranchAddress("GenmuPosPy",    &GenmuPosPy);
    gentree->SetBranchAddress("GenmuPosPz",    &GenmuPosPz);
    gentree->SetBranchAddress("GenmuPosEta",    &GenmuPosEta);
    gentree->SetBranchAddress("GenmuNegPx",    &GenmuNegPx);
    gentree->SetBranchAddress("GenmuNegPy",    &GenmuNegPy);
    gentree->SetBranchAddress("GenmuNegPz",    &GenmuNegPz);
    gentree->SetBranchAddress("GenmuNegEta",    &GenmuNegEta);
    

    //====================================================== Gen tree loop ================================================
    int NAccep=0;
    int nGenEntries=gentree->GetEntries();
    cout<<" Total Entries in GenLevel Tree for pT range: "<<fileName[ifile]<<"  "<<   nGenEntries<< " ========="<<endl;
    //dataFile<<" Total Entries in GenLevel Tree for pT range: "<<fileName[ifile]<<"  "<<   nGenEntries<< " ====="<<endl;
    
    
    for(int i=0; i< nGenEntries; i++)  {	    
      gentree->GetEntry(i);
      
      if(i%1000==0){
	cout<<" processing record "<<i<<endl;
	cout<<" Mass "<< GenJpsiMass<< " pT "<< GenJpsiPt << " Y " <<GenJpsiRap<<endl; 
      }
      
      bool GenPosIn=0, GenNegIn=0,GenPosPass=0,GenNegPass=0;
      
      GenmuPosPt= TMath::Sqrt(GenmuPosPx*GenmuPosPx + GenmuPosPy*GenmuPosPy); 
      GenmuNegPt= TMath::Sqrt(GenmuNegPx*GenmuNegPx + GenmuNegPy*GenmuNegPy); 
            
      diMuonsInvMass_Gen->Fill(GenJpsiMass);
      diMuonsPt_Gen->Fill(GenJpsiPt);
 
      if(IsAccept(GenmuPosPt, GenmuPosEta)) {GenPosIn=1;}
      if(IsAccept(GenmuNegPt, GenmuNegEta)) {GenNegIn=1;}
      
     
      if(GenPosIn && GenNegIn ) NAccep++;
      
      if(GenPosIn==1 && GenmuPosPt> PtCut) {GenPosPass=1;}
      if(GenNegIn==1 && GenmuNegPt> PtCut) {GenNegPass=1;}

      double GenCenWeight=0,GenWeight=0;
      GenCenWeight=FindCenWeight(gbin);
      Bin_Gen->Fill(gbin);
      GenWeight=GenCenWeight*scale[ifile];
      if(PutWeight==0){GenWeight=1;}
      
      if(GenPosIn && GenNegIn){
	if(ifile==0){diMuonsRap_Gen0->Fill(GenJpsiRap);}
	if(ifile==1){diMuonsRap_Gen1->Fill(GenJpsiRap);}
	if(ifile==2){diMuonsRap_Gen2->Fill(GenJpsiRap);}
	if(ifile==3){diMuonsRap_Gen3->Fill(GenJpsiRap);}
	if(ifile==4){diMuonsRap_Gen4->Fill(GenJpsiRap);}
	if(ifile==5){diMuonsRap_Gen5->Fill(GenJpsiRap);}
      }
      
      
      for (Int_t ih = 0; ih < Nptbin; ih++) {
	//adding pT of all pt bins to see diss is cont
	if(iSpec == 1)  if( (GenPosPass==1 && GenNegPass==1) && (TMath::Abs(GenJpsiRap)<2.4 ) && (GenJpsiPt>pt_bound[ih] && GenJpsiPt<=pt_bound[ih+1])){diMuonsPt_GenA[ifile][ih]->Fill(GenJpsiPt,GenWeight);}
	
	if(iSpec == 1)  if( (GenPosPass==1 && GenNegPass==1) && (TMath::Abs(GenJpsiRap)<2.4 )&&(GenJpsiPt>pt_bound[ih] && GenJpsiPt<=pt_bound[ih+1])){diMuonsInvMass_GenA[ifile][ih]->Fill(GenJpsiMass,GenWeight);}
	//if(iSpec == 2)  if((GenPosPass==1 && GenNegPass==1) &&  (GenJpsiPt<20.0) && (TMath::Abs(GenJpsiRap) > pt_bound[ih] && TMath::Abs(GenJpsiRap) <=pt_bound[ih+1] )){diMuonsInvMass_GenA[ifile][ih]->Fill(GenJpsiMass,GenWeight);}
	

	//for non symetric plots
	if(iSpec == 2)  if((GenPosPass==1 && GenNegPass==1) &&  (GenJpsiPt<20.0) && ((GenJpsiRap) > pt_bound[ih] && (GenJpsiRap) <=pt_bound[ih+1] )){diMuonsInvMass_GenA[ifile][ih]->Fill(GenJpsiMass,GenWeight);}

	if(iSpec == 3)  if( (GenPosPass==1 && GenNegPass==1) && (GenJpsiPt < 20.0) &&  (TMath::Abs(GenJpsiRap)<2.4 ) && (gbin>=pt_bound[ih] && gbin<pt_bound[ih+1])){diMuonsInvMass_GenA[ifile][ih]->Fill(GenJpsiMass,GenWeight);}
	
      }
      
    }//gen loop end
    
    cout<<" accepted no "<< NAccep<<endl;
    //dataFile<<" accepted no "<< NAccep<<endl;
    
    //   new TCanvas;
    //diMuonsInvMass_Gen->Draw();
    //gPad->Print("plots/diMuonsInvMass_Gen.png");
    
    //new TCanvas;
    //diMuonsPt_Gen->Draw();
    //gPad->Print("plots/diMuonsPt_Gen.png");
    
    //new TCanvas;
    //diMuonsRap_Gen0->Draw();
    //sprintf(PlotName,"plots/diMuonsRap_Gen_%d.pdf",ifile);   
    //gPad->Print(PlotName);
    
    //new TCanvas;
    //Bin_Gen->Draw();
    //gPad->Print("plots/Bin_Gen.png");
    
    
    
    //=============== Rec Tree Loop ==============================================================================
    
    int nRecEntries=tree->GetEntries();
    cout<<"Total Entries in reconstructed Tree for pT range "<<fileName[ifile]<<"  "<<nRecEntries<< "====="<<endl;
    //dataFile<<"Total Entries in reconstructed Tree for pT range "<<fileName[ifile]<<"  "<<nRecEntries<<endl;
    
    for(int i=0; i<nRecEntries; i++)  {	    
      tree->GetEntry(i);
      if(i%100000==0){
	cout<<" processing record "<<i<<endl;
	cout<<" processing Run  " <<runNb <<" event "<<eventNb<<" lum block "<<lumiBlock<<endl;    
	cout<<" Mass "<< JpsiMass<< " pT "<< JpsiPt << " Y " <<JpsiRap<<"  "<<JpsiVprob<<" charge "<<JpsiCharge<<endl; 
      }
      
      bool PosPass=0, NegPass=0, AllCut=0 ,PosIn=0, NegIn=0;
      muPosPt= TMath::Sqrt(muPosPx*muPosPx + muPosPy*muPosPy); 
      muPosP = TMath::Sqrt(muPosPx*muPosPx + muPosPy*muPosPy+ muPosPz*muPosPz); 
      muNegPt= TMath::Sqrt(muNegPx*muNegPx + muNegPy*muNegPy); 
      muNegP = TMath::Sqrt(muNegPx*muNegPx + muNegPy*muNegPy +muNegPz*muNegPz); 
    
      if(IsAccept(muPosPt, muPosEta)){PosIn=1;}
      if(IsAccept(muNegPt, muNegEta)){NegIn=1;}
      
      if(muPos_found > 10 && muPos_pixeLayers > 0 && muPos_nchi2In < 4.0 && muPos_dxy < 3 && muPos_dz < 15 && muPos_nchi2Gl < 20 &&  muPos_arbitrated==1 && muPos_tracker==1 ){PosPass=1;}	  
	 
	 if((muNeg_found >10 && muNeg_pixeLayers >0 && muNeg_nchi2In <4.0 && muNeg_dxy < 3 && muNeg_dz < 15 && muNeg_nchi2Gl < 20 && muNeg_arbitrated==1 && muNeg_tracker==1)){NegPass=1;}

      

	     // cout<<muPos_matches<<"  "<<muNeg_matches<<endl;

	  if((muPosPt > PtCut && muNegPt > PtCut) && (muPos_matches==1 && muNeg_matches==1) && (PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)){AllCut=1;}
	 
	 //without muon ID cuts
	 //if((muPosPt > PtCut && muNegPt > PtCut) && (muPos_matches==1 && muNeg_matches==1) && (PosIn==1 && NegIn==1)){AllCut=1;}
	 
	 //without trigger
	 //if(  (muPosPt > PtCut && muNegPt > PtCut) && (PosIn==1 && NegIn==1 )  &&   (PosPass==1 && NegPass==1)){AllCut=1;}
	 
	 
	 double RecCenWeight=0,RecWeight=0;
	 RecCenWeight=FindCenWeight(rbin);
	 RecWeight=RecCenWeight*scale[ifile];
	 if(PutWeight==0){RecWeight=1;}
	 
	 if(i%100000==0){
	   cout<<" eff loop for reco "<<endl;
	 }
      
	 if(AllCut==1){
	   if(ifile==0){diMuonsRap_Rec0->Fill(JpsiRap);}
	   if(ifile==1){diMuonsRap_Rec1->Fill(JpsiRap);}
	   if(ifile==2){diMuonsRap_Rec2->Fill(JpsiRap);}
	   if(ifile==3){diMuonsRap_Rec3->Fill(JpsiRap);}
	   if(ifile==4){diMuonsRap_Rec4->Fill(JpsiRap);}
	   if(ifile==5){diMuonsRap_Rec5->Fill(JpsiRap);}
	 }

	 //Eff loop for reco
	 if((JpsiCharge == 0) && (JpsiVprob > 0.01)) {
	   for (Int_t ih = 0; ih < Nptbin; ih++) {
	     //to see cont reco pT

	     if(iSpec == 1)if((AllCut==1) && (TMath::Abs(JpsiRap) < 2.4) && (JpsiPt>pt_bound[ih] && JpsiPt<=pt_bound[ih+1])) {diMuonsPt_RecA[ifile][ih]->Fill(JpsiPt,RecWeight);}
	     if(iSpec == 1)if((AllCut==1) && (TMath::Abs(JpsiRap)<2.4 ) && (JpsiPt > pt_bound[ih] && JpsiPt <=pt_bound[ih+1])){diMuonsInvMass_RecA[ifile][ih]->Fill(JpsiMass, RecWeight);}
	    

	     //if(iSpec == 2) if( (AllCut==1) &&  (JpsiPt<20.0) && (TMath::Abs(JpsiRap) > pt_bound[ih] && TMath::Abs(JpsiRap) <=pt_bound[ih+1])){diMuonsInvMass_RecA[ifile][ih]->Fill(JpsiMass,RecWeight);}
	     
	     //for non symetric plots
	     if(iSpec == 2) if( (AllCut==1) &&  (JpsiPt<20.0) && ((JpsiRap) > pt_bound[ih] && (JpsiRap) <=pt_bound[ih+1])){diMuonsInvMass_RecA[ifile][ih]->Fill(JpsiMass,RecWeight);}
	     

	     if(iSpec == 3) if((AllCut==1) &&  (JpsiPt<20.0) && (TMath::Abs(JpsiRap) < 2.4) && (rbin>=pt_bound[ih] &&  rbin < pt_bound[ih+1])){diMuonsInvMass_RecA[ifile][ih]->Fill(JpsiMass,RecWeight);}
	     
	   }
	 }
 }
  
    /*
      new TCanvas;
      if(ifile==0){diMuonsRap_Gen0->Draw();new TCanvas; diMuonsRap_Rec0->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen0.png");}
      if(ifile==1){diMuonsRap_Gen1->Draw();new TCanvas; diMuonsRap_Rec1->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen1.png");}
      if(ifile==2){diMuonsRap_Gen2->Draw();new TCanvas; diMuonsRap_Rec2->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen2.png");}
      if(ifile==3){diMuonsRap_Gen3->Draw();new TCanvas; diMuonsRap_Rec3->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen3.png");}
      if(ifile==4){diMuonsRap_Gen4->Draw();new TCanvas; diMuonsRap_Rec4->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen4.png");}
      if(ifile==5){diMuonsRap_Gen5->Draw();new TCanvas; diMuonsRap_Rec5->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen5.png");}
    */
    }  // file loop ends 

  ///////////////////////////////////////////////////////////////////

  cout<< " adding "<<endl;
  TH1D *diMuonsInvMass_RecA1[100];
  TH1D *diMuonsInvMass_GenA1[100];
  TH1D *diMuonsPt_GenA1[100];
  TH1D *diMuonsPt_RecA1[100];
  TF1 *backfun_1;
  char namePt_1B[500];//for bkg func
 
  for(Int_t ih = 0; ih < Nptbin; ih++){
    diMuonsInvMass_RecA1[ih] = diMuonsInvMass_RecA[0][ih];
    diMuonsInvMass_GenA1[ih] = diMuonsInvMass_GenA[0][ih];
    diMuonsPt_GenA1[ih] = diMuonsPt_GenA[0][ih];
    diMuonsPt_RecA1[ih] = diMuonsPt_RecA[0][ih];
    
    for (int ifile = 1; ifile <= 5; ifile++) {
      diMuonsInvMass_RecA1[ih]->Add(diMuonsInvMass_RecA[ifile][ih]);
      diMuonsInvMass_GenA1[ih]->Add(diMuonsInvMass_GenA[ifile][ih]);     
      
      diMuonsPt_GenA1[ih]->Add(diMuonsPt_GenA[ifile][ih]); 
      diMuonsPt_RecA1[ih]->Add(diMuonsPt_RecA[ifile][ih]); 
    }
  }
  
  //===========================Fitting===================================================================//
  // Fit ranges
  double mass_low, mass_high;
  double MassUpsilon, WeidthUpsilon;
  
  // Low mass range upsilon width 54 KeV
  MassUpsilon = 9.46; WeidthUpsilon = 0.060;
  mass_low = 8.8; mass_high = 10.0;  // Fit ranges
  
  
  // Fit Function crystall ball
  // TF1 *GAUSPOL = new TF1("GAUSPOL",CrystalBall,8.0,12.0,5);
  //GAUSPOL->SetParNames("#alpha","n","Mean","#sigma","N");
  //GAUSPOL->SetLineWidth(2.0);
  //GAUSPOL->SetLineColor(2);
  //GAUSPOL->SetParameter(0, 1.756);
  //GAUSPOL->SetParameter(1, 2.636);
  //GAUSPOL->SetParameter(2, MassUpsilon);
  //GAUSPOL->SetParameter(3, WeidthUpsilon);
  //GAUSPOL->SetParLimits(2, 0.1*MassUpsilon,2.0*MassUpsilon);
  //GAUSPOL->SetParLimits(3, 0.1*WeidthUpsilon,2.0*WeidthUpsilon);


 // Fit Function crystall ball
  TF1 *GAUSPOL = new TF1("GAUSPOL",CrystalBall,8.0,12.0,6);
  GAUSPOL->SetParNames("Yield (#Upsilon)","BinWidth","Mean","Sigma","#alpha","n");
  GAUSPOL->SetParameter(2, MassUpsilon);
  GAUSPOL->SetParameter(3, WeidthUpsilon);
  GAUSPOL->SetParLimits(3, 0.1*WeidthUpsilon,2.0*WeidthUpsilon);
  GAUSPOL->SetParameter(4, 1.0);
  GAUSPOL->SetParameter(5, 20.0);
  GAUSPOL->SetLineWidth(2.0);
  GAUSPOL->SetLineColor(2);
  


  //=====================Loop for eff===========================================================
  double GenNo[100]={0};
  double Eff[100]={0};
  double GenError[100]={0};
  double RecError[100]={0};
  double errEff_cat_S1[100]={0};
  double errEff_cat_S2[100]={0};
  double errEff_cat_S1_1[100]={0},errEff_cat_S1_2[100]={0};
  double errEff_cat_S2_1[100]={0},errEff_cat_S2_2[100]={0};
  char PlotName[500],PlotName1[500], PlotName2[500]; 
  char GPlotName[500],GPlotName1[500], GPlotName2[500];

  for (Int_t ih = 0; ih < Nptbin; ih++) {
   
    cout<<" no of gen dimuons from diMuons Pt histo    "<<diMuonsPt_GenA1[ih]->Integral(1,100)<<endl;
    cout<<" no of gen dimuons from diMuons Mass histo  "<<diMuonsInvMass_GenA1[ih]->Integral(1,100)<<endl;
    

    //from pT histogram
    //gen_pt[ih] =diMuonsPt_GenA1[ih]->IntegralAndError(1,100,genError);
   
    gen_pt[ih] = diMuonsInvMass_GenA1[ih]->IntegralAndError(1,100,genError);
    gen_ptError[ih]= genError;
    
    if(iSpec==1) sprintf(PlotName,"plots/DiMuonMass_PtBin_%d.png",ih);
    if(iSpec==2) sprintf(PlotName,"plots/DiMuonMass_RapBin_%d.png",ih);
    if(iSpec==3) sprintf(PlotName,"plots/DiMuonMass_CentBin_%d.png",ih);
    
    if(iSpec==1) sprintf(PlotName1,"plots/DiMuonMass_PtBin_%d.pdf",ih);
    if(iSpec==2) sprintf(PlotName1,"plots/DiMuonMass_RapBin_%d.pdf",ih);
    if(iSpec==3) sprintf(PlotName1,"plots/DiMuonMass_CentBin_%d.pdf",ih);
    
    if(iSpec==1) sprintf(PlotName2,"plots/DiMuonMass_PtBin_%d.eps",ih);
    if(iSpec==2) sprintf(PlotName2,"plots/DiMuonMass_RapBin_%d.eps",ih);
    if(iSpec==3) sprintf(PlotName2,"plots/DiMuonMass_CentBin_%d.eps",ih);
 
    //giving inetial value for crystall ball fourth parameter 
    diMuonsInvMass_RecA1[ih]->Rebin(2);
    //GAUSPOL->SetParameter(0, diMuonsInvMass_RecA1[ih]->GetMaximum());
    GAUSPOL->SetParameter(0, diMuonsInvMass_RecA1[ih]->Integral(0,50));
    GAUSPOL->FixParameter(1, diMuonsInvMass_RecA1[ih]->GetBinWidth(1));
    
    new TCanvas; 
    diMuonsInvMass_RecA1[ih]->Fit("GAUSPOL","LLMERQ", "", mass_low, mass_high);
   
    double UpsilonMass = GAUSPOL->GetParameter(2);
    double UpsilonWidth = GAUSPOL->GetParameter(3);
   
    double UpsilonYield = GAUSPOL->GetParameter(0);
    double UpsilonYieldError = GAUSPOL->GetParError(0);

    double par[20];
    GAUSPOL->GetParameters(par);
    sprintf(namePt_1B,"pt_1B_%d",ih);
    backfun_1 = new TF1(namePt_1B, Pol2, mass_low, mass_high, 3);
    backfun_1->SetParameters(&par[4]);
   

    double MassLow=(UpsilonMass-3*UpsilonWidth);
    double MassHigh=(UpsilonMass+3*UpsilonWidth);
    
    int binlow =diMuonsInvMass_RecA1[ih]->GetXaxis()->FindBin(MassLow);
    int binhi =diMuonsInvMass_RecA1[ih]->GetXaxis()->FindBin(MassHigh);
    double binwidth=diMuonsInvMass_RecA1[ih]->GetBinWidth(1);
        
    //yield by function 
    //rec_pt[ih] = UpsilonYield;
    //rec_ptError[ih]=UpsilonYieldError;

    cout<<"Rec diMuons from Pt histo "<<diMuonsPt_RecA1[ih]->Integral(1,100)<<endl;  
    cout<<"Rec dimuons from mass "<<diMuonsInvMass_RecA1[ih]->Integral(1,100)<<endl; 
    

      
    //from pT histo
    //rec_pt[ih]=diMuonsPt_RecA1[ih]->IntegralAndError(1, 100,recError);

    //yield by histogram integral
    rec_pt[ih] = diMuonsInvMass_RecA1[ih]->IntegralAndError(binlow, binhi,recError);
    rec_ptError[ih]= recError;
  
    //Cal eff 
    Eff_cat_1[ih] = rec_pt[ih]/gen_pt[ih]; 
  
    //calculate error on eff
    GenNo[ih]=gen_pt[ih];
    Eff[ih]= Eff_cat_1[ih];
    GenError[ih]=gen_ptError[ih];
    RecError[ih]=rec_ptError[ih];
    //error    
    errEff_cat_S1_1[ih]= ( (Eff[ih] * Eff[ih]) /(GenNo[ih] * GenNo[ih]) );
    errEff_cat_S1_2[ih]= (RecError[ih] * RecError[ih]);
    errEff_cat_S1[ih]= (errEff_cat_S1_1[ih] * errEff_cat_S1_2[ih]);
   

    errEff_cat_S2_1[ih]= ( (1 - Eff[ih])* (1 - Eff[ih]) ) / ( GenNo[ih] * GenNo[ih]);
    errEff_cat_S2_2[ih]= (GenError[ih] * GenError[ih] ) - ( RecError[ih] * RecError[ih] );


    errEff_cat_S2[ih]=errEff_cat_S2_1[ih]*errEff_cat_S2_2[ih];
    Err_Eff_cat_1[ih]=sqrt(errEff_cat_S1[ih] + errEff_cat_S2[ih]);
   
    //error for no weights
    //Err_Eff_cat_1[ih]= Eff_cat_1[ih]*TMath::Sqrt(gen_ptError[ih]*gen_ptError[ih]/(gen_pt[ih]*gen_pt[ih]) + rec_ptError[ih]*rec_ptError[ih]/(rec_pt[ih]* rec_pt[ih]));

    cout<<"Upsilon Yield by integral of histo:  "<< diMuonsInvMass_RecA1[ih]->IntegralAndError(binlow, binhi,recError) <<"  error "<< rec_ptError[ih]<<endl; 
    cout<<"UpsilonYield by CB    yield det:     "<< UpsilonYield << " UpsilonWidth "<< UpsilonWidth<<" UpsilonMass "<<UpsilonMass <<endl;
    cout<<"Upsilon Yield by Function integral:  "<< GAUSPOL->Integral(MassLow,MassHigh)/binwidth <<endl;
    cout<<" rec_pt[ih]  "<<  rec_pt[ih] <<" gen_pt[ih] "<<gen_pt[ih]<<endl;
    //dataFile<<" rec_pt[ih]  "<<  rec_pt[ih] <<" gen_pt[ih] "<<gen_pt[ih]<<endl;
    cout<<" eff "<< Eff_cat_1[ih]<<" error "<<Err_Eff_cat_1[ih]<<endl;
    
    dataFile<<"ih " <<ih<<" eff "<< Eff_cat_1[ih]<<" error "<<Err_Eff_cat_1[ih]<<endl;
    
    if(iSpec==1) sprintf(GPlotName,"plots/GenDiMuonMass_PtBin_%d.png",ih);
    if(iSpec==2) sprintf(GPlotName,"plots/GenDiMuonMass_RapBin_%d.png",ih);
    if(iSpec==3) sprintf(GPlotName,"plots/GenDiMuonMass_CentBin_%d.png",ih);
    
    if(iSpec==1) sprintf(GPlotName1,"plots/GenDiMuonMass_PtBin_%d.pdf",ih);
    if(iSpec==2) sprintf(GPlotName1,"plots/GenDiMuonMass_RapBin_%d.pdf",ih);
    if(iSpec==3) sprintf(GPlotName1,"plots/GenDiMuonMass_CentBin_%d.pdf",ih);
    
    if(iSpec==1) sprintf(GPlotName2,"plots/GenDiMuonMass_PtBin_%d.eps",ih);
    if(iSpec==2) sprintf(GPlotName2,"plots/GenDiMuonMass_RapBin_%d.eps",ih);
    if(iSpec==3) sprintf(GPlotName2,"plots/GenDiMuonMass_CentBin_%d.eps",ih);
       
    backfun_1->SetLineColor(4);
    backfun_1->SetLineWidth(1);
    //backfun_1->Draw("same");
    gPad->Print(PlotName);
    gPad->Print(PlotName1);
    gPad->Print(PlotName2);

    new TCanvas;
    diMuonsInvMass_GenA1[ih]->Draw();
    gPad->Print(GPlotName);
    gPad->Print(GPlotName1);
    gPad->Print(GPlotName2);


    // new TCanvas;
    //diMuonsPt_GenA1[ih]->Draw();
    //new TCanvas;
    //diMuonsPt_RecA1[ih]->Draw();
 
}
  dataFile.close();

   TFile *outfile;
  if(iSpec==1)outfile =new TFile("EffUpsilon_Pt.root","Recreate");
  if(iSpec==2)outfile =new TFile("EffUpsilon_Rap.root","Recreate");
  if(iSpec==3)outfile =new TFile("EffUpsilon_Cent.root","Recreate");

  TGraphErrors *Eff_Upsilon = new TGraphErrors(Nptbin, PT, Eff_cat_1, mom_err,Err_Eff_cat_1);
  Eff_Upsilon->SetMarkerStyle(21);
  Eff_Upsilon->SetMarkerColor(2);
  Eff_Upsilon->GetYaxis()->SetTitle("Reco Eff");
 
  if(iSpec==1) Eff_Upsilon->GetXaxis()->SetTitle("#Upsilon pT (GeV/c^{2})");
  if(iSpec==2) Eff_Upsilon->GetXaxis()->SetTitle("#Upsilon rapidity");
  if(iSpec==3) Eff_Upsilon->GetXaxis()->SetTitle("bin");
   Eff_Upsilon->GetYaxis()->SetRangeUser(0,1.0);

  TLegend *legend_GP = new TLegend( 0.50,0.79,0.80,0.89);
  legend_GP->SetBorderSize(0);
  legend_GP->SetFillStyle(0);
  legend_GP->SetFillColor(0);
  legend_GP->SetTextSize(0.032);
  legend_GP->AddEntry(Eff_Upsilon,"PythiaEvtGen + HydjetBass", "P");
  
  new TCanvas;
  Eff_Upsilon->Draw("AP");
  legend_GP->Draw("Same");
    
 Eff_Upsilon->Write();

  if(iSpec==1){ gPad->Print("plots/Eff_Upsilon_Pt.pdf");gPad->Print("plots/Eff_Upsilon_Pt.png");gPad->Print("plots/Eff_Upsilon_Pt.eps");}
  if(iSpec==2){ gPad->Print("plots/Eff_Upsilon_Rap.pdf");gPad->Print("plots/Eff_Upsilon_Rap.png");  gPad->Print("plots/Eff_Upsilon_Rap.eps");}
  if(iSpec==3){ gPad->Print("plots/Eff_Upsilon_Cent.pdf");gPad->Print("plots/Eff_Upsilon_Cent.png"); gPad->Print("plots/Eff_Upsilon_Cent.eps"); }
 
  outfile->Write();
  outfile->Close();



}
Ejemplo n.º 14
0
int main(int argc, char* argv[]){
    UImanager uimanager(argc, argv, "dndt_fit");
//work directory    
    TString workdir(getenv("WORKDIR"));
//***************************set constant ****************************************
    Double_t acdntl_corr = 1., respf_corr = 1.;
	Double_t eff_corr = uimanager.get_adcerr() * uimanager.get_br_corr() * uimanager.get_ta_corr() * acdntl_corr * respf_corr;//	adcerr x tdiff_cut_eff x veto_eff x pi0 decay products abs. (set to 1, since included in current rmat) x bkg_in_fit (not in current rmat)
    if(uimanager.best_tdiff()) eff_corr *= uimanager.get_bit_corr();
    if(uimanager.ismc()) eff_corr = uimanager.get_ta_corr(); 

    cout << eff_corr << " " << uimanager.flux() << " " << uimanager.get_tgt_lumi() << endl;
	Double_t f_l = uimanager.flux() * uimanager.get_tgt_lumi() * eff_corr;

//************ start reading files *******************************
//read tables/eflux.dat [tables/effcor.dat] tables/dfp1_xx.dat or current_foler/dfp1_xx.dat
//get echn flux
	Double_t flw[180];
	ifstream eflux(workdir+"tables/eflux.dat");
	if (!eflux.is_open()) {
		cout << "eflux doesn't exist" << endl;
		exit(1);
 	}
	for(int i=0;i<180;i++)eflux>>flw[i];
//get efficiency table
    TString dfp;
    if (!uimanager.target()) dfp = Form("dfp%d", int(uimanager.isouter())) + uimanager.input_filename("mc") + "_si.dat";
    else dfp = Form("dfp%d", int(uimanager.isouter())) + uimanager.input_filename("mc") + "_c12.dat";

	ifstream profile;
    profile.open(dfp);
    if (profile.is_open()) {
        cout << "use local efficiency table: " << dfp << endl;
    } else {
        //profile.open(workdir+"efficiency2/tables/"+dfp);
        profile.open(workdir+"/tables/"+dfp);
        if(!profile.is_open()) cout << " can't open table " << dfp << endl;
        cout << " use efficiency table in tables: " << dfp << endl;
    }
	
    const int phy = 5;
	const int ech = 180;
	Double_t dfprob[phy][nangle][ech];
	Double_t coulm[nangle], ncohe[nangle], cosfiint[nangle], sinfiint[nangle], ninco[nangle];
	for(int i=0;i<nangle;i++){
		coulm[i]=0;
        ncohe[i]=0;
		cosfiint[i]=0;
		sinfiint[i]=0;
		ninco[i]=0;
	}

	for(int i = 0;i < 180;i++)
		for(int j = 0;j < nangle;j++)
			for(int k = 0;k < 5;k++){
				Double_t f_l_j=f_l;
				int ic = 0;
				int jc = 0;
				int kc = 0;
				profile>>ic>>jc>>kc>>dfprob[k][j][i];
                if(ic!=i+1||jc!=j+1||kc!=k+1){
					cout << i << " " << j << " " << k << endl;
					cout << ic << " " << jc << " " << kc << " " << dfprob[k][j][i] << endl;
					cout<<"Bad data given for dfprob"<<endl;
					exit(1);
				}
				if(kc==1)coulm[j]+=flw[i]*dfprob[k][j][i]*f_l_j;
				else if(kc==2)cosfiint[j]+=flw[i]*dfprob[k][j][i]*f_l_j;
				else if(kc==3)ncohe[j]+=flw[i]*dfprob[k][j][i]*f_l_j;
				else if(kc==4)ninco[j]+=flw[i]*dfprob[k][j][i]*f_l_j;
				else sinfiint[j]+=flw[i]*dfprob[k][j][i]*f_l_j;
            }

	for(int i=1;i<=nangle;i++){
		hcoulm->SetBinContent(i,coulm[i-1]);
		hcosfiint->SetBinContent(i,cosfiint[i-1]);
		hncohe->SetBinContent(i,ncohe[i-1]);
		hninco->SetBinContent(i,ninco[i-1]);
		hsinfiint->SetBinContent(i,sinfiint[i-1]);
    }
//read yield
    TString inrootname("pi0alt" + uimanager.input_filename("fit") + ".root");

	TFile *yield = new TFile(inrootname);
    if (!yield->IsOpen()) exit(open_err(inrootname));
	TH1F *yieldhist = (TH1F*)yield->Get("hyield");
	//TH1F *yieldhist = (TH1F*)yield->Get("hyield_mc_nocut");
	yieldhist->SetDirectory(0);
	if (!uimanager.target() && !uimanager.isouter()) yieldhist->SetTitle("#pi^{0} yield (Si, crystal w/o tran.)");
    else if (!uimanager.target()) yieldhist->SetTitle("#pi^{0} yield (Si, crystal w/ tran.)");
    else if (!uimanager.isouter()) yieldhist->SetTitle("#pi^{0} yield (C12, crystal w/o tran.)");
    else yieldhist->SetTitle("#pi^{0} yield (C12, crystal w/ tran.)");
    
    double nyield = 0, nyield_err = 0;
    for(int i = 1; i<=125; i++) {
        nyield += yieldhist->GetBinContent(i);
        nyield_err += yieldhist->GetBinError(i)*yieldhist->GetBinError(i);
    }
    nyield_err = sqrt(nyield_err);
//***************** end reading files **************************************
    
	gStyle->SetOptFit(1);
	gStyle->SetOptStat(0);
	gStyle->SetPaperSize(12,24);
	//Double_t parameter[4] = {7.9, 1.0, 1.0, 0.8};
	Double_t parameter[4] = {7.7, 1.0, 0.8, 0.5};

	TF1 *ftot = new TF1("ftot", dndt, 0., dndt_fit_range, 4);
	ftot->SetParNames("#Gamma","C1","#phi","C2");

	ftot->SetParameter(0,parameter[0]);
	ftot->SetParameter(1,parameter[1]);
	ftot->SetParameter(2,parameter[2]);
	ftot->SetParameter(3,parameter[3]);
/*
	ftot->FixParameter(0,parameter[0]);
	ftot->FixParameter(1,parameter[1]);
	ftot->FixParameter(2,parameter[2]);
	ftot->FixParameter(3,parameter[3]);
*/
    ftot->SetParLimits(0, 3, 10);
    ftot->SetParLimits(1, 0.3, 1.5);
    ftot->SetParLimits(2, 0, 3.1415936/2);
    ftot->SetParLimits(3, 0., 10.0);

	yieldhist->Fit("ftot", "RMBE0");

	Double_t chi2 = ftot->GetChisquare()/ftot->GetNDF();
	parameter[0]=ftot->GetParameter(0);
	parameter[1]=ftot->GetParameter(1);
	parameter[2]=ftot->GetParameter(2);
	parameter[3]=ftot->GetParameter(3);
	
    Double_t e1 = ftot->GetParError(0);
    Double_t e2 = ftot->GetParError(1);
    Double_t e3 = ftot->GetParError(2);
    Double_t e4 = ftot->GetParError(3);

	//cout<<chi2<<" "<<parameter[0]<<" "<<parameter[1]<<" "<<parameter[2]<<" "<<parameter[3]<<endl;
    TString fname = "fitresult" + uimanager.input_filename("fit") + ".dat";
    ofstream output(fname);
    output<<nyield<<" "<<nyield_err<<" "<<chi2<<" "<<parameter[0]<<" "<<e1<<" "<<parameter[1]<<" "<<e2<<" "<<parameter[2]<<" "<<e3<<" "<<parameter[3]<<" "<<e4<<endl;

	TH1F *fithist = new TH1F("fithist", "fithist", fit_nangle, 0, dndt_fit_range);
	TH1F *fitcoulm = new TH1F("fitcolum", "fitcolum", fit_nangle, 0, dndt_fit_range);
	TH1F *fitncohe = new TH1F("fitncohe", "fitncohe", fit_nangle, 0, dndt_fit_range);
	TH1F *fitit = new TH1F("fitit", "fitit", fit_nangle, 0, dndt_fit_range);
	TH1F *fitninco = new TH1F("fitninco", "fitninco", fit_nangle, 0, dndt_fit_range);

	yieldhist->SetLineWidth(2);
	fithist->SetLineWidth(2);
	fitcoulm->SetLineWidth(2);
	fitncohe->SetLineWidth(2);
	fitit->SetLineWidth(2);
	fitninco->SetLineWidth(2);

	float accfit[fit_nangle], acchist[fit_nangle], acchisterr[fit_nangle], diff[fit_nangle];

	for(int i=1;i<=fit_nangle;i++){
		fithist->SetBinContent(i,ftot->Eval(max_angle/nangle*(i-0.5)));
		fitcoulm->SetBinContent(i,parameter[0]*hcoulm->GetBinContent(i));
		fitncohe->SetBinContent(i,parameter[1]*hncohe->GetBinContent(i));
		fitit->SetBinContent(i,TMath::Sqrt(parameter[0]*parameter[1])*(TMath::Cos(parameter[2])*hcosfiint->GetBinContent(i)+TMath::Sin(parameter[2])*hsinfiint->GetBinContent(i)));
		fitninco->SetBinContent(i,parameter[3]*hninco->GetBinContent(i));
		if (i == 1) {
			accfit[0] = fithist->GetBinContent(1);
			acchist[0] = yieldhist->GetBinContent(1);
			acchisterr[0] = yieldhist->GetBinError(1) * yieldhist->GetBinError(1);
		}
		if (i != fit_nangle) {
			acchist[i] = yieldhist->GetBinContent(i) + acchist[i - 1];
			accfit[i] = fithist->GetBinContent(i) + accfit[i - 1];
			acchisterr[i] = acchisterr[i - 1] + yieldhist->GetBinError(i) * yieldhist->GetBinError(i);
		}
	}

	for(int i = 0; i < fit_nangle; ++i) {
		
		diff[i] = acchist[i] - accfit[i];
		acchisterr[i] = sqrt(acchisterr[i]);
	}

	TString outfilename("fyield" + uimanager.input_filename("fit"));

	float angles[fit_nangle], ex[fit_nangle];
	for(int i=0;i<fit_nangle;i++) {
		angles[i] = 0.02*(i+0.5);
        ex[i] = 0;
    }

	TGraphErrors ge(fit_nangle, angles, diff, ex, acchisterr);
	TGraphErrors ge1(fit_nangle, angles, acchist, ex, acchisterr);
	TGraph ge2(fit_nangle, angles, accfit);

	TCanvas *c1 = new TCanvas("c1","c1",1600,1200);
	c1->SaveAs(outfilename+".pdf[");
	yieldhist->SetMinimum(0);
	yieldhist->SetMaximum(yieldhist->GetMaximum()*1.05);
	yieldhist->Draw("e1");
	fitcoulm->SetLineColor(kBlue);
	fitcoulm->Draw("sameC");
	fitncohe->SetLineColor(32);
	fitncohe->Draw("sameC");
	fitit->SetLineColor(kBlack);
	fitit->Draw("sameC");
	fitninco->SetLineColor(kYellow);
	fitninco->Draw("sameC");
	fithist->SetLineColor(kRed);
	fithist->Draw("sameC");

	TLegend *leg = new TLegend(0.1,0.7,0.45,0.9);
	leg->SetFillColor(0);
	leg->SetTextSize(0.03);
	leg->AddEntry(fitcoulm,"Primakoff","L");
	leg->AddEntry(fitncohe,"Nuclear Coherent","L");
	leg->AddEntry(fitit,"Interference","L");
	leg->AddEntry(fitninco,"Nuclear Incoherent","L");
	//leg->Draw();

	c1->SaveAs(outfilename+".pdf");

	ge.SetMarkerStyle(20);
	ge.SetMarkerColor(kBlue);
	ge.SetTitle("accumulated yield - fit vs. #theta");
	ge.Draw("ap");
	c1->SaveAs(outfilename + ".pdf");

	ge1.SetMarkerStyle(20);
	ge1.SetMarkerColor(kBlue);
	ge1.SetTitle("accumulated yield and fitting vs. #theta");
	ge1.Draw("ap");
	ge2.SetLineColor(kRed);
	ge2.Draw("sameC");
	c1->SaveAs(outfilename + ".pdf");

	c1->SaveAs(outfilename+".pdf]");

	TFile *ftyd = new TFile(outfilename+".root", "RECREATE");
	yieldhist->Write();
	fithist->Write();
	fitcoulm->Write();
	fitncohe->Write();
	fitit->Write();
	fitninco->Write();
    hcoulm->Write();
    hncohe->Write();
    hninco->Write();
	hcosfiint->Write();
    hsinfiint->Write();
    ftyd->Close();
    
	return 0;
}
int main(int argc, char* argv[]) {

  std::string outputDir = "AK4Jets_Plot";                 
  mkdir(outputDir.c_str(), 0777); 

  TString dataFileName_DoubleMu;
  //  dataFileName_DoubleMu = TString::Format("../../output/HLTReco_Comparison/rootFile_JEC_HLT_v7_RecoLowerCuts10GeV_DoubleMu.root");
  //  dataFileName_DoubleMu = TString::Format("../../output/HLTReco_Comparison/rootFile_JEC_HLT_v7_RecoLowerCuts10GeV_WideEtaBin_DoubleMu.root");
  dataFileName_DoubleMu = TString::Format("../../output/HLTReco_Comparison/rootFile_JEC_HLT_v7_RecoLowerCuts10GeV_WideEtaBin_DoubleMu.root");
  TFile* dataFile_DoubleMu = TFile::Open(dataFileName_DoubleMu);
  if (dataFile_DoubleMu) {
    std::cout << "Opened data file '" << dataFileName_DoubleMu << "'." << std::endl;
  }
  TString dataFileName_HT450;
  //  dataFileName_HT450 = TString::Format("../../output/HLTReco_Comparison/rootFile_JEC_HLT_v7_RecoLowerCuts10GeV_HT450.root");
  //  dataFileName_HT450 = TString::Format("../../output/HLTReco_Comparison/rootFile_JEC_HLT_v7_RecoLowerCuts10GeV_WideEtaBin_HT450.root");
  dataFileName_HT450 = TString::Format("../../output/HLTReco_Comparison/rootFile_JEC_HLT_v7_RecoLowerCuts10GeV_WideEtaBin_HT450.root");
  TFile* dataFile_HT450 = TFile::Open(dataFileName_HT450);
  if (dataFile_HT450) {
    std::cout << "Opened data file '" << dataFileName_HT450 << "'." << std::endl;
  }

  TH1D *pT_AK4JetHLT = (TH1D*)dataFile_HT450->Get("AK4_pT_JetHLT");

  gErrorIgnoreLevel = kWarning;

  TF1* lineup1      = new TF1("lineup1", " 0.01", 0, 3000);
  TF1* linedown1 = new TF1("linedown1", "-0.01", 0, 3000);
  lineup1->SetLineColor(kBlack);                                                                                                                                        
  lineup1->SetLineStyle(2);                                                                                                                                             
  linedown1->SetLineColor(kBlack);                                                                                                                                      
  linedown1->SetLineStyle(2);

  TF1* lineup2      = new TF1("lineup2", " 0.02", 0, 3000);
  TF1* linedown2 = new TF1("linedown2", "-0.02", 0, 3000);
  lineup2->SetLineColor(kBlack);                                                                                                                                        
  lineup2->SetLineStyle(2);                                                                                                                                             
  linedown2->SetLineColor(kBlack);                                                                                                                                      
  linedown2->SetLineStyle(2);


  // procedura
  // prendo gli istogramma 1D del bias
  // per ogni bin di pT e eta
  // li fitto con una cristal ball
  // poi grafico il picco in funzione del pT in ogni bin di eta
  // fitto con una funzione logaritmica
  // mi creo l'istogramma 2D (eta,pT) con correzione sull'asse z

  //////////////////////// pTBias 1D
  EtaBinning mEtaBinning;
  size_t etaBinningSize = mEtaBinning.size();
  PtBinning mPtBinning;
  size_t pTBinningSize = mPtBinning.size();

  cout<< etaBinningSize << endl;

  for (size_t ii = 0; ii < etaBinningSize; ii++) {
    // for (size_t ii = 0; ii < 1; ii++) {
    for (size_t jj = 0; jj < pTBinningSize; jj++) {
      // for (size_t jj = 8; jj < 9; jj++) {
      
      std::string etaName = mEtaBinning.getBinName(ii);
      std::pair<float, float> ptBins = mPtBinning.getBinValue(jj);	       
      
      std::string HistoName = TString::Format("AK4_pTBias_%s_pT_%i_%i", etaName.c_str(), (int) ptBins.first, (int) ptBins.second ).Data();

      cout<< "("<<ii << ";"<< jj<<")" << endl;
      cout<< HistoName.c_str() << endl;


      TH1D *h;

      double sigma;
      double sigma2;
      
      if( jj < 2){ // pT<300
	sigma = 3;
	sigma2 = 4;
	h = (TH1D*)dataFile_DoubleMu->Get( HistoName.c_str() );
	cout << " Lo prendo dal DoubleMu" << endl;
      }else if( jj<8 ){
	sigma = 4; // 4
	sigma2 = 5; //5
	h = (TH1D*)dataFile_HT450->Get( HistoName.c_str() );
	cout << " Lo prendo dal HT450" << endl;
      }else{
	sigma = 4;
	sigma2 = 4; //3
	h = (TH1D*)dataFile_HT450->Get( HistoName.c_str() );
	cout << " Lo prendo dal HT450" << endl;
      }
      
      if( jj > 8) continue; // >8 prima
      if( ii==3 && jj > 6) continue; // ultimo fit in endcap non funziona
      if(!h) continue;
      int Nentries = h->GetEntries();
      if(Nentries<100) continue; //200

      h->Rebin(2);

      double hN = h->GetMaximum();
      double hMean = h->GetMean();
      double hRMS = h->GetRMS();

      /*
	TF1 *expon = new TF1("expon", "[0] + [1]*exp(-[2]*x)", 0.1, 0.4);
	h -> Fit(expon, "R");
      */
      
      /*
      TF1 *crystal = new TF1("crystal", CrystalBall, hMean-2*hRMS , hMean+1*hRMS, 5);
      crystal->SetParameters(hN, hMean, hRMS, 1.0, 2.0);
      crystal->SetParNames("N", "Mean", "sigma","#alpha","n");
      crystal->SetParLimits(0, hN-0.05*hN, hN+0.05*hN);
      h -> Fit(crystal, "R");
      */

      /*
	TF1 *doublecrystal = new TF1("doublecrystal", doubleCrystalBall, hMean-3*hRMS , hMean+4*hRMS, 7);
	doublecrystal->SetParNames("N", "Mean", "sigma","#alphaR","nR","#alphaL", "nL");
	doublecrystal->SetParameters(hN, 0.01, 0.03, 1.2, 30., 15, 40.);
	doublecrystal->SetParLimits(1, 0.005, 0.015);
	doublecrystal->SetParLimits(2, 0.015, 0.035);
	doublecrystal->SetParLimits(3, 0 , 1.4);
	doublecrystal->SetParLimits(4, 1, 10);
	doublecrystal->SetParLimits(5, 0, 10);
	doublecrystal->SetParLimits(6, 0, 15);
	h -> Fit(doublecrystal, "R");
      */

      /*
      // secondo giro
      TF1 *doublecrystal2 = new TF1("doublecrystal2", doubleCrystalBall, doublecrystal->GetParameter(1)-2* doublecrystal->GetParameter(2),doublecrystal->GetParameter(1)+1*doublecrystal->GetParameter(2), 7);      
      doublecrystal2->SetLineColor(kBlue);
      doublecrystal2->SetParNames("N", "Mean", "sigma","#alphaR","nR","#alphaL", "nL");
      doublecrystal2->SetParameters(doublecrystal->GetParameter(0), doublecrystal->GetParameter(1), doublecrystal->GetParameter(2),  doublecrystal->GetParameter(3),  doublecrystal->GetParameter(4),  doublecrystal->GetParameter(5), doublecrystal->GetParameter(6));  
      h -> Fit(doublecrystal2, "+R");

      // terzo giro
      TF1 *doublecrystal3 = new TF1("doublecrystal3", doubleCrystalBall, doublecrystal2->GetParameter(1)-2* doublecrystal2->GetParameter(2),doublecrystal2->GetParameter(1)+1*doublecrystal2->GetParameter(2), 7);      
      doublecrystal3->SetLineColor(kGreen);
      doublecrystal3->SetParNames("N", "Mean", "sigma","#alphaR","nR","#alphaL", "nL");
      doublecrystal3->SetParameters(doublecrystal2->GetParameter(0), doublecrystal2->GetParameter(1), doublecrystal2->GetParameter(2),  doublecrystal2->GetParameter(3),  doublecrystal2->GetParameter(4),  doublecrystal2->GetParameter(5), doublecrystal2->GetParameter(6));  
      h -> Fit(doublecrystal3, "+R");
      */      
      /*
      // provo a fittare solo la coda --> non viene manco cosi
      TF1 *Function = new TF1("Function", "[0]*(  (pow([4]/fabs([3]),[4])*exp(-0.5*[3]*[3])) / pow( ([4]/fabs([3])- fabs([3]) - (x - [1])/[2]),[4]))", 0.03 , 0.4);
      Function->SetParNames("N", "Mean", "sigma","aR","nR");
      Function->SetParameters(hN, hMean, hRMS, 1 , 3.);
      Function->SetParLimits(0, hN-0.05*hN, hN+0.05*hN);
      h -> Fit(Function, "R");
      */

      TF1 *ExponentialGauss = new TF1("ExponentialGauss", ExpGaussExp, hMean-sigma*hRMS , hMean+sigma*hRMS, 5);
      ExponentialGauss->SetParNames("N", "Mean", "sigma","kL","kR");
      ExponentialGauss->SetParameters(hN, hMean, hRMS, 1., 1.);
      ExponentialGauss->SetParLimits(0, hN-0.2*hN, hN+0.2*hN); // se non funziona rimettilo
      if( jj>= 8 ) ExponentialGauss->SetParLimits(2, 0.005, 0.025);
      // if( jj>= 9 ) ExponentialGauss->SetParLimits(1, -0.01, 0.01);
      // ExponentialGauss->FixParameter(0, hN);
      h -> Fit(ExponentialGauss, "R");

      // secondo giro
      TF1 *ExponentialGauss2 = new TF1("ExponentialGauss2", ExpGaussExp, ExponentialGauss->GetParameter(1)-sigma2*ExponentialGauss->GetParameter(2) , ExponentialGauss->GetParameter(1)+sigma2*ExponentialGauss->GetParameter(2), 5);
      ExponentialGauss2 -> SetParNames("N", "Mean", "sigma","kL","kR");
      ExponentialGauss2 -> SetParameters( ExponentialGauss->GetParameter(0), ExponentialGauss->GetParameter(1), ExponentialGauss->GetParameter(2), ExponentialGauss->GetParameter(3), ExponentialGauss->GetParameter(4));
      h -> Fit(ExponentialGauss2, "R");

      TCanvas *c1 = new TCanvas("c1", "c1", 800, 800);
      //      gPad->SetLogy();
      // h -> SetStats(0);
      gStyle->SetOptFit(1111);
      h -> SetMarkerStyle(20);
      h -> SetMarkerSize(1.5);
      h -> GetXaxis()->SetRangeUser(-0.4, 0.4);
      h  -> Draw();
      c1 -> SaveAs( Form("AK4Jets_Plot/%s.png", HistoName.c_str() ) );
      c1 -> Destructor();

      /////////////////////////////////////////////////

      //      int pTMin = ptBins.first;
      //      int pTMax = ptBins.second;
      //      double pTMean= (pTMin + pTMax) /2. ;
           
      pT_AK4JetHLT ->GetXaxis()->SetRangeUser(ptBins.first, ptBins.second);                                                                                                
      double pTMean = pT_AK4JetHLT->GetMean();                                                                                                                             
      std::cout<< "Bin " << ptBins.first<< "-"<<ptBins.second<<" -> Mean  "<< pTMean << std::endl;

      double pTBias     = ExponentialGauss2 -> GetParameter(1);
      double pTBiasErr = ExponentialGauss2 -> GetParError(1);

      cout<< "ii = "<< ii <<endl;
      cout<< "pT mean = "<< pTMean <<endl;
      cout<< "pT Bias = "<< pTBias <<endl;
      cout<< "sigma(pT Bias) = "<< pTBiasErr <<endl;

      std::string TGraphName = TString::Format("AK4_pTBias_vs_pT_etabin_%s", etaName.c_str()).Data();
      cout<< TGraphName.c_str() << endl;
      CreateAndFillUserTGraph(TGraphName.c_str(), jj, pTMean, pTBias, 0, pTBiasErr);

    }
  }

  cout << endl;
  cout<< "Fitto i TGraph" << endl;
  
  for(int ii = 0; ii < etaBinningSize ; ii++){ 
    // for(int ii = 0; ii < 1 ; ii++){ 

    std::string etaName = mEtaBinning.getBinName(ii);
      
    std::string TGraphName = TString::Format("AK4_pTBias_vs_pT_etabin_%s", etaName.c_str()).Data();
    map<std::string , TGraphErrors*>::iterator nh_h = userTGraphs_.find( TGraphName );
    if( nh_h == userTGraphs_.end()) continue;

    cout<< TGraphName.c_str() << endl;
    
    // TF1* functionFit = new TF1( "functionFit", "[0]*(log(x)*log(x)*log(x)) + [1]*(log(x)*log(x)) + [2]*log(x) + [3]", 65, 700);
    // TF1* functionFit = new TF1( "functionFit", "[0]*(log(x)*log(x)) + [1]*(log(x)) + [2]", 60, 700);
    // TF1* functionFit = new TF1( "functionFit", "[0]*log(x) + [1]", 65, 700);

    TF1* functionFit = new TF1("functionFit"," ([0]/2)*( [3] + TMath::Erf( (x-[1])/[2]) )", 0, 1000);
    //    TF1* functionFit = new TF1("functionFit"," [0]*(TMath::Erf( (x-[1])/[2])) ", 0, 1000);
    functionFit -> SetParameters(0.02, 100, 200, -0.01);
    functionFit -> SetParLimits(0, 0.005, 0.05); //0.04
    functionFit -> SetParLimits(1, 150, 300);
    functionFit -> SetParLimits(2, 100, 350); //125

    if(ii==3){
      functionFit -> SetParLimits(0, 0.005, 0.03); //0.04
      functionFit -> SetParLimits(1, 150, 300);
      functionFit -> SetParLimits(2, 20, 350); //125
    }
 
   // functionFit -> SetParLimits(3, 0, 10000);
    

    TCanvas *c1 = new TCanvas("c1", "c1", 800, 800);
    //    gPad -> SetLogx();
    gStyle->SetOptFit(0);
    nh_h->second->SetMarkerStyle(20);
    nh_h->second->SetMarkerSize(1.5);
    nh_h->second->SetMaximum(0.05);
    nh_h->second->SetMinimum(-0.05);
    nh_h->second->Fit(functionFit, "R");
    nh_h->second->Draw("ZAP");
    lineup1 -> Draw("same");
    linedown1 -> Draw("same");
    lineup2 -> Draw("same");
    linedown2 -> Draw("same");
    c1 -> SaveAs( Form("AK4Jets_Plot/%s.png", TGraphName.c_str() ) );
    c1 -> Destructor();
   
    double Par0       =  functionFit->GetParameter(0);
    double Par1       =  functionFit->GetParameter(1);
    double Par2       =  functionFit->GetParameter(2);                                                                                                              
    double Par3       =  functionFit->GetParameter(3); 
    double NDF       =  functionFit->GetNDF();
    double Chisquare      =  functionFit->GetChisquare();
    cout<< "Par 0 = " << Par0 << endl;
    cout<< "Par 1 = " << Par1 << endl;
    cout<< "Par 2 = " << Par2 << endl;
    cout<< "Par 3 = " << Par3 << endl;                                                                                                                                                                 
    cout<< "Chisquare / NDF = " << Chisquare<<"/"<<NDF << endl;

    for(int jj=0; jj < binnum; jj++){
      
      int pTMin = pTMeanArray[jj];
      int pTMax = pTMeanArray[jj+1];
      double pTMean= (pTMin + pTMax) /2. ;
      cout<<"pT Mean = " << pTMean <<endl;

      //      double pTBiasFit = Par0*(log(pTMean)*log(pTMean)) + Par1*log(pTMean) + Par2;
      //double pTBiasFit = Par0*(log(pTMean)*log(pTMean)*log(pTMean)) + Par1*log(pTMean)*log(pTMean) + Par2*log(pTMean) + Par3;

      //    functionFit  = ([0]/2)   *( [3]  + TMath::Erf( (x-[1])/[2]) )", 0, 1000);
      double pTBiasFit = (Par0/2)*( Par3 + TMath::Erf( (pTMean -Par1)/Par2));
      cout<<"pT Bias from fit = " << pTBiasFit <<endl;

      Histo_Corrections->SetBinContent(ii+1, jj+1, pTBiasFit);
   
    }

  } 


    TCanvas *c2 = new TCanvas("c2", "c2", 900, 800);
    Histo_Corrections->SetStats(0);
    gStyle->SetPalette(55);
    Histo_Corrections->SetContour(100);
    Histo_Corrections->Draw("colz");
    c2->SetRightMargin(0.13);
    c2->SaveAs("AK4Jets_Plot/Corrections.png");

    TFile* outputFile= new TFile("AK4JetsCorrections_JEC_HLT_v7.root","RECREATE");
    outputFile->cd();
    Histo_Corrections -> Write();
    outputFile->Close();

 
  return 0;
}
Ejemplo n.º 16
0
//*****************************************************************************
void fitter::ComputeMomFromRange(const Trajectory& traj, int nplanes, int firsthit, EVector& V){
  //*****************************************************************************

  //Some catchers for pointless returns.
  int fitcatch;
  //
  /// int nfit;
  /// int fitRange[3];
  const int fitpoints = nplanes - firsthit;
  ///double meanchange = 0;
  double xpos[fitpoints], ypos[fitpoints], zpos[fitpoints];
  double upos[fitpoints];/// wpos[fitpoints];
  std::vector<EVector> dr;
  std::vector<EVector> B;
  bool isContained = true, cuspfound = false;



  double Xmax = _geom.getPlaneX() - 1*cm;
  double Ymax = _geom.getPlaneY() - 1*cm;
  /// double Zmax = _geom.getPlaneZ() - 1*cm;
  //double dx[fitpoints-1], dy[fitpoints-1], dz[fitpoints-1];
  // double ax[fitpoints-2], ay[fitpoints-2], az[fitpoints-2];
  // double bx[fitpoints-2], by[fitpoints-2], bz[fitpoints-2];
  
  

  ///double ds0=0, ds1=0;
  double Bmean=0;
  double pathlength=0;
  int Npts=0;
  ///double initR = 0;
  double sumDR = 0;
  int minindex = nplanes - firsthit;
  ///double minR = 999999.9999;
  double pdR = 0.0;
  
  
  
  EVector Z = EVector(3,0); Z[2] = 1;
  for (int ipoint=firsthit;ipoint < nplanes;ipoint++){
    
    xpos[ipoint-firsthit] = traj.node(ipoint).measurement().position()[0];
    ypos[ipoint-firsthit] = traj.node(ipoint).measurement().position()[1];
    zpos[ipoint-firsthit] = traj.node(ipoint).measurement().position()[2]
      - traj.node(firsthit).measurement().position()[2];
    if(fabs(xpos[ipoint-firsthit]) > Xmax || fabs(ypos[ipoint-firsthit]) > Ymax)
      isContained = false;
    else if(fabs(ypos[ipoint-firsthit]) > 
	    (1 + tan(atan(1.)/2.)) * Xmax - fabs(xpos[ipoint-firsthit])) 
      isContained = false;
    EVector pos0 = EVector(3,0);
    pos0[0] = xpos[ipoint-firsthit];
    pos0[1] = ypos[ipoint-firsthit];
    pos0[2] = zpos[ipoint-firsthit];
    EVector B0 = _geom.getBField(pos0);
    B.push_back(B0);
    Bmean += B0.norm();
    upos[ipoint-firsthit] = // sqrt(pos0[0]*pos0[0] + pos0[1]*pos0[1]);
      dot(pos0,crossprod(Z, B0))/crossprod(Z, B0).norm();
    //if(!cuspfound)
    //  if(ipoint == firsthit) initR = upos[ipoint-firsthit];
    //  else {
    //sumDR += initR - upos[ipoint-firsthit];
    //initR = upos[ipoint - firsthit];
    //  }
    Npts++;
    if ( ipoint > firsthit){
      EVector drtemp = EVector(3,0);
      drtemp[0] = xpos[ipoint-firsthit] - xpos[ipoint-firsthit-1];
      drtemp[1] = ypos[ipoint-firsthit] - ypos[ipoint-firsthit-1];
      drtemp[2] = zpos[ipoint-firsthit] - zpos[ipoint-firsthit-1];
      dr.push_back(drtemp);      
      pathlength +=  drtemp.norm();
      if ( ipoint > firsthit + 1 ) {
	int k = ipoint-firsthit-1;
	EVector dr0 = dr[k-1];
	EVector dr1 = dr[k];
	EVector ddr = dr1 + dr0;
	EVector Ddr = dr1 - dr0;
	EVector pos = EVector(3,0);
	pos[0] = xpos[k-1]; pos[1] = ypos[k-1]; pos[2] = zpos[k-1]; 
	EVector B = _geom.getBField(pos);
	double dR = dot(ddr, crossprod(Z, B0))/ (crossprod(Z,B0).norm());
	double DR = dot(Ddr, crossprod(Z, B0))/ (crossprod(Z,B0).norm());
	if(pdR != 0.0){
	  if(!cuspfound && DR/fabs(DR) == pdR/fabs(pdR)){
	    // sumDR += fabs(dR) > 0.0 ? dR/fabs(dR):0.0;
	    sumDR += dR;
	    // pdR = dR;
	    pdR = dR;
	  }
	  else if(dR/fabs(dR) != pdR/fabs(pdR)){
	    // cuspfound = true;
	    minindex = ipoint - firsthit - 1;
	    pdR = dR;
	    // std::cout<<"At cusp, sumDR = "<<sumDR<<std::endl;
	  }
	}
	else if(!cuspfound && fabs(dR) > 0){
	  // sumDR += fabs(DR) > 0.0 ? DR/fabs(DR) : 0.0;
	  sumDR += dR;
	  pdR = dR;
	}
	/*
	  if(pdR != 0){
	  if(minR < upos[ipoint - firsthit - 1] &&
	  (xpos[ipoint-firsthit]/fabs(xpos[ipoint-firsthit]) != 
	  xpos[ipoint-firsthit-1]/fabs(xpos[ipoint-firsthit-1])) ||
	  (ypos[ipoint-firsthit]/fabs(ypos[ipoint-firsthit]) != 
	  ypos[ipoint-firsthit-1]/fabs(ypos[ipoint-firsthit-1]))
	  && !cuspfound){
	  minR = upos[ipoint - firsthit - 1];
	  minindex = ipoint - firsthit - 1;
	  cuspfound = true;
	  }
	  }*/
      }
    }
  }
  Bmean /=Npts;
  
  double wFe = _geom.get_Fe_prop();
  double p = (wFe*(0.017143*GeV/cm * pathlength - 1.73144*GeV)
	      + (1- wFe)*(0.00277013*GeV/cm * pathlength + 1.095511*GeV));
  double meansign = 1;
  if(sumDR != 0) {
    //std::cout<<"sumDR = "<<sumDR<<std::endl;
    meansign = sumDR/fabs(sumDR);
  }
  
  ///double planesep  = fabs(zpos[1] - zpos[0]);



  // Assume that the magnetic field does not change very much over 1 metre
  // (terrible assumption by the way)
  const int sample = minindex < 20 ? (const int)minindex: 20;
  
  int pi3=0, pi4=0;
  while(dr.at(pi3)[2] == 0.0) pi3++;
  while(dr.at(pi4)[2] == 0.0) pi4++;
  V[3] = dr.at(pi3)[0]/dr.at(pi3)[2];
  V[4] = dr.at(pi4)[1]/dr.at(pi4)[2];
  if(isContained && p != 0)
    V[5] = meansign/fabs(p);
  else{


    // meansign = 0;
    // Consider a fit to a subset of points at the begining of the track
    //for(int j=0; j<fitpoints-2; j++){
    TGraph* localcurveUW = new TGraph(sample, zpos, upos);
    TF1 *func = new TF1("fit",fitf2,-30,30,4);
    func->SetParameters(0.,0.,0.001,0.0001,0.0001);
    func->SetParNames("a", "b", "c", "d", "e");
    fitcatch = localcurveUW->Fit("fit", "QN");
    double b = func->GetParameter(1);
    double c = func->GetParameter(2);
    
    p = 300.0 * B[1].norm() * pow(1. + b*b,3./2.) /2./c;
    //double wt = TMath::Gaus(fabs(pt), p, 0.25*p, true);
    // std::cout<<pt<<std::endl;
    // meansign += wt * pt/fabs(pt);
    
    delete localcurveUW;      
    delete func;
    if(p!=0){
      meansign = p/fabs(p);
      V[5] = 1./p;
    }
  
  }
  int sign = 1;
  if(meansign==meansign){
    if(meansign!=0)
      sign = int(meansign/fabs(meansign));
    else
      sign = 0;
  }
  else
    sign = 1;




  // std::cout<<"Pathlength is "<<pathlength // <<" or "<<pathlength0
  //	   <<" with charge "<<meansign<<std::endl;
  
  _initialqP = V[5];
  // _m.message("_initialqP ="<<_initialqP,bhep::VERBOSE);
  
}
Ejemplo n.º 17
0
void histoLoader_new(char* arg){
	
	//Take the arguments and save them into respective strings
	std::string infileName, outfileName;
	std::string inF, outF;
	std::string inPrefix, outPrefix;
	std::string layers;
	std::istringstream stm(arg);
	
	inPrefix = "/home/p180f/Do_Jo_Ol_Ma/Analysis/MainProcedure/testMain/analysisRoot/";
	outPrefix = "/home/p180f/Do_Jo_Ol_Ma/Analysis/MainProcedure/testMain/moliRoot/";
	
	outF = "moli_all.root";
	outfileName = outPrefix + outF;

	Double_t p0 = 248.5;
	Double_t p1 = 222;
	Double_t p2 = 275;

	int i = 0;
	Double_t thetaRMS[4];
	while(true){
		if( std::getline(stm, layers, ' ') ){
			inF        = "errorAnalysis_" + layers + "layers.root";
			infileName = inPrefix + inF;

			TFile *inFile = new TFile(infileName.c_str());
			TF1 *func = (TF1*)inFile->Get("gausFuncCuts");
			Double_t RMS1;
			Double_t RMS2;	
			RMS1 = TMath::Abs(func->GetParameter("Sigma1"));
			RMS2 = TMath::Abs(func->GetParameter("Sigma2"));
			std::cout << "RMS1_" << i << " = " << RMS1 << std::endl;
			std::cout << "RMS2_" << i << " = " << RMS2 << std::endl;
			if( RMS1 > RMS2 ){
				thetaRMS[i] = RMS2;
			} else thetaRMS[i] = RMS1;
			inFile->Close();
		}
		else break;
		i++;
	}
	
	TFile *outFile = new TFile(outfileName.c_str(), "RECREATE");

	Double_t x_data[4] = {2.54 / 4, 2.54 / 2, 2.54*3/4, 2.54};
	Double_t xerr[4]   = {0.005, 0.005, 0.005, 0.005};
	Double_t yerr[4]   = {0.197, 0.272, 0.351, 0.136};

	Double_t x0[20] = {0};
	Double_t y0[20] = {0};
	Double_t x1[20] = {0};
	Double_t y1[20] = {0};
	Double_t x2[20] = {0};
	Double_t y2[20] = {0};
	int j=1;
	for (Double_t h=0.15; j<20; j++) {
		x0[j] = h;
		y0[j] = moliFunc(x0[j], p0);
		h+=0.15;
		std::cout << "x0[" << j << "] = " << x0[j] << std::endl;
		std::cout << "y0[" << j << "] = " << y0[j] << std::endl;
	}
	int k=1;
	for (Double_t h=0.15; k<20; k++) {
		x1[k] = h;
		y1[k] = moliFunc(x1[k], p1);
		h+=0.15;
		std::cout << "x1[" << k << "] = " << x1[k] << std::endl;
		std::cout << "y1[" << k << "] = " << y1[k] << std::endl;
	}
	int l=1;
	for (Double_t h=0.15; l<20; l++) {
		x2[l] = h;
		y2[l] = moliFunc(x2[l], p2);
		h+=0.15;
		std::cout << "x2[" << l << "] = " << x2[l] << std::endl;
		std::cout << "y2[" << l << "] = " << y2[l] << std::endl;
	}
	
	TGraph *moliGraph0 = new TGraph(20, x0, y0);
	TGraph *moliGraph1 = new TGraph(20, x1, y1);
	TGraph *moliGraph2 = new TGraph(20, x2, y2);
	TGraphErrors *dataGraph = new TGraphErrors(4, x_data, thetaRMS, xerr, yerr);

	TF1 *moliFit = new TF1("moliFit", moliFunc_Fit, 0, 10, 1);
	moliFit->SetLineColor(6);
	moliFit->SetLineWidth(2);
	moliFit->SetParameters(0, 13.6);
	moliFit->SetParNames("Constant");
	moliFit->SetParLimits(0, 0, 30);
//	moliFit->SetParLimits(1, 0, 0.25);
	dataGraph->Fit("moliFit");

	std::cout << "thetaRMS[0] = " << thetaRMS[0] << std::endl;
	std::cout << "thetaRMS[1] = " << thetaRMS[1] << std::endl;
	std::cout << "thetaRMS[2] = " << thetaRMS[2] << std::endl;
	std::cout << "thetaRMS[3] = " << thetaRMS[3] << std::endl;
	//std::cout << "thetaRMS[4] = " << thetaRMS[4] << std::endl;

	moliGraph0->SetLineColor(2);
	moliGraph0->SetLineWidth(1.5);
	moliGraph1->SetLineColor(8);
	moliGraph1->SetLineWidth(1.5);
	moliGraph2->SetLineColor(9);
	moliGraph2->SetLineWidth(1.5);
	dataGraph ->SetMarkerStyle(22);		

	moliGraph0->Draw("AC");	
	moliGraph1->Draw("PC");	
	moliGraph2->Draw("PC");	
	dataGraph->Draw("P");
	//moliFit->Draw("*");	

	TLegend *leg = new TLegend(0.1, 0.7, 0.48, 0.9);
	leg->SetHeader("Legend");
//	gStyle->SetLegendFillColor(0);
	leg->AddEntry(moliGraph1, "Moliere Distribution for p = 222 MeV/c", "LP");
	leg->AddEntry(moliGraph0, "Moliere Distribution for p = 248.5 MeV/c", "LP");
	leg->AddEntry(moliGraph2, "Moliere Distribution for p = 275 MeV/c", "LP");
	leg->AddEntry(dataGraph, "The angular RMS for varying Pb thicknesses", "LP");
	leg->AddEntry(moliFit, "The angular RMS data fit to the Moliere Distribution", "LP");
	leg->Draw();

	moliGraph0->Write();	
	moliGraph1->Write();	
	moliGraph2->Write();	
	moliFit->Write();
	dataGraph->Write();
	
	outFile->Close();	
}
Ejemplo n.º 18
0
void createTBevents(int input){

  printf("Starting Simulation of data\n");

  //creating the output file
  char outputFileName[100] = {"OutputFile.root"};

  printf("Creating output file: %s \n",outputFileName);
  TFile * outputFile = new TFile(outputFileName,"RECREATE");


  //Counter for event number
  unsigned int eventNr;

  //Counter for total number of hits
  unsigned int hitsTotal = 0;

  
  short int col, row, adc;
  short int ladder = 2;
  short int mod = 3;
  short int disk = 2;
  short int blade = 2;
  short int panel = 2;
  
  //create the tree to store the data
  TTree *bpixTree[3];

  char title[30];
  for (int i=1; i<4; i++){
    sprintf(title,"BPIX_Digis_Layer%1d",i);
    bpixTree[i-1]= new TTree(title,title);
    bpixTree[i-1]->Branch("Event", &eventNr, "Event/i");           
    bpixTree[i-1]->Branch("Ladder", &ladder, "Ladder/S");      
    bpixTree[i-1]->Branch("Module", &mod, "Module/S");      
    bpixTree[i-1]->Branch("adc", &adc, "adc/S");       
    bpixTree[i-1]->Branch("col", &col, "col/S");       
    bpixTree[i-1]->Branch("row", &row, "row/S");
  }

  

  //Maximum number of events. Events does not correspond with Hits
  unsigned int maxEventNr = input;

  //Number of Hits per Event
  //This should be randomized later and be dependant on the rate
  double meanHitsPerEvent = 2;

  //Maximum particle flux [MHz cm^-2]
  int maxParticleFlux = 500;

  //number of hits in current event
  int hitsInEvent = -1; 

  //create a random number generator
  TRandom3 * random = new TRandom3();
  TRandom3 * randomrow = new TRandom3();
  TRandom3 * randomcol = new TRandom3();
  TRandom3 * randomadc = new TRandom3();

  //using custom function to distribute values
  //values used from http://ntucms1.cern.ch/pixel_dev/flux/v8/016031/fitspot_bin_11.pdf
  
  TF1 * fx = new TF1("xfunc", "[0]*exp(2.59349*exp(-0.5*((-x+3.24273/.15+[1]/.15)/7.07486*.15)**2)+2.07765*exp(-0.5*((-x+9.33060e-01/.15+[1]/.15)/2.24067*.15)**2)-4.21847)",0, 52);
  
  fx->SetParameters(1,337.0);
  fx->SetParameters(2,1.74);
  
  TF1 * fy = new TF1("yfunc", AsyGaus,0,80,4);
  
  fy->SetParNames("mean","sigma1","sigma2","amplitude");
  fy->SetParameter("mean",43);
  fy->SetParameter("sigma1",11.4);
  fy->SetParameter("sigma2",15.0);
  fy->SetParameter("amplitude",347.0);
  
  TF1 * fadc = new TF1("adcfunc", langaufun,0,400,4);
  fadc->SetParNames("scale","mpv","area","sigma");
  fadc->SetParameter("scale",19);
  fadc->SetParameter("mvp",220);
  fadc->SetParameter("area",10000);
  fadc->SetParameter("sigma",30);




  while (eventNr < maxEventNr){
    //printf("eventNr: %d \n",eventNr);
    //Function used for fitting according to Xin an Stefano
    
    //Start by generating the number of hits per event
    //following a poisson distribution
    random->SetSeed(0);
    hitsInEvent = random->Poisson(meanHitsPerEvent);
    //printf("hitsInEvent %d \n", hitsInEvent);

    hitsTotal += hitsInEvent;

    if(hitsInEvent < 0){
      printf("ERROR: Number of hits in event is negative!!!\n");
      break;
    }

    //distribute the hits in the event over the roc accorsing to gaus distribution
    /*
    for(int i = 0; i < hitsInEvent; ++i){

      //random row value
      randomrow->SetSeed(0);
      row = randomrow->Gaus(40,10);
      
      //random column value
      randomcol->SetSeed(0);
      col = randomcol->Gaus(25,8);

      //printf("row: %d | col: %d | adc: %d\n",row,col,adc);

      bpixTree[2]->Fill();

    }
    */


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

      //random row value
      row = fy->GetRandom();
      
      //random column value
      col = fx->GetRandom();

      //random adc value
      adc = fadc->GetRandom();

      //printf("row: %d | col: %d | adc: %d\n",row,col,adc);


      bpixTree[1]->Fill();

    }


    ++ eventNr;
  }


  printf("Total number of Hits: %d\n",hitsTotal);
  printf("Writing output file: %s \n", outputFileName);

  outputFile->cd();
  outputFile->Write();
  outputFile->Close();

  printf("DONE!\n");

}
Ejemplo n.º 19
0
void calibrateEM()
{

  // FIXME: There are two possibilities to execute the script:
  // i) root run_hadron_g4.C
  //    root[] .L calibrateEM.C
  //    root[] calibrateEM()
  // or ii) Include the basics from run_hadron_g4.C here and
  //    execute simply:
  //    root calibrateEM.C
  // Load basic libraries
   // Load basic libraries
  gROOT->LoadMacro("/opt/geant4_vmc.2.15a/examples/macro/basiclibs.C");
  basiclibs();

  // Load Geant4 libraries
  gROOT->LoadMacro("/opt/geant4_vmc.2.15a/examples/macro/g4libs.C");
  g4libs();
  
  // Load the tutorial application library
  gSystem->Load("libTutorialApplication");
  
  // MC application
  TutorialApplication* app 
    = new TutorialApplication("TutorialApplication",
			      "Tutorial Application for HEP Lecture @EKP");
  
  // configure Geant4
  gROOT->LoadMacro("g4Config.C");
  Config();

 // instantiate graphical user interface for tutorial application
 new TutorialMainFrame(app);
  //FIXME: Load "CountChargedinScint.C"
  gROOT->ProcessLine(".L CountChargedinScint.C");

  //FIXME: Initialize the geometry
  app->InitMC("geometry/calor(1,0.2)");
  //FIXME: Set the primary particle to photon
  app->SetPrimaryPDG(22);
  // Profile histogram - will show us the mean numbers of counts in bins of the energy.
  // The given binning refers to the energy, the other binning will be inferred automatically.
  TProfile* hcounts = new TProfile("hcounts","Counts per particle energy",
				   10,0,10);
  hcounts->SetXTitle("energy [GeV]");
  hcounts->SetYTitle("mean number of counts");

  // FIXME loop over different particle momenta, and for each momentum simulate several events (e.g. 10)
  for(Int_t i = 0 ; i < 10 ; ++i) {
    for(Int_t k = 0 ; k < 10; k ++) {
    //FIXME: Set the momentum of the primary particle to p
      Double_t p = i;
      app->SetPrimaryMomentum(p);
    //FIXME: Run the simulation
      app->RunMC();
    //FIXME: Fill both the momentum and the output from CountChargedinScint
    //        into the profile histogram hcounts
      Double_t x = CountChargedinScint();
      hcounts->Fill(p,x);
    }
  }

  TCanvas* c = new TCanvas();
  c->cd();
  hcounts->Draw();

  TF1 *fitter = new TF1("fitf","[0]*x", 0,10);
  fitter->SetParameter(0,1.0);
  fitter->SetParNames("calibration factor");
  //FIXME: Fit the histogram to get the calibration factor
  hcounts->Fit("fitf");
}
Ejemplo n.º 20
0
Archivo: plotqfit.C Proyecto: XuQiao/HI
void plotqfit(int fixv2=0,int fixg2=0){
    const int nbin24 = 12;
    const double avgtrkbin[nbin24]={44.36,54.33,68.63,88.39,108.2,131.3,162.1,196.6,227.5,247.2,269.2,301.2};
    const double V24[nbin24]={0.02965,0.03913,0.04832,0.04941,0.04822,0.04955,0.049,0.04805,0.04709,0.04665,0.04772,0.04797};
    int xtheta=0;
    gStyle->SetOptStat(1011);
    gStyle->SetOptFit(1111);
TFile *f = TFile::Open("mergedV_Sum.root");
TFile *fout = TFile::Open("qfitV.root","Update");
TVectorD *vecDNevent = (TVectorD*)f->Get(Form("Nevent"));
TVectorD *vecDavgmult = (TVectorD*)f->Get(Form("avgmultall"));
TVectorD *vecDtotmult = (TVectorD*)f->Get(Form("totmultall"));
TVectorD *vecDavgpt = (TVectorD*)f->Get(Form("avgpt"));
TVectorD *vecDavgpt2 = (TVectorD*)f->Get(Form("avgpt2"));
TVectorD *vecDavgtrk = (TVectorD*)f->Get(Form("avgtrk"));
TVectorD *vecDq22 = (TVectorD*)f->Get(Form("q22"));
TVectorD *vecDq24 = (TVectorD*)f->Get(Form("q24"));
double avgmultall = vecDtotmult->Sum()/vecDNevent->Sum();
double *avgmult = vecDavgmult->GetMatrixArray();
double *avgtrk = vecDavgtrk->GetMatrixArray();
double *avgpt = vecDavgpt->GetMatrixArray();
double *avgpt2 = vecDavgpt2->GetMatrixArray();
double *q22 = vecDq22->GetMatrixArray();
double *q24 = vecDq24->GetMatrixArray();
TLatex *t= new TLatex();
t->SetNDC();
t->SetTextSize(0.04);
t->SetTextFont(42);
/*
if(fixg2){
TH1D* hq2all = new TH1D("hq2all","hq2all",1000,0,10);
for(int ibin=0;ibin<nbin;ibin++){	//ibin<1
TH1D* hq2 = (TH1D*)f->Get(Form("D_%d/hq2",ibin));
hq2all->Add(hq2);
}
TF1 *ffit = new TF1(Form("ffit"),"1./(0.5*(1+[0]))*TMath::Exp(-([1]*[1]*[2]+x*x)/(1+[0]))*TMath::BesselI0(x*[1]*TMath::Sqrt([2])/(0.5*(1+[0])))",0,10);
TF1* f1fit = new TF1(Form("f1fit"),"x/(0.5*(1+[0]))*TMath::Exp(-([1]*[1]*[2]+x*x)/(1+[0]))*TMath::BesselI0(x*[1]*TMath::Sqrt([2])/(0.5*(1+[0])))",0,10);
TH1D* hq2all_cp = (TH1D*)hq2all->Clone("hq2all_cp");
hq2all->Scale(1./hq2all->Integral(0,-1,"width"));
hq2all->Draw();
divideByBinCenter(hq2all_cp);
ffit->SetParameters(1,0.05,avgmultall);
f1fit->SetParameters(1,0.05,avgmultall);
ffit->FixParameter(2,avgmultall);
f1fit->FixParameter(2,avgmultall);
hq2all->Fit(Form("f1fit"),"R","",0,10);
double g2all = f1fit->GetParameter(0);
}
*/
for(int ibin=0;ibin<nbin;ibin++){	//ibin<1
 //   if(ibin!=100) continue;
TH1D* hq = (TH1D*)f->Get(Form("D_%d/D_%d/hq",ibin,xtheta));
TH1D* hqx = (TH1D*)f->Get(Form("D_%d/hqx",ibin));
TH1D* hqy = (TH1D*)f->Get(Form("D_%d/hqy",ibin));
TH1D* hq2 = (TH1D*)f->Get(Form("D_%d/hq2",ibin));
TH1D* hq2nonf = (TH1D*)f->Get(Form("D_%d/hq2nonf",ibin));
int k;
for(k=0;k<nbin24;k++){
    if(avgtrk[ibin]>avgtrkbin[k]&& avgtrk[ibin]<=avgtrkbin[k+1])
        break;
}
        //multiplyByBinCenter(hq);
        hq->Scale(1./hq->Integral(0,-1,"width"));
        //normalizeByBinWidth(hq);
        //multiplyByBinCenter(hqx);
        hqx->Scale(1./hqx->Integral(0,-1,"width"));
        //normalizeByBinWidth(hqx);
        //multiplyByBinCenter(hqy);
        hqy->Scale(1./hqy->Integral(0,-1,"width"));
        //normalizeByBinWidth(hqy);
        hq2->Scale(1./hq2->Integral(0,-1,"width"));
        hq2nonf->Scale(1./hq2nonf->Integral(0,-1,"width"));
TF1 *ffit = new TF1(Form("ffit"),"1./(0.5*(1+[0]))*TMath::Exp(-([1]*[1]*[2]+x*x)/(1+[0]))*TMath::BesselI0(x*[1]*TMath::Sqrt([2])/(0.5*(1+[0])))",0,10);
TF1* f1fit = new TF1(Form("f1fit"),"x/(0.5*(1+[0]))*TMath::Exp(-([1]*[1]*[2]+x*x)/(1+[0]))*TMath::BesselI0(x*[1]*TMath::Sqrt([2])/(0.5*(1+[0])))",0,10);
//ffit = new TF1(Form("ffit"),"1./([0])*TMath::Exp(-([1]*[1]*[2]+x*x)/(2*[0]))*TMath::BesselI0(x*[1]*TMath::Sqrt([2])/([0]))",0,10);
//f1fit = new TF1(Form("f1fit"),"x/([0])*TMath::Exp(-([1]*[1]*[2]+x*x)/(2*[0]))*TMath::BesselI0(x*[1]*TMath::Sqrt([2])/([0]))",0,10);
ffit->SetParNames("g2","v2","M");
f1fit->SetParNames("g2","v2","M");
//ffit->SetParNames("#sigma2","v2","M");
//f1fit->SetParNames("sigma2","v2","M");
ffit->SetParameters(0.1,0.05,avgmult[ibin]);
f1fit->SetParameters(0.1,0.05,avgmult[ibin]);
if(fixv2){
ffit->FixParameter(1,V24[k]);
f1fit->FixParameter(1,V24[k]);
}
if(fixg2){
    double sigma2 = avgpt2[ibin]/2./avgpt[ibin]/avgpt[ibin];
    double g2all = 2*sigma2-1;
    ffit->FixParameter(0,g2all);
    f1fit->FixParameter(0,g2all);
}

//f1fit->FixParameter(0,0);
//f1fit->FixParameter(0,0);
ffit->FixParameter(2,avgmult[ibin]);
f1fit->FixParameter(2,avgmult[ibin]);
/*
hq->Fit(Form("f1fit"),"R","P",0,10);
TCanvas *c2 = new TCanvas("c2","c2",1000,500);
c2->Divide(2,1);
c2->cd(1)->SetLogy();
fixedFontHist(hqx,1.0,2.0);
hqx->SetTitle("");
hqx->GetXaxis()->SetTitle("q_{x}");
hqx->GetYaxis()->SetTitle("#frac{dN}{dq_{x}}");
hqx->GetYaxis()->SetRangeUser(1e-10,1);
hqx->Fit(Form("f1fit"),"R","",0,10);
c2->cd(2)->SetLogy();
TH1D* hqx_cp = (TH1D*)hqx->Clone("hqx_cp");
fixedFontHist(hqx_cp,1.0,2.0);
divideByBinCenter(hqx_cp);
hqx_cp->GetYaxis()->SetTitle("#frac{dN}{q_{x}dq_{x}}");
hqx_cp->GetYaxis()->SetRangeUser(1e-10,10);
hqx_cp->Fit(Form("ffit"),"R","",0,10);
t->DrawLatex(0.5,0.2,Form("N_{trk}^{offline} = %.2f", avgtrk[ibin]));

TCanvas *c3 = new TCanvas("c3","c3",1000,500);
c3->Divide(2,1);
c3->cd(1);
fixedFontHist(hqy,1.0,2.0);
hqy->SetTitle("");
hqy->GetXaxis()->SetTitle("q_{y}");
hqy->GetYaxis()->SetTitle("#frac{dN}{dq_{y}}");
hqy->GetYaxis()->SetRangeUser(0,1);
hqy->SetMarkerStyle(24);
hqy->SetMarkerSize(0.5);
hqy->Fit(Form("f1fit"),"R","",0,10);
hqy->Draw("Psame");
c3->cd(2)->SetLogy();
TH1D* hqy_cp = (TH1D*)hqy->Clone("hqy_cp");
fixedFontHist(hqy_cp,1.0,2.0);
divideByBinCenter(hqy_cp);
hqy_cp->GetYaxis()->SetTitle("#frac{dN}{q_{y}dq_{y}}");
hqy_cp->GetYaxis()->SetRangeUser(1e-10,10);
hqy_cp->SetMarkerStyle(24);
hqy_cp->SetMarkerSize(0.5);
hqy_cp->Fit(Form("ffit"),"R","",0,10);
hqy_cp->Draw("Psame");
t->DrawLatex(0.5,0.2,Form("N_{trk}^{offline} = %.2f",avgtrk[ibin]));
*/
TCanvas *c4 = new TCanvas("c4","c4",1000,500);
c4->Divide(2,1);
c4->cd(1)->SetLeftMargin(0.18);
fixedFontHist(hq2,1.0,2.0);
hq2->SetTitle("");
hq2->GetXaxis()->SetTitle("q_{2}");
hq2->GetYaxis()->SetTitle("#frac{dN}{dq_{2}}");
hq2->GetYaxis()->SetRangeUser(0,1);
hq2->SetMarkerStyle(24);
hq2->SetMarkerColor(4);
hq2->SetLineColor(4);
hq2->SetMarkerSize(0.5);
hq2->Fit(Form("f1fit"),"R","",0,10);
TVectorD vecr;
vecr.ResizeTo(8);
vecr[0]=f1fit->GetParameter(0);
vecr[1]=f1fit->GetParError(0);
vecr[2]=f1fit->GetParameter(1);
vecr[3]=f1fit->GetParError(1);
vecr[4]=avgmult[ibin];
vecr[5]=avgtrk[ibin];
hq2->Draw("Psame");
c4->cd(2)->SetLogy();
c4->cd(2)->SetLeftMargin(0.2);
TH1D* hq2_cp = (TH1D*)hq2->Clone("hq2_cp");
fixedFontHist(hq2_cp,1.0,2.0);
divideByBinCenter(hq2_cp);
hq2_cp->GetYaxis()->SetTitle("#frac{dN}{q_{2}dq_{2}}");
hq2_cp->GetYaxis()->SetRangeUser(1e-10,10);
hq2_cp->SetMarkerStyle(24);
hq2_cp->SetMarkerColor(4);
hq2_cp->SetLineColor(4);
hq2_cp->SetMarkerSize(0.5);
hq2_cp->Fit(Form("ffit"),"R","",0,10);
hq2_cp->Draw("Psame");
t->DrawLatex(0.5,0.2,Form("N_{trk}^{offline} = %.2f", avgtrk[ibin]));

TCanvas *c5 = new TCanvas("c5","c5",1000,500);
c5->Divide(2,1);
c5->cd(1);
fixedFontHist(hq2nonf,1.0,2.0);
hq2nonf->SetTitle("");
hq2nonf->GetXaxis()->SetTitle("q_{2}");
hq2nonf->GetYaxis()->SetTitle("#frac{dN}{dq_{2}}");
hq2nonf->GetYaxis()->SetRangeUser(0,1);
hq2nonf->SetMarkerStyle(24);
hq2nonf->SetMarkerColor(4);
hq2nonf->SetLineColor(4);
hq2nonf->SetMarkerSize(0.5);
ffit->SetParameters(1.5,0.05,avgmult[ibin]*2);
f1fit->SetParameters(1.5,0.05,avgmult[ibin]*2);
ffit->FixParameter(2,avgmult[ibin]*2);
f1fit->FixParameter(2,avgmult[ibin]*2);
if(fixv2){
ffit->FixParameter(1,V24[k]);
f1fit->FixParameter(1,V24[k]);
}
if(fixg2){
    ffit->FixParameter(0,g2all+1);
    f1fit->FixParameter(0,g2all+1);
}
//ffit->FixParameter(0,1);
//f1fit->FixParameter(0,1);
hq2nonf->Fit(Form("f1fit"),"R","",0,10);
TVectorD vecrnonf;
vecrnonf.ResizeTo(8);
vecrnonf[0]=f1fit->GetParameter(0);
vecrnonf[1]=f1fit->GetParError(0);
vecrnonf[2]=f1fit->GetParameter(1);
vecrnonf[3]=f1fit->GetParError(1);
vecrnonf[4]=avgmult[ibin];
vecrnonf[5]=avgtrk[ibin];
hq2nonf->Draw("Psame");
c5->cd(2)->SetLogy();
TH1D* hq2nonf_cp = (TH1D*)hq2nonf->Clone("hq2nonf_cp");
fixedFontHist(hq2nonf_cp,1.0,2.0);
divideByBinCenter(hq2nonf_cp);
hq2nonf_cp->GetYaxis()->SetTitle("#frac{dN}{q_{2}dq_{2}}");
hq2nonf_cp->GetYaxis()->SetRangeUser(1e-10,10);
hq2nonf_cp->SetMarkerStyle(24);
hq2nonf_cp->SetMarkerColor(4);
hq2nonf_cp->SetLineColor(4);
hq2nonf_cp->SetMarkerSize(0.5);
hq2nonf_cp->Fit(Form("ffit"),"R","",0,10);
hq2nonf_cp->Draw("Psame");
t->DrawLatex(0.5,0.2,Form("N_{trk}^{offline} = %.2f", avgtrk[ibin]*2));

double v2calc = TMath::Sqrt(TMath::Sqrt(2*q22[ibin]*q22[ibin]-q24[ibin])/avgmult[ibin]);
double g2calc = q22[ibin]-TMath::Sqrt(2*q22[ibin]*q22[ibin]-q24[ibin])-1;
vecr[6]=v2calc;
vecr[7]=g2calc;

fout->cd();
vecr.Write(Form("r_%d_%d_%d",ibin,fixv2,fixg2),TObject::kOverwrite);
vecrnonf.Write(Form("rnonf_%d_%d_%d",ibin,fixv2,fixg2),TObject::kOverwrite);
//if(ibin==15)
//c4->Print("hq2_fit_15.png");
}
//c5->Print("hq2nonf_fit.png");
}
Ejemplo n.º 21
0
/** Make Va1 response
    @param n 
    @param B 
    @param dc 
    @param errors 
    @ingroup simple_script
*/
void 
VA1Response(Int_t n=4, Float_t B=6, Float_t dc=.01, Bool_t errors=kFALSE,
	    Bool_t doFit=kFALSE) 
{
  gStyle->SetOptTitle(0);
  gStyle->SetOptStat(0);
  gStyle->SetOptFit(0);
  gStyle->SetLabelFont(132, "xyz");
  gStyle->SetTitleFont(132, "xyz");
  gStyle->SetTitleSize(0.08, "y");
  gStyle->SetTitleOffset(0.5, "y");
  gStyle->SetTitleSize(0.06, "x");
  gStyle->SetTitleOffset(0.7, "x");

  TCanvas* c = new TCanvas("c", "c", 800, 500);
  c->SetFillColor(0);
  c->SetBorderMode(0);
  c->SetBorderSize(0);
  c->SetTopMargin(0.05);
  c->SetRightMargin(0.05);
  c->SetGridx();
  c->SetGridy();

  TF1* response = new TF1("response", "[0] * (1 - exp(-[1] * x))", 0, 1.4);
  response->SetParameters(1, B);
  response->SetParNames("A", "B");
  response->SetLineColor(2);
  
  TGraph* graph = 0;
  if (n >= 2) {
    if (errors) graph = new TGraphErrors(n);
    else        graph = new TGraph(n);
    for (Int_t i = 0; i < n; i++) {
      Float_t t = Float_t(i + 1) / n;
      Float_t q = gRandom->Gaus(response->Eval(t), dc);
      graph->SetPoint(i, t, q);
      if (errors) ((TGraphErrors*)graph)->SetPointError(i, 0, dc);
    }
  }

  response->Draw();
  response->GetHistogram()->GetYaxis()->SetRangeUser(0, 1.05);
  response->GetHistogram()->GetXaxis()->SetRangeUser(0, 1.1);
  response->GetHistogram()->GetXaxis()->SetNdivisions(6, kTRUE);
  response->GetHistogram()->GetYaxis()->SetNdivisions(10, kTRUE);
  response->GetHistogram()->SetXTitle("t");
  response->GetHistogram()->SetYTitle(Form("1-e^{-%3.1f t}", B));
  
  if (graph) {
    
    
    graph->Draw("P*");
    TString fitOpt("E");
    if (!errors) fitOpt.Append("W");

    if (doFit) {
      TF1* fit = new TF1("fit",  "[0] * (1 - exp(-[1] * x))",  0, 1);
      fit->SetParameters(.5, B/2);
      fit->SetParNames("A", "B");
      fit->SetLineColor(3);
      graph->Fit("fit", fitOpt.Data());
      graph->Fit("fit", fitOpt.Data());
      
      std::cout << "Chi^2/NDF = " << fit->GetChisquare() << "/" << fit->GetNDF()
		<< " = " << std::flush;
      if (fit->GetNDF() == 0) 
	std::cout << " undefined!" << std::endl;
      else
	std::cout << (fit->GetChisquare() / fit->GetNDF()) << std::endl;
      std::cout << "f(t) = " 
		<< fit->GetParameter(0) << "+/-" << fit->GetParError(0) 
		<< " * (1 - exp(" 
		<< fit->GetParameter(1) << "+/-" << fit->GetParError(1) 
		<< " * t))" << std::endl;
    }
  }

  c->Modified();
  c->Update();
  c->cd();
  c->SaveAs("va1_response.png");
}
Ejemplo n.º 22
0
//*****************************************************************************
void fitter::ComputeMomFromParabola(const Trajectory& traj, int nplanes, int firsthit, EVector& V){
  //*****************************************************************************

  //Some catchers for pointless returns.
  int fitcatch;
  //
  int nfit, sign;
  int fitRange[3];
  const int fitpoints = nplanes - firsthit;
  
  double xpos[fitpoints], ypos[fitpoints], zpos[fitpoints];
  double upos[fitpoints], vpos[fitpoints];

  int pos = 0;

  EVector currentpos = EVector(3,0);
  EVector currentB   = EVector(3,0);
  EVector z = EVector(3,0);
  z[2] = 1;
  double Bmean=0;
  for( int ipoint=firsthit; ipoint < nplanes; ipoint ++ ){
    xpos[pos] = traj.node(ipoint).measurement().position()[0];
    ypos[pos] = traj.node(ipoint).measurement().position()[1];
    zpos[pos] = traj.node(ipoint).measurement().position()[2]
      - traj.node(firsthit).measurement().position()[2];
    currentpos[0] = traj.node(ipoint).measurement().position()[0];
    currentpos[1] = traj.node(ipoint).measurement().position()[1];
    currentpos[2] = 0.;
    currentB = _geom.getBField(currentpos);
    upos[pos] = xpos[pos] > 0 ? asin(ypos[pos]/currentpos.norm())
      : -asin(ypos[pos]/currentpos.norm());
    vpos[pos] = dot(currentpos,crossprod(z,currentB))/currentB.norm();
    Bmean += currentB.norm();
    ++pos;
  }
  Bmean /= pos;
  Bmean /= tesla;
  
  if (fitpoints <= 15) { nfit = 1; fitRange[0] = fitpoints;}
  else if (fitpoints <= 40) { 
    nfit = 2;
    fitRange[0] = 15; fitRange[1] = (int)(0.7*fitpoints);
  }
  else if (fitpoints > 40) { 
    nfit = 3;
    fitRange[0] = 15; fitRange[1] = (int)(fitpoints/2); fitRange[2] = (int)(0.7*fitpoints);
  }
  for (int ifit = 0;ifit < nfit;ifit++) {
    TGraph *trajFitXZ = new TGraph(fitRange[ifit],zpos, xpos);
    TGraph *trajFitYZ = new TGraph(fitRange[ifit],zpos, ypos);
    TGraph *trajFitUZ = new TGraph(fitRange[ifit],zpos, upos);
    TGraph *trajFitVZ = new TGraph(fitRange[ifit],zpos, vpos);
    
    TF1 *func = new TF1("fit",fitf2,-3,3,3);
    func->SetParameters(0.,0.,0.001,0.0001,0.0001);
    func->SetParNames("a", "b", "c", "d", "e");
    
    TF1 *func2 = new TF1("fit2",fitf2,-3,3,3);
    func2->SetParameters(0.,0.,0.001,0.0001,0.0001);
    func2->SetParNames("f", "g", "h", "i", "j");

    TF1 *func3 = new TF1("fit3",fitf2,-3,3,3);
    func->SetParameters(0.,0.,0.001,0.0001,0.0001);
    func->SetParNames("a1", "b1", "c1", "d1", "e1");
    
    TF1 *func4 = new TF1("fit4",fitf2,-3,3,3);
    func2->SetParameters(0.,0.,0.001,0.0001,0.0001);
    func2->SetParNames("f1", "g1", "h1", "i1", "j1");

    fitcatch = trajFitXZ->Fit("fit", "QN");
    fitcatch = trajFitYZ->Fit("fit2", "QN");
    fitcatch = trajFitUZ->Fit("fit3", "QN");
    fitcatch = trajFitVZ->Fit("fit4", "QN");
    
    double b = func->GetParameter(1);
    double c = func->GetParameter(2);
    double g = func2->GetParameter(1);
    /*double f = func2->GetParameter(0);
      double a = func->GetParameter(0);
      double h = func2->GetParameter(2);  
      double a1 = func3->GetParameter(0);
      double b1 = func3->GetParameter(1);
      double c1 = func3->GetParameter(2);  
      double f1 = func4->GetParameter(0);*////
    double g1 = func4->GetParameter(1);
    double h1 = func4->GetParameter(2);  
    
    if (ifit == 0) {

      V[4] = g;   //func2->GetParameter(1);
      V[3] = b;

      if (h1!=0) {
	V[5] = 1./(-0.3*Bmean*pow((1+g1*g1),3./2.)/
		   (2*h1)*0.01);
	V[5] /= GeV;
	sign = (int)( V[5]/fabs( V[5] ));
      } else V[5] = 0;
    } else {
      if ((int)(-c/fabs(c)) == sign) {
	V[4] = g;
	V[3] = b;
	V[5] = 1/(-0.3*Bmean*pow((1+g1*g1),3./2.)/(2*h1)*0.01);
	V[5] /= GeV;
      } else break;
    }
    
    delete trajFitXZ;
    delete trajFitYZ;
    delete trajFitUZ;
    delete trajFitVZ;
  
    delete func;
    delete func2;
    delete func3;
    delete func4;
  }
  
  //std::cout<<"Momentum guess from polynomial fit: p/q = "<<1./V[5]<<std::endl;
}
Ejemplo n.º 23
0
void betaMS(Double_t z = 1000, const TString &opt="pdf") {

  gROOT->Reset();
  PGlobals::Initialize();
  
  // gStyle->SetPadTopMargin(0.10);
  // gStyle->SetPadRightMargin(0.05);
  // gStyle->SetPadBottomMargin(0.15);
  // gStyle->SetPadLeftMargin(0.15);

  Double_t E0  = 1000;  // MeV
  Double_t gamma = E0/0.511; 
  Double_t X0  = 35.0E4; // um (Berylium)
  Double_t sx0 = 10.0;   // um
  Double_t emitxn  = 1.00; // um
  Double_t emitx   = emitxn/gamma; // um
  Double_t sd0 = 1000. * (emitx/sx0); // mrad
  Double_t kp  = 0.0595; // um^-1  for n0 = 10^17 cm^-3
  Double_t kbeta  = kp/TMath::Sqrt(2 * gamma);
  Double_t betamatch = (1/kbeta) / 1000.; // mm

  TF1 *ftheta = new TF1("ftheta",theta,-0.01*z,z,4);
  ftheta->SetParameters(E0,X0,sx0,sd0);
  ftheta->SetParNames("Energy","X0","sx0","sd0");
  ftheta->SetTitle("");
  ftheta->GetXaxis()->SetTitle("#Deltaz [#mum]");
  ftheta->GetYaxis()->SetTitle("#Theta_{0} [mrad]");

  TF1 *fsigmax = new TF1("fsigmax",Sigmax,-0.01*z,z,4);
  fsigmax->SetParameters(E0,X0,sx0,sd0);
  fsigmax->SetParNames("Energy","X0","sx0","sd0");
  fsigmax->SetTitle("");
  fsigmax->GetXaxis()->SetTitle("#Deltaz [#mum]");
  fsigmax->GetYaxis()->SetTitle("#sigma_{x} [#mum]");

  TF1 *fsigmaxp = new TF1("fsigmaxp",Sigmaxp,-0.01*z,z,4);
  fsigmaxp->SetParameters(E0,X0,sx0,sd0);
  fsigmaxp->SetParNames("Energy","X0","sx0","sd0");
  fsigmaxp->SetTitle("");
  fsigmaxp->GetXaxis()->SetTitle("#Deltaz [#mum]");
  fsigmaxp->GetYaxis()->SetTitle("#sigma_{x'} [mrad]");

  TF1 *femit = new TF1("femit",emittance,-0.01*z,z,4);
  femit->SetParameters(E0,X0,sx0,sd0);
  femit->SetParNames("Energy","X0","sx0","sd0");
  femit->SetTitle("");
  femit->GetXaxis()->SetTitle("#Deltaz [#mum]");
  femit->GetYaxis()->SetTitle("#epsilon_{x,n} [#mum]");

  TF1 *fbeta = new TF1("fbeta",beta,-0.01*z,z,4);
  fbeta->SetParameters(E0,X0,sx0,sd0);
  fbeta->SetParNames("Energy","X0","sx0","sd0");
  fbeta->SetTitle("");
  fbeta->GetXaxis()->SetTitle("#Deltaz [#mum]");
  fbeta->GetYaxis()->SetTitle("#beta [mm]");
  
  TF1 *femitfin = new TF1("femitfin",finalemittance,-0.01*z,z,5);
  femitfin->SetParameters(E0,X0,sx0,sd0,betamatch);
  femitfin->SetParNames("Energy","X0","sx0","sd0","betam");
  femitfin->SetTitle("");
  femitfin->GetXaxis()->SetTitle("#Deltaz [#mum]");
  femitfin->GetYaxis()->SetTitle("#epsilon_{x,n,F} [#mum]");

  const UInt_t NPad = 6;
  TCanvas *C = new TCanvas("C","",640,1024);
  // Setup Pad layout:
  TPad **pad = new TPad*[NPad];
  Float_t bMargin = 0.10;
  Float_t tMargin = 0.04;
  Float_t lMargin = 0.20;
  Float_t rMargin = 0.08;
  Float_t vSpacing = 0.017;
  PGlobals::CanvasPartition(C,NPad,lMargin,rMargin,bMargin,tMargin,vSpacing);
 
  // Define the frames for plotting
  Int_t fonttype = 43;
  Int_t fontsize = 22;
  Int_t tfontsize = 26;
  Float_t txoffset = 5.0;
  Float_t lxoffset = 0.02;
  Float_t tyoffset = 3.0;
  Float_t lyoffset = 0.01;
  Float_t tylength = 0.02;
  Float_t txlength = 0.04;

  TF1 *func[NPad];
  func[5] = ftheta;
  func[4] = fsigmax;
  func[3] = fsigmaxp;
  func[2] = femit;
  func[1] = fbeta;
  func[0] = femitfin;

  for(Int_t i=0;i<NPad;i++) {
    char name[16];
    sprintf(name,"pad_%i",i);
    pad[i] = (TPad*) gROOT->FindObject(name);
    pad[i]->SetFrameLineWidth(2);  
    pad[i]->SetTickx(1);
    pad[i]->SetTicky(1);
    pad[i]->SetFillStyle(4000);
    pad[i]->SetFrameFillStyle(4000);

    Float_t xFactor = pad[0]->GetAbsWNDC()/pad[i]->GetAbsWNDC();
    Float_t yFactor = pad[0]->GetAbsHNDC()/pad[i]->GetAbsHNDC();

    // Format for y axis
    func[i]->GetYaxis()->SetTitleFont(fonttype);
    func[i]->GetYaxis()->SetTitleSize(tfontsize);
    func[i]->GetYaxis()->SetTitleOffset(tyoffset);
    func[i]->GetYaxis()->SetLabelFont(fonttype);
    func[i]->GetYaxis()->SetLabelSize(fontsize);
    func[i]->GetYaxis()->SetLabelOffset(lyoffset);

    func[i]->GetYaxis()->SetTickLength(xFactor*tylength/yFactor);
    func[i]->GetYaxis()->CenterTitle();

    // Format for x axis
    func[i]->GetXaxis()->SetTitleFont(fonttype);
    func[i]->GetXaxis()->SetTitleSize(tfontsize+2);
    func[i]->GetXaxis()->SetTitleOffset(txoffset);
    func[i]->GetXaxis()->SetLabelFont(fonttype);
    func[i]->GetXaxis()->SetLabelSize(fontsize);
    func[i]->GetXaxis()->SetLabelOffset(lxoffset);
    
    func[i]->GetXaxis()->SetTickLength(yFactor*txlength/xFactor);      
    func[i]->GetXaxis()->CenterTitle();

    if(i>0) {
      func[i]->GetXaxis()->SetTitleSize(0.0);
      func[i]->GetXaxis()->SetLabelSize(0.0);
    }


    pad[i]->cd();
    //    pad[i]->SetLogy(1);
    func[i]->Draw("L");

  }

  // Calculations:
  cout << Form(" Matched beta = %.4f mm", betamatch) << endl;
  
  Double_t iniemit0  = femit->Eval(0.0);
  Double_t inibeta0 = fbeta->Eval(0.0);
  Double_t inibetap0 = inibeta0/betamatch;
  Double_t finemit0  = iniemit0 * 0.5 * ( 1.0/inibetap0 + inibetap0);
  cout << Form(" Initial beta = %6.2f mm, emit = %6.2f um --> final emittance = %6.3f um %6.3f um ",
	       inibeta0,iniemit0,finemit0,femitfin->Eval(0)) << endl;

  Double_t iniemitZ  = femit->Eval(z);
  Double_t inibetaZ = fbeta->Eval(z);
  Double_t inibetapZ = inibetaZ/betamatch;
  Double_t finemitZ  = iniemitZ * 0.5 * ( 1.0/inibetapZ + inibetapZ);
  cout << Form(" Initial beta = %6.2f mm, emit = %6.2f um --> final emittance = %6.3f um %6.3f um",
	       inibetaZ,iniemitZ,finemitZ,femitfin->Eval(z) ) << endl;

  

  // Writing the figure
  TString fOutName = Form("./betaMS");
  PGlobals::imgconv(C,fOutName,opt);
  // ---------------------------------------------------------
  
  PGlobals::DestroyCanvases();

  

}
Ejemplo n.º 24
0
// Function for the computation of channeling efficiency at various incoming angle
Int_t AnalyseChannelingEfficiency(TTree *fTree,Float_t fChannelingMinimum = 35., Float_t fChannelingMaximum = 70.){
    //**//Channeling Gaussian Fit Function
    TF1 *vChanneling = new TF1("vChanneling","gaus",fChannelingMinimum,fChannelingMaximum);
    vChanneling->SetParNames("Const","Mean","Sigma");
    vChanneling->SetLineColor(4);
    vChanneling->SetLineStyle(2);

    TH2D *hChannelingPlot = new TH2D("hChannelingPlot","Deflection Angle vs. Incoming Angle;Horizontal Incoming Angle [#murad];Horizontal Deflection Angle [#murad]",21,-10.5,10.5,256,-127.5,128.5);
    
    TH1F *hChannelingEfficiency = new TH1F("hChannelingEfficiency","G4Channeling;Horizontal Incoming Angle [#murad];Efficiency [%]",21,-10.5,10.5);

    fTree->Draw("-(angXout-angXin):-angXin>>hChannelingPlot");
    
    Double_t vNormalizationToAmorphous = 0.965; // Normalization for channeling efficiency, see PRSTAB 11, 063501 (2008)
    
    for(int i=2;i<=21;i++){
        TH1D* h1 = hChannelingPlot->ProjectionY("h1",i,i);
        h1->Fit(vChanneling,"QR");
        Double_t *vChannelingParameters;
        vChannelingParameters = vChanneling->GetParameters();
        hChannelingEfficiency->SetBinContent(i,ComputeEfficiency(h1,vChannelingParameters)/vNormalizationToAmorphous);
        h1->Delete();
    }
    hChannelingEfficiency->SetLineColor(3);
    hChannelingEfficiency->SetLineStyle(4);
    hChannelingEfficiency->SetMarkerColor(3);
    hChannelingEfficiency->SetFillStyle(0);
    hChannelingEfficiency->SetMarkerStyle(20);
    hChannelingEfficiency->Draw("PL");

    TGraph* gRoughExperimentalData = new TGraph(11);
    gRoughExperimentalData->SetPoint(	0	,	-10	,	20	);
    gRoughExperimentalData->SetPoint(	1	,	-8	,	38	);
    gRoughExperimentalData->SetPoint(	2	,	-6	,	56	);
    gRoughExperimentalData->SetPoint(	3	,	-4	,	72	);
    gRoughExperimentalData->SetPoint(	4	,	-2	,	80	);
    gRoughExperimentalData->SetPoint(	5	,	0	,	84	);
    gRoughExperimentalData->SetPoint(	6	,	2	,	82	);
    gRoughExperimentalData->SetPoint(	7	,	4	,	78	);
    gRoughExperimentalData->SetPoint(	8	,	6	,	66	);
    gRoughExperimentalData->SetPoint(	9	,	8	,	52	);
    gRoughExperimentalData->SetPoint(	10	,	10	,	37	);

    gRoughExperimentalData->SetLineColor(4);
    gRoughExperimentalData->SetLineStyle(3);
    gRoughExperimentalData->SetFillStyle(0);
    gRoughExperimentalData->SetFillColor(0);
    gRoughExperimentalData->SetMarkerColor(4);
    gRoughExperimentalData->SetMarkerStyle(21);
    gRoughExperimentalData->SetTitle("Phys. Lett. B 680, 129");

    gRoughExperimentalData->Draw("sameCP");

    TLegend *aLegend = new TLegend(0.30,0.15,0.55,0.3);
    aLegend->AddEntry(hChannelingEfficiency);
    aLegend->AddEntry(gRoughExperimentalData);
    aLegend->SetFillStyle(0);
    aLegend->SetLineColor(0);
    aLegend->Draw();

    return 0;
}
int main(int argc, char* argv[]) {

  std::string outputDir = "WideJets_Plot";                 
  mkdir(outputDir.c_str(), 0777); 

  //  TString dataFileName_DoubleMu;
  //  dataFileName_DoubleMu = TString::Format("../../output/HLTReco_Comparison/rootFile_JEC_HLT_v7_RecoLowerCuts10GeV_DoubleMu.root");
  // TFile* dataFile_DoubleMu = TFile::Open(dataFileName_DoubleMu);
  // if (dataFile_DoubleMu) {
  //  std::cout << "Opened data file '" << dataFileName_DoubleMu << "'." << std::endl;
  // }

  TString dataFileName_HT450;
  dataFileName_HT450 = TString::Format("../../output/HLTReco_Comparison/rootFile_JEC_HLT_v7_RecoLowerCuts10GeV_HT450.root");
  TFile* dataFile_HT450 = TFile::Open(dataFileName_HT450);
  if (dataFile_HT450) {
    std::cout << "Opened data file '" << dataFileName_HT450 << "'." << std::endl;
  }

  TH1D *pT_WideJetHLT = (TH1D*)dataFile_HT450->Get("pT_WideJetHLT");

  if( !pT_WideJetHLT) cout<<"Not found" <<endl;

  gErrorIgnoreLevel = kWarning;

  // procedura
  // prendo gli istogramma 1D del bias
  // per ogni bin di pT e eta
  // li fitto con una cristal ball
  // poi grafico il picco in funzione del pT in ogni bin di eta
  // fitto con una funzione logaritmica
  // mi creo l'istogramma 2D (eta,pT) con correzione sull'asse z

  //////////////////////// pTBias 1D
  EtaBinning mEtaBinning;
  size_t etaBinningSize = mEtaBinning.size();
  PtBinning mPtBinning;
  size_t pTBinningSize = mPtBinning.size();

  cout<< etaBinningSize << endl;

  for (size_t ii = 0; ii < etaBinningSize; ii++) { 
    // for (size_t ii = 9; ii < 10; ii++) {
    for (size_t jj = 0; jj < pTBinningSize; jj++) {

      cout<< "ii = "<< ii <<endl;
      cout<< "jj = "<< jj <<endl;

      if(jj < 2) continue; // pT<300
      if(jj > 7) continue; // pT>900

      std::string etaName = mEtaBinning.getBinName(ii);
      std::pair<float, float> ptBins = mPtBinning.getBinValue(jj);	       
      
      std::string HistoName = TString::Format("pTBias_%s_pT_%i_%i", etaName.c_str(), (int) ptBins.first, (int) ptBins.second ).Data();
      
      cout<< HistoName.c_str() << endl;
      
      TH1D *h;
      h = (TH1D*)dataFile_HT450->Get( HistoName.c_str() );
            
      double hN = h->GetMaximum();
      double hMean = h->GetMean();
      double hRMS = h->GetRMS();

      //histo->GetMean() - sigma * histo->GetRMS(), histo->GetMean() + sigma * histo->GetRMS() 

      //      TF1 *crystal = new TF1("crystal", CrystalBall, hMean-1*hRMS , hMean+1*hRMS, 5);
      TF1 *crystal = new TF1("crystal", CrystalBall, -0.1, 0.15, 5);
      //      TF1 *crystal = new TF1("crystal", CrystalBall, -0.05, 0.1, 5);
      crystal->SetParameters(hN, hMean, hRMS, 1.0, 2.0);
      crystal->SetParNames("N", "Mean", "sigma","#alpha","n");
      
      //      TF1 *doublecrystal = new TF1("doublecrystal", doubleCrystalBall, hMean-1*hRMS , hMean+1*hRMS, 7);
      TF1 *doublecrystal = new TF1("doublecrystal", doubleCrystalBall, -0.2 , 0.2, 7);
      doublecrystal->SetParameters(hN, hMean, hRMS, 3, 3, 3, 3);
      doublecrystal->SetParNames("N", "Mean", "sigma","#alphaR","nR","#alphaL", "nL");
      
      TCanvas *c1 = new TCanvas("c1", "c1", 800, 800);
      h -> SetMarkerStyle(20);
      h -> SetMarkerSize(1.5);
      h -> GetXaxis()->SetRangeUser(-0.4, 0.4);
      // h -> Fit(crystal, "R");
      h -> Fit(doublecrystal, "R");
      h -> Draw();
      c1 -> SaveAs( Form("WideJets_Plot/%s.png", HistoName.c_str() ) );
      c1-> Destructor();

      /////////////////////////////////////////////////
      
      pT_WideJetHLT ->GetXaxis()->SetRangeUser(ptBins.first, ptBins.second);
      double pTMean = pT_WideJetHLT->GetMean();
      std::cout<< "Bin " << ptBins.first<< "-"<<ptBins.second<<" -> Mean  "<< pTMean << std::endl; 
      
      double pTBias = doublecrystal->GetParameter(1);
      double pTBiasErr = doublecrystal->GetParError(1);
      
      cout<< "pT mean = "<< pTMean <<endl;
      cout<< "pT Bias = "<< pTBias <<endl;
      cout<< "sigma(pT Bias) = "<< pTBiasErr <<endl;

      std::string TGraphName = TString::Format("pTBias_vs_pT_etabin_%i", ii).Data();
      cout<< TGraphName.c_str() << endl;
      CreateAndFillUserTGraph(TGraphName.c_str(), jj, pTMean, pTBias, 0, pTBiasErr);
      
    }
  }
  

  for(int ii = 0; ii < etaBinningSize ; ii++){ 
   
    std::string TGraphName = TString::Format("pTBias_vs_pT_etabin_%i", ii).Data();
    cout<< TGraphName.c_str() << endl;
    map<std::string , TGraphErrors*>::iterator nh_h = userTGraphs_.find( TGraphName );
    if( nh_h == userTGraphs_.end()) continue;

    TF1* functionFit = new TF1( "functionFit", "[0]*(log(x)*log(x)*log(x)) + [1]*(log(x)*log(x)) + [2]*log(x) + [3]", 300, 1000);
    //TF1* functionFit = new TF1( "functionFit", "[0]*(log(x)*log(x)) + [1]*log(x) + [2]", 300, 1000);

    TCanvas *c1 = new TCanvas("c1", "c1", 800, 800);
    nh_h->second->SetMarkerStyle(20);
    nh_h->second->SetMarkerSize(1.5);
    nh_h->second->GetXaxis()->SetRangeUser(300, 1000);
    nh_h->second->SetMaximum(0.1);
    nh_h->second->SetMinimum(-0.1);
    nh_h->second->Fit(functionFit, "R");
    nh_h->second->Draw("ZAP");
    c1 -> SaveAs( Form("WideJets_Plot/%s.png", TGraphName.c_str() ) );
    c1 -> Destructor();

    double Par0       =  functionFit->GetParameter(0);
    double Par1       =  functionFit->GetParameter(1);
    double Par2       =  functionFit->GetParameter(2);                                                                                                              
    double Par3       =  functionFit->GetParameter(3); 
    double NDF       =  functionFit->GetNDF();
    double Chisquare      =  functionFit->GetChisquare();
    cout<< "Par 0 = " << Par0 << endl;
    cout<< "Par 1 = " << Par1 << endl;
    cout<< "Par 2 = " << Par2 << endl;
    cout<< "Par 3 = " << Par3 << endl;                                                                                                                                                                 
    cout<< "Chisquare / NDF = " << Chisquare<<"/"<<NDF << endl;

    for(int jj=0; jj < binnum; jj++){
      
      int pTMin = pTMeanArray[jj];
      int pTMax = pTMeanArray[jj+1];
      double pTMean= (pTMin + pTMax) /2. ;
      cout<<"pT Mean = " << pTMean <<endl;

      //      double pTBiasFit = Par0*(log(pTMean)*log(pTMean)) + Par1*log(pTMean) + Par2;
      double pTBiasFit = Par0*(log(pTMean)*log(pTMean)*log(pTMean)) + Par1*log(pTMean)*log(pTMean) + Par2*log(pTMean) + Par3;
      cout<<"pT Bias from fit = " << pTBiasFit <<endl;

      Histo_Corrections->SetBinContent(ii+1, jj+1, pTBiasFit);
    }
  } 

    TCanvas *c2 = new TCanvas("c2", "c2", 900, 800);
    Histo_Corrections->SetStats(0);
    gStyle->SetPalette(55);
    Histo_Corrections->SetContour(100);
    Histo_Corrections->Draw("colz");
    c2->SetRightMargin(0.13);
    c2->SaveAs("WideJets_Plot/Corrections.png");

    TFile* outputFile= new TFile("WideJetsCorrections_JEC_HLT_v7.root","RECREATE");
    outputFile->cd();
    Histo_Corrections -> Write();
    outputFile->Close();

   
  return 0;
}
Ejemplo n.º 26
0
void UpsilonMassFit_PolWeights(int iSpec = 3, int PutWeight=1)
{

  double PtCut=4;

  //minbias integrated, |y|<1.2 and |y|\in[1.2,2.4], centrality [0,10][10,20][20,100]%,  pt [0,6.5], [6.5, 10] [10,20]

  gROOT->SetStyle("Plain");
  gStyle->SetPalette(1);
  gStyle->SetFrameBorderMode(0);
  gStyle->SetFrameFillColor(0);
  gStyle->SetCanvasColor(0);
  gStyle->SetTitleFillColor(0);
  gStyle->SetStatColor(0);
  gStyle->SetPadBorderSize(0);
  gStyle->SetCanvasBorderSize(0);
  gStyle->SetOptTitle(1); // at least most of the time
  gStyle->SetOptStat(1); // most of the time, sometimes "nemriou" might be useful to display name, 
  //number of entries, mean, rms, integral, overflow and underflow
  gStyle->SetOptFit(1); // set to 1 only if you want to display fit results

  //==================================== Define Histograms====================================================
  ofstream dataFile(Form("Eff_Upsilon.txt"));
  
  TH1D *diMuonsInvMass_Gen = new TH1D("diMuonsInvMass_Gen","diMuonsInvMass_Gen", 100,8.0,12.0);
  TH1D *diMuonsPt_Gen = new TH1D("diMuonsPt_Gen","diMuonsPt_Gen", 100,0,30);
  //Rapidity Gen
  TH1D *diMuonsRap_Gen0 = new TH1D("diMuonsRap_Gen0","diMuonsRap_Gen0", 100,-5,5);
  TH1D *diMuonsRap_Gen1 = new TH1D("diMuonsRap_Gen1","diMuonsRap_Gen1", 100,-5,5);
  TH1D *diMuonsRap_Gen2 = new TH1D("diMuonsRap_Gen2","diMuonsRap_Gen2", 100,-5,5);
  TH1D *diMuonsRap_Gen3 = new TH1D("diMuonsRap_Gen3","diMuonsRap_Gen3", 100,-5,5);
  TH1D *diMuonsRap_Gen4 = new TH1D("diMuonsRap_Gen4","diMuonsRap_Gen4", 100,-5,5);
  TH1D *diMuonsRap_Gen5 = new TH1D("diMuonsRap_Gen5","diMuonsRap_Gen5", 100,-5,5);
  ////Rapidity Reco
  TH1D *diMuonsRap_Rec0 = new TH1D("diMuonsRap_Rec0","diMuonsRap_Rec0", 100,-5,5);
  diMuonsRap_Rec0->SetLineColor(2);
  TH1D *diMuonsRap_Rec1 = new TH1D("diMuonsRap_Rec1","diMuonsRap_Rec1", 100,-5,5);
  diMuonsRap_Rec1->SetLineColor(2);
  TH1D *diMuonsRap_Rec2 = new TH1D("diMuonsRap_Rec2","diMuonsRap_Rec2", 100,-5,5);
  diMuonsRap_Rec2->SetLineColor(2);
  TH1D *diMuonsRap_Rec3 = new TH1D("diMuonsRap_Rec3","diMuonsRap_Rec3", 100,-5,5);
  diMuonsRap_Rec3->SetLineColor(2);
  TH1D *diMuonsRap_Rec4 = new TH1D("diMuonsRap_Rec4","diMuonsRap_Rec4", 100,-5,5);
  diMuonsRap_Rec4->SetLineColor(2);
  TH1D *diMuonsRap_Rec5 = new TH1D("diMuonsRap_Rec5","diMuonsRap_Rec5", 100,-5,5);
  diMuonsRap_Rec5->SetLineColor(2);
  TH1D *Bin_Gen = new TH1D("Bin_Gen","Bin_Gen", 40,0,40);

  //==============================================Define AccEff Stuff here===========================================
  // Pt bin sizes
  int Nptbin=1;
  double pt_bound[100] = {0};
  if(iSpec == 1) { 
    Nptbin = 5;
    pt_bound[0] = 0;
    pt_bound[1] = 20.0;
    pt_bound[2] = 0.0;
    pt_bound[3] = 6.5;
    pt_bound[4] = 10.0;
    pt_bound[5] = 20.0;
   

    pt_bound[6] = 30.0;
    pt_bound[7] = 35;
    pt_bound[8] = 40;
    pt_bound[9] = 45;
    pt_bound[10] = 50;
  }
  
  if(iSpec == 2) { 
    Nptbin = 2;
    pt_bound[0] = 0.0; 
    pt_bound[1] = 1.2; 
    pt_bound[2] = 2.4; 
    
    pt_bound[3] = 0.0; 
    pt_bound[4] = 0.8; 
    pt_bound[5] = 1.8; 
    //pt_bound[7] = 2.0; 
    pt_bound[6] = 2.4; 
  
  }
  
  
  if(iSpec == 3) {
    Nptbin = 3;
    //for plots
    pt_bound[0] = 0.0;//0
    pt_bound[1] = 4.0;//10
    pt_bound[2] = 8.0;//20
    pt_bound[3] = 40.0;//100
   

    //pt_bound[4] = 16.0;//50
    //pt_bound[5] = 20.0;//100
    //pt_bound[6] = 24.0;
    //pt_bound[7] = 32.0;
    //pt_bound[8] = 40.0;
    //pt_bound[9] = 40.0;
  }
  //X Axis error on Eff graph 
  double PT[100], DelPT[100], mom_err[100];
  for (Int_t ih = 0; ih < Nptbin; ih++) {
    PT[ih] = (pt_bound[ih] + pt_bound[ih+1])/2.0;
    DelPT[ih] = pt_bound[ih+1] - pt_bound[ih];
    mom_err[ih] = DelPT[ih]/2.0;
  }
  
  double genError, recError;
  double gen_pt[100]={0}, gen_ptError[100]={0}; 
  double rec_pt[100]={0}, rec_ptError[100]={0}; 
  double Eff_cat_1[100]={0},Err_Eff_cat_1[100]={0};  
  
  // Histogram arrays
  TH1D *diMuonsInvMass_GenA[10][1000];
  TH1D *diMuonsInvMass_RecA[10][1000];
  TH1D *diMuonsPt_GenA[10][1000];
  TH1D *diMuonsPt_RecA[10][1000];
  char nameGen[10][500], nameRec[10][500], nameGenPt[10][500], nameRecPt[10][500];
 
  
  for (int ifile = 0; ifile <= 5; ifile++) {
    for (Int_t ih = 0; ih < Nptbin; ih++) {
      sprintf(nameGen[ifile],"DiMuonMassGen_pt_%d_%d",ih,ifile);
      sprintf(nameRec[ifile],"DiMuonMassRec_pt_%d_%d",ih,ifile);

      sprintf(nameGenPt[ifile],"DiMuonPtGen_pt_%d_%d",ih,ifile);
      sprintf(nameRecPt[ifile],"DiMuonPtRec_pt_%d_%d",ih,ifile);
      
      diMuonsInvMass_GenA[ifile][ih]= new TH1D(nameGen[ifile],nameGen[ifile],  100,8.0,12.0); //for eff Gen;
      diMuonsInvMass_GenA[ifile][ih]->Sumw2();
      diMuonsInvMass_GenA[ifile][ih]->SetMarkerStyle(7);
      diMuonsInvMass_GenA[ifile][ih]->SetMarkerColor(4);
      diMuonsInvMass_GenA[ifile][ih]->SetLineColor(4);

      diMuonsInvMass_RecA[ifile][ih] = new TH1D(nameRec[ifile],nameRec[ifile], 100,8.0,12.0); //for eff Rec;
      diMuonsInvMass_RecA[ifile][ih]->Sumw2();
      diMuonsInvMass_RecA[ifile][ih]->SetMarkerStyle(8);
      diMuonsInvMass_RecA[ifile][ih]->SetMarkerColor(4);
      diMuonsInvMass_RecA[ifile][ih]->SetLineColor(4);


      diMuonsPt_GenA[ifile][ih]= new TH1D(nameGenPt[ifile],nameGenPt[ifile],  100,0,40); //for eff Gen;
      diMuonsPt_RecA[ifile][ih]= new TH1D(nameRecPt[ifile],nameRecPt[ifile],  100,0,40); //for eff Rec;
    }
  }
  
  //===========================================Input Root File============================================================
  char fileName[10][500];
  //0.0380228 	0.0480769 	0.0293255 	0.0125156 	0.00336587 	0.00276319*2/5 = 0.001105276
  //Scales
  double scale[10]={0};  
  scale[0]=(6.8802); // pT [0-3]
  scale[1]=(8.6995); // pT [3-6]
  scale[2]=(5.3065); // pT [6-9]
  scale[3]=(2.2647); // pT [9-12] 
  scale[4]=(3.0453); // pT [12-15] 
  scale[5]=(1.0000); // pT [15-30]
  
  sprintf(fileName[0],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt03_N.root");
  sprintf(fileName[1],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt36_N.root");
  sprintf(fileName[2],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt69_N.root");
  sprintf(fileName[3],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt912_N.root");
  sprintf(fileName[4],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt1215_N.root");
  sprintf(fileName[5],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt1530_N.root");



  //double scale[10]={0};  
  //scale[0]=(0.0380228/0.001105276);
  //scale[1]=(0.0480769/0.001105276);
  //scale[2]=(0.0293255/0.001105276);
  //scale[3]=(0.0125156/0.001105276);
  //scale[4]=(0.00336587/0.001105276);
  //scale[5]=(0.001105276/0.001105276);
   //34.55 , 43.70 , 26.65 , 11.37 , 3.05 , 1
  //sprintf(fileName[0],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt03.root");
  //sprintf(fileName[1],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt36.root");
  //sprintf(fileName[2],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt69.root");
  //sprintf(fileName[3],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt912.root");
  //sprintf(fileName[4],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt1215.root");
  //sprintf(fileName[5],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt1530.root");
  
  TFile *infile;
  TTree *tree;
  TTree *gentree;
  
  //===========File loop ======================
  
  for(int ifile =0; ifile<=5; ifile++){
    
    infile=new TFile(fileName[ifile],"R");
    tree=(TTree*)infile->Get("SingleMuonTree");
    gentree=(TTree*)infile->Get("SingleGenMuonTree");
    
    //Event variables
    int eventNb,runNb,lumiBlock, gbin, rbin;
    //Jpsi Variables
    Double_t JpsiMass,JpsiPt,JpsiPx,JpsiPy,JpsiPz,JpsiRap, JpsiCharge,JpsiE;
    Double_t JpsiVprob;
    //2.) muon variables RECO                                                                       
    double muPosPx, muPosPy, muPosPz,  muPosEta, muPosPt,muPosP,muPosPhi;
    double muNegPx, muNegPy, muNegPz,  muNegEta, muNegPt,muNegP,muNegPhi;
    //(1).Positive Muon                                     
    double muPos_nchi2In, muPos_dxy, muPos_dz, muPos_nchi2Gl;
    int muPos_found, muPos_pixeLayers, muPos_nValidMuHits,muPos_arbitrated;
    bool muPos_matches,muPos_tracker;
    //(2).Negative Muon                                     
    double muNeg_nchi2In, muNeg_dxy, muNeg_dz, muNeg_nchi2Gl;
    int muNeg_found, muNeg_pixeLayers, muNeg_nValidMuHits,muNeg_arbitrated;
    bool muNeg_matches,muNeg_tracker;
    //Gen Level variables
    //Gen JPsi Variables
    double GenJpsiMass, GenJpsiPt, GenJpsiRap;
    double GenJpsiPx, GenJpsiPy, GenJpsiPz, GenJpsiE;
   
    //2.) Gen muon variables 
    double GenmuPosPx, GenmuPosPy, GenmuPosPz,  GenmuPosEta, GenmuPosPt, GenmuPosPhi;
    double GenmuNegPx, GenmuNegPy, GenmuNegPz,  GenmuNegEta, GenmuNegPt, GenmuNegPhi;

    //Event variables
    tree->SetBranchAddress("eventNb",&eventNb);
    tree->SetBranchAddress("runNb",&runNb);
    tree->SetBranchAddress("lumiBlock",&lumiBlock);
    
    //Jpsi Variables
    tree->SetBranchAddress("JpsiCharge",&JpsiCharge);
    tree->SetBranchAddress("JpsiMass",&JpsiMass);
    tree->SetBranchAddress("JpsiPt",&JpsiPt);
    tree->SetBranchAddress("JpsiPx",&JpsiPx);
    tree->SetBranchAddress("JpsiPy",&JpsiPy);
    tree->SetBranchAddress("JpsiPz",&JpsiPz);
    tree->SetBranchAddress("JpsiRap",&JpsiRap);
    tree->SetBranchAddress("JpsiVprob",&JpsiVprob);
    tree->SetBranchAddress("rbin",&rbin);
    
    //muon variable
    tree->SetBranchAddress("muPosPx",&muPosPx);
    tree->SetBranchAddress("muPosPy",&muPosPy);
    tree->SetBranchAddress("muPosPz",&muPosPz);
    tree->SetBranchAddress("muPosEta",&muPosEta);
    tree->SetBranchAddress("muPosPhi",&muPosPhi);
    tree->SetBranchAddress("muNegPx", &muNegPx);
    tree->SetBranchAddress("muNegPy",    &muNegPy);
    tree->SetBranchAddress("muNegPz",    &muNegPz);
    tree->SetBranchAddress("muNegEta",    &muNegEta);
     tree->SetBranchAddress("muNegPhi", &muNegPhi);

    //1). Positive Muon
    tree->SetBranchAddress("muPos_nchi2In", &muPos_nchi2In);
    tree->SetBranchAddress("muPos_dxy", &muPos_dxy);
    tree->SetBranchAddress("muPos_dz", &muPos_dz);
    tree->SetBranchAddress("muPos_nchi2Gl", &muPos_nchi2Gl);
    tree->SetBranchAddress("muPos_found", &muPos_found);
    tree->SetBranchAddress("muPos_pixeLayers", &muPos_pixeLayers);
    tree->SetBranchAddress("muPos_nValidMuHits", &muPos_nValidMuHits);
    tree->SetBranchAddress("muPos_matches", &muPos_matches);
    tree->SetBranchAddress("muPos_tracker", &muPos_tracker);
    tree->SetBranchAddress("muPos_arbitrated", &muPos_arbitrated);  
    
    //2). Negative Muon                                                                            
    tree->SetBranchAddress("muNeg_nchi2In", &muNeg_nchi2In);
    tree->SetBranchAddress("muNeg_dxy", &muNeg_dxy);
    tree->SetBranchAddress("muNeg_dz", &muNeg_dz);
    tree->SetBranchAddress("muNeg_nchi2Gl", &muNeg_nchi2Gl);
    tree->SetBranchAddress("muNeg_found", &muNeg_found);
    tree->SetBranchAddress("muNeg_pixeLayers", &muNeg_pixeLayers);
    tree->SetBranchAddress("muNeg_nValidMuHits", &muNeg_nValidMuHits);
    tree->SetBranchAddress("muNeg_matches", &muNeg_matches);
    tree->SetBranchAddress("muNeg_tracker", &muNeg_tracker);
    tree->SetBranchAddress("muNeg_arbitrated", &muNeg_arbitrated);
    



//====================================Gen Variables=========================================================
    //Gen Jpsi Variables
    gentree->SetBranchAddress("GenJpsiMass",   &GenJpsiMass);
    gentree->SetBranchAddress("GenJpsiPt",     &GenJpsiPt);
    gentree->SetBranchAddress("GenJpsiRap",    &GenJpsiRap);
    gentree->SetBranchAddress("GenJpsiPx",     &GenJpsiPx);
    gentree->SetBranchAddress("GenJpsiPy",     &GenJpsiPy);
    gentree->SetBranchAddress("GenJpsiPz",     &GenJpsiPz);
    gentree->SetBranchAddress("gbin",&gbin);
    //muon variable
    gentree->SetBranchAddress("GenmuPosPx",    &GenmuPosPx);
    gentree->SetBranchAddress("GenmuPosPy",    &GenmuPosPy);
    gentree->SetBranchAddress("GenmuPosPz",    &GenmuPosPz);
    gentree->SetBranchAddress("GenmuPosEta",    &GenmuPosEta);
     gentree->SetBranchAddress("GenmuPosPhi",    &GenmuPosPhi);
    gentree->SetBranchAddress("GenmuNegPx",    &GenmuNegPx);
    gentree->SetBranchAddress("GenmuNegPy",    &GenmuNegPy);
    gentree->SetBranchAddress("GenmuNegPz",    &GenmuNegPz);
    gentree->SetBranchAddress("GenmuNegEta",    &GenmuNegEta);
    gentree->SetBranchAddress("GenmuNegPhi",    &GenmuNegPhi);

    //====================================================== Gen tree loop ================================================
    int NAccep=0;
    int nGenEntries=gentree->GetEntries();
    cout<<" Total Entries in GenLevel Tree for pT range: "<<fileName[ifile]<<"  "<<   nGenEntries<< " ========="<<endl;
    //dataFile<<" Total Entries in GenLevel Tree for pT range: "<<fileName[ifile]<<"  "<<   nGenEntries<< " ====="<<endl;
    
    
    for(int i=0; i< nGenEntries; i++)  {	    
      gentree->GetEntry(i);
      
      if(i%1000==0){
	cout<<" processing record "<<i<<endl;
	cout<<" Mass "<< GenJpsiMass<< " pT "<< GenJpsiPt << " Y " <<GenJpsiRap<<endl; 
      }
      
      bool GenPosIn=0, GenNegIn=0,GenPosPass=0,GenNegPass=0;

      GenmuPosPt= TMath::Sqrt(GenmuPosPx*GenmuPosPx + GenmuPosPy*GenmuPosPy); 
      GenmuNegPt= TMath::Sqrt(GenmuNegPx*GenmuNegPx + GenmuNegPy*GenmuNegPy); 
      
      GenJpsiE= TMath::Sqrt( GenJpsiPx*GenJpsiPx+GenJpsiPy*GenJpsiPy+GenJpsiPz*GenJpsiPz + 9.46*9.46);


      
      //============================ calculate Pol weight ========================================================================================= //
      Float_t w1,w2,w3,w4,w5;
      // this is the beam energy: 2760GeV->/2->1380GeV each beam
      // the mp=0.938272 is the mass of the proton, as we are looking at p+p collisions
      double E=1380; double pz = sqrt(E*E - 0.938272*0.938272);
      TLorentzVector h1; // beam 1
      TLorentzVector h2; // beam 2
     
      TLorentzVector genJpsi;    // generated upsilon (mother of the single muons) --> if you look at jpsi-> genJpsi (prompt or non-prompt)
      TLorentzVector genMuPlus,genMuMinus; // generator positive muon (charge=+1)
      
      //int mp;
      Float_t cosThetaStarHel; // cosTheta in the Helicity frame
      Float_t cosThetaStarCS;  // cosTheta in the Collins-Soper frame
      TVector3 zCS;             // collins-soper variable

      // put the coordinates of the parent in a TLorentzVector
      // ATTENTION: the last coordinate is the MASS of the parent, which in this case, since it's about Upsilon, it's 9.46
      // when you'll do this for Jpsi, this value has to change to m_jpsi=3.097
      genJpsi.SetPxPyPzE(GenJpsiPx, GenJpsiPy, GenJpsiPz, GenJpsiE); 
      TLorentzRotation boost(-genJpsi.BoostVector()); // boost it
   
      // put the muon in a LorentzVector
      genMuPlus.SetPtEtaPhiM(GenmuPosPt, GenmuPosEta, GenmuPosPhi, 0.106);
      genMuPlus *= boost; // boost it
      
      //genMuMinus.SetPtEtaPhiM(GenmuNegPt, GenmuNegEta, GenmuNegPhi, 0.106);
      //genMuMinus *= boost; // boost it


      //and get the cosTheta in the helicity frame
      cosThetaStarHel = genMuPlus.Vect().Dot(genJpsi.Vect())/(genMuPlus.Vect().Mag()*genJpsi.Vect().Mag());
     
      //int genMuCharge = 1;
      //int mp = genMuCharge>0 ? 0 : 1;
      //cout << genMuCharge << "     " << mp << endl;


      h1.SetPxPyPzE(0,0,pz,E);  // TLorentzVector for beam 1
      h2.SetPxPyPzE(0,0,-pz,E); //  TLorentzVector for beam 2
      h1*=boost;
      h2*=boost;
      // calculate cosTheta CS

      zCS = ( h1.Vect().Unit() - h2.Vect().Unit() ).Unit();
      cosThetaStarCS = genMuPlus.Vect().Dot(zCS)/genMuPlus.Vect().Mag();

      // setup the weights
      w1 = 1;
      w2 = 1 + cosThetaStarHel*cosThetaStarHel;
      w3 = 1 - cosThetaStarHel*cosThetaStarHel;
      w4 = 1 + cosThetaStarCS*cosThetaStarCS;
      w5 = 1 - cosThetaStarCS*cosThetaStarCS;
      

      //w5=1; 

      // cout<<" gen "<<w2<<"   "<<w3<<"  "<<w4<<"  "<<w5<<endl;

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


    
      diMuonsInvMass_Gen->Fill(GenJpsiMass);
      diMuonsPt_Gen->Fill(GenJpsiPt);
 
      if(IsAccept(GenmuPosPt, GenmuPosEta)) {GenPosIn=1;}
      if(IsAccept(GenmuNegPt, GenmuNegEta)) {GenNegIn=1;}
  

    
      if(GenPosIn && GenNegIn ) NAccep++;
      
      if(GenPosIn==1 && GenmuPosPt>PtCut ) {GenPosPass=1;}
      if(GenNegIn==1 && GenmuNegPt>PtCut ) {GenNegPass=1;}

      double GenCenWeight=0,GenWeight=0;
      GenCenWeight=FindCenWeight(gbin);
      Bin_Gen->Fill(gbin);
      GenWeight=GenCenWeight*scale[ifile];
      if(PutWeight==0){GenWeight=1;}

      if(GenPosIn && GenNegIn){
	if(ifile==0){diMuonsRap_Gen0->Fill(GenJpsiRap);}
	if(ifile==1){diMuonsRap_Gen1->Fill(GenJpsiRap);}
	if(ifile==2){diMuonsRap_Gen2->Fill(GenJpsiRap);}
	if(ifile==3){diMuonsRap_Gen3->Fill(GenJpsiRap);}
	if(ifile==4){diMuonsRap_Gen4->Fill(GenJpsiRap);}
	if(ifile==5){diMuonsRap_Gen5->Fill(GenJpsiRap);}
      }
 

      for (Int_t ih = 0; ih < Nptbin; ih++) {
	//adding pT of all pt bins to see diss is cont
	if(iSpec == 1)  if( (GenPosPass==1 && GenNegPass==1) && (TMath::Abs(GenJpsiRap)<2.4 ) && (GenJpsiPt>pt_bound[ih] && GenJpsiPt<=pt_bound[ih+1])){diMuonsPt_GenA[ifile][ih]->Fill(GenJpsiPt,GenWeight*w5);}
	if(iSpec == 1)  if( (GenPosPass==1 && GenNegPass==1) && (TMath::Abs(GenJpsiRap)<2.4 )&&(GenJpsiPt>pt_bound[ih] && GenJpsiPt<=pt_bound[ih+1])){diMuonsInvMass_GenA[ifile][ih]->Fill(GenJpsiMass,GenWeight*w5);}
	if(iSpec == 2)  if((GenPosPass==1 && GenNegPass==1) &&  (GenJpsiPt<20.0) && (TMath::Abs(GenJpsiRap) > pt_bound[ih] && TMath::Abs(GenJpsiRap) <=pt_bound[ih+1] )){diMuonsInvMass_GenA[ifile][ih]->Fill(GenJpsiMass,GenWeight*w5);}
	if(iSpec == 3)  if( (GenPosPass==1 && GenNegPass==1) && (GenJpsiPt < 20.0) &&  (TMath::Abs(GenJpsiRap)<2.4 ) && (gbin>=pt_bound[ih] && gbin<pt_bound[ih+1])){diMuonsInvMass_GenA[ifile][ih]->Fill(GenJpsiMass,GenWeight*w5);}
      

      }

    }//gen loop end
    
    cout<<" accepted no "<< NAccep<<endl;
    //dataFile<<" accepted no "<< NAccep<<endl;
     
    //   new TCanvas;
    //diMuonsInvMass_Gen->Draw();
    //gPad->Print("plots/diMuonsInvMass_Gen.png");
    
    //new TCanvas;
    //diMuonsPt_Gen->Draw();
    //gPad->Print("plots/diMuonsPt_Gen.png");
  
    //new TCanvas;
    //diMuonsRap_Gen0->Draw();
    //sprintf(PlotName,"plots/diMuonsRap_Gen_%d.pdf",ifile);   
    //gPad->Print(PlotName);
    
    //new TCanvas;
    //Bin_Gen->Draw();
    //gPad->Print("plots/Bin_Gen.png");
    
  

    //=============== Rec Tree Loop ==============================================================================
    
    int nRecEntries=tree->GetEntries();
    cout<<"Total Entries in reconstructed Tree for pT range "<<fileName[ifile]<<"  "<<nRecEntries<< "====="<<endl;
    //dataFile<<"Total Entries in reconstructed Tree for pT range "<<fileName[ifile]<<"  "<<nRecEntries<<endl;
    
    for(int i=0; i<nRecEntries; i++)  {	    
      tree->GetEntry(i);
      if(i%100000==0){
	cout<<" processing record "<<i<<endl;
	cout<<" processing Run  " <<runNb <<" event "<<eventNb<<" lum block "<<lumiBlock<<endl;    
	cout<<" Mass "<< JpsiMass<< " pT "<< JpsiPt << " Y " <<JpsiRap<<"  "<<JpsiVprob<<" charge "<<JpsiCharge<<endl; 
      }
      
      bool PosPass=0, NegPass=0, AllCut=0 ,PosIn=0, NegIn=0;
      muPosPt= TMath::Sqrt(muPosPx*muPosPx + muPosPy*muPosPy); 
      muPosP = TMath::Sqrt(muPosPx*muPosPx + muPosPy*muPosPy+ muPosPz*muPosPz); 
      muNegPt= TMath::Sqrt(muNegPx*muNegPx + muNegPy*muNegPy); 
      muNegP = TMath::Sqrt(muNegPx*muNegPx + muNegPy*muNegPy +muNegPz*muNegPz); 
    
      
      JpsiE= TMath::Sqrt(JpsiPx*JpsiPx+JpsiPy*JpsiPy+JpsiPz*JpsiPz + JpsiMass*JpsiMass);
      //============================ calculate Pol weight rec ========================================================================================= //
      Float_t w1=0,w2=0,w3=0,w4=0,w5=0;
      double E=1380; double pz = sqrt(E*E - 0.938272*0.938272);
      TLorentzVector h1; // beam 1
      TLorentzVector h2; // beam 2
      
      TLorentzVector Jpsi;    
      TLorentzVector MuPlus;       
      Float_t cosThetaStarHel; // cosTheta in the Helicity frame
      Float_t cosThetaStarCS;  // cosTheta in the Collins-Soper frame
      TVector3 zCS;             // collins-soper variable
      
      Jpsi.SetPxPyPzE(JpsiPx, JpsiPy, JpsiPz, JpsiE); 
      TLorentzRotation boost(-Jpsi.BoostVector()); // boost it
      
      // put the muon in a LorentzVector
      MuPlus.SetPtEtaPhiM(muPosPt, muPosEta, muPosPhi, 0.106);
      MuPlus *= boost; // boost it
      //and get the cosTheta in the helicity frame
      cosThetaStarHel = MuPlus.Vect().Dot(Jpsi.Vect())/(MuPlus.Vect().Mag()*Jpsi.Vect().Mag());
      h1.SetPxPyPzE(0,0,pz,E);  // TLorentzVector for beam 1
      h2.SetPxPyPzE(0,0,-pz,E); //  TLorentzVector for beam 2
      h1*=boost;
      h2*=boost;
      zCS = ( h1.Vect().Unit() - h2.Vect().Unit() ).Unit();
      cosThetaStarCS = MuPlus.Vect().Dot(zCS)/MuPlus.Vect().Mag();
      // setup the weights
      w1 = 1;
      w2 = 1 + cosThetaStarHel*cosThetaStarHel;
      w3 = 1 - cosThetaStarHel*cosThetaStarHel;
      w4 = 1 + cosThetaStarCS*cosThetaStarCS;
      w5 = 1 - cosThetaStarCS*cosThetaStarCS;
      


      //w5=1;
      //cout<<" rec "<<w2<<"   "<<w3<<"  "<<w4<<"  "<<w5<<endl; 
      //================================================== Pol weights  ===============================================================================//
      
      if(IsAccept(muPosPt, muPosEta)){PosIn=1;}
      if(IsAccept(muNegPt, muNegEta)){NegIn=1;}



      if(muPos_found > 10 && muPos_pixeLayers > 0 && muPos_nchi2In < 4.0 && muPos_dxy < 3 && muPos_dz < 15 && muPos_nchi2Gl < 20 &&  muPos_arbitrated==1 && muPos_tracker==1){PosPass=1;}	  
      
      if(muNeg_found >10 && muNeg_pixeLayers >0 && muNeg_nchi2In <4.0 && muNeg_dxy < 3 && muNeg_dz < 15 && muNeg_nchi2Gl < 20 && muNeg_arbitrated==1 && muNeg_tracker==1){NegPass=1;}

      // cout<<muPos_matches<<"  "<<muNeg_matches<<endl;
      
      if((muPosPt > PtCut && muNegPt > PtCut) && (muPos_matches==1 && muNeg_matches==1) && (PosIn==1 && NegIn==1 )  &&   (PosPass==1 && NegPass==1)){AllCut=1;}
    
      double RecCenWeight=0,RecWeight=0;
      RecCenWeight=FindCenWeight(rbin);
      RecWeight=RecCenWeight*scale[ifile];
      if(PutWeight==0){RecWeight=1;}
     
      if(i%100000==0){
	cout<<" eff loop for reco "<<endl;
      }
      
      if(AllCut==1){
	if(ifile==0){diMuonsRap_Rec0->Fill(JpsiRap);}
	if(ifile==1){diMuonsRap_Rec1->Fill(JpsiRap);}
	if(ifile==2){diMuonsRap_Rec2->Fill(JpsiRap);}
	if(ifile==3){diMuonsRap_Rec3->Fill(JpsiRap);}
	if(ifile==4){diMuonsRap_Rec4->Fill(JpsiRap);}
	if(ifile==5){diMuonsRap_Rec5->Fill(JpsiRap);}
      }

      //Eff loop for reco
      if((JpsiCharge == 0) && (JpsiVprob > 0.01)) {
	for (Int_t ih = 0; ih < Nptbin; ih++) {
	  //to see cont reco pT
	  if(iSpec == 1)if((AllCut==1) && (TMath::Abs(JpsiRap) < 2.4) && (JpsiPt>pt_bound[ih] && JpsiPt<=pt_bound[ih+1])) {diMuonsPt_RecA[ifile][ih]->Fill(JpsiPt,RecWeight*w5);}
	  
	  if(iSpec == 1)if((AllCut==1) && (TMath::Abs(JpsiRap)<2.4 ) && (JpsiPt > pt_bound[ih] && JpsiPt <=pt_bound[ih+1])){diMuonsInvMass_RecA[ifile][ih]->Fill(JpsiMass, RecWeight*w5);}
	  if(iSpec == 2) if( (AllCut==1) &&  (JpsiPt<20.0) && (TMath::Abs(JpsiRap) > pt_bound[ih] && TMath::Abs(JpsiRap) <=pt_bound[ih+1])){diMuonsInvMass_RecA[ifile][ih]->Fill(JpsiMass,RecWeight*w5);}
	  if(iSpec == 3) if((AllCut==1) &&  (JpsiPt<20.0) && (TMath::Abs(JpsiRap) < 2.4) && (rbin>=pt_bound[ih] &&  rbin < pt_bound[ih+1])){diMuonsInvMass_RecA[ifile][ih]->Fill(JpsiMass,RecWeight*w5);}
	



	}
      }
    }
  
    /*
    new TCanvas;
    if(ifile==0){diMuonsRap_Gen0->Draw();new TCanvas; diMuonsRap_Rec0->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen0.png");}
    if(ifile==1){diMuonsRap_Gen1->Draw();new TCanvas; diMuonsRap_Rec1->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen1.png");}
    if(ifile==2){diMuonsRap_Gen2->Draw();new TCanvas; diMuonsRap_Rec2->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen2.png");}
    if(ifile==3){diMuonsRap_Gen3->Draw();new TCanvas; diMuonsRap_Rec3->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen3.png");}
    if(ifile==4){diMuonsRap_Gen4->Draw();new TCanvas; diMuonsRap_Rec4->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen4.png");}
    if(ifile==5){diMuonsRap_Gen5->Draw();new TCanvas; diMuonsRap_Rec5->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen5.png");}
    */
  }  // file loop ends 

  ///////////////////////////////////////////////////////////////////

  cout<< " adding "<<endl;
  TH1D *diMuonsInvMass_RecA1[100];
  TH1D *diMuonsInvMass_GenA1[100];
  TH1D *diMuonsPt_GenA1[100];
  TH1D *diMuonsPt_RecA1[100];
  TF1 *backfun_1;
  char namePt_1B[500];//for bkg func
 
  for(Int_t ih = 0; ih < Nptbin; ih++){
    diMuonsInvMass_RecA1[ih] = diMuonsInvMass_RecA[0][ih];
    diMuonsInvMass_GenA1[ih] = diMuonsInvMass_GenA[0][ih];
    diMuonsPt_GenA1[ih] = diMuonsPt_GenA[0][ih];
    diMuonsPt_RecA1[ih] = diMuonsPt_RecA[0][ih];
    
    for (int ifile = 1; ifile <= 5; ifile++) {
      diMuonsInvMass_RecA1[ih]->Add(diMuonsInvMass_RecA[ifile][ih]);
      diMuonsInvMass_GenA1[ih]->Add(diMuonsInvMass_GenA[ifile][ih]);     
      
      diMuonsPt_GenA1[ih]->Add(diMuonsPt_GenA[ifile][ih]); 
      diMuonsPt_RecA1[ih]->Add(diMuonsPt_RecA[ifile][ih]); 
    }
  }
  
  //===========================Fitting===================================================================//
  // Fit ranges
  double mass_low, mass_high;
  double MassUpsilon, WeidthUpsilon;
  
  // Low mass range upsilon width 54 KeV
  MassUpsilon = 9.46; WeidthUpsilon = 0.055;
  //MassUpsilon = 9.46; WeidthUpsilon = 0.068;
  mass_low = 9.0; mass_high = 10.0;  // Fit ranges
  
  // Fit Function crystall ball
  TF1 *GAUSPOL = new TF1("GAUSPOL",CrystalBall,8.0,12.0,6);
  GAUSPOL->SetParNames("Yield (#Upsilon)","BinWidth","Mean","Sigma","#alpha","n");
  GAUSPOL->SetParameter(2, MassUpsilon);
  GAUSPOL->SetParameter(3, WeidthUpsilon);
  //GAUSPOL->SetParLimits(3, 0.1*WeidthUpsilon,2.0*WeidthUpsilon);
  GAUSPOL->SetParameter(4, 1.0);
  GAUSPOL->SetParameter(5, 20.0);
  GAUSPOL->SetLineWidth(2.0);
  GAUSPOL->SetLineColor(2);




  //=====================Loop for eff===========================================================
  double GenNo[100]={0};
  double Eff[100]={0};
  double GenError[100]={0};
  double RecError[100]={0};
  double errEff_cat_S1[100]={0};
  double errEff_cat_S2[100]={0};
  double errEff_cat_S1_1[100]={0},errEff_cat_S1_2[100]={0};
  double errEff_cat_S2_1[100]={0},errEff_cat_S2_2[100]={0};
  char PlotName[500],PlotName1[500], PlotName2[500]; 
  char GPlotName[500],GPlotName1[500], GPlotName2[500];

  for (Int_t ih = 0; ih < Nptbin; ih++) {
   
    cout<<" no of gen dimuons from diMuons Pt histo    "<<diMuonsPt_GenA1[ih]->Integral(1,100)<<endl;
    cout<<" no of gen dimuons from diMuons Mass histo  "<<diMuonsInvMass_GenA1[ih]->Integral(1,100)<<endl;
    

    //from pT histogram
    //gen_pt[ih] =diMuonsPt_GenA1[ih]->IntegralAndError(1,100,genError);
   
    gen_pt[ih] = diMuonsInvMass_GenA1[ih]->IntegralAndError(1,100,genError);
    gen_ptError[ih]= genError;
    
    if(iSpec==1) sprintf(PlotName,"plots/DiMuonMass_PtBin_%d.png",ih);
    if(iSpec==2) sprintf(PlotName,"plots/DiMuonMass_RapBin_%d.png",ih);
    if(iSpec==3) sprintf(PlotName,"plots/DiMuonMass_CentBin_%d.png",ih);
    
    if(iSpec==1) sprintf(PlotName1,"plots/DiMuonMass_PtBin_%d.pdf",ih);
    if(iSpec==2) sprintf(PlotName1,"plots/DiMuonMass_RapBin_%d.pdf",ih);
    if(iSpec==3) sprintf(PlotName1,"plots/DiMuonMass_CentBin_%d.pdf",ih);
    
    if(iSpec==1) sprintf(PlotName2,"plots/DiMuonMass_PtBin_%d.eps",ih);
    if(iSpec==2) sprintf(PlotName2,"plots/DiMuonMass_RapBin_%d.eps",ih);
    if(iSpec==3) sprintf(PlotName2,"plots/DiMuonMass_CentBin_%d.eps",ih);
 

    //giving inetial value for crystall ball fourth parameter 
    diMuonsInvMass_RecA1[ih]->Rebin(2);
    GAUSPOL->SetParameter(0, diMuonsInvMass_RecA1[ih]->Integral(0,50));
    GAUSPOL->FixParameter(1, diMuonsInvMass_RecA1[ih]->GetBinWidth(1));
    
    new TCanvas; 
    diMuonsInvMass_RecA1[ih]->Fit("GAUSPOL","LLMERQ", "", mass_low, mass_high);
   
    double UpsilonMass = GAUSPOL->GetParameter(2);
    double UpsilonWidth = GAUSPOL->GetParameter(3);
   
    double UpsilonYield = GAUSPOL->GetParameter(0);
    double UpsilonYieldError = GAUSPOL->GetParError(0);
 
    double par[20];
    GAUSPOL->GetParameters(par);
    sprintf(namePt_1B,"pt_1B_%d",ih);
    backfun_1 = new TF1(namePt_1B, Pol2, mass_low, mass_high, 3);
    backfun_1->SetParameters(&par[4]);
   

    double MassLow=(UpsilonMass-3*UpsilonWidth);
    double MassHigh=(UpsilonMass+3*UpsilonWidth);
    
    int binlow =diMuonsInvMass_RecA1[ih]->GetXaxis()->FindBin(MassLow);
    int binhi =diMuonsInvMass_RecA1[ih]->GetXaxis()->FindBin(MassHigh);
    double binwidth=diMuonsInvMass_RecA1[ih]->GetBinWidth(1);
        
    //yield by function 
    //rec_pt[ih] = UpsilonYield;
    //rec_ptError[ih]= UpsilonYieldError;

    cout<<"Rec diMuons from Pt histo "<<diMuonsPt_RecA1[ih]->Integral(1,100)<<endl;  
    cout<<"Rec dimuons from mass "<<diMuonsInvMass_RecA1[ih]->Integral(1,100)<<endl; 
    

      
    //from pT histo
    //rec_pt[ih]=diMuonsPt_RecA1[ih]->IntegralAndError(1, 100,recError);

    //yield by histogram integral
    rec_pt[ih] = diMuonsInvMass_RecA1[ih]->IntegralAndError(binlow, binhi,recError);
    rec_ptError[ih]= recError;
  
    //Cal eff 
    Eff_cat_1[ih] = rec_pt[ih]/gen_pt[ih]; 
  
    //calculate error on eff
    GenNo[ih]=gen_pt[ih];
    Eff[ih]= Eff_cat_1[ih];
    GenError[ih]=gen_ptError[ih];
    RecError[ih]=rec_ptError[ih];
    //error    
    errEff_cat_S1_1[ih]= ( (Eff[ih] * Eff[ih]) /(GenNo[ih] * GenNo[ih]) );
    errEff_cat_S1_2[ih]= (RecError[ih] * RecError[ih]);
    errEff_cat_S1[ih]= (errEff_cat_S1_1[ih] * errEff_cat_S1_2[ih]);
   

    errEff_cat_S2_1[ih]= ( (1 - Eff[ih])* (1 - Eff[ih]) ) / ( GenNo[ih] * GenNo[ih]);
    errEff_cat_S2_2[ih]= (GenError[ih] * GenError[ih] ) - ( RecError[ih] * RecError[ih] );


    errEff_cat_S2[ih]=errEff_cat_S2_1[ih]*errEff_cat_S2_2[ih];
   

    Err_Eff_cat_1[ih]=sqrt(errEff_cat_S1[ih] + errEff_cat_S2[ih]);
   
    //error for no weights
    //Err_Eff_cat_1[ih]= Eff_cat_1[ih]*TMath::Sqrt(gen_ptError[ih]*gen_ptError[ih]/(gen_pt[ih]*gen_pt[ih]) + rec_ptError[ih]*rec_ptError[ih]/(rec_pt[ih]* rec_pt[ih]));

    cout<<"Upsilon Yield by integral of histo:  "<< diMuonsInvMass_RecA1[ih]->IntegralAndError(binlow, binhi,recError) <<"  error "<< rec_ptError[ih]<<endl; 
    cout<<"UpsilonYield by Gauss yield det:     "<< UpsilonYield << " UpsilonWidth "<< UpsilonWidth<<" UpsilonMass "<<UpsilonMass <<endl;
    cout<<"Upsilon Yield by Function integral:  "<< GAUSPOL->Integral(MassLow,MassHigh)/binwidth <<endl;
    cout<<" rec_pt[ih]  "<<  rec_pt[ih] <<" gen_pt[ih] "<<gen_pt[ih]<<endl;
    //dataFile<<" rec_pt[ih]  "<<  rec_pt[ih] <<" gen_pt[ih] "<<gen_pt[ih]<<endl;
    cout<<" eff "<< Eff_cat_1[ih]<<" error "<<Err_Eff_cat_1[ih]<<endl;
    
    dataFile<<"ih " <<ih<<" eff "<< Eff_cat_1[ih]<<" error "<<Err_Eff_cat_1[ih]<<endl;
    
    if(iSpec==1) sprintf(GPlotName,"plots/GenDiMuonMass_PtBin_%d.png",ih);
    if(iSpec==2) sprintf(GPlotName,"plots/GenDiMuonMass_RapBin_%d.png",ih);
    if(iSpec==3) sprintf(GPlotName,"plots/GenDiMuonMass_CentBin_%d.png",ih);
    
    if(iSpec==1) sprintf(GPlotName1,"plots/GenDiMuonMass_PtBin_%d.pdf",ih);
    if(iSpec==2) sprintf(GPlotName1,"plots/GenDiMuonMass_RapBin_%d.pdf",ih);
    if(iSpec==3) sprintf(GPlotName1,"plots/GenDiMuonMass_CentBin_%d.pdf",ih);
    
    if(iSpec==1) sprintf(GPlotName2,"plots/GenDiMuonMass_PtBin_%d.eps",ih);
    if(iSpec==2) sprintf(GPlotName2,"plots/GenDiMuonMass_RapBin_%d.eps",ih);
    if(iSpec==3) sprintf(GPlotName2,"plots/GenDiMuonMass_CentBin_%d.eps",ih);
       
    backfun_1->SetLineColor(4);
    backfun_1->SetLineWidth(1);
    //backfun_1->Draw("same");
    gPad->Print(PlotName);
    gPad->Print(PlotName1);
    gPad->Print(PlotName2);

    new TCanvas;
    diMuonsInvMass_GenA1[ih]->Draw();
    gPad->Print(GPlotName);
    gPad->Print(GPlotName1);
    gPad->Print(GPlotName2);


    //new TCanvas;
    //diMuonsPt_GenA1[ih]->Draw();
    //new TCanvas;
    //diMuonsPt_RecA1[ih]->Draw();
 
}
  dataFile.close();

  TGraphErrors *Eff_Upsilon = new TGraphErrors(Nptbin, PT, Eff_cat_1, mom_err,Err_Eff_cat_1);
  Eff_Upsilon->SetMarkerStyle(21);
  Eff_Upsilon->SetMarkerColor(2);
  Eff_Upsilon->GetYaxis()->SetTitle("Reco Eff");
 
  if(iSpec==1) Eff_Upsilon->GetXaxis()->SetTitle("#Upsilon pT (GeV/c^{2})");
  if(iSpec==2) Eff_Upsilon->GetXaxis()->SetTitle("#Upsilon rapidity");
  if(iSpec==3) Eff_Upsilon->GetXaxis()->SetTitle("bin");
   Eff_Upsilon->GetYaxis()->SetRangeUser(0,1.0);

  TLegend *legend_GP = new TLegend( 0.50,0.79,0.80,0.89);
  legend_GP->SetBorderSize(0);
  legend_GP->SetFillStyle(0);
  legend_GP->SetFillColor(0);
  legend_GP->SetTextSize(0.032);
  legend_GP->AddEntry(Eff_Upsilon,"PythiaEvtGen + HydjetBass", "P");
  
  new TCanvas;
  Eff_Upsilon->Draw("AP");
  legend_GP->Draw("Same");
    
  if(iSpec==1){ gPad->Print("plots/Eff_Upsilon_Pt.pdf");gPad->Print("plots/Eff_Upsilon_Pt.png");gPad->Print("plots/Eff_Upsilon_Pt.eps");}
  if(iSpec==2){ gPad->Print("plots/Eff_Upsilon_Rap.pdf");gPad->Print("plots/Eff_Upsilon_Rap.png");  gPad->Print("plots/Eff_Upsilon_Rap.eps");}
  if(iSpec==3){ gPad->Print("plots/Eff_Upsilon_Cent.pdf");gPad->Print("plots/Eff_Upsilon_Cent.png"); gPad->Print("plots/Eff_Upsilon_Cent.eps"); }

}
Ejemplo n.º 27
0
int makeInvMassHistosNoBGKK(){
    //Set global style stuff
    gROOT->Reset();
    gROOT->SetStyle("Plain");
    gStyle->SetPalette(1);
    gStyle->SetCanvasColor(kWhite);
    gStyle->SetCanvasBorderMode(0);
    gStyle->SetPadBorderMode(0);
    gStyle->SetTitleBorderSize(0);
    gStyle->SetOptStat(0);
    gStyle->SetOptFit(1);
    gStyle->SetErrorX(0);
    gStyle->SetTitleW(0.9);
    gStyle->SetTitleSize(0.05, "xyz");
    gStyle->SetTitleSize(0.06, "h");

    int NUM_PT_BINS = 20;
    int NUM_MASS_BINS = 1000;
    double MASS_LOW = 0.0;
    double MASS_HIGH = 2.0;
    string particles [8];
    particles[0] = "K*^{+} + K*^{0}";
    particles[1] = "K*^{-} + #bar{K}*^{0}";
    particles[2] = "K*^{+}";
    particles[3] = "K*^{-}";
    particles[4] = "K*^{0}";
    particles[5] = "#bar{K}*^{0}";
    particles[6] = "K*^{0} + #bar{K}*^{0}";
    particles[7] = "K*^{+} + K*^{-}";
//at decay point
//    string folder = "/Users/jtblair/Downloads/kstar_data/decayed/pt02/";
//reconstructed
    string folder = "/Users/jtblair/Downloads/kstar_data/reconstructed/pt02/";

    string files[20];
    files[0] = "invm_[0.0,0.2].dat";
    files[1] = "invm_[0.2,0.4].dat";
    files[2] = "invm_[0.4,0.6].dat";
    files[3] = "invm_[0.6,0.8].dat";
    files[4] = "invm_[0.8,1.0].dat";
    files[5] = "invm_[1.0,1.2].dat";
    files[6] = "invm_[1.2,1.4].dat";
    files[7] = "invm_[1.4,1.6].dat";   
    files[8] = "invm_[1.6,1.8].dat";
    files[9] = "invm_[1.8,2.0].dat";
    files[10] = "invm_[2.0,2.2].dat";
    files[11] = "invm_[2.2,2.4].dat";
    files[12] = "invm_[2.4,2.6].dat";
    files[13] = "invm_[2.6,2.8].dat";
    files[14] = "invm_[2.8,3.0].dat";
    files[15] = "invm_[3.0,3.2].dat";
    files[16] = "invm_[3.2,3.4].dat";
    files[17] = "invm_[3.4,3.6].dat";
    files[18] = "invm_[3.6,3.8].dat";
    files[19] = "invm_[3.8,4.0].dat";
/*
    string files[8];
    files[0] = "invm_[0.0,0.5].dat";
    files[1] = "invm_[0.5,1.0].dat";
    files[2] = "invm_[1.0,1.5].dat";
    files[3] = "invm_[1.5,2.0].dat";
    files[4] = "invm_[2.0,2.5].dat";
    files[5] = "invm_[2.5,3.0].dat";
    files[6] = "invm_[3.0,3.5].dat";
    files[7] = "invm_[3.5,4.0].dat";
*/

    Int_t PARTICLE_NUM = 5;

    TFile *output = new TFile("20170721_KKbarAdded2_fixedwidth42_recon_pf100_scaled_error05.root", "RECREATE");

    TH1D *kstar0mass = new TH1D("kstar0mass", Form("Fit value of M*_{0} vs. p_{T} for %s", particles[PARTICLE_NUM].c_str()), NUM_PT_BINS, 0.0, 4.0);
    TH1D *kstar0width = new TH1D("kstar0width", Form("#Gamma_{tot}(M=M*_{0}) vs p_{T} for %s", particles[PARTICLE_NUM].c_str()), NUM_PT_BINS, 0.0, 4.0);
    TH1D *kstar0collWidth = new TH1D("kstar0collWidth", Form("Fit value of #Gamma_{coll} component vs. p_{T} for %s", particles[PARTICLE_NUM].c_str()), NUM_PT_BINS,0.0, 4.0);
    TH1D *kstar0decWidth = new TH1D("kstar0decWidth", Form("#Gamma_{dec}(M=M*_{0}) component vs. p_{T} for %s;p_{T} (GeV/c);Width (GeV/c^2)", particles[PARTICLE_NUM].c_str()), NUM_PT_BINS,0.0, 4.0);
   
    kstar0mass->GetXaxis()->SetTitle("p_{T} (GeV/c)");
    kstar0mass->GetYaxis()->SetTitle("Mass (GeV/c^{2})");
    kstar0width->GetXaxis()->SetTitle("p_{T} (GeV/c)");
    kstar0width->GetYaxis()->SetTitle("Width (GeV/c^2)");
    kstar0collWidth->GetXaxis()->SetTitle("p_{T} (GeV/c)");
    kstar0collWidth->GetYaxis()->SetTitle("Width (GeV/c^2)");

    kstar0mass->SetStats(kFALSE);
    kstar0width->SetStats(kFALSE);
    kstar0collWidth->SetStats(kFALSE);
    kstar0decWidth->SetStats(kFALSE);

    TF1 *massline = new TF1("massline", "[0]", 0.0, 4.0);
    massline->SetParameter(0, 0.892);
    massline->SetLineColor(2);
    massline->SetLineStyle(7);

    TF1 *widthline = new TF1("widthline", "[0]", 0.0, 4.0);
    widthline->SetParameter(0, 0.042);

    double mass = 0.0, width = 0.0, collWidth = 0.0, massBG=0.0;
    double massError = 0.0, widthError= 0.0, collWidthError = 0.0, massBGError=0.0;

    TCanvas *canvas[9];
    TCanvas *diffCanvas[9];
    TPaveStats *st;
    TPad *pad;

    //ofstream integrals;
    //integrals.open("kstarbar_integrals.txt");

    for(int nfile = 0; nfile < NUM_PT_BINS; nfile++){
        double meanPT = (double)(nfile*2+1)/10.0;
        string filename = folder+files[nfile];
        string ptLower = filename.substr(filename.find("[")+1, 3);
        string ptHigher = filename.substr(filename.find(",")+1, 3);   
        TH1D* histos[8];
        TH1D* newHistos[8];
        TH1D* diffHistos[8];
        TH1D* bg[8];
        for(int i=0; i<8; i++){
            if(nfile<5){
                histos[i] = new TH1D(Form("ptbin0%dparticle%d",nfile*2+1, i), Form("Invariant Mass for (%s), %s < p_{T} < %s",particles[i].c_str(), ptLower.c_str(), ptHigher.c_str()), NUM_MASS_BINS, MASS_LOW, MASS_HIGH);
            newHistos[i] = new TH1D(Form("newptbin0%dparticle%d",nfile*2+1, i), Form("Invariant Mass for (%s), %s < p_{T} < %s",particles[i].c_str(), ptLower.c_str(), ptHigher.c_str()), 250, MASS_LOW, MASS_HIGH);

            }else{
                histos[i] = new TH1D(Form("ptbin%dparticle%d",nfile*2+1, i), Form("Invariant Mass for (%s), %s < p_{T} < %s",particles[i].c_str(), ptLower.c_str(), ptHigher.c_str()), NUM_MASS_BINS, MASS_LOW, MASS_HIGH);
                newHistos[i] = new TH1D(Form("newptbin%dparticle%d",nfile*2+1, i), Form("Invariant Mass for (%s), %s < p_{T} < %s",particles[i].c_str(), ptLower.c_str(), ptHigher.c_str()), 250, MASS_LOW, MASS_HIGH);

            }
            histos[i]->GetXaxis()->SetTitle("Invariant Mass (GeV/c^{2})");
            histos[i]->GetYaxis()->SetTitle("Counts");
        }

        ifstream input;
        input.open(filename.c_str());
        string line = "";
        if(input.good()){
            getline(input, line);
        }

        double massBin=0.0;
        double invMass[8];
        for(int i=0; i<8; i++){
            invMass[i] = 0.0;
        }
        int lineNumber = 1;
        while(1){
            input >> massBin >> invMass[0] >> invMass[1] >> invMass[2] >> invMass[3] >> invMass[4] >> invMass[5] >> invMass[6] >> invMass[7];
            if(!input.good())break;
            for(int i =0; i<8; i++){
                histos[i]->SetBinContent(lineNumber, invMass[i]/500.0);
            }
            if(lineNumber > 440 && lineNumber < 460 && nfile==6){
//               printf("mass: %.12f invMass[6]: %.12f\n", massBin, invMass[6]);
            }
            lineNumber++;
        }
         

        printf("****** Fits for file: %s ******\n", filename.c_str());
        for(int i=PARTICLE_NUM; i<PARTICLE_NUM+1; i++){
           
            //add the K*0 distribution to the K*0bar (K*0 = 4 for decay, K*0 = 3 for reconstructed)
            histos[i]->Add(histos[3]);
            if(nfile==0){
                canvas[i] = new TCanvas(Form("c%i", i),Form("c%i", i), 0,0,900,900);
                canvas[i]->Divide(5,4);
                diffCanvas[i] = new TCanvas(Form("diffC%i", i),Form("diffC%i", i), 0,0,900,900);
                diffCanvas[i]->Divide(5,4);
            }
            //rebin
            //histos[i]->Sumw2();
            histos[i]->Rebin(4);

            //Fixing the errors to a percentage of the signal region:
            for(int ibin=1; ibin < histos[i]->GetNbinsX(); ibin++){
                histos[i]->SetBinError(ibin, histos[i]->GetBinContent((int)(0.892*(250.0/2.0)))*0.05);
                newHistos[i]->SetBinContent(ibin, histos[i]->GetBinContent(ibin));
                newHistos[i]->SetBinError(ibin, histos[i]->GetBinError(ibin));
            }
            
            pad = (TPad*)canvas[i]->cd(nfile+1);
            histos[i]->SetLineColor(1);
            histos[i]->SetLineWidth(1);
            histos[i]->GetXaxis()->SetRangeUser(0.7, 1.2);
            histos[i]->GetYaxis()->SetRangeUser(0, 1.5*histos[i]->GetBinContent(histos[i]->GetMaximumBin()));
            //histos[i]->SetStats(kFALSE);
            
            //histos[i]->Draw("HIST");

            printf("mean PT: %f\n", meanPT);

            TF1 *fit = new TF1(Form("fitPTbin%d00particle%d", nfile*2+1, i), FitFunRelBW, 0.68, 1.05, 5);
            //TF1 *fit = new TF1(Form("fitPTbin%d00particle%d", nfile*2+1, i), "gaus(0)", 0.86, 0.92);


            fit->SetParNames("BW Area", "Mass", "Width", "PT", "Temp");
            fit->SetParameters(TMath::Power(10.0, (float)(nfile)/1.7), 0.89, 0.1, 0.5, 0.130);
            //fit->SetParNames("BW Area", "Mass", "Width");
            //fit->SetParameters(100, 0.89, 0.0474);
            //fit->SetParLimits(0, -10, 1.5e9);
            Float_t max = histos[i]->GetXaxis()->GetBinCenter(histos[i]->GetMaximumBin());
            //if(max < 0.91 && max > 0.892){
            //    fit->SetParLimits(1, max-0.001, max+0.001);
            //}else{
                fit->SetParLimits(1, 0.82, 0.98);
            //}
            //fit->SetParLimits(2, 0.005, 0.15);
            fit->FixParameter(2, 0.042);
            fit->FixParameter(3, meanPT);
            //fit->SetParLimits(4, 0.05, 0.2);
            fit->FixParameter(4, 0.100001);
            fit->SetLineColor(2);

            printf("%s\n", fit->GetName());

            histos[i]->Fit(Form("fitPTbin%d00particle%d", nfile*2+1, i), "BRIM", "SAME");
            TVirtualFitter *fitter = TVirtualFitter::GetFitter();
           
            histos[i]->SetStats(1);
            histos[i]->Draw();
            gPad->Update();
            pad->Update();
            st = (TPaveStats*)histos[i]->FindObject("stats");
            st->SetX1NDC(0.524);
            st->SetY1NDC(0.680);
            st->SetX2NDC(0.884);
            st->SetY2NDC(0.876);
            //fit->Draw("SAME");
            //histos[i]->Draw();
            gPad->Update();
            pad->Update();
            printf("\n");
    
            diffHistos[i] = (TH1D*)histos[i]->Clone(Form("diffPTbin%d00particl%d", nfile*2+1, i));
            diffHistos[i]->Add(fit, -1);
            diffCanvas[i]->cd(nfile+1);
            diffHistos[i]->Draw("HIST E");
            diffHistos[i]->Write();

            //counting bins
            Float_t integral = histos[i]->Integral(1, 500)*500.0;
            //integrals << integral <<" \n";
            histos[i]->Write();
            fit->Write();
            //Do mass and width vs. pT plots just for K*0
            if(i==PARTICLE_NUM){
                mass = fit->GetParameter(1);
                massError = fit->GetParError(1);

                collWidth = fit->GetParameter(2);
                collWidthError = fit->GetParError(2);

                width = Gamma(mass, collWidth);

                kstar0mass->SetBinContent(nfile+1, mass);
                kstar0mass->SetBinError(nfile+1, massError);

                kstar0width->SetBinContent(nfile+1, width);
                Double_t widthError = TMath::Sqrt((GammaDerivative(mass)**2)*fitter->GetCovarianceMatrixElement(1,1) + fitter->GetCovarianceMatrixElement(2,2) + 2.0*GammaDerivative(mass)*fitter->GetCovarianceMatrixElement(1,2));
                kstar0width->SetBinError(nfile+1, widthError);

                kstar0collWidth->SetBinContent(nfile+1, collWidth);
                kstar0collWidth->SetBinError(nfile+1, collWidthError);

                kstar0decWidth->SetBinContent(nfile+1, width - collWidth);
                Double_t decWidthError = TMath::Sqrt((GammaDerivative(mass)**2)*fitter->GetCovarianceMatrixElement(1,1));
                kstar0decWidth->SetBinError(nfile+1, decWidthError);

                if(nfile==4){
                    TCanvas *singlecanvas = new TCanvas("singlecanvas", "singlecanvas", 0,0,600,600);
                    singlecanvas->cd();
                    printf("Got here! \n");
                    histos[i]->Draw("HIST E SAME");

                    fit->SetLineColor(8);
                    fit->SetLineStyle(1);
                    
                    fit->Draw("SAME");
                    if(fitter){
                        printf("sig11: %f, sig12: %f, sig21: %f, sig22: %f GammaDer(0.8): %f GammaDer(0.85): %f GammaDer(0.9): %f\n", TMath::Sqrt(fitter->GetCovarianceMatrixElement(1,1)), fitter->GetCovarianceMatrixElement(2,1), fitter->GetCovarianceMatrixElement(1,2), TMath::Sqrt(fitter->GetCovarianceMatrixElement(2,2)), GammaDerivative(0.8), GammaDerivative(0.85), GammaDerivative(0.9));
                    }
                }
            }
        }
        printf("************************************************************\n");
         
    }
        //integrals.close();
/*
    TH2D *gammaPlot = new TH2D("gammaPlot", "#Gamma_{tot}(M_{0}*);M_{0}*;#Gamma_{coll};#Gamma_{tot}", 100, 0.82, 0.9, 100, 0.0, 0.08);
    for(int im = 0; im<100; im++){
        for(int ig = 0; ig < 100; ig++){
            gammaPlot->SetBinContent(im+1, ig+1, Gamma(((0.9-0.82)/(100.0))*((double)(im)) + 0.82, ((0.08)/100.0)*((double)(ig))));
        }
    }

    TH1D *gammaMassDpnd = gammaPlot->ProjectionX("gammaMassDpnd");
*/
    TCanvas *masscanvas = new TCanvas("masscanvas", "masscanvas", 50,50, 600, 600);
    masscanvas->cd();
    kstar0mass->Draw();
    massline->Draw("SAME");
    masscanvas->Write();

    for(int i=PARTICLE_NUM; i<PARTICLE_NUM+1; i++){
        canvas[i]->Write();
    }
    kstar0mass->Write();
    kstar0collWidth->Write();
    kstar0decWidth->Write();
    kstar0width->Write();
//    gammaPlot->Write();
//    gammaMassDpnd->Write();
}
Ejemplo n.º 28
0
Stat_t AnalysisClass::doFit(Int_t RunNumber,Char_t *Variable, Char_t *SubDetName, Char_t *Layer,Char_t *label){
  TH1 *htoFit=0; 
  pLanGausS[0]=0; pLanGausS[1]=0; pLanGausS[2]=0; pLanGausS[3]=0;
  epLanGausS[0]=0; epLanGausS[1]=0; epLanGausS[2]=0; epLanGausS[3]=0;

  if (debug)   cout << d1->GetTitle() << " " << Variable << " " << SubDetName << endl;
  pPar[0]=0; pPar[1]=0;
  TIter it(d1->GetListOfKeys());
  TObject * o;
  while ( (o = it()))  
    {
      TObject * d =  d1->Get(o->GetName());
      if(d->IsA()->InheritsFrom("TDirectory") && strstr(d->GetName(),SubDetName)){
	if (debug) cout << "Found " << SubDetName << endl;
	TIter it2(((TDirectoryFile * )d)->GetListOfKeys());
	TObject *o2;
	while( ( o2 = it2()) ){
	  TObject *d2 = ((TDirectoryFile * )d)->Get(o2->GetName());
	  if(d2->IsA()->InheritsFrom("TDirectory") && strstr(d2->GetName(),Layer) ){
	    if (debug) cout << "Found Layer" << Layer << endl;
	    TIter it3(((TDirectoryFile * )d2)->GetListOfKeys());
	    TObject *o3;
	    while( ( o3 = it3()) ){
	      TObject *d3 = ((TDirectoryFile * )d2)->Get(o3->GetName());
	      if(strstr(d3->GetName(),Variable) && strstr(d3->GetName(),label)){
		htoFit = (TH1*) d3;
		if (debug) cout << "Found " << Variable << endl;
		
		if (htoFit->GetEntries()!=0) {
		  cout<<"Fitting "<< htoFit->GetTitle() <<endl;
		  // Setting fit range and start values
		  Double_t fr[2];
		  Double_t sv[4], pllo[4], plhi[4];
		  fr[0]=0.5*htoFit->GetMean();
		  fr[1]=3.0*htoFit->GetMean();
	      
		  // (EM) parameters setting good for signal only 
		  Int_t imax=htoFit->GetMaximumBin();
		  Double_t xmax=htoFit->GetBinCenter(imax);
		  Double_t ymax=htoFit->GetBinContent(imax);
		  Int_t i[2];
		  Int_t iArea[2];
	      
		  i[0]=htoFit->GetXaxis()->FindBin(fr[0]);
		  i[1]=htoFit->GetXaxis()->FindBin(fr[1]);
		  
		  iArea[0]=htoFit->GetXaxis()->FindBin(fr[0]);
		  iArea[1]=htoFit->GetXaxis()->FindBin(fr[1]);
		  Double_t AreaFWHM=htoFit->Integral(iArea[0],iArea[1],"width");
		  
		  sv[1]=xmax;
		  sv[2]=htoFit->Integral(i[0],i[1],"width");
		  sv[3]=AreaFWHM/(4*ymax);
		  sv[0]=sv[3];
		  
		  plhi[0]=25.0; plhi[1]=200.0; plhi[2]=1000000.0; plhi[3]=50.0;
		  pllo[0]=1.5 ; pllo[1]=10.0 ; pllo[2]=1.0      ; pllo[3]= 1.0;
		  
		  // create different landau+gaussians for different runs
		  Char_t FunName[100];
		  sprintf(FunName,"FitfcnLG_%s%d",htoFit->GetName(),fRun);  
		  TF1 *ffitold = (TF1*)gROOT->GetListOfFunctions()->FindObject(FunName);
		  if (ffitold) delete ffitold;
		  
		  langausFit = new TF1(FunName,langaufun,fr[0],fr[1],4);
		  langausFit->SetParameters(sv);
		  langausFit->SetParNames("Width","MP","Area","GSigma");
		  
		  for (Int_t i=0; i<4; i++) {
		    langausFit->SetParLimits(i,pllo[i],plhi[i]);
		  }  
		  
		  htoFit->Fit(langausFit,"R0");  // "R" fit in a range,"0" quiet fit
		  
		  langausFit->SetRange(fr[0],fr[1]);
		  pLanGausS=langausFit->GetParameters();
		  epLanGausS=langausFit->GetParErrors();
		  
		  chi2GausS =langausFit->GetChisquare();  // obtain chi^2
		  nDofGausS = langausFit->GetNDF();           // obtain ndf
		  
		  Double_t sPeak, sFWHM;
		  langaupro(pLanGausS,sPeak,sFWHM);
		  pLanConv[0]=sPeak;
		  pLanConv[1]=sFWHM;
		  cout << "langaupro:  max  " << sPeak << endl;
		  cout << "langaupro:  FWHM " << sFWHM << endl;
		  
		  TCanvas *cAll = new TCanvas("Fit",htoFit->GetTitle(),1);
		  Char_t fitFileName[60];
		  sprintf(fitFileName,"Fits/Run_%d/%s/Fit_%s.png",RunNumber,SubDetName,htoFit->GetTitle());
		  htoFit->Draw("pe");
		  htoFit->SetStats(100);
		  langausFit->Draw("lsame");
		  gStyle->SetOptFit(1111111);
		  
		  cAll->Print(fitFileName,"png");
		}
		else {  
		  pLanGausS[0]=-10; pLanGausS[1]=-10; pLanGausS[2]=-10; pLanGausS[3]=-10;
		  epLanGausS[0]=-10; epLanGausS[1]=-10; epLanGausS[2]=-10; epLanGausS[3]=-10;
		  pLanConv[0]=-10;   pLanConv[1]=-10;   chi2GausS=-10;  nDofGausS=-10;    
		}
	      }
	    }
	  }
	}
      }
    }
	
  return htoFit->GetEntries();
  
}
Ejemplo n.º 29
0
void massfitvn_Jpsi()
{
    double fit_range_low = 2.6;
    double fit_range_high = 3.5;
    double JPsi_mass = 3.097;
    int npt = 7;
    TFile* file1 = TFile::Open("HM185_JpsivnHist_etagap1p5_v30_eff_extdeta.root");
    
    TFile ofile("v2vspt_fromfit_jpsi_HM185_250_deta1p5_doubleCB_v30_eff_exp_extdeta.root","RECREATE");
    
    //v12
    double alpha_fit[14] = {4.30986,3.50841,3.03436,2.73741,2.37934,2.10685,2.03615};
    double n_fit[14] = {1.88853,1.9839,2.03198,2.07295,2.11001,2.15234,2.10154};
    
    TF1* fmasssig[9];
    TF1* fmassbkg[9];
    TF1* fmasstotal[9];
    TF1* fvn[9];
    
    double pt[13];
    double KET_ncq[13];
    double v2[13];
    double v2e[13];
    double v2_bkg[13];
    double v2_ncq[13];
    double v2e_ncq[13];
    double ptbin[14] = {0.2, 1.8, 3.0, 4.5, 6.0, 8.0, 10, 20};
    double a[13];
    double b[13];
    double sigfrac[13];
    
    TCanvas* c[10];
    for(int i=0;i<npt;i++)
    {
        c[i] = new TCanvas(Form("c_%d",i),Form("c_%d",i),800,400);
        c[i]->Divide(2,1);
    }
    
    for(int i=0;i<npt;i++)
    {
        c[i]->cd(1)->SetTopMargin(0.06);
        c[i]->cd(1)->SetLeftMargin(0.18);
        c[i]->cd(1)->SetRightMargin(0.043);
        c[i]->cd(1)->SetBottomMargin(0.145);
        c[i]->cd(2)->SetTopMargin(0.06);
        c[i]->cd(2)->SetLeftMargin(0.18);
        c[i]->cd(2)->SetRightMargin(0.043);
        c[i]->cd(2)->SetBottomMargin(0.145);

    }
    
    TCanvas* c2 = new TCanvas("c2","c2",100,100);
    
    TLatex* tex = new TLatex;
    tex->SetNDC();
    tex->SetTextFont(42);
    tex->SetTextSize(0.045);
    tex->SetLineWidth(2);
 
    TLatex* texCMS = new TLatex;
    texCMS->SetNDC();
    texCMS->SetTextFont(42);
    texCMS->SetTextSize(0.05);
    texCMS->SetTextAlign(12);
    
    TH1D* hist = new TH1D("hist","",10,2.6,3.5);
    hist->SetLineWidth(0);
    //hist->GetYaxis()->SetRangeUser(0,0.3);
    hist->GetXaxis()->SetTitle("#it{m}_{#mu#mu} (GeV)");
    hist->GetYaxis()->SetTitle("v_{2}^{S+B}");
    hist->GetXaxis()->CenterTitle();
    hist->GetYaxis()->CenterTitle();
    hist->GetXaxis()->SetTitleOffset(1.3);
    hist->GetYaxis()->SetTitleOffset(2);
    hist->GetXaxis()->SetLabelOffset(0.007);
    hist->GetYaxis()->SetLabelOffset(0.007);
    hist->GetXaxis()->SetTitleSize(0.045);
    hist->GetYaxis()->SetTitleSize(0.045);
    hist->GetXaxis()->SetTitleFont(42);
    hist->GetYaxis()->SetTitleFont(42);
    hist->GetXaxis()->SetLabelFont(42);
    hist->GetYaxis()->SetLabelFont(42);
    hist->GetXaxis()->SetLabelSize(0.04);
    hist->GetYaxis()->SetLabelSize(0.04);
    hist->SetMinimum(0.01);
    hist->SetMaximum(0.33);
    
    c2->cd();
    hist->Draw();
    
    for(int i=0;i<npt;i++)
    {
        TH1D* h_data = (TH1D*)file1->Get(Form("massjpsi_pt%d",i));
        h_data->SetMinimum(0);
        h_data->SetMarkerSize(0.8);
        h_data->SetMarkerStyle(20);
        h_data->SetLineWidth(1);
        h_data->SetOption("e");
        
        h_data->Rebin(2);

        h_data->GetXaxis()->SetRangeUser(2.6,3.5);
        h_data->GetXaxis()->SetTitle("#it{m}_{#mu#mu} (GeV)");
        h_data->GetYaxis()->SetTitle("Entries / 10 MeV");
        h_data->GetXaxis()->CenterTitle();
        h_data->GetYaxis()->CenterTitle();
        h_data->GetXaxis()->SetTitleOffset(1.3);
        h_data->GetYaxis()->SetTitleOffset(2);
        h_data->GetXaxis()->SetLabelOffset(0.007);
        h_data->GetYaxis()->SetLabelOffset(0.007);
        h_data->GetXaxis()->SetTitleSize(0.045);
        h_data->GetYaxis()->SetTitleSize(0.045);
        h_data->GetXaxis()->SetTitleFont(42);
        h_data->GetYaxis()->SetTitleFont(42);
        h_data->GetXaxis()->SetLabelFont(42);
        h_data->GetYaxis()->SetLabelFont(42);
        h_data->GetXaxis()->SetLabelSize(0.04);
        h_data->GetYaxis()->SetLabelSize(0.04);
        
        h_data->GetXaxis()->SetNoExponent(true);
        ((TGaxis*)h_data->GetXaxis())->SetMaxDigits(7);
        
        h_data->SetMaximum(h_data->GetMaximum()*1.5);
        
        TH1D* h_pt = (TH1D*)file1->Get(Form("Ptjpsi_eff_pt%d",i));
        TH1D* h_KET = (TH1D*)file1->Get(Form("KETjpsi_eff_pt%d",i));
        pt[i] = h_pt->GetMean();
        KET_ncq[i] = h_KET->GetMean()/2.0;

        c[i]->cd(1);
        
        /*p definitions
         [0] CB1 yield;
         [1] Common mean of CB and Gaus;
         [2] CB1 sigma;
         [3] CB n;
         [4] CB alpha;
         [5] CB2 yield;
         [6] CB2 sigma;
         [7-10] poly 3;
         [11] v2 signal;
         [12-13] v2 bkg;
         */
        TF1* f = new TF1(Form("f_%d",i), crystalball_function_total, fit_range_low, fit_range_high, 11);
        f->SetLineColor(2);
        f->SetLineWidth(1);
        f->SetParNames("CB1_Yield","common_mean","CB1_sigma","CB_N","CB_Alpha","CB2_Yield","CB2_Sigma","Pol0","Pol1","Pol2","Pol3");

        //first fit data mass signal + bkg
        
        f->SetParameter(0,10000.);
        f->SetParameter(1,JPsi_mass);
        f->SetParameter(2,0.03);
        f->SetParameter(3,1.0);
        f->SetParameter(4,1.0);
        f->SetParameter(5,10000);
        f->SetParameter(6,0.03);
        
        f->SetParLimits(2,0.01,0.1);
        f->SetParLimits(6,0.01,0.1);
        
        //fix alpha & n from MC
        f->FixParameter(4,alpha_fit[i]);
        f->FixParameter(3,n_fit[i]);
        
        f->FixParameter(1,JPsi_mass); //for first few attempt fix mean of gaussian to get reasonable estimation of other pars; later open it up
        h_data->Fit(Form("f_%d",i),"q","",fit_range_low,fit_range_high);
        h_data->Fit(Form("f_%d",i),"q","",fit_range_low,fit_range_high);
        f->ReleaseParameter(1); //now let gaussian mean float
        h_data->Fit(Form("f_%d",i),"L q","",fit_range_low,fit_range_high);
        h_data->Fit(Form("f_%d",i),"L q","",fit_range_low,fit_range_high);
        h_data->Fit(Form("f_%d",i),"L m","",fit_range_low,fit_range_high);
        
        
        //draw D0 signal separately
        TF1* f1 = new TF1(Form("f_sig_%d",i), crystalball_function_signal, fit_range_low, fit_range_high, 7);
        f1->SetLineColor(kOrange-3);
        f1->SetLineWidth(1);
        f1->SetLineStyle(2);
        f1->SetFillColorAlpha(kOrange-3,0.3);
        f1->SetFillStyle(1001);
        f1->FixParameter(0,f->GetParameter(0));
        f1->FixParameter(1,f->GetParameter(1));
        f1->FixParameter(2,f->GetParameter(2));
        f1->FixParameter(3,f->GetParameter(3));
        f1->FixParameter(4,f->GetParameter(4));
        f1->FixParameter(5,f->GetParameter(5));
        f1->FixParameter(6,f->GetParameter(6));
        
        fmasssig[i] = (TF1*)f1->Clone();
        fmasssig[i]->SetName(Form("masssigfcn_pt%d",i));
        fmasssig[i]->Write();
        
        f1->Draw("LSAME");
        
        //draw poly bkg separately
        TF1* f3 = new TF1(Form("f_bkg_%d",i),"[7] + [8]*x + [9]*x*x + [10]*x*x*x", fit_range_low, fit_range_high);
        f3->SetLineColor(4);
        f3->SetLineWidth(1);
        f3->SetLineStyle(2);
        f3->FixParameter(7,f->GetParameter(7));
        f3->FixParameter(8,f->GetParameter(8));
        f3->FixParameter(9,f->GetParameter(9));
        f3->FixParameter(10,f->GetParameter(10));
        
        fmassbkg[i] = (TF1*)f3->Clone();
        fmassbkg[i]->SetName(Form("massbkgfcn_pt%d",i));
        fmassbkg[i]->Write();
        
        f3->Draw("LSAME");
        
        tex->DrawLatex(0.22,0.86,"185 #leq N_{trk}^{offline} < 250");
        tex->DrawLatex(0.22,0.80,Form("%.1f < p_{T} < %.1f GeV",ptbin[i],ptbin[i+1]));
        tex->DrawLatex(0.22,0.74,"-2.86 < y_{cm} < -1.86 or 0.94 < y_{cm} < 1.94");
        
        texCMS->DrawLatex(.18,.97,"#font[61]{CMS} #it{Preliminary}");
        //texCMS->DrawLatex(.18,.97,"#font[61]{CMS}");
        texCMS->DrawLatex(0.73,0.97, "#scale[0.8]{pPb 8.16 TeV}");
        
        TLegend* leg = new TLegend(0.21,0.4,0.5,0.65,NULL,"brNDC");
        leg->SetBorderSize(0);
        leg->SetTextSize(0.045);
        leg->SetTextFont(42);
        leg->SetFillStyle(0);
        leg->AddEntry(h_data,"data","p");
        leg->AddEntry(f,"Fit","L");
        leg->AddEntry(f1,"J/#psi Signal","f");
        leg->AddEntry(f3,"Combinatorial","l");
        leg->Draw("SAME");
        
        sigfrac[i] = f1->Integral(2.94,3.24)/f->Integral(2.94,3.24);
        
        //c->Print(Form("plots/massfit_pt%d.pdf",i));
        
        //fit vn
        //[9] is vn_sig
        //[10-11] is vn bkg, const + linear vn(pT)
        TGraphErrors* vn_data = (TGraphErrors*)file1->Get(Form("v2_mass_pt%d",i));
        
        c[i]->cd(2);
        
        hist->Draw();
        
        TF1* fmass_combinemassvnfit = new TF1(Form("fmass_combinemassvnfit_%d",i),crystalball_function_total, fit_range_low, fit_range_high, 11);
        
        TF1* fvn_combinemassvnfit = new TF1(Form("fvn_combinemassvnfit_%d",i), crystalball_function_v2, fit_range_low, fit_range_high, 15);
        
        fmass_combinemassvnfit->SetLineColor(2);
        fmass_combinemassvnfit->SetLineWidth(1);
        
        fvn_combinemassvnfit->SetLineColor(2);
        fvn_combinemassvnfit->SetLineWidth(1);

        ROOT::Math::WrappedMultiTF1 wfmass_combinemassvnfit(*fmass_combinemassvnfit,1);
        ROOT::Math::WrappedMultiTF1 wfvn_combinemassvnfit(*fvn_combinemassvnfit,1);
        
        ROOT::Fit::DataOptions opt;
        ROOT::Fit::DataRange range_massfit;

        range_massfit.SetRange(fit_range_low,fit_range_high);
        ROOT::Fit::BinData datamass(opt,range_massfit);
        ROOT::Fit::FillData(datamass, h_data);
        
        ROOT::Fit::DataRange range_vnfit;
        range_vnfit.SetRange(fit_range_low,fit_range_high);
        ROOT::Fit::BinData datavn(opt,range_vnfit);
        ROOT::Fit::FillData(datavn, vn_data);
        
        ROOT::Fit::Chi2Function chi2_B(datamass, wfmass_combinemassvnfit);
        ROOT::Fit::Chi2Function chi2_SB(datavn, wfvn_combinemassvnfit);
        
        GlobalChi2_poly3bkg_floatwidth globalChi2(chi2_B, chi2_SB);

        ROOT::Fit::Fitter fitter;
        
        const int Npar = 15;
        double par0[Npar];
        for( int ipar = 0; ipar < f->GetNpar(); ipar++ ) par0[ipar] = f->GetParameter(ipar);
        par0[11] = 0.01;
        par0[12] = 0.10;
        par0[13] = 0.05;
        par0[14] = 0.01;

        
        fitter.Config().SetParamsSettings(Npar,par0);
        // fix parameter
        fitter.Config().ParSettings(0).Fix();
        fitter.Config().ParSettings(1).Fix();
        fitter.Config().ParSettings(2).Fix();
        fitter.Config().ParSettings(3).Fix();
        fitter.Config().ParSettings(4).Fix();
        fitter.Config().ParSettings(5).Fix();
        fitter.Config().ParSettings(6).Fix();
        fitter.Config().ParSettings(7).Fix();
        fitter.Config().ParSettings(8).Fix();
        fitter.Config().ParSettings(9).Fix();
        fitter.Config().ParSettings(10).Fix();
        
        fitter.Config().MinimizerOptions().SetPrintLevel(0);
        fitter.Config().SetMinimizer("Minuit2","Migrad");

        fitter.FitFCN(Npar,globalChi2,0,datamass.Size()+datavn.Size(),true);
        ROOT::Fit::FitResult result = fitter.Result();
        result.Print(std::cout);
        
        fmass_combinemassvnfit->SetFitResult( result, iparmassfit_poly3bkg_floatwidth);
        fmass_combinemassvnfit->SetRange(range_massfit().first, range_massfit().second);
        fmass_combinemassvnfit->SetLineColor(kRed);
        h_data->GetListOfFunctions()->Add(fmass_combinemassvnfit);
        //c->cd();
        //h_data->Draw();
        
        fvn_combinemassvnfit->SetFitResult( result, iparvnfit_poly3bkg_floatwidth);
        fvn_combinemassvnfit->SetRange(range_vnfit().first, range_vnfit().second);
        fvn_combinemassvnfit->SetLineColor(2);
        //fvn_combinemassvnfit->SetLineStyle(2);
        vn_data->GetListOfFunctions()->Add(fvn_combinemassvnfit);
        vn_data->SetTitle("");
        vn_data->SetMarkerSize(0.8);
        vn_data->SetLineWidth(1);
        //c1->cd();
        vn_data->Draw("PESAME");
        
        fvn[i] = (TF1*)fvn_combinemassvnfit->Clone();
        fvn[i]->SetName(Form("vnfit_pt%d",i));
        fvn[i]->Write();
        
        fmasstotal[i] = (TF1*)fmass_combinemassvnfit->Clone();
        fmasstotal[i]->SetName(Form("masstotalfcn_pt%d",i));
        fmasstotal[i]->Write();
        
        tex->DrawLatex(0.22,0.86,"185 #leq N_{trk}^{offline} < 250");
        tex->DrawLatex(0.22,0.80,Form("%.1f < p_{T} < %.1f GeV",ptbin[i],ptbin[i+1]));
        //tex->DrawLatex(0.22,0.74,"1.4 < |y_{cm}+0.46| < 2.4");
        tex->DrawLatex(0.22,0.74,"-2.86 < y_{cm} < -1.86 or 0.94 < y_{cm} < 1.94");
        //tex->DrawLatex(0.22,0.68,"|#Delta#eta| > 2");

        
        //texCMS->DrawLatex(.18,.97,"#font[61]{CMS}");
        texCMS->DrawLatex(.18,.97,"#font[61]{CMS} #it{Preliminary}");
        texCMS->DrawLatex(0.73,0.97, "#scale[0.8]{pPb 8.16 TeV}");
        
        v2[i] = fvn_combinemassvnfit->GetParameter(11);
        v2e[i] = fvn_combinemassvnfit->GetParError(11);
        v2_bkg[i] = fvn_combinemassvnfit->GetParameter(12) + fvn_combinemassvnfit->GetParameter(13) * JPsi_mass;
        v2_ncq[i] = v2[i]/2.0;
        v2e_ncq[i] = v2e[i]/2.0;
        a[i] = fvn_combinemassvnfit->GetParameter(12);
        b[i] = fvn_combinemassvnfit->GetParameter(13);
        
        TF1* fvnbkg = new TF1(Form("fvnbkg_%d",1),"( [0] + [1] * x)", fit_range_low, fit_range_high);
        fvnbkg->FixParameter(0,fvn_combinemassvnfit->GetParameter(12));
        fvnbkg->FixParameter(1,fvn_combinemassvnfit->GetParameter(13));
        
        fvnbkg->SetName(Form("fvnbkg_fcn_pt%d",i));
        fvnbkg->Write();
        
        fvnbkg->SetLineStyle(7);
        //fvnbkg->Draw("LSAME");
        
        TF1* fvnsig = new TF1(Form("fvnsig_%d",i),function_v2_sig,fit_range_low,fit_range_high,12);
        for(int k=0;k<12;k++)
        {
            fvnsig->FixParameter(k,fvn_combinemassvnfit->GetParameter(k));
            
        }
        
        fvnsig->SetLineColor(kOrange-3);
        fvnsig->SetLineWidth(1);
        fvnsig->SetLineStyle(2);
        fvnsig->SetFillColorAlpha(kOrange-3,0.3);
        fvnsig->SetFillStyle(1001);
        
        //fvnsig->Draw("LSAME");
        
        TLegend* leg1 = new TLegend(0.72,0.525,0.91,0.65,NULL,"brNDC");
        leg1->SetBorderSize(0);
        leg1->SetTextSize(0.045);
        leg1->SetTextFont(42);
        leg1->SetFillStyle(0);
        leg1->AddEntry(h_data,"data","p");
        leg1->AddEntry(fvn_combinemassvnfit,"Fit","l");
        //leg1->AddEntry(fvnsig,"#alpha(#it{m}_{#mu#mu})v_{2}^{S}","f");
        leg1->Draw("SAME");

        double xmass[200];
        double pullmass[200];
        
        float Chi2=0;
        int ndf = (fit_range_high - fit_range_low)/0.01 - 8;
        
        for(int k=0;k<h_data->GetNbinsX();k++)
        {
            xmass[k] = h_data->GetBinCenter(k);
            pullmass[k] = (h_data->GetBinContent(k) - fmass_combinemassvnfit->Eval(xmass[k]))/h_data->GetBinError(k);
            if(fabs(pullmass[k])<5)
            {
                //cout<<pullmass[k]<<endl;
                Chi2 += pullmass[k]*pullmass[k];
            }
        }

        c[i]->cd(1);
        tex->DrawLatex(0.22,0.67,Form("#chi^{2}/ndf = %.0f/%d",Chi2,ndf));
        
        double xv2[200];
        double pullv2[200];
        double v2y[200];
        
        float Chi2v2=0;
        int ndfv2 = 8 - 4; //Nbin - Npar
        
        for(int k=0;k<vn_data->GetN()-1;k++)
        {
            vn_data->GetPoint(k,xv2[k],v2y[k]);
            //xv2[k] = vn_dara->GetBinCenter(k);
            pullv2[k] = (v2y[k] - fvn_combinemassvnfit->Eval(xv2[k]))/vn_data->GetErrorY(k);
            cout<<k<<": "<<pullv2[k]<<endl;
            if(fabs(pullv2[k])<1000)
            {
                //cout<<pullmass[k]<<endl;
                Chi2v2 += pullv2[k]*pullv2[k];
            }
            cout<<"fcn: "<<fvn_combinemassvnfit->Eval(xv2[k])<<endl;
            cout<<"data: "<<v2y[k]<<endl;
        }

        c[i]->cd(2);
        tex->DrawLatex(0.22,0.67,Form("#chi^{2}/ndf = %.1f/%d",Chi2v2,ndfv2));
        
    }
    
    for(int i=0;i<npt;i++)
    {
        c[i]->Print(Form("plots/v30/eff/exp/JPsi_mass_vnfit_combine_pt%d.pdf",i));
        c[i]->Print(Form("plots/v30/eff/exp/JPsi_mass_vnfit_combine_pt%d.gif",i));
    }
    
    TGraphErrors* v2plot = new TGraphErrors(npt,pt,v2,0,v2e);
    TGraphErrors* v2ncqplot = new TGraphErrors(npt,KET_ncq,v2_ncq,0,v2e_ncq);
    TGraphErrors* v2bkgplot = new TGraphErrors(npt,pt,v2_bkg,0,0);
    
    v2plot->SetName("v2vspt");
    v2ncqplot->SetName("v2vsKET_ncq");
    v2bkgplot->SetName("v2bkgvspt");
    
    v2plot->Write();
    v2ncqplot->Write();
    v2bkgplot->Write();
}
Ejemplo n.º 30
0
//Noise section
Stat_t AnalysisClass::doNoiseFit(Int_t RunNumber, Char_t *Variable, Char_t *SubDetName, Char_t *Layer, Char_t *label){
  TH1 *hNtoFit=0;
  if (debug) cout << d1->GetTitle() << " " << Variable << " " << SubDetName << endl;
  pPar[0]=0; pPar[1]=0;
  TIter it(d1->GetListOfKeys());
  TObject * o;
  while ( (o = it()))  
    {
      TObject * d =  d1->Get(o->GetName());
      if(d->IsA()->InheritsFrom("TDirectory") && strstr(d->GetName(),SubDetName)){
	if (debug) cout << "Found " << SubDetName << endl;
	TIter it2(((TDirectoryFile * )d)->GetListOfKeys());
	TObject *o2;
	while( ( o2 = it2()) ){
	  TObject *d2 = ((TDirectoryFile * )d)->Get(o2->GetName());
	  if(d2->IsA()->InheritsFrom("TDirectory") && strstr(d2->GetName(),Layer) ){
	    if (debug) cout << "Found Layer" << Layer << endl;
	    TIter it3(((TDirectoryFile * )d2)->GetListOfKeys());
	    TObject *o3;
	    while( ( o3 = it3()) ){
	      TObject *d3 = ((TDirectoryFile * )d2)->Get(o3->GetName());
	      if(strstr(d3->GetName(),Variable) && strstr(d3->GetName(),label)){
		hNtoFit = (TH1*) d3;
		if (debug) cout << "Found " << Variable << endl;
		if (hNtoFit->GetEntries()!=0) {
		  cout<<"Fitting "<< hNtoFit->GetTitle() <<endl;
		  // Setting fit range and start values
		  Double_t fr[2];
		  Double_t sv[3], pllo[3], plhi[3];
		  fr[0]=hNtoFit->GetMean()-5*hNtoFit->GetRMS();
		  fr[1]=hNtoFit->GetMean()+5*hNtoFit->GetRMS();
		  
		  Int_t imax=hNtoFit->GetMaximumBin();
		  Double_t xmax=hNtoFit->GetBinCenter(imax);
		  Double_t ymax=hNtoFit->GetBinContent(imax);
		  Int_t i[2];
		  Int_t iArea[2];
		  
		  i[0]=hNtoFit->GetXaxis()->FindBin(fr[0]);
		  i[1]=hNtoFit->GetXaxis()->FindBin(fr[1]);
		  
		  iArea[0]=hNtoFit->GetXaxis()->FindBin(fr[0]);
		  iArea[1]=hNtoFit->GetXaxis()->FindBin(fr[1]);
		  Double_t AreaFWHM=hNtoFit->Integral(iArea[0],iArea[1],"width");
		  
		  sv[2]=AreaFWHM/(4*ymax);
		  sv[1]=xmax;
		  sv[0]=hNtoFit->Integral(i[0],i[1],"width");
		  
		  plhi[0]=1000000.0; plhi[1]=10.0; plhi[2]=10.;
		  pllo[0]=1.5 ; pllo[1]=0.1; pllo[2]=0.3;
		  Char_t FunName[100];
		  sprintf(FunName,"FitfcnLG_%s%d",hNtoFit->GetName(),fRun);
		  TF1 *ffitold = (TF1*)gROOT->GetListOfFunctions()->FindObject(FunName);
		  if (ffitold) delete ffitold;
		  
		  gausFit = new TF1(FunName,Gauss,fr[0],fr[1],3);
		  gausFit->SetParameters(sv);
		  gausFit->SetParNames("Constant","GaussPeak","Sigma");
		  
		  for (Int_t i=0; i<3; i++) {
		    gausFit->SetParLimits(i,pllo[i],plhi[i]);
		  }
		  hNtoFit->Fit(gausFit,"R0");
		  
		  gausFit->SetRange(fr[0],fr[1]);
		  pGausS=gausFit->GetParameters();
		  epGausS=gausFit->GetParErrors();
		  
		  chi2GausS =langausFit->GetChisquare(); // obtain chi^2
		  nDofGausS = langausFit->GetNDF();// obtain ndf
		  
		  TCanvas *cAllN = new TCanvas("NoiseFit",hNtoFit->GetTitle(),1);
		  Char_t fitFileName[60];
		  sprintf(fitFileName,"Fits/Run_%d/%s/Fit_%s.png",RunNumber,SubDetName,hNtoFit->GetTitle());
		  hNtoFit->Draw("pe");
		  gStyle->SetOptFit(1111111);
		  gausFit->Draw("lsame");
   
		  cAllN->Print(fitFileName,"png");
		}else {
		  pGausS[0]=-10; pGausS[1]=-10; pGausS[2]=-10;
		  epGausS[0]=-10; epGausS[1]=-10; epGausS[2]=-10;
		}
	      }
	    }
	  }
	}
      }
    }
 
  return hNtoFit->GetEntries();
}