void write_ntuple_to_file(){

    TFile ofile("conductivity_experiment.root","RECREATE");

    // Initialise the TNtuple
    TNtuple cond_data("cond_data",
                      "Example N-Tuple",
                      "Potential:Current:Temperature:Pressure");

    // Fill it randomly to fake the acquired data
    TRandom3 rndm;
    float pot,cur,temp,pres;
    for (int i=0;i<10000;++i){
        pot=rndm.Uniform(0.,10.);      // get voltage
        temp=rndm.Uniform(250.,350.);  // get temperature
        pres=rndm.Uniform(0.5,1.5);    // get pressure
        cur=pot/(10.+0.05*(temp-300.)-0.2*(pres-1.)); // current
// add some random smearing (measurement errors)
        pot*=rndm.Gaus(1.,0.01); // 1% error on voltage
        temp+=rndm.Gaus(0.,0.3); // 0.3 abs. error on temp.
        pres*=rndm.Gaus(1.,0.02);// 1% error on pressure
        cur*=rndm.Gaus(1.,0.01); // 1% error on current
// write to ntuple
        cond_data.Fill(pot,cur,temp,pres);
        }

    // Save the ntuple and close the file
    cond_data.Write();
    ofile.Close();
}
Esempio n. 2
0
void macro6(){

    TH1F* sig_h=new TH1F("sig_h","Signal Histo",50,0,10);
    TH1F* gaus_h1=new TH1F("gaus_h1","Gauss Histo 1",30,0,10);
    TH1F* gaus_h2=new TH1F("gaus_h2","Gauss Histo 2",30,0,10);
    TH1F* bkg_h=new TH1F("exp_h","Exponential Histo",50,0,10);

    // simulate the measurements
    TRandom3 rndgen;
    for (int imeas=0;imeas<4000;imeas++){
        bkg_h->Fill(rndgen.Exp(4));
        if (imeas%4==0) gaus_h1->Fill(rndgen.Gaus(5,2));
        if (imeas%4==0) gaus_h2->Fill(rndgen.Gaus(5,2));
        if (imeas%10==0)sig_h->Fill(rndgen.Gaus(5,.5));}

    // Format Histograms
    TH1F* histos[4]={sig_h,bkg_h,gaus_h1,gaus_h2};
    for (int i=0;i<4;++i){
        histos[i]->Sumw2(); // *Very* Important
        format_h(histos[i],i+1);
        }

    // Sum
    TH1F* sum_h= new TH1F(*bkg_h);
    sum_h->Add(sig_h,1.);
    sum_h->SetTitle("Exponential + Gaussian");
    format_h(sum_h,kBlue);

    TCanvas* c_sum= new TCanvas();
    sum_h->Draw("hist");
    bkg_h->Draw("SameHist");
    sig_h->Draw("SameHist");

    // Divide
    TH1F* dividend=new TH1F(*gaus_h1);
    dividend->Divide(gaus_h2);

    // Graphical Maquillage
    dividend->SetTitle(";X axis;Gaus Histo 1 / Gaus Histo 2");
    format_h(dividend,kOrange);
    gaus_h1->SetTitle(";;Gaus Histo 1 and Gaus Histo 2");
    gStyle->SetOptStat(0);

    TCanvas* c_divide= new TCanvas();
    c_divide->Divide(1,2,0,0);
    c_divide->cd(1);
    c_divide->GetPad(1)->SetRightMargin(.01);
    gaus_h1->DrawNormalized("Hist");
    gaus_h2->DrawNormalized("HistSame");

    c_divide->cd(2);
    dividend->GetYaxis()->SetRangeUser(0,2.49);
    c_divide->GetPad(2)->SetGridy();
    c_divide->GetPad(2)->SetRightMargin(.01);
    dividend->Draw();
}
Esempio n. 3
0
int main(int argc, char *argv[])
{
    std::auto_ptr<TRint> application(new TRint("histInMemory", 0, 0));

    TH1F *hist1 = new TH1F("hist1", "hist1", 50, 0, 10);
    TH1F *hist2 = new TH1F("hist2", "hist2", 50, 0, 10);
    TH1F *hist3 = new TH1F("hist3", "hist3", 50, 0, 10);
    TH1F *hist4 = new TH1F("hist4", "hist4", 50, 0, 10);
    TH1F *hist5 = new TH1F("hist5", "hist5", 50, 0, 10);

    {
        TRandom3 *random = new TRandom3(1);
        for(int i = 0; 10000 > i; ++i)
        {
            hist1->Fill(random->Gaus(5, 1));
            hist2->Fill(random->Poisson(5));
            hist3->Fill(random->Uniform(0, 10));
            hist4->Fill(random->Gaus(4, 1));
            hist5->Fill(random->Poisson(3));
        }
        delete random;
    }

    TFile *output = new TFile("output.root", "RECREATE");
    TDirectory *group1 = output->mkdir("group1");
    group1->cd();

    hist1->Write();
    hist2->Write();

    TDirectory *group2 = output->mkdir("group2");
    group2->cd();

    hist3->Write();
    hist4->Write();
    hist5->Write();

    delete output;

    application->Run(true);

    delete hist1;
    delete hist2;
    delete hist3;
    delete hist4;
    delete hist5;

    return 0;
}
Esempio n. 4
0
//____________________________________________________________________
void fitCircle(Int_t n=10000) {
   //generates n points around a circle and fit them
   TCanvas *c1 = new TCanvas("c1","c1",600,600);
   c1->SetGrid();
   gr = new TGraph(n);
   if (n> 999) gr->SetMarkerStyle(1);
   else        gr->SetMarkerStyle(3);
   TRandom3 r;
   Double_t x,y;
   for (Int_t i=0;i<n;i++) {
      r.Circle(x,y,r.Gaus(4,0.3));
      gr->SetPoint(i,x,y);
   }
   c1->DrawFrame(-5,-5,5,5);
   gr->Draw("p");

   //Fit a circle to the graph points
   TVirtualFitter::SetDefaultFitter("Minuit");  //default is Minuit
   TVirtualFitter *fitter = TVirtualFitter::Fitter(0, 3);
   fitter->SetFCN(myfcn);

   fitter->SetParameter(0, "x0",   0, 0.1, 0,0);
   fitter->SetParameter(1, "y0",   0, 0.1, 0,0);
   fitter->SetParameter(2, "R",    1, 0.1, 0,0);

   Double_t arglist[1] = {0};
   fitter->ExecuteCommand("MIGRAD", arglist, 0);

   //Draw the circle on top of the points
   TArc *arc = new TArc(fitter->GetParameter(0),
      fitter->GetParameter(1),fitter->GetParameter(2));
   arc->SetLineColor(kRed);
   arc->SetLineWidth(4);
   arc->Draw();
}
Esempio n. 5
0
void smearEmEnergy( const EnergyScaleCorrection_class& egcor, TLorentzVector& p, const ZGTree& myTree, float r9 ) {

    float smearSigma =  egcor.getSmearingSigma(myTree.run, fabs(p.Eta())<1.479, r9, p.Eta(), p.Pt(), 0., 0.);
    float cor = myRandom_.Gaus( 1., smearSigma );
    p.SetPtEtaPhiM( p.Pt()*cor, p.Eta(), p.Phi(), p.M() );

}
void plot_distortion(){
    
    TRandom3* rand = new TRandom3();

//    TF1 *func = new TF1("func","TMath::Abs([0]+[1]*x)",0,12);
//
//    rand->SetSeed(0);
//    Double_t slope=0.2*rand->Gaus(0,1);
//    Double_t anchor_point=3.5;
//    //want offset to be set by requiring func at anchor point to be 1
//    Double_t offset=(1-slope*anchor_point);
//    func->SetParameter(0,offset);
//    func->SetParameter(1,slope);
    
    //FN distortion
    TF1 *func = new TF1("func","[0]/(0.2*pow(x,0.1))+[1]",0,12);
    rand->SetSeed(0);
    Double_t scaling =0.2*rand->Gaus(0,1);
    func->SetParameter(0,scaling);
    func->SetParameter(1,0);
    //set offset so that func(FinalEnergy)=1;
    func->SetParameter(1,1-1*func->Eval(12));
    
    func->Draw();
    
    
   }
