Пример #1
0
void makePoints(Int_t n, Double_t *x, Double_t *y, Double_t *e, Int_t p)
{
  Int_t i;
  TRandom r;

  if (p==2) {
    for (i=0; i<n; i++) {
      x[i] = r.Uniform(-2, 2);
      y[i]=TMath::Sin(x[i]) + TMath::Sin(2*x[i]) + r.Gaus()*0.1;
      e[i] = 0.1;
    }
  }
  if (p==3) {
    for (i=0; i<n; i++) {
      x[i] = r.Uniform(-2, 2);
      y[i] = -7 + 2*x[i]*x[i] + x[i]*x[i]*x[i]+ r.Gaus()*0.1;
      e[i] = 0.1;
    }
  }
  if (p==4) {
    for (i=0; i<n; i++) {
      x[i] = r.Uniform(-2, 2);
      y[i]=-2 + TMath::Exp(-x[i]) + r.Gaus()*0.1;
      e[i] = 0.1;
    }
  }
}
Пример #2
0
double write(int n) {



  TRandom R;
  TStopwatch timer;


  TFile f1("mathcoreLV.root","RECREATE");

  // create tree
  TTree t1("t1","Tree with new LorentzVector");

  std::vector<ROOT::Math::XYZTVector>  tracks;
  std::vector<ROOT::Math::XYZTVector> * pTracks = &tracks;
  t1.Branch("tracks","std::vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > >",&pTracks);

  double M = 0.13957;  // set pi+ mass

  timer.Start();
  double sum = 0;
  for (int i = 0; i < n; ++i) {
    int nPart = R.Poisson(5);
    pTracks->clear();
    pTracks->reserve(nPart);
    for (int j = 0; j < nPart; ++j) {
      double px = R.Gaus(0,10);
      double py = R.Gaus(0,10);
      double pt = sqrt(px*px +py*py);
      double eta = R.Uniform(-3,3);
      double phi = R.Uniform(0.0 , 2*TMath::Pi() );
      RhoEtaPhiVector vcyl( pt, eta, phi);
      // set energy
      double E = sqrt( vcyl.R()*vcyl.R() + M*M);
      XYZTVector q( vcyl.X(), vcyl.Y(), vcyl.Z(), E);
      // fill track vector
      pTracks->push_back(q);
      // evaluate sum of components to check
      sum += q.x()+q.y()+q.z()+q.t();
    }
    t1.Fill();
  }

  f1.Write();
  timer.Stop();
  std::cout << " Time for new Vector " << timer.RealTime() << "  " << timer.CpuTime() << std::endl;

  t1.Print();
  return sum;
}
Пример #3
0
 void Build() {
    TRandom rand;
    for (int i = 0; i < nelems; ++i) {
       fV0[i] = rand.Uniform();
       fV1[i] = rand.Uniform();
       fV2[i] = rand.Uniform();
       fV3[i] = rand.Uniform();
       fV4[i] = rand.Uniform();
       fV5[i] = rand.Uniform();
       fV6[i] = rand.Uniform();
       fV7[i] = rand.Uniform();
       fV8[i] = rand.Uniform();
       fV9[i] = rand.Uniform();
    }
 }
