Ejemplo n.º 1
0
void hsumTimer(Int_t nfill=100000)
{
//
// Simple example illustrating how to use the C++ interpreter	
// to fill histograms in a loop and show the graphics results
// This program is a variant of the tutorial "hsum".
// It illustrates the use of Timers.
//Author: Rene Brun
   
  c1 = new TCanvas("c1","The HSUM example",200,10,600,400);
  c1->SetGrid();


// Create some histograms.
  total  = new TH1F("total","This is the total distribution",100,-4,4);
  main   = new TH1F("main","Main contributor",100,-4,4);
  s1     = new TH1F("s1","This is the first signal",100,-4,4);
  s2     = new TH1F("s2","This is the second signal",100,-4,4);
  total->Sumw2();   // store the sum of squares of weights
  total->SetMarkerStyle(21);
  total->SetMarkerSize(0.7);
  main->SetFillColor(16);
  s1->SetFillColor(42);
  s2->SetFillColor(46);
  total->SetMaximum(nfill/20.);
  total->Draw("e1p");
  main->Draw("same");
  s1->Draw("same");
  s2->Draw("same");
  c1->Update();slider = new TSlider("slider",
     "test",4.2,0,4.6,0.8*total->GetMaximum(),38);
  slider->SetFillColor(46);

// Create a TTimer (hsumUpdate called every 300 msec)
  TTimer timer("hsumUpdate()",300); 
  timer.TurnOn();

 // Fill histograms randomly
  Float_t xs1, xs2, xmain;
  gRandom->SetSeed();
  for (Int_t i=0; i<nfill; i++) {
     ratio = Float_t(i)/Float_t(nfill);
     if (gSystem->ProcessEvents()) break;
     xmain = gRandom->Gaus(-1,1.5);
     xs1   = gRandom->Gaus(-0.5,0.5);
     xs2   = gRandom->Landau(1,0.15);
     main->Fill(xmain);
     s1->Fill(xs1,0.3);
     s2->Fill(xs2,0.2);
     total->Fill(xmain);
     total->Fill(xs1,0.3);
     total->Fill(xs2,0.2);
  }
  timer.TurnOff();
  hsumUpdate();
}
Ejemplo n.º 2
0
Archivo: greyscale.C Proyecto: Y--/root
void greyscale()
{
   TCanvas *c = new TCanvas("grey", "Grey Scale", 500, 500);
   c->SetBorderMode(0);

   Int_t   n = 200;   // tunable parameter
   Float_t n1 = 1./n;
   for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
         TBox *b = new TBox(n1*j, n1*(n-1-i), n1*(j+1), n1*(n-i));
         Float_t grey = Float_t(i*n+j)/(n*n);
         b->SetFillColor(TColor::GetColor(grey, grey, grey));
         b->Draw();
      }
   }
   TPad *p = new TPad("p","p",0.3, 0.3, 0.7,0.7);
   const char *guibackground = gEnv->GetValue("Gui.BackgroundColor", "");
   p->SetFillColor(TColor::GetColor(guibackground));
   p->Draw();
   p->cd();
   TText *t = new TText(0.5, 0.5, "GUI Background Color");
   t->SetTextAlign(22);
   t->SetTextSize(.09);
   t->Draw();

   c->SetEditable(kFALSE);
}
Ejemplo n.º 3
0
// histograms filled and drawn in a loop
void hsum() {
//
// To see the output of this macro, click begin_html <a href="gif/hsum.gif" >here</a> end_html
//    Simple example illustrating how to use the C++ interpreter
//    to fill histograms in a loop and show the graphics results
//Author: Rene Brun

  TCanvas *c1 = new TCanvas("c1","The HSUM example",200,10,600,400);
  c1->SetGrid();

  gBenchmark->Start("hsum");

// Create some histograms.
  auto total  = new TH1F("total","This is the total distribution",100,-4,4);
  auto main   = new TH1F("main","Main contributor",100,-4,4);
  auto s1     = new TH1F("s1","This is the first signal",100,-4,4);
  auto s2     = new TH1F("s2","This is the second signal",100,-4,4);
  total->Sumw2();  // store the sum of squares of weights
  total->SetMarkerStyle(21);
  total->SetMarkerSize(0.7);
  main->SetFillColor(16);
  s1->SetFillColor(42);
  s2->SetFillColor(46);
  TSlider *slider = 0;

// Fill histograms randomly
  gRandom->SetSeed();
  const Int_t kUPDATE = 500;
  Float_t xs1, xs2, xmain;
  for ( Int_t i=0; i<10000; i++) {
     xmain = gRandom->Gaus(-1,1.5);
     xs1   = gRandom->Gaus(-0.5,0.5);
     xs2   = gRandom->Landau(1,0.15);
     main->Fill(xmain);
     s1->Fill(xs1,0.3);
     s2->Fill(xs2,0.2);
     total->Fill(xmain);
     total->Fill(xs1,0.3);
     total->Fill(xs2,0.2);
     if (i && (i%kUPDATE) == 0) {
        if (i == kUPDATE) {
           total->Draw("e1p");
           main->Draw("same");
           s1->Draw("same");
           s2->Draw("same");
           c1->Update();
           slider = new TSlider("slider",
              "test",4.2,0,4.6,total->GetMaximum(),38);
           slider->SetFillColor(46);
        }
        if (slider) slider->SetRange(0,Float_t(i)/10000.);
        c1->Modified();
        c1->Update();
     }
  }
  slider->SetRange(0,1);
  total->Draw("sameaxis"); // to redraw axis hidden by the fill area
  c1->Modified();
  gBenchmark->Show("hsum");
}
Ejemplo n.º 4
0
TGraph* 
makeGraph(const TArrayI& adcs, Int_t rate) 
{
  Int_t    last = adcs.fArray[0];
  TArrayI  counts(4);
  TGraph*  graph = new TGraph(rate * adcs.fN);
  graph->SetLineColor(rate);
  graph->SetMarkerColor(rate);
  graph->SetMarkerStyle(20+rate);
  graph->SetLineStyle(rate);
  graph->SetName(Form("rate%d", rate));
  graph->SetTitle(Form("Rate %d", rate));
  for (Int_t i = 0; i < adcs.fN; i++) { 
    counts.Reset(-1);
    convert(rate, adcs.fArray[i], last, counts);
    
    for (Int_t j = 0; j < rate; j++) { 
      Int_t    idx = (i * rate + j);
      Double_t x   = (i + (rate > 1 ? Float_t(j+1) / rate-1 : 0));
      graph->SetPoint(idx, x, counts[j]);
    }
    last = counts[rate - 1];
  }
  return graph;
}
Ejemplo n.º 5
0
int main(int argc, char *argv[])
{
   ROOT::Mpi::TEnvironment env(argc, argv);
   ROOT::Mpi::TIntraCommunicator world;

   MpiInitTest(world, 2, ROOT::Mpi::GreaterIqual);

   world.AllReduceSendScalar(world.Rank(), ROOT::Mpi::SUM);
   world.AllReduceSendScalar(Float_t(world.Rank() + 0.1), ROOT::Mpi::SUM);

   Int_t    i ;
   Float_t  f;

   world.AllReduceRecvScalar(i, ROOT::Mpi::SUM);
   world.AllReduceRecvScalar(f, ROOT::Mpi::SUM);
   MpiCompareTest(i, (world.Size() * (world.Size() + 1) / 2) - world.Size(), world.Rank(), "AllReduce Send/Recv Scalar Int_t");
   MpiCompareTest(f, Float_t((world.Size() * (world.Size() + 1) / 2) - world.Size() + 0.1 * world.Size()), world.Rank(), "AllReduce Send/Recv Scalar Float_t");

}
Ejemplo n.º 6
0
void
convert(UShort_t rate, Int_t adc, Int_t last, TArrayI& counts)
{
  if (rate == 1) { 
    Float_t a = adc;
    if (a < 0) a = 0;
    counts[0] = UShort_t(TMath::Min(a, 1023.F));
    return;
  }
  Float_t b = 6;
  for (Ssiz_t i = 0; i < rate; i++) { 
    Float_t t = Float_t(i) / rate + 1./rate;
    Float_t s = adc + (last - adc) * TMath::Exp(-b * t);
    Float_t a = s;
    if (a < 0) a = 0;
    counts[i] = UShort_t(TMath::Min(a, 1023.F));
    std::cout << " rate=" << rate << "\tadc=" << adc 
	      << "\tcount[" << i << "]=" << counts[i] 
	      << "\ts=" << adc << " + (" << last << " - " 
	      << adc << ") * exp(-" << b << " * " << t 
	      << ")=" << s << std::endl;
  }
  return;
}
Ejemplo n.º 7
0
void probability(Float_t param = 1, Float_t x1 = 0.9, Float_t x2 = 1.3, 
		 Float_t over = 2,const char * com ="", Int_t N=20)
{  

  //create canvas for drawing
  TCanvas  * c1 = new TCanvas("canprob","Pad response function",700,900);
  TPad * pad1 = new TPad("Theoretical probability","",0.05,0.22,0.95,0.95,21);
  pad1->Draw();
   
  //create histogram with estimated occupancy 
  //normalised to obtained occupancy at first pad
  Float_t y1=0;
  Float_t y2;
  char s[120];
  sprintf(s,"1-exp(-[1]/x**%f)",over);
  cout<<s<<"\n";
  TF1 *funr1 = new TF1("funr1",s,x1,x2);
  funr1->SetParameters(1,param);
  sprintf(s,"Probability  according 1-exp(-%1.3f/x**%1.1f distribution)",
	  param,over);
  pad1->cd();
  TH1F * hOccuT = new TH1F("hOccuT",s,5*N,x1,x2);
  Float_t x=x1;
  Float_t y;

  for (Float_t i = 0;i<N+1;i++)
    {     
      y = funr1->Eval(x);
      hOccuT->Fill(x,y);
      x+=(x2-x1)/Float_t(N);
    };
  //fitting calculated dependence with linear fit and with
  //generic function
  pad1->cd();
  sprintf(s,"[1]/(x**%1.1f)",over);
  TF1 *lin1 = new TF1("lin1","pol1",x1,x2);
  lin1->SetLineColor(2);
  lin1->SetLineWidth(5);
  lin1->SetLineStyle(1);
  hOccuT->Draw();
  hOccuT->Fit("lin1","S+");

  sprintf(s,"[1]/(x**%1.1f)",over);
  TF1 *funorig = new TF1("funorig",s,x1,x2);
  funorig->SetLineColor(3);
  funorig->SetLineWidth(5);
  funorig->SetLineStyle(2);
  hOccuT->Fit("funorig","S+");
  
  //find minimum and maximum and scale histo  
  if (y1 == 0)  
    {
      Float_t ymin,ymax;
      y1=lin1->Eval(x2);
      y2=lin1->Eval(x1);
      ymin= funorig->Eval(x2);
      ymax= funorig->Eval(x1);
      if (ymin<y1) y1=ymin;
      if (ymax>y2) y2=ymax;
    }
  gStyle->SetOptFit(0);
  gStyle->SetOptStat(0); 
  hOccuT->SetMaximum(y2);
  hOccuT->SetMinimum(y1); 
  hOccuT->SetXTitle("r position [m]");
  hOccuT->SetYTitle("probability");  
  //add comments to the histograms 
  c1->cd();
  TPaveText * comment = new TPaveText(0.05,0.03,0.95,0.20,"NDC");
  comment->SetTextAlign(12);
  comment->SetFillColor(42);
  TText *title = comment->AddText("Estimation of occupancy dependence on R position");
  title->SetTextSize(0.04);
  comment->AddText("Observed efect of probability saturation");
  sprintf(s,"Supposed generic flux dependence : %1.3f/(x**%1.1f)",param,over);
  comment->AddText(s);
  comment->AddText("Probility : 1-exp(-flux*mean particle \"pad x time\" area)");
  comment->AddText("Full line  linear fit ");
  comment->AddText("Dashed line : fit by generic flux function ");
  
  comment->AddText(com);
  comment->Draw();
}
Ejemplo n.º 8
0
void V0_efficiencies()