Esempio n. 7
0
void gtime2(Int_t nsteps = 200, Int_t np=5000) {
   if (np > 5000) np = 5000;
   Int_t color[5000];
   Double_t cosphi[5000], sinphi[5000], speed[5000];
   TRandom3 r;
   Double_t xmin = 0, xmax = 10, ymin = -10, ymax = 10;
   TGraphTime *g = new TGraphTime(nsteps,xmin,ymin,xmax,ymax);
   g->SetTitle("TGraphTime demo 2;X;Y");
   Int_t i,s;
   Double_t phi,fact = xmax/Double_t(nsteps);
   for (i=0;i<np;i++) { //calculate some object parameters
      speed[i]  = r.Uniform(0.5,1);
      phi       = r.Gaus(0,TMath::Pi()/6.);
      cosphi[i] = fact*speed[i]*TMath::Cos(phi);
      sinphi[i] = fact*speed[i]*TMath::Sin(phi);
      Double_t rc = r.Rndm();
      color[i] = kRed;
      if (rc > 0.3) color[i] = kBlue;
      if (rc > 0.7) color[i] = kYellow;
   }
   for (s=0;s<nsteps;s++) { //fill the TGraphTime step by step
      for (i=0;i<np;i++) {
         Double_t xx = s*cosphi[i];
         if (xx < xmin) continue;
         Double_t yy = s*sinphi[i];
         TMarker *m = new TMarker(xx,yy,25);
         m->SetMarkerColor(color[i]);
         m->SetMarkerSize(1.5 -s/(speed[i]*nsteps));
         g->Add(m,s);
      }
      g->Add(new TPaveLabel(.70,.92,.98,.99,Form("shower at %5.3f nsec",3.*s/nsteps),"brNDC"),s);
   }
   g->Draw();
}
Esempio n. 8
0
File: fitCircle.C Progetto: Y--/root
//____________________________________________________________________
void fitCircle(Int_t n=10000) {
   //generates n points around a circle and fit them
   TCanvas *c1 = new TCanvas("c1","c1",600,600);
   c1->SetGrid();
   gr = new TGraph(n);
   if (n> 999) gr->SetMarkerStyle(1);
   else        gr->SetMarkerStyle(3);
   TRandom3 r;
   Double_t x,y;
   for (Int_t i=0;i<n;i++) {
      r.Circle(x,y,r.Gaus(4,0.3));
      gr->SetPoint(i,x,y);
   }
   c1->DrawFrame(-5,-5,5,5);
   gr->Draw("p");


   auto chi2Function = [&](const Double_t *par) {
      //minimisation function computing the sum of squares of residuals
      // looping at the graph points
      Int_t np = gr->GetN();
      Double_t f = 0;
      Double_t *x = gr->GetX();
      Double_t *y = gr->GetY();
      for (Int_t i=0;i<np;i++) {
         Double_t u = x[i] - par[0];
         Double_t v = y[i] - par[1];
         Double_t dr = par[2] - std::sqrt(u*u+v*v);
         f += dr*dr;
      }
      return f;
   };

   // wrap chi2 funciton in a function object for the fit
   // 3 is the number of fit parameters (size of array par)
   ROOT::Math::Functor fcn(chi2Function,3);
   ROOT::Fit::Fitter  fitter;


   double pStart[3] = {0,0,1};
   fitter.SetFCN(fcn, pStart);
   fitter.Config().ParSettings(0).SetName("x0");
   fitter.Config().ParSettings(1).SetName("y0");
   fitter.Config().ParSettings(2).SetName("R");

   // do the fit 
   bool ok = fitter.FitFCN();
   if (!ok) {
      Error("line3Dfit","Line3D Fit failed");
   }   

   const ROOT::Fit::FitResult & result = fitter.Result();
   result.Print(std::cout);

   //Draw the circle on top of the points
   TArc *arc = new TArc(result.Parameter(0),result.Parameter(1),result.Parameter(2));
   arc->SetLineColor(kRed);
   arc->SetLineWidth(4);
   arc->Draw();
}
Esempio n. 9
0
// Code from http://www.hongliangjie.com/2012/12/19/how-to-generate-gamma-random-variables/
// Parameter b could be theta...
double gsl_ran_gamma(const double a, const double b, TRandom3 &rand)
{
  
  if (a < 1)
  {
    double u = rand.Uniform(1);
    return gsl_ran_gamma(1.0 + a, b, rand) * pow (u, 1.0 / a);
  }

  double x, v, u;
  double d = a - 1.0 / 3.0;
  double c = (1.0 / 3.0) / sqrt (d);
  
  while (1) 
  {
    do 
    {
      x = rand.Gaus(0, 1.0);
      v = 1.0 + c * x;
    }
    while (v <= 0);
      
    v = v * v * v;
    u = rand.Uniform(1);

    if (u < 1 - 0.0331 * x * x * x * x) 
      break;

    if (log (u) < 0.5 * x * x + d * (1 - v + log (v)))
      break;
  }
    
  return b * d * v;
}
Esempio n. 10
0
int main()
{
	// Manual input:
	if (true)
	{
		vector<KLV> gen(4); // pt eta phi m
		gen[1].p4.SetCoordinates(30,  1.0, 0.5, 0);
		gen[3].p4.SetCoordinates(25, -1.0, 2.5, 0);
		gen[2].p4.SetCoordinates(15,  2.1, 1.1, 0);
		gen[0].p4.SetCoordinates(10,  2.3, 1.0, 0);
		vector<KLV> rec(3);
		rec[2].p4.SetCoordinates(20,  1.3, 0.4, 0);
		rec[0].p4.SetCoordinates(18, -0.9, 2.2, 0);
		rec[1].p4.SetCoordinates(13,  2.2, 1.1, 0);
		test(gen, rec);
	}

	// Automatic input
	TRandom3 rnd;
	for (size_t i = 0; i < 4; ++i)
	{
		vector<KLV> gen, rec;
		// GEN stuff
		for (size_t j = 0; j < (size_t)rnd.Poisson(10); ++j)
		{
			gen.push_back(KLV());
			gen.back().p4.SetCoordinates(rnd.Uniform(5, 100), rnd.Gaus(0, 5), rnd.Uniform(-M_PI, +M_PI), rnd.Gaus(0, 10));
			// RECO efficiency
			if (rnd.Uniform(0, 1) > 0.05)
			{
				rec.push_back(KLV());
				rec.back().p4.SetCoordinates(
					gen.back().p4.pt() * fabs(rnd.Gaus(0.8, 0.1)),
					gen.back().p4.eta() * fabs(rnd.Gaus(1, 0.1)),
					gen.back().p4.phi() + rnd.Uniform(0, 0.1),
					gen.back().p4.mass() * rnd.Gaus(1, 0.1));
			}
		}
		// RECO noise
		for (size_t j = 0; j < (size_t)rnd.Poisson(5); ++j)
		{
			rec.push_back(KLV());
			rec.back().p4.SetCoordinates(rnd.Uniform(1, 10), rnd.Gaus(0, 5), rnd.Uniform(-M_PI, +M_PI), rnd.Gaus(0, 10));
		}
		test(gen, rec);
	}
}
Esempio n. 11
0
int main() {

     //Teil a)
    int array[100];
    for(int i = 0; i < 100; i++) {
        array[i] = i+1;
        //cout << array[i] << endl;
    }


    //Teil b)
    double array2d[100][8];
    
    TRandom3 randomgen;
    for(int i = 0; i < 100; i++) {
        //0.Spalte
        array2d[i][0] = i+1;

        //1. Spalte
        array2d[i][1] = randomgen.Rndm();

        //2. Spalte
        array2d[i][2] = randomgen.Rndm() * 10;

        //3. Spalte
        array2d[i][3] = randomgen.Rndm() * 10 + 20;

        //4. Spalte
        array2d[i][4]= randomgen.Gaus();

        //5. Spalte
        array2d[i][5] = randomgen.Gaus(5, 2);

        //6. Spalte
        array2d[i][6] = array2d[i][0] * array2d[i][0];

        //7. Spalte
        array2d[i][7] = TMath::Cos(array2d[i][0]); 
    }


    return 0;
}
Esempio n. 12
0
File: ks-test.C Progetto: Fmajor/src
//ks-test for Gaussian Random samples
void test(Int_t num)
{
  Double_t *d=new Double_t[num];
  Double_t p,t;
  TRandom3 r;
  for (int i=0;i<num;i++)
    d[i]=r.Gaus();
  ROOT::Math::GoFTest *tt=new ROOT::Math::GoFTest(num,d,ROOT::Math::GoFTest::kGaussian);
  tt->KolmogorovSmirnovTest(p,t);
  cout<<"p:"<<p<<",t:"<<t<<endl;
}
Esempio n. 13
0
int Ngenerated(double muIn)
{

	double sigma = sqrt(muIn + background);
	double mean = muIn + background;
	double nn = rnd.Gaus(mean, sigma);
	int ng = int(round(nn));

	return ng;

}
Esempio n. 14
0
void generateGaussRandom(){

  TRandom3 *gr = new TRandom3(12345);
  cout<<"generating gaus rand for use "<< Nrand<<endl; 
  for(int j=0;j<Nrand;j++){
    if(j%100000000==0) cout<<" j " << j <<endl; 
    float tmp = gr->Gaus();
    vrandgaus.push_back(tmp);
  }
  
}
Esempio n. 15
0
Double_t Reconstruct( Double_t xt, TRandom3& R )
{
   // apply some Gaussian smearing + bias and efficiency corrections to fake reconstruction
   const Double_t cutdummy = -99999.0;
   Double_t xeff = 0.3 + (1.0 - 0.3)/20.0*(xt + 10.0);  // efficiency
   Double_t x    = R.Rndm();
   if (x > xeff) return cutdummy;
   else {
     Double_t xsmear= R.Gaus(-2.5,0.2); // bias and smear
     return xt+xsmear;
   }
}
Esempio n. 16
0
void NeuSmear( TH1D* NeuDet, TH1* NeuSp, TH1* Reso )
{
  TRandom3 r;

  for( int b=1; b<=nBin; b++ ) {
    double mea = 1.5 + (12-1.5)/nBin*(b-0.5);
    double wei = NeuSp->GetBinContent( b );
    double res = Reso ->GetBinContent( b );
    
    for( int s=1; s<=1000; s++ ) {
      double d = r.Gaus( mea, res );
      NeuDet->Fill( d, wei/nBin );
    }
  }
}
Esempio n. 17
0
void smearEmEnergy( TLorentzVector& p ) {

    float smearEBlowEta     = 0.013898;
    float smearEBhighEta    = 0.0189895;
    float smearEElowEta     = 0.027686;
    float smearEEhighEta    = 0.031312;
    float theGaussMean      = 1.;
    float pt = p.Pt();
    float eta = p.Eta();
    float phi = p.Phi();
    float mass = p.M();
    float theSmear = 0.;
    if      (fabs(eta)<1.                   )  theSmear = smearEBlowEta;
    else if (fabs(eta)>=1.  && fabs(eta)<1.5)  theSmear = smearEBhighEta;
    else if (fabs(eta)>=1.5 && fabs(eta)<2. )  theSmear = smearEElowEta;
    else if (fabs(eta)>=2.  && fabs(eta)<2.5)  theSmear = smearEEhighEta;
    float fromGauss = myRandom_.Gaus(theGaussMean,theSmear);
    p.SetPtEtaPhiM( fromGauss*pt, eta, phi, mass ); // keep mass and direction same

}
Esempio n. 18
0
int main(int argc, char *argv[])
{
    std::auto_ptr<TRint> application(new TRint("histInMemory", 0, 0));

    TH1F *histogram  = new TH1F("hist1", "hist1", 50, 0, 10);

    TRandom3 *random = new TRandom3(1);
    for(int i = 0; 10000 > i; ++i)
    {
        histogram->Fill(random->Gaus(5, 1));
    }
    delete random;

    histogram->Draw();

    application->Run(true);

    delete histogram;

    return 0;
}
Esempio n. 19
0
// ----------------------------------------------------------------------
TGraphErrors* CreateDataGraph(int n, double xmin, double xmax)
{
    const double pi =  3.141592;

    // initialize random number generator
    TRandom3* ran = new TRandom3(0);

    double* xx = new double[n];
    double* yy = new double[n];
    double* err = new double[n];

    double dx = (xmax-xmin)/(double)(n-1);

    // loop over points
    for (int i=0; i<n; i++)
    {
        // get x value
        double x = xmin + (double)i*dx;

        // get y value
        double yexp = p0 + p1*x + p2*x*x + a/(sqrt(2.*pi)*s)*exp(-.5*(x-m)*(x-m)/(s*s));
        double y = ran->Gaus(yexp*100., sigmay*100.) / 100.;

        xx[i]=x;
        yy[i]=y;
        err[i]=sigmay;
    }

    TGraphErrors* g = new TGraphErrors(n,xx,yy,0,err);

    delete [] xx;
    delete [] yy;
    delete [] err;

    return g;
}
Esempio n. 20
0
void acc_media(){

	TRandom3 rndgen;

  //efficienze
  //  float eps1 [3][3] = {{0.612,0.662,0.762},{0.425,0.470,0.612},{0.574,0.618,0.722}};
	double  rxmax, rymax, rD12, rD23, reps1, reps2, reps3; 
  float eps1 = 0.745;
  float s_eps1 = 0.003;
  float eps2 = 0.5658;
  float s_eps2 = 0.003;
  float eps3 = 0.6066;
  float s_eps3 = 0.003;
  double theta, W1,W2,W3, phi,x1,x2,x3,y1,y2,y3;
  int j = 0;
  
 TH1F* hacc = new TH1F("a","Distribuzione accettanza; a; # esperimenti", 100, 0.2, 0.3);
 TH1F* haccA = new TH1F("aA","Distribuzione accettanza; aA (cm^2); # esperimenti", 100, 400, 600);

 TFile rfile("accettanza_media.root","RECREATE");

  for (int a = 1; a <= nexp; a++) { 
    cout << "Experiment n. " << a << ": " << endl;
      rxmax = xmax + rndgen.Uniform(2*s_xmax)-s_xmax;
      rymax = ymax + rndgen.Uniform(2*s_ymax)-s_ymax;
      rD12 = D12 + rndgen.Uniform(2*s_D12)-s_D12;
      rD23 = D23 + rndgen.Uniform(2*s_D23)-s_D23;
      reps1 = rndgen.Gaus(eps1,s_eps1); //inserire distribuzione corretta
      reps2 = rndgen.Gaus(eps2,s_eps2);
      reps3 = rndgen.Gaus(eps3,s_eps3);
    for (int i = 1; i <= imax;) {
            
      theta = rndgen.Uniform(2*atan(1.)); 
      W1 = rndgen.Uniform(1);
      if (sin(theta)*pow(cos(theta),2) > W1) { // distribuzione: cos^2(theta) dcos(theta)
	i+=1;
	//	if (i%int(double(imax)/10) == 0) cout << double(i)/double(imax)*100 << "%" << endl;
	phi = rndgen.Uniform(8*atan(1.));
	x2 = (rndgen.Uniform(rxmax)-rxmax/2.);
	y2 = (rndgen.Uniform(rymax)-rymax/2.);
	x1 = tan(theta)*cos(phi)*rD12 + x2;
	y1 = tan(theta)*sin(phi)*rD12 + y2;
	x3 = -tan(theta)*cos(phi)*rD23+x2;
	y3 = -tan(theta)*sin(phi)*rD23 + y2;
	W1 = rndgen.Uniform(1);
	W2 = rndgen.Uniform(1);
	W3 = rndgen.Uniform(1);
      
	if ((pow(x1,2) <= pow(rxmax,2)/4) && (pow(y1,2) <= pow(rymax,2)/4) && (pow(x3,2) <= pow(rxmax,2)/4) && (pow(y3,2) <= pow(rymax,2)/4) && W1 < reps1 && W2 < reps2 && W3 < reps3){
	  
	  j+=1;}
      }
    }

    cout << "Generati: " << imax << endl;
    cout << "Accettati: " << j << endl;
    cout << "Accettanza: " << double(j)/double(imax) << endl;
hacc->Fill(double(j)/double(imax));   
haccA->Fill(double(j)/double(imax)*rxmax*rymax); //le moltiplico anche per l'area perché nel flusso accettanza e area compaiono insieme
    j = 0;
  }
  cout << "Accettanza media: " << hacc->GetMean()*xmax*ymax << endl;
  hacc->Write();
  haccA->Write();
}
Esempio n. 21
0
void acc_zone(){

	TRandom3 rndgen;

  //efficienze
    float eps1 [3][3] = {{0.7498,0.729,0.725},{0.746,0.713,0.7336},{0.7833,0.7471,0.7786}};
    float eps2 [3][3] = {{0.6204,0.5303,0.5673},{0.6307,0.5626,0.6080},{0.7440,0.6701,0.7241}};
    float eps3 [3][3] = {{0.5743,0.4255,0.6121},{0.6176,0.4701,0.6620},{0.7229,0.6124,0.7621}};
    double  rxmax, rymax, rD12, rD23, reps1[3][3], reps2[3][3], reps3[3][3];
    int cx1, cx2, cx3, cy1, cy2, cy3;
  float s_eps1 = 0.003;
  float s_eps2 = 0.003;
  float s_eps3 = 0.003;
  double theta, W1,W2,W3, phi,x1,x2,x3,y1,y2,y3;
  int j = 0;
  
 TH1F* hacc = new TH1F("a","Distribuzione accettanza; a; # esperimenti", 100, 0.2, 0.3);
 TH1F* haccA = new TH1F("aA","Distribuzione accettanza; aA (cm^2); # esperimenti", 100, 400, 600);

 TFile rfile("accettanza_zone.root","RECREATE");

  for (int a = 1; a <= nexp; a++) { 
    cout << "Experiment n. " << a << ": " << endl;
      rxmax = xmax + rndgen.Uniform(2*s_xmax)-s_xmax;
      rymax = ymax + rndgen.Uniform(2*s_ymax)-s_ymax;
      rD12 = D12 + rndgen.Uniform(2*s_D12)-s_D12;
      rD23 = D23 + rndgen.Uniform(2*s_D23)-s_D23;
      for (int m = 0; m < 3; m++) {
	for (int n = 0; n < 3; n++) {
	  reps1[m][n] = rndgen.Gaus(eps1[m][n],s_eps1); //inserire distribuzione corretta
	  reps2[m][n] = rndgen.Gaus(eps2[m][n],s_eps2);
	  reps3[m][n] = rndgen.Gaus(eps3[m][n],s_eps3);
	}
      }
    for (int i = 1; i <= imax;) {
            
      theta = rndgen.Uniform(2*atan(1.)); 
      W1 = rndgen.Uniform(1);
      if (sin(theta)*pow(cos(theta),2) > W1) { // distribuzione: cos^2(theta) dcos(theta)
	i+=1;
	//	if (i%int(double(imax)/10) == 0) cout << double(i)/double(imax)*100 << "%" << endl;
	phi = rndgen.Uniform(8*atan(1.));
	x2 = (rndgen.Uniform(rxmax)-rxmax/2.);
	y2 = (rndgen.Uniform(rymax)-rymax/2.);
	x1 = tan(theta)*cos(phi)*rD12 + x2;
	y1 = tan(theta)*sin(phi)*rD12 + y2;
	x3 = -tan(theta)*cos(phi)*rD23+x2;
	y3 = -tan(theta)*sin(phi)*rD23 + y2;
	W1 = rndgen.Uniform(1);
	W2 = rndgen.Uniform(1);
	W3 = rndgen.Uniform(1);

	cx1 = cell(x1,rxmax);
	cx2 = cell(x2,rxmax);
	cx3 = cell(x3,rxmax);
	cy1 = cell(y1,rymax);
	cy2 = cell(y2,rymax);
	cy3 = cell(y3,rymax);

	if ((pow(x1,2) <= pow(rxmax,2)/4) && (pow(y1,2) <= pow(rymax,2)/4) && (pow(x3,2) <= pow(rxmax,2)/4) && (pow(y3,2) <= pow(rymax,2)/4) && W1 < reps1[cx1][cy1] && W2 < reps2[cx2][cy2] && W3 < reps3[cx3][cy3]){
	  
	  j+=1;}
      }
    }

    cout << "Generati: " << imax << endl;
    cout << "Accettati: " << j << endl;
    cout << "Accettanza: " << double(j)/double(imax) << endl;
hacc->Fill(double(j)/double(imax));   
haccA->Fill(double(j)/double(imax)*rxmax*rymax); //le moltiplico anche per l'area perché nel flusso accettanza e area compaiono insieme
    j = 0;
  }
  cout << "Accettanza media: " << hacc->GetMean()*xmax*ymax << endl;
  hacc->Write();
  haccA->Write();
}
void FindConstant::produceSIMEvents( std::vector<double>& SIMEvents, const double eRes)
{

  // DEKLARACJE ZMIENNYCH
  Double_t przekroj, E_0, E, stala, fi, firad, pi;
  Int_t i;
  Double_t T, kos, x, y, max, Eprim;
  TRandom3 los;
  Double_t rozdzielczosc, g, sigma, rozmyciex, Troz;

  // INICJALIZACJIA
  przekroj = 0.0;
  E = 1.0;
  stala = pow((2.82 * 1E-13), 2.0) * 0.5;
  E_0 = 511.0      ;
  fi = 0.0;
  i = 0;
  firad = 0;
  pi = 3.14159265358979323846;
  kos = 0.0;
  T = 0.0;
  Eprim = 0.0;
  rozdzielczosc = 0.0;
  g = 0.0;
  sigma = 0.0;
  rozmyciex = 0.0;
  Troz = 0.0;     //Ek. Kin. rozmyta

  // jeden stopien to okolo 0.0175 radiana  bo 1* pi /180 = 0.0175
  rozdzielczosc = eRes;

  fi = 0;

  firad = fi * pi / 180.0;
  E = E_0 * 511.0 / (511.0 + E_0 * ( 1 - cos(firad)));

  max = E * (2 * E / 511) / (1 + 2 * E / 511);

  //// PETLA DO RYSOWANIA WIDMA

  for (i = 0; i < 100000;) {



    x = los.Rndm() * max;

    y = los.Rndm() * 10.0;
    g = los.Gaus(0, 1);
    T = x;
    kos = (511.0 / E * T + T - E) / (T - E);
    Eprim = E - T;

    przekroj =  2.0 * 3.14 * stala * pow(Eprim / E, 2.0) * (E / Eprim + Eprim / E - 1.0 + pow(kos, 2.0) ) * ((511.0 / E + 1.0) / (T - E) - (511.0 / E * T + T - E) / (pow((T - E), 2.0))) * (-1.0) * 1E27;



    if (przekroj > y) {

      sigma = rozdzielczosc * sqrt(x);
      rozmyciex = sigma * g;
      Troz = x + rozmyciex;
      SIMEvents.push_back(Troz);
      i++;
    }


  }
}
Esempio n. 23
0
int main(int argc, char* argv[]){
  typedef ROOT::Math::SMatrix<double,2>                                       SMatrix22;
  typedef ROOT::Math::SVector<double,2>                                       SVector2; 

  std::string param_file;
  if (argc != 2) {
    std::cout << "Usage: ./ZbbCalc <parameter file>" << std::endl;
    exit(1);
  } else {
    param_file = argv[1];
  }

  TRandom3 rand;
  TH1F h_N1("N1","N1",100,10000,13000);
  TH1F h_N2("N2","N2",100,1000,2000);

  SimpleParamParser input;
  input.ParseFile(param_file);
  double x_N_TAG_1 = input.GetParam<double>("N_TAG_1");
  double N_TAG_1_err = input.GetParam<double>("N_TAG_1_err");
  double x_N_TAG_2 = input.GetParam<double>("N_TAG_2");
  double N_TAG_2_err = input.GetParam<double>("N_TAG_2_err");
  double N_TAG_1, N_TAG_2;
  double p_1  = input.GetParam<double>("p_1");
  double p_21 = input.GetParam<double>("p_21");
  double p_22 = input.GetParam<double>("p_22");
  double p_2;
  double ftt_1 = input.GetParam<double>("ftt_1");
  double ftt_2 = input.GetParam<double>("ftt_2");
  double N_RTAG_1, N_RTAG_2;
  double x_e_b_11 =  input.GetParam<double>("e_b_11");
  double e_b_11_err = input.GetParam<double>("e_b_11_err");
  double x_e_b_21 = input.GetParam<double>("e_b_21"); 
  double e_b_21_err = input.GetParam<double>("e_b_21_err");
  double x_e_b_22 = input.GetParam<double>("e_b_22");
  double e_b_22_err = input.GetParam<double>("e_b_22_err");
  double e_b_11, e_b_21, e_b_22;
  double x_e_l_1 = input.GetParam<double>("e_l_1");
  double e_l_1_err = input.GetParam<double>("e_l_1_err");
  double x_e_l_2 = input.GetParam<double>("e_l_2");
  double e_l_2_err = input.GetParam<double>("e_l_2_err");
  double e_l_1, e_l_2;
  double x_e_r_11 = input.GetParam<double>("e_r_11");
  double e_r_11_err = input.GetParam<double>("e_r_11_err");
  double x_e_r_21 = input.GetParam<double>("e_r_21");
  double e_r_21_err = input.GetParam<double>("e_r_21_err");
  double x_e_r_12 = input.GetParam<double>("e_r_12");
  double e_r_12_err = input.GetParam<double>("e_r_12_err");
  double x_e_r_22 = input.GetParam<double>("e_r_22");
  double e_r_22_err = input.GetParam<double>("e_r_22_err");
  double x_e_r_01 = input.GetParam<double>("e_r_01");
  double e_r_01_err = input.GetParam<double>("e_r_01_err");
  double x_e_r_02 = input.GetParam<double>("e_r_02");
  double e_r_02_err = input.GetParam<double>("e_r_02_err");
  double e_r_11, e_r_21, e_r_12, e_r_22, e_r_01, e_r_02;
  double R = input.GetParam<double>("R");
  double x_a_l_1 = input.GetParam<double>("a_l_1");
  double a_l_1_err = input.GetParam<double>("a_l_1_err");
  double x_a_l_2 = input.GetParam<double>("a_l_2");
  double a_l_2_err = input.GetParam<double>("a_l_2_err");
  double a_l_1, a_l_2;
  double lumi = input.GetParam<double>("lumi");
  double N1, N2;

  for (unsigned i = 0; i < 1000000; ++i) {
    p_2           = p_21 * p_22;

    N_TAG_1 = x_N_TAG_1;
    N_TAG_2 = x_N_TAG_2;
    e_b_11 = x_e_b_11;
    e_b_21 = x_e_b_21;
    e_b_22 = x_e_b_22;
    e_l_1 = x_e_l_1;
    e_l_2 = x_e_l_2;
    e_r_11 = x_e_r_11;
    e_r_21 = x_e_r_21;
    e_r_12 = x_e_r_12;
    e_r_22 = x_e_r_22;
    e_r_01 = x_e_r_01;
    e_r_02 = x_e_r_02;
    a_l_1 = x_a_l_1;
    a_l_2 = x_a_l_2;

  if (i > 0) {
    N_TAG_1 = rand.Gaus(N_TAG_1, N_TAG_1_err);
    N_TAG_2 = rand.Gaus(N_TAG_2, N_TAG_2_err);
    e_b_11 = rand.Gaus(e_b_11, e_b_11_err);
    e_b_21 = rand.Gaus(e_b_21, e_b_21_err);
    e_b_22 = rand.Gaus(e_b_22, e_b_22_err);
    e_l_1 = rand.Gaus(e_l_1, e_l_1_err);
    e_l_2 = rand.Gaus(e_l_2, e_l_2_err);
    e_r_11 = rand.Gaus(e_r_11, e_r_11_err);
    e_r_12 = rand.Gaus(e_r_12, e_r_12_err);
    e_r_21 = rand.Gaus(e_r_21, e_r_21_err);
    e_r_22 = rand.Gaus(e_r_22, e_r_22_err);
    e_r_01 = rand.Gaus(e_r_01, e_r_01_err);
    e_r_02 = rand.Gaus(e_r_02, e_r_02_err);
    a_l_1 = rand.Gaus(a_l_1, a_l_1_err);
    a_l_2 = rand.Gaus(a_l_2, a_l_2_err);
  }


  double N_T_arr[] = {  N_TAG_1, 
                        N_TAG_2 };
  SVector2 N_T(N_T_arr,2);

  if (i == 0) {
    std::cout << "-----------------------------------------------" << std::endl;
    std::cout << "N_events (tagged) [Z+1b, Z+2b]: \n\t" << N_T << std::endl;
  }

  N_T[0]      = N_TAG_1 * (p_1 - ftt_1) 
  + N_TAG_2 * (p_22+p_21 - 2.*p_2);
  N_T[1]      = N_TAG_2 * (p_2 - ftt_2);
  

  double ep_b_arr[] = {   1.0/e_b_11  ,  -1.0 * e_b_21/(e_b_22*e_b_11),
                          0.0         ,  1.0/(e_b_22)   };

  double ep_l_arr[] = {   1.0/e_l_1 ,  0.0,
                          0.0       ,  1.0/e_l_2   };

  double ep_r_arr[] = {   e_r_11 + R*e_r_01 ,  e_r_21 + R*e_r_01,
                          e_r_12 + R*e_r_02 ,  e_r_22 + R*e_r_02   };

  double A_l_arr[] =  {   1.0/a_l_1 ,  0.0,
                          0.0       ,  1.0/a_l_2   };

  SMatrix22 ep_b(ep_b_arr,4);
  SMatrix22 ep_l(ep_l_arr,4);
  SMatrix22 ep_r(ep_r_arr,4);
  SMatrix22  A_l(A_l_arr,4);

  if (i ==0) {
    std::cout << "-----------------------------------------------" << std::endl;
    std::cout << "epsilon_b Matrix:\n" << ep_b << std::endl;
    std::cout << "epsilon_l Matrix:\n" << ep_l << std::endl;
    std::cout << "epsilon_r/C_hadron Matrix:\n" << ep_r << std::endl;
  }
  ep_r.Invert();
  if (i == 0) {
    std::cout << "epsilon_r/C_hadron Matrix (inverted):\n" << ep_r << std::endl;
    std::cout << "Acceptance_l Matrix:\n" << A_l << std::endl;
    std::cout << "-----------------------------------------------" << std::endl;
    std::cout << "N_events (after purity & f_tt): \n\t" << N_T << std::endl;
  }

  double total_before_ep_b = N_T[0] + N_T[1];
  N_T = ep_b * N_T;
  if (i == 0) std::cout << "N_events (after epsilon_b):\n\t" << N_T << std::endl;
  double total_before_ep_l = N_T[0] + N_T[1];
  N_T = ep_l * N_T;
  if (i == 0) std::cout << "N_events (after epsilon_l):\n\t" << N_T << std::endl;
  double total_before_c_had = N_T[0] + N_T[1];
  N_T = ep_r * N_T;
  if (i == 0) std::cout << "N_events (after epsilon_r/C_hadron):\n\t" << N_T << std::endl;
  double total_before_a_l = N_T[0] + N_T[1];
  N_T = A_l * N_T;
  double total_after_a_l = N_T[0] + N_T[1];
  if (i == 0)std::cout << "N_events (after Acceptance_l):\n\t" << N_T << std::endl;

  if (i > 0) {
    h_N1.Fill(N_T[0]);
    h_N2.Fill(N_T[1]);
  }

    if (i == 0) {
      N1 = N_T[0];
      N2 = N_T[1];
      std::cout << "-----------------------------------------------" << std::endl;
      std::cout << "Effective Z+1b inclusive e_b(HE): " << total_before_ep_b/total_before_ep_l << std::endl;
      std::cout << "Effective Z+1b inclusive e_l: " << total_before_ep_l/total_before_c_had << std::endl;
      std::cout << "Effective Z+1b inclusive C_had: " << total_before_c_had/total_before_a_l << std::endl;
      std::cout << "Effective Z+1b inclusive A_l: " << total_before_a_l/total_after_a_l << std::endl;
      std::cout << "-----------------------------------------------" << std::endl;
  }
  }

  TFitResultPtr h_N1_fit = h_N1.Fit("gaus","NSQ");
  double N1_err = h_N1_fit->Parameter(2);
  TFitResultPtr h_N2_fit = h_N2.Fit("gaus","NSQ");
  double N2_err = h_N2_fit->Parameter(2);
  double XS_1 = N1 / lumi;
  double XS_1_err = N1_err/lumi;
  double XS_2 = N2 / lumi;
  double XS_2_err = N2_err/lumi;
  std::cout << "XS [pb] (Z+1b Exclusive):\t" << XS_1 
            << " +/- " << XS_1_err << " (stat)" << std::endl;
  std::cout << "XS [pb] (Z+2b Inclusive):\t" << XS_2 
            << " +/- " << XS_2_err << " (stat)" << std::endl;

  return 0;
}
Esempio n. 24
0
int main() {

TRandom3 u;
u.SetSeed(0);


vector <double> s_vec;
vector <double> mu_vec;


//Starting values for the param
//----------------------------
double  start_s, start_mu;
start_s=10;
start_mu=1;
s_vec.push_back(start_s); mu_vec.push_back(start_mu); 

// Read the data		data are the observables, fdata the density evaluated at data
//-------------
vector<double> data;
vector<double> fdata;
double temp_data,temp_fdata;
ifstream file("data.txt");
while (!file.eof()) {
file >> temp_data >> temp_fdata;
data.push_back(temp_data); fdata.push_back(temp_fdata);
}
data.pop_back(); fdata.pop_back();

//Function for likelihood
//---------------------
TF1* f1 = new TF1("density",density,-20,20,2);



const int nMCmax=1000;
//MCMC running
//-----------
for (int nMC=0; nMC<nMCmax; nMC++){
        double width=.1;
	s_vec.push_back(s_vec[nMC]+width*u.Gaus(0,1));
	mu_vec.push_back(mu_vec[nMC]+width*u.Gaus(0,1));

	double like_i=0; double like_f=0;
	for (int k=0; k<data.size(); k++){
	//initial likelihood
	//------------------ 
	f1->SetParameter(0,s_vec[nMC]);    f1->SetParameter(1,mu_vec[nMC]);
	like_i=like_i+log(f1->Eval(data[k]));
	//cout << k << "    " << like_i<< "    " <<data[k] << endl;
	//final likelihood
	//------------------ 
	f1->SetParameter(0,s_vec[nMC+1]);    f1->SetParameter(1,mu_vec[nMC+1]);
	like_f=like_f+log(f1->Eval(data[k]));
	}
	//cout << like_i<<"   "<<like_f<<"   "  <<s_vec[nMC]<<"   " << s_vec[nMC+1]<<"   " <<mu_vec[nMC]<<"   " << mu_vec[nMC+1]<< endl;
	//Acceptance probability
	//----------------------
	double prob_ratio=exp(like_f-like_i);
	double accept=TMath::Min(1.,prob_ratio);
	if (u.Binomial(1,accept)==0) {
	s_vec.pop_back(); mu_vec.pop_back(); 
	s_vec.push_back(s_vec[nMC]); mu_vec.push_back(mu_vec[nMC]);
	}
	cout <<accept << "    " << prob_ratio<<"    " << like_i<<"   "<<like_f<< "   " <<s_vec[nMC]<<"   " << s_vec[nMC+1]<<"   " <<mu_vec[nMC]<<"   " << mu_vec[nMC+1]<< endl;
	//cout << like_i<<"   "<<like_f<<"   "  <<s_vec[nMC]<<"   " << s_vec[nMC+1]<<"   " <<mu_vec[nMC]<<"   " << mu_vec[nMC+1]<< endl;
}
//End of MCMC running
//-----------

double s_tabl[nMCmax+1]; double mu_tabl[nMCmax+1];
double nMC_tabl[nMCmax+1]; 
for (int k=0; k<=nMCmax; k++) {
   nMC_tabl[k]=k;
   s_tabl[k]=s_vec[k]; mu_tabl[k]=mu_vec[k];
}



TGraph *gr_s = new TGraph (nMCmax, nMC_tabl, s_tabl);
gr_s->SetLineColor(kRed);
gr_s->SetLineWidth(2);
gr_s->SetName("Sigma");

TGraph *gr_mu = new TGraph (nMCmax, nMC_tabl, mu_tabl);
gr_mu->SetLineColor(kBlue);
gr_mu->SetLineWidth(2);
gr_mu->SetName("Mean");


TFile f("graph_MCMC_simplified.root","recreate");
 gr_s->Write(); gr_mu->Write();
f.Close();

return 0;
}
Esempio n. 25
0
void toyMC(int nsteps = 1e6) {
    
    Float_t LA = 9.2;
    Float_t LB = 10.3;
    
    Float_t SF = 492./LB;
    Float_t eSF = TMath::Sqrt(23.*23.+19.7*19.7)/LB;
//     Float_t OF = 358./LA;
//     Float_t eOF = 27./LA;
    Float_t OF = 358./LB;
    Float_t eOF = 31./LB;
    
    Float_t SigB = 188.+238-414;
    
    
    TH1F* hSig = new TH1F("hSig ; SF-R_{SF/OF}#timesOF ; ","Signal component",600,-100.,500.);
    
    hSig->SetLineColor(kRed+2);
    
    TRandom3* ran = new TRandom3();
    
    for ( int i=0; i<nsteps; ++i ) {
        
        Float_t nBSF = ran->Gaus(SF*LB,eSF*LB);
        Float_t nBOF = ran->Gaus(OF*LB,eOF*LB);
        Float_t rsfof = ran->Gaus(1.0,0.05);
        
        hSig->Fill(nBSF-nBOF*rsfof);
        
    }
    
    
    TCanvas* mycan = new TCanvas("mycan","",100,10,900,600);
    mycan->SetLogy();
    TH1F* hSigNorm = hSig->DrawNormalized("");
    hSigNorm->SetMinimum(1e-5);
    hSigNorm->Draw();
    
    // Find 95% CL range
    float integral = 0;
    int binStart = -1;
    while ( integral <= 0.025 ) {
        ++binStart;
        integral += hSigNorm->GetBinContent(binStart);
    }
    std::cout << integral << " up to " << hSigNorm->GetBinCenter(binStart) << std::endl;
    integral = 0;
    int binEnd = hSigNorm->GetNbinsX()+2;
    while ( integral <= 0.025 ) {
        --binEnd;
        integral += hSigNorm->GetBinContent(binEnd);
    }
    std::cout << integral << " up to " << hSigNorm->GetBinCenter(binEnd) << std::endl;
    
    // Draw 95% CL
    TBox* range95 = new TBox(hSigNorm->GetBinCenter(binStart),hSigNorm->GetMinimum(),hSigNorm->GetBinCenter(binEnd),1.2*hSigNorm->GetMaximum());
    range95->SetFillColor(kBlue-9);
    range95->SetFillStyle(1000);
    range95->SetLineColor(range95->GetFillColor());
    range95->Draw();
    
    hSigNorm->SetTitle("hSigNorm; \"S\" #equiv SF - R_{SF/OF}#timesOF ; pdf");
    hSigNorm->Draw("same");
    
    std::cout << "Integrating from 0 to " << SigB << ": " << std::endl;
    std::cout << hSigNorm->Integral(0,hSigNorm->FindBin(SigB)) <<std::endl;
    
    TLegend* legend = new TLegend(0.6,0.7,0.95,0.9,"","brNDC");
    legend->SetBorderSize(0);
    legend->AddEntry(hSigNorm,"Expected \"S\" for block B","l");
    legend->AddEntry(range95,"95% region","f");
    legend->Draw();

    mycan->RedrawAxis();
    mycan->SaveAs("toyMCexp.pdf");

    TArrow* a = new TArrow(SigB,hSigNorm->GetMaximum(),SigB,hSigNorm->GetMinimum()*1.1,0.02);
    a->SetLineColor(kBlue+2);
    a->Draw();


    TLegend* legend2 = new TLegend(0.6,0.6,0.95,0.7,"","brNDC");
    legend2->SetBorderSize(0);
    legend2->AddEntry(a,"Observed (p-value 0.6%)","l");
    legend2->Draw();
    

    mycan->SaveAs("toyMC.pdf");
    
}
Esempio n. 26
0
void proSTEGvnwithnfv3()
{
  
  int mult = atoi(getenv("MULT"));

  int tot_num=50000;  //50k events
  double MeanMult=(double)mult;
  double RMSMult=10;
  
  int ifile = atoi(getenv("IFILE")); 

  //simple toy event generator
  //TFile f(Form("/lio/lfs/cms/store/user/qixu/flow/NewSTEG/pPbDataV205m%d/vndata_50k_%d.root",mult,ifile), "RECREATE","ROOT file with histograms & tree");
  TFile f(Form("/tmp/xuq7/pPbDataV205m%d/vndata_50k_%d.root",mult,ifile), "RECREATE","ROOT file with histograms & tree");
//  TFile f(Form("vndata_50k_%d.root",mult,ifile), "RECREATE","ROOT file with histograms & tree");
  TTree *tree = new TTree("tree","Event tree with a few branches");
//  tree->Branch("npg", &b_npg, "npg/I");   // # of particles;
//  tree->Branch("phirg", &b_phirg, "phirg/F");  // RP angle;
  tree->Branch("n", &b_n, "n/I");          // same as npg;
  tree->Branch("ptg", &b_ptg, "ptg[n]/F");  // ;
  tree->Branch("etag", &b_etag, "etag[n]/F");
  tree->Branch("phig", &b_phig, "phig[n]/F");
  
  TF1 *EtaDistr = new TF1("EtaDistr","exp(-(x-2.1)^2/6.3)+exp(-(x+2.1)^2/6.3)",-4,4);
  //TF1 *PhiDistr = new TF1("PhiDistr","1+2*[0]*cos(x)+2*[1]*cos(2*x)+2*[2]*cos(3*x)+2*[3]*cos(4*x)+2*[4]*cos(5*x)+2*[5]*cos(6*x)",0,2.*TMath::Pi());
  TF1 *PhiDistr = new TF1("PhiDistr","1+2*[0]*cos(2*x)+2*[1]*cos(3*x)+2*[2]*cos(4*x)+2*[3]*cos(5*x)+2*[4]*cos(6*x)",0,2.*TMath::Pi());
  //TF1 *PtDistr  = new TF1("PtDistr","exp (-(x/.40))+0.0015*exp (-(x/1.5))", 0.2,10);	//V~0.12
  //TF1 *PtDistr  = new TF1("PtDistr","exp (-(x/0.90))+0.15*exp (-(x/15))", 0.1,10);	//V~=0.06
  TF1 *PtDistr  = new TF1("PtDistr","0.03*(exp (-(x/0.594540))+0.00499506*exp (-(x/1.89391)))", 0.3,6.0);	//Real Data
  //  TF1 *PtDistr = new TF1("PtDistr","[0]*x*TMath::Power(1+(sqrt(x*x+[1]*[1])-[1]/[2]),-[3])",0.2,10);
	//PtDistr->SetParameters(118.836,-0.335972,0.759243,118.836);	//Real data fit with Tsallis
  //TF1 *V1vsEta = new TF1("V1vsEta","-exp(-(x+1)^2)/20-x/30+exp(-(x-1)^2)/20",-2.4,2.4); 
  //TF1 *V2vsPt   = new TF1("V2vsPt","((x/3)^1.8/(1+(x/3)^1.8))*(.00005+(1/x)^0.8)",0.2,10);
  //TF1 *V2vsPt = new TF1("V2vsPt","((x/[0])^[1]/(1+(x/[2])^[3]))*(.00005+(1/x)^[4])",0.1,10);
 //	V2vsPt->SetParameters(4.81159,1.80783,3.69272,3.11889,0.931485);	//Real data V~0.05
  //	V2vsPt->SetParameters(5,1.8,3,1.8,0.8); //V~0.06
  TF1 *V2vsPt = new TF1("V2vsPt","((x/3.31699)^2.35142/(1+(x/3.49188)^3.54429))*(.00005+(1/x)^1.50600)",0.3,6.0);
  TF1 *V3vsPt = new TF1("V3vsPt","((x/3.2)^2.3/(1+(x/3.4)^2.1))*(.00005+(1/x)^1.4)",0.3,6.0);
  TF1 *V4vsPt = new TF1("V4vsPt","((x/4.8)^2.1/(1+(x/3.4)^2.1))*(.00005+(1/x)^1.4)",0.3,6.0);
  TF1 *V5vsPt = new TF1("V5vsPt","((x/6.0)^3.2/(1+(x/11.4)^2.1))*(.00005+(1/x)^1.4)",0.3,6.0);
  TF1 *V6vsPt = new TF1("V6vsPt","((x/5.6)^2.4/(1+(x/4.7)^2.1))*(.00005+(1/x)^1.4)",0.3,6.0);
 
    UInt_t iniseed = SetSeedOwn();
    gRandom->SetSeed(iniseed);
  TRandom3 *rnd = new TRandom3(0);
  
  double v1, v2, v3, v4, v5, v6, ph, myphi, mypt, myeta, phi0, Psi;
  int nnf,k;
  double neta, nphi, npt;
  int slicept;
  
  for(int i=0; i<tot_num; i++){ 
    
    Psi = rnd->Uniform(0.0,2.*TMath::Pi());
    //Psi=0;
    b_phirg = Psi; 
    b_npg = rnd->Gaus(MeanMult,RMSMult); 
    int b_npgsame = (int)b_npg * 0.10;
    n = 0;
  
    for(int j=0; j<b_npg;j++ ){
      mypt = PtDistr->GetRandom();
      myeta =  EtaDistr->GetRandom();

      //v1=V1vsEta->Eval(myeta);
      v2=V2vsPt->Eval(mypt);
      v3=V3vsPt->Eval(mypt);
      v4=V4vsPt->Eval(mypt);
      v5=V5vsPt->Eval(mypt);
      v6=V6vsPt->Eval(mypt);

      b_etag[n] = myeta;
      b_ptg[n]  = mypt;
      //PhiDistr->SetParameters(v1,v2,v3,v4,v5,v6);
      PhiDistr->SetParameters(v2,v3,v4,v5,v6);
      
      myphi = PhiDistr->GetRandom(); // randon selection dn/dphi

      myphi = myphi+Psi; // angle in lab frame -- needed for correct cumulant v2
      if (myphi>2.*TMath::Pi()) myphi=myphi-2.*TMath::Pi(); // 0 - 2*Pi
      
      b_phig[n] = myphi; // save angle in lab frame
      n++;
    }
    if(i%10==0){
    for(int j=0;j<b_npgsame;j++){
      mypt = PtDistr->GetRandom();
      myeta =  EtaDistr->GetRandom();
      b_ptg[n] = mypt;
      b_etag[n] = myeta;
      myphi = rnd->Gaus(Psi, 0.3);
      if (myphi>2.*TMath::Pi()) myphi=myphi-2.*TMath::Pi(); // 0 - 2*Pi
      b_phig[n] = myphi;
      n++;
    }
    }
    if (i%10000 == 0) cout << i << " " << "events processed" << endl;

    b_n = n;
    tree->Fill();
  } // End of loop over events
  
  cout << "writing tree" << endl;
  tree->Write();
  cout << "writing to file" << endl;
  f.Write();
  cout << "closing file" << endl;
  f.Close();
  cout << "THE END" << endl;
}
Esempio n. 27
0
void linfit()
{
   gStyle->SetOptFit();

   Double_t x2[1000], y2[1000], ex2[1000], ey2[1000];
   Int_t n2 = 10;

   TRandom3 random;
   Double_t x0, delta;
   Double_t dy = 10;
   Double_t sigma = 10;

   // parameters of line y = k*x + b
   Double_t k;
   Double_t b;
   // errors on parameters
   Double_t dk;
   Double_t db;
   // intersection with x-axis
   Double_t xint;
   Double_t dx;

   TF1 *fitfunction = 0;

   delta = 100./n2;
   x0 = 0 - delta;
   for (int i=0; i<n2; ++i) {
      x0 += delta;
      x2[i] = x0;
      y2[i] = random.Gaus(x2[i], sigma);
      ex2[i] = 0;
      ey2[i] = dy;         // all weights are equal
      ey2[i] = TMath::Sqrt(y2[i]);
   }

   TGraphErrors *gr2 = new TGraphErrors(n2, x2,y2, ex2, ey2);
   gr2->SetNameTitle("gr2", "gr2");
   gr2->SetMarkerStyle(20);
   gr2->SetMarkerColor(4);
   gr2->SetLineColor(4);

   new TCanvas;
   gr2->Draw("ap");
   gr2->Fit("pol1");

   fitfunction = gr2->GetFunction("pol1");
   b = fitfunction->GetParameter(0);
   db = fitfunction->GetParError(0);
   k = fitfunction->GetParameter(1);
   dk = fitfunction->GetParError(1);
   xint = -b / k;
   dx = TMath::Abs(b/k) * TMath::Sqrt( (db/b)*(db/b) + (dk/k)*(dk/k) );
   gr2->SetTitle(Form("intersection with x-axis: %0.3f #pm %0.3f", xint,dx));
   cout<< "--> intersection with x-axis: " << xint << " +- " << dx <<endl;

   cout<< "--> chi2ndf = " << fitfunction->GetChisquare() / fitfunction->GetNDF();
   cout<<endl<<endl;

   // fast straight line fit y = am + bm*x
   // Source: Kalashnikova, Kozodaev, Detektory Elementarnyx chastic.

   //-- Float_t version of the data
   Float_t xf[1000], yf[1000], eyf[1000];
   Int_t nf = n2;
   for (int i=0; i<nf; ++i) {
      xf[i] = x2[i];
      yf[i] = y2[i];
      eyf[i] = ey2[i];
   }

   Double_t wx = 0;
   Double_t wy = 0;
   Double_t wxy = 0;
   Double_t wx2 = 0;
   Double_t W = 0;

   wx = wy = wxy = wx2 = W = 0;
   for (int i=0; i<gr2->GetN(); ++i)
   {
      Double_t x = gr2->GetX()[i];
      Double_t y = gr2->GetY()[i];
      Double_t yerror = gr2->GetEY()[i];
      Double_t w = 1./(yerror*yerror);       // weights are 1/ey

      W += w;
      wx += w*x;
      wx2 += w*x*x;
      wy += w*y;
      wxy += w*x*y;
   }

   Double_t Discriminant = W*wx2 - wx*wx;
   Double_t am = (wy*wx2 - wxy*wx) / Discriminant;    // y = am + bm*x
   Double_t bm = (W*wxy - wx*wy) / Discriminant;

   Double_t chi2 = 0;
   Double_t chi2ndf = 0;
   for (int i=0; i<gr2->GetN(); ++i)
   {
      Double_t x = gr2->GetX()[i];
      Double_t y = gr2->GetY()[i];
      Double_t yerror = gr2->GetEY()[i];
      Double_t yfit = am + bm*x;
      Double_t r = (y - yfit) / yerror;
      chi2 += r*r;
   }
   chi2ndf = chi2 / (gr2->GetN() - 2);

   cout<< "--> fast straight line fit: am " << am << " bm " << bm << " chi2ndf = " << chi2ndf <<endl;
   //--
   //-- NB: operator
   //-- cout<< "pol1fast(xf,yf,eyf,0,nf, am,bm) = " << pol1fast(xf,yf,eyf,0,nf, am,bm) << " am " << am << " bm " << bm <<endl;
   //-- will be executed from the tail: 
   //-- print __current__ version (before call of pol1fast) of the am and bm first
   //-- and will call pol1fast (and will obtain updated versions of am and bm) after that!!!!!!!!!!!
   //--
   chi2ndf = pol1fast(xf,yf,eyf,0,nf, am,bm);
   cout<< "pol1fast(xf,yf,eyf,0,nf, am,bm) = " << chi2ndf << " am " << am << " bm " << bm <<endl;
   cout<< "for comparizon eyf=0 generates fit with equal weights:" <<endl;
   chi2ndf = pol1fast(xf,yf,0,0,nf, am,bm);
   cout<< "pol1fast(xf,yf,0,0,nf, am,bm) / dy = " << chi2ndf / dy << " am " << am << " bm " << bm <<endl;

   cout<< "all weights are equal to 1" <<endl;
   wx = wy = wxy = wx2 = W = 0;
   for (int i=0; i<gr2->GetN(); ++i)
   {
      Double_t x = gr2->GetX()[i];
      Double_t y = gr2->GetY()[i];
      // Double_t yerror = gr2->GetEY()[i];
      // Double_t w = 1./(yerror*yerror);       // weights are 1/ey
      Double_t w = 1.;

      W += w;
      wx += w*x;
      wx2 += w*x*x;
      wy += w*y;
      wxy += w*x*y;
   }

   Discriminant = W*wx2 - wx*wx;
   am = (wy*wx2 - wxy*wx) / Discriminant;
   bm = (W*wxy - wx*wy) / Discriminant;

   chi2 = 0;
   for (int i=0; i<gr2->GetN(); ++i)
   {
      Double_t x = gr2->GetX()[i];
      Double_t y = gr2->GetY()[i];
      Double_t yerror = gr2->GetEY()[i];
      Double_t yfit = am + bm*x;
      Double_t r = (y - yfit) / yerror;
      chi2 += r*r;
   }
   chi2ndf = chi2 / (gr2->GetN() - 2);

   cout<< "--> fast straight line fit: am " << am << " bm " << bm << " chi2ndf = " << chi2ndf / dy <<endl;

   // optimized

   cout<< "optimized fit with equal weights" <<endl;

   wx = wy = wxy = wx2 = W = 0;
   W = n2;              // the number of points
   for (int i=0; i<n2; ++i)
   {
      Double_t x = x2[i];
      Double_t y = y2[i];
      wx += x;
      wx2 += x*x;
      wy += y;
      wxy += x*y;
   }

   Discriminant = W*wx2 - wx*wx;
   am = (wy*wx2 - wxy*wx) / Discriminant;    // y = am + bm*x
   bm = (W*wxy - wx*wy) / Discriminant;

   chi2 = 0;
   for (int i=0; i<n2; ++i)
   {
      Double_t x = x2[i];
      Double_t y = y2[i];
      Double_t yfit = am + bm*x;
      Double_t r = y - yfit;
      chi2 += r*r;
   }
   chi2ndf = chi2 / (n2-2);
   cout<< "normalize chi2ndf to dy = 10. NB: in current dataset the weights are different!" <<endl;
   chi2ndf /= dy;

   cout<< "--> fast straight line fit: am " << am << " bm " << bm << " chi2ndf = " << chi2ndf <<endl;

   chi2ndf = pol1fast(nf,xf,yf, am,bm);
   cout<< "pol1fast(nf,xf,yf, am,bm) / dy = " << chi2ndf / dy << " am " << am << " bm " << bm <<endl;

   // version optimized for point.C
   chi2ndf = pol1fast(xf,yf,0,nf, am,bm);
   cout<< "pol1fast(xf,yf,0,nf, am,bm) / dy = " << chi2ndf / dy << " am " << am << " bm " << bm <<endl;
}
Esempio n. 28
0
void FluxErr_nomcheck(){
    
    //TFile *fop = TFile::Open("/home/kikawa/for_pm_v3/flux_cov/flux_cov_full.root");
    TFile *fop = TFile::Open("/home/cvson/cc1picoh/syst/flux_cov_full.root");
    TMatrixDSym *mat = (TMatrixDSym*)fop->Get("flux_cov");
    if(mat==NULL){
        cout << "Cannot get matrix from " << fop->GetPath() << endl;
        exit;
    }
    
    float cov_mat[nbin][nbin];
    for(int i=0; i<nbin; i++)
        for(int j=0; j<nbin; j++)
            cov_mat[i][j] = (*mat)(i+258, j+258);
    
#ifdef MKPLOT
    draw_matrix(cov_mat);
#endif
    
    float chol_mat[nbin][nbin];
    cholcov_conv(cov_mat, chol_mat);
    
#ifdef MKPLOT
    draw_matrix(chol_mat);
#endif
    
    int nthrows = 1000000;
    float weight[nbin],nrand[nbin];
    TH1F*  hqeint;
    TH1F*  hqedet;
    TH1F*  hnqeint;
    TH1F*  hnqedet;
    TH1F*  hflux;
    
    //TFile *fccqe  = new TFile("cccoh.root");
    //TFile *fccqe  = new TFile("cccoh_frkikawa.root");
    //TFile *fccqe  = new TFile("cccoh_mva.root");
    TFile *fccqe  = new TFile("cccoh_nomcheck.root");
    
    hqeint  = (TH1F*)fccqe  -> Get("qeint");//all signal
    
    hnqeint  = (TH1F*)fccqe  -> Get("nqeint");//all background
    
    hqedet  = (TH1F*)fccqe  -> Get("qedet");//all signal-selected
    
    hnqedet  = (TH1F*)fccqe  -> Get("nqedet");// all background-selected
    
    hflux   = (TH1F*)fccqe  -> Get("flux");
    
    
    //TFile *fout = new TFile("toymc_nom.root","recreate");
    TFile *fout = new TFile("toymc_nomcheck.root","recreate");
    
    TTree *tree = new TTree("tree","tree");
    //float pm,ing,pm_int,ing_int,pm_det,ing_det;
    //float pm_ccint,ing_ccint,pm_ccdet,ing_ccdet,pm_ncint,ing_ncint,pm_ncdet,ing_ncdet,pm_cceff,ing_cceff,pm_nceff,ing_nceff,pm_flux,ing_flux;
    
    float qeint,nqeint,
    qedet,nqedet,
    qeeff,nqeeff,
    flux;
    
    tree->Branch("qeint",&qeint,"qeint/F");//all signal interaction
    tree->Branch("nqeint",&nqeint,"nqeint/F");//all background interaction
    
    tree->Branch("qedet",&qedet,"qedet/F");// all selected-signal
    
    tree->Branch("nqedet",&nqedet,"nqedet/F");//all selected-background
    
    tree->Branch("qeeff",&qeeff,"qeeff/F");//efficiency of signal selection
    
    tree->Branch("nqeeff",&nqeeff,"nqeeff/F");//efficiency of background selection
    
    tree->Branch("flux",&flux,"flux/F");
    
    
    //float pm0_ccint=0,ing0_ccint=0,pm0_ccdet=0,ing0_ccdet=0,pm0_ncint=0,ing0_ncint=0,pm0_ncdet=0,ing0_ncdet=0,pm0_cceff=0,ing0_cceff=0,pm0_nceff=0,ing0_nceff=0,pm0_flux=0,ing0_flux=0;
    
    float qeint_nomi=0,nqeint_nomi=0,
    qedet_nomi=0,nqedet_nomi=0,
    qeeff_nomi=0,nqeeff_nomi=0,
    flux_nomi=0;
    
    
    for(int j=0;j<nbin;j++){
        qeint_nomi   += hqeint   -> GetBinContent(j+1);
        nqeint_nomi  += hnqeint  -> GetBinContent(j+1);
        qedet_nomi  += hqedet  -> GetBinContent(j+1);
        nqedet_nomi += hnqedet -> GetBinContent(j+1);
        flux_nomi    += hflux    -> GetBinContent(j+1);
    }
    //make toy simulation
    for(int i=0;i<nthrows;i++){
        if(i%10000==0)cout<<i<<endl;
        //pm_ccint=0,ing_ccint=0,pm_ccdet=0,ing_ccdet=0,pm_ncint=0,ing_ncint=0,pm_ncdet=0,ing_ncdet=0,pm_cceff=0,ing_cceff=0,pm_nceff=0,ing_nceff=0,pm_flux=0,ing_flux=0;
        qeint=0;nqeint=0;
        qedet=0;nqedet=0;
        qeeff=0;nqeeff=0;
        flux=0;
        
        for(int k=0;k<nbin;k++){
            nrand[k]=rand.Gaus();//gaussian random
        }
        
        //fluctuate the weight
        for(int j=0;j<nbin;j++){
            weight[j]=1;
            for(int k=0;k<=j;k++){
                weight[j]+=chol_mat[j][k]*nrand[k];
            }
            
            qeint   += hqeint   -> GetBinContent(j+1)*weight[j];
            nqeint  += hnqeint  -> GetBinContent(j+1)*weight[j];
            qedet  += hqedet  -> GetBinContent(j+1)*weight[j];
            nqedet += hnqedet -> GetBinContent(j+1)*weight[j];
            flux    += hflux    -> GetBinContent(j+1)*weight[j];
            
        }
        
        
        qeint    /=   qeint_nomi;
        nqeint   /=   nqeint_nomi;
        qedet   /=   qedet_nomi;
        nqedet  /=   nqedet_nomi;
        flux     /=   flux_nomi;
        
        qeeff  = qedet/qeint;
        nqeeff = nqedet/nqeint;
        
        tree->Fill();
    }
    tree->Write();
    
    hqedet  ->Write();
    hnqedet ->Write();
    
    fout->Close();
}
Esempio n. 29
0
void RAA_dataDrivenUnfoldingErrorCheck(int radius = 4, int radiusPP = 4, char* algo = (char*) "Pu", char *jet_type = (char*) "PF", int unfoldingCut = 30, char* etaWidth = (char*) "n20_eta_p20", double deltaEta = 4.0){

  TStopwatch timer; 
  timer.Start();
  
  TH1::SetDefaultSumw2();
  TH2::SetDefaultSumw2();
  
  bool printDebug = true;

  // get the data and mc histograms from the output of the read macro. 
  
  TDatime date;//this is just here to get them to run optimized. 

  // Raghav's files: 
  //TFile * fPbPb_in = TFile::Open(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/CMSSW_5_3_18/src/Output/PbPb_CutEfficiency_YetkinCuts_matched_slantedlinecalopfpt_addingunmatched_exclusionhighertriggers_eMaxSumcand_A_R0p%d.root",radius));
  //  //TFile * fPP_in = TFile::Open(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/CMSSW_5_3_18/src/Output/Pp_CutEfficiency_YetkinCuts_matched_slantedlinecalopfpt_addingunmatched_exclusionhighertriggers_eMaxSumcand_A_R0p%d.root",radius));
  //TFile * fPP_in = TFile::Open(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/CMSSW_5_3_18/src/Output/Pp_CutEfficiency_noJetID_exclusionhighertriggers_A_R0p%d.root",radius));

  // Pawan's files:
  TFile * fPbPb_in = TFile::Open(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/CMSSW_5_3_18/src/Output/Pawan_ntuplehistograms/PbPb_CutEfficiency_YetkinCuts_matched_slantedlinecalopfpt_addingunmatched_exclusionhighertriggers_eMaxSumcand_A_R0p%d.root",radius));
  //TFile * fPP_in = TFile::Open(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/CMSSW_5_3_18/src/Output/Pp_CutEfficiency_YetkinCuts_matched_slantedlinecalopfpt_addingunmatched_exclusionhighertriggers_eMaxSumcand_A_R0p%d.root",radius));
  TFile * fPP_in = TFile::Open(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/CMSSW_5_3_18/src/Output/Pawan_ntuplehistograms/Pp_CutEfficiency_YetkinCuts_matched_slantedlinecalopfpt_addingunmatched_exclusionhighertriggers_eMaxSumcand_A_R0p%d.root",radius));

  TFile * fPbPb_MB_in = TFile::Open(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/CMSSW_5_3_18/src/Output/PbPb_MinBiasUPC_CutEfficiency_YetkinCuts_matched_slantedlinecalopfpt_addingunmatched_exclusionhighertriggers_eMaxSumcand_A_R0p%d.root",radius));


  
  //TH1F * htest = new TH1F("htest","",nbins_pt, boundaries_pt);
  //Int_t unfoldingCutBin = htest->FindBin(unfoldingCut);
  
  cout<<"after input file declaration"<<endl;
  // need to make sure that the file names are in prefect order so that i can run them one after another. 
  // for the above condition, i might have to play with the date stamp. 
  
  const int nbins_cent = 6;
  double boundaries_cent[nbins_cent+1] = {0,2,4,12,20,28,36};
  double ncoll[nbins_cent+1] = {1660,1310,745,251,62.8,10.8,362.24};
  
  // histogram declarations with the following initial appendage: d - Data, m - MC, u- Unfolded
  // for the MC closure test, ive kept separate 

  // setup the radius and the eta bin loop here later. not for the time being. Aug 20th. only run the -2 < eta < 2 with the differenent centrality bins 

  TH1F *dPbPb_TrgComb[nbins_cent+1], *dPbPb_Comb[nbins_cent+1], *dPbPb_Trg80[nbins_cent+1], *dPbPb_Trg65[nbins_cent+1], *dPbPb_Trg55[nbins_cent+1], *dPbPb_1[nbins_cent+1], *dPbPb_2[nbins_cent+1], *dPbPb_3[nbins_cent+1], *dPbPb_80[nbins_cent+1], *dPbPb_65[nbins_cent+1], *dPbPb_55[nbins_cent+1];
  
  TH1F *mPbPb_Gen[nbins_cent+1], *mPbPb_Reco[nbins_cent+1];
  TH2F *mPbPb_Matrix[nbins_cent+1], *mPbPb_Response[nbins_cent+1], *mPbPb_ResponseNorm[nbins_cent+1];
  TH1F *mPbPb_mcclosure_data[nbins_cent+1];
  TH2F *mPbPb_mcclosure_Matrix[nbins_cent+1],*mPbPb_mcclosure_Response[nbins_cent+1], *mPbPb_mcclosure_ResponseNorm[nbins_cent+1];
  TH1F *mPbPb_mcclosure_gen[nbins_cent+1];
  const int Iterations = 20; //for unfolding systematics. 
  const int BayesIter = 4;
  TH1F *uPbPb_Bayes[nbins_cent+1], *uPbPb_BinByBin[nbins_cent+1], *uPbPb_SVD[nbins_cent+1]; 
  TH1F *uPbPb_BayesianIter[nbins_cent+1][Iterations];
  TH1F *dPbPb_MinBias[nbins_cent];
  
  TH1F *dPP_1, *dPP_2, *dPP_3, *dPP_Comb;
  TH1F *mPP_Gen, *mPP_Reco;
  TH2F *mPP_Matrix, *mPP_Response,*mPP_ResponseNorm;
  TH1F *mPP_mcclosure_data;
  TH2F *mPP_mcclosure_Matrix, *mPP_mcclosure_Response,*mPP_mcclosure_ResponseNorm;
  TH1F *mPP_mcclosure_Gen;
  TH1F *uPP_Bayes, *uPP_BinByBin, *uPP_SVD;
  TH1F *uPP_BayesianIter[Iterations];

  // would be better to read in the histograms and rebin them. come to think of it, it would be better to have them already rebinned (and properly scaled - to the level of differential cross section in what ever barns (inverse micro barns) but keep it consistent) from the read macro. 

  // get PbPb data
  for(int i = 0;i<nbins_cent;i++){
    if(printDebug) cout<<"cent_"<<i<<endl;
    dPbPb_TrgComb[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_HLTComb_R%d_n20_eta_p20_cent%d",radius,i));
    //dPbPb_TrgComb[i]->Scale(4*145.156*1e6);
    dPbPb_TrgComb[i]->Print("base");
    dPbPb_Trg80[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_HLT80_R%d_n20_eta_p20_cent%d",radius,i));
    //dPbPb_Trg80[i]->Scale(4*145.156*1e6);
    dPbPb_Trg80[i]->Print("base");
    dPbPb_Trg65[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_HLT65_R%d_n20_eta_p20_cent%d",radius,i));
    //dPbPb_Trg65[i]->Scale(4*145.156*1e6);
    dPbPb_Trg65[i]->Print("base");
    dPbPb_Trg55[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_HLT55_R%d_n20_eta_p20_cent%d",radius,i));
    //dPbPb_Trg55[i]->Scale(4*145.156*1e6);
    dPbPb_Trg55[i]->Print("base");
    //dPbPb_TrgComb[i] = (TH1F*)dPbPb_Trg80[i]->Clone(Form("Jet_80_triggered_spectra_data_PbPb_cent%d",i));
    
    //dPbPb_MinBias[i] = (TH1F*)fPbPb_MB_in->Get(Form("hpbpb_HLTComb_R%d_n20_eta_p20_cent%d",radius,i));
    //dPbPb_MinBias[i]->Print("base");
    dPbPb_TrgComb[i]->Scale(1./(145.156 * 1e9));
    //dPbPb_MinBias[i]->Scale(1./(161.939 * 1e9));
    
    //dPbPb_TrgComb[i]->Add(dPbPb_MinBias[i]);
    
    for(int k = 1;k<=unfoldingCut;k++) {
      dPbPb_TrgComb[i]->SetBinContent(k,0);
      dPbPb_Trg80[i]->SetBinContent(k,0);
      dPbPb_Trg65[i]->SetBinContent(k,0);
      dPbPb_Trg55[i]->SetBinContent(k,0);
    }
    
  }
  
  //Int_t nSVDIter = 4;
  
  if(printDebug)cout<<"loaded the data histograms PbPb"<<endl;
  // get PbPb MC
  for(int i = 0;i<nbins_cent;i++){
    
    mPbPb_Gen[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_JetComb_gen_R%d_n20_eta_p20_cent%d",radius,i));
    //mPbPb_Gen[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_gen_R%d_n20_eta_p20_cent%d",radius,i));
    mPbPb_Gen[i]->Print("base");
    mPbPb_Reco[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_JetComb_reco_R%d_n20_eta_p20_cent%d",radius,i));
    //mPbPb_Reco[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_reco_R%d_n20_eta_p20_cent%d",radius,i));
    mPbPb_Reco[i]->Print("base");
    mPbPb_Matrix[i] = (TH2F*)fPbPb_in->Get(Form("hpbpb_matrix_HLT_R%d_n20_eta_p20_cent%d",radius,i));
    //mPbPb_Matrix[i] = (TH2F*)fPbPb_in->Get(Form("hpbpb_matrix_R%d_n20_eta_p20_cent%d",radius,i));
    mPbPb_Matrix[i]->Print("base");
    mPbPb_mcclosure_data[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_mcclosure_JetComb_data_R%d_n20_eta_p20_cent%d",radius,i));
    mPbPb_mcclosure_data[i]->Print("base");
    mPbPb_mcclosure_gen[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_mcclosure_gen_JetComb_R%d_n20_eta_p20_cent%d",radius,i));
    mPbPb_mcclosure_gen[i]->Print("base");
    mPbPb_mcclosure_Matrix[i] = (TH2F*)fPbPb_in->Get(Form("hpbpb_mcclosure_matrix_HLT_R%d_n20_eta_p20_cent%d",radius,i));
    mPbPb_mcclosure_Matrix[i]->Print("base");
    
    //since SVD is very straight forward, lets do it rignt here:
    //get the SVD response matrix:
    //RooUnfoldResponse ruResponse(mPbPb_Matrix[i]->ProjectionY(),mPbPb_Matrix[i]->ProjectionX(), mPbPb_Matrix[i],"","");
    //regularization parameter definition: 
    //RooUnfoldSvd unfoldSvd(&ruResponse, dPbPb_TrgComb[i], nSVDIter);
    //uPbPb_SVD[i] = (TH1F*)unfoldSvd.Hreco();
  
    
    // for(int k = 1;k<=unfoldingCut;k++){

    //   mPbPb_Gen[i]->SetBinContent(k,0);
    //   mPbPb_Reco[i]->SetBinContent(k,0);
    //   mPbPb_mcclosure_data[i]->SetBinContent(k,0);
    //   mPbPb_mcclosure_gen[i]->SetBinContent(k,0);
    //   for(int l = 1;l<=1000;l++){
    // 	mPbPb_Matrix[i]->SetBinContent(k,l,0);
    // 	mPbPb_mcclosure_Matrix[i]->SetBinContent(k,l,0);
    // 	mPbPb_Matrix[i]->SetBinContent(l,k,0);
    // 	mPbPb_mcclosure_Matrix[i]->SetBinContent(l,k,0);	
    //   }
    // }
    
    //mPbPb_Response[i] = new TH2F(Form("mPbPb_Response_cent%d",i),"Response Matrix",nbins_pt,boundaries_pt,nbins_pt,boundaries_pt);
    //mPbPb_ResponseNorm[i] = new TH2F(Form("mPbPb_ResponseNorm_cent%d",i),"Normalized Response Matrix",nbins_pt,boundaries_pt,nbins_pt,boundaries_pt);
  }
  
  if(printDebug) cout<<"loaded the data and mc PbPb histograms from the files"<<endl;

  // get PP data
  if(printDebug) cout<<"Getting PP data and MC"<<endl;
  dPP_1 = (TH1F*)fPP_in->Get(Form("hpp_HLT80_R%d_%s",radiusPP,etaWidth)); 
  dPP_1->Print("base");
  dPP_2 = (TH1F*)fPP_in->Get(Form("hpp_HLT60_R%d_%s",radiusPP,etaWidth));
  dPP_2->Print("base");
  dPP_3 = (TH1F*)fPP_in->Get(Form("hpp_HLT40_R%d_%s",radiusPP,etaWidth));
  dPP_3->Print("base");
  dPP_Comb = (TH1F*)fPP_in->Get(Form("hpp_HLTComb_R%d_%s",radiusPP,etaWidth));   
  //dPP_Comb = (TH1F*)dPP_1->Clone(Form("hpp_TrgComb_R%d_n20_eta_p20",radiusPP,etaWidth));   
  dPP_Comb->Print("base");

  dPP_Comb->Scale(1./(5.3 * 1e9));
  
  for(int k = 1;k<=unfoldingCut;k++) {
    dPP_Comb->SetBinContent(k,0);
    dPP_1->SetBinContent(k,0);
    dPP_2->SetBinContent(k,0);
    dPP_3->SetBinContent(k,0);
  }
  
  // get PP MC
  mPP_Gen = (TH1F*)fPP_in->Get(Form("hpp_JetComb_gen_R%d_%s",radiusPP,etaWidth));
  mPP_Gen->Print("base");
  mPP_Reco = (TH1F*)fPP_in->Get(Form("hpp_JetComb_reco_R%d_%s",radiusPP,etaWidth));
  mPP_Reco->Print("base");
  mPP_Matrix = (TH2F*)fPP_in->Get(Form("hpp_matrix_HLT_R%d_%s",radiusPP,etaWidth));
  mPP_Matrix->Print("base");
  mPP_mcclosure_data = (TH1F*)fPP_in->Get(Form("hpp_mcclosure_JetComb_data_R%d_%s",radiusPP,etaWidth));
  mPP_mcclosure_data->Print("base");
  mPP_mcclosure_Matrix = (TH2F*)fPP_in->Get(Form("hpp_mcclosure_matrix_HLT_R%d_%s",radiusPP,etaWidth));
  mPP_mcclosure_Matrix->Print("base");

  //RooUnfoldResponse ruResponsePP(mPP_Matrix->ProjectionY(),mPP_Matrix->ProjectionX(), mPP_Matrix,"","");
  //regularization parameter definition: 
  //RooUnfoldSvd unfoldSvdPP(&ruResponsePP, dPP_Comb, nSVDIter);
  //uPP_SVD = (TH1F*)unfoldSvdPP.Hreco();

  
  // for(int k = 1;k<=unfoldingCut;k++){
  //   mPP_Gen->SetBinContent(k,0);
  //   mPP_Reco->SetBinContent(k,0);
  //   mPP_mcclosure_data->SetBinContent(k,0);
  //   for(int l = 1;l<=1000;l++){
  //     mPP_Matrix->SetBinContent(k,l,0);
  //     mPP_mcclosure_Matrix->SetBinContent(k,l,0);
  //     mPP_Matrix->SetBinContent(l,k,0);
  //     mPP_mcclosure_Matrix->SetBinContent(l,k,0);
  //   }
  // }

  
  if(printDebug) cout<<"Filling the PbPb response Matrix"<<endl;

  // response matrix and unfolding for PbPb 
  // going to try it the way kurt has it. 

  for(int i = 0;i<nbins_cent;i++){
    if(printDebug) cout<<"centrality bin iteration = "<<i<<endl;
    TF1 *f = new TF1("f","[0]*pow(x+[2],[1])");
    f->SetParameters(1e10,-8.8,40);
    // TH1F *hGenSpectraCorr = (TH1F*)mPbPb_Matrix[i]->ProjectionX()->Clone(Form("hGenSpectraCorr_cent%d",i));
    // hGenSpectraCorr->Fit("f"," ");
    // hGenSpectraCorr->Fit("f","","");
    // hGenSpectraCorr->Fit("f","LL");
    // TH1F *fHist = functionHist(f,hGenSpectraCorr,Form("fHist_cent%d",i));// function that you get from the fitting 
    // hGenSpectraCorr->Divide(fHist);
    for (int y=1;y<=mPbPb_Matrix[i]->GetNbinsY();y++) {
      double sum=0;
      for (int x=1;x<=mPbPb_Matrix[i]->GetNbinsX();x++) {
	if (mPbPb_Matrix[i]->GetBinContent(x,y)<=1*mPbPb_Matrix[i]->GetBinError(x,y)) {
	  //in the above line mine had 0*getbinerror while Kurt's had 1*. 
	  mPbPb_Matrix[i]->SetBinContent(x,y,0);
	  mPbPb_Matrix[i]->SetBinError(x,y,0);
	}
	sum+=mPbPb_Matrix[i]->GetBinContent(x,y);
      }
      
      for (int x=1;x<=mPbPb_Matrix[i]->GetNbinsX();x++) {	   
	double ratio = 1;
	// if (hGenSpectraCorr->GetBinContent(x)!=0) ratio = 1e5/hGenSpectraCorr->GetBinContent(x);
	mPbPb_Matrix[i]->SetBinContent(x,y,mPbPb_Matrix[i]->GetBinContent(x,y)*ratio);
	mPbPb_Matrix[i]->SetBinError(x,y,mPbPb_Matrix[i]->GetBinError(x,y)*ratio);
      }
    }
    //mPbPb_Matrix[i]->Smooth(0);
    // Ok major differences here between my code and Kurt in b-jet Tools under Unfold - lines 469 and above.  
    
    mPbPb_Response[i] = (TH2F*)mPbPb_Matrix[i]->Clone(Form("mPbPb_Response_cent%d",i));
    TH1F *hProj = (TH1F*)mPbPb_Response[i]->ProjectionY()->Clone(Form("hProj_cent%d",i));

    for (int y=1;y<=mPbPb_Response[i]->GetNbinsY();y++) {
      double sum=0;
      for (int x=1;x<=mPbPb_Response[i]->GetNbinsX();x++) {
	if (mPbPb_Response[i]->GetBinContent(x,y)<=1*mPbPb_Response[i]->GetBinError(x,y)) {
	  // in the above if loop, kurt has 1*error and my old had 0*error
	  mPbPb_Response[i]->SetBinContent(x,y,0);
	  mPbPb_Response[i]->SetBinError(x,y,0);
	}
	sum+=mPbPb_Response[i]->GetBinContent(x,y);
      }
      
      for (int x=1;x<=mPbPb_Response[i]->GetNbinsX();x++) {  	
	if (sum==0) continue;
	double ratio = 1;
	//if(dPbPb_TrgComb[i]->GetBinContent(y)==0) ratio = 1e-100/sum;
	// else ratio = dPbPb_TrgComb[i]->GetBinContent(y)/sum
	ratio = 1./sum;
	if (hProj->GetBinContent(y)==0) ratio = 1e-100/sum;
	else ratio = hProj->GetBinContent(y)/sum;
	mPbPb_Response[i]->SetBinContent(x,y,mPbPb_Response[i]->GetBinContent(x,y)*ratio);
	mPbPb_Response[i]->SetBinError(x,y,mPbPb_Response[i]->GetBinError(x,y)*ratio);
      }
    }
    
    mPbPb_ResponseNorm[i] = (TH2F*)mPbPb_Matrix[i]->Clone(Form("mPbPb_ResponseNorm_cent%d",i));
    for (int x=1;x<=mPbPb_ResponseNorm[i]->GetNbinsX();x++) {
      double sum=0;
      for (int y=1;y<=mPbPb_ResponseNorm[i]->GetNbinsY();y++) {
	if (mPbPb_ResponseNorm[i]->GetBinContent(x,y)<=1*mPbPb_ResponseNorm[i]->GetBinError(x,y)) {
	  mPbPb_ResponseNorm[i]->SetBinContent(x,y,0);
	  mPbPb_ResponseNorm[i]->SetBinError(x,y,0);
	}
	sum+=mPbPb_ResponseNorm[i]->GetBinContent(x,y);
      }
      
      for (int y=1;y<=mPbPb_ResponseNorm[i]->GetNbinsY();y++) {  	
	if (sum==0) continue;
	double ratio = 1./sum;
	mPbPb_ResponseNorm[i]->SetBinContent(x,y,mPbPb_ResponseNorm[i]->GetBinContent(x,y)*ratio);
	mPbPb_ResponseNorm[i]->SetBinError(x,y,mPbPb_ResponseNorm[i]->GetBinError(x,y)*ratio);
      }
      
    }
    
    
  }

  
  if(printDebug) cout<<"Filling PP response Matrix"<<endl;

  // response matrix for pp.  
  // Kurt doesnt have this whole hGenSpectraCorr thing in his macro. need to check why the difference exists between out codes
  
  TF1 *fpp = new TF1("fpp","[0]*pow(x+[2],[1])");
  fpp->SetParameters(1e10,-8.8,40);
  // if(printDebug) cout<<"before getting the gen spectra corr matrix"<<endl;
  // TH1F *hGenSpectraCorrPP = (TH1F*)mPP_Matrix->ProjectionX()->Clone("hGenSpectraCorrPP");
  // if(printDebug) cout<<"after gettign the gen spectra corr matrix"<<endl;
  // hGenSpectraCorrPP->Fit("f"," ");
  // hGenSpectraCorrPP->Fit("f","","");
  // hGenSpectraCorrPP->Fit("f","LL");
  // TH1F *fHistPP = functionHist(fpp,hGenSpectraCorrPP,"fHistPP");// that the function that you get from the fitting 
  // hGenSpectraCorrPP->Divide(fHistPP);
  
  for (int y=1;y<=mPP_Matrix->GetNbinsY();y++) {
    double sum=0;
    for (int x=1;x<=mPP_Matrix->GetNbinsX();x++) {
      if (mPP_Matrix->GetBinContent(x,y)<=1*mPP_Matrix->GetBinError(x,y)) {
	mPP_Matrix->SetBinContent(x,y,0);
	mPP_Matrix->SetBinError(x,y,0);
      }
      sum+=mPP_Matrix->GetBinContent(x,y);
    }
    
    for (int x=1;x<=mPP_Matrix->GetNbinsX();x++) {	   
      double ratio = 1;
      // if (hGenSpectraCorrPP->GetBinContent(x)!=0) ratio = 1e5/hGenSpectraCorrPP->GetBinContent(x);
      mPP_Matrix->SetBinContent(x,y,mPP_Matrix->GetBinContent(x,y)*ratio);
      mPP_Matrix->SetBinError(x,y,mPP_Matrix->GetBinError(x,y)*ratio);
    }
  }
  // mPbPb_Matrix[i]->Smooth(0);
  
  // Ok major differences here between my code and Kurt in b-jet Tools under Unfold - lines 469 and above.  

  if(printDebug) cout<<"getting the response matrix"<<endl;

  mPP_Response = (TH2F*)mPP_Matrix->Clone("mPP_Response");
  TH1F *hProjPP = (TH1F*)mPP_Response->ProjectionY()->Clone("hProjPP");
  
  
  for (int y=1;y<=mPP_Response->GetNbinsY();y++) {
    double sum=0;
    for (int x=1;x<=mPP_Response->GetNbinsX();x++) {
      if (mPP_Response->GetBinContent(x,y)<=1*mPP_Response->GetBinError(x,y)) {
	// in the above if statement, kurt has 1*error and my old has 0*error
	mPP_Response->SetBinContent(x,y,0);
	mPP_Response->SetBinError(x,y,0);
      }
      sum+=mPP_Response->GetBinContent(x,y);
    }
    
    for (int x=1;x<=mPP_Response->GetNbinsX();x++) {  	
      if (sum==0) continue;
      double ratio = 1;
      //if(dPbPb_TrgComb[i]->GetBinContent(y)==0) ratio = 1e-100/sum;
      // else ratio = dPbPb_TrgComb[i]->GetBinContent(y)/sum
      ratio = 1./sum;
      if (hProjPP->GetBinContent(y)==0) ratio = 1e-100/sum;
      else ratio = hProjPP->GetBinContent(y)/sum;
      mPP_Response->SetBinContent(x,y,mPP_Response->GetBinContent(x,y)*ratio);
      mPP_Response->SetBinError(x,y,mPP_Response->GetBinError(x,y)*ratio);
    }
  }
  if(printDebug) cout<<"getting the normalized response matrix"<<endl;
  mPP_ResponseNorm = (TH2F*)mPP_Matrix->Clone("mPP_ResponseNorm");
  for (int x=1;x<=mPP_ResponseNorm->GetNbinsX();x++) {
    double sum=0;
    for (int y=1;y<=mPP_ResponseNorm->GetNbinsY();y++) {
      if (mPP_ResponseNorm->GetBinContent(x,y)<=1*mPP_ResponseNorm->GetBinError(x,y)) {
	mPP_ResponseNorm->SetBinContent(x,y,0);
	mPP_ResponseNorm->SetBinError(x,y,0);
      }
      sum+=mPP_ResponseNorm->GetBinContent(x,y);
    }
    
    for (int y=1;y<=mPP_ResponseNorm->GetNbinsY();y++) {  	
      if (sum==0) continue;
      double ratio = 1./sum;
      mPP_ResponseNorm->SetBinContent(x,y,mPP_ResponseNorm->GetBinContent(x,y)*ratio);
      mPP_ResponseNorm->SetBinError(x,y,mPP_ResponseNorm->GetBinError(x,y)*ratio);
    }
    
    
  }
  
  // scale the spectra to the respective units

  // for(int i = 0;i<nbins_cent;++i){
  //   dPbPb_TrgComb[i] = (TH1F*)dPbPb_TrgComb[i]->Rebin(nbins_pt,Form("PbPb_measured_spectra_combined_cent%d",i),boundaries_pt);
  //   divideBinWidth(dPbPb_TrgComb[i]);
  // }

  // dPP_Comb = (TH1F*)dPP_Comb->Rebin(nbins_pt,"pp_measured_spectra_combined",boundaries_pt);
  // divideBinWidth(dPP_Comb);
  // dPP_Comb->Scale(1./ dPP_Comb->GetBinContent(nbins_pt));
  
  // Now that we have all the response matrix for the 6 centralities in PbPb and one pp spectra lets start doing the steps:
  // we have 39 pt bins, so we need 1000 gaussian functions for each pt bin.
  
  Int_t unfoldingTrials = 200;
  Double_t meanMeasPbPb[nbins_pt][nbins_cent], sigmaMeasPbPb[nbins_pt][nbins_cent];
  Double_t meanMeasPP[nbins_pt], sigmaMeasPP[nbins_pt];
  Double_t meanUnfoldPbPb[nbins_pt][nbins_cent][unfoldingTrials], sigmaUnfoldPbPb[nbins_pt][nbins_cent][unfoldingTrials];
  Double_t meanUnfoldPP[nbins_pt][unfoldingTrials], sigmaUnfoldPP[nbins_pt][unfoldingTrials]; 
  
  TRandom3 *random = new TRandom3(0);

  for(int u = 0;u<unfoldingTrials;++u){
    cout<<"unfolding trial no = "<<u+1<<endl;
  
    for(int j = 0;j<nbins_pt;++j){
      for(int i = 0;i<nbins_cent;++i){
      
	meanMeasPbPb[j][i] = dPbPb_TrgComb[i]->GetBinContent(j+1);
	sigmaMeasPbPb[j][i] = dPbPb_TrgComb[i]->GetBinError(j+1);

      }// centrality loop

      meanMeasPP[j] = dPP_Comb->GetBinContent(j+1);
      sigmaMeasPP[j] = dPP_Comb->GetBinContent(j+1);
      
    }// nbins_pt loop

    // now proceed to unfolding for each trial.

    for(int i = 0;i<nbins_cent;++i){
      //cout<<"centrality = "<<i<<endl;

      TH1F * hPreUnfoldingSpectra = new TH1F("hPreUnfoldingSpectra","",nbins_pt,0,nbins_pt);
      TH1F * hAfterUnfoldingSpectra;

      for(int j = 0;j<nbins_pt;++j){
	
	hPreUnfoldingSpectra->SetBinContent(j+1, random->Gaus(meanMeasPbPb[j][i], sigmaMeasPbPb[j][i]));
	hPreUnfoldingSpectra->SetBinError(j+1, sigmaMeasPbPb[j][i]/sqrt(unfoldingTrials));
        //if(j==100)cout << " before unfolding bin " << j << " value = " << hPreUnfoldingSpectra->GetBinContent(j+1)<<endl;
        //if(j==100)cout << " before unfolding bin " << j << " error = " << hPreUnfoldingSpectra->GetBinError(j+1)<<endl;
	
      }// nbins_pt loop

      TH1F* hMCGen          = (TH1F*)mPbPb_Response[i]->ProjectionX();
      removeZero(hMCGen);
      //cout << " MC bin " << 100 << " value = " << hMCGen->GetBinContent(100)<<endl;
      bayesianUnfold myUnfoldingMulti(mPbPb_Matrix[i], hMCGen, 0);
      myUnfoldingMulti.unfold(hPreUnfoldingSpectra, BayesIter);

      hAfterUnfoldingSpectra = (TH1F*) myUnfoldingMulti.hPrior->Clone("hAfterUnfoldingSpectra");

      for(int j = 0;j<nbins_pt;++j){
	
	//if(j==100)cout << " before unfolding bin " << j << " value = " << hPreUnfoldingSpectra->GetBinContent(j+1)<<endl;
	//if(j==100)cout << " after  unfolding bin " << j << " value = " << hAfterUnfoldingSpectra->GetBinContent(j+1)<<endl;
	
	meanUnfoldPbPb[j][i][u] = hAfterUnfoldingSpectra->GetBinContent(j+1);
	sigmaUnfoldPbPb[j][i][u] = hAfterUnfoldingSpectra->GetBinError(j+1);

	// cout << "after unfolding meanUnfoldPbPb[" << j << "][" << i << "][" << u<< "] = " <<meanUnfoldPbPb[j][i][u]<<"    ";
	// cout << "after unfolding meanUnfoldPbPb[" << j << "][" << i << "][" << u<< "] = " <<sigmaUnfoldPbPb[j][i][u]<<endl;
	
      }// nbins_pt loop
      
      //hPreUnfoldingSpectra->Print("base");
      //hAfterUnfoldingSpectra->Print("base");
      
      delete hPreUnfoldingSpectra;
      delete hAfterUnfoldingSpectra;
      delete hMCGen; 
      
    }// centrality loop

    cout<<"pp "<<endl;

    // now do it for the pp:
    TH1F * hPreUnfoldingSpectraPP = new TH1F("hPreUnfoldingSpectraPP","",nbins_pt,0,nbins_pt);
    TH1F * hAfterUnfoldingSpectraPP;
    
    for(int j = 0;j<nbins_pt;++j){
	
      hPreUnfoldingSpectraPP->SetBinContent(j+1, random->Gaus(meanMeasPP[j], sigmaMeasPP[j]));
      hPreUnfoldingSpectraPP->SetBinError(j+1, sigmaMeasPP[j]/sqrt(unfoldingTrials));
        
    }// nbins_pt loop
    TH1F* hMCGenPP          = (TH1F*)mPP_Response->ProjectionX();
    removeZero(hMCGenPP);
    bayesianUnfold myUnfoldingMultiPP(mPP_Matrix, hMCGenPP, 0);
    myUnfoldingMultiPP.unfold(hPreUnfoldingSpectraPP, BayesIter);

    hAfterUnfoldingSpectraPP = (TH1F*) myUnfoldingMultiPP.hPrior->Clone("hAfterUnfoldingSpectraPP");

    for(int j = 0;j<nbins_pt;++j){

      meanUnfoldPP[j][u] = hAfterUnfoldingSpectraPP->GetBinContent(j+1);
      sigmaUnfoldPP[j][u] = hAfterUnfoldingSpectraPP->GetBinError(j+1);

    }// nbins_pt loop

    delete hPreUnfoldingSpectraPP;
    delete hAfterUnfoldingSpectraPP;
    delete hMCGenPP; 
    
  }// unfolding trials loop


  // Now that we have all the necesary values we need, lets proceed to fill a histogram with the mean values for each ptbin and get the corrected values.
  TH1F * hAfterUnfoldingptBinDistribution[nbins_pt];
  TH1F * hCorrUnfoldingPbPb[nbins_cent];
  
  for(int i = 0;i<nbins_cent;++i){

    hCorrUnfoldingPbPb[i] = new TH1F(Form("PbPb_BayesianUnfolded_cent%d",i),"Spectra after correction", nbins_pt, 0, nbins_pt);

    for(int j = 0;j<nbins_pt;++j){
      
      //hAfterUnfoldingptBinDistribution[j] = new TH1F(Form("hAfterUnfoldingptBinDistribution_ptBin%d",j),"",100,	(meanMeasPbPb[j][i]-10) * sigmaMeasPbPb[j][i], (meanMeasPbPb[j][i]+10) * sigmaMeasPbPb[j][i]);
      hAfterUnfoldingptBinDistribution[j] = new TH1F(Form("hAfterUnfoldingptBinDistribution_ptBin%d",j),"",100,	0, 1);
      for(int u = 0;u<unfoldingTrials;++u){

	hAfterUnfoldingptBinDistribution[j]->Fill(meanUnfoldPbPb[j][i][u]);

	//if(j==100) cout<< "unfolding_trial = " << u+1 << " mean unfold value = "<< meanUnfoldPbPb[j][i][u] <<endl;

      }// unfolding trials loop

      //if(j==100) cout<<"Mean of that value for pt=100 = "<< (Float_t)hAfterUnfoldingptBinDistribution[j]->GetMean() <<endl;      
      hCorrUnfoldingPbPb[i]->SetBinContent(j+1, hAfterUnfoldingptBinDistribution[j]->GetMean());
      //cout<<"centrality bin "<<i<<", pT bin "<<j<<" bin Content = "<<hCorrUnfoldingPbPb[i]->GetBinContent(j+1)<<endl;
      hCorrUnfoldingPbPb[i]->SetBinError(j+1, hAfterUnfoldingptBinDistribution[j]->GetRMS());
      //cout<<"centrality bin "<<i<<", pT bin "<<j<<" bin Error   = "<<hCorrUnfoldingPbPb[i]->GetBinError(j+1)<<endl;

      delete hAfterUnfoldingptBinDistribution[j];
      
    }// nbins_pt loop

  }// centrality loop

  // similar for the pp:
  TH1F * hAfterUnfoldingptBinDistributionPP[nbins_pt];
  TH1F * hCorrUnfoldingPP;
  
  hCorrUnfoldingPP = new TH1F("PP_BayesianUnfolded","Spectra after unfolding error correction",nbins_pt, 0, nbins_pt);
  
  for(int j = 0;j<nbins_pt;++j){
    
    //hAfterUnfoldingptBinDistributionPP[j] = new TH1F(Form("hAfterUnfoldingptBinDistributionPP_ptBin%d",j),"",1000,(meanMeasPP[j]-10) * sigmaMeasPP[j], (meanMeasPP[j]+10) * sigmaMeasPP[j]);
    hAfterUnfoldingptBinDistributionPP[j] = new TH1F(Form("hAfterUnfoldingptBinDistributionPP_ptBin%d",j),"",100, 0, 1);
    for(int u = 0;u<unfoldingTrials;++u){
      
      hAfterUnfoldingptBinDistributionPP[j]->Fill(meanUnfoldPP[j][u]);
      
    }// unfolding trials loop
    
    hCorrUnfoldingPP->SetBinContent(j+1, hAfterUnfoldingptBinDistributionPP[j]->GetMean());
    //cout<<"PP pT bin "<<j<<" bin Content = "<<hCorrUnfoldingPP->GetBinContent(j+1)<<endl;
    hCorrUnfoldingPP->SetBinError(j+1, hAfterUnfoldingptBinDistributionPP[j]->GetRMS());
    //cout<<"PP pT bin "<<j<<" bin Error   = "<<hCorrUnfoldingPP->GetBinError(j+1)<<endl;
    
    delete hAfterUnfoldingptBinDistributionPP[j];
    
  }// nbins_pt loop
    
  TFile f(Form("../../Output/Pawan_ntuple_PbPb_R%d_pp_R%d_%s_unfoldingCut_%d_data_driven_correction_ak%s%s_%d.root",radius, radiusPP, etaWidth ,unfoldingCut,algo,jet_type,date.GetDate()),"RECREATE");
  f.cd();

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

    hCorrUnfoldingPbPb[i]->Scale(145.156 * 1e9);
    //hCorrUnfoldingPbPb[i] = (TH1F*)hCorrUnfoldingPbPb[i]->Rebin(nbins_pt_coarse, Form("PbPb_BayesianUnfolded_cent%d",i), boundaries_pt_coarse);
    hCorrUnfoldingPbPb[i]->Write();
    hCorrUnfoldingPbPb[i]->Print("base");

    dPbPb_TrgComb[i]->Scale(145.156 * 1e9);
    //dPbPb_TrgComb[i] = (TH1F*)dPbPb_TrgComb[i]->Rebin(nbins_pt_coarse, Form("PbPb_measured_cent%d",i), boundaries_pt_coarse);
    dPbPb_TrgComb[i]->Write();
    dPbPb_TrgComb[i]->Print("base");
    
  }

  hCorrUnfoldingPP->Scale(5.3 * 1e9);
  //hCorrUnfoldingPP = (TH1F*)hCorrUnfoldingPP->Rebin(nbins_pt_coarse, "PP_BayesianUnfolded", boundaries_pt_coarse);
  hCorrUnfoldingPP->Write();
  hCorrUnfoldingPP->Print("base");
  dPP_Comb->Scale(5.3 * 1e9);
  //dPP_Comb = (TH1F*)dPP_Comb->Rebin(nbins_pt_coarse, "PP_measured", boundaries_pt_coarse);  
  dPP_Comb->Write();
  dPP_Comb->Print("base");
  
  f.Write();
  f.Close();

  timer.Stop();
  if(printDebug) cout<<"CPU time (mins) = "<<(Float_t)timer.CpuTime()/60<<endl;
  if(printDebug) cout<<"Real tile (mins) = "<<(Float_t)timer.RealTime()/60<<endl;
  

}
Esempio n. 30
0
//............................................
// Constructor for accpetance from a ROOT Tfile
SlicedAcceptance::SlicedAcceptance( string type, string fileName,string histName, bool fluctuate, bool quiet ) :
	slices(), nullSlice(new AcceptanceSlice(0.,0.,0.)), tlow(), thigh(), beta(), _sortedSlices(false), maxminset(false), t_min(0.), t_max(0.), _hasChecked(false), _storedDecision(false)
{
	if(!quiet) cout << "Root file being used for acceptance" << endl;
	(void)type;
	if( type != "RootFile" ) {   }//do nothing for now

	string fullFileName = StringProcessing::FindFileName( fileName, quiet );

	if( !quiet ) cout << "Opening: " << fullFileName << endl;

	TFile* file = TFile::Open(TString(fullFileName));
 	if(!quiet) cout << "File " << fullFileName << " opened!" << endl;
	TH1F* histo = (TH1F*)file->Get(TString(histName));
	if(!quiet) cout << "Histo " << histName << " opened!" << endl;
	histo->Draw();
	if(!quiet) cout << "Histo " << histName << " drawn!" << endl;
//	histo->Sumw2();

	if(fluctuate){
	cout << "WARNING! You have fluctuated the acceptance." << endl;
	cout << "WARNING! This is for systematic studies only. " << endl;
	cout << "WARNING! Projections and pull fits will have a different fluctuated acceptance to the PDF you fit with." << endl;
	cout << "WARNING! ONLY USE FluctuateAcceptance:True FOR SYSTEMATIC STUDIES" << endl;
	TRandom3 * rng = new TRandom3(0);	
	//Randomly fluctuate bin contents within error: 
	for (int l = 1; l <= histo->GetNbinsX(); ++l){
	if(!quiet)	cout << "Bin content and error before: " << histo->GetBinContent(l) << "+/-" << histo->GetBinError(l);
		histo->SetBinContent(l,rng->Gaus(histo->GetBinContent(l),histo->GetBinError(l)));
	if(!quiet)	cout <<  " and after: " << histo->GetBinContent(l) << "+/-" << histo->GetBinError(l) << endl;
	}
	delete rng;
	}

	histo->Scale(1./(histo->GetBinContent(histo->GetMaximumBin())));
	histo->SetMinimum(0);


	double maxend = histo->GetBinLowEdge(histo->GetNbinsX()) + histo->GetBinWidth(histo->GetNbinsX());
	double height;
	double start;
	double end  = histo->GetBinLowEdge(histo->GetNbinsX()) + histo->GetBinWidth(histo->GetNbinsX());
	double dheight;
	for (int l = 1; l <= histo->GetNbinsX(); ++l){
		height = histo->GetBinContent(l);
		dheight = height;
		for (int n = l; n>0; n--){
			if(histo->GetBinContent(n)<height){
				dheight = height - histo->GetBinContent(n);
				cout << l << " " << n << " " << dheight << endl;
				break;
			}
		}
		start = histo->GetBinLowEdge(l);
		end = maxend;
		for (int m = l; m <= histo->GetNbinsX(); ++m){
			double thisbinheight = histo->GetBinContent(m);
			if(thisbinheight<height){
				end = histo->GetBinLowEdge(m);
				break;
			}
		}
		slices.push_back( new AcceptanceSlice( start, end, dheight ) );
	if(!quiet)	cout << start << "	" << end << "      " << dheight << endl;
	}
	histo->Delete();
//	delete histo;
	file->Close();
	delete file;

	if( !quiet ) cout << "Time Acc Slices: " << slices.size() << endl;
	if( slices.size() == 1 )
	{
		cout << "SlicedAcceptance: SERIOUS ERROR" << endl;
		exit(0);
	}
	//....done.....


	_sortedSlices = this->isSorted();

	if( _sortedSlices )
	{
		if( !quiet ) cout << "Sliced Acceptance is using sorted horizontal slices" << endl;
	}
	else
	{
		if( !quiet ) cout << "Sliced Acceptance is NOT using sorted horizontal slices" << endl;
	}
}