Пример #4
0
Файл: fmpmt.c Проект: ekawa/test
void fmpmt(void){

  TTree *t = new TTree("tree","fine mesh");
  double adc;
  t->Branch("adc",&adc,"adc/D");

  double Mult(double seed){
    do{
      double _fac=2.79360;
      TRandom _rand;
      _rand.SetSeed(0);
      double _judge = _rand.Uniform(0,1);
      double _x = _rand.Uniform(0.001,10);
    } while (TMath::Gaus(_x, _fac, _fac/20) < _judge);
    return seed*_x;
  }


  double prob = 0.7;
  double npe = 0.1;
  double judge, tmp;
  TRandom rand;
  rand.SetSeed(0);

  for(int i=0; i<4000; ++i){
    if(i%100==0){
      cout<<"=====  "<<i<<"  ====="<<endl;
    }
    do{
      tmp = rand.Uniform(0,4);
      judge = rand.Uniform(0,1);
    } while (TMath::Poisson(tmp, npe) < judge);
    for(int j=0; j<19; ++j){
      if(j==0){
        judge = rand.Uniform(0,1);
        if(judge>prob){
          continue;
        }
      }
      tmp=Mult(tmp);
    }
    adc=tmp;
    t->Fill();
  }
  t->Draw("adc");


}
Пример #5
0
void graph2derrorsfit()
{
   TCanvas *c1 = new TCanvas("c1");

   Double_t rnd, x, y, z, ex, ey, ez;
   Double_t e = 0.3;
   Int_t nd = 500;

   TRandom r;
   TF2  *f2 = new TF2("f2","1000*(([0]*sin(x)/x)*([1]*sin(y)/y))+200",-6,6,-6,6);
   f2->SetParameters(1,1);
   TGraph2DErrors *dte = new TGraph2DErrors(nd);

   // Fill the 2D graph
   for (Int_t i=0; i<nd; i++) {
      f2->GetRandom2(x,y);      
      rnd = r.Uniform(-e,e); // Generate a random number in [-e,e]
      z = f2->Eval(x,y)*(1+rnd);
      dte->SetPoint(i,x,y,z);
      ex = 0.05*r.Rndm();
      ey = 0.05*r.Rndm();
      ez = TMath::Abs(z*rnd);
      dte->SetPointError(i,ex,ey,ez);
   }

   f2->SetParameters(0.5,1.5);
   dte->Fit(f2);
   TF2 *fit2 = (TF2*)dte->FindObject("f2");
   fit2->SetTitle("Minuit fit result on the Graph2DErrors points");
   fit2->Draw("surf1");
   dte->Draw("axis p0");
}
Пример #6
0
void multicolor(Int_t isStack=0) {
   TCanvas *c1 = new TCanvas;
   Int_t nbins = 20;
   TH2F *h1 = new TH2F("h1","h1",nbins,-4,4,nbins,-4,4);
   h1->SetFillColor(kBlue);
   TH2F *h2 = new TH2F("h2","h2",nbins,-4,4,nbins,-4,4);
   h2->SetFillColor(kRed);
   TH2F *h3 = new TH2F("h3","h3",nbins,-4,4,nbins,-4,4);
   h3->SetFillColor(kYellow);
   THStack *hs = new THStack("hs","three plots");
   hs->Add(h1);
   hs->Add(h2);
   hs->Add(h3);
   TRandom r;
   Int_t i;
   for (i=0;i<20000;i++) h1->Fill(r.Gaus(),r.Gaus());
   for (i=0;i<200;i++) {
      Int_t ix = (Int_t)r.Uniform(0,nbins);
      Int_t iy = (Int_t)r.Uniform(0,nbins);
      Int_t bin = h1->GetBin(ix,iy);
      Double_t val = h1->GetBinContent(bin);
      if (val <= 0) continue;
      if (!isStack) h1->SetBinContent(bin,0);
      if (r.Rndm() > 0.5) {
         if (!isStack) h2->SetBinContent(bin,0);
         h3->SetBinContent(bin,val);
      } else {
         if (!isStack) h3->SetBinContent(bin,0);
         h2->SetBinContent(bin,val);
      }
   }
   hs->Draw("lego1");
}
Пример #7
0
void spheres(Int_t nspheres=20, Int_t npoints=100000) {
   // generate random points uniformly distributed over the surface
   // of spheres generated at random positions.

   TCanvas *c1 = new TCanvas("c1","spheres",600,600);
   c1->SetFillColor(kBlack);
   TView *view = new TView(1);
   Double_t k=0.8;
   view->SetRange( -k, -k, -k, k, k, k);
   
   //generate sphere coordinates and radius
   TRandom r;
   if (nspheres <=0) nspheres = 10;
   Double_t *xs = new Double_t[nspheres];
   Double_t *ys = new Double_t[nspheres];
   Double_t *zs = new Double_t[nspheres];
   Double_t *rs = new Double_t[nspheres];
   Int_t i;
   for (i=0;i<nspheres;i++) {
      xs[i] = r.Uniform(-1,1);
      ys[i] = r.Uniform(-1,1);
      zs[i] = r.Uniform(-1,1);
      rs[i] = r.Uniform(0.05,0.25);
   }

   //generate points
   TPolyMarker3D *pm = new TPolyMarker3D(npoints);
   pm->SetMarkerColor(kRed);
   Double_t x,y,z;
   for (Int_t j=0;j<npoints;j++) {
       i = (Int_t)r.Uniform(0,nspheres);  //choose sphere
       r.Sphere(x,y,z,rs[i]);
       pm->SetPoint(j,xs[i]+x, ys[i]+y,zs[i]+z);
   }
   
   delete [] xs;
   delete [] ys;
   delete [] zs;
   delete [] rs;
    
   pm->Draw();
}
Пример #8
0
void FitterUtils::initiateParams(int nGenSignalZeroGamma, int nGenSignalOneGamma, int nGenSignalTwoGamma, RooRealVar const& expoConstGen, RooRealVar& nSignal, RooRealVar& nPartReco, 
      RooRealVar& nComb, RooRealVar& fracZero, RooRealVar& fracOne, RooRealVar& expoConst, RooRealVar&  nJpsiLeak, bool constPartReco, RooRealVar const& fracPartRecoSigma)
{
   TRandom rand;
   rand.SetSeed();

   int nGenSignal = nGenSignalZeroGamma + nGenSignalOneGamma + nGenSignalTwoGamma;

   double nGenSignal2;
   double nGenPartReco2;
   if(!constPartReco)
   {
      nGenSignal2 = rand.Uniform(nGenSignal-5*sqrt(nGenSignal), nGenSignal+5*sqrt(nGenSignal));
      nGenPartReco2 = rand.Uniform(nGenPartReco-5*sqrt(nGenPartReco), nGenPartReco+5*sqrt(nGenPartReco));
   }
   if(constPartReco)
   { 
      double nGenSigPartReco( nGenSignal+nGenPartReco );
      double nGenSigPartReco2( rand.Uniform( nGenSigPartReco-5*sqrt(nGenSigPartReco), nGenSigPartReco+5*sqrt(nGenSigPartReco) ) );
      double fracPartReco1( nGenPartReco/(1.*nGenSignal));
      double fracPartReco2( rand.Uniform(fracPartReco1-5*fracPartRecoSigma.getVal(), fracPartReco1+5*fracPartRecoSigma.getVal()) ); 

      nGenPartReco2 = fracPartReco2*nGenSigPartReco2 / (1+fracPartReco2); 
      nGenSignal2 = nGenSigPartReco2 / (1+fracPartReco2); 
   }
   double nGenComb2 = rand.Uniform(nGenComb-5*sqrt(nGenComb), nGenComb+5*sqrt(nGenComb));
   double nGenJpsiLeak2 = rand.Uniform(nGenJpsiLeak-5*sqrt(nGenJpsiLeak), nGenJpsiLeak+5*sqrt(nGenJpsiLeak));


   nSignal.setVal(nGenSignal2);
   nSignal.setRange(TMath::Max(0.,nGenSignal2-10.*sqrt(nGenSignal)) , nGenSignal2+10*sqrt(nGenSignal));

   nPartReco.setVal(nGenPartReco2);
   nPartReco.setRange(TMath::Max(0.,nGenPartReco2-10.*sqrt(nGenPartReco)), nGenPartReco2+10*sqrt(nGenPartReco));


   nComb.setVal(nGenComb2);
   nComb.setRange(TMath::Max(0.,nGenComb2-10.*sqrt(nGenComb)), nGenComb2+10*sqrt(nGenComb));

   nJpsiLeak.setVal(nGenJpsiLeak2);
   nJpsiLeak.setRange(TMath::Max(0., nGenJpsiLeak2-10*sqrt(nGenJpsiLeak)), nGenJpsiLeak2+10*sqrt(nGenJpsiLeak));

   double fracGenZero(nGenSignalZeroGamma/(1.*nGenSignal));
   double fracGenOne(nGenSignalOneGamma/(1.*nGenSignal));

   fracZero.setVal(rand.Gaus(fracGenZero, sqrt(nGenSignalZeroGamma)/(1.*nGenSignal))) ;
   fracZero.setRange(0., 1.);
   fracOne.setVal(rand.Gaus(fracGenOne, sqrt(nGenSignalOneGamma)/(1.*nGenSignal))) ;
   fracOne.setRange(0., 1.);

   expoConst.setVal(rand.Uniform( expoConstGen.getVal() - 5*expoConstGen.getError(), expoConstGen.getVal() + 5*expoConstGen.getError() ) );
   expoConst.setRange( expoConstGen.getVal() - 10*expoConstGen.getError(), expoConstGen.getVal() + 10*expoConstGen.getError() );
}
Пример #9
0
void triangles(Int_t ntriangles=50) {
  TCanvas *c1 = new TCanvas("c1","triangles",10,10,700,700);
  TRandom r;
  Double_t dx = 0.2; Double_t dy = 0.2;
  Int_t ncolors = gStyle->GetNumberOfColors();
  Double_t x[4],y[4];
  TColor *c;
  Int_t ci;
  for (Int_t i=0;i<ntriangles;i++) {
     x[0] = r.Uniform(.05,.95); y[0] = r.Uniform(.05,.95);
     x[1] = x[0] + dx*r.Rndm(); y[1] = y[0] + dy*r.Rndm();
     x[2] = x[1] - dx*r.Rndm(); y[2] = y[1] - dy*r.Rndm();
     x[3] = x[0];               y[3] = y[0];
     TPolyLine *pl = new TPolyLine(4,x,y);
     pl->SetUniqueID(i);
     ci = ncolors*r.Rndm();
     c  = gROOT->GetColor(TColor::GetColorPalette(ci));
     c->SetAlpha(r.Rndm());
     pl->SetFillColor(ci);
     pl->Draw("f");
  }
  c1->AddExec("ex","TriangleClicked()");
}
Пример #10
0
void generate_imt_tree()
{
  // Create the file and the tree
  TFile hfile("ttree_read_imt.root", "RECREATE", "File for IMT test");
  TTree tree("TreeIMT", "TTree for IMT test");

  int nvbranches = 50, nabranches = 50;
  int nentries = 1000, nvelems = 100;
  std::vector<std::vector<Double_t>> vbranches(nvbranches);
  std::vector<A> abranches(nabranches);

  // Create the tree branches
  for (int i = 0; i < nvbranches; ++i) {
    vbranches[i] = std::vector<Double_t>(nvelems);

    std::string branchname("Vbranch");
    branchname += std::to_string(i);
    branchname += std::string("."); // make the top-level branch name be included in the sub-branch names

    tree.Branch(branchname.c_str(), &vbranches[i]);
  }
  for (int i = 0; i < nabranches; ++i) {
    std::string branchname("Abranch");
    branchname += std::to_string(i);
    branchname += std::string("."); // make the top-level branch name be included in the sub-branch names

    tree.Branch(branchname.c_str(), &abranches[i]);
  }

  // Fill the tree
  TRandom rand;
  for (int i = 0; i < nentries; i++) {
    for (int i = 0; i < nvbranches; ++i) {
      for (int j = 0; j < nvelems; ++j) {
        vbranches[i][j] = rand.Uniform();
      }
    }
    for (int i = 0; i < nabranches; ++i) {
      abranches[i].Build();
    }
    Int_t nb = tree.Fill();
  }

  // Write the file 
  hfile.Write();
  hfile.Close();
}
Пример #11
0
void apply_fake_rate(TRandom & rng, hxx_tree & data, double rate) {
    data.weight *= rate;

    //if (data.l1_pt <= 0.0) return;
    //if (data.l2_pt > 0.0) return;

    int n = data.jet_pt->size();

    if (n <= 0) return;

    int i = (int) (rng.Uniform() * n);
    //cout << i << " of " << n << "\n";

    double pt = data.jet_pt->at(i);

    if (pt > data.l1_pt) {
        data.l2_pt  = data.l1_pt;
        data.l2_eta = data.l1_eta;
        data.l2_phi = data.l1_phi;
        data.l1_pt  = pt;
        data.l1_eta = data.jet_eta->at(i);
        data.l1_phi = data.jet_phi->at(i);
    } else {
        data.l2_pt  = pt;
        data.l2_eta = data.jet_eta->at(i);
        data.l2_phi = data.jet_phi->at(i);
    }

    data.erase_jet(i);

    if (data.l2_pt <= 0.0) {
        data.mll = 0.0;
        return;
    }

    TLorentzVector v, v1, v2;
    v1.SetPtEtaPhiM(data.l1_pt, data.l1_eta, data.l1_phi, 0.0);
    v2.SetPtEtaPhiM(data.l2_pt, data.l2_eta, data.l2_phi, 0.0);
    v = v1 + v2;
    data.mll = v.M();

    //cout << data.mll << "\n";
    //cout << "   " << data.l1_pt << "\n";
    //cout << "   " << data.l2_pt << "\n";

}
double sampleXgenFromFunction1d(TRandom& rnd, TF1* function, double xMin, double xMax, double pMax)
{
  //std::cout << "<sampleXgenFromFunction1d>:" << std::endl;
  //std::cout << " function = " << function->GetTitle() << std::endl;
  //int numParameter = function->GetNpar();
  //for ( int iParameter = 0; iParameter < numParameter; ++iParameter ) {
  //  std::cout << " parameter #" << iParameter << " = " << function->GetParameter(iParameter) << std::endl;
  //}
  //assert(0);
  double x;
  bool isDone = false;
  while ( !isDone ) {
    x = rnd.Uniform(xMin, xMax);
    double u = rnd.Rndm();
    double f_x = function->Eval(x);
    //std::cout << "x = " << x << ": f(x) = " << f_x << " (pMax = " << pMax << ")" << std::endl;
    isDone = ((u*pMax) < f_x);
  }
  return x;
}
void test_mc_rejection_method_lin()
{
  const int    N     = 500000;
  const int    nbins = 300;
  const double ymax  = 1.1;
  const double xmin  = 0;
  const double xmax  = 10;
  const double dx    = xmax-xmin;

  TRandom rg;

  TF1 *  func = new TF1  ("func","1/(x+1)",0,10);
  TH1D * hgen = new TH1D ("hgen","generated",nbins,xmin,xmax);

  for(int i=0; i<N; i++) {
     cout << "..................." << i << endl;
     bool selected=false;
     while(1) {
       double xg = xmin + rg.Uniform() * dx;
       double yg = ymax * rg.Uniform();
       double yc = func->Eval(xg);
       selected = (yg<yc);
       if(selected) {
           hgen->Fill(xg);
           break;
       }
     }
  }

  double IF = func->Integral(xmin,xmax);
  double IH = hgen->Integral("width");
  double sc = IF/IH;
  hgen->Scale(sc);

  hgen->Draw();
  func->Draw("same");
}
Пример #14
0
TLorentzVector* applyResolution(TLorentzVector *l_gen){

  if(randomForSmearing.Uniform()<.9){
    double l_Perp =
      l_gen->Perp()+(randomForSmearing.Gaus(0,0.012*1.15*
					    l_gen->Perp()+0.00000*1.15* l_gen->Perp()* l_gen->Perp() ));
    double l_Theta = l_gen->Theta()+(randomForSmearing.Gaus(0,0.001));
    double l_Phi = l_gen->Phi()+(randomForSmearing.Gaus(0,0.001));
  }else{
    double l_Perp =
      l_gen->Perp()+randomForSmearing.Gaus(-l_gen->Perp()*.04,l_gen->Perp()*.08);
    //double l_Perp = l_gen->Perp();
    double l_Theta = l_gen->Theta()+(randomForSmearing.Gaus(0,0.001));
    double l_Phi = l_gen->Phi()+(randomForSmearing.Gaus(0,0.001));
  }
  double l_Px = l_Perp*cos(l_Phi);
  double l_Py = l_Perp*sin(l_Phi);
  double l_Pz = l_Perp/tan(l_Theta);
  double l_E = sqrt(l_Px*l_Px+l_Py*l_Py+l_Pz*l_Pz);

  return (new TLorentzVector( l_Px, l_Py, l_Pz, l_E ));


}
void FitterUtilsSimultaneousExpOfPolyTimesX::initiateParams(int nGenSignalZeroGamma, int nGenSignalOneGamma, int nGenSignalTwoGamma,
      RooRealVar& nKemu, RooRealVar& nSignal, RooRealVar& nPartReco,
      RooRealVar& nComb, RooRealVar& fracZero, RooRealVar& fracOne,
      RooRealVar&  nJpsiLeak, bool constPartReco, RooRealVar const& fracPartRecoSigma,
      RooRealVar& l1Kee, RooRealVar& l2Kee, RooRealVar& l3Kee, RooRealVar& l4Kee, RooRealVar& l5Kee,
      RooRealVar& l1Kemu, RooRealVar& l2Kemu, RooRealVar& l3Kemu, RooRealVar& l4Kemu, RooRealVar& l5Kemu,
      RooRealVar const& l1KeeGen, RooRealVar const& l2KeeGen, RooRealVar const& l3KeeGen, RooRealVar const& l4KeeGen, RooRealVar const& l5KeeGen 

      )
{
  FitterUtilsExpOfPolyTimesX::initiateParams(nGenSignalZeroGamma, nGenSignalOneGamma, nGenSignalTwoGamma,
           nSignal, nPartReco, nComb, fracZero, fracOne, nJpsiLeak, constPartReco, fracPartRecoSigma,
           l1Kee, l2Kee, l3Kee, l4Kee, l5Kee,
           l1KeeGen, l2KeeGen, l3KeeGen, l4KeeGen, l5KeeGen ); 



  TRandom rand;
  rand.SetSeed();

  nKemu.setVal(rand.Uniform(nGenKemu-5*sqrt(nGenKemu), nGenKemu+5*sqrt(nGenKemu)));
  nKemu.setRange(nGenKemu-10*sqrt(nGenKemu), nGenKemu+10*sqrt(nGenKemu));

  l1Kemu.setVal(rand.Uniform( l1KeeGen.getVal() - 5*l1KeeGen.getError(), l1KeeGen.getVal() + 5*l1KeeGen.getError() ) );
  l1Kemu.setRange( l1KeeGen.getVal() - 10*l1KeeGen.getError(), l1KeeGen.getVal() + 10*l1KeeGen.getError() );

  l2Kemu.setVal(rand.Uniform( l2KeeGen.getVal() - 5*l2KeeGen.getError(), l2KeeGen.getVal() + 5*l2KeeGen.getError() ) );
  l2Kemu.setRange( l2KeeGen.getVal() - 10*l2KeeGen.getError(), l2KeeGen.getVal() + 10*l2KeeGen.getError() );

  l3Kemu.setVal(rand.Uniform( l3KeeGen.getVal() - 5*l3KeeGen.getError(), l3KeeGen.getVal() + 5*l3KeeGen.getError() ) );
  l3Kemu.setRange( l3KeeGen.getVal() - 10*l3KeeGen.getError(), l3KeeGen.getVal() + 10*l3KeeGen.getError() );

  l4Kemu.setVal(rand.Uniform( l4KeeGen.getVal() - 5*l4KeeGen.getError(), l4KeeGen.getVal() + 5*l4KeeGen.getError() ) );
  l4Kemu.setRange( l4KeeGen.getVal() - 10*l4KeeGen.getError(), l4KeeGen.getVal() + 10*l4KeeGen.getError() );

  l5Kemu.setVal(rand.Uniform( l5KeeGen.getVal() - 5*l5KeeGen.getError(), l5KeeGen.getVal() + 5*l5KeeGen.getError() ) );
  l5Kemu.setRange( l5KeeGen.getVal() - 10*l5KeeGen.getError(), l5KeeGen.getVal() + 10*l5KeeGen.getError() );

}
Пример #16
0
void Trasporta(Int_t s,Int_t Rhum, TRandom *GeneratoreEsterno=0,Int_t Noise_Medio = 20) {

	TStopwatch tempo;

	tempo.Start(kTRUE);

	cout<<endl<<"Sto trasportando attraverso i rivelatori: attendere... "<<endl;
	TRandom *smear;
	if(GeneratoreEsterno == 0){
		smear = new TRandom3();
		cout<<"Generatore Interno";
	}else{
		smear = GeneratoreEsterno;
		cout<<"Generatore Esterno";
	}
	
	cout<<" FirstRNDM: "<<smear->Rndm()<<endl;
	
	//////////////////////////////////////////////////////
	//Creo un nuovo file e
	//Definisco Struct per salvare i nuovi dati x y z 
	//////////////////////////////////////////////////////

	//Definisco il nuovo albero per salvare i punti di hit	
	TFile sfile("trasporto_tree.root","RECREATE");
  
	TTree *trasporto = new TTree("Ttrasporto","TTree con 3 branches");
	 //Punti sul layer
	TTree *Rel_Lay1 = new TTree("Layer1","TTree con 1 branch");
	TTree *Rel_Lay2 = new TTree("Layer2","TTree con 1 branch");
	 //rumore
	TTree *Noise = new TTree("Rumore","TTree con 1 branch");

	typedef struct {
		Double_t X,Y,Z;
		Int_t Flag;		
	} HIT; 
	static HIT beam;  	
	static HIT lay1;  
	static HIT lay2;

	typedef struct {
		Int_t event;
		Int_t tipo;
		Int_t Noiselay1;
		Int_t Noiselay2;
	} infoRumore;
	static infoRumore InfoR;


	//Dichiaro i rami dei tree
	trasporto->Branch("BeamPipe",&beam.X,"X/D:Y:Z:Flag/I");  
	trasporto->Branch("Layer1",&lay1.X,"X/D:Y:Z:Flag/I"); 
	trasporto->Branch("Layer2",&lay2.X,"X/D:Y:Z:Flag/I");  

	Rel_Lay1->Branch("RealLayer1",&lay1.X,"X/D:Y:Z:Flag/I"); 
	Rel_Lay2->Branch("RealLayer2",&lay2.X,"X/D:Y:Z:Flag/I"); 
	
	Noise->Branch("Rumore",&InfoR,"event/I:tipo:Noiselay1:Noiselay2"); 
	Double_t temp_phi = 0;
	Int_t Nnoise=0;	

  ////////////////////////////////
  //Acquisizione Vertici
  ///////////////////////////////
  TClonesArray *dir = new TClonesArray("Direction",100);	
  typedef struct {
    Double_t X,Y,Z;
    Int_t N;
  }SINGLE_EVENT;
  static SINGLE_EVENT event;    //struct con molteplicita' e vertice di un singolo evento
	
  TFile hfile("event_tree.root");


  TTree *Born = (TTree*)hfile.Get("T");       
  TBranch *b1=Born->GetBranch("Event"); 
  TBranch *b2=Born->GetBranch("Direzioni");  //acquisisco i due branches


  b1->SetAddress(&event.X); //passo l'indirizzo del primo oggetto della struct e assegno tutto a b1
  b2->SetAddress(&dir); // lo stesso per il vettore 




  /////////////////////////
  //Geometria del rivelatore
  /////////////////////////
  Double_t R1=3;	//raggio 3 cm beam pipe
  Double_t R2=4;	//raggio 4 cm primo layer
  Double_t R3=7;	//raggio 7 cm secondo layer

  Double_t limit = 8.; //lunghezza layer su z-> z in [-8,8]

  //Variabili Varie
	Double_t Xo=0.;Double_t Yo=0.;Double_t Zo=0.;
  	Double_t X1=0.;Double_t Y1=0.;Double_t Z1=0.;
	Double_t X2=0.;Double_t Y2=0.;Double_t Z2=0.;

	Int_t N=0; //molteplicita'

	Int_t yes = 0;
	Int_t no = 0;	       
	
	for(Int_t e=0; e < Born->GetEntries(); e++){
	
		Born->GetEvent(e);
		Xo=event.X;
		Yo=event.Y;
		Zo=event.Z;		
		N=event.N;	    
		
		for(Int_t i=0; i<N; i++){
			
			//Cast dell'elemenento i di TClones a Direction
			Direction *angolacci=(Direction*)dir->At(i);
			angolacci->SetRNDGenerator(smear);//uso lo stesso generatore anche nella classe
			
			//primo hit beam pipe
			angolacci->GeneraHit(Xo,Yo,Zo,R1);//genero il punto di impatto sul beam pipe		
			
			beam.X=angolacci->GetNewX(); //recupero le coordinate del punto d'impatto sul BP
			beam.Y=angolacci->GetNewY();					
			beam.Z=angolacci->GetNewZ();
			beam.Flag=1;
		

			///////////////////////////////////////////////////
			/////////////scattering sul beam pipe//////////////
			///////////////////////////////////////////////////
			if(s==1){
				//dipende dal tipo di materiale
				angolacci->Scattering(0.08,35.28);
			}
					
				
			//secondo hit layer 1			
			angolacci->GeneraHit(beam.X,beam.Y,beam.Z,R2);

			X1 = angolacci->GetNewX();	
			Y1 = angolacci->GetNewY();
			Z1 = angolacci->GetNewZ();
			
			lay1.X=X1;
			lay1.Y=Y1;							
			lay1.Z=Z1;	
			
			//verifico che la particella colpisca il layer
			if(TMath::Abs(Z1) < limit){

				lay1.Flag = e;
				Rel_Lay1->Fill();					       
				
				///////////////////////////////////////////////
				/////////////scattering sul layer//////////////	
				///////////////////////////////////////////////
				if(s==1){
					angolacci->Scattering(0.02,9.37);
				}				
							
				yes++;
				
			}else no++;	      
				

		      //terzo hit layer 2			
		      angolacci->GeneraHit(X1,Y1,Z1,R3);

		      X2 = angolacci->GetNewX();	
		      Y2 = angolacci->GetNewY();
		      Z2 = angolacci->GetNewZ();
		      lay2.X=X2;
		      lay2.Y=Y2;							
		      lay2.Z=Z2;
			

		      //verifico che la particella colpisca il layer
		      if(TMath::Abs(Z2) < limit){

			lay2.Flag = e;	
			Rel_Lay2->Fill();			
	
			yes++;

		      }else{
			no++;	
		      }

			angolacci->RemoveGenerator();
			trasporto->Fill(); //riempie tutto con quello che ho definito sopra

		      // Debug
		      /*printf("Evento %d : part %d \n",e,i+1);
			printf("x beam= %f ; y beam= %f; z beam= %f \n",beam.X,beam.Y,beam.Z);

			if(lay1.Flag){
			printf("x lay1= %f ; y lay1= %f; z lay1= %f \n",lay1.X,lay1.Y,lay1.Z);
			}else{
			printf("Non urta sul layer 1 \n");
			}


			if(lay2.Flag){
			printf("x lay2= %f ; y lay2= %f; z lay2= %f \n",lay2.X,lay2.Y,lay2.Z);
			}else{
			printf("Non urta sul layer 2 \n");
			}*/
		}

		////////////////////////////////////////////////////////////////////////////
		//////////////////////////RUMORE////////////////////////////////////////////
		////////////////////////////////////////////////////////////////////////////
		InfoR.event = e;
		InfoR.tipo = Rhum;
		if(Rhum != 0){
		//genero rumore lay 1
			if(Rhum == 1){
				//Nnoise= TMath::Abs(smear->Gaus(20,5));
				//Nnoise = 1+(Int_t)(20*smear->Rndm());
				Nnoise = 1+(Int_t)(Noise_Medio*smear->Rndm());
			}else{
				Nnoise= Rhum;
			}
		
		
			InfoR.Noiselay1 = Nnoise;
		
			for(Int_t y =0; y < Nnoise; y++){
				temp_phi = smear->Uniform(0,2*TMath::Pi());
				lay1.X = R2*TMath::Cos(temp_phi);
				lay1.Y = R2*TMath::Sin(temp_phi);							
				lay1.Z = smear->Uniform(-limit,limit);
	
				lay1.Flag=e;

				Rel_Lay1->Fill();		
		
			}

		      //genero rumore lay 2					
			if(Rhum == 1){
				//Nnoise= TMath::Abs(smear->Gaus(20,5));
				//Nnoise = 1+(Int_t)(20*smear->Rndm());
				Nnoise = 1+(Int_t)(Noise_Medio*smear->Rndm());
			}else{
				Nnoise= Rhum;
			}

			InfoR.Noiselay2 = Nnoise;

			for(Int_t w =0; w < Nnoise; w++){
				temp_phi = smear->Uniform(0,2*TMath::Pi());

				lay2.X = R3*TMath::Cos(temp_phi);
				lay2.Y = R3*TMath::Sin(temp_phi);							
				lay2.Z = smear->Uniform(-limit,limit);
	
				lay2.Flag=e;

				Rel_Lay2->Fill();	
			}
		}else{
			InfoR.Noiselay1 = 0;
			InfoR.Noiselay2 = 0;
		}
	
	//fill per il rumore
	Noise->Fill();
	}


	sfile.Write(); 
 
	sfile.Close();
	//ho il file con tutti gli eventi

  

 	tempo.Stop();
  
	cout<<endl<<endl<<endl<<"//////////////////////////////////////"<<endl<<endl;
	cout<<"Completato!"<<endl<<endl;
	cout<<"Il trasporto è durato "<<endl;
	tempo.Print();
	cout<<endl<<endl;
	cout<<"PARAMETRI TRASPORTO: "<<endl;
	cout<<"\t"<<"Scattering:     "<<s;
	if(s==1)cout<<"  Scattering attivo"<<endl;
	if(s==0)cout<<"  Scattering non attivo"<<endl;
	cout<<"\t"<<"Rumore:         ";
	if(Rhum==1)cout<<"  Rumore gaussiano  "<<endl;
	if(Rhum==0)cout<<"  Nessun rumore"<<endl;
	if((Rhum!=0) & (Rhum!=1))cout<<"  Rumore con molteplicita' fissa "<<Rhum<<endl;
  	cout<<endl<<"//////////////////////////////////////"<<endl;

}
Пример #17
0
Файл: p_ela.c Проект: ekawa/test
int p_ela() {

  TRandom *r = new TRandom();

  //reaction
  TGenPhaseSpace event1;//p(gamma, omega)p
  TLorentzVector TotalLv1;

  //Initial state
  TLorentzVector * Beam_Lv = new TLorentzVector();
  TLorentzVector * Tgt_Lv = new TLorentzVector();



  //Final state
  TLorentzVector *Proton1_Lv = new TLorentzVector();
  TLorentzVector *Proton2_Lv = new TLorentzVector();

  //tree component
  double p1mom;
  double p1mom_x;
  double p1mom_y;
  double p1mom_z;
  double p2mom;
  double p2mom_x;
  double p2mom_y;
  double p2mom_z;
  double theta_p1;
  double theta_p2;
  double theta_12;



  //Set Initial Condition
  double beame=0.1;
  double beammom=sqrt( (0.1+M_PROTON)**2 - M_PROTON**2 );

  TVector3 mom_Beam(0.,0.,beammom);
  TVector3 mom_Tgt(0.,0.,0.);
  Beam_Lv->SetVectM(mom_Beam,M_PROTON);
  Tgt_Lv->SetVectM(mom_Tgt,M_PROTON);
  TotalLv1 = (*Beam_Lv) + (*Tgt_Lv);// Total Vector



  //Set Output file
  TFile *f = new TFile("p_ela.root","recreate");
  TTree *  tree = new TTree("tree","p_ela production");

  tree->Branch("beam"  ,  "TLorentzVector",      &Beam_Lv, 32000, 1);
  tree->Branch("tgt"   ,  "TLorentzVector",       &Tgt_Lv, 32000, 1);
  tree->Branch("proton1", "TLorentzVector",   &Proton1_Lv, 32000, 1);
  tree->Branch("proton2", "TLorentzVector",   &Proton2_Lv, 32000, 1);
  tree->Branch("p1mom"  ,     &p1mom,     "p1mom/D");
  tree->Branch("p1mom_x",   &p1mom_x,   "p1mom_x/D");
  tree->Branch("p1mom_y",   &p1mom_y,   "p1mom_y/D");
  tree->Branch("p1mom_z",   &p1mom_z,   "p1mom_z/D");
  tree->Branch("p2mom"  ,     &p2mom,     "p2mom/D");
  tree->Branch("p2mom_x",   &p2mom_x,   "p2mom_x/D");
  tree->Branch("p2mom_y",   &p2mom_y,   "p2mom_y/D");
  tree->Branch("p2mom_z",   &p2mom_z,   "p2mom_z/D");
  tree->Branch("theta_p1", &theta_p1,  "theta_p1/D");
  tree->Branch("theta_p2", &theta_p2,  "theta_p2/D");
  tree->Branch("theta_12", &theta_12,  "theta_12/D");

  //Event Generation start!
  int Max_No = 10000;  // repeat no
  int i=0;


  double masses[2];
  double weight=0;
  double comp=0;
  masses[0] = M_PROTON;
  masses[1] = M_PROTON;

  event1.SetDecay(TotalLv1, 2, masses, "Fermi");///Total E, particle No, particle mass

  do{
    if(i%1000 == 0){
      std::cout<<"ev_no=" << i <<std::endl;
    }
    int try_no=0;
    do{
      comp=r->Uniform(0.,0.5);
      weight =event1.Generate();
      try_no++;
    }while(comp > weight);




    std::cout << "weight = "<<weight << " comp = "<<comp <<" try_no ="<<try_no <<std::endl;

    if(TotalLv1.Mag() < masses[0] + masses[1]  ){
      std::cout<<"event1 not happen!" << TotalLv1.Mag() <<":"
        << masses[0] + masses[1]<<std::endl;
      continue;
    }

    Proton1_Lv = event1.GetDecay(0);
    Proton2_Lv = event1.GetDecay(1);


    p1mom   = Proton1_Lv->Vect().Mag();
    p1mom_x = Proton1_Lv->X();
    p1mom_y = Proton1_Lv->Y();
    p1mom_z = Proton1_Lv->Z();
    p2mom   = Proton2_Lv->Vect().Mag();
    p2mom_x = Proton2_Lv->X();
    p2mom_y = Proton2_Lv->Y();
    p2mom_z = Proton2_Lv->Z();
    theta_p1  = acos( p1mom_z/p1mom );
    theta_p2  = acos( p2mom_z/p2mom );
    theta_12  = acos( (p1mom_x*p2mom_x + p1mom_y*p2mom_y + p1mom_z*p2mom_z) / (p1mom*p2mom) );


    tree->Fill();

    i++;
  }while(i<Max_No);



  tree->Write();


  f->Close();

}
Пример #18
0
void PhaseDplusKKpi( std::string filename = "bsdspi.root", int nToGen = 1e7) {


  // gROOT->ProcessLine(".x ~/lhcb/lhcbStyle.C");
	if (!gROOT->GetClass("TGenPhaseSpace")) gSystem->Load("libPhysics");


	// loaf the fonll stuff
        TFile* fonll = new TFile("fonll.root");
        TH1F* ptHisto = (TH1F*) fonll->Get("pthisto"); 
        TH1F* etaHisto = (TH1F*) fonll->Get("etahisto"); 

        // get the graph to smear with
        TFile* smearfile = new TFile("smear12.root");
        TGraphErrors* sgraph = (TGraphErrors*)smearfile->Get("data;1");

	Double_t masses[2] = {mDplus,mpi};
        Double_t masses2[3] = {mK,mpi,mpi};
        
	double min(5.2);
	double max(5.5);
     

	TH1F *h1 = new TH1F("h1","h1", 100, 4850, 5550);
        h1->Sumw2();

        TH1F *dh1 = new TH1F("dh1","dh1", 100, 0., 5000.);
        dh1->Sumw2();

        TH1F *dh2 = new TH1F("dh2","dh2", 100, 1000., 2000.);
        dh2->Sumw2();


        TH1F *dh3 = new TH1F("pi","pi", 100, 2000., 4000.);
        dh3->Sumw2();

        TH1F *dh4 = new TH1F("phi","phi", 100, 750, 1250);
        dh4->Sumw2();

        TRandom ran;

	for (Int_t n=0;n<nToGen; n++) {
	  //	   Double_t weight = event.Generate();
          TLorentzVector Bs = genB(ran,ptHisto,etaHisto, mBd);
          TGenPhaseSpace event;
          if (!generateEvent(Bs,event,masses,ran,1000)) continue;

          TLorentzVector dplus = *event.GetDecay(0); // ds
	  TLorentzVector pi1 = *event.GetDecay(1); //pi 
          
          // generate the Ds
          TGenPhaseSpace subevent; 
 
          if (!generateEvent(dplus,subevent,masses2,ran,1000)) continue;
          TLorentzVector k1 = *subevent.GetDecay(0);
          TLorentzVector pi2 = *subevent.GetDecay(1);
          TLorentzVector pi3 = *subevent.GetDecay(2);

	   // smear the vectors
	  TLorentzVector spi1 = smearedVec(pi1,sgraph,ran);
	  TLorentzVector spi2 = smearedVec(pi2,sgraph,ran);
	  TLorentzVector spi3 =  smearedVec(pi3,sgraph,ran);
          TLorentzVector sk1 =  smearedVec(k1,sgraph,ran);

          TLorentzVector fk2;  TLorentzVector fpi2;
          if (ran.Uniform() > 0.5){
            fk2 = reassignMass(spi2,mK);
	    fpi2 = spi3;
	  }
          else{
            fk2 = reassignMass(spi3,mK);
	    fpi2 = spi2;
	  }


           TLorentzVector sum = spi1 + spi2 + sk1 +fk2;
           TLorentzVector pipi = spi1 + fpi2 ;
           TLorentzVector phi = sk1+fk2 ;
           TLorentzVector dsum = spi1 + sk1 + fk2 ;
           TLorentzVector dsum2 = spi2 + sk1 + fk2 ;
 
	   if ( select(spi1,fpi2,sk1,fk2,ran)) {
              h1->Fill(1000*sum.M());
              dh1->Fill(1000*dsum.M());
              dh2->Fill(1000*dsum2.M());
              dh3->Fill(1000*pipi.M());
              dh4->Fill(1000*phi.M()); 
	   }
	   // std::cout << pipi.P() << std::endl;
	}

        TCanvas* can = new TCanvas("can","can", 800,600); 
        h1->Draw("HISTO");

        TCanvas* can2 = new TCanvas("can2","can2", 800,600); 
	dh1->Draw("HISTO");

        TCanvas* can3 = new TCanvas("can3","can3", 800,600); 
	dh2->Draw("HISTO");


        TCanvas* can4 = new TCanvas("can4","can4", 800,600); 
	dh3->Draw("HISTO");

        TCanvas* can5 = new TCanvas("can5","can5", 800,600); 
	dh4->Draw("HISTO");


        TFile* output = new TFile(filename.c_str(),"RECREATE","output ROOT file");
        dh1->Write(); 
        dh2->Write(); 
        dh3->Write(); 
        dh4->Write(); 
        h1->Write();  
        output->Close();
  
}
Пример #19
0
//void asymmetry(std::string algoType="caloItCone5") {
void asymmetry() {

  int nBins = 5;


  TChain* chain = new TChain("jetTree");
  int nFiles=49;

  for(int i=1; i<(nFiles+1); ++i) {
    char name[100];
    sprintf(name, "2ndLevelOutputFiles/2ndLevelOutputFile_%d.root/jetTree", i);
    chain->Add(name);
  }


 
  int nJetReco_caloItCone5;
  chain->SetBranchAddress("nJetReco_caloItCone5", &nJetReco_caloItCone5);
 
  Float_t ptReco_caloItCone5[40];
  chain->SetBranchAddress("ptReco_caloItCone5", ptReco_caloItCone5);
 
  Float_t phiReco_caloItCone5[40];
  chain->SetBranchAddress("phiReco_caloItCone5", phiReco_caloItCone5);
 

  std::vector< TH1F* > h1_asymmetry_less10;
  std::vector< TH1F* > h1_asymmetry_less12;
  std::vector< TH1F* > h1_asymmetry_less15;
  std::vector< TH1F* > h1_asymmetry_less17;
  std::vector< TH1F* > h1_asymmetry_less20;
  std::vector< TH1F* > h1_asymmetry_less30;


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

    char histName[40];
    sprintf(histName, "less10_bin%d", i);
    TH1F* less10 = new TH1F(histName, "", 100, -0.6, 0.6);
    h1_asymmetry_less10.push_back(less10);

    sprintf(histName, "less12_bin%d", i);
    TH1F* less12 = new TH1F(histName, "", 100, -0.6, 0.6);
    h1_asymmetry_less12.push_back(less12);

    sprintf(histName, "less15_bin%d", i);
    TH1F* less15 = new TH1F(histName, "", 100, -0.6, 0.6);
    h1_asymmetry_less15.push_back(less15);

    sprintf(histName, "less17_bin%d", i);
    TH1F* less17 = new TH1F(histName, "", 100, -0.6, 0.6);
    h1_asymmetry_less17.push_back(less17);

    sprintf(histName, "less20_bin%d", i);
    TH1F* less20 = new TH1F(histName, "", 100, -0.6, 0.6);
    h1_asymmetry_less20.push_back(less20);

    sprintf(histName, "less30_bin%d", i);
    TH1F* less30 = new TH1F(histName, "", 100, -0.6, 0.6);
    h1_asymmetry_less30.push_back(less30);

  }


  TRandom t;

  Int_t nEntries = chain->GetEntries();

  //for(int iEntry=0; iEntry<100000; ++iEntry) { 
  for(int iEntry=0; iEntry<nEntries; ++iEntry) { 

    if( (iEntry % 100000) == 0 ) std::cout << "Entry #" << iEntry << " /" << nEntries << std::endl;
    chain->GetEntry(iEntry);

    //------------ CALO IT CONE 0.5

    if( nJetReco_caloItCone5 > 2 ) {

      Float_t pt1(0.), pt2(0.), pt3(0.);
      Float_t phi1(0.), phi2(0.);


      for(int iJet = 0; iJet<nJetReco_caloItCone5; ++iJet ) {

        Float_t ptJet = ptReco_caloItCone5[iJet];

        if( ptJet > pt1 ) {
          pt3=pt2;
          pt2=pt1;
          pt1=ptJet;
          phi1=phiReco_caloItCone5[iJet];
        } else if( ptJet > pt2 ) {
          pt3=pt2;
          pt2=ptJet;
          phi2=phiReco_caloItCone5[iJet];
        } else if( ptJet > pt3 ) {
          pt3=ptJet;
        }
        
      } //for jets


      Float_t pi = 3.14159;
      //Float_t deltaPhi = acos(cos(phi1-phi2));
      Float_t deltaPhi = phi1-phi2;
      if( deltaPhi > pi ) deltaPhi-=2*pi;
      if( deltaPhi < -pi ) deltaPhi+=2*pi;

      if( (pt3 < 30.) && (deltaPhi>2.7) ) {

        Float_t asymmetry = (pt1-pt2)/(pt1+pt2);
        Float_t oneHalfProb = t.Uniform(1.);
        if(oneHalfProb<0.5) asymmetry *= -1.;

        Float_t averagePt = (pt1+pt2)/2.;
        
        int iBin=-1;
         
        if( (averagePt > 80.)&&(averagePt < 100.) ) iBin=0;
        else if( (averagePt > 100.)&&(averagePt < 125.) ) iBin=1;
        else if( (averagePt > 125.)&&(averagePt < 160.) ) iBin=2;
        else if( (averagePt > 160.)&&(averagePt < 190.) ) iBin=3;
        else if( (averagePt > 190.)&&(averagePt < 215.) ) iBin=4;

        if(iBin!=-1) {

          h1_asymmetry_less30[iBin]->Fill(asymmetry);

          if( pt3 < 20. ) h1_asymmetry_less20[iBin]->Fill(asymmetry);
          if( pt3 < 17. ) h1_asymmetry_less17[iBin]->Fill(asymmetry);
          if( pt3 < 15. ) h1_asymmetry_less15[iBin]->Fill(asymmetry);
          if( pt3 < 12. ) h1_asymmetry_less12[iBin]->Fill(asymmetry);
          if( pt3 < 10. ) h1_asymmetry_less10[iBin]->Fill(asymmetry);

        } // if ibin

      } //if pt3 < 30

    } //if nJet>2

  } //for entries

  TCanvas* c_prova = new TCanvas("c_prova", "c_prova", 800, 600);
  c_prova->cd();
  


  Double_t Lower[nBins];

  Lower[0] = 80.;  
  Lower[1] = 100.;  
  Lower[2] = 125.;  
  Lower[3] = 160.;  
  Lower[4] = 190.;  
  Lower[5] = 215.;  


  TH1F* h1_resolution_vs_pt = new TH1F("resolution_vs_pt", "Jet Energy Resolution vs. Average Jet p_{T}", nBins, Lower);
  h1_resolution_vs_pt->SetXTitle("Average p_{T}^{RECO} [GeV/c]");
  h1_resolution_vs_pt->SetYTitle("#sigma(p_{T})/p_{T}");


  for(int iBin=0; iBin<nBins; ++iBin) {

    int nPoints = 6;
    Float_t x[nPoints], y[nPoints];
    Float_t err_x[nPoints], err_y[nPoints];

    x[0] = 10.;
    x[1] = 12.;
    x[2] = 15.;
    x[3] = 17.;
    x[4] = 20.;
    x[5] = 30.;

    y[0] = sqrt(2)*h1_asymmetry_less10[iBin]->GetRMS();
    y[1] = sqrt(2)*h1_asymmetry_less12[iBin]->GetRMS();
    y[2] = sqrt(2)*h1_asymmetry_less15[iBin]->GetRMS();
    y[3] = sqrt(2)*h1_asymmetry_less17[iBin]->GetRMS();
    y[4] = sqrt(2)*h1_asymmetry_less20[iBin]->GetRMS();
    y[5] = sqrt(2)*h1_asymmetry_less30[iBin]->GetRMS();

    err_x[0] = 0.; 
    err_x[1] = 0.; 
    err_x[2] = 0.; 
    err_x[3] = 0.; 
    err_x[4] = 0.; 
    err_x[5] = 0.; 

    err_y[0] = y[0]/sqrt(h1_asymmetry_less10[iBin]->GetEntries()); 
    err_y[1] = y[1]/sqrt(h1_asymmetry_less12[iBin]->GetEntries()); 
    err_y[2] = y[2]/sqrt(h1_asymmetry_less15[iBin]->GetEntries()); 
    err_y[3] = y[3]/sqrt(h1_asymmetry_less17[iBin]->GetEntries()); 
    err_y[4] = y[4]/sqrt(h1_asymmetry_less20[iBin]->GetEntries()); 
    err_y[5] = y[5]/sqrt(h1_asymmetry_less30[iBin]->GetEntries()); 


    TGraphErrors* resolution_vs_pt3 = new TGraphErrors(nPoints, x, y, err_x, err_y);
    resolution_vs_pt3->SetMarkerStyle(20);

    TF1* line = new TF1("line", "[0] + [1]*x");
    line->SetParameter(0, y[0]);
    line->SetParameter(1, (y[1]-y[0])/(x[1]-x[0]));
    line->SetRange(0., 32.);

    resolution_vs_pt3->Fit(line, "R");

    char plotName[70];
    sprintf(plotName, "asymmetry/asymmetry_less10_%d.eps", iBin);
    h1_asymmetry_less10[iBin]->Draw();
    c_prova->SaveAs(plotName);

    sprintf(plotName, "asymmetry/asymmetry_less20_%d.eps", iBin);
    h1_asymmetry_less20[iBin]->Draw();
    c_prova->SaveAs(plotName);

    sprintf(plotName, "asymmetry/asymmetry_less30_%d.eps", iBin);
    h1_asymmetry_less30[iBin]->Draw();
    c_prova->SaveAs(plotName);


    sprintf(plotName, "asymmetry/resolution_vs_pt3_%d.eps", iBin);
    resolution_vs_pt3->Draw("AP");
    c_prova->SaveAs(plotName);


    h1_resolution_vs_pt->SetBinContent(iBin+1, line->GetParameter(0));
    h1_resolution_vs_pt->SetBinError(iBin+1, line->GetParError(0));

  } //for pt bins


  TFile* outFile = new TFile("asymmetryOutputFile.root", "RECREATE");

  outFile->cd();
  h1_resolution_vs_pt->Write();
  outFile->Close();
  outFile->Write();

} //asymmetry
Пример #20
0
void th2polyEurope(Int_t npoints=500000)
{
   Int_t i,j;
   Double_t lon1 = -25;
   Double_t lon2 =  35;
   Double_t lat1 =  34;
   Double_t lat2 =  72;
   Double_t R = (lat2-lat1)/(lon2-lon1);
   Int_t W    = 800;
   Int_t H    = (Int_t)(R*800);
   gStyle->SetStatX(0.28);
   gStyle->SetStatY(0.45);
   gStyle->SetStatW(0.15);

   // Canvas used to draw TH2Poly (the map)
   TCanvas *ce = new TCanvas("ce", "ce",0,0,W,H);
   ce->ToggleEventStatus();
   ce->SetGridx();
   ce->SetGridy();

   // Real surfaces taken from Wikipedia.
   const Int_t nx = 36;
   // see http://en.wikipedia.org/wiki/Area_and_population_of_European_countries
   const char *countries[nx] = {
      "france",     "spain",  "sweden",  "germany",       "finland",
      "norway",     "poland", "italy",   "yugoslavia",    "united_kingdom",
      "romania",    "belarus","greece",  "czechoslovakia","bulgaria",
      "iceland",    "hungary","portugal","austria",       "ireland",
      "lithuania",  "latvia", "estonia", "denmark",       "netherlands",
      "switzerland","moldova","belgium", "albania",       "cyprus",
      "luxembourg", "andorra","malta",   "liechtenstein", "san_marino", "monaco" };
   Float_t surfaces[nx] = {
      547030,        505580,   449964,      357021,        338145,
      324220,        312685,   301230,      255438,        244820,
      237500,        207600,   131940,      127711,        110910,
      103000,         93030,    89242,       83870,         70280,
      65200,         64589,    45226,       43094,         41526,
      41290,         33843,    30528,       28748,          9250,
      2586,           468,      316,         160,            61, 2};

   TH1F *h = new TH1F("h","Countries surfaces (in km^{2})",3,0,3);
   for (i=0; i<nx; i++) h->Fill(countries[i], surfaces[i]);
   h->LabelsDeflate();

   TFile::SetCacheFileDir(".");
   TFile *f;
   f = TFile::Open("http://root.cern.ch/files/europe.root","cacheread");

   if (!f) {
      printf("Cannot access europe.root. Is internet working ?\n");
      return;
   }

   TH2Poly *p = new TH2Poly(
             "Europe",
             "Europe (bin contents are normalized to the surfaces in km^{2})",
             lon1,lon2,lat1,lat2);
   p->GetXaxis()->SetNdivisions(520);
   p->GetXaxis()->SetTitle("longitude");
   p->GetYaxis()->SetTitle("latitude");

   p->SetContour(100);

   TMultiGraph *mg;
   TKey *key;
   TIter nextkey(gDirectory->GetListOfKeys());
   while ((key = (TKey*)nextkey())) {
      TObject *obj = key->ReadObj();
      if (obj->InheritsFrom("TMultiGraph")) {
         mg = (TMultiGraph*)obj;
         p->AddBin(mg);
      }
   }

   TRandom r;
   Double_t longitude, latitude;
   Double_t x, y, pi4 = TMath::Pi()/4, alpha = TMath::Pi()/360;

   gBenchmark->Start("Partitioning");
   p->ChangePartition(100, 100);
   gBenchmark->Show("Partitioning");

   // Fill TH2Poly according to a Mercator projection.
   gBenchmark->Start("Filling");
   for (i=0; i<npoints; i++) {
      longitude = r.Uniform(lon1,lon2);
      latitude  = r.Uniform(lat1,lat2);
      x         = longitude;
      y         = 38*TMath::Log(TMath::Tan(pi4+alpha*latitude));
      p->Fill(x,y);
   }
   gBenchmark->Show("Filling");

   Int_t nbins = p->GetNumberOfBins();
   Double_t maximum = p->GetMaximum();


   // h2 contains the surfaces computed from TH2Poly.
   TH1F *h2 = (TH1F *)h->Clone("h2");
   h2->Reset();
   for (j=0; j<nx; j++) {
      for (i=0; i<nbins; i++) {
         if (strstr(countries[j],p->GetBinName(i+1))) {
            h2->Fill(countries[j],p->GetBinContent(i+1));
            h2->SetBinError(j, p->GetBinError(i+1));
         }
      }
   }

   // Normalize the TH2Poly bin contents to the real surfaces.
   Double_t scale = surfaces[0]/maximum;
   for (i=0; i<nbins; i++) p->SetBinContent(i+1, scale*p->GetBinContent(i+1));

   gStyle->SetOptStat(1111);
   p->Draw("COLZ");

   TCanvas *c1 = new TCanvas("c1", "c1",W+10,0,W-20,H);
   c1->SetRightMargin(0.047);

   scale = h->GetMaximum()/h2->GetMaximum();

   h->SetStats(0);
   h->SetLineColor(kRed-3);
   h->SetLineWidth(2);
   h->SetMarkerStyle(20);
   h->SetMarkerColor(kBlue);
   h->SetMarkerSize(0.8);
   h->Draw("LP");
   h->GetXaxis()->SetLabelFont(42);
   h->GetXaxis()->SetLabelSize(0.03);
   h->GetYaxis()->SetLabelFont(42);

   h2->Scale(scale);
   Double_t scale2=TMath::Sqrt(scale);
   for (i=0; i<nx; i++) h2->SetBinError(i+1, scale2*h2->GetBinError(i+1));
   h2->Draw("E SAME");
   h2->SetMarkerStyle(20);
   h2->SetMarkerSize(0.8);

   TLegend *leg = new TLegend(0.5,0.67,0.92,0.8,NULL,"NDC");
   leg->SetTextFont(42);
   leg->SetTextSize(0.025);
   leg->AddEntry(h,"Real countries surfaces from Wikipedia (in km^{2})","lp");
   leg->AddEntry(h2,"Countries surfaces from TH2Poly (with errors)","lp");
   leg->Draw();
   leg->Draw();

   Double_t wikiSum = h->Integral();
   Double_t polySum = h2->Integral();
   Double_t error = TMath::Abs(wikiSum-polySum)/wikiSum;
   printf("THPoly Europe surface estimation error wrt wikipedia = %f per cent when using %d points\n",100*error,npoints);
}
Пример #21
0
void Plot::FitSignal(int mode, int fitMode) {

	const int nPar = 6;
	TRandom ran;

	if(mode==0) {
		gStyle->SetOptLogy(1);
	} else {
		gStyle->SetOptLogy(0);
	}
	gStyle->SetOptStat(0);
	gStyle->SetOptTitle(0);
	const float limitBinSize = 2.0; // **** bin size here
	TCanvas* c = NewCanvas();
	c->Divide(1,2);

	gROOT->cd();
	TH1F* cc = new TH1F("CCSignal","CC Signal",500,0.0,1000.0);
	TH1F* ccBg = new TH1F("CCBgFit","CC Bg Fit",500,0.0,1000.0);
	TH1F* ccBgErr = new TH1F("CCBgErr","CC Bg Err",500,0.0,1000.0);
	TH1F* ccBgP = new TH1F("CCBgPlus","CC Bg Plus",500,0.0,1000.0);
	TH1F* ccBgM = new TH1F("CCBgMinus","CC Bg Minus",500,0.0,1000.0);
	TH1F* cp = new TH1F("CPSignal","CP Signal",500,0.0,1000.0);
	TH1F* cpBg = new TH1F("CPBgFit","CP Bg Fit",500,0.0,1000.0);
	TH1F* cpBgErr = new TH1F("CPBgErr","CP Bg Err",500,0.0,1000.0);
	TH1F* cpBgP = new TH1F("CPBgPlus","CP Bg Plus",500,0.0,1000.0);
	TH1F* cpBgM = new TH1F("CPBgMinus","CP Bg Minus",500,0.0,1000.0);
	TMatrixD matrix(nPar,nPar);

	fd->cd();

	TH1F* hInt,*hBgInt;
	char fitname[100];
	for(int ind=0; ind<2; ind++) {
		if(debug) printf("starting ind %i\n",ind);
		c->cd(ind+1);
		gStyle->SetOptLogy(1);
		printf("Starting %i ######################################\n",ind);

		TH1F* h;
		//char cind[20];
		//char handle[100];
		//sprintf(handle,"side_1exp_%02i_%02i_%02i",ind,mode,fitMode);
		TF1* fits[4];
		//TF1* dpx[4];
		if(debug) printf("looking for h %i\n",int(fd));
		if(ind==0) {
			h = (TH1F*)fd->FindObjectAny("pair_mass_2GeV1");
		} else if(ind==1) {
			h = (TH1F*)fd->FindObjectAny("pair_mass_2GeV3");
		}
		if(debug) printf("new h %i\n",int(h));

		if(debug) printf("new fit\n");
		sprintf(fitname,"hfit_%1i",ind);
		fits[ind] = new TF1(fitname,"([0]*pow((x-30.0),[1])+[3]*pow((x-30.0),0.2))*([2]*exp(-[2]*(x-30.0))+[4]*[5]*exp(-[5]*(x-30.0)))",30.0,500.0);
		//fits[ind] = new TF1(fitname,"([0]*((1-[3])*pow((x-30.0),[1])+[3]*pow((x-30.0),0.2)))*(exp(-[2]*(x-30.0))+[4]*exp(-[5]*(x-30.0)))",30.0,500.0);
		fits[ind]->SetParameter(0,0.0004);
		fits[ind]->SetParameter(1,2);
		fits[ind]->SetParameter(2,0.02);
		fits[ind]->SetParameter(3,0.005);
		//fits[ind]->SetParameter(3,0.5);
		fits[ind]->SetParameter(4,1.005);
		fits[ind]->SetParameter(5,0.05);

		float llim = 30.0;
		h->Fit(fits[ind],"LN","",llim,1000.0);

		double par[20],parMin[20],fval,fvalMin;
		for(int i=0; i<nPar; i++) parMin[i] = fits[ind]->GetParameter(i);

		gMinuit->Eval(nPar,0,fvalMin,parMin,0);
		//printf("got back %10.5f\n",fvalMin);

		// save the fit results in a histogram, for limit program
		for(int ibin=16; ibin<250; ibin++) {
			float xx = h->GetBinCenter(ibin);
			float yy = fits[ind]->Eval(xx);
			if(ind==0) {
				cc->SetBinContent(ibin,h->GetBinContent(ibin));
				ccBg->SetBinContent(ibin,yy);
				ccBgErr->SetBinContent(ibin,0.0);
				ccBgP->SetBinContent(ibin,0.0);
				ccBgM->SetBinContent(ibin,99999.0);
			} else {
				cp->SetBinContent(ibin,h->GetBinContent(ibin));
				cpBg->SetBinContent(ibin,yy);
				cpBgErr->SetBinContent(ibin,0.0);
				cpBgP->SetBinContent(ibin,0.0);
				cpBgM->SetBinContent(ibin,99999.0);
			}
		}

		//vary the parameters to find an error envelope
		double par2[20],fval2=1e10;
		int pslim = (ind==0?25000:150000);
		for(int ips=0; ips<pslim; ips++) {
			if(ips%10000==0) printf("Processing %d\n",ips);
			for(int i=0; i<nPar; i++) {
				par[i] = parMin[i];
			}
			for(int i=0; i<nPar; i++) {
				//int i = (ips%2==0?0:3);
				par[i] = parMin[i]+(2.0*(ran.Uniform()-0.5))*fits[ind]->GetParError(i);
			}
			fval = 0.0;
			gMinuit->Eval(nPar,0,fval,par,0);
			if((fval-fvalMin)<1.0) {
				printf("Found nearby min %10.5f\n",fval-fvalMin);
				float eOld,eNew;
				for(int ibin=16; ibin<250; ibin++) {
					float xx = h->GetBinCenter(ibin);
					for(int i=0; i<nPar; i++) fits[ind]->SetParameter(i,par[i]);
					float yy = fits[ind]->Eval(xx);
					for(int i=0; i<nPar; i++) fits[ind]->SetParameter(i,parMin[i]);
					float yyMin = fits[ind]->Eval(xx);
					TH1F *hBgErr,*hBgP,*hBgM;
					if(ind==0) {
						hBgErr = ccBgErr; hBgP = ccBgP; hBgM = ccBgM;
					} else {
						hBgErr = cpBgErr; hBgP = cpBgP; hBgM = cpBgM;
					}

					eOld = hBgErr->GetBinContent(ibin);
					eNew = yy - yyMin;
					if(eOld>fabs(eNew)) hBgErr->SetBinContent(ibin,fabs(eNew));
					eOld = hBgP->GetBinContent(ibin);
					if(yy>eOld)  hBgP->SetBinContent(ibin,yy);
					eOld = hBgM->GetBinContent(ibin);
					if(yy<eOld)  hBgM->SetBinContent(ibin,yy);
				}

			} // end if near maximum

			/*
				if(fval<fval2) {
				for(int i=0; i<nPar; i++) par2[i] = par[i];
				fval2 = fval;
				}
				*/
		}

		/*
			printf("forcing new fit..\n");
			for(int i=0; i<nPar; i++) {
			printf("old,new = %10.5f %10.5f\n",parMin[i],par2[i]);
			fits[ind]->SetParameter(i,par2[i]);
			}
			*/

		// restore original fit
		fval = 0.0;
		gMinuit->Eval(nPar,0,fval,parMin,0);
		for(int i=0; i<nPar; i++) fits[ind]->SetParameter(i,parMin[i]);



		//extract fit error matrix
		gMinuit->mnemat(matrix.GetMatrixArray(),nPar);
		matrix.Print();

		for(int i=0; i<nPar; i++) {
			for(int j=0; j<nPar; j++) {
				printf("%10.5f",matrix(i,j)/sqrt(matrix(i,i)*matrix(j,j)));
			}
			printf("\n");
		}
		//matrix.Draw("text");

		float hm = h->GetMaximum();
		if(mode==0) {
			//TAxis* ax = h->GetXaxis();
			//ax->SetRangeUser(24.1,199.9);
			h->SetMaximum(1.2*hm);
			//h->SetMinimum(0.0);
		} else if(mode==1) {
			TAxis* ax = h->GetXaxis();
			ax->SetRangeUser(20.0,500.0);
			h->SetMaximum(1.15*hm);
			h->SetMinimum(0.0);
		}


		h->Draw();
		fits[ind]->SetLineColor(1);
		fits[ind]->SetLineWidth(2.0);
		fits[ind]->Draw("SAME");
		// find chi2's and KS's
		//AnaChiKs(h,fits[ind]);



		TAxis* ax,*ay;
		ax = h->GetXaxis(); 
		ay = h->GetYaxis();
		ax->SetTitle("m(#gamma#gamma) (GeV/c^{2})"); 
		ay->SetTitle("Entries/2 GeV/c^{2}");
		ax->CenterTitle(); ay->CenterTitle();
		ax->SetTitleOffset(0.9);
		ay->SetTitleOffset(1.0);
		ax->SetTitleSize(0.08);
		ay->SetTitleSize(0.07);
		ax->SetLabelSize(0.07);
		ay->SetLabelSize(0.07);

		gPad->SetLeftMargin(0.16);
		gPad->SetBottomMargin(0.16);

		TText* text;
		text = new TLatex(0.5,0.8,"Diphoton Data");
		text->SetNDC(true);
		text->SetTextSize(0.06);
		text->Draw();
		if(ind==0)      text = new TLatex(0.5,0.72,"Central-Central");
		else if(ind==1) text = new TLatex(0.5,0.72,"Central-Plug");
		text->SetNDC(true);
		text->SetTextSize(0.06);
		text->Draw();
		if(ind==0) {
			text = new TLatex(0.15,0.92,"W/Z H#rightarrow X(#gamma#gamma)");
			text->SetNDC(true);
			text->SetTextSize(0.08);
			text->Draw();

			text = new TLatex(0.5,0.92,"CDF Run II Preliminary, 2.0 fb^{-1}");
			text->SetNDC(true);
			text->SetTextSize(0.06);
			text->Draw();
		}    

		/*
			if(debug) printf("start loop\n");
			int ibin;
			for(ibin=16; ibin<=250; ibin++) {
			if(debug) printf("start bin            %i\n",ibin);
			float xx = (ibin-0.5)*2.0; // *** bin width here
			if(debug) printf("-1 test ibin %i\n",ibin);
			float yy = fits[ind]->Eval(xx);
		//printf("%f  yy= %f \n",xx,yy);
		// the derivative of this yield wrt parameters
		if(debug) printf("0 test ibin %i\n",ibin);
		double y0 = yy;
		if(debug) printf("1 test ibin %i\n",ibin);
		TMatrixD vv(nPar,1);
		float dirSize = 0.5;
		for(int i=0; i<nPar; i++){
		int ipar = i;
		double par = fits[ind]->GetParameter(ipar);
		double spar = fits[ind]->GetParError(ipar);
		double parp = par + dirSize*spar;
		fits[ind]->SetParameter(ipar,parp);
		double yp = fits[ind]->Eval(xx);
		vv(i,0) = limitBinSize*(yp-y0)/(dirSize*spar);
		fits[ind]->SetParameter(ipar,par);
		//printf("%f %f %f\n",yp,y0,spar);
		}
		//vv.Print();
		if(debug) printf("start matrix %i\n",ibin);
		TMatrixD tempM(matrix, TMatrixDBase::kMult, vv);
		//matrix.Print();
		TMatrixD tempN(vv, TMatrixDBase::kTransposeMult, tempM);
		//tempN.Print();
		float bgSig = 0.0;
		if(tempN(0,0)>0.0) bgSig = sqrt(tempN(0,0));
		// ****** hack temp  **********
		bgSig = 0.3*y0;


		// file hists to be saved
		if(debug) printf("start fill %i\n",ibin);
		if(ind==0) {
		//printf("filling cc %i %f\n",ibin,h->GetBinContent(ibin));
		cc->SetBinContent(ibin,h->GetBinContent(ibin));
		//printf("getting cc %i %f\n",ibin,cc->GetBinContent(ibin));
		ccBg->SetBinContent(ibin,yy);
		ccBgErr->SetBinContent(ibin,bgSig);
		ccBgP->SetBinContent(ibin,yy+bgSig);
		ccBgM->SetBinContent(ibin,TMath::Max(yy-bgSig,float(0.0)));
		//if(ibin==27) {
		//printf("bg %f %f \n",yy,bgSig);
		//}
		} else {
		cp->SetBinContent(ibin,h->GetBinContent(ibin));
		cpBg->SetBinContent(ibin,yy);
		cpBgErr->SetBinContent(ibin,bgSig);
		cpBgP->SetBinContent(ibin,yy+bgSig);
		cpBgM->SetBinContent(ibin,TMath::Max(yy-bgSig,float(0.0)));
		}
		if(debug) printf("end fill %i\n",ibin);
		}
		*/

	}

	printf("cc plus  BG=%f\n",ccBgP->GetSum());
	printf("cc minus BG=%f\n",ccBgM->GetSum());
	printf("cp plus  BG=%f\n",cpBgP->GetSum());
	printf("cp minus BG=%f\n",cpBgM->GetSum());

	char fn[100];
	if(mode==0) {
		sprintf(fn,"FitSignal_%d",fitMode);
		savePlot(c,fn);
	} else if(mode==1) {
		sprintf(fn,"FitSignalLin_%d",fitMode);
		savePlot(c,fn);
	}

	//if(mode!=0) return;

	// plot of fit results
	gStyle->SetOptLogy(0);
	c = NewCanvas();
	c->Divide(1,2);

	c->cd(1);
	cc->Draw();
	ccBg->Draw("SAME");
	c->cd(2);
	ccBgErr->SetMinimum(0.0); ccBgErr->SetMaximum(4.0); 
	ccBgErr->Draw();
	ccBgP->SetLineStyle(2); ccBgP->Draw("SAME");
	ccBgM->SetLineStyle(2); ccBgM->Draw("SAME");

	savePlot(c,"FitSignalResultsCC");

	c = NewCanvas();
	c->Divide(1,2);

	c->cd(1);
	cp->Draw();
	cpBg->Draw("SAME");
	c->cd(2);
	cpBgErr->SetMinimum(0.0); cpBgErr->SetMaximum(4.0); 
	cpBgErr->Draw();
	cpBgP->SetLineStyle(2); cpBgP->Draw("SAME");
	cpBgM->SetLineStyle(2); cpBgM->Draw("SAME");

	savePlot(c,"FitSignalResultsCP");

	char title[100];
	if(name) {
		sprintf(title,"TPeaksHiggs_FitSignalHist_%s.root",name);
		TFile* ff = new TFile(title,"RECREATE");
		gROOT->GetList()->Write();
		ff->Close();
	}

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

  DrawTools::setStyle();

  std::string runName = "precalib_BGO_pedestal_noSource";
  if( argc>1 ) {
    std::string runName_str(argv[1]);
    runName = runName_str;
  }

  NORDERS = 6;
  if( argc>2 ) {
    NORDERS = atoi(argv[2]);
    std::cout << "-> NORDER is set to: " << NORDERS << std::endl;
  }


  std::string fileName = "../PositionAnalysis/data/run_" + runName + ".root";
  TFile* file = TFile::Open(fileName.c_str());
  
  
  if( argc>1 ) {
    std::string runName_str(argv[1]);
    runName = runName_str;
  }
  if( file==0 ) {
    std::cout << "ERROR! Din't find file " << fileName << std::endl;
    std::cout << "Exiting." << std::endl;
    exit(11);
  }
  
  TTree* tree = (TTree*)file->Get("eventRawData");
  UInt_t evtNumber;
  tree->SetBranchAddress( "evtNumber", &evtNumber );
  UInt_t adcData[40];
  tree->SetBranchAddress( "adcData", adcData );
  UInt_t adcBoard[40];
  tree->SetBranchAddress( "adcBoard", adcBoard );
  UInt_t adcChannel[40];
  tree->SetBranchAddress( "adcChannel", adcChannel );
  
  int nentries = tree->GetEntries();

  std::string outfileName = "calibAn_" + runName + ".root";
  TFile* outFile = TFile::Open( outfileName.c_str(), "RECREATE" );

  TH1D* h1_cef3_0   = new TH1D("cef3_0",   "", 400, 0., 400.);
  TH1D* h1_cef3_1   = new TH1D("cef3_1",   "", 400, 0., 400.);
  TH1D* h1_cef3_2   = new TH1D("cef3_2",   "", 400, 0., 400.);
  TH1D* h1_cef3_3   = new TH1D("cef3_3",   "", 400, 0., 400.);
  TH1D* h1_cef3_tot = new TH1D("cef3_tot", "", 400, 0., 4.*400.);

  TH1D* h1_cef3_corr_0   = new TH1D("cef3_corr_0",   "", 400, 0., 400.);
  TH1D* h1_cef3_corr_1   = new TH1D("cef3_corr_1",   "", 385, 0., 400.4);
  TH1D* h1_cef3_corr_2   = new TH1D("cef3_corr_2",   "", 400, 0., 404.);
  TH1D* h1_cef3_corr_3   = new TH1D("cef3_corr_3",   "", 400, 0., 400.);
  TH1D* h1_cef3_corr_tot = new TH1D("cef3_corr_tot", "", 400, 0., 4.*400.);

  TH1D* h1_cef3_pedSubtracted_0   = new TH1D("cef3_pedSubtracted_0",   "", 400, 0., 400.);
  TH1D* h1_cef3_pedSubtracted_1   = new TH1D("cef3_pedSubtracted_1",   "", 400, 0., 400.);
  TH1D* h1_cef3_pedSubtracted_2   = new TH1D("cef3_pedSubtracted_2",   "", 400, 0., 400.);
  TH1D* h1_cef3_pedSubtracted_3   = new TH1D("cef3_pedSubtracted_3",   "", 400, 0., 400.);

  TH1D* h1_cef3_pedSubtracted_corr_0   = new TH1D("cef3_pedSubtracted_corr_0",   "", 400, 0., 400.*1.11228);
  TH1D* h1_cef3_pedSubtracted_corr_1   = new TH1D("cef3_pedSubtracted_corr_1",   "", 400, 0., 400.*0.855333);
  TH1D* h1_cef3_pedSubtracted_corr_2   = new TH1D("cef3_pedSubtracted_corr_2",   "", 400, 0., 400.*0.97973);
  TH1D* h1_cef3_pedSubtracted_corr_3   = new TH1D("cef3_pedSubtracted_corr_3",   "", 400, 0., 400.*1.08781); 

  TH1D* h1_cef3_pedSubtracted_corr_sum   = new TH1D("cef3_pedSubtracted_sum",   "", 400, 0., 400.);
  TH1D* h1_cef3_pedSubtracted_corr_sum_dummy   = new TH1D("cef3_pedSubtracted_sum",   "", 400, 0., 400.);

  TH1D* h1_cef3_pedSubtracted_corr_rebin_0   = new TH1D("cef3_pedSubtracted_corr_rebin_0",   "", 200, 0., 400.*1.11228);
  TH1D* h1_cef3_pedSubtracted_corr_rebin_1   = new TH1D("cef3_pedSubtracted_corr_rebin_1",   "", 200, 0., 400.*0.855333);
  TH1D* h1_cef3_pedSubtracted_corr_rebin_2   = new TH1D("cef3_pedSubtracted_corr_rebin_2",   "", 200, 0., 400.*0.97973);
  TH1D* h1_cef3_pedSubtracted_corr_rebin_3   = new TH1D("cef3_pedSubtracted_corr_rebin_3",   "", 200, 0., 400.*1.08781);



  TH1D* h1_cef3_pedSubtracted_corr_muQ_0   = new TH1D("cef3_pedSubtracted_corr_muQ_0",   "", 400, 0., 400.*1.19514);
  TH1D* h1_cef3_pedSubtracted_corr_muQ_1   = new TH1D("cef3_pedSubtracted_corr_muQ_1",   "", 400, 0., 400.*0.860177);
  TH1D* h1_cef3_pedSubtracted_corr_muQ_2   = new TH1D("cef3_pedSubtracted_corr_muQ_2",   "", 400, 0., 400.*0.952363);
  TH1D* h1_cef3_pedSubtracted_corr_muQ_3   = new TH1D("cef3_pedSubtracted_corr_muQ_3",   "", 400, 0., 400.*0.977169);

  TH1D* h1_cef3_pedSubtracted_corr_muMean_0   = new TH1D("cef3_pedSubtracted_corr_muMean_0",   "", 400, 0., 400.*1.09716);
  TH1D* h1_cef3_pedSubtracted_corr_muMean_1   = new TH1D("cef3_pedSubtracted_corr_muMean_1",   "", 400, 0., 400.*0.843707);
  TH1D* h1_cef3_pedSubtracted_corr_muMean_2   = new TH1D("cef3_pedSubtracted_corr_muMean_2",   "", 400, 0., 400.*0.966413);
  TH1D* h1_cef3_pedSubtracted_corr_muMean_3   = new TH1D("cef3_pedSubtracted_corr_muMean_3",   "", 400, 0., 400.*1.07241);


  // there is only one cosmic run
  unsigned int runNumber_;
  runNumber_=91;  


  std::string pedestalFileName = "../PositionAnalysis/pedestalFile.root";
  std::vector<std::pair<float, float> > pedestals = getPedestals( "cef3", pedestalFileName, runNumber_ );
  std::cout << std::endl;
  std::cout << "-> Got pedestals of CeF3: " << std::endl;
  for( unsigned i=0; i<CEF3_CHANNELS; ++i )
    std::cout << " CeF3 Channel " << i << ": " << pedestals[i].first << " (+- " << pedestals[i].second << ")" << std::endl;
  std::cout << std::endl;


  int nSigma=4;  

  for( unsigned iEntry=0; iEntry<nentries; ++iEntry ) {
    
    tree->GetEntry(iEntry);
    
    if( iEntry % 5000 == 0 ) std::cout << "Entry: " << iEntry << " / " << nentries << std::endl;
    
    for( unsigned i=0; i<40; ++i ) {
      
      int board  = adcBoard[i];
      int channel= adcChannel[i];
      
      float cef3=0;
      
      
      if( board==CEF3_ADC_BOARD ) {
	if( channel==(CEF3_ADC_START_CHANNEL  ) ){
	  h1_cef3_0->Fill(adcData[i]);
	  cef3+=adcData[i];
	  if(adcData[i]>(pedestals[0].first + nSigma*pedestals[0].second)) h1_cef3_pedSubtracted_0->Fill(adcData[i]-pedestals[0].first);
	}
        else if( channel==(CEF3_ADC_START_CHANNEL+1) ){
	  h1_cef3_1->Fill(adcData[i]);
	  cef3+=adcData[i];
	  if(adcData[i]>(pedestals[1].first + nSigma*pedestals[1].second))h1_cef3_pedSubtracted_1->Fill(adcData[i]-pedestals[1].first);
	}
        else if( channel==(CEF3_ADC_START_CHANNEL+2) ) {
	  h1_cef3_2->Fill(adcData[i]);
	  cef3+=adcData[i];
	  if(adcData[i]>(pedestals[2].first + nSigma*pedestals[2].second))h1_cef3_pedSubtracted_2->Fill(adcData[i]-pedestals[2].first);
	}
        else if( channel==(CEF3_ADC_START_CHANNEL+3) ) {
	  h1_cef3_3->Fill(adcData[i]);
	  cef3+=adcData[i];
	  if(adcData[i]>(pedestals[3].first + nSigma*pedestals[3].second))h1_cef3_pedSubtracted_3->Fill(adcData[i]-pedestals[3].first);
	}
	h1_cef3_tot->Fill(cef3);
      }
      
    }
  }




  h1_cef3_0->SetLineWidth(2);
  h1_cef3_1->SetLineWidth(2);
  h1_cef3_2->SetLineWidth(2);
  h1_cef3_3->SetLineWidth(2);

  h1_cef3_0->SetLineColor(kBlack);
  h1_cef3_1->SetLineColor(kRed);
  h1_cef3_2->SetLineColor(kBlue);
  h1_cef3_3->SetLineColor(kMagenta);

  h1_cef3_corr_0->SetLineWidth(2);
  h1_cef3_corr_1->SetLineWidth(2);
  h1_cef3_corr_2->SetLineWidth(2);
  h1_cef3_corr_3->SetLineWidth(2);

  h1_cef3_corr_0->SetLineColor(kBlack);
  h1_cef3_corr_1->SetLineColor(kRed);
  h1_cef3_corr_2->SetLineColor(kBlue);
  h1_cef3_corr_3->SetLineColor(kMagenta);

  h1_cef3_pedSubtracted_0->SetLineWidth(2);
  h1_cef3_pedSubtracted_1->SetLineWidth(2);
  h1_cef3_pedSubtracted_2->SetLineWidth(2);
  h1_cef3_pedSubtracted_3->SetLineWidth(2);

  h1_cef3_pedSubtracted_0->SetLineColor(kBlack);
  h1_cef3_pedSubtracted_1->SetLineColor(kRed);
  h1_cef3_pedSubtracted_2->SetLineColor(kBlue);
  h1_cef3_pedSubtracted_3->SetLineColor(kMagenta);

  h1_cef3_pedSubtracted_corr_0->SetLineWidth(2);
  h1_cef3_pedSubtracted_corr_1->SetLineWidth(2);
  h1_cef3_pedSubtracted_corr_2->SetLineWidth(2);
  h1_cef3_pedSubtracted_corr_3->SetLineWidth(2);

  h1_cef3_pedSubtracted_corr_0->SetLineColor(kBlack);
  h1_cef3_pedSubtracted_corr_1->SetLineColor(kRed);
  h1_cef3_pedSubtracted_corr_2->SetLineColor(kBlue);
  h1_cef3_pedSubtracted_corr_3->SetLineColor(kMagenta);

  h1_cef3_pedSubtracted_corr_muQ_0->SetLineWidth(2);
  h1_cef3_pedSubtracted_corr_muQ_1->SetLineWidth(2);
  h1_cef3_pedSubtracted_corr_muQ_2->SetLineWidth(2);
  h1_cef3_pedSubtracted_corr_muQ_3->SetLineWidth(2);
			     
  h1_cef3_pedSubtracted_corr_muQ_0->SetLineColor(kBlack);
  h1_cef3_pedSubtracted_corr_muQ_1->SetLineColor(kRed);
  h1_cef3_pedSubtracted_corr_muQ_2->SetLineColor(kBlue);
  h1_cef3_pedSubtracted_corr_muQ_3->SetLineColor(kMagenta);

  h1_cef3_pedSubtracted_corr_muMean_0->SetLineWidth(2);
  h1_cef3_pedSubtracted_corr_muMean_1->SetLineWidth(2);
  h1_cef3_pedSubtracted_corr_muMean_2->SetLineWidth(2);
  h1_cef3_pedSubtracted_corr_muMean_3->SetLineWidth(2);
			     
  h1_cef3_pedSubtracted_corr_muMean_0->SetLineColor(kBlack);
  h1_cef3_pedSubtracted_corr_muMean_1->SetLineColor(kRed);
  h1_cef3_pedSubtracted_corr_muMean_2->SetLineColor(kBlue);
  h1_cef3_pedSubtracted_corr_muMean_3->SetLineColor(kMagenta);


  //plot uncorr energy (before intercalibration)
  TCanvas* cuncorr = new TCanvas( "cuncorr", "", 600, 600 );



  cuncorr->cd();
  cuncorr->SetLogy();

  TH1D* histo_axes = new TH1D("cef3_0",   "", 400, 0., 350.);


  histo_axes->GetXaxis()->SetRangeUser(80.,350.);
  histo_axes->GetYaxis()->SetRangeUser(10.,h1_cef3_0->GetMaximum()+h1_cef3_0->GetMaximum()*0.10);
  histo_axes->SetXTitle( "ADC Counts" );
  histo_axes->Draw();

  TLegend* legend = new TLegend( 0.7, 0.7, 0.90, 0.9 );
  legend->SetLineColor(0);
  legend->SetFillColor(0);
  legend->SetFillStyle(0);
  legend->SetTextSize(0.038);
  legend->AddEntry( h1_cef3_0, "channel 0", "L" );
  legend->AddEntry( h1_cef3_1, "channel 1", "L" );
  legend->AddEntry( h1_cef3_2, "channel 2", "L" );
  legend->AddEntry( h1_cef3_3, "channel 3", "L" );
  legend->Draw("same");


  h1_cef3_0->Draw("same");
  h1_cef3_1->Draw("same");
  h1_cef3_2->Draw("same");
  h1_cef3_3->Draw("same");

  cuncorr->SaveAs("uncorrEnergyAllChannels.png");
  cuncorr->SaveAs("uncorrEnergyAllChannels.eps");

  TCanvas* cuncorr_2 = new TCanvas( "cuncorr_2", "", 600, 600 );

  cuncorr_2->cd();
  cuncorr_2->SetLogy();

  histo_axes->GetXaxis()->SetRangeUser(120.,200.);
  histo_axes->GetYaxis()->SetRangeUser(10.,h1_cef3_0->GetMaximum()+h1_cef3_0->GetMaximum()*0.10);
  histo_axes->SetXTitle( "ADC Counts" );
  histo_axes->Draw();


  h1_cef3_0->Draw("same");
  h1_cef3_1->Draw("same");
  h1_cef3_2->Draw("same");
  h1_cef3_3->Draw("same");

  legend->Draw("same");

  cuncorr_2->SaveAs("uncorrEnergyAllChannels_zoom.png");
  cuncorr_2->SaveAs("uncorrEnergyAllChannels_zoom.eps");

  //plot uncorr energy (before intercalibration) for pedSubtracted
  TCanvas* cuncorr_pedSubtracted = new TCanvas( "cuncorr_pedSubtracted", "", 600, 600 );


  cuncorr_pedSubtracted->cd();
  cuncorr_pedSubtracted->SetLogy();


  histo_axes->GetXaxis()->SetRangeUser(0.,250.);
  histo_axes->GetYaxis()->SetRangeUser(10.,h1_cef3_pedSubtracted_0->GetMaximum()+h1_cef3_pedSubtracted_0->GetMaximum()*0.10);
  histo_axes->SetXTitle( "ADC Counts" );
  histo_axes->Draw();

  legend->Draw("same");


  h1_cef3_pedSubtracted_0->Draw("same");
  h1_cef3_pedSubtracted_1->Draw("same");
  h1_cef3_pedSubtracted_2->Draw("same");
  h1_cef3_pedSubtracted_3->Draw("same");

  cuncorr_pedSubtracted->SaveAs("uncorrEnergyAllChannelspedSubtracted.png");
  cuncorr_pedSubtracted->SaveAs("uncorrEnergyAllChannelspedSubtracted.eps");


  TCanvas* cuncorr_pedSubtracted_2 = new TCanvas( "cuncorr_pedSubtracted_2", "", 600, 600 );

  cuncorr_pedSubtracted_2->cd();
  cuncorr_pedSubtracted_2->SetLogy();

  histo_axes->GetXaxis()->SetRangeUser(20.,100.);
  histo_axes->GetYaxis()->SetRangeUser(10.,h1_cef3_pedSubtracted_0->GetMaximum()+h1_cef3_pedSubtracted_0->GetMaximum()*0.10);
  histo_axes->SetXTitle( "ADC Counts" );
  histo_axes->Draw();


  h1_cef3_pedSubtracted_0->Draw("same");
  h1_cef3_pedSubtracted_1->Draw("same");
  h1_cef3_pedSubtracted_2->Draw("same");
  h1_cef3_pedSubtracted_3->Draw("same");

  legend->Draw("same");

  cuncorr_pedSubtracted_2->SaveAs("uncorrEnergyAllChannelspedSubtracted_zoom.png");
  cuncorr_pedSubtracted_2->SaveAs("uncorrEnergyAllChannelspedSubtracted_zoom.eps");



  //intercalibration of single fibers with photoelectrons
  FitResults fr_0 = fitSingleHisto( h1_cef3_0, 110., 135., 138., 185. );
  FitResults fr_1 = fitSingleHisto( h1_cef3_1, 100., 125., 125., 190. );
  FitResults fr_2 = fitSingleHisto( h1_cef3_2, 100., 125., 128., 190. );
  FitResults fr_3 = fitSingleHisto( h1_cef3_3, 100., 125., 137., 198. );

  std::vector<float> lowerFitBoundary;
  lowerFitBoundary.push_back(137.);
  lowerFitBoundary.push_back(125.);
  lowerFitBoundary.push_back(127.);
  lowerFitBoundary.push_back(137.);

  

  FitResults fr_pedSubtracted_0 = fitSingleHisto( h1_cef3_pedSubtracted_0, 0., 0., lowerFitBoundary[0]-pedestals[0].first, 185.-pedestals[0].first );
  FitResults fr_pedSubtracted_1 = fitSingleHisto( h1_cef3_pedSubtracted_1, 0., 0., lowerFitBoundary[1]-pedestals[1].first, 190.-pedestals[1].first );
  FitResults fr_pedSubtracted_2 = fitSingleHisto( h1_cef3_pedSubtracted_2, 0., 0., lowerFitBoundary[2]-pedestals[2].first, 190.-pedestals[2].first );
  FitResults fr_pedSubtracted_3 = fitSingleHisto( h1_cef3_pedSubtracted_3, 0., 0., lowerFitBoundary[3]-pedestals[3].first, 198.-pedestals[3].first );


  std::vector<float> correctionFactors = intercalibrateFibers(fr_0,fr_1,fr_2,fr_3,true);
  std::vector<float> correctionFactors_pedSubtracted = intercalibrateFibers(fr_pedSubtracted_0,fr_pedSubtracted_1,fr_pedSubtracted_2,fr_pedSubtracted_3,true);
  std::vector<float> correctionFactors_pedSubtracted_muQ = intercalibrateFibers(fr_pedSubtracted_0,fr_pedSubtracted_1,fr_pedSubtracted_2,fr_pedSubtracted_3,false);

  std::vector<float> mu;
  mu.push_back(fr_0.mu);
  mu.push_back(fr_1.mu);
  mu.push_back(fr_2.mu);
  mu.push_back(fr_3.mu);
  float mumean=0.;


  for(int i=0;i<4;i++){
    mumean+=mu[i];
  }

  mumean=mumean/4.;

  std::vector<float> correctionFactors_pedSubtracted_muMean= intercalibrateFibers(fr_pedSubtracted_0,fr_pedSubtracted_1,fr_pedSubtracted_2,fr_pedSubtracted_3,false,mumean);

  for(int i=0;i<4;i++){
    std::cout<<"correctionFactors "<<correctionFactors[i]<<std::endl;
    std::cout<<"correctionFactors pedSub "<<correctionFactors_pedSubtracted[i]<<std::endl;
    std::cout<<"correctionFactors pedSub muQ "<<correctionFactors_pedSubtracted_muQ[i]<<std::endl;
    std::cout<<"correctionFactors pedSub muMean "<<correctionFactors_pedSubtracted_muMean[i]<<std::endl;
  }
  TRandom a;
  a.SetSeed(100);

  for( unsigned iEntry=0; iEntry<nentries; ++iEntry ) {
    
    tree->GetEntry(iEntry);
    
    if( iEntry % 5000 == 0 ) std::cout << "Entry: " << iEntry << " / " << nentries << std::endl;
    
    for( unsigned i=0; i<40; ++i ) {
      
      int board  = adcBoard[i];
      int channel= adcChannel[i];
      
      
      float cef3_corr=0;

      
      if( board==CEF3_ADC_BOARD ) {
	if( channel==(CEF3_ADC_START_CHANNEL  ) ){
	  h1_cef3_corr_0->Fill(adcData[i]*correctionFactors[0]);
	  if(adcData[i]>(pedestals[0].first + nSigma*pedestals[0].second)){
	    h1_cef3_pedSubtracted_corr_0->Fill((adcData[i]-pedestals[0].first)*correctionFactors_pedSubtracted[0]);
	    h1_cef3_pedSubtracted_corr_rebin_0->Fill((adcData[i]-pedestals[0].first)*correctionFactors_pedSubtracted[0]);
	    h1_cef3_pedSubtracted_corr_muQ_0->Fill((adcData[i]-pedestals[0].first)*correctionFactors_pedSubtracted_muQ[0]);
	    h1_cef3_pedSubtracted_corr_muMean_0->Fill((adcData[i]-pedestals[0].first)*correctionFactors_pedSubtracted_muMean[0]);
	    h1_cef3_pedSubtracted_corr_sum->Fill(a.Uniform(adcData[i]-pedestals[0].first-0.5,adcData[i]-pedestals[0].first+0.5)*correctionFactors_pedSubtracted[0]);
	  }
	  cef3_corr+=adcData[i]*correctionFactors[0];
	}
        else if( channel==(CEF3_ADC_START_CHANNEL+1) ){
	  h1_cef3_corr_1->Fill(adcData[i]*correctionFactors[1]);
	  if(adcData[i]>(pedestals[1].first + nSigma*pedestals[1].second)) {
	    h1_cef3_pedSubtracted_corr_1->Fill((adcData[i]-pedestals[1].first)*correctionFactors_pedSubtracted[1]);
	    h1_cef3_pedSubtracted_corr_rebin_1->Fill((adcData[i]-pedestals[1].first)*correctionFactors_pedSubtracted[1]);
	    h1_cef3_pedSubtracted_corr_muQ_1->Fill((adcData[i]-pedestals[1].first)*correctionFactors_pedSubtracted_muQ[1]);
	    h1_cef3_pedSubtracted_corr_muMean_1->Fill((adcData[i]-pedestals[1].first)*correctionFactors_pedSubtracted_muMean[1]);
	    h1_cef3_pedSubtracted_corr_sum->Fill(a.Uniform(adcData[i]-pedestals[1].first-0.5,adcData[i]-pedestals[1].first+0.5)*correctionFactors_pedSubtracted[1]);
	  }
	  cef3_corr+=adcData[i]*correctionFactors[1];
	}
        else if( channel==(CEF3_ADC_START_CHANNEL+2) ) {
	  h1_cef3_corr_2->Fill(adcData[i]*correctionFactors[2]);
	  if(adcData[i]>(pedestals[2].first + nSigma*pedestals[2].second)) {
	    h1_cef3_pedSubtracted_corr_2->Fill((adcData[i]-pedestals[2].first)*correctionFactors_pedSubtracted[2]);
	    h1_cef3_pedSubtracted_corr_rebin_2->Fill((adcData[i]-pedestals[2].first)*correctionFactors_pedSubtracted[2]);
	    h1_cef3_pedSubtracted_corr_muQ_2->Fill((adcData[i]-pedestals[2].first)*correctionFactors_pedSubtracted_muQ[2]);
	    h1_cef3_pedSubtracted_corr_muMean_2->Fill((adcData[i]-pedestals[2].first)*correctionFactors_pedSubtracted_muMean[2]);
	    h1_cef3_pedSubtracted_corr_sum->Fill(a.Uniform(adcData[i]-pedestals[2].first-0.5,adcData[i]-pedestals[2].first+0.5)*correctionFactors_pedSubtracted[2]);
	  }
	  cef3_corr+=adcData[i]*correctionFactors[2];
	}
        else if( channel==(CEF3_ADC_START_CHANNEL+3) ) {
	  h1_cef3_corr_3->Fill(adcData[i]*correctionFactors[3]);
	  if(adcData[i]>(pedestals[3].first + nSigma*pedestals[3].second)){
	    h1_cef3_pedSubtracted_corr_3->Fill((adcData[i]-pedestals[3].first)*correctionFactors_pedSubtracted[3]);
	    h1_cef3_pedSubtracted_corr_rebin_3->Fill((adcData[i]-pedestals[3].first)*correctionFactors_pedSubtracted[3]);
	    h1_cef3_pedSubtracted_corr_muQ_3->Fill((adcData[i]-pedestals[3].first)*correctionFactors_pedSubtracted_muQ[3]);
	    h1_cef3_pedSubtracted_corr_muMean_3->Fill((adcData[i]-pedestals[3].first)*correctionFactors_pedSubtracted_muMean[3]);
	    h1_cef3_pedSubtracted_corr_sum->Fill(a.Uniform(adcData[i]-pedestals[3].first-0.5,adcData[i]-pedestals[3].first+0.5)*correctionFactors_pedSubtracted[3]);
	  }
	  cef3_corr+=adcData[i]*correctionFactors[3];
	}
	h1_cef3_tot->Fill(cef3_corr);
      }
      
    }
  }




  //plot corr energy (after intercalibration)
  TCanvas* ccorr = new TCanvas( "ccorr", "", 600, 600 );

  ccorr->cd();
  ccorr->SetLogy();

  TH2D* h2_axes_corr = new TH2D("axes_corr", "", 10, 0., 350., 10, 10., 1.1*h1_cef3_corr_0->GetMaximum() );
  h2_axes_corr->GetXaxis()->SetRangeUser(80.,350);
  h2_axes_corr->SetXTitle( "ADC Counts" );
  h2_axes_corr->Draw();


  h1_cef3_corr_0->Draw("same");
  h1_cef3_corr_1->Draw("same");
  h1_cef3_corr_2->Draw("same");
  h1_cef3_corr_3->Draw("same");

  legend->Draw("same");

  ccorr->SaveAs("corrEnergyAllChannels.png");
  ccorr->SaveAs("corrEnergyAllChannels.eps");

  //pedsubtracted plot
  ccorr->Clear();

  histo_axes->GetXaxis()->SetRangeUser(0.,250.);
  histo_axes->GetYaxis()->SetRangeUser(10.,h1_cef3_pedSubtracted_0->GetMaximum()+h1_cef3_pedSubtracted_0->GetMaximum()*0.10);
  histo_axes->SetXTitle( "ADC Counts" );
  histo_axes->Draw();

  histo_axes->Draw();

  h1_cef3_pedSubtracted_corr_0->Draw("same");
  h1_cef3_pedSubtracted_corr_1->Draw("same");
  h1_cef3_pedSubtracted_corr_2->Draw("same");
  h1_cef3_pedSubtracted_corr_3->Draw("same");

  legend->Draw("same");

  ccorr->SaveAs("corrEnergyAllChannelspedSubtracted.png");
  ccorr->SaveAs("corrEnergyAllChannelspedSubtracted.eps");

  h1_cef3_pedSubtracted_corr_sum->Rebin(2);
  FitResults fr_corr_sum = fitSingleHisto_sum( h1_cef3_pedSubtracted_corr_sum, 0., 0.,13.,68.,true );

  //plot for the paper. all corr channels sum and fit
  ccorr->Clear();
  ccorr->SetLogy(0);
  ccorr->cd();

  h1_cef3_pedSubtracted_corr_sum->SetLineWidth(2);
  
  h1_cef3_pedSubtracted_corr_sum->GetXaxis()->SetRangeUser(0.,150.);
  h1_cef3_pedSubtracted_corr_sum->GetYaxis()->SetRangeUser(50.,h1_cef3_pedSubtracted_corr_sum->GetMaximum()+h1_cef3_pedSubtracted_corr_sum->GetMaximum()*0.10);
  h1_cef3_pedSubtracted_corr_sum->SetYTitle( "Events / 2" );
  h1_cef3_pedSubtracted_corr_sum->SetXTitle( "ADC Counts" );

 
  h1_cef3_pedSubtracted_corr_sum->Draw();
  //  ccorr->SetLogy(1);
  TPaveText* labelTop = DrawTools::getLabelTop("Cosmic Data");
  labelTop->Draw("same");
  gPad->RedrawAxis(); 
  ccorr->SaveAs("sum_fitted.png");
  ccorr->SaveAs("sum_fitted.eps");
  ccorr->SaveAs("sum_fitted.C");
  //ccorr->SaveAs("sum_fitted_log.png");

  ccorr->Clear();
  h1_cef3_pedSubtracted_corr_sum->Draw();
  labelTop->Draw("same");
  ccorr->SetLogy(1);
  ccorr->SaveAs("sum_fitted_log.png");
  ccorr->SaveAs("sum_fitted_log.eps");
  ccorr->SaveAs("sum_fitted_log.C");


  //unconstrained fit
  FitResults fr_corr_unconstrained_sum = fitSingleHisto_sum( h1_cef3_pedSubtracted_corr_sum, 0., 0.,14.,69.,false );
  
  h1_cef3_pedSubtracted_corr_sum->GetXaxis()->SetRangeUser(0.,150.);
  h1_cef3_pedSubtracted_corr_sum->GetYaxis()->SetRangeUser(50.,h1_cef3_pedSubtracted_corr_sum->GetMaximum()+h1_cef3_pedSubtracted_corr_sum->GetMaximum()*0.10);
  h1_cef3_pedSubtracted_corr_sum->SetXTitle( "ADC Counts" );

 
  h1_cef3_pedSubtracted_corr_sum->Draw();
  ccorr->SetLogy(1);
  ccorr->SaveAs("sum_fitted_log_unc.png");

  ccorr->Clear();
  ccorr->cd();
  h1_cef3_pedSubtracted_corr_sum_dummy->Add(h1_cef3_pedSubtracted_corr_0);
  h1_cef3_pedSubtracted_corr_sum_dummy->Add(h1_cef3_pedSubtracted_corr_1);
  h1_cef3_pedSubtracted_corr_sum_dummy->Add(h1_cef3_pedSubtracted_corr_2);
  h1_cef3_pedSubtracted_corr_sum_dummy->Add(h1_cef3_pedSubtracted_corr_3);

  h1_cef3_pedSubtracted_corr_sum_dummy->Rebin(2);  
  FitResults fr_corr_sum_dummy = fitSingleHisto_sum( h1_cef3_pedSubtracted_corr_sum_dummy, 0., 0.,13.,68.,true );

  h1_cef3_pedSubtracted_corr_sum_dummy->GetXaxis()->SetRangeUser(0.,150.);
  h1_cef3_pedSubtracted_corr_sum_dummy->GetYaxis()->SetRangeUser(50.,h1_cef3_pedSubtracted_corr_sum->GetMaximum()+h1_cef3_pedSubtracted_corr_sum->GetMaximum()*0.10);
  h1_cef3_pedSubtracted_corr_sum_dummy->SetXTitle( "ADC Counts" );
  ccorr->SetLogy(0);

  h1_cef3_pedSubtracted_corr_sum_dummy->Draw();
  ccorr->SaveAs("sum_fitted_log_dummy.png");

  std::cout<<"######################## mean random:"<<h1_cef3_pedSubtracted_corr_sum->GetMean()<<"+-"<<h1_cef3_pedSubtracted_corr_sum->GetMeanError()<<std::endl;
  std::cout<<"######################## mean not random:"<<h1_cef3_pedSubtracted_corr_sum_dummy->GetMean()<<"+-"<<h1_cef3_pedSubtracted_corr_sum_dummy->GetMeanError()<<std::endl;


  cuncorr_pedSubtracted_2->Clear();
  cuncorr_pedSubtracted_2->cd();
  cuncorr_pedSubtracted_2->SetLogy();

  histo_axes->GetXaxis()->SetRangeUser(20.,100.);
  histo_axes->GetYaxis()->SetRangeUser(10.,h1_cef3_pedSubtracted_0->GetMaximum()+h1_cef3_pedSubtracted_0->GetMaximum()*0.10);
  histo_axes->SetXTitle( "ADC Counts" );
  histo_axes->Draw();


  h1_cef3_pedSubtracted_corr_0->Draw("same");
  h1_cef3_pedSubtracted_corr_1->Draw("same");
  h1_cef3_pedSubtracted_corr_2->Draw("same");
  h1_cef3_pedSubtracted_corr_3->Draw("same");

  legend->Draw("same");

  cuncorr_pedSubtracted_2->SaveAs("corrEnergyAllChannelspedSubtracted_zoom.png");
  cuncorr_pedSubtracted_2->SaveAs("corrEnergyAllChannelspedSubtracted_zoom.eps");


  //pedsubtracted plot
  ccorr->Clear();

  histo_axes->GetXaxis()->SetRangeUser(0.,250.);
  histo_axes->GetYaxis()->SetRangeUser(10.,h1_cef3_pedSubtracted_0->GetMaximum()+h1_cef3_pedSubtracted_0->GetMaximum()*0.10);
  histo_axes->SetXTitle( "ADC Counts" );
  histo_axes->Draw();

  histo_axes->Draw();

  h1_cef3_pedSubtracted_corr_muQ_0->Draw("same");
  h1_cef3_pedSubtracted_corr_muQ_1->Draw("same");
  h1_cef3_pedSubtracted_corr_muQ_2->Draw("same");
  h1_cef3_pedSubtracted_corr_muQ_3->Draw("same");

  legend->Draw("same");

  ccorr->SaveAs("corr_muQEnergyAllChannelspedSubtracted.png");
  ccorr->SaveAs("corr_muQEnergyAllChannelspedSubtracted.eps");

  cuncorr_pedSubtracted_2->Clear();
  cuncorr_pedSubtracted_2->cd();
  cuncorr_pedSubtracted_2->SetLogy();

  histo_axes->GetXaxis()->SetRangeUser(20.,100.);
  histo_axes->GetYaxis()->SetRangeUser(10.,h1_cef3_pedSubtracted_0->GetMaximum()+h1_cef3_pedSubtracted_0->GetMaximum()*0.10);
  histo_axes->SetXTitle( "ADC Counts" );
  histo_axes->Draw();


  h1_cef3_pedSubtracted_corr_muQ_0->Draw("same");
  h1_cef3_pedSubtracted_corr_muQ_1->Draw("same");
  h1_cef3_pedSubtracted_corr_muQ_2->Draw("same");
  h1_cef3_pedSubtracted_corr_muQ_3->Draw("same");

  legend->Draw("same");

  cuncorr_pedSubtracted_2->SaveAs("corr_muQEnergyAllChannelspedSubtracted_zoom.png");
  cuncorr_pedSubtracted_2->SaveAs("corr_muQEnergyAllChannelspedSubtracted_zoom.eps");

  //pedsubtracted muMean plot
  ccorr->Clear();

  histo_axes->GetXaxis()->SetRangeUser(0.,250.);
  histo_axes->GetYaxis()->SetRangeUser(10.,h1_cef3_pedSubtracted_0->GetMaximum()+h1_cef3_pedSubtracted_0->GetMaximum()*0.10);
  histo_axes->SetXTitle( "ADC Counts" );
  histo_axes->Draw();

  histo_axes->Draw();

  h1_cef3_pedSubtracted_corr_muMean_0->Draw("same");
  h1_cef3_pedSubtracted_corr_muMean_1->Draw("same");
  h1_cef3_pedSubtracted_corr_muMean_2->Draw("same");
  h1_cef3_pedSubtracted_corr_muMean_3->Draw("same");

  legend->Draw("same");

  ccorr->SaveAs("corr_muMeanEnergyAllChannelspedSubtracted.png");
  ccorr->SaveAs("corr_muMeanEnergyAllChannelspedSubtracted.eps");

  cuncorr_pedSubtracted_2->Clear();
  cuncorr_pedSubtracted_2->cd();
  cuncorr_pedSubtracted_2->SetLogy();

  histo_axes->GetXaxis()->SetRangeUser(20.,100.);
  histo_axes->GetYaxis()->SetRangeUser(10.,h1_cef3_pedSubtracted_0->GetMaximum()+h1_cef3_pedSubtracted_0->GetMaximum()*0.10);
  histo_axes->SetXTitle( "ADC Counts" );
  histo_axes->Draw();


  h1_cef3_pedSubtracted_corr_muMean_0->Draw("same");
  h1_cef3_pedSubtracted_corr_muMean_1->Draw("same");
  h1_cef3_pedSubtracted_corr_muMean_2->Draw("same");
  h1_cef3_pedSubtracted_corr_muMean_3->Draw("same");

  legend->Draw("same");

  cuncorr_pedSubtracted_2->SaveAs("corr_muMeanEnergyAllChannelspedSubtracted_zoom.png");
  cuncorr_pedSubtracted_2->SaveAs("corr_muMeanEnergyAllChannelspedSubtracted_zoom.eps");




  TCanvas* ccorr_2 = new TCanvas( "ccorr_2", "", 600, 600 );

  ccorr_2->cd();
  ccorr_2->SetLogy();

  h2_axes_corr->GetXaxis()->SetRangeUser(120.,200.);

  h2_axes_corr->Draw();
  h1_cef3_corr_0->Draw("same");
  h1_cef3_corr_1->Draw("same");
  h1_cef3_corr_2->Draw("same");
  h1_cef3_corr_3->Draw("same");

  legend->Draw("same");

  ccorr_2->SaveAs("corrEnergyAllChannels_zoom.png");
  ccorr_2->SaveAs("corrEnergyAllChannels_zoom.eps");


  //fit corrected histos
  FitResults fr_corr_0 = fitSingleHisto( h1_cef3_corr_0, 0.966779*120., 0.966779*130., 0.966779*138., 0.966779*185. );
  FitResults fr_corr_1 = fitSingleHisto( h1_cef3_corr_1, 1.04148*100., 1.04148*125., 1.04148*125., 1.04148*189. );
  FitResults fr_corr_2 = fitSingleHisto( h1_cef3_corr_2, 1.01311*100., 1.01311*125., 1.01311*128., 1.01311*189. );
  FitResults fr_corr_3 = fitSingleHisto( h1_cef3_corr_3, 0.984112*100., 0.984112*125., 0.984112*137., 0.984112*200. );

  FitResults fr_pedSubtracted_corr_0 = fitSingleHisto( h1_cef3_pedSubtracted_corr_0, 0., 0., lowerFitBoundary[0]+2-pedestals[0].first, 188.-pedestals[0].first );
  FitResults fr_pedSubtracted_corr_1 = fitSingleHisto( h1_cef3_pedSubtracted_corr_1, 0., 0., lowerFitBoundary[1]-3-pedestals[1].first, 182.-pedestals[1].first );
  FitResults fr_pedSubtracted_corr_2 = fitSingleHisto( h1_cef3_pedSubtracted_corr_2, 0., 0., lowerFitBoundary[2]+1-pedestals[2].first, 188.-pedestals[2].first );
  FitResults fr_pedSubtracted_corr_3 = fitSingleHisto( h1_cef3_pedSubtracted_corr_3, 0., 0., lowerFitBoundary[3]+1-pedestals[3].first, 198.-pedestals[3].first );



  FitResults fr_pedSubtracted_corr_rebin_0 = fitSingleHisto( h1_cef3_pedSubtracted_corr_rebin_0, 0., 0., lowerFitBoundary[0]+2-pedestals[0].first, 189.-pedestals[0].first );
  FitResults fr_pedSubtracted_corr_rebin_1 = fitSingleHisto( h1_cef3_pedSubtracted_corr_rebin_1, 0., 0., lowerFitBoundary[1]-3-pedestals[1].first, 177.-pedestals[1].first );
  FitResults fr_pedSubtracted_corr_rebin_2 = fitSingleHisto( h1_cef3_pedSubtracted_corr_rebin_2, 0., 0., lowerFitBoundary[2]+1-pedestals[2].first, 181.-pedestals[2].first );
  FitResults fr_pedSubtracted_corr_rebin_3 = fitSingleHisto( h1_cef3_pedSubtracted_corr_rebin_3, 0., 0., lowerFitBoundary[3]+1-pedestals[3].first, 196.-pedestals[3].first );





  h1_cef3_0->Write(); 
  h1_cef3_1->Write(); 
  h1_cef3_2->Write(); 
  h1_cef3_3->Write(); 
  h1_cef3_tot->Write(); 
                 
  h1_cef3_corr_0->Write();    
  h1_cef3_corr_1->Write();    
  h1_cef3_corr_2->Write();    
  h1_cef3_corr_3->Write();    
  h1_cef3_corr_tot->Write();  

  outFile->Write(); 


  doSummaryPlots(fr_pedSubtracted_0,fr_pedSubtracted_1,fr_pedSubtracted_2,fr_pedSubtracted_3,fr_pedSubtracted_corr_0,fr_pedSubtracted_corr_1,fr_pedSubtracted_corr_2,fr_pedSubtracted_corr_3);



  return 0;

}
Int_t dieleAna(TString inputlist, TString outfile, Int_t nev=-1, Int_t whichweight = 0)
{

    TH1::SetDefaultSumw2();
    TH3F *p3DEffEle[6][NWEIGHTS+1]; // mult bins, MLP weights + HC
    TH3F *p3DEffPos[6][NWEIGHTS+1];
    TH3F *p3DAccEle[6][NWEIGHTS+1];
    TH3F *p3DAccPos[6][NWEIGHTS+1];
    readAccEffMatrices(p3DAccEle, p3DAccPos, p3DEffEle, p3DEffPos);
    TH2F *smear_ele, *smear_pos;
    TFile *file_smear = new TFile("smearing_matrix.root","read");
    smear_ele = (TH2F*)file_smear->Get("smear_ele");
    smear_pos = (TH2F*)file_smear->Get("smear_pos");

    TRandom random;

/*
    TFile *pEffFile;

    pEffFile = new TFile("Input/EffMatrixMVA2RefAccNewCP_100Mio.root");
    if (pEffFile)
    {
	pEffFile->cd();
	for(Int_t i = 0 ; i < 5 ; i++){
            p3DEffEle[i][6] = (TH3F*) pEffFile->Get(Form("hHistEff3DMult%iNeg",i));
            p3DEffPos[i][6] = (TH3F*) pEffFile->Get(Form("hHistEff3DMult%iPos",i));
     //       p3DEffEle[i] = (TH3F*) pEffFile->Get("hHistEff3DNeg");
      //      p3DEffPos[i] = (TH3F*) pEffFile->Get("hHistEff3DPos");
        }
    }
    else
    {
	Error("DrawFromNtuple constructor","pointer to eff matrix file is NULL");
	for(Int_t i = 0 ; i < 5 ; i++){
	    p3DEffEle[i][6] = NULL;
	    p3DEffPos[i][6] = NULL;
        }
    }
*/

    TH1F *pEventClass;
    TH1F *pEventClass_recur;
    TFile *pEventClassFile;
//    pEventClassFile = new TFile("eventClass_mult_nonempty_4secmult_200fpj_wait.root");
//    pEventClassFile = new TFile("eventClass_target_mult_rplane_nonempty_4secmult.root");
    pEventClassFile = new TFile("eventClass_target_mult_rplane_minmom_nmix_w6.root");
    if (pEventClassFile) {
        pEventClass = (TH1F*)pEventClassFile->Get("eventClass");
        pEventClass_recur = (TH1F*)pEventClassFile->Get("eventClass_recur");
        if (pEventClass == NULL || pEventClass_recur == NULL) {
            Error("DrawFromNtuple constructor","Histogram not found in the event class file");
            exit (-1);
        }
    }    
    else {
        Error("DrawFromNtuple constructor","Event class file not found");
        exit (-1);
    }
    HLoop* loop = new HLoop(kTRUE);  // kTRUE : create Hades  (needed to work with standard eventstructure)
    TString readCategories = "";
    if (inputlist.EndsWith(".list")) {
        loop->addFilesList(inputlist);
    }
    else {
        loop->addMultFiles(inputlist);
    }
    if(!loop->setInput(readCategories)) { exit(1); }
    loop->printCategories();
    loop->readSectorFileList("FileListLepton.list");
    int sectors[6];

    HGeantKine *kine1;
    HGeantKine *kine2;

    HCategory* kineCat = (HCategory*)HCategoryManager::getCategory(catGeantKine);

    HHistMap hM(outfile.Data());
    hM.setSilentFail(kTRUE);

    //------------------------------------------------------------------
    //--------------- begin histo booking -----------------------------------------------------
    //------------------------------------------------------------------------------------------

    const Int_t nbins = 26;
    Double_t xAxis1[nbins+1] = {0, 0.010, 0.020, 0.030, 0.040, 0.050, 0.060, 0.070, 0.080, 0.090, 0.110, 0.130, 0.150, 0.170, 0.200, 0.250, 0.300, 0.350, 0.400, 0.450, 0.500, 0.550, 0.600, 0.700, 0.800, 0.900, 1.};

    hM.addHist(new TH1F(TString("hmassNP"),TString("hmassNP"),nbins,xAxis1));
    hM.addHist(new TH1F(TString("hmassPP"),TString("hmassPP"),nbins,xAxis1));
    hM.addHist(new TH1F(TString("hmassNN"),TString("hmassNN"),nbins,xAxis1));
    hM.addHist(new TH1F(TString("hoAngleNP"),TString("hoAngleNP"),2000,0,200));
    hM.addHist(new TH1F(TString("hoAnglePP"),TString("hoAnglePP"),2000,0,200));
    hM.addHist(new TH1F(TString("hoAngleNN"),TString("hoAngleNN"),2000,0,200));
    hM.addHist(new TH1F(TString("hyNP"),TString("hyNP"),100,0,2));
    hM.addHist(new TH1F(TString("hyPP"),TString("hyPP"),100,0,2));
    hM.addHist(new TH1F(TString("hyNN"),TString("hyNN"),100,0,2));
    hM.addHist(new TH1F(TString("hptNP"),TString("hptNP"),100,0,1000));
    hM.addHist(new TH1F(TString("hptPP"),TString("hptPP"),100,0,1000));
    hM.addHist(new TH1F(TString("hptNN"),TString("hptNN"),100,0,1000));
    hM.addHist(new TH2F(TString("hoAnglemassNP"),TString("hoAnglemassNP"),90,0,180,nbins,xAxis1));
    hM.addHist(new TH2F(TString("hoAnglemassPP"),TString("hoAnglemassPP"),90,0,180,nbins,xAxis1));
    hM.addHist(new TH2F(TString("hoAnglemassNN"),TString("hoAnglemassNN"),90,0,180,nbins,xAxis1));
    hM.addHist(new TH2F(TString("hoAngleptNP"),TString("hoAngleptNP"),90,0,180,120,0,1200));
    hM.addHist(new TH2F(TString("hoAngleptPP"),TString("hoAngleptPP"),90,0,180,120,0,1200));
    hM.addHist(new TH2F(TString("hoAngleptNN"),TString("hoAngleptNN"),90,0,180,120,0,1200));
    hM.addHist(new TH2F(TString("hmassptNP"),TString("hmassptNP"),nbins,xAxis1,120,0,1200));
    hM.addHist(new TH2F(TString("hmassptPP"),TString("hmassptPP"),nbins,xAxis1,120,0,1200));
    hM.addHist(new TH2F(TString("hmassptNN"),TString("hmassptNN"),nbins,xAxis1,120,0,1200));
    hM.addHist(new TH2F(TString("hoAngleyNP"),TString("hoAngleyNP"),90,0,180,100,0,2));
    hM.addHist(new TH2F(TString("hoAngleyPP"),TString("hoAngleyPP"),90,0,180,100,0,2));
    hM.addHist(new TH2F(TString("hoAngleyNN"),TString("hoAngleyNN"),90,0,180,100,0,2));
    hM.addHist(new TH2F(TString("hmassyNP"),TString("hmassyNP"),nbins,xAxis1,100,0,2));
    hM.addHist(new TH2F(TString("hmassyPP"),TString("hmassyPP"),nbins,xAxis1,100,0,2));
    hM.addHist(new TH2F(TString("hmassyNN"),TString("hmassyNN"),nbins,xAxis1,100,0,2));
    hM.addHist(new TH2F(TString("hptyNP"),TString("hptyNP"),120,0,1200,100,0,2));
    hM.addHist(new TH2F(TString("hptyPP"),TString("hptyPP"),120,0,1200,100,0,2));
    hM.addHist(new TH2F(TString("hptyNN"),TString("hptyNN"),120,0,1200,100,0,2));
    hM.addHist(new TH2F(TString("hth1th2NP"),TString("hth1th2NP"),90,0,90,90,0,90));
    hM.addHist(new TH2F(TString("hth1th2PP"),TString("hth1th2PP"),90,0,90,90,0,90));
    hM.addHist(new TH2F(TString("hth1th2NN"),TString("hth1th2NN"),90,0,90,90,0,90));
    hM.addHist(new TH2F(TString("hp1p2NP"),TString("hp1p2NP"),100,0,1100,100,0,1100));
    hM.addHist(new TH2F(TString("hp1p2PP"),TString("hp1p2PP"),100,0,1100,100,0,1100));
    hM.addHist(new TH2F(TString("hp1p2NN"),TString("hp1p2NN"),100,0,1100,100,0,1100));

    for (int i = 0; i < 5; ++i) {
        hM.addHist(new TH1F(TString("hmassNP_eff_multbin")+TString::Itoa(i,10),TString("hmassNP_eff_multbin")+TString::Itoa(i,10),nbins,xAxis1));
        hM.addHist(new TH1F(TString("hmassPP_eff_multbin")+TString::Itoa(i,10),TString("hmassPP_eff_multbin")+TString::Itoa(i,10),nbins,xAxis1));
        hM.addHist(new TH1F(TString("hmassNN_eff_multbin")+TString::Itoa(i,10),TString("hmassNN_eff_multbin")+TString::Itoa(i,10),nbins,xAxis1));
        hM.addHist(new TH1F(TString("hoAngleNP_eff_multbin")+TString::Itoa(i,10),TString("hoAngleNP_eff_multbin")+TString::Itoa(i,10),2000,0,200));
        hM.addHist(new TH1F(TString("hoAnglePP_eff_multbin")+TString::Itoa(i,10),TString("hoAnglePP_eff_multbin")+TString::Itoa(i,10),2000,0,200));
        hM.addHist(new TH1F(TString("hoAngleNN_eff_multbin")+TString::Itoa(i,10),TString("hoAngleNN_eff_multbin")+TString::Itoa(i,10),2000,0,200));
        hM.addHist(new TH1F(TString("hyNP_eff_multbin")+TString::Itoa(i,10),TString("hyNP_eff_multbin")+TString::Itoa(i,10),100,0,2));
        hM.addHist(new TH1F(TString("hyPP_eff_multbin")+TString::Itoa(i,10),TString("hyPP_eff_multbin")+TString::Itoa(i,10),100,0,2));
        hM.addHist(new TH1F(TString("hyNN_eff_multbin")+TString::Itoa(i,10),TString("hyNN_eff_multbin")+TString::Itoa(i,10),100,0,2));
        hM.addHist(new TH1F(TString("hptNP_eff_multbin")+TString::Itoa(i,10),TString("hptNP_eff_multbin")+TString::Itoa(i,10),100,0,1000));
        hM.addHist(new TH1F(TString("hptPP_eff_multbin")+TString::Itoa(i,10),TString("hptPP_eff_multbin")+TString::Itoa(i,10),100,0,1000));
        hM.addHist(new TH1F(TString("hptNN_eff_multbin")+TString::Itoa(i,10),TString("hptNN_eff_multbin")+TString::Itoa(i,10),100,0,1000));
        hM.addHist(new TH2F(TString("hoAnglemassNP_eff_multbin")+TString::Itoa(i,10),TString("hoAnglemassNP_eff_multbin")+TString::Itoa(i,10),90,0,180,nbins,xAxis1));
        hM.addHist(new TH2F(TString("hoAnglemassPP_eff_multbin")+TString::Itoa(i,10),TString("hoAnglemassPP_eff_multbin")+TString::Itoa(i,10),90,0,180,nbins,xAxis1));
        hM.addHist(new TH2F(TString("hoAnglemassNN_eff_multbin")+TString::Itoa(i,10),TString("hoAnglemassNN_eff_multbin")+TString::Itoa(i,10),90,0,180,nbins,xAxis1));
        hM.addHist(new TH2F(TString("hoAngleptNP_eff_multbin")+TString::Itoa(i,10),TString("hoAngleptNP_eff_multbin")+TString::Itoa(i,10),90,0,180,120,0,1200));
        hM.addHist(new TH2F(TString("hoAngleptPP_eff_multbin")+TString::Itoa(i,10),TString("hoAngleptPP_eff_multbin")+TString::Itoa(i,10),90,0,180,120,0,1200));
        hM.addHist(new TH2F(TString("hoAngleptNN_eff_multbin")+TString::Itoa(i,10),TString("hoAngleptNN_eff_multbin")+TString::Itoa(i,10),90,0,180,120,0,1200));
        hM.addHist(new TH2F(TString("hmassptNP_eff_multbin")+TString::Itoa(i,10),TString("hmassptNP_eff_multbin")+TString::Itoa(i,10),nbins,xAxis1,120,0,1200));
        hM.addHist(new TH2F(TString("hmassptPP_eff_multbin")+TString::Itoa(i,10),TString("hmassptPP_eff_multbin")+TString::Itoa(i,10),nbins,xAxis1,120,0,1200));
        hM.addHist(new TH2F(TString("hmassptNN_eff_multbin")+TString::Itoa(i,10),TString("hmassptNN_eff_multbin")+TString::Itoa(i,10),nbins,xAxis1,120,0,1200));
        hM.addHist(new TH2F(TString("hoAngleyNP_eff_multbin")+TString::Itoa(i,10),TString("hoAngleyNP_eff_multbin")+TString::Itoa(i,10),90,0,180,100,0,2));
        hM.addHist(new TH2F(TString("hoAngleyPP_eff_multbin")+TString::Itoa(i,10),TString("hoAngleyPP_eff_multbin")+TString::Itoa(i,10),90,0,180,100,0,2));
        hM.addHist(new TH2F(TString("hoAngleyNN_eff_multbin")+TString::Itoa(i,10),TString("hoAngleyNN_eff_multbin")+TString::Itoa(i,10),90,0,180,100,0,2));
        hM.addHist(new TH2F(TString("hmassyNP_eff_multbin")+TString::Itoa(i,10),TString("hmassyNP_eff_multbin")+TString::Itoa(i,10),nbins,xAxis1,100,0,2));
        hM.addHist(new TH2F(TString("hmassyPP_eff_multbin")+TString::Itoa(i,10),TString("hmassyPP_eff_multbin")+TString::Itoa(i,10),nbins,xAxis1,100,0,2));
        hM.addHist(new TH2F(TString("hmassyNN_eff_multbin")+TString::Itoa(i,10),TString("hmassyNN_eff_multbin")+TString::Itoa(i,10),nbins,xAxis1,100,0,2));
        hM.addHist(new TH2F(TString("hptyNP_eff_multbin")+TString::Itoa(i,10),TString("hptyNP_eff_multbin")+TString::Itoa(i,10),120,0,1200,100,0,2));
        hM.addHist(new TH2F(TString("hptyPP_eff_multbin")+TString::Itoa(i,10),TString("hptyPP_eff_multbin")+TString::Itoa(i,10),120,0,1200,100,0,2));
        hM.addHist(new TH2F(TString("hptyNN_eff_multbin")+TString::Itoa(i,10),TString("hptyNN_eff_multbin")+TString::Itoa(i,10),120,0,1200,100,0,2));
        hM.addHist(new TH2F(TString("hth1th2NP_eff_multbin")+TString::Itoa(i,10),TString("hth1th2NP_eff_multbin")+TString::Itoa(i,10),90,0,90,90,0,90));
        hM.addHist(new TH2F(TString("hth1th2PP_eff_multbin")+TString::Itoa(i,10),TString("hth1th2PP_eff_multbin")+TString::Itoa(i,10),90,0,90,90,0,90));
        hM.addHist(new TH2F(TString("hth1th2NN_eff_multbin")+TString::Itoa(i,10),TString("hth1th2NN_eff_multbin")+TString::Itoa(i,10),90,0,90,90,0,90));
        hM.addHist(new TH2F(TString("hp1p2NP_eff_multbin")+TString::Itoa(i,10),TString("hp1p2NP_eff_multbin")+TString::Itoa(i,10),100,0,1100,100,0,1100));
        hM.addHist(new TH2F(TString("hp1p2PP_eff_multbin")+TString::Itoa(i,10),TString("hp1p2PP_eff_multbin")+TString::Itoa(i,10),100,0,1100,100,0,1100));
        hM.addHist(new TH2F(TString("hp1p2NN_eff_multbin")+TString::Itoa(i,10),TString("hp1p2NN_eff_multbin")+TString::Itoa(i,10),100,0,1100,100,0,1100));
    }

    //--------------- end histo booking -----------------------------------------------------

    HGenericEventMixer<HGeantKine> eventmixer;
    eventmixer.setPIDs(2,3,1);
    eventmixer.setBuffSize(80);
    //eventmixer.setBuffSize(2);
    HGenericEventMixer<HGeantKine> eventmixer_eff[5];
    for (int mb = 0; mb < 5; ++mb) {
        eventmixer_eff[mb].setPIDs(2,3,1);
        eventmixer_eff[mb].setBuffSize(80);
        //eventmixer_eff[mb].setBuffSize(2);
    }

    TStopwatch timer;
    timer.Reset();
    timer.Start();

    Float_t impB = -1.;
    Float_t impB_bins[]  = {9.3, 8.1, 6.6, 4.7, 0.};

    Int_t evtsInFile = loop->getEntries();
    if(nev < 0 || nev > evtsInFile ) nev = evtsInFile;

    for(Int_t i = 1; i < nev; i++)
    {
        //----------break if last event is reached-------------
        //if(!gHades->eventLoop(1)) break;
        if(loop->nextEvent(i) <= 0) { cout<<" end recieved "<<endl; break; } // last event reached
        HTool::printProgress(i,nev,1,"Analyze :");
        loop->getSectors(sectors);

	HPartialEvent *fSimul        = ((HRecEvent*)gHades->getCurrentEvent())->getPartialEvent(catSimul);
	HGeantHeader *fSubHeader = (HGeantHeader*)(fSimul->getSubHeader());
	impB = fSubHeader->getImpactParameter();

	Int_t multbin = 0;
        if (impB >= impB_bins[4] && impB <= impB_bins[3]) {multbin=1;} // most central
	if (impB >  impB_bins[3] && impB <= impB_bins[2]) {multbin=2;}
	if (impB >  impB_bins[2] && impB <= impB_bins[1]) {multbin=3;}
	if (impB >  impB_bins[1] && impB <= impB_bins[0]) {multbin=4;} // most peripheral
	if (impB >  impB_bins[0]) {multbin=5;}
/*
	HParticleEvtInfo* evtinfo;
	evtinfo = HCategoryManager::getObject(evtinfo,catParticleEvtInfo,0);

	Int_t multbin = 0;
	Int_t mult_meta = evtinfo->getSumTofMultCut() + evtinfo->getSumRpcMultHitCut();
        if (mult_meta >  60 && mult_meta <=  88) multbin = 4; // most peripheral
        if (mult_meta >  88 && mult_meta <= 121) multbin = 3;
        if (mult_meta > 121 && mult_meta <= 160) multbin = 2;
        if (mult_meta > 160 && mult_meta <= 250) multbin = 1; // most central
        if (mult_meta > 250) multbin = 5;
*/

        if (multbin == 0 || multbin == 5) continue;

        Int_t size = kineCat->getEntries();

        // Additional loop to fill vector
        vector<HGeantKine *> vep;
        vector<HGeantKine *> vem;
        vector<HGeantKine *> vep_eff;
        vector<HGeantKine *> vem_eff;
        vector<HGeantKine *> vep_eff_multbin;
        vector<HGeantKine *> vem_eff_multbin;
	for(Int_t j = 0; j < size; j ++){
	    kine1 = HCategoryManager::getObject(kine1,kineCat,j);
            Float_t vx,vy,vz;
            kine1->getVertex(vx,vy,vz);
	    Float_t vr = TMath::Sqrt(vx*vx+vy*vy);
            if (vz < -60 || vz > 0) continue;
            if (vr > 2) continue;
            Int_t mamaNum = kine1->getParentTrack();

            if (kine1->isInAcceptance()) {
                if (kine1->getTotalMomentum() > 100 && kine1->getTotalMomentum() < 1000) {
                    Float_t px,py,pz;
                    kine1->getMomentum(px,py,pz);
                    TH2F *smear_matr;
                    if (kine1->getID() == 2) {
                        smear_matr = smear_pos;
                    } else {
                        smear_matr = smear_ele;
                    }
                    Float_t mom_ideal = kine1->getTotalMomentum();
                    Float_t mom_reco = smear(mom_ideal,smear_matr,random);
                    Float_t reco_over_ideal = mom_reco / mom_ideal;
                    kine1->setMomentum(px*reco_over_ideal,py*reco_over_ideal,pz*reco_over_ideal);
                    TLorentzVector vec;
                    HParticleTool::getTLorentzVector(kine1,vec,kine1->getID());

                    Float_t mom = vec.Vect().Mag();
                    Float_t the = vec.Theta()*TMath::RadToDeg();
                    Float_t phi = (vec.Phi()+TMath::Pi())*TMath::RadToDeg();
                    Float_t chg = (kine1->getID() == 2) ? 1 : -1;

                    if (kine1->getID() == 3) {
                        vem.push_back(new HGeantKine(*kine1));
                    }
                    if (kine1->getID() == 2) {
                        vep.push_back(new HGeantKine(*kine1));
                    }
                    Float_t eff = 1./getEfficiencyFactor(p3DEffEle[0][6],p3DEffPos[0][6],mom_ideal,the,phi,chg,false,false); // don't debug, don't check min value
                    if (isinf(eff) || isnan(eff)) eff = 0.;
                    if (random.Uniform(1) > eff) {
                        if (kine1->getID() == 3) {
                            vem_eff.push_back(new HGeantKine(*kine1));
                        }
                        if (kine1->getID() == 2) {
                            vep_eff.push_back(new HGeantKine(*kine1));
                        }
                    }
                    Float_t eff_multbin = 1./getEfficiencyFactor(p3DEffEle[multbin][6],p3DEffPos[multbin][6],mom,the,phi,chg,false,false);
                    if (isinf(eff_multbin) || isnan(eff_multbin)) eff_multbin = 0.;
                    if (random.Uniform(1) > eff_multbin) {
                        if (kine1->getID() == 3) {
                            vem_eff_multbin.push_back(new HGeantKine(*kine1));
                        }
                        if (kine1->getID() == 2) {
                            vep_eff_multbin.push_back(new HGeantKine(*kine1));
                        }
                    }
                }
            }
        }

        eventmixer.nextEvent();
        eventmixer.addVector(vep,2);
        eventmixer.addVector(vem,3);
        vector<pair<HGeantKine *, HGeantKine* > >& pairsVec_acc = eventmixer.getMixedVector();

        eventmixer_eff[0].nextEvent();
        eventmixer_eff[0].addVector(vep_eff,2);
        eventmixer_eff[0].addVector(vem_eff,3);
        vector<pair<HGeantKine *, HGeantKine* > >& pairsVec_eff = eventmixer_eff[0].getMixedVector();

        eventmixer_eff[multbin].nextEvent();
        eventmixer_eff[multbin].addVector(vep_eff,2);
        eventmixer_eff[multbin].addVector(vem_eff,3);
        vector<pair<HGeantKine *, HGeantKine* > >& pairsVec_eff_multbin = eventmixer_eff[multbin].getMixedVector();

        for (int imix = 0; imix < 3; ++imix) {
            vector<pair<HGeantKine *, HGeantKine* > > pairsVec;
            TString suffix;
            switch (imix) {
                case 0: 
                    pairsVec = pairsVec_acc;
                    suffix = TString(""); 
                    break;
                case 1: 
                    pairsVec = pairsVec_eff;
                    suffix = TString("_eff_multbin0");
                    break;
                case 2: 
                    pairsVec = pairsVec_eff_multbin;
                    suffix = TString("_eff_multbin")+TString::Itoa(multbin,10);
                    break;
            }
            size = pairsVec.size();

            for (Int_t j = 0; j < size; j ++) {
                pair<HGeantKine*,HGeantKine*>& pair = pairsVec[j];

                kine1 = pair.first;
                kine2 = pair.second;
                TLorentzVector vec1, vec2;
                HParticleTool::getTLorentzVector(kine1,vec1,kine1->getID());
                HParticleTool::getTLorentzVector(kine2,vec2,kine2->getID());

                Float_t mom1 = vec1.Vect().Mag();
                Float_t the1 = vec1.Theta()*TMath::RadToDeg();
                Float_t mom2 = vec2.Vect().Mag();
                Float_t the2 = vec2.Theta()*TMath::RadToDeg();

                TLorentzVector dilep = vec1 + vec2;
                Float_t oAngle = vec1.Angle(vec2.Vect())*TMath::RadToDeg();
                Float_t mass   = dilep.M()/1000;
                Float_t pt     = dilep.Perp();
                Float_t y      = dilep.Rapidity();
                Float_t mbinw  = hM.get("hmassNP")->GetBinWidth(hM.get("hmassNP")->FindBin(mass));

                if (oAngle < 9) continue;

                TString chg = "NP";
                if (kine1->getID() == kine2->getID()) {
                    if (kine1->getID() == 2) chg = "PP";
                    if (kine1->getID() == 3) chg = "NN";
                }

                hM.get( TString("hmass")      +chg+suffix)->Fill(mass,       1./mbinw);
                hM.get( TString("hoAngle")    +chg+suffix)->Fill(oAngle      );
                hM.get( TString("hy")         +chg+suffix)->Fill(y           );
                hM.get( TString("hpt")        +chg+suffix)->Fill(pt          );
                hM.get2(TString("hoAnglemass")+chg+suffix)->Fill(oAngle,mass,1./mbinw);
                hM.get2(TString("hoAnglept")  +chg+suffix)->Fill(oAngle,pt   );
                hM.get2(TString("hmasspt")    +chg+suffix)->Fill(mass,pt,    1./mbinw);
                hM.get2(TString("hoAngley")   +chg+suffix)->Fill(oAngle,y    );
                hM.get2(TString("hmassy")     +chg+suffix)->Fill(mass,y,     1./mbinw);
                hM.get2(TString("hpty")       +chg+suffix)->Fill(pt,y        );
                hM.get2(TString("hth1th2")    +chg+suffix)->Fill(the1,the2   );
                hM.get2(TString("hp1p2")      +chg+suffix)->Fill(mom1,mom2   );
            }
        }
//#define DELETE_MIX
#ifdef DELETE_MIX
        vector <HGeantKine *>* toDel = eventmixer.getObjectsToDelete();
        for (unsigned int ii = 0; ii < toDel->size(); ++ii) {
            delete toDel->at(ii);
        }
        toDel->clear();
        delete toDel;
        vector <HGeantKine *>* toDel_eff = eventmixer_eff[0].getObjectsToDelete();
        for (unsigned int ii = 0; ii < toDel_eff->size(); ++ii) {
            delete toDel_eff->at(ii);
        }
        toDel_eff->clear();
        delete toDel_eff;
        vector <HGeantKine *>* toDel_eff_multbin = eventmixer_eff[multbin].getObjectsToDelete();
        for (unsigned int ii = 0; ii < toDel_eff_multbin->size(); ++ii) {
            delete toDel_eff_multbin->at(ii);
        }
        toDel_eff_multbin->clear();
        delete toDel_eff_multbin;
#endif

    } // end event loop

    timer.Stop();

    hM.getFile()->cd();
    TMacro m1(__DIELEANA_FILE__);
    m1.Write();
    hM.writeHists("nomap");

    cout<<"####################################################"<<endl;
    return 0;
}
void KKpiFlatDalitzFractions(){

  Float_t M=1.9686;
  Float_t m1=.49368;
  Float_t m2=.49368;
  Float_t m3=.13957;
  

  //Define the Histogram with the boundaries
  Float_t XMin=.8;
  Float_t XMax=3.5;
  Float_t YMin=.3;
  Float_t YMax=2.3;
  TH2F HTop("HTop","",Npoints,XMin,XMax,Npoints,YMin,YMax); 
  HTop.SetStats(0);
  TH2F HBot("HBot","",Npoints,XMin,XMax,Npoints,YMin,YMax);
  HBot.SetStats(0);
  Double_t x=0;
  Double_t y=0;
  Float_t xmin=(m1+m2)*(m1+m2);
  Float_t xmax=(M-m3)*(M-m3);
  Float_t xstep=(xmax-xmin)/Npoints;
  Float_t x0=0;
  Float_t y0=0;

  Float_t E2,E3;
  
  //First do the top points from left to right
  for(Int_t p=0;p<Npoints;p++){
    x=xmin+p*xstep;
    E2=(x-m1*m1+m2*m2)/(2*sqrt(x));
    E3=(M*M-x-m3*m3)/(2*sqrt(x));
    y=(E2+E3)*(E2+E3)-pow((sqrt(E2*E2-m2*m2)-sqrt(E3*E3-m3*m3)),2);      
    HTop.Fill(x,y,1);
  }

  //Now do the bottom points from right to left
  for(Int_t p=0;p<Npoints;p++){
    x=xmax-p*xstep;//move backwards to draw with line   
    E2=(x-m1*m1+m2*m2)/(2*sqrt(x));
    E3=(M*M-x-m3*m3)/(2*sqrt(x));
    y=(E2+E3)*(E2+E3)-pow((sqrt(E2*E2-m2*m2)+sqrt(E3*E3-m3*m3)),2);  
    HBot.Fill(x,y,1);
  }
  
  for(Int_t bx=1;bx<=Npoints;bx++)
    for(Int_t by=1;by<=Npoints;by++){
      if(HTop.GetBinContent(bx,by)>0)HTop.SetBinContent(bx,by,1);
      if(HBot.GetBinContent(bx,by)>0)HBot.SetBinContent(bx,by,1);
    }
 
  TCanvas C;
  C.Print("KKpiFlatDalitzFractions.ps[");

  C.Clear();
  HTop.Draw("col");
  C.Print("KKpiFlatDalitzFractions.ps");
  C.Clear();
  HBot.Draw("col");
  C.Print("KKpiFlatDalitzFractions.ps");

  C.Clear();
  HTop.Draw("col");
  HBot.Draw("col same");
  C.Print("KKpiFlatDalitzFractions.ps");



  ////////////////////////////////
  //Create the arrays which map the y bin for each x bin
  Int_t TopBound[Npoints];
  Int_t BotBound[Npoints];
  for(Int_t bx=0;bx<Npoints;bx++){
    TopBound[bx]=0;
    BotBound[bx]=Npoints;
    for(Int_t by=0;by<Npoints;by++){
      if(HTop.GetBinContent(bx+1,by+1)>0)TopBound[bx]=by;
      if(HBot.GetBinContent(bx+1,by+1)>0)BotBound[bx]=by;
    }
  }
  
  //Dalitz1 Bounds
  Float_t xwidth=(XMax-XMin)/Npoints;
  Float_t ywidth=(YMax-YMin)/Npoints;
  
  Int_t Dalitz1Xmin=(int)((.95-XMin)/xwidth);
  Int_t Dalitz1Xmax=(int)((1.15-XMin)/xwidth);

  Int_t Dalitz2Ymin=(int)((.6-YMin)/ywidth);
  Int_t Dalitz2Ymax=(int)((1.-YMin)/ywidth);


  ////////////Throw random points on the full range and determine if it is inside  the physical region
  TH2F HDalitzSig("HDalitzSig","",Npoints,XMin,XMax,Npoints,YMin,YMax); 
  HDalitzSig.SetStats(0);
  TH2F HDalitz1("HDalitz1","",Npoints,XMin,XMax,Npoints,YMin,YMax); 
  HDalitz1.SetStats(0);
  TH2F HDalitz2("HDalitz2","",Npoints,XMin,XMax,Npoints,YMin,YMax); 
  HDalitz2.SetStats(0);
  TH2F HDalitz3("HDalitz3","",Npoints,XMin,XMax,Npoints,YMin,YMax); 
  HDalitz3.SetStats(0);
  TRandom rand;
  for(Int_t i=0;i<Npoints*Npoints*2;i++){
    Int_t xr=(int)rand.Uniform(1,Npoints+1);
    Int_t yr=(int)rand.Uniform(1,Npoints+1);
    if(BotBound[xr]<=yr&&yr<=TopBound[xr]){
      HDalitzSig.SetBinContent(xr,yr,HDalitzSig.GetBinContent(xr,yr)+1);
      
      if(Dalitz1Xmin<=xr&&xr<=Dalitz1Xmax){
	HDalitz1.SetBinContent(xr,yr,HDalitz1.GetBinContent(xr,yr)+1);
      }
      else if(Dalitz2Ymin<=yr&&yr<=Dalitz2Ymax){
	HDalitz2.SetBinContent(xr,yr,HDalitz2.GetBinContent(xr,yr)+1);
      }else HDalitz3.SetBinContent(xr,yr,HDalitz3.GetBinContent(xr,yr)+1);

      
    }
  }

  C.Clear();
  //HTop.Draw("col");
  //HBot.Draw("col same");
  HDalitzSig.Draw("col");
  C.Print("KKpiFlatDalitzFractions.ps");

  C.Clear();
  //HTop.Draw("col");
  //HBot.Draw("col same");
  HDalitz1.Draw("col ");
  C.Print("KKpiFlatDalitzFractions.ps");

  C.Clear();
  //HTop.Draw("col");
  //HBot.Draw("col same");
  HDalitz2.Draw("col");
  C.Print("KKpiFlatDalitzFractions.ps");

  C.Clear();
  //HTop.Draw("col");
  //HBot.Draw("col same");
  HDalitz3.Draw("col");
  C.Print("KKpiFlatDalitzFractions.ps");

  cout<<"Fraction1 = "<<HDalitz1.Integral()/(float)HDalitzSig.Integral()<<endl;
  cout<<"Fraction2 = "<<HDalitz2.Integral()/(float)HDalitzSig.Integral()<<endl;
  cout<<"Fraction3 = "<<HDalitz3.Integral()/(float)HDalitzSig.Integral()<<endl;


  C.Print("KKpiFlatDalitzFractions.ps]");
  

}
Пример #25
0
int l_production() {

  TRandom *r = new TRandom();

  //reaction
  TGenPhaseSpace event1;//p(gamma, omega)p
  TLorentzVector TotalLv1;

  //Initial state
  TLorentzVector * Beam_Lv = new TLorentzVector();
  TLorentzVector * Tgt_Lv = new TLorentzVector();



  //Final state
  TLorentzVector *Kaon_Lv = new TLorentzVector();
  TLorentzVector *L_Lv = new TLorentzVector();

  //tree component
  double kmom;
  double kmom_x;
  double kmom_y;
  double kmom_z;
  double xmom;
  double xmom_x;
  double xmom_y;
  double xmom_z;
  double theta_k;
  double theta_x;
  double theta_xk;



  //Set Initial Condition
  double beammom=1.67 ;

  TVector3 mom_Beam(0.,0.,beammom);
  TVector3 mom_Tgt(0.,0.,0.);
  Beam_Lv->SetVectM(mom_Beam,M_KAON);
  Tgt_Lv->SetVectM(mom_Tgt,M_NEUTRON);
  TotalLv1 = (*Beam_Lv) + (*Tgt_Lv);// Total Vector



  //Set Output file
  TFile *f = new TFile("l_production.root","recreate");
  TTree *tree = new TTree("tree","l production");

  tree->Branch("beam"  , "TLorentzVector",   &Beam_Lv, 32000, 1);
  tree->Branch("tgt"   , "TLorentzVector",    &Tgt_Lv, 32000, 1);
  tree->Branch("kaon"  , "TLorentzVector",   &Kaon_Lv, 32000, 1);
  tree->Branch("l"    , "TLorentzVector",     &L_Lv, 32000, 1);
  tree->Branch("kmom"  ,   &kmom,   "kmom/D");
  tree->Branch("kmom_x", &kmom_x, "kmom_x/D");
  tree->Branch("kmom_y", &kmom_y, "kmom_y/D");
  tree->Branch("kmom_z", &kmom_z, "kmom_z/D");
  tree->Branch("xmom"  ,   &xmom,   "xmom/D");
  tree->Branch("xmom_x", &xmom_x, "xmom_x/D");
  tree->Branch("xmom_y", &xmom_y, "xmom_y/D");
  tree->Branch("xmom_z", &xmom_z, "xmom_z/D");
  tree->Branch("theta_k" ,  &theta_k,  "theta_k/D");
  tree->Branch("theta_x" ,  &theta_x,  "theta_x/D");
  tree->Branch("theta_xk" ,  &theta_xk,  "theta_xk/D");

  //Event Generation start!
  int Max_No = 100000;  // repeat no
  int i=0;


  double masses[3];
  double weight=0;
  double comp=0;
  masses[0] = M_PROTON;
  masses[1] = M_PION;
  masses[2] = M_PION;

  event1.SetDecay(TotalLv1, 3, masses, "Fermi");///Total E, particle No, particle mass

  do{
    if(i%1000 == 0){
      std::cout<<"ev_no=" << i <<std::endl;
    }
    int try_no=0;
    do{
    comp=r->Uniform(0.,0.5);
    weight =event1.Generate();
    try_no++;
    }while(comp > weight);




    std::cout << "weight = "<<weight << " comp = "<<comp <<" try_no ="<<try_no <<std::endl;

    if(TotalLv1.Mag() < masses[0] + masses[1] + masses[2]  ){
      std::cout<<"event1 not happen!" << TotalLv1.Mag() <<":"
        << masses[0] + masses[1] + masses[2] <<std::endl;
      continue;
    }

    Kaon_Lv = event1.GetDecay(0);
    Xi_Lv = event1.GetDecay(1);


    kmom   = Kaon_Lv->Vect().Mag();
    kmom_x = Kaon_Lv->X();
    kmom_y = Kaon_Lv->Y();
    kmom_z = Kaon_Lv->Z();
    xmom   = Xi_Lv->Vect().Mag();
    xmom_x = Xi_Lv->X();
    xmom_y = Xi_Lv->Y();
    xmom_z = Xi_Lv->Z();
    theta_k  = acos( kmom_z/kmom );
    theta_x  = acos( xmom_z/xmom );
    theta_xk  = acos( (kmom_x*xmom_x + kmom_y*xmom_y + kmom_z*xmom_z) / (kmom*xmom) );


    tree->Fill();

    i++;
  }while(i<Max_No);



  tree->Write();


  f->Close();

}
Пример #26
0
void MassPlotterSingleTop::singleTopAnalysis(TList* allCuts, Long64_t nevents ,TString myfileName ){

  TopUtilities topUtils ;

  int lumi = 0;

  TIter nextcut(allCuts); 
  TObject *objcut; 

  std::vector<TString> alllabels;
  while( objcut = nextcut() ){
    ExtendedCut* thecut = (ExtendedCut*)objcut ;
    alllabels.push_back( thecut->Name );
  }  
  //alllabels.push_back( "NoCut" );
  alllabels.push_back( "Trigger" );
  //alllabels.push_back( "MuonSelection" );
  //alllabels.push_back( "MuonVeto1" );
  //alllabels.push_back( "MuonVeto" );
  alllabels.push_back( "== 1#mu" );
  alllabels.push_back( "== 2-Jets" );
  alllabels.push_back( "== 1-bJet" );
  alllabels.push_back( "MT >50 GeV" );
  //alllabels.push_back( "j'-bVeto" );
  alllabels.push_back( "mtop" );
  //cout << alllabels.size() << endl;

  ExtendedObjectProperty cutflowtable("" , "cutflowtable" , "1" , alllabels.size() ,  0 , alllabels.size() , "2", {}, &alllabels );  
  ExtendedObjectProperty cutflowtablew1("" , "cutflowtablew1" , "1" , alllabels.size() ,  0 , alllabels.size() , "2", {}, &alllabels );  
  

  TString fileName = fOutputDir;
  if(!fileName.EndsWith("/")) fileName += "/";
  Util::MakeOutputDir(fileName);

  bool printEventIds = false;
  vector< ofstream* > EventIdFiles;
  if(printEventIds){
    for( int i = 0 ; i < alllabels.size() ; i++ ){
      ofstream* filetxt = new ofstream(fileName + "/IPM_" + myfileName  + "_step" + boost::lexical_cast<string>(i) + ".txt" );
      EventIdFiles.push_back( filetxt );
    }
  }


  ExtendedObjectProperty nJetsBeforeCut("LeptonVeto" , "nJets" , "1" , 8 , 0 , 8 , "2", {});
  ExtendedObjectProperty nJets20_47("OneBjet" , "nJets20_47" , "1" , 8 , 0 , 8 , "2", {});
  ExtendedObjectProperty nJets20_24("OneBjet" , "nJets20_24" , "1" , 8 , 0 , 8 , "2", {});
  ExtendedObjectProperty nbJets("Jets" , "nbJets" , "1" , 3 , 0 , 3 , "2", {});

  ExtendedObjectProperty MTBeforeCut("OneBjetNoMT" , "MT" , "1" , 30 , 0 , 300 , "2", {});

  ExtendedObjectProperty nPVBeforeCutsUnCorr("nPVBeforeCutsUnCorr" , "nPVBeforeCutsUnCorr" , "1" , 100 , 0 , 100 , "2", {});
  ExtendedObjectProperty nPVBeforeCuts("nPVBeforeCuts" , "nPVBeforeCuts" , "1" , 100 , 0 , 100 , "2", {});
  ExtendedObjectProperty nPVAfterCutsUnCorr("nPVAfterCutsUnCorr" , "nPVAfterCutsUnCorr" , "1" , 100 , 0 , 100 , "2", {});
  ExtendedObjectProperty nPVAfterCuts("nPVAfterCuts" , "nPVAfterCuts" , "1" , 100 , 0 , 100 , "2", {});

  ExtendedObjectProperty TopMass("OneBjet" , "TopMass" , "1" , 30 , 100 , 400 , "2", {});
  ExtendedObjectProperty jprimeEta("OneBjet" , "jPrimeEta" , "1" , 10 , 0 , 5.0 , "2", {});
  ExtendedObjectProperty jprimeEtaSB("SideBand" , "jPrimeEtaSB" , "1" , 10 , 0 , 5.0 , "2", {});
  ExtendedObjectProperty jprimePt("OneBjet" , "jPrimePt" , "1" , 30 , 30 , 330 , "2", {});
  ExtendedObjectProperty muPtOneB("OneBjet" , "muPt" , "1" , 20 , 20 , 120 , "2", {});
  ExtendedObjectProperty muCharge("OneBjet" , "muCharge" , "1" , 40 , -2 , 2 , "2", {});
  ExtendedObjectProperty muEtaOneB("OneBjet" , "muEta" , "1" , 10 , -2.5 , 2.5 , "2", {});
  ExtendedObjectProperty METOneBSR("OneBjet" , "MET_SR" , "1" , 20 , 0 , 200 , "2", {});
  ExtendedObjectProperty METOneBSB("OneBjet" , "MET_SB" , "1" , 20 , 0 , 200 , "2", {});
  ExtendedObjectProperty METOneBAll("OneBjet" , "MET_ALL" , "1" , 20 , 0 , 200 , "2", {});
  ExtendedObjectProperty bPtOneB("OneBjet" , "bPt" , "1" , 30 , 30 , 330 , "2", {});
  ExtendedObjectProperty bEtaOneB("OneBjet" , "bEta" , "1" , 10 , 0 , 5.0 , "2", {});
  ExtendedObjectProperty nonbCSV("OneBjet" , "jpCSV" , "1" , 20 , 0 , 1.0 , "2", {});

  ExtendedObjectProperty nLbjets1EJ24("1EJ24" , "nLbJets_1EJ24" , "1" , 2 , 0 , 2  , "2", {});
  ExtendedObjectProperty nTbjets1EJ24("1EJ24" , "nTbJets_1EJ24" , "1" , 2 , 0 , 2  , "2", {});

  ExtendedObjectProperty nLbjets2EJ24("2EJ24" , "nLbJets_2EJ24" , "1" , 3 , 0 , 3  , "2", {});
  ExtendedObjectProperty nTbjets2EJ24("2EJ24" , "nTbJets_2EJ24" , "1" , 3 , 0 , 3  , "2", {});

  ExtendedObjectProperty nLbjets3EJ24("3EJ24" , "nLbJets_3EJ24" , "1" , 4 , 0 , 4  , "2", {});
  ExtendedObjectProperty nTbjets3EJ24("3EJ24" , "nTbJets_3EJ24" , "1" , 4 , 0 , 4  , "2", {});

  ExtendedObjectProperty nLbjets4EJ24("4EJ24" , "nLbJets_4EJ24" , "1" , 5 , 0 , 5  , "2", {});
  ExtendedObjectProperty nTbjets4EJ24("4EJ24" , "nTbJets_4EJ24" , "1" , 5 , 0 , 5  , "2", {});

  ExtendedObjectProperty nLbjets1EJ47("1EJ47" , "nLbJets_1EJ47" , "1" , 2 , 0 , 2  , "2", {});
  ExtendedObjectProperty nTbjets1EJ47("1EJ47" , "nTbJets_1EJ47" , "1" , 2 , 0 , 2  , "2", {});

  ExtendedObjectProperty nLbjets2EJ47("2EJ47" , "nLbJets_2EJ47" , "1" , 3 , 0 , 3  , "2", {});
  ExtendedObjectProperty nTbjets2EJ47("2EJ47" , "nTbJets_2EJ47" , "1" , 3 , 0 , 3  , "2", {});

  ExtendedObjectProperty nLbjets3EJ47("3EJ47" , "nLbJets_3EJ47" , "1" , 4 , 0 , 4  , "2", {});
  ExtendedObjectProperty nTbjets3EJ47("3EJ47" , "nTbJets_3EJ47" , "1" , 4 , 0 , 4  , "2", {});

  ExtendedObjectProperty nLbjets4EJ47("4EJ47" , "nLbJets_4EJ47" , "1" , 5 , 0 , 5  , "2", {});
  ExtendedObjectProperty nTbjets4EJ47("4EJ47" , "nTbJets_4EJ47" , "1" , 5 , 0 , 5  , "2", {});

  TH1* hTopMass = new TH1D("hTopMass" , "Top Mass" , 500 , 0 , 500 );
  TH1* hTopMassEtaJ = new TH2D( "hTopMassEtaJ" , "Top Mass" , 500 , 0 , 500 , 20 , 0 , 5.0 );

  TH1* hEtajPDFScales[102];
  double ScalesPDF[102];
  double CurrentPDFWeights[102];
  for(int i=0 ; i < 102 ; i++){
    TString s(to_string(i));
    hEtajPDFScales[i] = new TH1D( TString("hEtaJp_PDF")+s , "" , 10 , 0 , 5.0 );
    ScalesPDF[i] = 0 ;
    CurrentPDFWeights[i] = 0;
  }

  TH1* hEtajWScales[9];
  double WScalesTotal[9];
  double CurrentLHEWeights[9];
  for(int i=0; i < 9; i++){
    TString s(to_string(i));
    hEtajWScales[i] = new TH1D( TString("hEtaJp_")+s , "" , 10 , 0 , 5.0 );
    WScalesTotal[i] = 0 ;
    CurrentLHEWeights[i] = 0;
  }

  std::vector<ExtendedObjectProperty*> allProps = {&cutflowtable, &cutflowtablew1 , &nJetsBeforeCut , &nbJets , &MTBeforeCut, &TopMass , &jprimeEta , &jprimeEtaSB , &jprimePt , &muPtOneB, &muCharge, &muEtaOneB , &METOneBSR ,&METOneBSB , &METOneBAll , & bPtOneB , &bEtaOneB , &nonbCSV ,&nJets20_24, &nJets20_47,&nPVAfterCuts, &nPVBeforeCuts , &nPVAfterCutsUnCorr , &nPVBeforeCutsUnCorr};

  std::vector<ExtendedObjectProperty*> JbJOptimizationProps = {&nLbjets1EJ24,&nTbjets1EJ24,&nLbjets2EJ24,&nTbjets2EJ24,&nLbjets3EJ24,&nTbjets3EJ24,&nLbjets4EJ24,&nTbjets4EJ24,&nLbjets1EJ47,&nTbjets1EJ47,&nLbjets2EJ47,&nTbjets2EJ47,&nLbjets3EJ47,&nTbjets3EJ47,&nLbjets4EJ47,&nTbjets4EJ47};
  nextcut.Reset();


  //codes for 2j0t selection
  TFile *theTreeFile = NULL;
  if(IsQCD==1)
    theTreeFile = new TFile( (fileName+ myfileName + "_Trees.root" ).Data(), "RECREATE");    

  double MT_QCD_Tree , TOPMASS_QCD_Tree , MuIso_QCD_Tree , Weight_QCD_Tree;

  TTree* theQCD_Tree = NULL;
  //end of 2j0t

  for(int ii = 0; ii < fSamples.size(); ii++){

    int data = 0;
    sample Sample = fSamples[ii];

    TEventList* list = 0;
   
    if(Sample.type == "data"){
      data = 1;
    }else
      lumi = Sample.lumi; 

    if( theTreeFile ){
      TString treename = Sample.sname ;
      if( data )
	treename = "Data";
      if( theTreeFile->Get( treename ) ){
	theQCD_Tree = (TTree*) (theTreeFile->Get( treename )) ; 
      }else{
	theTreeFile->cd();
	theQCD_Tree = new TTree( treename , treename + " tree for QCD shape/normalization studies" );
	theQCD_Tree->Branch( "MT/D" , &MT_QCD_Tree );
	theQCD_Tree->Branch( "TOPMASS/D" , &TOPMASS_QCD_Tree );
	theQCD_Tree->Branch( "MuIso/D" , &MuIso_QCD_Tree );
	theQCD_Tree->Branch( "Weight/D" , &Weight_QCD_Tree );
      }
    }


    double Weight = Sample.xsection * Sample.kfact * Sample.lumi / (Sample.nevents*Sample.PU_avg_weight);
    //Weight = 1.0;
    if(data == 1)
      Weight = 1.0;

    Sample.Print(Weight);

    SingleTopTree fTree( Sample.tree );
    Sample.tree->SetBranchStatus("*", 1);

    string lastFileName = "";

    Long64_t nentries =  Sample.tree->GetEntries();
    Long64_t maxloop = min(nentries, nevents);

    int counter = 0;
    double EventsIsPSeudoData ;
    int cutPassCounter = 0;
    for (Long64_t jentry=0; jentry<maxloop;jentry++, counter++) {
      Sample.tree->GetEntry(jentry);
      // //cout << fTree.Event_EventNumber << endl;
      // if(  !(fTree.Event_EventNumber == 11112683 || fTree.Event_EventNumber == 11112881 ) ){
      // 	//cout << " " ;
      // 	continue;
      // }
      // else{
      // 	cutPassCounter ++ ;
      // 	cout << cutPassCounter << " : " << fTree.Event_EventNumber << " : " << endl;
      // }
      EventsIsPSeudoData = PSeudoDataRandom->Uniform();

      if( lastFileName.compare( ((TChain*)Sample.tree)->GetFile()->GetName() ) != 0 ) {
	for(auto prop : allProps)
	  prop->SetTree( Sample.tree , Sample.type, Sample.sname );
	for(auto prop2 : JbJOptimizationProps ) 
	  prop2->SetTree( Sample.tree , Sample.type, Sample.sname );

	nextcut.Reset();
	while( objcut = nextcut() ){
	  ExtendedCut* thecut = (ExtendedCut*)objcut ;
	  thecut->SetTree( Sample.tree ,  Sample.name , Sample.sname , Sample.type , Sample.xsection, Sample.nevents, Sample.kfact , Sample.PU_avg_weight);
	}

	lastFileName = ((TChain*)Sample.tree)->GetFile()->GetName() ;
	cout << "new file : " << lastFileName << endl;
      }

      if ( counter == 100000 ){  
	fprintf(stdout, "\rProcessed events: %6d of %6d ", jentry + 1, nentries);
	fflush(stdout);
	counter = 0;
      }
 
      nextcut.Reset();
      double weight = Weight;

      if( !data ){
	weight *= fTree.Event_puWeight ;
      }

      if( Sample.UseLHEWeight ){
	//cout << "SIGNAL" << endl;
	weight *= fTree.Event_LHEWeightSign ;
	// if(fTree.Event_LHEWeightSign < 0.0)
	//   cout << fTree.Event_LHEWeightSign << endl;
      }

      #ifdef SingleTopTreeLHEWeights_h
      for( int i = 0 ; i < 102 ; i++ ){
	CurrentPDFWeights[i] = fTree.GetPDFWeight(i)/fabs(fTree.Event_LHEWeight) ;
	ScalesPDF[i] += CurrentPDFWeights[i] ;
      }

      if( Sample.name == "WJets" || Sample.name == "Signal" ){

	
	if(fTree.GetLHEWeight(0) != fTree.Event_LHEWeight0) cout << "Wrong GetLHEWeight(0) Value" << endl;
	if(fTree.GetLHEWeight(1) != fTree.Event_LHEWeight1) cout << "Wrong GetLHEWeight(1) Value" << endl;
	if(fTree.GetLHEWeight(2) != fTree.Event_LHEWeight2) cout << "Wrong GetLHEWeight(2) Value" << endl;
	if(fTree.GetLHEWeight(3) != fTree.Event_LHEWeight3) cout << "Wrong GetLHEWeight(3) Value" << endl;
	if(fTree.GetLHEWeight(4) != fTree.Event_LHEWeight4) cout << "Wrong GetLHEWeight(4) Value" << endl;
	if(fTree.GetLHEWeight(5) != fTree.Event_LHEWeight5) cout << "Wrong GetLHEWeight(5) Value" << endl;
	if(fTree.GetLHEWeight(6) != fTree.Event_LHEWeight6) cout << "Wrong GetLHEWeight(6) Value" << endl;
	if(fTree.GetLHEWeight(7) != fTree.Event_LHEWeight7) cout << "Wrong GetLHEWeight(7) Value" << endl;
	if(fTree.GetLHEWeight(8) != fTree.Event_LHEWeight8) cout << "Wrong GetLHEWeight(8) Value" << endl;
	
	// CurrentLHEWeights[0] = fTree.Event_LHEWeight /fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[1] = fTree.Event_LHEWeight1/fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[2] = fTree.Event_LHEWeight2/fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[3] = fTree.Event_LHEWeight3/fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[4] = fTree.Event_LHEWeight4/fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[5] = fTree.Event_LHEWeight5/fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[6] = fTree.Event_LHEWeight6/fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[7] = fTree.Event_LHEWeight7/fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[8] = fTree.Event_LHEWeight8/fabs(fTree.Event_LHEWeight) ;
	
	for(int i = 0 ; i<9 ;i++){
	  CurrentLHEWeights[i] = fTree.GetLHEWeight(i)/fabs(fTree.Event_LHEWeight) ;
	  WScalesTotal[i] += CurrentLHEWeights[i];
	}
      }
      #endif
      
      double cutindex = 0.5;
      bool pass=true;
      while( objcut = nextcut() ){
	ExtendedCut* thecut = (ExtendedCut*)objcut ;
	pass &= thecut->Pass(jentry , weight);
	if(! pass ){
	  break;
	}else{
	  if( isfinite (weight) ){
	    cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
	    cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
	  }
	  else
	    cout << "non-finite weight : " << weight << endl;
	}
	cutindex+=1.0;
      }

      if(! pass)
	continue;

      int cut = 0;

      //cout << alllabels[ int(cutindex) ] << endl;
//       cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
//       cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
//       cutindex ++ ;

      // if( data && !(fTree.Event_passesHLT_IsoMu20_eta2p1_v2 > 0.5) )
      // 	continue;
      
      // if( !data && !(fTree.Event_passesHLT_IsoMu20_eta2p1_v1 > 0.5) )
      // 	continue;

      nPVBeforeCutsUnCorr.Fill( fTree.Event_nPV , weight/fTree.Event_puWeight , false , true );
      nPVBeforeCuts.Fill( fTree.Event_nPV , weight , false, true);

      // if( printEventIds )
      // 	(*(EventIdFiles[cutindex])) << fTree.Event_EventNumber << endl; 
      // cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      // cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      // cutindex ++ ;
      
      if( data && !(fTree.Event_passesHLT_IsoMu20_v2 > 0.5 || fTree.Event_passesHLT_IsoMu20_v1 > 0.5 || fTree.Event_passesHLT_IsoMu20_v3 > 0.5)  )
	continue;
      if(!data && !(fTree.Event_passesHLT_IsoMu20_v1 > 0.5) )
	continue;

      if( printEventIds )
	(*(EventIdFiles[cutindex])) << fTree.Event_EventNumber << endl;
      cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      cutindex ++ ;
      

      //cout << "nMuons : " << fTree.muons_size << endl;
      int tightMuIndex =-1;
      int nonTightMuIndex = -1;
      int nLooseMuos   = 0;
      int nTightMuons = 0;
      int nTightNonIsoMuons = 0;

      for( int imu=0 ; imu < fTree.muons_size ; imu++ ){
	// cout << imu << " : " << fTree.muons_Pt[imu] << "-" << fTree.muons_Eta[imu] << "-"
	//      << fTree.muons_IsTightMuon[imu] << "-" << fTree.muons_Iso04[imu] << endl;
	
	bool isTight = false;
      	if( fTree.muons_Pt[imu] > 22.0 &&
	    fabs(fTree.muons_Eta[imu]) < 2.1 &&
	    fTree.muons_IsTightMuon[imu] > 0.5 ){


	  if( fTree.muons_Iso04[imu] < 0.06 ){ 
	    isTight = true;
	    nTightMuons ++;
	    if( tightMuIndex == -1 )
	      tightMuIndex = imu;
	  }else if( fTree.muons_Iso04[imu] < 0.15 ){
	    nTightNonIsoMuons ++;
	    if( nonTightMuIndex == -1 )
	      nonTightMuIndex = imu;
	  }
	}

	if( ! isTight )
	  if( fTree.muons_Pt[ imu ] > 10.0 &&
	      fTree.muons_IsLooseMuon[ imu ] > 0.5 &&
	      fabs(fTree.muons_Eta[imu]) < 2.5 && 
	      fTree.muons_Iso04[imu] < 0.20 ){
	    nLooseMuos++;
	  }
      }      

      if(IsQCD){
	nLooseMuos = nTightMuons ;	
	nTightMuons = nTightNonIsoMuons ;
	tightMuIndex = nonTightMuIndex ;
      }


      if( nTightMuons != 1 )
	  continue;

      bool isiso = true;

      if( nLooseMuos > 0 )
      	continue;

#ifdef MUONCHARGEP
      if(fTree.muons_Charge[tightMuIndex] < 0)
	continue;
#endif
#ifdef MUONCHARGEN
      if(fTree.muons_Charge[tightMuIndex] > 0)
	continue;
#endif

      // if( printEventIds )
      // 	(*(EventIdFiles[cutindex])) << (fTree.Event_EventNumber) << endl ;
      // cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      // cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      // cutindex ++ ;

      int nLooseElectrons = 0;
      for( int iele = 0 ; iele < fTree.electrons_size;iele ++ ){
      	if( fTree.electrons_Pt[iele] > 20 &&
	    fabs(fTree.electrons_Eta[iele]) < 2.5 && 
	    ( fabs(fTree.electrons_Eta[iele]) < 1.4442 || fabs(fTree.electrons_Eta[iele]) > 1.566) &&
	    fTree.electrons_vidVeto[iele] > 0.5 )
	  nLooseElectrons++;
      }
      
      if( nLooseElectrons > 0 )
      	continue;

      if( printEventIds )
	(*(EventIdFiles[cutindex])) << (fTree.Event_EventNumber) << endl ;
      cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      cutindex ++ ;

      int j1index = -1;
      int j2index = -1;
      int j3index = -1;
      int nJets = 0 ;
      int howManyBJets = 0;
      int bjIndex = -1;
      int bj2Index = -1;
      int jprimeIndex ; 

      int nJetsPt20_47 = 0;

      int nJetsPt20_24 = 0;
      int nLbJetsPt20 = 0;
      int nTbJetsPt20 = 0;

      TLorentzVector muon;
      muon.SetPtEtaPhiE( fTree.muons_Pt[tightMuIndex] , fTree.muons_Eta[tightMuIndex] , fTree.muons_Phi[tightMuIndex] , fTree.muons_E[tightMuIndex] );
      if( muon.Energy() == 0.0 )
	cout << "ZERO???" <<endl;
      for( int jid = 0 ; jid < fTree.jetsAK4_size ; jid++ ){

	float NHF = fTree.jetsAK4_JetID_neutralHadronEnergyFraction[jid] ;
	float NEMF = fTree.jetsAK4_JetID_neutralEmEnergyFraction[jid] ;
	float NumConst = fTree.jetsAK4_JetID_numberOfDaughters[jid] ;
	float eta = fTree.jetsAK4_Eta[jid] ;
	float CHF = fTree.jetsAK4_JetID_chargedHadronEnergyFraction[jid] ;
	float CHM = fTree.jetsAK4_JetID_chargedMultiplicity[jid] ;
	float CEMF = fTree.jetsAK4_JetID_chargedEmEnergyFraction[jid] ;
	float NumNeutralParticle = fTree.jetsAK4_JetID_neutralMultiplicity[jid] ;


	bool looseid ;
	if(  abs(eta)<=3.0 ) {
	  looseid = (NHF<0.99 && NEMF<0.99 && NumConst>1) && ((abs(eta)<=2.4 && CHF>0 && CHM>0 && CEMF<0.99) || abs(eta)>2.4) ;
	}
	else
	  looseid = (NEMF<0.90 && NumNeutralParticle>10) ;

      	if( fTree.jetsAK4_CorrPt[jid] > 20 &&
	    fabs( fTree.jetsAK4_Eta[jid] ) < 4.7 &&
	    looseid
	    ){
	  TLorentzVector jet;
	  jet.SetPtEtaPhiE( fTree.jetsAK4_CorrPt[jid] , fTree.jetsAK4_Eta[jid] , fTree.jetsAK4_Phi[jid] , fTree.jetsAK4_CorrE[jid] );
	  double DR = muon.DeltaR( jet );

	  if ( DR > 0.3 ){

	    if( fTree.jetsAK4_CorrPt[jid] <= 40 ){
	      nJetsPt20_47 ++ ;
	      if( fabs( fTree.jetsAK4_Eta[jid] ) < 2.4 ){
		nJetsPt20_24 ++;
		if( fTree.jetsAK4_CSV[jid] > 0.97 )
		  nTbJetsPt20++;
		else if( fTree.jetsAK4_CSV[jid] > 0.605 )
		  nLbJetsPt20++;
	      }
	      
	      continue;
	    }	    
	    nJets++;
	    if( nJets == 1 )
	      j1index = jid ;
	    else if(nJets == 2 )
	      j2index = jid ;
	    else if( nJets == 3 )
	      j3index = jid ;
	    
	    if( fTree.jetsAK4_IsCSVT[jid] == true  && fabs( fTree.jetsAK4_Eta[jid] ) <= 2.4 ){
	      howManyBJets ++;
	      if(howManyBJets==1)
		bjIndex = jid ;
	      else if(howManyBJets==2)
		bj2Index = jid ;
	    }else
	      jprimeIndex = jid ;
	  }
	}
      }
      
      nJetsBeforeCut.Fill( nJets , weight , EventsIsPSeudoData < fabs(weight) , isiso );
      if (nJets != NUMBEROFJETS)
	continue;


      if( printEventIds )
	(*(EventIdFiles[cutindex])) << (fTree.Event_EventNumber) << endl ;
      cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      cutindex ++ ;
      
      nbJets.Fill( howManyBJets , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      if( howManyBJets != NUMBEROFBJETS )
	continue;

      if( !data ){
	if( NUMBEROFBJETS == 2 )
	  weight *= fTree.Event_bWeight2CSVT ;
	else if (NUMBEROFBJETS == 1 )
	  weight *= fTree.Event_bWeight1CSVT ;
      }

      //weight = 1.0;

      if( printEventIds )
	(*(EventIdFiles[cutindex])) << (fTree.Event_EventNumber) << endl ;
      cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      cutindex ++ ;

     
      double MT = sqrt( 2*fTree.met_Pt* fTree.muons_Pt[tightMuIndex]*(1-TMath::Cos( Util::DeltaPhi(fTree.met_Phi , fTree.muons_Phi[tightMuIndex]) ) )  ) ;
      MTBeforeCut.Fill( MT , weight , EventsIsPSeudoData < fabs(weight) , isiso );
      // if( fTree.met_Pt < 45 )
      // 	continue;
      if( MT < 50 && (NUMBEROFBJETS == 1 && NUMBEROFJETS == 2) && !IsQCD )
      	continue;

      if( printEventIds )
	(*(EventIdFiles[cutindex])) << (fTree.Event_EventNumber) << endl ;
     
      cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      cutindex ++ ;

      nonbCSV.Fill( fTree.jetsAK4_CSV[jprimeIndex] , weight , EventsIsPSeudoData < fabs(weight) , isiso);

//       if( fTree.jetsAK4_CSV[jprimeIndex] > 0.605 )
// 	continue;

      // if( printEventIds )
      // 	(*(EventIdFiles[cutindex])) << (fTree.Event_EventNumber) << endl ;
      // cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      // cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      // cutindex ++ ;

      nJets20_47.Fill( nJetsPt20_47 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      nJets20_24.Fill( nJetsPt20_24 , weight , EventsIsPSeudoData < fabs(weight) , isiso);

      if(nJetsPt20_24 < 2){
	nLbjets1EJ24.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets1EJ24.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }
      if(nJetsPt20_24 < 3){
	nLbjets2EJ24.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets2EJ24.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }
      if(nJetsPt20_24 < 4){
	nLbjets3EJ24.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets3EJ24.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }
      if(nJetsPt20_24 < 5){
	nLbjets4EJ24.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets4EJ24.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }

      if(nJetsPt20_47 < 2){
	nLbjets1EJ47.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets1EJ47.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }
      if(nJetsPt20_47 < 3){
	nLbjets2EJ47.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets2EJ47.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }
      if(nJetsPt20_47 < 4){
	nLbjets3EJ47.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets3EJ47.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }
      if(nJetsPt20_47 < 5){
	nLbjets4EJ47.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets4EJ47.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }


      if( NUMBEROFBJETS == 2 )
	if( fTree.jetsAK4_CSV[bj2Index] > fTree.jetsAK4_CSV[bjIndex] )
	  std::swap( bj2Index , bjIndex );

      //int jprimeIndex = (bjIndex == j1index) ? j2index : j1index ;
      TLorentzVector muLV;
      muLV.SetPtEtaPhiE( fTree.muons_Pt[tightMuIndex] , fTree.muons_Eta[tightMuIndex] , fTree.muons_Phi[ tightMuIndex ] , fTree.muons_E[tightMuIndex] );
      TLorentzVector bjetLV;
      bjetLV.SetPtEtaPhiE( fTree.jetsAK4_CorrPt[ bjIndex ] , fTree.jetsAK4_Eta[ bjIndex ] , fTree.jetsAK4_Phi[ bjIndex ] , fTree.jetsAK4_CorrE[ bjIndex ] ) ; 
      double topMass = topUtils.top4Momentum( muLV , bjetLV , fTree.met_Px , fTree.met_Py ).mass();
      TopMass.Fill( topMass , weight , EventsIsPSeudoData < fabs(weight) , isiso ); //fTree.resolvedTopSemiLep_Mass[0]

      MT_QCD_Tree = MT;
      TOPMASS_QCD_Tree = topMass ;
      MuIso_QCD_Tree = fTree.muons_Iso04[tightMuIndex];
      Weight_QCD_Tree = weight ;

      if( IsQCD )
	theQCD_Tree->Fill();



      if( (130. < topMass && topMass < 225.) || NUMBEROFBJETS == 2 ){

	nPVAfterCutsUnCorr.Fill( fTree.Event_nPV , weight/fTree.Event_puWeight , EventsIsPSeudoData < fabs(weight) , isiso );
	nPVAfterCuts.Fill( fTree.Event_nPV , weight , EventsIsPSeudoData < fabs(weight) , isiso );

#ifdef SingleTopTreeLHEWeights_h
	for(int i = 0 ; i< 102 ; i++){
	  hEtajPDFScales[i]->Fill( fabs( fTree.jetsAK4_Eta[jprimeIndex] ) , weight*fabs( CurrentPDFWeights[i] ) );
	}
	if( Sample.name == "WJets" || Sample.name == "Signal"){
	  for(int i=0;i<9;i++)
	    hEtajWScales[i]->Fill( fabs( fTree.jetsAK4_Eta[jprimeIndex] ) , weight*fabs( CurrentLHEWeights[i] ) );
	}
#endif
	
	jprimeEta.Fill( fabs( fTree.jetsAK4_Eta[jprimeIndex] ) , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	jprimePt.Fill( fTree.jetsAK4_CorrPt[jprimeIndex] , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	muPtOneB.Fill( fTree.muons_Pt[tightMuIndex] , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	muCharge.Fill( fTree.muons_Charge[tightMuIndex] , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	muEtaOneB.Fill( fabs(fTree.muons_Eta[tightMuIndex]) , weight , EventsIsPSeudoData < fabs(weight), isiso );
	METOneBSR.Fill(  fTree.met_Pt , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	bPtOneB.Fill( fTree.jetsAK4_CorrPt[bjIndex] , weight , EventsIsPSeudoData < fabs(weight), isiso );
	bEtaOneB.Fill(fabs( fTree.jetsAK4_Eta[bjIndex] ) , weight , EventsIsPSeudoData < fabs(weight), isiso );

	if( printEventIds )
	  (*(EventIdFiles[cutindex])) << (fTree.Event_EventNumber) << endl ;
	cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
	cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
	cutindex++;
      }else{
	jprimeEtaSB.Fill( fabs( fTree.jetsAK4_Eta[jprimeIndex] ) , weight , EventsIsPSeudoData < fabs(weight) , isiso );
	METOneBSB.Fill(  fTree.met_Pt , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }

      METOneBAll.Fill(  fTree.met_Pt , weight , EventsIsPSeudoData < fabs(weight) , isiso);

      if(Sample.name == "Signal" )
	hTopMass->Fill( topMass , weight );
      if(Sample.name == "WJets")
	hTopMassEtaJ->Fill( topMass ,fabs( fTree.jetsAK4_Eta[jprimeIndex] )  );
    }
    theQCD_Tree->Write();
    
  }

  theTreeFile->Close();
      

  // TString fileName = fOutputDir;
  // if(!fileName.EndsWith("/")) fileName += "/";
  // Util::MakeOutputDir(fileName);
  fileName += myfileName + ".root" ;

  TFile *theFile = new TFile(fileName.Data(), "RECREATE");

  nonbCSV.CalcSig( 0 , 0 , -1 , 0 ) ; 
  nonbCSV.CalcSig( 0 , 4 , -1 , 0.1); 
  nonbCSV.CalcSig( 0 , 2 , -1 , 0 ) ; 

  nJets20_24.CalcSig( 0 , 0 , -1 , 0 ) ; 
  nJets20_24.CalcSig( 0 , 4 , -1 , 0.1 ) ; 
  nJets20_24.CalcSig( 0 , 2 , -1 , 0 ) ; 
  nJets20_47.CalcSig( 0 , 0 , -1 , 0 ) ; 
  nJets20_47.CalcSig( 0 , 4 , -1 , 0.1 ) ; 
  nJets20_47.CalcSig( 0 , 2 , -1 , 0 ) ; 

  muCharge.CalcSig( 0 , 0 , -1 , 0 ) ; 
  muCharge.CalcSig( 0 , 4 , -1 , 0.1 ) ; 
  muCharge.CalcSig( 0 , 2 , -1 , 0 ) ; 
  muCharge.CalcSig( 1 , 0 , -1 , 0 ) ; 
  muCharge.CalcSig( 1 , 4 , -1 , 0.1 ) ; 
  muCharge.CalcSig( 1 , 2 , -1 , 0 ) ; 

  for(auto prop : allProps)
    prop->Write( theFile , 1000  );

#ifdef SingleTopTreeLHEWeights_h
  TDirectory* dirWScales = theFile->mkdir("WJScales");
  dirWScales->cd();
  for(int i=0;i<9;i++){
    cout << "WScalesTotal[i]" << WScalesTotal[i] << "," << WScalesTotal[0]/WScalesTotal[i] << endl;
    hEtajWScales[i]->Scale( WScalesTotal[0]/WScalesTotal[i] );
    hEtajWScales[i]->Write();
  }

  TDirectory* dirPDFScales = theFile->mkdir("PDFScales");
  dirPDFScales->cd();
  for(int i=0;i<102;i++){
    cout << "PDFScales[i]" << ScalesPDF[i] << "," << WScalesTotal[0]/ScalesPDF[i] << endl;
    hEtajPDFScales[i]->Scale( WScalesTotal[0]/ScalesPDF[i] );
    hEtajPDFScales[i]->Write();
  }
#endif

  TDirectory* dir2 = theFile->mkdir("JbJOptimizationProps");
  dir2->cd();

  for(auto prop2 : JbJOptimizationProps){
    prop2->CalcSig( 0 , 0 , -1 , 0 ) ; 
    prop2->CalcSig( 0 , 4 , -1 , 0.1 ) ; 
    prop2->CalcSig( 0 , 2 , -1 , 0 ) ; 
    prop2->Write( dir2 , 1000  );
  }

  theFile->cd();
  hTopMass->Write();
  hTopMassEtaJ->Write();
  //cutflowtable.Print("cutflowtable");
  theFile->Close();
  if( printEventIds )
    for( auto a : EventIdFiles ){
      a->close();
    }
}
Пример #27
0
int main(int argc, char **argv){
	TApplication *fApp = new TApplication("Test", NULL, NULL);
	int xbins = 10;
	int ybins = 10;
	int zbins = 10;
	int xlow = 0, xhigh = 10.;
	int ylow = 0, yhigh = 10.;
	int zlow = 0, zhigh = 10.;
	TCanvas *c = new TCanvas("TestCanvas", "ScatteringAngleCanvas", 800, 600);
	c->Divide(4,2);
	TH3F *hist = new TH3F("Test3DHist","Test3DHist",xbins,xlow,xhigh,ybins,ylow,yhigh,zbins,zlow,zhigh);
	for(int i = 0 ; i < 10 ; i++){
		for(int j = 0 ; j < 10; j++){
			for(int k = 0 ; k < 10 ; k++){
				hist->Fill(2,3,4);
				//hist->Fill(2,3,8);
			}
		}
	}


	TRandom t;
	TH3F *histValue = new TH3F("Test3DHistvalue","Test3DHistvalue",xbins,xlow,xhigh,ybins,ylow,yhigh,zbins,zlow,zhigh);
	int count = 0;
	float sum = 0.;
	for(int i = 0 ; i < 2 ; i++){
			for(int j = 0 ; j < 3; j++){
				for(int k = 0 ; k < 3 ; k++){
					count++;
					float val = t.Uniform(1,1010);
					std::cout<<"Count : " << count <<" : Val : "<< val << std::endl;
					sum += val;
					histValue->Fill(2,3,4,val);
					//hist->Fill(2,3,8);
				}
			}
		}

	std::cout<<"Sum : " << sum <<" : Average : " << (sum/1000) << std::endl;



	c->cd(1);
	hist->Draw();
	c->cd(2);
	hist->Project3D("x")->Draw();
	c->cd(3);
	hist->Project3D("y")->Draw();
	c->cd(4);
	hist->Project3D("yz")->Draw("0lego1 PFC");
	c->cd(5);
	histValue->Draw();
	histValue->Divide(hist);
	c->cd(6);
	histValue->Draw();

	sum = 0.;
	count = 0;
	TH2F *hist2DValue = new TH2F("Test2DHistvalue","Test2DHistvalue",xbins,xlow,xhigh,ybins,ylow,yhigh);
	for(int j = 0 ; j < 3; j++){
					for(int k = 0 ; k < 3 ; k++){
						count++;
						float val = t.Uniform(1,1010);
						std::cout<<"Count : " << count <<" : Val : "<< val << std::endl;
						sum += val;
						hist2DValue->Fill(2,3,val);
						//hist->Fill(2,3,8);
					}
				}

	std::cout<<"Sum : " << sum <<" : Average : " << (sum/count) << std::endl;

	c->cd(7);
	hist2DValue->Draw();

	fApp->Run();

}
Пример #28
0
int main(int argc, char** argv)
{ 
  //Check if all nedeed arguments to parse are there
  if(argc != 2)
  {
    std::cerr << ">>>>> VertexStudiesAnalysis::usage: " << argv[0] << " configFileName" << std::endl ;
    return 1;
  }
  
  // Parse the config file
  parseConfigFile (argv[1]) ;

  std::string inputFileList = gConfigParser -> readStringOption("Input::inputFileList");

  std::string treeName  = gConfigParser -> readStringOption("Input::treeName");

  std::string outputRootFilePath = gConfigParser -> readStringOption("Output::outputRootFilePath");
  std::string outputRootFileName = gConfigParser -> readStringOption("Output::outputRootFileName");  
 
  std::string tmvaMethod    = gConfigParser -> readStringOption("Input::tmvaMethod");
  std::string tmvaWeights   = gConfigParser -> readStringOption("Input::tmvaWeights");
 
  int entryMIN = gConfigParser -> readIntOption("Options::entryMIN");
  int entryMAX = gConfigParser -> readIntOption("Options::entryMAX");
 
  int isZee    = gConfigParser -> readIntOption("Options::isZee");
  int isZmumu  = gConfigParser -> readIntOption("Options::isZmumu");
  int isHiggs  = gConfigParser -> readIntOption("Options::isHiggs");

  int isData   = gConfigParser -> readIntOption("Options::isData");

  double trackThr = gConfigParser -> readDoubleOption("Options::trackThr");

  int useWeights      = gConfigParser -> readIntOption("Options::useWeights");
  int poissonWeights  = gConfigParser -> readIntOption("Options::poissonWeights");
  int nAvePU          = gConfigParser -> readIntOption("Options::nAvePU");
  
  std::string puweightsFileName = gConfigParser -> readStringOption("Options::puweightsFileName");  

  int useJSON      = gConfigParser -> readIntOption("Options::useJSON");
  std::string jsonFileName = gConfigParser -> readStringOption("Options::jsonFileName");  

  //******* Get run/LS map from JSON file *******
  std::map<int, std::vector<std::pair<int, int> > > jsonMap;
  if ( isData && useJSON ) {
    std::cout << ">>> Getting GOOD  run/LS from JSON file" << std::endl;
    jsonMap = readJSONFile(jsonFileName);
    std::cout << std::endl;
    std::cout << std::endl;
  }

  
  //****** Get weights for MC ****** 
  float nmax;
  float w[50];
  TRandom *gRandom = new TRandom();
  
  if (useWeights){
    
    TFile weightsFile(puweightsFileName.c_str(),"READ");  
    TH1F* hweights;
     
    if ( poissonWeights ){
      std::cout << "N ave PU for Poisson PU reweighting : " << nAvePU << std::endl;
      char hname[100];
      sprintf(hname,"hwpoisson_%d",nAvePU);
      hweights = (TH1F*)weightsFile.Get(hname);
    }
    else {
      hweights = (TH1F*)weightsFile.Get("hweights");
    }
    nmax = hweights ->GetMaximum();
    std::cout << " Max weight " << nmax << std::endl;
    
    for (int ibin = 1; ibin < hweights->GetNbinsX()+1; ibin++){
      w[ibin-1] = hweights->GetBinContent(ibin);  // bin 1 --> nvtx = 0 
    }
    weightsFile.Close();
  }
  
  //****** open TH1 with tracks pt for kolmogorov test
  TH1F *hTrackPt;
  TFile ptFile("hTracksPt_PU25_upTo10GeV.root","READ"); 
  hTrackPt = (TH1F*)ptFile.Get("hTracksPt")->Clone("hTrackPt");
  hTrackPt->SetDirectory(0);
  ptFile.Close();
  std::cout << hTrackPt->GetEntries() << std::endl;

  TH1F *htemp = (TH1F*)hTrackPt->Clone("htemp");
  htemp->Reset();
 

  //****** Parameters for vertex finding algo ****** 
  VertexAlgoParameters vtxAlgoParams_;
  vtxAlgoParams_.rescaleTkPtByError = false;
  vtxAlgoParams_.trackCountThr      = 1.;
  vtxAlgoParams_.highPurityOnly     = false;
  vtxAlgoParams_.maxD0Signif        = 9999999.;
  vtxAlgoParams_.maxDzSignif        = 9999999.;
  vtxAlgoParams_.removeTracksInCone = 1;
  vtxAlgoParams_.coneSize           = 0.05;
  
  //--- sumpt2 ordering
  vector<string> ranksumpt2_;
  ranksumpt2_.push_back("logsumpt2");  

  //--- ranking product variables
  vector<string> rankVariables_;
  // variables order matters to resolve ties
  rankVariables_.push_back("ptbal"), rankVariables_.push_back("ptasym"),rankVariables_.push_back("logsumpt2");  
  
  //--- book TMVA 
  int isSig, evtNumber, nVertices;
  float diphopt; 
  float logsumpt2;
  float ptbal, ptasym, ptmax, ptmax3, sumpt, nchthr, nch, sumtwd;
  float dk;
  TMVA::Reader *tmvaReader_ = new TMVA::Reader( "!Color:!Silent" );
  
  tmvaReader_->AddVariable( "logsumpt2",&logsumpt2 );
  tmvaReader_->AddVariable( "ptbal" , &ptbal);
  tmvaReader_->AddVariable( "ptasym", &ptasym );
  tmvaReader_->AddVariable( "nch",&nch );
  tmvaReader_->AddVariable( "nchthr",&nchthr );
  tmvaReader_->AddVariable( "ptmax" ,&ptmax  );
  tmvaReader_->AddVariable( "ptmax3",&ptmax3 );
  tmvaReader_->AddVariable( "sumtwd",&sumtwd );
  tmvaReader_->AddVariable( "dk",&dk );
  tmvaReader_->BookMVA( tmvaMethod.c_str(), tmvaWeights.c_str() );

 

  //****** BOOK OUTPUT HISTOGRAMS ******

  TH1F PtAll("PtAll","Pt of boson all",80,0,400);
  TH1F PtGood("PtGood","Pt of boson good",80,0,400);
  TH1F PtGood_BDT("PtGood_BDT","Pt of boson good (BDT)",80,0,400);
  TH1F PtGood_RANK("PtGood_RANK","Pt of boson good (RANKING)",80,0,400);

  TH1F PtAll_EBEB("PtAll_EBEB","Pt of boson all",80,0,400);
  TH1F PtGood_EBEB("PtGood_EBEB","Pt of boson good",80,0,400);
  TH1F PtGood_BDT_EBEB("PtGood_BDT_EBEB","Pt of boson good (BDT)",80,0,400);
  TH1F PtGood_RANK_EBEB("PtGood_RANK_EBEB","Pt of boson good (RANKING)",80,0,400);

  TH1F PtAll_EBEE("PtAll_EBEE","Pt of boson all",80,0,400);
  TH1F PtGood_EBEE("PtGood_EBEE","Pt of boson good",80,0,400);
  TH1F PtGood_BDT_EBEE("PtGood_BDT_EBEE","Pt of boson good (BDT)",80,0,400);
  TH1F PtGood_RANK_EBEE("PtGood_RANK_EBEE","Pt of boson good (RANKING)",80,0,400);

  TH1F PtAll_EEEE("PtAll_EEEE","Pt of boson all",80,0,400);
  TH1F PtGood_EEEE("PtGood_EEEE","Pt of boson good",80,0,400);
  TH1F PtGood_BDT_EEEE("PtGood_BDT_EEEE","Pt of boson good (BDT)",80,0,400);
  TH1F PtGood_RANK_EEEE("PtGood_RANK_EEEE","Pt of boson good (RANKING)",80,0,400);

  TH1F EtaAll("EtaAll","Eta of max SC",50,-5,5);
  TH1F EtaGood("EtaGood","Eta of max SC good",50,-5,5);
  TH1F EtaGood_BDT("EtaGood_BDT","Eta of max SC good (BDT)",50,-5,5);
  TH1F EtaGood_RANK("EtaGood_RANK","Eta of max SC good (RANKING)",50,-5,5);
  
  TH1F NvtAll("NvtAll","number of PV all",50,0,50);
  TH1F NvtGood("NvtGood","number of PV good",50,0,50);
  TH1F NvtGood_BDT("NvtGood_BDT","number of PV good (BDT)",50,0,50);
  TH1F NvtGood_RANK("NvtGood_RANK","number of PV good (RANKING)",50,0,50);

  TH1F NpuAll("NpuAll","number of PV all",50,0,50);
  TH1F NpuGood("NpuGood","number of PV good",50,0,50);
  TH1F NpuGood_BDT("NpuGood_BDT","number of PV good (BDT)",50,0,50);
  TH1F NpuGood_RANK("NpuGood_RANK","number of PV good (RANKING)",50,0,50);

  TH1F PtGood_matchedClosest("PtGood_matchedClosest","Pt of boson good",80,0,400);
  TH1F PtGood_BDT_matchedClosest("PtGood_BDT_matchedClosest","Pt of boson good (BDT)",80,0,400);
  TH1F PtGood_RANK_matchedClosest("PtGood_RANK_matchedClosest","Pt of boson good (RANKING)",80,0,400);

  TH1F EtaGood_matchedClosest("EtaGood_matchedClosest","Eta of max SC good",50,-5,5);
  TH1F EtaGood_BDT_matchedClosest("EtaGood_BDT_matchedClosest","Eta of max SC good (BDT)",50,-5,5);
  TH1F EtaGood_RANK_matchedClosest("EtaGood_RANK_matchedClosest","Eta of max SC good (RANKING)",50,-5,5);
  
  TH1F NvtGood_matchedClosest("NvtGood_matchedClosest","number of PV good",50,0,50);
  TH1F NvtGood_BDT_matchedClosest("NvtGood_BDT_matchedClosest","number of PV good (BDT)",50,0,50);
  TH1F NvtGood_RANK_matchedClosest("NvtGood_RANK_matchedClosest","number of PV good (RANKING)",50,0,50);

  TH1F NpuGood_matchedClosest("NpuGood_matchedClosest","number of PV good",50,0,50);
  TH1F NpuGood_BDT_matchedClosest("NpuGood_BDT_matchedClosest","number of PV good (BDT)",50,0,50);
  TH1F NpuGood_RANK_matchedClosest("NpuGood_RANK_matchedClosest","number of PV good (RANKING)",50,0,50);

  TH2F hdist("hdist"," hdist",80,0,200,400,-10,10);
  TH2F hdiff_dZ_muons("hdiff_dZ_muons","hdiff_dZ_muons",80,0,200,400,-10,10);
  TH2F hdiff_dZ_electrons("hdiff_dZ_electrons","hdiff_dZ_electrons",80,0,200,400,-10,10);

  TH1F BDToutput("BDToutput","BDT output",500,-1,1);
  TH1F BDToutput_sig("BDToutput_sig","BDT output - signal vertices",500,-1,1);
  TH1F BDToutput_bkg("BDToutput_bkg","BDT output - background",500,-1,1);
  

  TH1F pt2h("pt2h","pt2 H",500,0,500);
  TH1F pt2bkg("pt2bkg","pt2 bkg",500,0,500);


  TH2F * hAcceptedLumis = new TH2F("hAcceptedLumis","hAcceptedLumis",20000, 160000, 180000, 10000, 0, 10000);


  float ww = 1;
  float r9cut = 0.93;
  
  //****** LOAD TREE ******
  TChain* chain = new TChain(treeName.c_str());
  FillChain(*chain, inputFileList.c_str());
  treeReader reader((TTree*)(chain));
  std::cout<<"found "<< reader.GetEntries() <<" entries"<<std::endl;

  //****** Start loop over entries ******
  int runId, lumiId;

  for (int u = 0; u < reader.GetEntries(); u++ )
    {
      if(u == entryMAX) break;
      if(u < entryMIN)  continue;
      if(u%10000 == 0) std::cout<<"reading event "<< u <<std::endl;
      reader.GetEntry(u);
      
      //*** filter bad runs/lumis
      runId = reader.GetInt("runId")->at(0);
      lumiId = reader.GetInt("lumiId")->at(0);
      
      bool skipEvent = false;
      if( isData && useJSON ){
	if(AcceptEventByRunAndLumiSection(runId,lumiId,jsonMap) == false)
	  skipEvent = true;
      }
      if( skipEvent == true ) continue;
      hAcceptedLumis -> Fill(runId, lumiId);

      //*** pu weights
      std::vector<float>*PU_z ;
      std::vector<int>* mc_PUit_NumInteractions; 
      int npu ;

      if ( !isData ){
      	mc_PUit_NumInteractions  = reader.GetInt("mc_PUit_NumInteractions");
	npu = mc_PUit_NumInteractions->at(0);
      
	//--- use weights 
	if (useWeights){
	  float myrnd = gRandom->Uniform(0,nmax);
	  if (myrnd > w[npu]) continue;
	}
      }

     
      //*** setup common branches ***
      std::vector<int>* PV_nTracks;
      std::vector<float>* PV_z;
      std::vector<float>* PV_d0;
      std::vector<ROOT::Math::XYZVector>* PVtracks;
      std::vector<int>* PVtracks_PVindex;
      std::vector<int>* tracks_PVindex;
      std::vector<float>* tracks_dz ; //?
      std::vector<float>* tracks_dz_PV ; //?
      std::vector<float>* tracks_dxy_PV ; //?
      std::vector<ROOT::Math::XYZTVector>* sc; // supercluster
      
      int accept = 0;
      int indpho1 = -100;
      int indpho2 = -100;
	
      ROOT::Math::XYZTVector sum2pho;
      float etaMaxSC ;
      float TrueVertex_Z;

      //*** selections for Hgg ***
      if (isHiggs){
	std::vector<ROOT::Math::XYZVector>* mc_H_vertex = reader.Get3V("mc_H_vertex");
	std::vector<ROOT::Math::XYZTVector>* mcV1 = reader.Get4V("mcV1");
	std::vector<ROOT::Math::XYZTVector>* mcV2 = reader.Get4V("mcV2");
	std::vector<ROOT::Math::XYZTVector>* photons = reader.Get4V("photons");
	std::vector<float>* photons_r9 = reader.GetFloat("photons_r9");
	
	if (mc_H_vertex->size() != 1) continue;
	
	PV_nTracks       = reader.GetInt("PV_nTracks");
	PV_z             = reader.GetFloat("PV_z");
	PV_d0            = reader.GetFloat("PV_d0");
	PVtracks         = reader.Get3V("PVtracks");
	PVtracks_PVindex = reader.GetInt("PVtracks_PVindex");
	tracks_PVindex   = reader.GetInt("tracks_PVindex");
	tracks_dxy_PV    = reader.GetFloat("tracks_dxy_PV");
	tracks_dz_PV     = reader.GetFloat("tracks_dz_PV");
	tracks_dz        = reader.GetFloat("tracks_dz");
	sc               = reader.Get4V("photons_SC");

	hggSelection(mcV1, mcV2, photons, sc, photons_r9, accept, indpho1, indpho2);
	if (!accept) continue;

	if ( photons_r9->at(indpho1) < r9cut ) continue;
	if ( photons_r9->at(indpho2) < r9cut ) continue;
	
	etaMaxSC = sc->at(indpho1).eta();
	sum2pho  = photons->at(indpho1)+ photons->at(indpho2);
	TrueVertex_Z = mc_H_vertex->at(0).Z();
      }// end Hgg selection


      //*** selections for Zee ***
      if (isZee){
	std::vector<ROOT::Math::XYZTVector>* electrons = reader.Get4V("electrons");
	// std::vector<float>* eleid = reader.GetFloat("simpleEleId95cIso");
	// no eleID95 available for data 2011 --> compute it by hand
	std::vector<float>* eleid = new std::vector<float>;
	eleid->clear();
	if ( electrons->size() < 2) continue; 
	
	for (unsigned int iele = 0; iele < electrons->size(); iele++){
	  
	  float pt = electrons->at(iele).pt();
	  float tkIso   = reader.GetFloat("electrons_tkIsoR03")->at(iele);
	  float emIso   = reader.GetFloat("electrons_emIsoR03")->at(iele);
	  float hadIso  = reader.GetFloat("electrons_hadIsoR03_depth1")->at(iele) + reader.GetFloat("electrons_hadIsoR03_depth2")->at(iele);
	  float combIso = tkIso + emIso + hadIso;
	
	  int isEB = reader.GetInt("electrons_isEB")->at(iele);
	  float sigmaIetaIeta = reader.GetFloat("electrons_sigmaIetaIeta")->at(iele);
	  float DetaIn        = reader.GetFloat("electrons_deltaEtaIn")->at(iele);
	  float DphiIn        = reader.GetFloat("electrons_deltaPhiIn")->at(iele);
	  float HOverE        = reader.GetFloat("electrons_hOverE")->at(iele);
	  int mishits         = reader.GetInt("electrons_mishits")->at(iele);

	  float id = eleId95 ( pt, tkIso, emIso, hadIso, combIso, isEB, sigmaIetaIeta, DetaIn, DphiIn, HOverE, mishits);	
	  id *= 7.; // to emulate simpleEleId95cIso

	  eleid->push_back( id );
	}

	std::vector<float>* electrons_dz_PV_noEle = reader.GetFloat("electrons_dz_PV_noEle");

	PV_nTracks       = reader.GetInt("PV_noEle_nTracks");
	PV_z             = reader.GetFloat("PV_noEle_z");
	PV_d0            = reader.GetFloat("PV_noEle_d0");
	PVtracks         = reader.Get3V("PVEleLessTracks");
	PVtracks_PVindex = reader.GetInt("PVEleLessTracks_PVindex");
	tracks_PVindex   = reader.GetInt("tracks_PVindex");
	tracks_dxy_PV    = reader.GetFloat("tracks_dxy_PV");
	tracks_dz_PV     = reader.GetFloat("tracks_dz_PV");
	tracks_dz        = reader.GetFloat("tracks_dz");
	//sc               = reader.Get4V("electrons_SC");
	sc               = reader.Get4V("electrons");
	
	zeeSelection(electrons, eleid, accept, indpho1, indpho2);
	if (!accept) continue;

	etaMaxSC = sc->at(indpho1).eta();
	sum2pho  = electrons->at(indpho1)+ electrons->at(indpho2);
	TrueVertex_Z = PV_z->at(0) + (electrons_dz_PV_noEle->at(indpho1) + electrons_dz_PV_noEle->at(indpho2))/2.;

	hdiff_dZ_electrons.Fill( sum2pho.pt(), electrons_dz_PV_noEle->at(indpho1) - electrons_dz_PV_noEle->at(indpho2) );
      }

      //*** selections for Zmumu
      if ( isZmumu ){
	std::vector<ROOT::Math::XYZTVector>* muons = reader.Get4V("muons");
	std::vector<int>* muons_global = reader.GetInt("muons_global");
	std::vector<int>* muons_tracker = reader.GetInt("muons_tracker");
	std::vector<float>* muons_tkIsoR03 = reader.GetFloat("muons_tkIsoR03");
	std::vector<float>* muons_normalizedChi2 = reader.GetFloat("muons_normalizedChi2");
	std::vector<int>* muons_numberOfValidMuonHits = reader.GetInt("muons_numberOfValidMuonHits");
	std::vector<int>* muons_numberOfValidPixelHits = reader.GetInt("muons_numberOfValidPixelHits");
	std::vector<float>* muons_dxy_PV = reader.GetFloat("muons_dxy_PV");
	std::vector<float>* muons_dz_PV = reader.GetFloat("muons_dz_PV");
	std::vector<float>* muons_dz_PV_noMuon = reader.GetFloat("muons_dz_PV_noMuon");
	
	PV_nTracks       = reader.GetInt("PV_noMuon_nTracks");
	PV_z             = reader.GetFloat("PV_noMuon_z");
	PV_d0            = reader.GetFloat("PV_noMuon_d0");
	PVtracks         = reader.Get3V("PVMuonLessTracks");
	PVtracks_PVindex = reader.GetInt("PVMuonLessTracks_PVindex");
	tracks_PVindex   = reader.GetInt("tracks_PVindex");
	tracks_dxy_PV    = reader.GetFloat("tracks_dxy_PV");
	tracks_dz_PV     = reader.GetFloat("tracks_dz_PV");
	tracks_dz        = reader.GetFloat("tracks_dz");
	sc               = reader.Get4V("muons");  // use muon info for SC
	
	
	zmumuSelection(muons,muons_global,muons_tracker, muons_tkIsoR03, 
		       muons_normalizedChi2 , 
		       muons_numberOfValidMuonHits,
		       muons_numberOfValidPixelHits,
		       muons_dxy_PV,
		       muons_dz_PV,
		       accept, indpho1, indpho2);
	

	if (!accept) continue;
	
	etaMaxSC = muons->at(indpho1).eta();
	sum2pho  = muons->at(indpho1)+ muons->at(indpho2);
	TrueVertex_Z = PV_z->at(0) + (muons_dz_PV_noMuon->at(indpho1) + muons_dz_PV_noMuon->at(indpho2))/2.;
	
	hdiff_dZ_muons.Fill( sum2pho.pt(), muons_dz_PV_noMuon->at(indpho1) - muons_dz_PV_noMuon->at(indpho2) );
	
	if ( fabs(muons_dz_PV_noMuon->at(indpho1) - muons_dz_PV_noMuon->at(indpho2))> 0.5) continue;
      }//Zmumu end
      
      // branches buffers
      int nvtx_;
      float  vtxx_[1000], vtxy_[1000], vtxz_[1000];
      int ntracks_;
      float tkpx_[1000], tkpy_[1000], tkpz_[1000], tkPtErr_[1000], tkWeight_[1000], 
	tkd0_[1000], tkd0Err_[1000], tkdz_[1000], tkdzErr_[1000];
      int tkVtxId_[1000];
      bool tkIsHighPurity_[1000];
      
      float phocalox_[100], phocaloy_[100], phocaloz_[100], phoen_[100];
      
      // set variables
      
      // vertices 
      nvtx_    = (int) PV_z->size();
      for ( int iv = 0; iv < nvtx_; iv++){
	vtxx_[iv] =  0;
	vtxy_[iv] =  0;
	vtxz_[iv] =  PV_z->at(iv) ;
      }
      
      // tracks
      ntracks_ = PVtracks->size();
      for (int itrk = 0; itrk <ntracks_; itrk++ ){
	tkpx_[itrk]    = PVtracks->at(itrk).X();
	tkpy_[itrk]    = PVtracks->at(itrk).Y();
	tkpz_[itrk]    = PVtracks->at(itrk).Z();
	tkPtErr_[itrk] = 0;
	tkVtxId_[itrk] = PVtracks_PVindex->at(itrk);
	
	tkWeight_[itrk]= 1.;
	tkd0_[itrk]    = 0;
	tkd0Err_[itrk] = 0;
	tkdz_[itrk]    = 0;
	tkdzErr_[itrk] = 0;
	tkIsHighPurity_[itrk]= 1.;
      }
      
      // photons
      for (int ipho = 0 ; ipho < sc->size(); ipho++){
	float px = sc->at(ipho).X();
	float py = sc->at(ipho).Y();
	float pz = sc->at(ipho).Z();
	float pt = sqrt ( px*px+py*py ); 
	float theta = 2*atan(exp(-sc->at(ipho).eta()) );
	float tantheta = tan(theta);

	if ( fabs(sc->at(ipho).eta()) < etaEB ) {
	  phocalox_[ipho] = R_ECAL*px/pt;
	  phocaloy_[ipho] = R_ECAL*py/pt;
	  phocaloz_[ipho] = R_ECAL/tantheta;
	} 

	if ( fabs(sc->at(ipho).eta()) > etaEE ) {
	  float r_endcap  = fabs(Z_ENDCAP * tantheta);
	  phocalox_[ipho] = r_endcap * px/pt;
	  phocaloy_[ipho] = r_endcap * py/pt;
	  if (pz > 0) phocaloz_[ipho] = Z_ENDCAP;
	  else phocaloz_[ipho] = -Z_ENDCAP;
	} 
	
	phoen_[ipho] = sc->at(ipho).E();
	
      }


      float eta1 = sc->at(indpho1).eta();
      float eta2 = sc->at(indpho2).eta();

      if ( (fabs(eta1) > etaEB && fabs(eta1) < etaEE) || fabs(eta1) > 2.5) continue;
      if ( (fabs(eta2) > etaEB && fabs(eta2) < etaEE) || fabs(eta2) > 2.5) continue;
   
      //*** set vertex info
      TupleVertexInfo vinfo( nvtx_, vtxx_ , vtxy_, vtxz_, ntracks_, tkpx_, tkpy_, tkpz_, tkPtErr_, tkVtxId_, tkWeight_, tkd0_, tkd0Err_,tkdz_, tkdzErr_ , tkIsHighPurity_);
           
      //*** set photon info
      PhotonInfo pho1(indpho1, TVector3(phocalox_[indpho1],phocaloy_[indpho1],phocaloz_[indpho1]),phoen_[indpho1]); 
      PhotonInfo pho2(indpho2, TVector3(phocalox_[indpho2],phocaloy_[indpho2],phocaloz_[indpho2]),phoen_[indpho2]); 
     
      //*** vertex analyzer
      HggVertexAnalyzer vAna(vtxAlgoParams_,nvtx_);
      vAna.analyze(vinfo,pho1,pho2);
            
      // if Zmumu : setNconv to zero
      if (isZmumu) vAna.setNConv(0);

      //*** preselect vertices 
      std::vector<int> presel;
      for(int i=0; i<nvtx_; i++) {
	presel.push_back(i); 
      }
      vAna.preselection(presel);
      
      
      //*** Look if the H vertex matches one of the PV vertices
      float dmin = 10000;
      int iClosest = -1;
      for ( int uu = 0; uu < nvtx_; uu++){
	float distt = fabs( PV_z->at(uu) - TrueVertex_Z );
	if ( distt < dmin)   { dmin = distt; iClosest = uu; }
      }

      //*** NOW FILL HISTOGRAMS
      
      PtAll.Fill( sum2pho.pt(),ww );
      if (fabs(eta1) < etaEB && fabs(eta2) < etaEB)  PtAll_EBEB.Fill( sum2pho.pt(),ww );
      if (fabs(eta1) > etaEE && fabs(eta2) > etaEE)  PtAll_EEEE.Fill( sum2pho.pt(),ww );
      if ( (fabs(eta1) < etaEB && fabs(eta2) > etaEE) || (fabs(eta2) < etaEB && fabs(eta1) > etaEE))  PtAll_EBEE.Fill( sum2pho.pt(),ww );

      EtaAll.Fill( etaMaxSC ,ww);
      NvtAll.Fill( nvtx_,ww );
      if (!isData) NpuAll.Fill(npu,ww);

      
      //*** SUMPT2 CRITERION
      vector<int> ranksumpt2 = vAna.rankprod(ranksumpt2_);
      //-- matching 1cm
      if ( fabs( TrueVertex_Z - PV_z->at(ranksumpt2[0]) ) < 1.) {
	PtGood.Fill( sum2pho.pt(),ww );
	EtaGood.Fill( etaMaxSC ,ww);
	NvtGood.Fill( nvtx_ ,ww);
	if (!isData) NpuGood.Fill(npu,ww);
      }
      //-- matching closest vtx
      if ( iClosest == ranksumpt2[0]){
	PtGood_matchedClosest.Fill( sum2pho.pt(),ww );
	EtaGood_matchedClosest.Fill( etaMaxSC ,ww);
	NvtGood_matchedClosest.Fill( nvtx_ ,ww);
	if (!isData) NpuGood_matchedClosest.Fill(npu,ww);
	} 

   
      //*** RANKING PRODUCT
      vector<int> rankprod = vAna.rankprod(rankVariables_);
      //-- matching 1cm
      if ( fabs( TrueVertex_Z - PV_z->at(rankprod[0]) ) < 1.) {
	PtGood_RANK.Fill( sum2pho.pt(),ww );
	EtaGood_RANK.Fill( etaMaxSC ,ww);
	NvtGood_RANK.Fill( nvtx_,ww );
	if (!isData) NpuGood_RANK.Fill(npu,ww);
      }
      //-- matching closest vtx
      if ( iClosest == rankprod[0]){
	PtGood_RANK_matchedClosest.Fill( sum2pho.pt(),ww );
	EtaGood_RANK_matchedClosest.Fill( etaMaxSC ,ww);
	NvtGood_RANK_matchedClosest.Fill( nvtx_,ww );
	if (!isData) NpuGood_RANK_matchedClosest.Fill(npu,ww);
      }
      


      //*** BDT
      int TMVAind = -1;
      float TMVAmax = -1000.;

      for ( int uu = 0; uu < nvtx_; uu++){
			
	diphopt   = vAna.diphopt(uu);
	logsumpt2 = vAna.logsumpt2(uu);
	nch       = vAna.nch(uu);
	nchthr    = vAna.nchthr(uu);
	ptbal     = vAna.ptbal(uu);
	ptasym    = vAna.ptasym(uu);
	ptmax     = vAna.ptmax(uu);
	ptmax3    = vAna.ptmax3(uu);
	sumtwd    = vAna.sumtwd(uu);

	htemp->Reset();
	for (unsigned int kk = 0; kk < PVtracks->size(); ++kk){
	  if (PVtracks_PVindex->at(kk) == uu){
	    float tkpt = sqrt(PVtracks->at(kk).perp2()) ;
	    htemp ->Fill( (tkpt < 10. ? tkpt : 10.) );
	  }
	}

	if ( htemp->GetEntries()!=0 ) 
	  dk = htemp->KolmogorovTest(hTrackPt);

	//--- Evaluate TMVA
	Double_t mva = tmvaReader_->EvaluateMVA( "BDTG" ); 
	
	BDToutput.Fill( mva );
	if ( fabs( TrueVertex_Z - PV_z->at(uu) ) < 1.)  
	  BDToutput_sig.Fill( mva );
	else 
	  BDToutput_bkg.Fill( mva );

	// take the highest score
	if ( mva > TMVAmax) {
	  TMVAmax = mva;
	  TMVAind = uu;
	}
	
      } // end loop over vertices


      //-- matching 1cm
      if ( fabs( TrueVertex_Z - PV_z->at(TMVAind) ) < 1.) {
	PtGood_BDT.Fill( sum2pho.pt(),ww );
	EtaGood_BDT.Fill( etaMaxSC ,ww);
	NvtGood_BDT.Fill( nvtx_ ,ww);
	if (!isData) NpuGood_BDT.Fill(npu,ww);
      }
      //-- matching closest vtx
      if ( iClosest == TMVAind){
	PtGood_BDT_matchedClosest.Fill( sum2pho.pt(),ww );
	EtaGood_BDT_matchedClosest.Fill( etaMaxSC ,ww);
	NvtGood_BDT_matchedClosest.Fill( nvtx_,ww );
	if (!isData) NpuGood_BDT_matchedClosest.Fill(npu,ww);
      }
      
      
      
    }// end loop over entries

  std::cout << "END LOOP OVER ENTRIES" << std::endl;
  std::cout << "Saving histos on file ..." << std::endl;
  
  TFile ff( (outputRootFilePath+outputRootFileName).c_str(),"recreate");

  hAcceptedLumis -> Write();
  
  PtAll.Write();
  PtGood.Write();
  PtGood_BDT.Write();
  PtGood_RANK.Write();
  
  EtaAll.Write();
  EtaGood.Write();
  EtaGood_BDT.Write();
  EtaGood_RANK.Write();
  
  NvtAll.Write();
  NvtGood.Write();
  NvtGood_BDT.Write(); 
  NvtGood_RANK.Write();

  NpuAll.Write();
  NpuGood.Write();
  NpuGood_BDT.Write(); 
  NpuGood_RANK.Write();
    
  PtGood_matchedClosest.Write();
  PtGood_BDT_matchedClosest.Write();
  PtGood_RANK_matchedClosest.Write();
  
  EtaGood_matchedClosest.Write();
  EtaGood_BDT_matchedClosest.Write();
  EtaGood_RANK_matchedClosest.Write();
  
  NvtGood_matchedClosest.Write();
  NvtGood_BDT_matchedClosest.Write(); 
  NvtGood_RANK_matchedClosest.Write();

  NpuGood_matchedClosest.Write();
  NpuGood_BDT_matchedClosest.Write(); 
  NpuGood_RANK_matchedClosest.Write();

  hdist.Write();
  hdiff_dZ_muons.Write();
  hdiff_dZ_electrons.Write();
  
  BDToutput.Write();
  BDToutput_sig.Write();
  BDToutput_bkg.Write();
   
  ff.Close();
  
  std::cout << "BYE BYE !!!! " << std::endl;

  return 0; 
  

}