{      
// Caution: time windows and cuts on signals are HARD-coded 
//          they need to be adjusted to the current configuration

        gROOT->Reset();
	rl = AliRunLoader::Open("galice.root");
	rl->LoadgAlice();
	gAlice = rl->GetAliRun();
        Int_t nevent = rl->GetNumberOfEvents();
	cout<<" --- Number of events in file = "<< nevent <<" ---"<<endl;
	
//___________________________________________________
// Book HISTOGRAMS 
      
    	TH2F *hMapV0L   = new TH2F("hMapV0L","V0L",161,-0.8,0.8,161,-0.8,0.8);
    	TH2F *hMapV0R   = new TH2F("hMapV0R","V0R",161,-0.8,0.8,161,-0.8,0.8);	 
	TH1F *hpdgV0    = new TH1F("hpdgV0","pdgV0",1001,-500,500);  
	TH1F *hvertexZ  = new TH1F("hvertexZ","vertex Z",972,-40.,40.); 
	TH1F *hTimC     = new TH1F("hTimC","Time of Flight in V0C",500,0,49);
	TH1F *hTimA     = new TH1F("hTimA","Time of Flight in V0A",500,0,49);
	TH1F *hCell     = new TH1F("hCell","Cell Number",100,0,99);
	TH2F *hCellADC  = new TH2F("hCellADC","ADC vs Cell",100,0,99,1000,0,3999);
 
        TH1F *hMul0     = new TH1F("hMul0 ","Multiplicity in V0",80,0,79);
	TH1F *hMulC0    = new TH1F("hMulC0","Multiplicity in V0C",50,0,49);
        TH1F *hMulA0    = new TH1F("hMulA0","Multiplicity in V0A",50,0,49);
        TH1F *hMulAnd0  = new TH1F("hMulAnd0","Trigger and",50,0,49);
	
//___________________________________________________
	
	AliLoader *ld = rl->GetLoader("VZEROLoader");
	ld->GetHitsDataLoader()->Load("READ");
	
        rl->LoadHeader();
  
        // to access the particle  Stack
        rl->LoadKinematics("READ");

	AliVZERO  *v0 = (AliVZERO*)gAlice->GetDetector("VZERO");
	
	bool    flagV0L  = false;
	bool    flagV0R  = false;	
	Float_t timeV0L  = 1e12;
	Float_t timeV0R  = 1e12;	
	
	Int_t   fNdigits = 0;
	Int_t   fMulA    = 0;
	Int_t   fMulC    = 0;
        Int_t   fDigits  = 0;  
        Float_t fPhotoCathodeEfficiency =   0.18;
	
	
	Int_t   nVOL     = 0;
	Int_t   nVOR     = 0;
	Int_t   nVOLetR  = 0;
	Int_t   nVOLouR  = 0;
	
	TDatabasePDG * pdgdb = TDatabasePDG::Instance();


        Float_t fPMVoltage =  768.0;
        Float_t fPMGain1   = TMath::Power((fPMVoltage / 112.5) ,7.04277);
	Float_t fPMGain[64];
	Float_t cPM[64]; 
	
	for(Int_t ii=0; ii<64; ii++){
	fPMGain[ii] = gRandom->Gaus(fPMGain1, fPMGain1/5); // 20% uncertainty on the PM gain
        cPM[ii] = fPhotoCathodeEfficiency * fPMGain[ii];}
	
	Float_t kC     =  1e-11;
        Float_t kthau  =  2.1*1e-9;
        Float_t ktheta =  50.0 * kC;
        Float_t kQe    =  1.6e-19;
	Float_t coef   =  200.0;       //  p-p
//	Float_t coef   =    1.0;       // Pb-Pb
		
        Int_t map[80];     
        for(Int_t i=0; i<80; i++) map[i] = 0;
        Int_t hit[80];     
        for(Int_t i=0; i<80; i++) hit[i] = 0;
		
	for(Int_t event = 0; event < nevent; event++){
	Float_t timeV0L = 1e12;
	Float_t timeV0R = 1e12;	
	
	    rl->GetEvent(event);
            for(Int_t i=0; i<80; i++) map[i] = 0;
            for(Int_t i=0; i<80; i++) hit[i] = 0;
	    ld->LoadHits();
	    v0->SetTreeAddress();
	    TTree *treeH = ld->TreeH();
	    Int_t ntracks = treeH->GetEntries();
	
	    for (Int_t itrack=0; itrack<ntracks;itrack++) {
    
		v0->ResetHits();
		treeH->GetEvent(itrack);
		if(v0){
		  for (AliVZEROhit *vhit=(AliVZEROhit*)v0->FirstHit(itrack);
			  vhit; vhit=(AliVZEROhit*)v0->NextHit())
		  {
//			vhit->Dump();
                        hpdgV0->Fill(vhit->TrackPiD());
			hvertexZ->Fill(vhit->Vz()/100.);
			
			Float_t dt_scintillator = gRandom->Gaus(0,0.7);		
		        Float_t time = dt_scintillator + 1e9*vhit->Tof();
			
                        if(vhit->Z() > 0){
			if (time < 9 || time > 13) {continue;}		//time window V0A : 11 +/- 2 ns
			
			flagV0L = true;	
			hTimA->Fill(time);	
			if(time < timeV0L) timeV0L = time;	
		        hMapV0L->Fill(vhit->X()/100.,vhit->Y()/100.);}
					 
                        if(vhit->Z() < 0){
			if (time < 1 ||time > 5) {continue;}		//time window V0C : 3 +/- 2 ns
			
			flagV0R = true;	
			hTimC->Fill(time);
			if(time < timeV0R) timeV0R = time;
		        hMapV0R->Fill(vhit->X()/100.,vhit->Y()/100.);}
			
			Int_t nPhot = vhit->Nphot();
	                Int_t cell  = vhit->Cell();                                    
	                map[cell] += nPhot;
	                hit[cell] ++;
			
		  }
		} 
	     }
	     	
	       
        Int_t map2[64];      // cell to digits
        Int_t hit2[64];      // cell to digits
	Int_t j;
        Float_t time1[80];  
        Float_t time2[64];  
 	
	for (j=0; j<16; j++){
	map2[j] = map [j];
	hit2[j] = hit [j];
	//time2[j]=time1[j];
	}
	
	for (j=0; j<16; j++){
	map2[j+16] = map [2*j+16]+map [2*j+17];
	hit2[j+16] = hit [2*j+16]+hit [2*j+17];
	//time2[j+16]= TMath::Min(time1 [16 + 2*j], time1 [16 + 2*j + 1]);
	}
	
	for (j=32; j<64; j++){
	map2[j] =map[j+16];
	hit2[j] =hit[j+16];
	//time2[j] =time[j+16];
	}
		
	   fNdigits = 0;
	   fMulC    = 0;
	   fMulA    = 0;       
           for (Int_t i=0; i<64; i++) { 
                 Float_t q1 = Float_t ( map2[i] )* cPM[i] * kQe;
                 Float_t noise = gRandom->Gaus(10.5,3.22);
                 Float_t pmResponse  =  q1/kC*TMath::Power(ktheta/kthau,1/(1-ktheta/kthau)) 
                              + noise*1e-3;
                 map2[i] = Int_t( pmResponse * coef);
		 int test = 0;
                 if(map2[i] > 10) {map2[i] = Int_t( gRandom->Gaus(map2[i], 80));}		// charge smearing of MIP/4 -> sigma = MIP/4 = 120 (MIP = 480)
                 if(map2[i] > 240) {                                        			// cut at MIP/2 = 240
                       hCell->Fill(float(i));
		       hCellADC->Fill(float(i),map2[i]);		       
                       fNdigits++;
		       if(i<32) fMulC++;
		       if(i>31) fMulA++;
		       }
		       
	     } 
	     hMul0->Fill(fNdigits);
	     hMulC0->Fill(fMulC);
	     hMulA0->Fill(fMulA);
	     hMulAnd0->Fill(TMath::Min(fMulA, fMulC));
	     	     	
	     if(fMulA > 0){	
		nVOL++;}
		
	     if(fMulC > 0){	
		nVOR++;}
		
	     if(fMulA > 0 && fMulC > 0){	
		nVOLetR++;}
				
	     if(fMulA > 0 || fMulC > 0){	
		nVOLouR++;}      
 	
	     if(event%100==0) cout <<" event    = " << event <<endl;
//	     cout <<" multi   = " << fNdigits <<endl;   
        }
  	
	cout <<" nVOA     = " << nVOL <<endl;
	cout <<" nVOC     = " << nVOR <<endl;
	cout <<" nVOAandC = " << nVOLetR <<endl;
	cout <<" nVOAorC  = " << nVOLouR <<endl;
  		
//__________________________________________________
//      Fill root file

        TFile *histoFile = new TFile("Efficiencies.root","RECREATE");
   
    	hMapV0L->Write();
    	hMapV0R->Write();
	hpdgV0->Write();
	hvertexZ->Write();
	hTimC->Write();
	hTimA->Write();
	hCell->Write();
	hCellADC->Write();

	hMul0->Write();
	hMulC0->Write();
	hMulA0->Write();
	hMulAnd0->Write();
	histoFile->Close();   
	
}
Ejemplo n.º 9
0
/** Make Va1 response
    @param n 
    @param B 
    @param dc 
    @param errors 
    @ingroup simple_script
*/
void 
VA1Response(Int_t n=4, Float_t B=6, Float_t dc=.01, Bool_t errors=kFALSE,
	    Bool_t doFit=kFALSE) 
{
  gStyle->SetOptTitle(0);
  gStyle->SetOptStat(0);
  gStyle->SetOptFit(0);
  gStyle->SetLabelFont(132, "xyz");
  gStyle->SetTitleFont(132, "xyz");
  gStyle->SetTitleSize(0.08, "y");
  gStyle->SetTitleOffset(0.5, "y");
  gStyle->SetTitleSize(0.06, "x");
  gStyle->SetTitleOffset(0.7, "x");

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

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

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

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

  c->Modified();
  c->Update();
  c->cd();
  c->SaveAs("va1_response.png");
}
Ejemplo n.º 10
0
void analisi_tree_1hit(){ //faccio gli istogrammi dal Tree T creato nel file CheckESD.C
  gROOT->Reset();
  gStyle->SetOptStat(0012);
  gStyle->SetOptFit(0111);

  Bool_t kCal=kFALSE;

  TFile *fcal = TFile::Open("calibration.root");
  TProfile *hCalX;
  TProfile *hCalZ;
  if(fcal){
    kCal=kTRUE;
    hCalX = (TProfile *) fcal->Get("hCalX");
    hCalZ = (TProfile *) fcal->Get("hCalZ");
  }
  else{
    hCalX= new TProfile("hCalX","x alignement per strip;# strip;#DeltaX (cm)",1700,0,1700);
    hCalZ= new TProfile("hCalZ","z alignement per strip;# strip;#DeltaX (cm)",1700,0,1700);
  }

  // check alignment
  TProfile *hx = new TProfile("hx","x alignement per strip;# strip;#DeltaX (cm)",1700,0,1700);
  TProfile *hz = new TProfile("hz","z alignement per strip;# strip;#DeltaZ (cm)",1700,0,1700);
  
  // definire istogrammi (ricordarsi di fare il write nel file successivamente)
  //TH1F *hdeltat = new TH1F("hdeltat","inside the pad (cl_{1}) - cluster along x;t_{1} - t_{2} (ps)",400,-500,500);
  //TH1F *hdeltax = new TH1F("hdeltax","inside the pad (cl_{1}) - cluster along x;#Deltax_{1} - #Deltax_{2} (cm)",100,-10,10);
  TH1F *hch = new TH1F("hch","inside the pad (cl_{1}) - cluster along x;ch_{1} - ch_{2}",500,0,500);
  //TH2F *pxt = new TH2F("pxt","inside the pad (cl_{1}) - cluster along x ;t_{1} - t_{2} (ps);cl_{1} #Deltax (cm)",41,-20.5*24.4,20.5*24.4,100,-4,4); // 24.4 ps quantizzazione TDC
  //TH2F *pzt = new TH2F("pzt","inside the pad (cl_{1}) - cluster along z ;t_{1} - t_{2} (ps);cl_{1} #Deltaz (cm)",41,-20.5*24.4,20.5*24.4,100,-4,4); // 24.4 ps quantizzazione TDC
  //CFC:Istogramma numero cluster(qua coincidono con le hit)
  //TH1F *hnc = new TH1F("hnc","Number of Hits",12,0.,12.);
  //Istogramma  tempi TOF
  TH1F *ht1 = new TH1F("ht1","TOF's Time ",41,0.,30000.);
  
  //Istogramma 1D per i residui
  TH1F *hresx1 = new TH1F("hresx1","Residui x1",100,-10.,10.);
  TH1F *hresz1 = new TH1F("hresz1","Residui z1",100,-10.,10.);
  TH1F *hresdist1 = new TH1F("hresdist1","Residui sqrt(x1^2+z1^2)",100,-10.,10.);
  
  //Istogramma 2D per i residui
  TH2F *h2resxz1 = new TH2F("h2resxz1" , "Residui dx1 e dz1", 100, -4. , 4. , 100 , -4. , 4.);
  
  //Istogramma tempi meno tempi attesi
  TH1F *ht1_texp = new TH1F("ht1_texp","",100,-2000.,2000.);
  TH1F *ht1_texptot = new TH1F("ht1_texptot","",100,-2000.,2000.);
  
  //TH1F *hexp_time_pi = new TH1F("hexp_time_pi","hexp_time_pi",1000,0.,30000.);
  
  TProfile *hprofx  = new TProfile("hprofx","Profile t1-t_exp_pi vs dx1",26, -2.,2.);
  TProfile *hprofxcorr  = new TProfile("hprofxcorr","Profile t1-t_exp_pi corr vs dx1",26, -2.,2.);
  
  TProfile *hprofz  = new TProfile("hprofz","Profile t1-t_exp_pi vs dz1",26, -3.,3.);
  
  TProfile *hprofd=new TProfile("hprofd","Profile t1-t_exp_pi vs d",26, 0.,4.);
  
  TH1F *htbest = new TH1F("htbest","htbest",100,-2000.,2000.);
  
  TH1F *htcorrtw= new TH1F("htcorrtw","htcorrtw",100,-2000.,2000.);
  
  //TH2F *h2dxdzt1_texp=new TH2F("h2dxdzt1_texp","h2dxdzt1_texp",30,-10.25.,10.25,50,-10.75.,10.75.);
  //TH2F *h2dxdzt1_texp_dummy=new TH2F("h2dxdzt1_texp_dummy","h2dxdzt1_texp_dummy",30,-10.25.,10.25,50,-10.75.,10.75.);
  TH2F *h2dxdzt1_texp=new TH2F("h2dxdzt1_texp","h2dxdzt1_texp",20,-1.25,1.25,10,-1.75,1.75);
  TH2F *h2dxdzt1_texp_dummy=new TH2F("h2dxdzt1_texp_dummy","h2dxdzt1_texp_dummy",20,-1.25,1.25,10,-1.75,1.75);
  
  //Istogramma 2D distanza eff vs delay time
  TH2F *h2t1_texp_deff= new TH2F("h2t1_texp_deff" , "Delay time 0 vs deff", 50, 0. , 10.,100,-400.,400.);
  TH2F *h2t1_texp_deff_tw= new TH2F("h2t1_texp_deff_tw" , "Delay time 0 corr tw vs deff", 50, 0. , 10.,100,-400.,400.);
  
  TProfile *hprofdeff=new TProfile("hprofdeff","Profile t1-t_exp_pi vs deff",50, -3.,10.);
  
  // Utilizzo TOT.
  TH2F *h2t1_texp_TOT= new TH2F("h2t1_texp_TOT" , "Delay time vs TOT", 50, 0. , 100.,100,-400.,400.);
  TProfile *hproft1_texp_TOT = new TProfile("hproft1_texp_TOT","Profile t1-t_exp_pi vs TOT",50, 0. , 100.);
  TH2F *h2t1_deff_TOT= new TH2F("h2t1_deff_TOT" , "deff vs TOT", 50, 0. , 100.,50, 0. , 10.);
  TH2F *h2t1_TOT_deff= new TH2F("h2t1_TOT_deff" , "TOT vs deff",50, 0. , 10., 50, 0. , 100.);
  
  
  TFile *f = new TFile("AnalysisResults.root");
  TTree *T = (TTree*)f->Get("T"); //in generale . (e non freccia) se Tfile è un oggetto e NON un puntatore(*)
  
  
  //Varibili tree "T"
  //Int_t nevento;
  //Int_t ntracks;
  Int_t ncluster;
  Float_t tempo[100];//con start time sottratto
  Float_t DeltaX[100];
  Float_t DeltaZ[100];

  Int_t ChannelTOF[100];
  Float_t impulso_trasv;
  Float_t exp_time_pi[100];
  Float_t L[100];
  Float_t TOT[100];
  Float_t res[3];
  Int_t charge;
  Float_t phi,eta;
  Float_t secAngle;
  Float_t cval[5];
  Float_t thetay;
  Float_t StartTime,StartTimeRes;
  Float_t z;
  
  //T->Branch("nevento",&nevento,"nevento/I");
  //T->SetBranchAddress("ntracks",&ntracks);
  T->SetBranchAddress("ncluster",&ncluster);
  T->SetBranchAddress("tempo",tempo);
  T->SetBranchAddress("DeltaX",DeltaX);
  T->SetBranchAddress("DeltaZ",DeltaZ);
  T->SetBranchAddress("ChannelTOF",ChannelTOF);
  T->SetBranchAddress("impulso_trasv",&impulso_trasv);
  T->SetBranchAddress("exp_time_pi",exp_time_pi);
  T->SetBranchAddress("L",L);
  T->SetBranchAddress("TOT",TOT);
  T->SetBranchAddress("res",res);
  T->SetBranchAddress("charge",&charge);
  T->SetBranchAddress("phi",&phi);
  T->SetBranchAddress("eta",&eta);
  T->SetBranchAddress("secPhi",&secAngle);
  T->SetBranchAddress("cval",cval);
  T->SetBranchAddress("thetay",&thetay);
  T->SetBranchAddress("StartTime",&StartTime);
  T->SetBranchAddress("StartTimeRes",&StartTimeRes);
  
  
  Int_t nentries = (Int_t)T->GetEntries();
  
  for(Int_t i=0;i<nentries;i++) {
    T->GetEntry(i);
    
    for(Int_t ip=0;ip<ncluster;ip++){
      tempo[ip] -= StartTime;
      Int_t strip=ChannelTOF[0]/96;
      if(kCal){
	DeltaX[ip] -= hCalX->GetBinContent(strip+1);
	DeltaZ[ip] -= hCalZ->GetBinContent(strip+1);

      }
    }
    
    if(ncluster == 1){
      
      if(impulso_trasv>1.3){
	hx->Fill(int(ChannelTOF[0]/96),DeltaX[0]);
	hz->Fill(int(ChannelTOF[0]/96),DeltaZ[0]);

	if(!kCal){
	  hCalX->Fill(int(ChannelTOF[0]/96),DeltaX[0]);
	  hCalZ->Fill(int(ChannelTOF[0]/96),DeltaZ[0]);	  
	}

	h2resxz1->Fill(DeltaX[0],DeltaZ[0]);
	h2resxz1->GetXaxis()->SetTitle("Dx1 (cm)");
	h2resxz1->GetYaxis()->SetTitle("Dz1 (cm)");
	
	hresx1->Fill(DeltaX[0]);
	hresx1->GetXaxis()->SetTitle("Dx1 (cm)");
	
	hresz1->Fill(DeltaZ[0]);
	hresz1->GetXaxis()->SetTitle("Dz1 (cm)");
	
	hresdist1->Fill(sqrt(DeltaX[0]*DeltaX[0]+DeltaZ[0]*DeltaZ[0]));
	hresdist1->GetXaxis()->SetTitle("sqrt(Dx^2+Dz^2) (cm)");
      }

      if(impulso_trasv>0.8 && impulso_trasv<1.){ // serve per gli exp time
	//if( TMath::Abs(DeltaZ[0])<1.75){
	
	
	if(TMath::Abs(tempo[0]-exp_time_pi[0])<800./* per avere circa 3 sigma che sia un pi*/ ){
	  if(TMath::Abs(DeltaX[0])<1.5){
	    //if((ChannelTOF[0]/48)%2==0){z=1.75+DeltaZ[0];}
	    //if((ChannelTOF[0]/48)%2 == 1){z=1.75-DeltaZ[0];}
	    if((ChannelTOF[0]/48)%2==0){z=DeltaZ[0];}
	    if((ChannelTOF[0]/48)%2 == 1){z= -DeltaZ[0];}
	    Float_t w=tempo[0]- exp_time_pi[0];
	    h2dxdzt1_texp->Fill(DeltaX[0],z, w);
	    h2dxdzt1_texp_dummy->Fill(DeltaX[0],z);
	    
	    if( TMath::Abs(DeltaZ[0])<1.75 && TMath::Abs(DeltaX[0])<1.25){ //sto selezionando che il pad matchato sia dove passa la traccia, poichè altrimenti nel grafico con d e delay time vi sarebbero degli effetti di bordo
			  
	      Float_t t1=tempo[0];
	      ht1->Fill(t1);
	      ht1->GetXaxis()->SetTitle("t1(ps)");
	      
	      //cout<<(ChannelTOF[0]/48)%2<<endl;
	      
	      
	      Float_t d;
	      
	      if((ChannelTOF[0]/48)%2 == 0){
		d=sqrt(DeltaX[0]*DeltaX[0]+(1.75+DeltaZ[0])*(1.75+DeltaZ[0])); //da quello che ho capito il pad 0 è quello in alto quindi ha punto d raccolta in alto
		/*
		  if((ChannelTOF[0]/96)==((ChannelTOF[0]+48)/96)) //if fatto per capire quale sia quallo in alto e quale quello in basso poichè hanno una raccolta di carica differente
		  {
		  cout<<"ciao, io ,pad 0, sono quello sopra"<<endl;
		  }
		*/
	      }
	      if((ChannelTOF[0]/48)%2 == 1) {
		d=sqrt(DeltaX[0]*DeltaX[0]+(1.75-DeltaZ[0])*(1.75-DeltaZ[0])); //da quello che ho capito il pad 1 è quello in basso quindi ha punto d raccolta in basso
		/*//if fatto per capire quale sia quallo in alto e quale quello in basso poichè hanno una raccolta di carica differente
		  
		if((ChannelTOF[0]/96)==((ChannelTOF[0]+48)/96))
		{
		cout<<"ciao, io ,pad 1, sono quello sopra"<<endl;
		}
		*/
	      }
	      	      
              Float_t res1 = DeltaX[0]*DeltaX[0] + DeltaZ[0]*DeltaZ[0];
	      
              //Float_t posx = (DeltaX[0])*(ChannelTOF[0]-ChannelTOF[1]);
              
	      // hdeltax->Fill(posx);
              //hdeltax->GetXaxis()->SetTitle("posx (cm)");
	      //
	      //              pxt->Fill(tempo[0], DeltaX[0]);
	      //              pxt->GetXaxis()->SetTitle("t (cm)");
	      //              pxt->GetYaxis()->SetTitle("dx (cm)");
	      
              
	      //              pzt->Fill(tempo[0], DeltaZ[0]);
	      //              pzt->GetXaxis()->SetTitle("t(cm)");
	      //              pzt->GetYaxis()->SetTitle("Dz1 (cm)");
	      
              hch->Fill(ChannelTOF[0]);
              hch->GetXaxis()->SetTitle("ch");
	      
              Float_t tw1=tempo[0]- exp_time_pi[0];
	      
              ht1_texp->Fill(tw1);
              ht1_texp->GetXaxis()->SetTitle("t_{1} - t_{exp #pi} (ps)");
	      
	      //cerco correlazione tra TOT e delay time
              h2t1_texp_TOT->Fill(TOT[0],tw1);
              h2t1_texp_TOT->GetXaxis()->SetTitle("TOT ");
              h2t1_texp_TOT->GetYaxis()->SetTitle("t_{1}-t_{exp #pi} (ps)");
              hproft1_texp_TOT->Fill(TOT[0],tw1 ,1);
              hproft1_texp_TOT->GetXaxis()->SetTitle("TOT");
              hproft1_texp_TOT->GetYaxis()->SetTitle("t_{0}-t_{exp #pi} (ps)");
	      
	      /////////////////////PROFILE  1
	      
              //riempio istogrammma, poi lo fitto fuori dal loop
	      
	      //               hprofx->Fill(DeltaX[0],tw1 ,1);
	      //               hprofx->GetXaxis()->SetTitle("dx (cm)");
	      //               hprofx->GetYaxis()->SetTitle("t_{1}-t_{exp #pi} (ps)");
	      //        
	      //               hprofz->Fill(DeltaZ[0],tw1 ,1);
	      //               hprofz->GetXaxis()->SetTitle("dz (cm)");
	      //               hprofz->GetYaxis()->SetTitle("t_{1}-t_{exp #pi} (ps)");
	      
	      
	      hprofd->Fill(d,tw1 ,1);
	      hprofd->GetXaxis()->SetTitle("d (cm)");
	      hprofd->GetYaxis()->SetTitle("t_{1}-t_{exp #pi} (ps)");
	      
	      
	      
	      //}
	    }
	  }
	}
      }
    }
  }
    
  
  h2dxdzt1_texp->Divide(h2dxdzt1_texp_dummy);
  h2dxdzt1_texp->SetOption("LEGO2");
  h2dxdzt1_texp->GetXaxis()->SetTitle("dx (cm)");
  h2dxdzt1_texp->GetYaxis()->SetTitle("dz (cm)");
  
  //Double_t par[0]=0;
  //Double_t par[1]=0;
  
  TF2 *myfunc=new TF2("myfunc"," [0] * sqrt(x*x+[1]*[1]*(1.75+y)*(1.75+y))+[2]", -1.25,1.25,-1.75,1.75);
  myfunc->SetParameter(1,0.5);
  h2dxdzt1_texp->Fit(myfunc,"R");
  Double_t vel1, alfa;
  vel1= pow(myfunc->GetParameter(0),-1);
  alfa= myfunc->GetParameter(1);
  cout<<"Ciao, io sono la velocità in 3d "<<vel1<<endl;
  
  for(Int_t i=0;i<nentries;i++){
    T->GetEntry(i);
    
    for(Int_t ip=0;ip<ncluster;ip++){
      tempo[ip] -= StartTime;
      Int_t strip=ChannelTOF[0]/96;
      if(kCal){
	DeltaX[ip] -= hCalX->GetBinContent(strip+1);
	DeltaZ[ip] -= hCalZ->GetBinContent(strip+1);

      }
    }

    if(ncluster == 1) {
      if(impulso_trasv>0.8 && impulso_trasv<1.){ // serve per gli exp time
	if(TMath::Abs(tempo[0]-exp_time_pi[0])<800./* per avere circa 3 sigma che sia un pi*/ ){
	  
	  if(TMath::Abs(DeltaX[0])<1.5){
	    if((ChannelTOF[0]/48)%2==0){z=DeltaZ[0];}
	    if((ChannelTOF[0]/48)%2==1){z= -DeltaZ[0];}
	    Float_t deff=sqrt(DeltaX[0]*DeltaX[0]+ alfa*alfa * (1.75+z)*(1.75+z)*(z>-1.75));
	    Float_t tw1tot=tempo[0]- exp_time_pi[0];
	    h2t1_texp_deff->Fill(deff,tw1tot);
	    h2t1_texp_deff->GetXaxis()->SetTitle("deff (cm)");
	    h2t1_texp_deff->GetYaxis()->SetTitle("delay time (ps)");
            
	    hprofdeff ->Fill(deff,tw1tot ,1);
	    hprofdeff->GetXaxis()->SetTitle("deff (cm)");
	    hprofdeff->GetYaxis()->SetTitle("t_{1}-t_{exp #pi} (ps)");
            
	    h2t1_deff_TOT->Fill(TOT[0],deff);
	    h2t1_deff_TOT->GetXaxis()->SetTitle("TOT (ps)");
	    h2t1_deff_TOT->GetYaxis()->SetTitle("deff (cm)");
            
	    h2t1_TOT_deff->Fill(deff, TOT[0]);
	    h2t1_TOT_deff->GetXaxis()->SetTitle("deff (cm)");
	    h2t1_TOT_deff->GetYaxis()->SetTitle("TOT (ps)");
	           
	  }
	}
      }
    }
  }
  
  TF1 *fs = new TF1("fs","gaus",-400.,400.);
  h2t1_texp_deff->FitSlicesY(fs);
  TH1D *h2t1_texp_deff_1 = (TH1D *) gDirectory->FindObject("h2t1_texp_deff_1");
  h2t1_texp_deff_1->Draw("same");
  //h2t1_texp_deff_2->Draw("same");
  
  //   TF1 *f1 = new TF1("f1","pol1",0., 2.15);
  //    h2t1_texp_deff_1->Fit("f1","R");
  //    Double_t vel2;
  //    vel2 = pow(f1->GetParameter(1),-1);
  //    cout<<"Ciao, io sono la velocità in 2d "<<vel2<<endl;
  
  TF1 *f1 = new TF1("f1","[0]*TMath::Min(x,1.75)+[1]",0., 2.8); //Min(x,1.75) , l'1.75 è stato scelto guardando il fit, come meglio sembrava interploare. Per ora, per quanto ne so, è solo una coincidenza che coincida con pad z
  h2t1_texp_deff_1->Fit(f1,"R");
  Double_t p0,vel2, offset_tw;
  p0=f1->GetParameter(0);
  vel2= pow(p0,-1);
  offset_tw=f1->GetParameter(1);
  cout<<"Ciao, io sono la velocità in 2d "<<vel2<<endl;
  
  for(Int_t i=0;i<nentries;i++){
    T->GetEntry(i);
    
    for(Int_t ip=0;ip<ncluster;ip++){
      tempo[ip] -= StartTime;
      Int_t strip=ChannelTOF[0]/96;
      if(kCal){
	DeltaX[ip] -= hCalX->GetBinContent(strip+1);
	DeltaZ[ip] -= hCalZ->GetBinContent(strip+1);

      }
    }
    
    if(ncluster == 1){
      if(impulso_trasv>0.8 && impulso_trasv<1.){ // serve per gli exp time
	if(TMath::Abs(tempo[0]-exp_time_pi[0])<800./* per avere circa 3 sigma che sia un pi*/ ){                   
	  if(TMath::Abs(DeltaX[0])<1.5){
	    if((ChannelTOF[0]/48)%2==0){z=DeltaZ[0];}
	    if((ChannelTOF[0]/48)%2==1){z= -DeltaZ[0];}
            
	    Float_t deff=sqrt(DeltaX[0]*DeltaX[0]+ alfa*alfa * (1.75+z)*(1.75+z)*(z>-1.75));
            
	    if(deff<2.8){
	      Float_t tw1tot=tempo[0]- exp_time_pi[0];
	      ht1_texptot->Fill(tw1tot);
	      ht1_texptot->GetXaxis()->SetTitle("t_{1} - t_{exp #pi} (ps)");
	      
	      Float_t tw1corrtw=tw1tot-(offset_tw + p0 *TMath::Min(deff,Float_t(1.75)));//Min(x,1.75) , l'1.75 è stato scelto guardando il fit, come meglio sembrava interploare. Per ora, per quanto ne so, è solo una coincidenza che coincida con pad z
	      htcorrtw->Fill(tw1corrtw);
	      htcorrtw->GetXaxis()->SetTitle("t_corr_tw (ps)");
              
	      h2t1_texp_deff_tw->Fill(deff,tw1corrtw);
	      h2t1_texp_deff_tw->GetXaxis()->SetTitle("deff (cm)");
	      h2t1_texp_deff_tw->GetYaxis()->SetTitle("delay time corr_tw (ps)");
	      
	    }
	  }
	}
      }
    }
  }

    
  TF1 *fstw = new TF1("fstw","gaus",-400.,400.);
  h2t1_texp_deff_tw->FitSlicesY(fstw);
  TH1D *h2t1_texp_deff_tw_1 = (TH1D *) gDirectory->FindObject("h2t1_texp_deff_tw_1");
  TH1D *h2t1_texp_deff_tw_2 = (TH1D *) gDirectory->FindObject("h2t1_texp_deff_tw_2");
  
  h2t1_texp_deff_tw_1->Draw("same");
  h2t1_texp_deff_tw_2->Draw("same");
  
  //    TF1 *f1 = new TF1("f1","pol1",-1.25,0.5);
  //    //hprofx->GetYaxis()->SetRangeUser(-40.,100.);
  //    hprofx->Fit("f1","R");
  //    Double_t offset_p1,x1_p1;
  //    offset_p1= f1->GetParameter(0);
  //    x1_p1= f1->GetParameter(1);
  
  
  //    for(Int_t i=0;i<nentries;i++)
  //    {
  //        T->GetEntry(i);
  //    for(Int_t ip=0;ip<ncluster;ip++)
  //      tempo[ip] -= StartTime;
  //        if(ncluster == 1)
  //        {
  //        if(impulso_trasv>0.8 && impulso_trasv<1.2) // serve per gli exp time
  //        {
  //                //if( TMath::Abs(DeltaZ[0])<1.75)
  //                //{
  //        if(TMath::Abs(tempo[0]-exp_time_pi[0])<800./* per avere circa 3 sigmca che sia un pi*/ )
  //        {
  //
  //            //Float_t posx = (DeltaX[0])* dch;
  //            Float_t tw1=tempo[0]- exp_time_pi[0];
  //            
  //            Float_t tw1corr=tw1-(offset_p1 + x1_p1 *DeltaX[0]);
  //            
  //            hprofxcorr->Fill(DeltaX[0],tw1corr,1);
  //            hprofxcorr->GetXaxis()->SetTitle("Dx1 (cm)");
  //            hprofxcorr->GetYaxis()->SetTitle("t1_corr=t1-t_exp_pi corr(ps)");
  //            
  //            htbest->Fill(tw1corr);
  //            htbest->GetXaxis()->SetTitle("t_best=t1_corr(ps)");
  //        
  //        //}
  //        }
  //        }
  //        }
  //    }
  //    
  //    TF1 *f1c = new TF1("f1c","pol1",-1.25,0.5);
  //    hprofxcorr->Fit("f1c","R");
  
  TFile *fo2 = new TFile("output_ist_tree_1hit.root","RECREATE");
  
  hch->Write();
  ht1->Write();
  h2resxz1->Write();
  hresx1->Write();
  hresz1->Write();
  hresdist1->Write();
  //hdeltax->Write();
  //pxt->Write();
  //pzt->Write();
  //hdeltach->Write();
  ht1_texp->Write();
  ht1_texptot->Write();
  //hprofx->Write();
  //hprofz->Write();
  //hprofxcorr->Write();
  //htbest->Write();
  hprofd->Write();
  h2dxdzt1_texp->Write();
  //h2dxdzt1_texp_dummy->Write();
  h2t1_texp_deff->Write();
  h2t1_texp_deff_1->Write();
  //h2t1_texp_deff_2->Write();
  hprofdeff->Write();
  
  htcorrtw->Write();
  
  h2t1_texp_deff_tw->Write();
  h2t1_texp_deff_tw_1->Write();
  h2t1_texp_deff_tw_2->Write();
  h2t1_texp_TOT->Write();
  hproft1_texp_TOT->Write();
  h2t1_deff_TOT->Write();
  h2t1_TOT_deff->Write();
  hx->Write();
  hz->Write();
  fo2->Close();
  
  if(!kCal){
    printf("write calibration\n");
    fcal = new TFile("calibration.root","RECREATE");
    hCalX->Write();
    hCalZ->Write();
    fcal->Close();
  }

  system("say Ehi you, I have done");
}
Ejemplo n.º 11
0
void Fragment(Int_t nev=0, Int_t debug=0)
{
 gROOT->Reset();
 
 Float_t b;
 Int_t nspectp, nspectn, nspectpfree, nspectnfree; 
 Int_t zz[100], nn[100], nalpha, NFrag, ztot, ntot, ndeu;
 void spectator(Float_t, Int_t*, Int_t*);
 
 TH2F *hsp = new TH2F("hsp","Spectator protons vs b",50,0.,20.,90,0.,90.);
 hsp -> SetXTitle("b (fm)");
 hsp -> SetYTitle("Num. of spectator protons");
 
 TH2F *hsn = new TH2F("hsn","Spectator neutrons vs b",50,0.,20.,130,0.,130.);
 hsn -> SetXTitle("b (fm)");
 hsn -> SetYTitle("Num. of spectator neutrons");
 
 TH2F *hFragp = new TH2F("hFragp","Free spectator protons vs b",50,0.,20.,60,0.,60.);
 hFragp -> SetXTitle("b (fm)");
 hFragp -> SetYTitle("Num. of free spectator protons");
 
 TH2F *hFragn = new TH2F("hFragn","Free spectator neutrons vs b",50,0.,20.,80,0.,80.);
 hFragn -> SetXTitle("b (fm)");
 hFragn -> SetYTitle("Num. of free spectator neutrons");

 TF1 *funb = new  TF1("funb","x",0,20);
 for(Int_t ievent=0; ievent<nev; ievent++){  
   if(ievent%1000==0){printf("Processing event %d\n",ievent);}
   b= Float_t(funb->GetRandom()); 
   spectator(b, &nspectp, &nspectn);
   hsp -> Fill(b,nspectp);
   hsn -> Fill(b,nspectn);
   AliZDCFragment *gallio = new AliZDCFragment(b);
   for(Int_t j=0; j<=99; j++){
      zz[j] =0;
      nn[j] =0;
   }
//
// Generation of fragments
   gallio->GenerateIMF();
   nalpha = gallio->GetNalpha();
   NFrag = gallio->GetFragmentNum();
//
   // Attach neutrons
   ztot = gallio->GetZtot();
   ntot = gallio->GetNtot();
   gallio->AttachNeutrons();
   //
   nspectpfree = (nspectp-ztot-2*nalpha);
   nspectnfree = (nspectn-ntot-2*nalpha);
   
   // Removing deuterons
   ndeu = (Int_t) (nspectnfree*gallio->DeuteronNumber());
   nspectpfree -= ndeu;
   nspectnfree -= ndeu;
   //
   hFragp -> Fill(b, nspectpfree);
   hFragn -> Fill(b, nspectnfree);
//
// Print
   if(debug == 1){
     printf("\n	b = %f",b);
     printf("	#spect p = %d, #spect n = %d\n",nspectp,nspectn); 
     printf("	#spect p free = %d, #spect n free = %d\n",nspectpfree,nspectnfree); 
     printf("	#fragments = %f ",NFrag);
     /*for(Int_t i=0; i<NFrag; i++){
   	printf("\n	ZZ[%d] = %d, NN[%d] = %d\n",i,zz[i],i,nn[i]);
     }*/
     printf("	NAlpha = %d, Ztot = %d, Ntot = %d\n\n",nalpha,ztot,ntot);
   }
   delete gallio;
  } //Event loop
  
  TProfile *profsp = hsp->ProfileX("profsp",-1,-1,"s");
  TProfile *profsn = hsn->ProfileX("profsn",-1,-1,"s");
  TProfile *profFragp = hFragp->ProfileX("profFragp",-1,-1,"s");
  TProfile *profFragn = hFragn->ProfileX("profFragn",-1,-1,"s");

   
  //***********************************************************
  // #### ROOT initialization
  gROOT->Reset();
  gStyle->SetCanvasColor(10);
  gStyle->SetFrameFillColor(10);
  gStyle->SetPalette(1);
  gStyle->SetOptStat(0);
  //
  TCanvas *c1 = new TCanvas("c1","Fragmentation I",0,0,700,700);
  c1->cd();
  c1->SetFillColor(kAzure+7);
  c1->Divide(2,2);
  c1->cd(1);
  hsp -> Draw("colz");   
  c1->cd(2);
  hsn -> Draw("colz");    
  c1->cd(3);
  hFragp -> Draw("colz");   
  c1->cd(4);
  hFragn -> Draw("colz"); 
  //
  c1->Print("Fragment1.gif");   
  //
  TCanvas *c2 = new TCanvas("c2","Fragmentation II",300,10,700,700);
  c2->cd();
  c2->SetFillColor(kAzure+10);
  c2->Divide(2,2);
  c2->cd(1);
  profsp ->SetLineColor(kRed);  profsp ->SetLineWidth(2);
  profsp -> Draw("colz");   
  c2->cd(2);
  profsn ->SetLineColor(kRed);  profsn ->SetLineWidth(2);
  profsn -> Draw("colz");    
  c2->cd(3);
  profFragp -> Draw("colz");   
  profFragp ->SetLineColor(kAzure);  profFragp ->SetLineWidth(2);
  c2->cd(4);
  profFragn -> Draw("colz");    
  profFragn ->SetLineColor(kAzure);  profFragn ->SetLineWidth(2);
  //
  c1->Print("Fragment2.gif");   

}
Ejemplo n.º 12
0
void plotGlauberCenVars(Float_t eff=1., const Char_t* file="ZNA_ntuple_195483.root")
{
  TFile *f = TFile::Open(file);
  TNtuple* ntuple = dynamic_cast<TNtuple*> (f->Get("gnt"));
   
  TGraphErrors *gNpart=new TGraphErrors(0);
  gNpart->SetName("gNpart"); 
  TGraphErrors *gNcoll=new TGraphErrors(0);
  gNcoll->SetName("gNcoll"); 
  TGraphErrors *gtAA=new TGraphErrors(0);
  gtAA->SetName("gtAA"); 
  
  /*TFile *ffd = TFile::Open("hZNAcalibRUN195483.root");
  TH1F * hd = dynamic_cast<TH1F*> (ffd->Get(("hZNA")));
  hd->Sumw2();*/
  //
  TFile *ff = TFile::Open("ZNA_fit_195483.root");
  TH1F * hd = dynamic_cast<TH1F*> (ff->Get(("hZNA")));
  hd->Sumw2();
  TH1F * hg = dynamic_cast<TH1F*> (ff->Get(("hZNA_GLAU")));
  hd->SetMarkerColor(kBlue+3);
  hd->SetMarkerSize(1.);
  hd->SetLineColor(kBlue+3);
  hd->SetLineWidth(2);
  hd->SetMarkerStyle(20);
  hd->SetLineWidth(2);
//  hg->Scale(1./hd->GetEntries());
//  hd->Scale(1./hd->GetEntries());
  hd->SetMinimum(1.e-01);
  hd->SetXTitle("E_{ZNA} (TeV)");
  hg->SetLineColor(kPink-2);
  hg->SetLineWidth(2);
  
  TH1F* hist = (TH1F*) hg->Clone("hist");

  //---------------------------------------------------
  getCentrality(hist, eff);
  //---------------------------------------------------

  TCanvas* canvas = new TCanvas("canvas","Multiplicity",200,200,600,600);
  canvas->cd();
  canvas->SetLogy();
  hd->Draw("pe");
  //hd->GetXaxis()->SetRangeUser(0.,130.);
  hd->SetMinimum(0.01);
  hg->Draw("SAME");

  float low = 0;
  float high = hist->GetNbinsX();
  for(int i=0; i<binUp->GetSize(); i++){
      low = binUp->At(i);
      hist->GetXaxis()->SetRange(low+1, high);
      hist->SetFillColor((i%2==0)?0:kAzure+6);
      hist->SetLineColor((i%2==0)?0:kAzure+6);
      printf(" bin %d  low %f  high %f\n",i,low,high);
      hist->DrawCopy("h same");
      high=low;
  }
  hd->Draw("esame");
  hg->Draw("SAME");
  canvas->Print("plotGlauber.gif");   
  
  TCanvas* canvas2 = new TCanvas("canvas2","NPart");
  canvas2->cd();
  canvas2->SetLogy();
  TH1F *hist2 = new TH1F("hist2","N_{part}",35,0.,35);
  ntuple->Project("hist2","fNpart");
  //hist2->SetStats(0);
  hist2->SetTitle("");
  hist2->GetXaxis()->SetTitle("NPart");
  hist2->GetXaxis()->SetTitleSize(0.05);
  hist2->GetXaxis()->SetLabelSize(0.04);
  hist2->GetXaxis()->SetTitleOffset(1.2);
  hist2->GetYaxis()->SetTitle("");
  hist2->GetYaxis()->SetTitleOffset(1.3);
  hist2->GetYaxis()->SetTitleSize(0.05);
  hist2->GetYaxis()->SetLabelSize(0.04);
  hist2->DrawCopy();
  
  float lownp=0;
  float highnp=5000;
  TH1F *htemp10[nbins];
  printf("\n ***** N_part \n");
  for(int i=0; i<Multbin->GetSize(); i++){
      lownp = Multbin->At(i);
      char cuts[120];
      char histname[20];
      sprintf(cuts,"Etot>%f && Etot<=%f",lownp,highnp);
      sprintf(histname,"htemp10[%i]",i);
      htemp10[i] = new TH1F(histname,"N_{part}",35,0.,35);
      //printf(" cut: %s\n", cuts);
      ntuple->Project(histname,"fNpart",cuts);
      htemp10[i]->SetLineColor(i+1);
      htemp10[i]->Draw("same");
      cout  << i << " | " << lownp << " | " << highnp << " | " << setprecision(3) << 
      htemp10[i]->GetMean() << " | " << htemp10[i]->GetRMS() << " | " << endl;
      gNpart->SetPoint(i,Float_t(i),htemp10[i]->GetMean());
      gNpart->SetPointError(i,0,htemp10[i]->GetRMS());
      highnp = lownp;
  }
  cout << endl;
  
  TCanvas* canvas3 = new TCanvas("canvas3","NColl");
  canvas3->SetLogy();
  TH1F *hist3 = new TH1F("hist3","N_{coll}",35,0.,35);
  ntuple->Project("hist3","fNcoll");
  //hist3->SetStats(0);
  hist3->SetTitle("");
  hist3->GetXaxis()->SetTitle("NColl");
  hist3->GetXaxis()->SetTitleSize(0.05);
  hist3->GetXaxis()->SetLabelSize(0.04);
  hist3->GetXaxis()->SetTitleOffset(1.2);
  hist3->GetXaxis()->SetTitle("");
  hist3->GetXaxis()->SetTitleOffset(1.3);
  hist3->GetXaxis()->SetTitleSize(0.05);
  hist3->GetXaxis()->SetLabelSize(0.04);
  hist3->DrawCopy();
  
  float lownc = 0;
  float highnc = 5000;
  TH1F *htemp11[nbins];
  printf("\n ***** N_coll \n");
  for(int i=0; i<Multbin->GetSize(); i++){
      lownc = Multbin->At(i);
      char cuts[120];
      char histname[20];
      sprintf(cuts,"Etot>%f && Etot<=%f",lownc,highnc);
      sprintf(histname,"htemp11[%i]",i);
      htemp11[i] = new TH1F(histname,"N_{coll}",35,0.,35.);
      ntuple->Project(histname,"fNcoll",cuts);
      htemp11[i]->SetLineColor(i+1);
      htemp11[i]->Draw("same");
      cout << setprecision(3) << htemp11[i]->GetMean() << " | " << htemp11[i]->GetRMS() << " | " << endl;
      gNcoll->SetPoint(i,Float_t(i),htemp11[i]->GetMean());
      gNcoll->SetPointError(i,0,htemp11[i]->GetRMS());
      highnc = lownc;
  }
  cout << endl;
  
  TCanvas* canvas4 = new TCanvas("canvas4","Impact Parameter");
  canvas4->cd();
  TH1F *hist4 = new TH1F("hist4","b",100,0.,16.);
  ntuple->Project("hist4","fB");
  //hist4->SetStats(0);
  hist4->SetTitle("");
  hist4->GetXaxis()->SetTitle("b");
  hist4->GetXaxis()->SetTitleSize(0.05);
  hist4->GetXaxis()->SetLabelSize(0.04);
  hist4->GetXaxis()->SetTitleOffset(1.2);
  hist4->GetYaxis()->SetTitle("");
  hist4->GetYaxis()->SetTitleOffset(1.3);
  hist4->GetYaxis()->SetTitleSize(0.05);
  hist4->GetYaxis()->SetLabelSize(0.04);
  hist4->DrawCopy();
  
  float lowb = 0;
  float highb = 5000;
  TH1F *htemp12[nbins];
  printf("\n ***** b \n");
  for(int i=0; i<Multbin->GetSize(); i++){
      lowb = Multbin->At(i);
      char cuts[100];
      char histname[25];
      sprintf(cuts,"Etot>%f && Etot<=%f",lowb,highb);
      sprintf(histname,"htemp12[%i]",i);
      htemp12[i] = new TH1F(histname,"b",100,0.,16.);
      //printf(" cut: %s\n", cuts);
      ntuple->Project(histname,"fB",cuts);
      htemp12[i]->SetLineColor(i+1);
      htemp12[i]->DrawCopy("same");
      cout << i << " | " << lowb << " | " << highb << " | " << setprecision(3) << htemp12[i]->GetMean() << " | " << htemp12[i]->GetRMS() << " | " << endl;
      highb = lowb;
  }
  
  TCanvas* canvas5 = new TCanvas("canvas5","Taa");
  canvas5->SetLogy();
  TH1F *hist5 = new TH1F("hist5","T_{AA}",100,0.,0.5);
  ntuple->Project("hist5","fTaa");
  //hist5->SetStats(0);
  hist5->SetTitle("");
  hist5->GetXaxis()->SetTitle("tAA");
  hist5->GetXaxis()->SetTitleSize(0.05);
  hist5->GetXaxis()->SetLabelSize(0.04);
  hist5->GetXaxis()->SetTitleOffset(1.2);
  hist5->GetYaxis()->SetTitle("");
  hist5->GetYaxis()->SetTitleOffset(1.3);
  hist5->GetYaxis()->SetTitleSize(0.05);
  hist5->GetYaxis()->SetLabelSize(0.04);
  hist5->DrawCopy();
  
  float lowtaa = 0;
  float hightaa = 5000;
  TH1F *htemp13[nbins];
  printf("\n ***** T_AA \n");
  for (int i=0; i<Multbin->GetSize(); i++){
      lowtaa = Multbin->At(i);
      char cuts[100];
      char histname[100];
      sprintf(cuts,"Etot>%f && Etot<%f",lowtaa,hightaa);
      //printf(" cut: %s\n", cuts);
      sprintf(histname,"htemp13[%i]",i);
      htemp13[i] = new TH1F(histname,"b",100,0.,0.5);
      ntuple->Project(histname,"fTaa",cuts);
      htemp13[i]->SetLineColor(i+1);
      htemp13[i]->DrawCopy("same");
      cout << setprecision(3) << htemp13[i]->GetMean() << " | " << htemp13[i]->GetRMS() << " | " << endl;  
      gtAA->SetPoint(i,Float_t(i),htemp13[i]->GetMean());
      gtAA->SetPointError(i,0,htemp13[i]->GetRMS());
      hightaa = lowtaa;
  }

  /*TCanvas* canvas6 = new TCanvas("canvas6","Mean Mult");
  canvas6->SetLogy();
  //ntuple->Draw("ntot/Npart/23.867>>hmultperanc");
  ntuple->Draw("Etot/(0.801*Npart+(1-0.801)*Ncoll)/3.9>>hmultperanc");
  TH1F* hmultperanc = (TH1F*)gPad->GetPrimitive("hmultperanc");
  TH1F* hist6 = (TH1F*)hmultperanc->Clone();
  hist6->SetStats(0);
  hist6->SetTitle("");
  hist6->GetXaxis()->SetTitle("Mult/NPart");
  hist6->GetXaxis()->SetTitleSize(0.05);
  hist6->GetXaxis()->SetLabelSize(0.04);
  hist6->GetXaxis()->SetTitleOffset(1.);
  hist6->GetYaxis()->SetTitle("");
  hist6->GetYaxis()->SetTitleOffset(1.);
  hist6->GetYaxis()->SetTitleSize(0.05);
  hist6->GetYaxis()->SetLabelSize(0.04);
  hist6->DrawCopy();
  
  low=0;
  high=50000;
  for (int i=0; i<Multbin->GetSize(); i++)
    {
      low=Multbin->At(i);
      char cuts[100];
      char histtitle1[100];
      char histtitle[100];
      sprintf(cuts,"Etot>%i && Etot<%i",low,high);
      //sprintf(histtitle,"ntot/Npart/23.867>>htemp%i(100)",80+i);
      sprintf(histtitle,"Etot/(0.801*Npart+(1-0.801)*Ncoll)/3.9>>htemp%i(100)",80+i);
      sprintf(histtitle1,"htemp%i",80+i);
      ntuple->Draw(histtitle,cuts,"same");
      TH1F* htemp14 = (TH1F*)gPad->GetPrimitive(histtitle1);
      htemp14 = (TH1F*)gPad->GetPrimitive(histtitle1);
      htemp14->SetFillColor(i+1);
      htemp14->DrawCopy("same");
      //cout  << i << " | " << low << " | " << high << " | " << setprecision(3) << htemp14->GetMean() << " | " << htemp14->GetRMS() << " | " << endl;
      high=low;
      
      h->SetBinContent(i+1,htemp14->GetMean());
      h->SetBinError(i+1,0.01*htemp14->GetRMS());  
    }
  
  TCanvas* c7 = new TCanvas("c7","c7");
  c7->cd();
  h->Draw();
  */
  
  //TFile *outrootfile = new TFile("OutGlauber_Hijing.root","RECREATE");
  TFile *outrootfile = new TFile("test.root","RECREATE");
  outrootfile->cd();
  //h->Write();
  gNpart->Write();
  gNcoll->Write();
  gtAA->Write();
  hd->Write();
  outrootfile->Close();


}
Ejemplo n.º 13
0
//------------------------------------------------------------------------
void DrawWalk()
{
  Int_t npeaks = 20;
  Int_t sigma=3.;
  Bool_t down = false;

  Int_t index[20];
  Char_t buf1[10], buf2[10];
  
  TCanvas *c1 = new TCanvas("c1", "c1",0,48,1280,951);
  gStyle->SetOptStat(0);
  c1->Divide(4,3);
  
  for (Int_t i=0; i<12; i++)
    {
      c1->cd(i+1);
      sprintf(buf1,"T0_C_%i_CFD",i+1);
      sprintf(buf2,"CFDvsQTC%i",i+1);
      cout<<buf1<<" "<<buf2<<endl;
      TH2F *qtc_cfd = (TH2F*) gFile->Get(buf2);
      TH1F *cfd = (TH1F*) gFile->Get(buf1);
      //       cfd->Draw();
      TSpectrum *s = new TSpectrum(2*npeaks,1);
      Int_t nfound = s->Search(cfd,sigma," ",0.05);
      cout<<"Found "<<nfound<<" peaks sigma "<<sigma<<endl;;
      if(nfound!=0){
	Float_t *xpeak = s->GetPositionX();
  	TMath::Sort(nfound, xpeak, index,down);
  	Float_t xp = xpeak[index[0]];
	Int_t xbin = cfd->GetXaxis()->FindBin(xp);
	Float_t yp = cfd->GetBinContent(xbin);
	cout<<"xbin = "<<xbin<<"\txpeak = "<<xpeak[1]<<"\typeak = "<<yp<<endl;
	Float_t hmax = xp+10*sigma;
	Float_t hmin = xp-10*sigma;
	cout<<hmin<< " "<<hmax<<endl;
	//	    cfd->GetXaxis()->SetRange(hmin,hmax);
	//	    TF1 *g1 = new TF1("g1", "gaus", hmin, hmax);
	// cfd->Fit("g1","R");
	Int_t hminbin=  qtc_cfd->GetXaxis()->GetFirst();
	Int_t hmaxbin=  qtc_cfd->GetXaxis()->GetLast();
	Int_t nbins= qtc_cfd->GetXaxis()->GetNbins();
	cout<<"  qtc_cfd "<<hminbin<<" "<<hmaxbin<<" "<<nbins<<endl;
	//  qtc_cfd->Draw();
	TProfile *pr_y = qtc_cfd->ProfileX();
	Float_t maxHr=pr_y->GetBinCenter(hmaxbin);
	
	pr_y->SetMaximum(hmax);
	pr_y->SetMinimum(hmin);
	Int_t np=nbins/20;
	Double_t *xx = new Double_t[np];
	Double_t *yy = new Double_t[np];
	Int_t ng=0;
	Double_t yg=0;
	for (Int_t ip=1; ip<nbins; ip++)
	  {
	    if(ip%20 != 0 ) {
	      if (pr_y->GetBinContent(ip) !=0)
		yg +=pr_y->GetBinContent(ip);
	      //	cout<<ng<<" "<<pr_y->GetBinContent(ip)<<" "<<yg<<endl;
	      ng++;}
	    else {
	      xx[ip/20] = Float_t (pr_y->GetBinCenter(ip));
	      yy[ip/20] = yg/ng;
	      yg=0;
	      ng=0;
	     	      cout<<ip<<" "<<ip/20<<" "<< xx[ip/20]<<" "<< yy[ip/20]<<endl;
	    }
	  }
	TH2F *hr = new TH2F("hr"," ",np,0,maxHr, np, hmin, hmax);
	hr->Draw();
	TGraph *gr = new TGraph(np,xx,yy);
	gr->SetMinimum(hmin);
	gr->SetMaximum(hmax);
	gr->SetMarkerStyle(20);
	gr->Draw("P");
	//	delete [] xx;
	//	delete [] yy;
	
	// pr_y->Rebin(10);
		   //  pr_y->Draw();
	    
      }
      
    }
  

}
Ejemplo n.º 14
0
void fakeStudyMu( TCut Cuts_ = "ptL1>0",
		  TString variable_ = "MtLeg1",
		  TString XTitle_ = "M_{T}(#mu,MET)",
		  TString Unities_ = "GeV",
		  Int_t nBins_ = 12, Float_t xMin_=0, Float_t xMax_=120,
		  Float_t magnifySgn_ = 10,
		  Float_t hltEff_ = 1.0,
		  Int_t enableHLTmatching_ = 1,
		  Int_t logy_ = 0 ) 
{   
  
  float Lumi = 24.86+159.15;

  TCanvas *c1 = new TCanvas("c1","",5,30,650,600);
  c1->SetGrid(0,0);
  c1->SetFillStyle(4000);
  c1->SetFillColor(10);
  c1->SetTicky();
  c1->SetObjectStat(0);
  c1->SetLogy(logy_);

  TLegend* leg = new TLegend(0.60,0.50,0.85,0.85,NULL,"brNDC");
  leg->SetFillStyle(0);
  leg->SetBorderSize(0);
  leg->SetFillColor(10);
  leg->SetTextSize(0.04);
  leg->SetHeader("#mu+#tau_{had}");

  THStack* aStack = new THStack("aStack",Form("CMS Preliminary 2011    #sqrt{s}=7 TeV L=%.0f pb^{-1}", Lumi ));
  TH1F* hSiml = new TH1F();
  TH1F* hSgn   = new TH1F();
  TH1F* hSgn1  = new TH1F();
  TH1F* hSgn2  = new TH1F();
  TH1F* hData  = new TH1F();
 

  // OpenNTuples
  TString fDataName                = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011_iter2/Inclusive/nTupleRun2011-Mu_Open_MuTauStream.root";
  TString fSignalNameVBF           = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011_iter2/Inclusive/nTupleVBFH115-Mu-powheg-PUS1_Open_MuTauStream.root";
  TString fSignalNameGGH           = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011_iter2/Inclusive/nTupleGGFH115-Mu-powheg-PUS1_Open_MuTauStream.root";
  TString fBackgroundNameDYTauTau  = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011_iter2/Inclusive/nTupleDYJets-Mu-50-madgraph-PUS1_Open_MuTauStream.root";
  TString fBackgroundNameDYMuMu    = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011_iter2/Inclusive/nTupleDYJets-Mu-50-madgraph-PUS1_Open_MuTauStream.root";
  TString fBackgroundNameWJets     = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011_iter2/Inclusive/nTupleWJets-Mu-madgraph-PUS1_Open_MuTauStream.root";
  TString fBackgroundNameQCD       = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011_iter2/Inclusive/nTupleQCDmu_Open_MuTauStream.root";
  TString fBackgroundNameTTbar     = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011_iter2/Inclusive/nTupleTTJets-Mu-madgraph-PUS1_Open_MuTauStream.root";
  TString fBackgroundNameSingleTop = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011_iter2/Inclusive/nTupleSingleTop-Mu_Open_MuTauStream.root";
  TString fBackgroundNameDiBoson   = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011_iter2/Inclusive/nTupleDiBoson-Mu_Open_MuTauStream.root";

  TFile *fData(0); 
  TFile *fSignalVBF(0); 
  TFile *fSignalGGH(0); 
  TFile *fBackgroundDYTauTau(0);
  TFile *fBackgroundDYMuMu(0);
  TFile *fBackgroundWJets(0);
  TFile *fBackgroundQCD(0);
  TFile *fBackgroundTTbar(0);
  TFile *fBackgroundSingleTop(0);
  TFile *fBackgroundDiBoson(0);
 
  fData               = TFile::Open( fDataName ); 
  fSignalVBF          = TFile::Open( fSignalNameVBF ); 
  fSignalGGH          = TFile::Open( fSignalNameGGH ); 
  fBackgroundDYTauTau = TFile::Open( fBackgroundNameDYTauTau ); 
  fBackgroundDYMuMu   = TFile::Open( fBackgroundNameDYMuMu ); 
  fBackgroundWJets    = TFile::Open( fBackgroundNameWJets ); 
  fBackgroundQCD      = TFile::Open( fBackgroundNameQCD ); 
  fBackgroundTTbar    = TFile::Open( fBackgroundNameTTbar );
  fBackgroundSingleTop= TFile::Open( fBackgroundNameSingleTop ); 
  fBackgroundDiBoson  = TFile::Open( fBackgroundNameDiBoson ); 

  if(!fSignalVBF || !fBackgroundDYTauTau || !fBackgroundWJets || !fBackgroundQCD || !fBackgroundTTbar || !fBackgroundSingleTop ||
     !fSignalGGH || !fBackgroundDYMuMu || !fBackgroundDiBoson || !fData){
    std::cout << "ERROR: could not open files" << std::endl;
    exit(1);
  }

  TString tree = "outTreePtOrd";

  TTree *data                = (TTree*)fData->Get(tree);
  TTree *signalVBF           = (TTree*)fSignalVBF->Get(tree);
  TTree *signalGGH           = (TTree*)fSignalGGH->Get(tree);

  TFile* dummy1 = new TFile("dummy1.root","RECREATE");
  TTree *backgroundDYTauTau  = ((TTree*)fBackgroundDYTauTau->Get(tree))->CopyTree("isTauLegMatched>0.5");
  TTree *backgroundDYMuMu    = ((TTree*)fBackgroundDYMuMu->Get(tree))->CopyTree("isTauLegMatched<0.5");
  cout <<backgroundDYTauTau->GetEntries() << " -- " << backgroundDYMuMu->GetEntries() << endl;

  TTree *backgroundWJets     = (TTree*)fBackgroundWJets->Get(tree);
  TTree *backgroundQCD       = (TTree*)fBackgroundQCD->Get(tree);
  TTree *backgroundTTbar     = (TTree*)fBackgroundTTbar->Get(tree);
  TTree *backgroundSingleTop = (TTree*)fBackgroundSingleTop->Get(tree);
  TTree *backgroundDiBoson   = (TTree*)fBackgroundDiBoson->Get(tree);
 
  // here I choose the order in the stack
  std::vector<string> samples;
  samples.push_back("ggH115");
  samples.push_back("qqH115");
  samples.push_back("DiBoson");
  samples.push_back("SingleTop");
  samples.push_back("TTbar");
  samples.push_back("Wjets");
  samples.push_back("QCD");
  samples.push_back("ZfakeTau");
  samples.push_back("Ztautau");
  samples.push_back("Data");

  // here I define the map between a sample name and its tree
  std::map<std::string,TTree*> tMap;
  tMap["Data"]=data;
  tMap["ggH115"]=signalGGH;
  tMap["qqH115"]=signalVBF;
  tMap["Ztautau"]=backgroundDYTauTau;
  tMap["ZfakeTau"]=backgroundDYMuMu;
  tMap["Wjets"]=backgroundWJets;
  tMap["QCD"]=backgroundQCD;
  tMap["TTbar"]=backgroundTTbar;
  tMap["SingleTop"]=backgroundSingleTop;
  tMap["DiBoson"]=backgroundDiBoson;

  Float_t pt1, pt2, Deta, Mjj, eta1, eta2;
  Float_t diTauSVFitPt,diTauVisPt,diTauVisEta,diTauSVFitEta,diTauVisMass,diTauSVFitMass,ptL1,ptL2,etaL1,etaL2,diTauCharge,MtLeg1,numPV,combRelIsoLeg1DBeta,combRelIsoLeg1,pZetaCutVar, MEt, ptVeto, leadTrackPt, jetsBtagHE1, jetsBtagHE2;
  Float_t sampleWeight,puWeight;

  std::map<TString,Float_t> vMap;

  for( unsigned iter=0; iter<samples.size(); iter++){

    std::map<std::string,TTree*>::iterator it = tMap.find(samples[iter]);

    TString h1Name = "h1_"+it->first;
    TH1F* h1 = new TH1F( h1Name ,Form("CMS Preliminary 2011    #sqrt{s}=7 TeV L=%.0f pb^{-1}", Lumi) , nBins_ ,xMin_ , xMax_);

    TFile* dummy = new TFile("dummy.root","RECREATE");  
    TCut Cuts = Cuts_;
    TCut hlt = enableHLTmatching_ ? "( ((HLTmatch==2 && run<=163261) || (HLTmatch==1 && run>163261)) && ((HLTmu==1 && run<=163261) || (HLTx==1 && run>163261)) )" : "( ((HLTmu==1 && run<=163261) || (HLTx==1 && run>163261)) )";

    if((it->first).find("Data")!=string::npos) Cuts = Cuts_ && hlt;
    TTree* currentTree = (TTree*)(it->second)->CopyTree(Cuts);
    Int_t counter = 0;

    currentTree->SetBranchAddress( "pt1", &pt1 );
    currentTree->SetBranchAddress( "pt2", &pt2 );
    currentTree->SetBranchAddress( "Deta",&Deta );
    currentTree->SetBranchAddress( "Mjj", &Mjj );
    currentTree->SetBranchAddress( "diTauSVFitPt",&diTauSVFitPt);
    currentTree->SetBranchAddress( "diTauSVFitEta",&diTauSVFitEta);
    currentTree->SetBranchAddress( "diTauSVFitMass",&diTauSVFitMass);
    currentTree->SetBranchAddress( "diTauVisPt",&diTauVisPt);
    currentTree->SetBranchAddress( "diTauVisEta",&diTauVisEta);
    currentTree->SetBranchAddress( "diTauVisMass",&diTauVisMass);
    currentTree->SetBranchAddress( "ptL1",  &ptL1 );
    currentTree->SetBranchAddress( "ptL2",  &ptL2 );
    currentTree->SetBranchAddress( "etaL1", &etaL1 );
    currentTree->SetBranchAddress( "etaL2", &etaL2 );
    currentTree->SetBranchAddress( "combRelIsoLeg1DBeta",&combRelIsoLeg1DBeta);
    currentTree->SetBranchAddress( "combRelIsoLeg1",&combRelIsoLeg1);
    currentTree->SetBranchAddress( "diTauCharge",&diTauCharge);
    currentTree->SetBranchAddress( "MtLeg1",&MtLeg1);
    currentTree->SetBranchAddress( "pZetaCutVar",&pZetaCutVar);
    currentTree->SetBranchAddress( "numPV",&numPV);
    currentTree->SetBranchAddress( "sampleWeight",&sampleWeight);
    currentTree->SetBranchAddress( "puWeight",&puWeight);
    currentTree->SetBranchAddress( "ptVeto",&ptVeto);
    currentTree->SetBranchAddress( "MEt",&MEt);
    currentTree->SetBranchAddress( "leadTrackPt",&leadTrackPt);
    currentTree->SetBranchAddress( "jetsBtagHE1",&jetsBtagHE1);
    currentTree->SetBranchAddress( "jetsBtagHE2",&jetsBtagHE2);

    for (Long64_t ievt=0; ievt<currentTree->GetEntries();ievt++) {

      currentTree->GetEntry(ievt);

      if (ievt%10000 == 0){
	std::cout << (it->first) << " ---> processing event: " << ievt << " ..." <<std::endl;
      }

     
      vMap["diTauSVFitPt"]  = diTauSVFitPt;
      vMap["diTauSVFitEta"] = diTauSVFitEta;
      vMap["diTauSVFitMass"]= diTauSVFitMass;
      vMap["diTauVisPt"]    = diTauVisPt;
      vMap["diTauVisEta"]   = diTauVisEta;
      vMap["diTauVisMass"]  = diTauVisMass;
      vMap["ptL1"]  = ptL1;
      vMap["ptL2"]  = ptL2;
      vMap["etaL1"] = etaL1;
      vMap["etaL2"] = etaL2;
      vMap["diTauCharge"]= Float_t(diTauCharge);
      vMap["MtLeg1"]= MtLeg1;
      vMap["pZetaCutVar"] = pZetaCutVar;
      vMap["numPV"]= numPV;
      vMap["combRelIsoLeg1"]= combRelIsoLeg1;
      vMap["combRelIsoLeg1DBeta"]= combRelIsoLeg1DBeta;
      vMap["sampleWeight"]= sampleWeight;
      vMap["puWeight"]= puWeight;
      vMap["puWeight"]= puWeight;
      vMap["jetsBtagHE1"]= jetsBtagHE1;
      vMap["jetsBtagHE2"]= jetsBtagHE2;
      vMap["leadTrackPt"]= leadTrackPt;

      vMap["pt1"]= pt1;
      vMap["pt2"]= pt2;
      vMap["Deta"]= Deta;
      vMap["Mjj"]= Mjj;
      vMap["ptVeto"]= ptVeto;

      if((it->first).find("Data")==string::npos) sampleWeight*=(Lumi/1000*hltEff_*puWeight);

      counter++;
      h1->Fill( vMap[variable_], sampleWeight);
    
    }// end loop


    if( (it->first).find("ZfakeTau")!=string::npos ) {
      h1->SetFillColor(7);
      leg->AddEntry(h1,"Z+jets, fake-#tau","F");
    }
    if( (it->first).find("Ztautau")!=string::npos ) {
      h1->SetFillColor(kRed);
      leg->AddEntry(h1,"Z+jets, genuine-#tau","F");
    }
    if( (it->first).find("TTbar")!=string::npos ) {
      h1->SetFillColor(kBlue);
      leg->AddEntry(h1,"t#bar{t}+jets","F");
    }
    if( (it->first).find("SingleTop")!=string::npos ) {
      h1->SetFillColor(29);
      leg->AddEntry(h1,"single-t","F");
    }
    if( (it->first).find("Wjets")!=string::npos ) {
      h1->SetFillColor(kGreen);
      leg->AddEntry(h1,"W+jets","F");
    }
    if( (it->first).find("DiBoson")!=string::npos ) {
      h1->SetFillColor(38);
      leg->AddEntry(h1,"Di-Boson","F");
    }
    if( (it->first).find("QCD")!=string::npos ) {
      h1->SetFillColor(42);
      leg->AddEntry(h1,"QCD-multijets","F");
    }
    if((it->first).find("qqH115")!=string::npos){
      hSgn1 = (TH1F*)h1->Clone("hSgn1");
      hSgn1->Scale(magnifySgn_);
      hSgn1->SetLineWidth(2);
      h1->SetFillColor(kBlack);
      h1->SetFillStyle(3004);
      h1->SetLineColor(kBlack);
      leg->AddEntry(h1,Form("VBF H(115) X %.0f",magnifySgn_),"F");
    }
    if((it->first).find("ggH115")!=string::npos){
      hSgn2 = (TH1F*)h1->Clone("hSgn2");
      hSgn2->Scale(magnifySgn_);
      hSgn2->SetLineWidth(2);
      h1->SetFillColor(kBlack);
      h1->SetFillStyle(3005);
      h1->SetLineColor(kBlack);
      leg->AddEntry(h1,Form("GGF H(115) X %.0f",magnifySgn_),"F");
    }
    if((it->first).find("Data")!=string::npos){
      hData = (TH1F*)h1->Clone("hData");
      hData->Sumw2();
      hData->SetMarkerStyle(20);
      hData->SetMarkerSize(1.2);
      hData->SetMarkerColor(kBlack);
      hData->SetLineColor(kBlack);
      hData->SetXTitle(XTitle_+" ("+Unities_+")");
      hData->SetYTitle(Form(" Events/(%.0f %s)", hData->GetBinWidth(1), Unities_.Data() ) );
      hData->SetTitleSize(0.04,"X");
      hData->SetTitleSize(0.05,"Y");
      hData->SetTitleOffset(0.95,"Y");
      leg->AddEntry(hData,"DATA","P");
    }

    if(iter==0) hSiml=(TH1F*)h1->Clone("hSiml");
    else if((it->first).find("Data")==string::npos) hSiml->Add(h1);

    if((it->first).find("Data")==string::npos) aStack->Add(h1);

    if(VERBOSE) cout<<(it->first) << " ==> " 
		   << h1->Integral() << " +/- " 
		   << TMath::Sqrt(h1->GetEntries())*(h1->Integral()/h1->GetEntries())
		   << endl;
  }

  // all signal summed together:
  hSgn = (TH1F*)hSgn1->Clone("hSgn");
  hSgn->Add(hSgn1,hSgn2,1,1);

  if(VERBOSE) cout<< "S/sqrt(B) ==> " 
		  << hSgn->Integral()/ TMath::Sqrt(hSiml->Integral()) << " +/- " 
		  << (1./2)*TMath::Sqrt(hSiml->GetEntries())*(hSiml->GetSumOfWeights())/hSiml->Integral()*( hSgn->Integral()/ TMath::Sqrt(hSiml->Integral())  )
		  << endl;

  hData->SetXTitle(XTitle_+" ("+Unities_+")");
  hData->SetYTitle(Form(" Events/(%.1f %s)", hData->GetBinWidth(1), Unities_.Data() ) );
  hData->SetTitleSize(0.04,"X");
  hData->SetTitleSize(0.05,"Y");
  hData->SetTitleOffset(0.95,"Y");

  hData->Draw("P");
  aStack->Draw("HISTSAME");
  hData->Draw("PSAME");
  //hSgn1->Draw("HISTSAME");
  //hSgn2->Draw("HISTSAME");

  TH1F* hStack = (TH1F*)aStack->GetHistogram();
  hStack->SetXTitle(XTitle_+" ("+Unities_+")");
  hStack->SetYTitle(Form(" Events/(%.0f %s)", hStack->GetBinWidth(1), Unities_.Data() ) );
  hStack->SetTitleSize(0.04,"X");
  hStack->SetTitleSize(0.05,"Y");
  hStack->SetTitleOffset(0.95,"Y");
  //aStack->GetYaxis()->SetRangeUser(0.0,std::max(hData->GetMaximum(),hStack->GetMaximum())*1.1);
  leg->Draw();


}
Ejemplo n.º 15
0
int main(int argc , char* argv[]){
		
		//Program Options

	po::options_description desc("Allowed Options");
	desc.add_options()
		 ("help,h", "Produce this help message")
		 ("startwl,s",po::value<double>(),"Set the start Wavelength for the Analysis")
		 ("stopwl,p",po::value<double>(),"Set the stop Wavelength for the Analysis")
		 ("non-interactive,n","Runs the program in Noninteractive mode. It quits when it's finished")
		 ("version,v","Prints Version")
	;
		 
	po::variables_map vm;
		 po::store(po::parse_command_line(argc,argv,desc),vm);
		 po::notify(vm);
	if (vm.count("help")) {
		std::cout << desc<< std::endl;
		return 3;
	}
	if (vm.count("version")) {
		std::cout << "VCSEL Laser Analysis Version " << _VERSION << std::endl;
		std::cout << "Using ROOT version " << _ROOT_VERSION << " and Boost version " << _BOOST_VERSION << std::endl;
		return 0;
	}
	
	if (argc < 4) {
		std::cout << desc;
		return 2;
	}	
	double startwl, stopwl;
	startwl = 842.;
	stopwl = 860.;
	bool run = true;
	if (vm.count("startwl")) {
		startwl = vm["startwl"].as<double>();
		NUM_ARGS +=2;
	}
	if (vm.count("stopwl")) {
		double tmp =  vm["stopwl"].as<double>();
		stopwl =tmp;
		NUM_ARGS +=2;
	}
	if (vm.count("non-interactive")) {
		run = false;
		NUM_ARGS++;
	}
	
	
	//checking filetypes must be txt, csv or CSV
	if (!check_extensions(argc, argv)) {
		return 1;
	}
	std::cout <<"startwl: "<< startwl << '\t' << "stopwl: " << stopwl << std::endl;
	
	Double_t max = -210;
	Double_t maxwl = 0;
	int _argc = argc;
	TApplication *t = new TApplication("big",&_argc,argv);
	std::cout << "Running with boost and ROOT" <<std::endl;
	std::vector<double> _x,_y;
	Double_t x[LINES], y[LINES], _inta[LINES], _intb[LINES]; 
	
	Double_t *cmp_int = new Double_t[argc];
	Double_t *argc_ary = new Double_t[argc];
	Double_t *cmp_int_root = new Double_t[argc];
	Double_t *asymmety_ary = new Double_t[argc];
	Double_t *width_ary = new Double_t [argc];
	

	
	TGraph2D *gr = new TGraph2D(LINES*(argc-1));
		//Setting up canvas for plot of all sectrums (is it called spectrums? ;) )
	TCanvas *c1 = new TCanvas("All Plots","All Plots",10,10,3000,1500);
	TH1F *integral_hist = new TH1F("Asymmerty", "Asymmetry", 100,0, 100);
	

	if(!(argc % ROWS)){
		c1->Divide(argc/ROWS,ROWS);
		
	}else{
		c1->Divide(argc/ROWS+(argc %ROWS -1),ROWS);
	}
	
	for (Int_t i = NUM_ARGS +1; i < argc ; i++){
		try{ 
			
			max = -211;
			maxwl = 0;
			argc_ary[i] = i-NUM_ARGS;
			
			std::ifstream in;
			in.seekg(0, std::ios::beg);
				// voodoo keep this;
			char **arg1 = t->Argv() ;
			std::string tmp = arg1[i];
			in.open(tmp.c_str());
			
			std::cout<< "file: " << tmp << std::endl;
			std::string line;
			int cline = 0;
			std::vector<double> a,b, inta, intb;
			
				//reading file
			
			while(getline(in,line)){
				read_file(line, a, b, inta, intb);
				cline++;
			}
			
			if (cline < LINES){
				for(int i = cline ; i < LINES ; i++){
					a.push_back(100);
					b.push_back(-70);
				}
			}
			std::cout<< "\n\ncline: " << cline<< std::endl; 
			cline =(cline > LINES) ? LINES :cline;
			
			for(Int_t j = 0; j <LINES ;j++){
				x[j] = a[j];
				y[j] = b[j];
				_inta[j] = inta[j];
				_intb[j]= (intb[j] < 0)? 0:intb[j];
			}
			
			
			
			double s_integral = 0;
			
			std::cout <<"size of int " <<  intb.size()<< std::endl;
			for (size_t it = 0; it < intb.size() - 1; it++){
				double y_val = (intb[it]+intb[it+1])/2;
				assert (y_val >= 0);
				double area = 0.002*y_val;
				if(area > 0 )
					s_integral += area;
			}
			
			
			
			
			std::cout << "Simpson integral: " <<s_integral <<std::endl;
			integral_hist->Fill(s_integral);
			cmp_int[i] = s_integral;
			Int_t lines = (Int_t)intb.size();
			TGraph *r_integral = new TGraph(lines, _inta, _intb);
			
			std::cout << "ROOT integral: " << r_integral->Integral() << std::endl;
			cmp_int_root[i] = r_integral->Integral();
			
				//expanding
				//expand(y, THRS_EXPAND, RATIO_EXPAND, LINES);
			
			
				//Filling TGraph2D
			
			for(Int_t j = 0; j <LINES ; j++){
				if (y[j] > max){
					max = y[j];
					maxwl = x[j];
				}
				gr->SetPoint(j+i*LINES, x[j],i,y[j]);
			}
			
			
			in.seekg(0, std::ios::beg);
			in.close();
			
				//Plotting each spectrum
			
			TGraph *_gr = new TGraph(LINES,x,y);
			_gr->GetHistogram()->GetXaxis()->SetTitle("#lambda in nm");
			_gr->GetHistogram()->GetYaxis()->SetTitle("Intensity in dB");
			c1->cd(i-NUM_ARGS);
			_gr->Draw("AP");
			_gr->GetYaxis()->SetRangeUser(-80.,-10.);
			_gr->GetXaxis()->SetRangeUser(startwl,stopwl);
			_gr->SetTitle(tmp.c_str());
			c1->Update();
			
			
				//Calculating asymmetry
			std::cout << "maximum: " << max << std::endl;
			double leftlimit, rightlimit = 1;
			leftlimit = findlower(x,y, max);
			rightlimit = findupper(x,y, max);
			if (leftlimit != 1 && rightlimit != 1){
				width_ary[i] = (leftlimit +rightlimit)/2;
			}else{
				width_ary[i] = maxwl;
			}
			double calced_asy = (maxwl-leftlimit)/(rightlimit-maxwl);
			asymmety_ary[i-NUM_ARGS] = calced_asy;
			
			std::cout << "Asymmetry: " << calced_asy << std::endl;
			
		}catch(std::exception e){
			std::cout << e.what()<< std::endl;
		}
	}
	
	
		//Setting style for 3D Plot
	TCanvas *d = new TCanvas("big","big",10,10,1500,800);
	d->Divide(2,2);
	d->cd(1);
	TGraph *the_ints = new TGraph(argc-1,argc_ary,cmp_int);
	the_ints->Draw("A*");
	the_ints->SetTitle("My Ints");
	d->Update();
	d->cd(2);
	std::cout << "Fitting\n\n";
	integral_hist->SetFillColor(kBlue);
		//settig everything to print fitresuts
	gStyle->SetOptStat(1211);
	gStyle->SetOptFit(1111);
	integral_hist->Draw();
	integral_hist->Fit("gaus","W","" ,10,100);
		//integral_hist->Draw("SAME");
	d->Update();
	d->cd(3);
	
	TGraph *roots_int = new TGraph(argc-1, argc_ary, cmp_int_root);
	roots_int->SetTitle("ROOTS Int");
	roots_int->Draw("A*");
	d->Update();
	d->cd(4);
	d->Update();
		//gROOT->SetStyle("modern");
	gr->SetTitle("big");
	gr->GetHistogram("empty")->GetXaxis()->SetTitle("#lambda in nm");
	gr->GetHistogram("empty")->GetXaxis()->SetLimits(startwl,stopwl);
	gr->GetHistogram("empty")->GetYaxis()->SetTitle("Messurement"); 
	gr->GetHistogram("empty")->GetZaxis()->SetTitle("Intensity in dB");
	gr->GetHistogram("empty")->GetXaxis()->SetTitleOffset(1.5);
	gr->GetHistogram("empty")->GetYaxis()->SetTitleOffset(1.5);
	gr->GetHistogram("empty")->GetZaxis()->SetTitleOffset(1.5);
	gr->GetHistogram("empty")->GetZaxis()->SetRangeUser(-70.,max);
	gr->GetHistogram("empty")->GetXaxis()->CenterTitle();
	gr->GetHistogram("empty")->GetYaxis()->CenterTitle();
	gr->GetHistogram("empty")->GetZaxis()->CenterTitle();
	gr->Draw("PCOL");
	d->SetFillColor(16);
	
	
#ifdef RENDER
		//Render 3D animation
	const Int_t kUPDATE = 1;
	TSlider *slider = 0;
	
	for (Int_t i = 1; i <= 125; i++){
		TView3D *v = new TView3D();
		v->RotateView(5+i,45+i,d);
			//d->Update();
		
		if(i && (i%kUPDATE)== 0){
			if (i == kUPDATE){
				gr->Draw("PCOL");
				d->Update();
				slider = new TSlider("slider","test",850,-70,856,max);
			}
			if (slider) slider->SetRange(0,Float_t(i)/10000.);
			d->Modified();
			d->Update();
			d->Print("3d.gif+");
		} 
	}
	d->Update();
	d->Print("3d.gif++");
#endif
	
	
		//Saving image
	TImage *img = TImage::Create();
	boost::filesystem::path p(t->Argv(3));
	std::string file = p.parent_path().string();
	file += "_big.png";
	img->FromPad(d);
	img->WriteImage(file.c_str());
		//cleaning
	
	TCanvas *e = new TCanvas("Asymmetry","Asymmetry",10,10,1500,800);
	e->Divide(2,1);
	TGraph *asy_plot = new TGraph(argc-1, argc_ary, asymmety_ary);
	e->cd(1);
	asy_plot->SetTitle("Asymmetry");
	asy_plot->GetHistogram()->GetXaxis()->SetTitle("# Meassurement");
	asy_plot->GetHistogram()->GetYaxis()->SetTitle("Asymmetry");
	asy_plot->GetHistogram()->GetXaxis()->SetRange(1, argc);
	asy_plot->Draw("A*");
	e->Update();
	e->cd(2);
	
	
	TGraph *center_plot = new TGraph(argc-1 , argc_ary, width_ary);
	center_plot->GetHistogram()->GetXaxis()->SetTitle("# Meassurement");
	center_plot->GetHistogram()->GetYaxis()->SetTitle("Center in nm");
	center_plot->GetHistogram()->GetYaxis()->SetRangeUser(startwl, stopwl);
	center_plot->SetTitle("Center");
	center_plot->Draw("A*");
	e->Update();
		//Saving Images
	TImage *secimg = TImage::Create();
	boost::filesystem::path p2(t->Argv(3));
	file = p2.parent_path().string();
	file += "_asy_cent.png";
	secimg->FromPad(e);
	secimg->WriteImage(file.c_str());
	
	TImage *thrdimg = TImage::Create();
	boost::filesystem::path p3(t->Argv(3));
	file = p3.parent_path().string();
	file += "_allplots.png";
	thrdimg->FromPad(c1);
	thrdimg->WriteImage(file.c_str());
	
		//detecting Gradients
	gradient(asymmety_ary, width_ary,cmp_int, argc-1,c1);
	std::cout << "\n\n\nDone !!\nYou can quit now using CTRL+C \n" ;
	
	if (run == true){
		t->Run();
	}
	std::cout << "With \n" ;
	
	delete[] cmp_int;
	delete[] argc_ary; 
	delete[] cmp_int_root;
	delete[] asymmety_ary;
	delete[] width_ary;
	return 0;
}
Ejemplo n.º 16
0
// input: - Input file (result from TMVA)
//        - use of TMVA plotting TStyle
void mvas( TString fin = "TMVA.root", HistType htype = MVAType, Bool_t useTMVAStyle = kTRUE, Int_t logy = 0)
{
   // set style and remove existing canvas'
   TMVAGlob::Initialize( useTMVAStyle );

   // switches
   const Bool_t Save_Images = kTRUE;

   // checks if file with name "fin" is already open, and if not opens one
   TFile* file = TMVAGlob::OpenFile( fin );  

   // define Canvas layout here!
   Int_t xPad = 1; // no of plots in x
   Int_t yPad = 1; // no of plots in y
   Int_t noPad = xPad * yPad ; 
   const Int_t width = 600;   // size of canvas

   // this defines how many canvases we need
   TCanvas *c = 0;

   // counter variables
   Int_t countCanvas = 0;

   // search for the right histograms in full list of keys
   TIter next(file->GetListOfKeys());
   TKey *key(0);   
   while ((key = (TKey*)next())) {

      if (!TString(key->GetName()).BeginsWith("Method_")) continue;
      if (!gROOT->GetClass(key->GetClassName())->InheritsFrom("TDirectory")) continue;

      TString methodName;
      TMVAGlob::GetMethodName(methodName,key);

      TDirectory* mDir = (TDirectory*)key->ReadObj();

      TIter keyIt(mDir->GetListOfKeys());
      TKey *titkey;
      while ((titkey = (TKey*)keyIt())) {

         if (!gROOT->GetClass(titkey->GetClassName())->InheritsFrom("TDirectory")) continue;

         TDirectory *titDir = (TDirectory *)titkey->ReadObj();
         TString methodTitle;
         TMVAGlob::GetMethodTitle(methodTitle,titDir);

         cout << "--- Found directory for method: " << methodName << "::" << methodTitle << flush;
         TString hname = "MVA_" + methodTitle;
         if      (htype == ProbaType  ) hname += "_Proba";
         else if (htype == RarityType ) hname += "_Rarity";
         TH1* sig = dynamic_cast<TH1*>(titDir->Get( hname + "_S" ));
         TH1* bgd = dynamic_cast<TH1*>(titDir->Get( hname + "_B" ));

         if (sig==0 || bgd==0) {
            if     (htype == MVAType)     
               cout << ":\t mva distribution not available (this is normal for Cut classifier)" << endl;
            else if(htype == ProbaType)   
               cout << ":\t probability distribution not available" << endl;
            else if(htype == RarityType)  
               cout << ":\t rarity distribution not available" << endl;
            else if(htype == CompareType) 
               cout << ":\t overtraining check not available" << endl;
            else cout << endl;
            continue;
         }

         cout << " containing " << hname << "_S/_B" << endl;
         // chop off useless stuff
         sig->SetTitle( Form("TMVA response for classifier: %s", methodTitle.Data()) );
         if      (htype == ProbaType) 
            sig->SetTitle( Form("TMVA probability for classifier: %s", methodTitle.Data()) );
         else if (htype == RarityType) 
            sig->SetTitle( Form("TMVA Rarity for classifier: %s", methodTitle.Data()) );
         else if (htype == CompareType) 
            sig->SetTitle( Form("TMVA overtraining check for classifier: %s", methodTitle.Data()) );
         
         // create new canvas
         TString ctitle = ((htype == MVAType) ? 
                           Form("TMVA response %s",methodTitle.Data()) : 
                           (htype == ProbaType) ? 
                           Form("TMVA probability %s",methodTitle.Data()) :
                           (htype == CompareType) ? 
                           Form("TMVA comparison %s",methodTitle.Data()) :
                           Form("TMVA Rarity %s",methodTitle.Data()));
         
         c = new TCanvas( Form("canvas%d", countCanvas+1), ctitle, 
                          countCanvas*50+200, countCanvas*20, width, (Int_t)width*0.78 ); 
    
         // set the histogram style
         TMVAGlob::SetSignalAndBackgroundStyle( sig, bgd );
         
         // normalise both signal and background
         TMVAGlob::NormalizeHists( sig, bgd );
         
         // frame limits (choose judicuous x range)
         Float_t nrms = 10;
         cout << "--- Mean and RMS (S): " << sig->GetMean() << ", " << sig->GetRMS() << endl;
         cout << "--- Mean and RMS (B): " << bgd->GetMean() << ", " << bgd->GetRMS() << endl;
         //Float_t xmin = TMath::Max( TMath::Min(sig->GetMean() - nrms*sig->GetRMS(), 
         //                                      bgd->GetMean() - nrms*bgd->GetRMS() ),
         //                           sig->GetXaxis()->GetXmin() );
         //Float_t xmax = TMath::Min( TMath::Max(sig->GetMean() + nrms*sig->GetRMS(), 
         //                                      bgd->GetMean() + nrms*bgd->GetRMS() ),
         //                           sig->GetXaxis()->GetXmax() );
	 Float_t xmin = -1;
	 Float_t xmax = 1;
	 Float_t ymin = 0;
	 Float_t ymax = 9;
         Float_t maxMult = (htype == CompareType) ? 1.3 : 1.2;
         //Float_t ymax = TMath::Max( sig->GetMaximum(), bgd->GetMaximum() )*maxMult;
   
         // build a frame
         Int_t nb = 500;
         TString hFrameName(TString("frame") + methodTitle);
         TObject *o = gROOT->FindObject(hFrameName);
         if(o) delete o;
         TH2F* frame = new TH2F( hFrameName, sig->GetTitle(), 
                                 nb, xmin, xmax, nb, ymin, ymax );
         frame->GetXaxis()->SetTitle( methodTitle + ((htype == MVAType || htype == CompareType) ? " response" : "") );
		 if      (htype == ProbaType  ) frame->GetXaxis()->SetTitle( "Signal probability" );
         else if (htype == RarityType ) frame->GetXaxis()->SetTitle( "Signal rarity" );
         frame->GetYaxis()->SetTitle("(1/N) dN^{ }/^{ }dx");
         TMVAGlob::SetFrameStyle( frame );
         gPad->SetLogy(logy);
         // eventually: draw the frame
         frame->Draw();  
    
         c->GetPad(0)->SetLeftMargin( 0.105 );
         frame->GetYaxis()->SetTitleOffset( 1.2 );

         // Draw legend               
         TLegend *legend= new TLegend( c->GetLeftMargin(), 1 - c->GetTopMargin() - 0.12, 
                                       c->GetLeftMargin() + (htype == CompareType ? 0.40 : 0.3), 1 - c->GetTopMargin() );
         legend->SetFillStyle( 1 );
         legend->AddEntry(sig,TString("Signal")     + ((htype == CompareType) ? " (test sample)" : ""), "F");
         legend->AddEntry(bgd,TString("Background") + ((htype == CompareType) ? " (test sample)" : ""), "F");
         legend->SetBorderSize(1);
         legend->SetMargin( (htype == CompareType ? 0.2 : 0.3) );
         legend->Draw("same");

         // overlay signal and background histograms
         sig->Draw("samehist");
         bgd->Draw("samehist");
   
         if (htype == CompareType) {
            // if overtraining check, load additional histograms
            TH1* sigOv = 0;
            TH1* bgdOv = 0;

            TString ovname = hname += "_Train";
            sigOv = dynamic_cast<TH1*>(titDir->Get( ovname + "_S" ));
            bgdOv = dynamic_cast<TH1*>(titDir->Get( ovname + "_B" ));
      
            if (sigOv == 0 || bgdOv == 0) {
               cout << "+++ Problem in \"mvas.C\": overtraining check histograms do not exist" << endl;
            }
            else {
               cout << "--- Found comparison histograms for overtraining check" << endl;

               TLegend *legend2= new TLegend( 1 - c->GetRightMargin() - 0.42, 1 - c->GetTopMargin() - 0.12,
                                              1 - c->GetRightMargin(), 1 - c->GetTopMargin() );
               legend2->SetFillStyle( 1 );
               legend2->SetBorderSize(1);
               legend2->AddEntry(sigOv,"Signal (training sample)","P");
               legend2->AddEntry(bgdOv,"Background (training sample)","P");
               legend2->SetMargin( 0.1 );
               legend2->Draw("same");
            }
            // normalise both signal and background
            TMVAGlob::NormalizeHists( sigOv, bgdOv );

            Int_t col = sig->GetLineColor();
            sigOv->SetMarkerColor( col );
            sigOv->SetMarkerSize( 0.7 );
            sigOv->SetMarkerStyle( 20 );
            sigOv->SetLineWidth( 1 );
            sigOv->SetLineColor( col );
            sigOv->Draw("e1same");
      
            col = bgd->GetLineColor();
            bgdOv->SetMarkerColor( col );
            bgdOv->SetMarkerSize( 0.7 );
            bgdOv->SetMarkerStyle( 20 );
            bgdOv->SetLineWidth( 1 );
            bgdOv->SetLineColor( col );
            bgdOv->Draw("e1same");

            ymax = TMath::Max( ymax, Float_t(TMath::Max( sigOv->GetMaximum(), bgdOv->GetMaximum() )*maxMult) );
            // ymax = std::max( ymax, std::max( sigOv->GetMaximum(), bgdOv->GetMaximum() )*maxMult );
            frame->GetYaxis()->SetLimits( 0, ymax );
      
            // for better visibility, plot thinner lines
            sig->SetLineWidth( 1 );
            bgd->SetLineWidth( 1 );

            // perform K-S test
            cout << "--- Perform Kolmogorov-Smirnov tests" << endl;
            Double_t kolS = sig->KolmogorovTest( sigOv );
            Double_t kolB = bgd->KolmogorovTest( bgdOv );
            cout << "--- Goodness of signal (background) consistency: " << kolS << " (" << kolB << ")" << endl;

            TString probatext = Form( "Kolmogorov-Smirnov test: signal (background) probability = %5.3g (%5.3g)", kolS, kolB );
            TText* tt = new TText( 0.12, 0.74, probatext );
            tt->SetNDC(); tt->SetTextSize( 0.032 ); tt->AppendPad(); 
         }

         // redraw axes
         frame->Draw("sameaxis");

         // text for overflows
         Int_t    nbin = sig->GetNbinsX();
         Double_t dxu  = sig->GetBinWidth(0);
         Double_t dxo  = sig->GetBinWidth(nbin+1);
         TString uoflow = Form( "U/O-flow (S,B): (%.1f, %.1f)%% / (%.1f, %.1f)%%", 
                                sig->GetBinContent(0)*dxu*100, bgd->GetBinContent(0)*dxu*100,
                                sig->GetBinContent(nbin+1)*dxo*100, bgd->GetBinContent(nbin+1)*dxo*100 );
         TText* t = new TText( 0.975, 0.115, uoflow );
         t->SetNDC();
         t->SetTextSize( 0.030 );
         t->SetTextAngle( 90 );
         t->AppendPad();    
   
         // update canvas
         c->Update();

         // save canvas to file

         TMVAGlob::plot_logo(1.058);
         if (Save_Images) {
            if      (htype == MVAType)     TMVAGlob::imgconv( c, Form("plots/mva_%s",     methodTitle.Data()) );
            else if (htype == ProbaType)   TMVAGlob::imgconv( c, Form("plots/proba_%s",   methodTitle.Data()) ); 
            else if (htype == CompareType) TMVAGlob::imgconv( c, Form("plots/overtrain_%s", methodTitle.Data()) ); 
            else                           TMVAGlob::imgconv( c, Form("plots/rarity_%s",  methodTitle.Data()) ); 
         }
         countCanvas++;
         
      }
      cout << "";
   }
}
Ejemplo n.º 17
0
void readTrigger()
{
  TLorentzVector eplus[50], eminus[50];
  TLorentzVector momentum,  momentum_pair;
  TVector3 mom;
  Float_t px, py, pz;
  Int_t pdg;
  Int_t nplus=0, nminus=0, njpsi=0; 

  TH1F *hEl = new TH1F("hEl","number of electrons", 10,0,10);
  TH1F *hPtel = new TH1F("hPtel"," dN/dPt ",100,0,4);
  TH1F *hPel = new TH1F("hPel"," dN/dP ",100,0,30);
   
 
  // Load basic libraries


  gROOT->LoadMacro("$VMCWORKDIR/gconfig/basiclibs.C");
  basiclibs();
  gSystem->Load("libPhysics");
  
  gSystem->Load("libGeoBase");
  gSystem->Load("libParBase");
  gSystem->Load("libBase");
  gSystem->Load("libCbmBase");
  gSystem->Load("libCbmData");
  gSystem->Load("libJpsi.so");

  Char_t fileName[100];
  Int_t fNevents = 0;
  Int_t fElectronEvents=0; 
  for (Int_t ifile=0; ifile<1; ifile++)
    {
      TFile *f1 = new TFile(Form("jpsitrigger.25gev.pure.0000.root",ifile));
      TTree* t1 =(TTree*) f1->Get("cbmsim");
      TFolder *fd1 =(TFolder*)  f1->Get("cbmout");

      TClonesArray* fJpsi = (TClonesArray*)fd1->FindObjectAny("CbmJpsiTriggerElectron");
      t1->SetBranchAddress("CbmJpsiTriggerElectron",&fJpsi);
      
      
      Int_t nevent = t1->GetEntries();
      cout<<nevent<<endl;
      nplus=0; nminus=0;
      for(Int_t i=0; i<nevent; i++)
	{
	  nplus = 0;  
	  nminus = 0;
	  fNevents++;
	  t1->GetEntry(i);
	  Int_t nel = fJpsi->GetEntries();
	  for ( Int_t iel=0; iel<nel; iel++)
	    { 
	      CbmJpsiTriggerElectron *jel = (CbmJpsiTriggerElectron*)fJpsi->At(iel);
	      mom = jel->GetMomentum();
	      hPel->Fill(mom.Mag());
	      hPtel->Fill(mom.Pt());
	      if (mom.Pt() < 1.2) continue;
	      momentum.SetVectM(mom,0.000511);
	      pdg = jel -> GetPdg();
	      Double_t ann = jel -> GetAnn();
	      Double_t like = jel -> GetLike();
	      Double_t wkn = jel -> GetWkn();
	      Double_t ran = gRandom->Rndm();
	        if(ann > 0.8 ) 
		{
		  eplus[nplus]=momentum; 
		  nplus++;
		  eplus[nplus].SetXYZT(0,0,0,0);

		}	
	    }
	  hEl->Fill(nplus);
	
	  if ( nplus>1 )   fElectronEvents++;  
    } // event loop
 
      f1->Close();
    }

  cout<< " ElectronEvents "<< fElectronEvents<<endl;
 TFile *fmass = new TFile("jpsiTrigger.hist.root","RECREATE");
 
  hEl->Scale(1./Float_t (fNevents));
  hEl->Write();
  hPel->Scale(1./Float_t (fNevents ));
  hPel->Write();
  hPtel->Scale(1./Float_t (fNevents));
  hPtel->Write();
}
Ejemplo n.º 18
0
// Commands executed in a GLOBAL scope, e.g. created hitograms aren't erased...
void plot_HF(TString  inputfile="simevent_HF.root",
	     TString outputfile="HF_histo.root",
	     Int_t drawmode = 2,
             TString    reffile="../data/HF_ref.root")
{
  // Option to no-action(0)/draw(1)/save(2) (default = 0) histograms in gif.
  //int doDraw = 0;
   int doDraw = drawmode;

  char * treename = "Events";        //The Title of Tree.
  
  delete gROOT->GetListOfFiles()->FindObject(inputfile);

  TFile * myf  = new TFile(inputfile);
  
  TTree * tree = dynamic_cast<TTree*>(myf->Get("Events"));
  assert(tree != 0);

  TBranch * branchLayer = tree->GetBranch("PHcalValidInfoLayer_g4SimHits_HcalInfoLayer_CaloTest.obj");
  assert(branchLayer != 0);

  TBranch * branchNxN = tree->GetBranch("PHcalValidInfoNxN_g4SimHits_HcalInfoNxN_CaloTest.obj");
  assert(branchNxN != 0);

  TBranch * branchJets = tree->GetBranch( "PHcalValidInfoJets_g4SimHits_HcalInfoJets_CaloTest.obj");  assert(branchJets != 0);

  // Just number of entries (same for all branches)
  int  nent = branchLayer->GetEntries();
  cout << "Entries branchLayer : " << nent << endl;
  nent = branchJets->GetEntries();
  cout << "Entries branchJets  : " << nent << endl;
  nent = branchNxN->GetEntries();
  cout << "Entries branchNxN   : " << nent << endl;

  // Variables from branches
  PHcalValidInfoJets infoJets;
  branchJets->SetAddress( &infoJets); 
  PHcalValidInfoLayer infoLayer;
  branchLayer->SetAddress( &infoLayer); 
  PHcalValidInfoNxN infoNxN;
  branchNxN->SetAddress( &infoNxN); 
  
  //***************************************************************************
  // Histo titles-labels

  const int Nhist1     = 20, Nhist2 = 1;  // N simple and N combined histos
  const int Nhist1spec =  5;              // N special out of Nsimple total 

  TH1F *h;                              // just a pointer
  TH1F *h1[Nhist1];
  TH2F *h2g;                    // +  eta-phi grid -related for all depthes
  
  char *label1[Nhist1];
  char *label2g;
  

  // simple histos  
  label1[0]  = &"rJetHits.gif";
  label1[1]  = &"tJetHits.gif";
  label1[2]  = &"eJetHits.gif";
  label1[3]  = &"ecalJet.gif";
  label1[4]  = &"hcalJet.gif";
  label1[5]  = &"etotJet.gif";
  label1[6]  = &"jetE.gif";
  label1[7]  = &"jetEta.gif";
  label1[8]  = &"jetPhi.gif";
  label1[9]  = &"etaHits.gif";          
  label1[10] = &"phiHits.gif";
  label1[11] = &"eHits.gif";
  label1[12] = &"tHits.gif";
  label1[13] = &"eEcalHF.gif";
  label1[14] = &"eHcalHF.gif";

  // special
  label1[15] = &"tHits_60ns.gif";   
  label1[16] = &"tHits_eweighted.gif"; 
  label1[17] = &"nHits_HF.gif";
  label1[18] = &"elongHF.gif";
  label1[19] = &"eshortHF.gif";

  label2g    = &"Eta-phi_grid_all_depths.gif";


  //***************************************************************************
  //...Book histograms 

  for (Int_t i = 0; i < Nhist1-Nhist1spec; i++) {
    char hname[3]; 
    sprintf(hname,"h%d",i);

    if(i == 4 || i == 7 || i == 8 ) {
      if(i == 7) h1[i] = new TH1F(hname,label1[i],100,-5.,5.);   
      if(i == 8) h1[i] = new TH1F(hname,label1[i],72,-3.1415926,3.1415926);   
      if(i == 4) h1[i] = new TH1F(hname,label1[i],30,0.,150.);  
    }
    else { 
      h1[i] = new TH1F(hname,label1[i],100,1.,0.);  
    }

  }

  // Special : global timing < 60 ns 
  h1[15] = new TH1F("h15",label1[15],60,0.,60.);  
  // Special : timing in the cluster (7x7) enery-weighted
  h1[16] = new TH1F("h16",label1[16],60,0.,60.);  
  // Special : number of HCAL hits
  h1[17] = new TH1F("h17",label1[17],20,0.,20.);  
  // Special : signal in long fibers
  h1[18] = new TH1F("h18",label1[18],50,0.,50.);
  // Special : signal in short fibers
  h1[19] = new TH1F("h19",label1[19],50,0.,50.);

  for (int i = 0;  i < Nhist1; i++) {
     h1[i]->Sumw2();
  }

  // eta-phi grid (for muon samples)
  h2g = new TH2F("Grid",label2g,1000,-5.,5.,576,-3.1415927,3.1415927);

  //***************************************************************************
  //***************************************************************************
  //...Fetch the data and fill the histogram 

  // branches separately - 

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

    // cout << "Ev. " << i << endl;

    // -- get entries
    branchLayer ->GetEntry(i);
    branchNxN   ->GetEntry(i);
    branchJets  ->GetEntry(i);

    // -- Leading Jet
    int nJetHits =  infoJets.njethit();
    //cout << "nJetHits = " << nJetHits << endl; 

    std::vector<float> rJetHits(nJetHits);
    rJetHits = infoJets.jethitr();
    std::vector<float> tJetHits(nJetHits);
    tJetHits = infoJets.jethitt();
    std::vector<float> eJetHits(nJetHits);
    eJetHits = infoJets.jethite();

    float ecalJet = infoJets.ecaljet();
    float hcalJet = infoJets.hcaljet();
    float   hoJet = infoJets.hojet();
    float etotJet = infoJets.etotjet();

    float detaJet = infoJets.detajet();
    float dphiJet = infoJets.dphijet();
    float   drJet = infoJets.drjet();
    float  dijetM = infoJets.dijetm();

    
    for (int j = 0; j < nJetHits; j++) {
      h1[0]->Fill(rJetHits[j]);
      h1[1]->Fill(tJetHits[j]); 
      h1[2]->Fill(eJetHits[j]);
    }
   
    h1[3]->Fill(ecalJet); //
    h1[4]->Fill(hcalJet); //
    h1[5]->Fill(etotJet);


    // All Jets 

    int                nJets  = infoJets.njet();
    std::vector<float> jetE(nJets);
    jetE  = infoJets.jete();
    std::vector<float> jetEta(nJets);
    jetEta = infoJets.jeteta();
    std::vector<float> jetPhi(nJets);
    jetPhi = infoJets.jetphi();

    for (int j = 0; j < nJets; j++) {
      h1[6]->Fill(jetE[j]);
      h1[7]->Fill(jetEta[j]);
      h1[8]->Fill(jetPhi[j]);
    }
 
  
    // CaloHits from PHcalValidInfoLayer  
    
    int                    nHits = infoLayer.nHit();
    std::vector<float>    idHits (nHits);
    idHits = infoLayer.idHit();
    std::vector<float>   phiHits (nHits);
    phiHits = infoLayer.phiHit();
    std::vector<float>   etaHits (nHits);
    etaHits = infoLayer.etaHit();
    std::vector<float> layerHits (nHits);
    layerHits = infoLayer.layerHit();
    std::vector<float>     eHits (nHits);
    eHits = infoLayer.eHit();
    std::vector<float>     tHits (nHits);
    tHits  = infoLayer.tHit();

    int ne = 0, nh = 0; 
    for (int j = 0; j < nHits; j++) {
      int layer = layerHits[j]-1;
      int id    = (int)idHits[j];

      if(id >= 10) {ne++;}
      else {nh++;}

      //      cout << "Hit subdet = " << id  << "  lay = " << layer << endl;
 
      h1[9]->Fill(etaHits[j]);
      h1[10]->Fill(phiHits[j]);
      h1[11]->Fill(eHits[j]);
      h1[12]->Fill(tHits[j]);

      h1[15]->Fill(tHits[j]);
      h1[16]->Fill(tHits[j],eHits[j]);
      
      if(id < 6) { // HCAL only. Depth is needed, not layer !!!
	h2g->Fill(etaHits[j],phiHits[j]);
      }
      

    }
      
    h1[17]->Fill(Float_t(nh));


    // The rest  PHcalValidInfoLayer
    float elongHF  =  infoLayer.elonghf(); 
    float eshortHF =  infoLayer.eshorthf(); 
    float eEcalHF  =  infoLayer.eecalhf(); 
    float eHcalHF  =  infoLayer.ehcalhf(); 

    h1[13]->Fill(eEcalHF);
    h1[14]->Fill(eHcalHF);
 
    h1[18]->Fill(elongHF);
    h1[19]->Fill(eshortHF);

  }

  // cout << "After event cycle " << i << endl;

  //...Prepare the main canva 
  TCanvas *myc = new TCanvas("myc","",800,600);
  gStyle->SetOptStat(1111);   // set stat         :0 - nothing 
  
 
  // Cycle for 1D distributions
  for (int ihist = 0; ihist < Nhist1 ; ihist++) {
    if(h1[ihist]->Integral() > 1.e-30 && h1[ihist]->Integral() < 1.e30 ) { 
      
      h1[ihist]->SetLineColor(45);
      h1[ihist]->SetLineWidth(2); 
      
      if(doDraw == 1) {
	h1[ihist]->Draw("h");
	myc->SaveAs(label1[ihist]);
      }
    }
  }


  // eta-phi grid 
  if(h2g->Integral() > 1.e-30 && h2g->Integral() < 1.e30 ) { 
    
    h2g->SetMarkerColor(41);
    h2g->SetMarkerStyle(20);
    h2g->SetMarkerSize(0.2); 
    h2g->SetLineColor(41);
    h2g->SetLineWidth(2); 
    
    if(doDraw == 1) {	
      h2g->Draw();
      myc->SaveAs(label2g);      
    }
  }
  

  // added by Julia Yarba
  //-----------------------   
  // this is a temporary stuff that I've made
  // to create a reference ROOT histogram file

  if (doDraw == 2) {
    TFile OutFile(outputfile,"RECREATE") ;
    int ih = 0 ;

    for ( ih=0; ih<Nhist1; ih++ )
      { 
	h1[ih]->Write() ;
      }

    OutFile.Write() ;
    OutFile.Close() ;
    cout << outputfile << " histogram file created" << endl ; 
    
    return;
    
  }

  /*
  return;
  */
 

   // now perform Chi2 test for histograms using
   // "reference" and "current" histograms 
   
   
   // open up ref. ROOT file
   //
   TFile RefFile(reffile) ;
   
   // service variables
   //
   TH1F* ref_hist = 0 ;
   int ih = 0 ;
   

   // loop over specials : timing,  nhits, simhits-E  
   //
   for ( ih=15; ih<20; ih++ )
   {
      // service - name of the ref histo
      //
      char ref_hname[4] ;
      sprintf( ref_hname, "h%d", ih ) ;
      
      // retrive ref.histos one by one
      //
      ref_hist = (TH1F*)RefFile.Get( ref_hname ) ;
      
      // check if valid (no-NULL)
      //
      if ( ref_hist == NULL )
      {
         // print warning in case of trouble
	 //
	 cout << "No such ref. histogram" << *ref_hname << endl ; 
      }
      else
      {
         // everything OK - perform Chi2 test
	 //
	Double_t *res;
	Double_t pval = h1[ih]->Chi2Test( ref_hist, "UU",res ) ;
	
	// output Chi2 comparison results
	//
	cout << "[OVAL] : histo " << ih << ", p-value= " << pval << endl ;
      }
   }

   
   // close ref. ROOT file
   //
   RefFile.Close() ;
   
  // at the end, close "current" ROOT tree file
  //
  myf->Close();


  return ;  
}
//void pi0_mfitpeak(char *FileName, char *HistName, Int_t etapi0flag) 
void pi0_mfitpeak(TH1F *mh1, Int_t etapi0flag, float xmin, float xmax, int npol,float res[],int posFlag, const char *dirName, const char *histName, float text_x, float text_y, const char *texName) 
  
{
  TGaxis::SetMaxDigits(3);


  // TVirtualFitter::SetDefaultFitter("Minuit");
  


  // This script attempts to fit any pi0 peak so that the freaking fit function would converge
  // currently background is fitted to a pol4 function and the peak by a gaussian;
  // results are not very nice
  // usage  .x pi0_mfitpeak.C++ ("pi0calib.root","minv_spb")
  // or eg.  .x pi0_mfitpeak.C ("../pi0anal/pi0ana_punorm.root","minv_spb",0)

  gROOT->Reset();
  //  gStyle->SetOptFit();
  //  gStyle->SetOptFit(0);
  //  gStyle->SetOptStat(0);
  //  gStyle->SetOptTitle(0);
Bool_t NOTE=1;
  if(NOTE) gStyle->SetCanvasBorderMode(0);

  gStyle->SetPadTopMargin(0.08);
  gStyle->SetPadBottomMargin(0.12);
  gStyle->SetPadLeftMargin(0.15);
  gStyle->SetPadRightMargin(0.08);

  mh1->GetXaxis()->SetRangeUser(xmin,xmax);
  
  Int_t highx=500;
  TCanvas *c2 = new TCanvas("c2","",200,10,highx,500);


    // cout<<FileName<<" "<<HistName<<endl;

  //     TFile f(FileName);
  //   TH1F *mh1 = (TH1F*) f.Get(HistName);
      mh1->SetMarkerStyle(20);
      mh1->SetMarkerSize(1.);
      mh1->SetStats(0); // 1/0 to set the stat box

   mh1->GetXaxis()->SetTitle("Invariant Mass of Photon Pairs (GeV/c^{2})");


   float binwidth = mh1->GetBinWidth(1);
   
   char *ytitle = new char[100];

   sprintf(ytitle,"Photon Pairs / %4.3f GeV/c^{2}",binwidth);
   

   mh1->GetYaxis()->SetTitle(ytitle);


   mh1->GetXaxis()->SetTitleSize(0.055);
   mh1->GetYaxis()->SetTitleSize(0.055);
   mh1->GetXaxis()->SetLabelSize(0.045);
   mh1->GetYaxis()->SetLabelSize(0.045);
   mh1->GetXaxis()->SetTitleOffset(0.90);
   mh1->GetXaxis()->CenterTitle();
   mh1->GetYaxis()->SetTitleOffset(1.32);
   

   // First work with the histogram and find the peak and fit ranges
   TAxis *xaxis = mh1->GetXaxis();
   Float_t binsiz= xaxis->GetBinCenter(3) - xaxis->GetBinCenter(2);
   Int_t nbins = xaxis->GetNbins(); 
   Float_t nevtperbin0[10000];
   Float_t errorbin0[10000];
   Float_t nevttot;
   Float_t maxbin=0; Int_t nmaxbin=0, nminbord=0, nmaxbord=nbins;
   
   for (Int_t nn=1; nn <= nbins; nn++)
     {
       nevtperbin0[nn] = mh1->GetBinContent(nn); 
       if(nevtperbin0[nn] > maxbin) { maxbin=nevtperbin0[nn]; nmaxbin=nn; }
       errorbin0[nn] = mh1->GetBinError(nn); 
       nevttot+=nevtperbin0[nn];
       if(nevtperbin0[nn] > 0 && nminbord == 0) nminbord=nn; 
       if(nevtperbin0[nn] == 0 && (nn > nminbord +10) && nmaxbord==0 && nminbord > 0) nmaxbord=nn; 
     }
   cout<<"Minbordl "<<nminbord<<" with events: "<<nevtperbin0[nminbord]<<endl;
   cout<<"Maxbordl "<<nmaxbord<<" with events: "<<nevtperbin0[nmaxbord]<<endl;
   nminbord+=0;
   nmaxbord-=0;
   Int_t nmin0=nminbord;
   while(nevtperbin0[nminbord] < nevtperbin0[nmaxbin]*0.025) nminbord++;
   while(nevtperbin0[nmaxbord] < nevtperbin0[nmaxbin]*0.025) nmaxbord--;
   // the above was just to get the info and low/high bins

   // Set the fit range ! This is for total fit !	 
   Float_t fitl=xmin;
     float fith=xmax;
   //     Float_t fitl=0.07, fith=0.2;// this works better for pileup
   //         Float_t fitl=0.08, fith=0.18;// this works even better for pileup
     //  if(etapi0flag == 1)
     // {
     //  fitl=0.35; fith=0.75;
     //}
     

     //   if(fitl < xaxis->GetBinCenter(nmin0)) fitl = xaxis->GetBinCenter(nmin0);
   //if(fith > xaxis->GetBinCenter(nmaxbord)) fith = xaxis->GetBinCenter(nmaxbord);
 
   


   cout<<" fit range "<<fitl<<" -- "<<fith<<endl;

   cout <<"Bin size "<<binsiz<<endl;
   cout<<"Total events "<<nevttot<<endl;
   cout<<"MaxBin "<<nmaxbin<<" with events: "<<nevtperbin0[nmaxbin]<<endl;
   cout<<"Minbord "<<nminbord<<" with events: "<<nevtperbin0[nminbord]<<endl;
   cout<<"Maxbord "<<nmaxbord<<" with events: "<<nevtperbin0[nmaxbord]<<endl;
      mh1->DrawCopy("sep");

      Float_t lowgauss=0.135-4.*0.010;
      Float_t highgauss=0.135+4.*0.010;
      if(etapi0flag == 1)
	{
	  lowgauss=0.55-5.*0.025;
              highgauss=0.55+5.*0.025;
	}
      Int_t nlowgauss=Int_t((lowgauss-xaxis->GetBinCenter(1))/Float_t(binsiz)+0.5);
      Int_t nhighgauss=Int_t((highgauss-xaxis->GetBinCenter(1))/Float_t(binsiz)+0.5);
      cout <<xaxis->GetBinCenter(nlowgauss)<<" "<<xaxis->GetBinCenter(nhighgauss)<<endl;
   // now make the "background" histogram and fit it with p4
      Float_t lowvalgauss=nevtperbin0[nlowgauss];
      Float_t increm=(nevtperbin0[nhighgauss]-nevtperbin0[nlowgauss])/Float_t(nhighgauss-nlowgauss);
      TH1F *hbkg = (TH1F*)mh1->Clone();
      hbkg->SetName("bkg_clone");
      for (Int_t nn=nlowgauss; nn<=nhighgauss; nn++)
	{
	  hbkg->SetBinContent(nn,Float_t(lowvalgauss+(nn-nlowgauss)*increm));
	  hbkg->SetBinError(nn,sqrt(lowvalgauss+(nn-nlowgauss)*increm));
	}
      hbkg->DrawCopy("samesep");
      //      break;
      // Now define the "gaussian" histogram
      TH1F *hgauss = (TH1F*)mh1->Clone();
      hgauss->SetName("gauss_clone");
      hgauss->Sumw2();
      hgauss->Add(mh1,hbkg,1,-1); // if errors are independent Add needs to be used !
       for (Int_t nn=1; nn <= nbins; nn++)
	 {
	   if(hgauss->GetBinContent(nn) < 0.) hgauss->SetBinContent(nn,0.001*nevtperbin0[nmaxbin]);
	   hgauss->SetBinError(nn,sqrt(hgauss->GetBinContent(nn)));
	 }

   // Declare function with wich to fit
       TF1 *g1 = new TF1("g1","gaus",lowgauss,highgauss);
   hgauss->Fit(g1,"R0");
   hgauss->DrawCopy("sep");
   g1->Draw("same");
   //  break;

   char *polff = new char[20];

   sprintf(polff,"pol%d",npol);
   
   TF1 *p4bkg; 
   if(etapi0flag != 1)
     p4bkg   = new TF1("pm2",polff, xaxis->GetBinCenter(nminbord),xaxis->GetBinCenter(nmaxbord));
   else
     p4bkg   = new TF1("pm2",polff, 0.35,0.75);
   
   

   hbkg->Fit(p4bkg,"R0");
   hbkg->DrawCopy("sep");
   p4bkg->SetLineStyle(kDashed);
   p4bkg->Draw("same");
   // break;
   
   
   Double_t par[20],parf[20],errparf[20];
   g1->GetParameters(&par[0]);
   p4bkg->GetParameters(&par[3]);

   char *totff = new char[20];
   
   sprintf(totff,"gaus(0)+pol%d(3)",npol);
   
   
   TF1 *total = new TF1("total",totff,fitl,fith);
   TF1 *p4bkgfin   = new TF1("pm2",polff,fitl,fith);
   total->SetParameters(par);

   if(etapi0flag==0){
     total->SetParLimits(1,0.10,0.15);
     total->SetParLimits(2,0.135*0.06,0.135*0.3);
     
   }else{
     total->SetParLimits(1,0.35,0.65);
   }
   
   
   //  total->FixParameter(1,1.21340e-01); 
   // total->FixParameter(2,2.69780e-02);
   
   
   

   

   mh1->Fit(total,"R0");
   
   cout<<" yield.. "<< total->GetParameter(0) <<"+/- " << total->GetParError(0)<<endl;
   

     total->GetParameters(parf);


     for( Int_t nn=0; nn < 3+npol+1; nn++) errparf[nn]=total->GetParError(nn);
     g1->SetParameters(&parf[0]);
     p4bkgfin->SetParameters(&parf[3]);
     cout <<" Piz Mass = "<<parf[1]*1000.<<" +- "<<errparf[1]*1000.<<
       " Sigma ="<<parf[2]*1000.<<" +- "<<errparf[2]*1000.<<endl;
      cout << " Sigma Rel. = "<< parf[2]/parf[1]<<" +- "
	   << errparf[2]/parf[1] <<endl;

    Float_t int_min=parf[1]-3.*parf[2];
    Float_t int_max=parf[1]+3.*parf[2];
    Float_t sig_peak=g1->Integral(int_min,int_max)/binsiz;
    Float_t bkgd_peak=p4bkgfin->Integral(int_min,int_max)/binsiz;
    cout<<" In +-3. sigma window: Signal="<<sig_peak<<" Bkgd="<<bkgd_peak<<endl;
    Float_t SB=sig_peak/bkgd_peak; Float_t SBerr=SB*(sqrt(1./sig_peak+1./bkgd_peak));
    cout<<" Signal/Bkgd "<<SB<<" +- "<<SBerr<<endl;   

    int_min=parf[1]-2.*parf[2];
    int_max=parf[1]+2.*parf[2];
    sig_peak=g1->Integral(int_min,int_max)/binsiz;
    bkgd_peak=p4bkgfin->Integral(int_min,int_max)/binsiz;
    cout<<" In +-2.sigma window: Signal="<<sig_peak<<" Bkgd="<<bkgd_peak<<endl;
    SB=sig_peak/bkgd_peak; SBerr=SB*(sqrt(1./sig_peak+1./bkgd_peak));
    cout<<" Signal/Bkgd "<<SB<<" +- "<<SBerr<<endl;   
 			

    float S = sig_peak; 
    float B = bkgd_peak; 
    
    int_min=parf[1]-20.*parf[2];
    int_max=parf[1]+20.*parf[2];
    float S_all = g1->Integral(int_min,int_max)/binsiz;
    
    

    float test_sall =  parf[0] * parf[2] * sqrt(acos(-1)) / binsiz; 
    
    cout<<"signal all: "<< S_all << " "<< test_sall <<endl; 
    
    float Serr_all = errparf[0]/ parf[0] * S_all; 
    


    res[0] = S_all; 
    res[1] = Serr_all; 

    res[2] = parf[1]; 
    res[3] = errparf[1];
    
    res[4] = parf[2]; 
    res[5] = errparf[2];

    res[6] = SB; 
    res[7] = SBerr; 
    


    total->SetLineWidth(3);
    
   total->SetLineColor(kBlue);

   p4bkgfin->SetLineWidth(3);
   
   p4bkgfin->SetLineColor(kRed);
   mh1->DrawCopy("sep");

   //   total->SetRange(0.07,0.185);
   //    p4bkgfin->SetRange(0.07,0.185);
   total->Draw("same");
   p4bkgfin->SetLineStyle(kDashed);
   p4bkgfin->Draw("same");   

   TLatex l;
   
   //   l.SetTextSize(0.06);
   l.SetTextSize(0.05);
   
   
   l.SetTextColor(1);
   l.SetNDC();
   
  
   float sigma = parf[2]/ parf[1]*100; 
   float sigmaerr = errparf[2]/ parf[1]*100; 
   char *sigma_name = new char[50]; 
   if(sigmaerr>0.005)
     sprintf(sigma_name,"#sigma = %3.2f #pm %3.2f %% ",sigma,sigmaerr);
   else sprintf(sigma_name,"#sigma = %3.2f %% ",sigma);
   
   if(posFlag==1){
     l.DrawLatex(0.54,0.75,sigma_name);
   }else if( posFlag==2){
     l.DrawLatex(0.54,0.3,sigma_name);

   }
      
      //  sprintf(sigma_name,"S/B = %3.2f #pm %3.2f ",SB,SBerr);
      //
      sprintf(sigma_name,"S = %2.1f #pm %2.1f",S_all,Serr_all);
	      //
      
      // l.DrawLatex(0.5,0.5,sigma_name);
      
      sprintf(sigma_name,"M = %3.1f #pm %3.1f MeV",parf[1]*1000.,errparf[1]*1000);
      if(posFlag==1){
      l.DrawLatex(0.54,0.82,sigma_name);
      }else if( posFlag==2){
	l.DrawLatex(0.54,0.37,sigma_name);

      }
      ///l.DrawLatex(0.169,470.,"d)");


      c2->Modified();
   c2->Update();
   //   c2->SaveAs("nice_pi0.gif");

   
   
   if( text_x >0 && text_y >0){
    TLatex *   tex = new TLatex(text_x, text_y, texName);
    tex->SetNDC();
    tex->SetTextSize(0.06);
    tex->SetLineWidth(2);
    tex->Draw();
  }
  

   char *filename = new char[1000];

   
   sprintf(filename,"%s/%s.gif",dirName,histName);
   c2->Print(filename);
   sprintf(filename,"%s/%s.C",dirName,histName);
   c2->Print(filename);
   
   // .x pi0_mfitpeak.C ("pi0ana_508030.root","minv_spb",0)
   // .x pi0_mfitpeak.C ("pi0ana_npu.root","minv_bkg",0)  
   // .x pi0_mfitpeak.C ("pi0ana_punormv2.root","minv_spb",0)
}
Ejemplo n.º 20
0
// Commands executed in a GLOBAL scope, e.g. created hitograms aren't erased...
void plot_HE(TString  inputfile="simevent_HE.root",
	     TString outputfile="HE_histo.root",
	     Int_t drawmode = 2,
             TString    reffile="../data/HE_ref.root"){
 
  // Option to no-action(0)/draw(1)/save(2) (default = 0) histograms in gif.
  //int doDraw = 0; 
  int doDraw = drawmode;

  char * treename = "Events";        //The Title of Tree.
  
  delete gROOT->GetListOfFiles()->FindObject(inputfile);

  TFile * myf  = new TFile(inputfile);
  
  TTree * tree = dynamic_cast<TTree*>(myf->Get("Events"));
  assert(tree != 0);

  TBranch * branchLayer = tree->GetBranch("PHcalValidInfoLayer_g4SimHits_HcalInfoLayer_CaloTest.obj");
  assert(branchLayer != 0);

  TBranch * branchNxN = tree->GetBranch("PHcalValidInfoNxN_g4SimHits_HcalInfoNxN_CaloTest.obj");
  assert(branchNxN != 0);

  TBranch * branchJets = tree->GetBranch( "PHcalValidInfoJets_g4SimHits_HcalInfoJets_CaloTest.obj");  assert(branchJets != 0);

  // Just number of entries (same for all branches)
  int  nent = branchLayer->GetEntries();
  cout << "Entries branchLayer : " << nent << endl;
  nent = branchJets->GetEntries();
  cout << "Entries branchJets  : " << nent << endl;
  nent = branchNxN->GetEntries();
  cout << "Entries branchNxN   : " << nent << endl;

  // Variables from branches
  PHcalValidInfoJets infoJets;
  branchJets->SetAddress( &infoJets); 
  PHcalValidInfoLayer infoLayer;
  branchLayer->SetAddress( &infoLayer); 
  PHcalValidInfoNxN infoNxN;
  branchNxN->SetAddress( &infoNxN); 
  
  //***************************************************************************
  // Histo titles-labels

  const int Nhist1     = 47, Nhist2 = 1;  // N simple and N combined histos
  const int Nhist1spec =  7;              // N special out of Nsimple total 
  const int nLayersMAX = 20;
  const int nDepthsMAX =  5;

  TH1F *h;                              // just a pointer
  TH1F *h1[Nhist1];
  TH1F *h1l[nLayersMAX];                // + all scint. layers separately
  TH1F *h1d[nDepthsMAX];                // + all depths  

  TH2F *h2[Nhist2];
  TH2F *h2g[5];         // +  eta-phi grid -related for all depthes
  
  char *label1[Nhist1], *label2[Nhist2], *label1l[nLayersMAX ];
  char *label1d[nDepthsMAX], *label2g[5];
  

  // simple histos  
  label1[0]  = &"rJetHits.gif";
  label1[1]  = &"tJetHits.gif";
  label1[2]  = &"eJetHits.gif";
  label1[3]  = &"ecalJet.gif";
  label1[4]  = &"hcalJet.gif";
  label1[5]  = &"hoJet.gif";
  label1[6]  = &"etotJet.gif";
  label1[7]  = &"detaJet.gif";
  label1[8]  = &"dphiJet.gif";
  label1[9]  = &"drJet.gif";
  label1[10] = &"jetE.gif";
  label1[11] = &"jetEta.gif";
  label1[12] = &"jetPhi.gif";
  label1[13] = &"dijetM.gif";
  label1[14] = &"ecalNxNr.gif";
  label1[15] = &"hcalNxNr.gif";
  label1[16] = &"hoNxNr.gif";
  label1[17] = &"etotNxNr.gif";
  label1[18] = &"ecalNxN.gif";
  label1[19] = &"hcalNxN.gif";
  label1[20] = &"hoNxN.gif";
  label1[21] = &"etotNxN.gif";
  label1[22] = &"layerHits.gif";
  label1[23] = &"etaHits.gif";          
  label1[24] = &"phiHits.gif";
  label1[25] = &"eHits.gif";
  label1[26] = &"tHits.gif";
  label1[27] = &"idHits.gif";
  label1[28] = &"jitterHits.gif";
  label1[29] = &"eIxI.gif";
  label1[30] = &"tIxI.gif";
  label1[31] = &"eLayer.gif";
  label1[32] = &"eDepth.gif";
  label1[33] = &"eHO.gif";
  label1[34] = &"eHBHE.gif";
  label1[35] = &"elongHF.gif";
  label1[36] = &"eshortHF.gif";
  label1[37] = &"eEcalHF.gif";
  label1[38] = &"eHcalHF.gif";

  // special
  label1[39] = &"NxN_trans_fraction.gif"; 
  label1[40] = &"tHist_50ns.gif";   
  label1[41] = &"tHist_eweighted.gif"; 
  label1[42] = &"nHits_ECAL.gif";
  label1[43] = &"nHits_HCAL.gif";
  label1[44] = &"nHits.gif";
  label1[45] = &"longProf_eweighted.gif";
  label1[46] = &"E_hcal.gif";

  label1l[0] = &"layer_0.gif"; 
  label1l[1] = &"layer_1.gif"; 
  label1l[2] = &"layer_2.gif"; 
  label1l[3] = &"layer_3.gif"; 
  label1l[4] = &"layer_4.gif"; 
  label1l[5] = &"layer_5.gif"; 
  label1l[6] = &"layer_6.gif"; 
  label1l[7] = &"layer_7.gif"; 
  label1l[8] = &"layer_8.gif"; 
  label1l[9] = &"layer_9.gif"; 
  label1l[10] = &"layer_10.gif"; 
  label1l[11] = &"layer_11.gif"; 
  label1l[12] = &"layer_12.gif"; 
  label1l[13] = &"layer_13.gif"; 
  label1l[14] = &"layer_14.gif"; 
  label1l[15] = &"layer_15.gif"; 
  label1l[16] = &"layer_16.gif"; 
  label1l[17] = &"layer_17.gif"; 
  label1l[18] = &"layer_18.gif"; 
  label1l[19] = &"layer_19.gif"; 

  label1d[0] = &"depth_0.gif"; 
  label1d[1] = &"depth_1.gif"; 
  label1d[2] = &"depth_2.gif"; 
  label1d[3] = &"depth_3.gif"; 
  label1d[4] = &"depth_4.gif"; 
 
  // more complicated histos and profiles
 
  label2[0] = &"JetHCALvsECAL.gif";

  label2g[0] = &"Eta-phi_grid_depth_0.gif";
  label2g[1] = &"Eta-phi_grid_depth_1.gif";
  label2g[2] = &"Eta-phi_grid_depth_2.gif";
  label2g[3] = &"Eta-phi_grid_depth_3.gif";
  label2g[4] = &"Eta-phi_grid_all_depths.gif";

  // Some constants

  const float fact = 117.0; // sampling factor which corresponds to those 
                            // for layer = 0,1 in SimG4HcalValidation.cc

  //***************************************************************************
  //...Book histograms 

  for (Int_t i = 0; i < Nhist1-Nhist1spec; i++) {
    char hname[3]; 
    sprintf(hname,"h%d",i);

    if(i == 4 || i == 7 || i == 8 || i == 11 || i == 12 || i == 6) {
      if(i == 11) h1[i] = new TH1F(hname,label1[i],100,-5.,5.);   
      if(i == 12) h1[i] = new TH1F(hname,label1[i],72,-3.1415926,3.1415926);   
      if(i == 7 || i == 8) h1[i] = new TH1F(hname,label1[i],100,-0.1,0.1);  
      if( i == 4)          h1[i] = new TH1F(hname,label1[i],50,0.,100.);  
      if( i == 6)          h1[i] = new TH1F(hname,label1[i],50,0.,100.);
    }
    else { 
      h1[i] = new TH1F(hname,label1[i],100,1.,0.);  
    }

  }

  // Special : global timing < 50 ns 
  h1[40] = new TH1F("h40",label1[40],50,0.,50.);  
  // Special : timing in the cluster (7x7) enery-weighted
  h1[41] = new TH1F("h41",label1[41],30,0.,30.);  
  // Special : number of ECAL&HCAL hits
  h1[42] = new TH1F("h42",label1[42],300,0.,3000.);  
  h1[43] = new TH1F("h43",label1[43],300,0.,3000.);  
  h1[44] = new TH1F("h44",label1[44],300,0.,3000.);  

  // Special : Longitudinal profile
  h1[45] = new TH1F("h45",label1[45],20,0.,20.);
  // Etot HCAL
  TH1F *h1[46] = new TH1F("h46",label1[46],50,0.,1.0);
  
  for (int i = 0; i < Nhist1; i++) {
    if(i != 39)  h1[i]->Sumw2();
  }


  for (int i = 0; i < Nhist2; i++) {
    char hname[3]; 
    sprintf(hname,"D%d",i);
    h2[i] = new TH2F(hname,label2[i],100,0.,100.,100,0.,100.);
  }
  //  h[i]->Sumw2();         // to get errors properly calculated

  // scint. layers
  for (int i = 0; i < nLayersMAX; i++) {
    char hname[4]; 
    sprintf(hname,"hl%d",i);
    h1l[i] = new TH1F(hname,label1l[i],40,0.,0.4);  
  }
  // depths
  Float_t max[5] = {30000, 500, 500, 200, 200.};
  for (int i = 0; i < nDepthsMAX; i++) {
    char hname[3]; 
    sprintf(hname,"hd%d",i);
    h1d[i] = new TH1F(hname,label1d[i],100,0.,max[i]);  
  }

  // eta-phi grid (for muon samples)
  for (int i = 0; i < 5; i++) {
    char hname[3]; 
    sprintf(hname,"Dg%d",i);
    h2g[i] = new TH2F(hname,label2g[i],1000,-5.,5.,576,-3.1415927,3.1415927);
  }

  //***************************************************************************
  //***************************************************************************
  //...Fetch the data and fill the histogram 

  // branches separately - 

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

    // cout << "Ev. " << i << endl;

    // -- get entries
    branchLayer ->GetEntry(i);
    branchNxN   ->GetEntry(i);
    branchJets  ->GetEntry(i);

    // -- Leading Jet
    int nJetHits =  infoJets.njethit();
    //cout << "nJetHits = " << nJetHits << endl; 

    std::vector<float> rJetHits(nJetHits);
    rJetHits = infoJets.jethitr();
    std::vector<float> tJetHits(nJetHits);
    tJetHits = infoJets.jethitt();
    std::vector<float> eJetHits(nJetHits);
    eJetHits = infoJets.jethite();

    float ecalJet = infoJets.ecaljet();
    float hcalJet = infoJets.hcaljet();
    float   hoJet = infoJets.hojet();
    float etotJet = infoJets.etotjet();

    float detaJet = infoJets.detajet();
    float dphiJet = infoJets.dphijet();
    float   drJet = infoJets.drjet();
    float  dijetM = infoJets.dijetm();

    
    for (int j = 0; j < nJetHits; j++) {
      h1[0]->Fill(rJetHits[j]);
      h1[1]->Fill(tJetHits[j]); 
      h1[2]->Fill(eJetHits[j]);
    }
   
    h1[3]->Fill(ecalJet); //
    h1[4]->Fill(hcalJet); //

    h1[5]->Fill(hoJet);
    h1[6]->Fill(etotJet);

    h2[0]->Fill(ecalJet,hcalJet); //

    h1[7]->Fill(detaJet);
    h1[8]->Fill(dphiJet);
    h1[9]->Fill(drJet);

    h1[13]->Fill(dijetM);

    // All Jets 

    int                nJets  = infoJets.njet();
    std::vector<float> jetE  (nJets);
    jetE   = infoJets.jete();
    std::vector<float> jetEta(nJets);
    jetEta = infoJets.jeteta();
    std::vector<float> jetPhi(nJets);
    jetPhi = infoJets.jetphi();

  
    for (int j = 0; j < nJets; j++) {
      h1[10]->Fill(jetE[j]);
      h1[11]->Fill(jetEta[j]);
      h1[12]->Fill(jetPhi[j]);
    }

  
    // NxN quantities
    float ecalNxNr = infoNxN.ecalnxnr();
    float hcalNxNr = infoNxN.hcalnxnr();
    float   hoNxNr = infoNxN.honxnr();
    float etotNxNr = infoNxN.etotnxnr();

    float ecalNxN  = infoNxN.ecalnxn();
    float hcalNxN  = infoNxN.hcalnxn();
    float   hoNxN  = infoNxN.honxn();
    float etotNxN  = infoNxN.etotnxn();

    h1[14]->Fill(ecalNxNr);
    h1[15]->Fill(hcalNxNr);
    h1[16]->Fill(hoNxNr);
    h1[17]->Fill(etotNxNr);
   
    h1[18]->Fill(ecalNxN);
    h1[19]->Fill(hcalNxN);
    h1[20]->Fill(hoNxN);
    h1[21]->Fill(etotNxN);


    // CaloHits from PHcalValidInfoLayer  
    
    int                    nHits = infoLayer.nHit();
    std::vector<float>    idHits(nHits);
    idHits = infoLayer.idHit();
    std::vector<float>   phiHits(nHits);
    phiHits = infoLayer.phiHit();
    std::vector<float>   etaHits(nHits); 
    etaHits = infoLayer.etaHit();
    std::vector<float> layerHits(nHits); 
    layerHits = infoLayer.layerHit();
    std::vector<float>     eHits(nHits); 
    eHits = infoLayer.eHit();
    std::vector<float>     tHits(nHits); 
    tHits = infoLayer.tHit();

    int ne = 0, nh = 0; 
    for (int j = 0; j < nHits; j++) {
      int layer = layerHits[j]-1;
      int id    = (int)idHits[j];

      if(id >= 10) {ne++;}
      else {if (id < 5) nh++;}

      //      cout << "Hit subdet = " << id  << "  lay = " << layer << endl;

      h1[22]->Fill(Float_t(layer));
      h1[23]->Fill(etaHits[j]);
      h1[24]->Fill(phiHits[j]);
      h1[25]->Fill(eHits[j]);
      h1[26]->Fill(tHits[j]);
      h1[27]->Fill(idHits[j]);
      //      h1[28]->Fill(jitterHits[j]);   // no jitter anymore

      h1[40]->Fill(tHits[j]);
      h1[41]->Fill(tHits[j],eHits[j]);
      
      if(id < 6) { // HCAL only. Depth is needed, not layer !!!
	//if(layer == 0)               h2g[0]->Fill(etaHits[j],phiHits[j]);
	//if(layer == 1)               h2g[1]->Fill(etaHits[j],phiHits[j]);
	//if(layer == 2)               h2g[2]->Fill(etaHits[j],phiHits[j]);
	//if(layer == 3)               h2g[3]->Fill(etaHits[j],phiHits[j]);
	h2g[4]->Fill(etaHits[j],phiHits[j]);
      }
      

    }
      
    h1[42]->Fill(Float_t(ne));
    h1[43]->Fill(Float_t(nh));
    h1[44]->Fill(Float_t(nHits));

    // NxN  PHcalValidInfoNxN 
    //    cout << " nIxI = " << nIxI << endl;
    int                    nIxI = infoNxN.nnxn();
    std::vector<float>    idIxI(nIxI);  
    idIxI = infoNxN.idnxn();
    std::vector<float>     eIxI(nIxI); 
    eIxI  = infoNxN.enxn();
    std::vector<float>     tIxI(nIxI); 
    tIxI  = infoNxN.tnxn();
    
    for (int j = 0; j < nIxI ; j++) {   // NB !!! j < nIxI
      h1[29]->Fill(eIxI[j]);
      h1[30]->Fill(tIxI[j]);

      h1[39]->Fill(idIxI[j],eIxI[j]);  // transverse profile

    }

    // Layers and depths PHcalValidInfoLayer
    
    std::vector<float> eLayer(nLayersMAX);
    eLayer = infoLayer.elayer();
    std::vector<float> eDepth(nDepthsMAX);
    eDepth = infoLayer.edepth();
    
    float eTot = 0.;

    for (int j = 0; j < nLayersMAX ; j++) {
      h1[31]->Fill(eLayer[j]);
      h1l[j]->Fill(eLayer[j]);

	h1[45]->Fill((Float_t)(j),eLayer[j]);  // HCAL SimHits only 
        eTot += eLayer[j];
    }
    for (int j = 0; j < nDepthsMAX; j++) {
      h1[32]->Fill(eDepth[j]);
      h1d[j]->Fill(eDepth[j]);
    }

    h1[46]->Fill(eTot);               
       
    // The rest  PHcalValidInfoLayer
    float eHO      =  infoLayer.eho(); 
    float eHBHE    =  infoLayer.ehbhe(); 
    float elongHF  =  infoLayer.elonghf(); 
    float eshortHF =  infoLayer.eshorthf(); 
    float eEcalHF  =  infoLayer.eecalhf(); 
    float eHcalHF  =  infoLayer.ehcalhf(); 

    h1[33]->Fill(eHO);
    h1[34]->Fill(eHBHE);
 
    h1[35]->Fill(elongHF);
    h1[36]->Fill(eshortHF);
    h1[37]->Fill(eEcalHF);
    h1[38]->Fill(eHcalHF);

  }

  // cout << "After event cycle " << i << endl;


  //...Prepare the main canva 
  TCanvas *myc = new TCanvas("myc","",800,600);
  gStyle->SetOptStat(1111);   // set stat         :0 - nothing 
 
  // Cycle for 1D distributions
  for (int ihist = 0; ihist < Nhist1 ; ihist++) {
    if(h1[ihist]->Integral() > 1.e-30 && h1[ihist]->Integral() < 1.e30 ) { 
      
      h1[ihist]->SetLineColor(45);
      h1[ihist]->SetLineWidth(2); 
      
      if(doDraw == 1) {
	h1[ihist]->Draw("h");
	myc->SaveAs(label1[ihist]);
      }
    }
  }

  // Cycle for energy in all layers
  for (int ihist = 0; ihist < nLayersMAX; ihist++) {
    if(h1l[ihist]->Integral() > 1.e-30 && h1l[ihist]->Integral() < 1.e30 ) { 
      
      h1l[ihist]->SetLineColor(45);
      h1l[ihist]->SetLineWidth(2); 


      if(doDraw == 1) {
	h1l[ihist]->Draw("h");
	myc->SaveAs(label1l[ihist]);
      }
    }
  }


  // Cycle for 2D distributions 
  //  for (int ihist = 0; ihist < 1 ; ihist++) {
  for (int ihist = 0; ihist < Nhist2 ; ihist++) {
    if(h2[ihist]->Integral() > 1.e-30 && h2[ihist]->Integral() < 1.e30 ) { 

      h2[ihist]->SetMarkerColor(45);
      h2[ihist]->SetMarkerStyle(20);
      h2[ihist]->SetMarkerSize(0.7);  // marker size !
      
      h2[ihist]->SetLineColor(45);
      h2[ihist]->SetLineWidth(2); 
      
      if(doDraw == 1) {
	h2[ihist]->Draw();
	myc->SaveAs(label2[ihist]);
      }
    }
  }
  
 
  // Cycle for eta-phi grids 
  //  for (int ihist = 0; ihist < 5 ; ihist++) {
  for (int ihist = 4; ihist < 5 ; ihist++) {
    if(h2g[ihist]->Integral() > 1.e-30 && h2g[ihist]->Integral() < 1.e30 ) { 
      
      h2g[ihist]->SetMarkerColor(41);
      h2g[ihist]->SetMarkerStyle(20);
      h2g[ihist]->SetMarkerSize(0.2); 
      
      h2g[ihist]->SetLineColor(41);
      h2g[ihist]->SetLineWidth(2); 
      
      if(doDraw == 1) {
	h2g[ihist]->Draw();
	myc->SaveAs(label2g[ihist]);
      }
    }
  }
 

 

  // added by Julia Yarba
  //-----------------------   
  // this is a temporary stuff that I've made
  // to create a reference ROOT histogram file


  if (doDraw == 2) {
    TFile OutFile(outputfile,"RECREATE") ;
    int ih = 0 ;
    for ( ih=0; ih<nLayersMAX; ih++ )
      {
	h1l[ih]->Write() ;
      }
    for ( ih=0; ih<Nhist1; ih++ )
      { 
	h1[ih]->Write() ;
      }

    OutFile.Write() ;
    OutFile.Close() ;
    cout << outputfile << " histogram file created" << endl ;
    
    return ;
    
  }
  /*
  return;
  */
 

   // now perform Chi2 test for histograms that hold
   // energy deposition in the Hcal layers 1-10, using
   // "reference" and "current" histograms 
   
   
   // open up ref. ROOT file
   //
   TFile RefFile(reffile) ;
   
   // service variables
   //
   TH1F* ref_hist = 0 ;
   int ih = 0 ;
   
   // loop over layers 1-10 
   //
   for ( ih=1; ih<11; ih++ )
   {
      // service - name of the ref histo
      //
      char ref_hname[4] ;
      sprintf( ref_hname, "hl%d", ih ) ;
      
      // retrive ref.histos one by one
      //
      ref_hist = (TH1F*)RefFile.Get( ref_hname ) ;
      
      // check if valid (no-NULL)
      //
      if ( ref_hist == NULL )
      {
         // print warning in case of trouble
	 //
	 cout << "No such ref. histogram" << *ref_hname << endl ; 
      }
      else
      {
         // everything OK - perform Chi2 test
	 //
	Double_t *res;
	Double_t pval = h1l[ih]->Chi2Test( ref_hist, "UU", res ) ;
	 
	 // output Chi2 comparison results
	 //
	 cout << "[OVAL] : Edep in Layer " << ih << ", p-value= " << pval << endl ;
      }
   }


   // loop over specials : timing,  nhits(ECAL and HCAL) 
   //
   for ( ih=40; ih<47; ih++ )
   {
      // service - name of the ref histo
      //
      char ref_hname[4] ;
      sprintf( ref_hname, "h%d", ih ) ;
      
      // retrive ref.histos one by one
      //
      ref_hist = (TH1F*)RefFile.Get( ref_hname ) ;
      
      // check if valid (no-NULL)
      //
      if ( ref_hist == NULL )
      {
         // print warning in case of trouble
	 //
	 cout << "No such ref. histogram" << *ref_hname << endl ; 
      }
      else
      {
	// everything OK - perform Chi2 test
	//
	Double_t *res;
	Double_t pval = h1[ih]->Chi2Test( ref_hist, "UU", res) ;
	
	// output Chi2 comparison results
	//
	cout << "[OVAL] : histo " << ih << ", p-value= " << pval << endl ;
      }
   }

   
   // close ref. ROOT file
   //
   RefFile.Close() ;
   
  // at the end, close "current" ROOT tree file
  //
  myf->Close();


  return ;  
}
Ejemplo n.º 21
0
void plot_efficiencies( TFile* file, Int_t type = 2, TDirectory* BinDir)
{
   // input:   - Input file (result from TMVA),
   //          - type = 1 --> plot efficiency(B) versus eff(S)
   //                 = 2 --> plot rejection (B) versus efficiency (S)

   Bool_t __PLOT_LOGO__  = kTRUE;
   Bool_t __SAVE_IMAGE__ = kTRUE;

   // the coordinates
   Float_t x1 = 0;
   Float_t x2 = 1;
   Float_t y1 = 0;
   Float_t y2 = 0.8;

   // reverse order if "rejection"
   if (type == 2) {
      Float_t z = y1;
      y1 = 1 - y2;
      y2 = 1 - z;    
      //      cout << "--- type==2: plot background rejection versus signal efficiency" << endl;
   }
   else {
      //  cout << "--- type==1: plot background efficiency versus signal efficiency" << endl;
   }
   // create canvas
   TCanvas* c = new TCanvas( "c", "the canvas", 200, 0, 650, 500 );

   // global style settings
   c->SetGrid();
   c->SetTicks();

   // legend
   Float_t x0L = 0.107,     y0H = 0.899;
   Float_t dxL = 0.457-x0L, dyH = 0.22;
   if (type == 2) {
      x0L = 0.15;
      y0H = 1 - y0H + dyH + 0.07;
   }
   TLegend *legend = new TLegend( x0L, y0H-dyH, x0L+dxL, y0H );
   legend->SetTextSize( 0.05 );
   legend->SetHeader( "MVA Method:" );
   legend->SetMargin( 0.4 );

   TString xtit = "Signal efficiency";
   TString ytit = "Background efficiency";  
   if (type == 2) ytit = "Background rejection";
   TString ftit = ytit + " versus " + xtit;

   if (TString(BinDir->GetName()).Contains("multicut")){
      ftit += "  Bin: ";
      ftit += (BinDir->GetTitle());
   }

   // draw empty frame
   if(gROOT->FindObject("frame")!=0) gROOT->FindObject("frame")->Delete();
   TH2F* frame = new TH2F( "frame", ftit, 500, x1, x2, 500, y1, y2 );
   frame->GetXaxis()->SetTitle( xtit );
   frame->GetYaxis()->SetTitle( ytit );
   TMVAGlob::SetFrameStyle( frame, 1.0 );

   frame->Draw();  

   Int_t color = 1;
   Int_t nmva  = 0;
   TKey *key, *hkey;

   TString hNameRef = "effBvsS";
   if (type == 2) hNameRef = "rejBvsS";

   TList hists;
   TList methods;
   UInt_t nm = TMVAGlob::GetListOfMethods( methods );
   //   TIter next(file->GetListOfKeys());
   TIter next(&methods);

   // loop over all methods
   while (key = (TKey*)next()) {
      TDirectory * mDir = (TDirectory*)key->ReadObj();
      TList titles;
      UInt_t ninst = TMVAGlob::GetListOfTitles(mDir,titles);
      TIter nextTitle(&titles);
      TKey *titkey;
      TDirectory *titDir;
      while ((titkey = TMVAGlob::NextKey(nextTitle,"TDirectory"))) {
         titDir = (TDirectory *)titkey->ReadObj();
         TString methodTitle;
         TMVAGlob::GetMethodTitle(methodTitle,titDir);
         TIter nextKey( titDir->GetListOfKeys() );
         while ((hkey = TMVAGlob::NextKey(nextKey,"TH1"))) {
            TH1 *h = (TH1*)hkey->ReadObj();    
            TString hname = h->GetName();
            if (hname.Contains( hNameRef ) && hname.BeginsWith( "MVA_" )) {
               h->SetLineWidth(3);
               h->SetLineColor(color);
               color++; if (color == 5 || color == 10 || color == 11) color++; 
               h->Draw("csame");
               hists.Add(h);
               nmva++;
            }
         }
      }
   }

   while (hists.GetSize()) {
      TListIter hIt(&hists);
      TH1* hist(0);
      Double_t largestInt=-1;
      TH1* histWithLargestInt(0);
      while ((hist = (TH1*)hIt())!=0) {
         Double_t integral = hist->Integral(1,hist->FindBin(0.9999));
         if (integral>largestInt) {
            largestInt = integral;
            histWithLargestInt = hist;
         }
      }
      if (histWithLargestInt == 0) {
         cout << "ERROR - unknown hist \"histWithLargestInt\" --> serious problem in ROOT file" << endl;
         break;
      }
      legend->AddEntry(histWithLargestInt,TString(histWithLargestInt->GetTitle()).ReplaceAll("MVA_",""),"l");
      hists.Remove(histWithLargestInt);
   }   
   
   // rescale legend box size
   // current box size has been tuned for 3 MVAs + 1 title
   if (type == 1) {
      dyH *= (1.0 + Float_t(nmva - 3.0)/4.0);
      legend->SetY1( y0H - dyH );
   }
   else {
      dyH *= (Float_t(nmva - 3.0)/4.0);
      legend->SetY2( y0H + dyH);
   }

   // redraw axes
   frame->Draw("sameaxis");  
   legend->Draw("same");

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

   if (__PLOT_LOGO__) TMVAGlob::plot_logo();

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

   c->Update();

   TString fname = "plots/" + hNameRef;
   if (TString(BinDir->GetName()).Contains("multicut")){
      TString fprepend(BinDir->GetName());
      fprepend.ReplaceAll("multicutMVA_","");
      fname = "plots/" + fprepend + "_" + hNameRef;
   }
   if (__SAVE_IMAGE__) TMVAGlob::imgconv( c, fname );

   return;
}
Ejemplo n.º 22
0
void quantiles() {
   // demo for quantiles
   // Authors: Rene Brun, Eddy Offermann
   
   const Int_t nq = 10000;
   const Int_t nshots = 10000;
   Double_t xq[nq];  // position where to compute the quantiles in [0,1]
   Double_t yq[nq];  // array to contain the quantiles
   for (Int_t i=0;i<nq;i++) xq[i] = Float_t(i+1)/nq;

   TGraph *gr70 = new TGraph(nshots);
   TGraph *gr90 = new TGraph(nshots);
   TGraph *gr98 = new TGraph(nshots);
   TH1F *h = new TH1F("h","demo quantiles",500,-4,4);
   
   for (Int_t shot=0;shot<nshots;shot++) {
      h->FillRandom("gaus",50);
      h->GetQuantiles(nq,yq,xq);
      gr70->SetPoint(shot,shot+1,yq[70]);
      gr90->SetPoint(shot,shot+1,yq[90]);
      gr98->SetPoint(shot,shot+1,yq[98]);
   }
   
   //show the original histogram in the top pad
   TCanvas *c1 = new TCanvas("c1","demo quantiles",10,10,600,900);
   c1->SetFillColor(41);
   c1->Divide(1,3);
   c1->cd(1);
   h->SetFillColor(38);
   h->Draw();
   
   // show the final quantiles in the middle pad
   c1->cd(2);
   gPad->SetFrameFillColor(33);
   gPad->SetGrid();
   TGraph *gr = new TGraph(nq,xq,yq);
   gr->SetTitle("final quantiles");
   gr->SetMarkerStyle(21);
   gr->SetMarkerColor(kRed);
   gr->SetMarkerSize(0.3);
   gr->Draw("ap");
   
   // show the evolution of some  quantiles in the bottom pad
   c1->cd(3);
   gPad->SetFrameFillColor(17);
   gPad->DrawFrame(0,0,nshots+1,3.2);
   gPad->SetGrid();
   gr98->SetMarkerStyle(22);
   gr98->SetMarkerColor(kRed);
   gr98->Draw("lp");
   gr90->SetMarkerStyle(21);
   gr90->SetMarkerColor(kBlue);
   gr90->Draw("lp");
   gr70->SetMarkerStyle(20);
   gr70->SetMarkerColor(kMagenta);
   gr70->Draw("lp");
   // add a legend
   TLegend *legend = new TLegend(0.85,0.74,0.95,0.95);
   legend->SetTextFont(72);
   legend->SetTextSize(0.05);
   legend->AddEntry(gr98," q98","lp");
   legend->AddEntry(gr90," q90","lp");
   legend->AddEntry(gr70," q70","lp");
   legend->Draw();
}
Ejemplo n.º 23
0
void pythia8(Int_t nev  = 100, Int_t ndeb = 1)
{
   const char *p8dataenv = gSystem->Getenv("PYTHIA8DATA");
   if (!p8dataenv) {
      const char *p8env = gSystem->Getenv("PYTHIA8");
      if (!p8env) {
         Error("pythia8.C",
               "Environment variable PYTHIA8 must contain path to pythia directory!");
         return;
      }
      TString p8d = p8env;
      p8d += "/xmldoc";
      gSystem->Setenv("PYTHIA8DATA", p8d);
   }

   const char* path = gSystem->ExpandPathName("$PYTHIA8DATA");
   if (gSystem->AccessPathName(path)) {
         Error("pythia8.C",
               "Environment variable PYTHIA8DATA must contain path to $PYTHIA8/xmldoc directory !");
      return;
   }

// Load libraries
#ifndef G__WIN32 // Pythia8 is a static library on Windows
   if (gSystem->Getenv("PYTHIA8")) {
      gSystem->Load("$PYTHIA8/lib/libpythia8");
   } else {
      gSystem->Load("libpythia8");
   }
#endif
   gSystem->Load("libEG");
   gSystem->Load("libEGPythia8");
// Histograms
   TH1F* etaH = new TH1F("etaH", "Pseudorapidity", 120, -12., 12.);
   TH1F* ptH  = new TH1F("ptH",  "pt",              50,   0., 10.);


// Array of particles
   TClonesArray* particles = new TClonesArray("TParticle", 1000);
// Create pythia8 object
   TPythia8* pythia8 = new TPythia8();

// Configure
   pythia8->ReadString("HardQCD:all = on");


// Initialize

   pythia8->Initialize(2212 /* p */, 2212 /* p */, 14000. /* TeV */);

// Event loop
   for (Int_t iev = 0; iev < nev; iev++) {
      pythia8->GenerateEvent();
      if (iev < ndeb) pythia8->EventListing();
      pythia8->ImportParticles(particles,"All");
      Int_t np = particles->GetEntriesFast();
// Particle loop
      for (Int_t ip = 0; ip < np; ip++) {
         TParticle* part = (TParticle*) particles->At(ip);
         Int_t ist = part->GetStatusCode();
         // Positive codes are final particles.
         if (ist <= 0) continue;
         Int_t pdg = part->GetPdgCode();
         Float_t charge = TDatabasePDG::Instance()->GetParticle(pdg)->Charge();
         if (charge == 0.) continue;
         Float_t eta = part->Eta();
         Float_t pt  = part->Pt();

         etaH->Fill(eta);
         if (pt > 0.) ptH->Fill(pt, 1./(2. * pt));
      }
   }

   pythia8->PrintStatistics();

   TCanvas* c1 = new TCanvas("c1","Pythia8 test example",800,800);
   c1->Divide(1, 2);
   c1->cd(1);
   etaH->Scale(5./Float_t(nev));
   etaH->Draw();
   etaH->SetXTitle("#eta");
   etaH->SetYTitle("dN/d#eta");

   c1->cd(2);
   gPad->SetLogy();
   ptH->Scale(5./Float_t(nev));
   ptH->Draw();
   ptH->SetXTitle("p_{t} [GeV/c]");
   ptH->SetYTitle("dN/dp_{t}^{2} [GeV/c]^{-2}");
 }
Ejemplo n.º 24
0
void applyBDT(std::string iName="/mnt/hscratch/dabercro/skims2/BDT_Signal.root",
              TString inputVariables = "trainingVars.txt",
              TString inputTree = "DMSTree",
              std::string iWeightFile="weights/TMVAClassificationCategory_BDT_simple_alpha.weights.xml",
              TString outName = "Output.root",
              TString fOutputName = "TMVA.root",
              TString fMethodName = "BDT",
              TString fUniformVariable = "fjet1MassTrimmed",
              TString fWeight = "f**k",
              Int_t NumBins = 10, Double_t VarMin = 10, Double_t VarMax = 190, Int_t NumMapPoints = 501) {

  Double_t binWidth = (VarMax - VarMin)/NumBins;
  Double_t VarVals[NumBins+1];
  for (Int_t i0 = 0; i0 < NumBins + 1; i0++)
    VarVals[i0] = VarMin + i0 * binWidth;

  std::vector<TGraph*> transformGraphs;
  TGraph *tempGraph;

  if (fUniformVariable != "") {
    // First scale the BDT to be uniform
    // Make the background shape

    TFile *TMVAFile = TFile::Open(fOutputName);
    TTree *BackgroundTree = (TTree*) TMVAFile->Get("TrainTree");

    mithep::PlotHists *HistPlotter = new mithep::PlotHists();
    HistPlotter->SetDefaultTree(BackgroundTree);
    HistPlotter->SetDefaultExpr(fMethodName);

    Double_t binWidth = 2.0/(NumMapPoints - 1);
    Double_t BDTBins[NumMapPoints];
    for (Int_t i0 = 0; i0 < NumMapPoints; i0++)
      BDTBins[i0] = i0 * binWidth - 1;

    for (Int_t iVarBin = 0; iVarBin < NumBins; iVarBin++) {
      TString BinCut = TString::Format("%s*(%s>=%f&&%s<%f)", fWeight.Data(),
                                       fUniformVariable.Data(), VarVals[iVarBin],
                                       fUniformVariable.Data(), VarVals[iVarBin+1]);
      HistPlotter->AddWeight(fWeight + TString("*(classID == 1 && ") + BinCut + ")");
    }

    std::vector<TH1D*> BDTHists = HistPlotter->MakeHists(NumMapPoints,-1,1);

    for (Int_t iVarBin = 0; iVarBin < NumBins; iVarBin++) {
      tempGraph = new TGraph(NumMapPoints);
      transformGraphs.push_back(tempGraph);
      Double_t FullIntegral = BDTHists[iVarBin]->Integral();
      for (Int_t iMapPoint = 0; iMapPoint < NumMapPoints; iMapPoint++) {
        transformGraphs[iVarBin]->SetPoint(iMapPoint, BDTBins[iMapPoint],
                                           BDTHists[iVarBin]->Integral(0,iMapPoint)/FullIntegral);
      }
    }

    for (UInt_t iHist = 0; iHist < BDTHists.size(); iHist++)
      delete BDTHists[iHist];

    TMVAFile->Close();
  }

  TMVA::Tools::Instance();
  TMVA::Reader *reader = new TMVA::Reader( "!Color:!Silent" );    

  TString BDTName;
  ifstream configFile;
  configFile.open(inputVariables.Data());
  TString tempFormula;

  std::vector<float> Evaluated;
  std::vector<TString> Strings;
  TTreeFormula *Formulas[40];
  
  configFile >> BDTName;  // Is the name of the BDT

  while(!configFile.eof()){
    configFile >> tempFormula;
    if(tempFormula != ""){
      Evaluated.push_back(0.);
      Strings.push_back(tempFormula);
    }
  }
  
  TFile *lFile = new TFile(iName.c_str());
  TTree *lTree = (TTree*) lFile->FindObjectAny(inputTree);

  if(lTree->GetBranch(BDTName) == NULL){

    for(unsigned int i0 = 0;i0 < Strings.size();i0++){
      if (i0 == 0)
        reader->AddSpectator(Strings[i0],&Evaluated[i0]);
      else
        reader->AddVariable(Strings[i0],&Evaluated[i0]);
      Formulas[i0] = new TTreeFormula(Strings[i0],Strings[i0],lTree);
    }
    
    std::string lJetName = "BDT";
    reader->BookMVA(lJetName .c_str(),iWeightFile.c_str());
    
    int lNEvents = lTree->GetEntries();
    TFile *lOFile = new TFile(outName,"RECREATE");
    TTree *lOTree = new TTree(inputTree,inputTree);
    float lMVA    = 0; lOTree->Branch(BDTName,&lMVA ,BDTName+TString("/F"));
    for (Long64_t i0=0; i0<lNEvents;i0++) {
      if (i0 % 10000 == 0) std::cout << "--- ... Processing event: " << double(i0)/double(lNEvents) << std::endl;
      lTree->GetEntry(i0);
      for(unsigned int i1 = 0;i1 < Strings.size();i1++){
        Evaluated[i1] = Formulas[i1]->EvalInstance();
      }
      
      lMVA      = float(reader->EvaluateMVA(lJetName.c_str()));

      if (fUniformVariable != "") {
        if (Evaluated[0] >= VarVals[0] && Evaluated[0] < VarVals[NumBins]) {
          for (Int_t iBin = 0; iBin < NumBins; iBin++) {
            if (Evaluated[0] < VarVals[iBin + 1]) {
              lMVA = Float_t(transformGraphs[iBin]->Eval(lMVA));
              break;
            }
          }
        }
      }

      lOTree->Fill();
    }
    lOTree->Write();
    lOFile->Close();
  }
  else std::cout << "Skipping " << iName.c_str() << std::endl;
  delete reader;

  for (UInt_t iGraph = 0; iGraph < transformGraphs.size(); iGraph++)
    delete transformGraphs[iGraph];
}