]> git.uio.no Git - u/mrichter/AliRoot.git/blob - PWG1/background/AliAnalysisTaskBGvsTime.cxx
Additional forward declaration
[u/mrichter/AliRoot.git] / PWG1 / background / AliAnalysisTaskBGvsTime.cxx
1 // AliAnalysisTaskBGvsTime
2
3 // This task computes various histos as a function of time, using a
4 // time stamp made from orbit, bx number and period. It is used for
5 // studies of BG vs time and of luminosity.
6
7 // The histograms are booked dinamically when they are called the
8 // first time. This simplifies the handling of different trigger
9 // classes (you don't need to know them in advance). The merging is
10 // then complicated, but it is handled via the external class
11 // AliHistoListWrapper.
12
13 // Different sets of cuts can be used, and the binning of vs time
14 // histos can be defined dynamically (see setters)
15
16 // Can also process MC, in which case the efficiency x acceptance for
17 // tracks used in the rate (luminosity) histos is also computed, and
18 // put in a histo in which each bin corresponds to a given rate histo
19 // (eta < 0.8 and pt > 0.5 or pt > 1.0 at the time I'm writing this).
20
21 // The rates are corrected for the dead time, computed using trigger
22 // scalers. WARNING: the dead time computation will NOT WORK on CAF
23 // (it assumes consecutive events).
24
25 // Author: Michele Floris, CERN
26
27 #include "AliAnalysisTaskBGvsTime.h"
28 #include "AliESDInputHandler.h"
29 #include "TString.h"
30 #include "AliVParticle.h"
31 #include "AliESDInputHandlerRP.h"
32 #include "TTree.h"
33 #include "TClonesArray.h"
34 #include "TBranch.h"
35 //#include "AliITSRecPoint.h"
36 #include "AliMultiplicity.h"
37 #include "AliLog.h"
38 #include "AliAnalysisManager.h"
39 #include "AliBackgroundSelection.h"
40 #include <iostream>
41 #include "TFile.h"
42 #include "TCanvas.h"
43 #include "AliHistoListWrapper.h"
44 #include "AliTriggerAnalysis.h"
45 #include "TMath.h"
46 #include "AliPhysicsSelection.h"
47 #include "AliBackgroundSelection.h"
48 #include "AliESDtrackCuts.h"
49 #include "AliStack.h"
50 #include "AliMCEvent.h"
51 #include "TDatime.h"
52
53 using namespace std;
54
55 ClassImp(AliAnalysisTaskBGvsTime)
56
57
58
59 AliAnalysisTaskBGvsTime::AliAnalysisTaskBGvsTime()
60   : AliAnalysisTaskSE("TaskBGvsTime"),
61     fESD(0),fListHisto(0),fListWrapper(0),fStartTime(0),fEndTime(0),
62     fNMultBins(0), fMultBins(0),fFirstTimeStamp(0), fLastTimeStamp(0), fBinWidth(10), fNoCuts(0), fPhysicsSelection(0), fUsePhysicsSelection(0),
63     fUseZeroBin(0), fIsMC(0), fSkipV0(0), fSkipZeroBin(0), fUseBunchInt(0), fHistoTimeStampVsUTC(0), fHistoTimeStampDiffUTC(0)
64
65 {
66   // constructor
67
68   DefineOutput(1, AliHistoListWrapper::Class());
69   DefineOutput(2, AliPhysicsSelection::Class());
70   //  DefineOutput(2, TH1I::Class());
71
72 }
73 AliAnalysisTaskBGvsTime::AliAnalysisTaskBGvsTime(const char * name)
74   : AliAnalysisTaskSE(name),fESD (0),fListHisto(0),fListWrapper(0),fStartTime(0),fEndTime(0),
75     fNMultBins(0),fMultBins(0),fFirstTimeStamp(0), fLastTimeStamp(0), fBinWidth(10), fNoCuts(0), fPhysicsSelection(0), fUsePhysicsSelection(0),
76     fUseZeroBin(0), fIsMC(0), fSkipV0(0), fSkipZeroBin(0), fUseBunchInt(0), fHistoTimeStampVsUTC(0), fHistoTimeStampDiffUTC(0)
77 {
78   //
79   // Standard constructur which should be used
80   //
81
82   DefineOutput(1, AliHistoListWrapper::Class());
83   DefineOutput(2, AliPhysicsSelection::Class());
84   //  DefineOutput(2, TH1I::Class());
85
86 }
87
88 AliAnalysisTaskBGvsTime::AliAnalysisTaskBGvsTime(const AliAnalysisTaskBGvsTime& obj) : 
89   AliAnalysisTaskSE(obj) ,fESD (0),fListHisto(0),fListWrapper(0),fStartTime(0),fEndTime(0),
90   fNMultBins(0),fMultBins(0),fFirstTimeStamp(0), fLastTimeStamp(0), fBinWidth(10), fNoCuts(0), fPhysicsSelection(0), fUsePhysicsSelection(0),
91   fUseZeroBin(0), fIsMC(0), fSkipV0(0), fSkipZeroBin(0), fUseBunchInt(0), fHistoTimeStampVsUTC(0), fHistoTimeStampDiffUTC(0)
92 {
93   //copy ctor
94   fESD = obj.fESD ;
95   fListHisto= obj.fListHisto;
96   fListWrapper= obj.fListWrapper;
97   fStartTime= obj.fStartTime;
98   fEndTime= obj.fEndTime;
99   
100   fNMultBins= obj.fNMultBins;
101   fMultBins= obj.fMultBins;
102   fFirstTimeStamp= obj.fFirstTimeStamp;
103   fLastTimeStamp= obj.fLastTimeStamp;
104   fBinWidth= obj.fBinWidth;
105   fNoCuts= obj.fNoCuts;
106   fPhysicsSelection= obj.fPhysicsSelection;
107   fUsePhysicsSelection= obj.fUsePhysicsSelection;
108   fUseZeroBin= obj.fUseZeroBin;
109   fIsMC= obj.fIsMC;
110   fSkipV0= obj.fSkipV0;
111   fSkipZeroBin= obj.fSkipZeroBin;
112   fUseBunchInt= obj.fUseBunchInt;
113   fHistoTimeStampVsUTC = obj.fHistoTimeStampVsUTC;
114   fHistoTimeStampDiffUTC = obj.fHistoTimeStampDiffUTC;
115
116 }
117
118 AliAnalysisTaskBGvsTime::~AliAnalysisTaskBGvsTime(){
119
120   // destructor
121   if(fListWrapper) {
122     delete fListWrapper;
123     fListWrapper = 0;
124   }
125   if(fMultBins) {
126     delete fMultBins;
127     fMultBins = 0;
128   }
129   if(fPhysicsSelection) {
130     delete fPhysicsSelection;
131     fPhysicsSelection = 0;
132   }
133   // Histos should not be destroyed: fListWrapper is owner!
134 }
135 void AliAnalysisTaskBGvsTime::UserCreateOutputObjects()
136 {
137   // Called once
138   fListWrapper = new AliHistoListWrapper("histoListWrapper","histoListWrapper");
139   fListHisto = fListWrapper->GetList();
140   Float_t lenght =  fEndTime - fStartTime;
141   Int_t nBins = TMath::FloorNint(lenght/fBinWidth)+1;
142   Int_t end   = nBins*fBinWidth;
143   // cover 20 days in UTC. I'll set offset by hand below.  
144   Int_t lenghtUTC = 20*3600*24;
145   Int_t nBinsUTC = TMath::FloorNint(Double_t(lenghtUTC)/fBinWidth)+1;
146   Int_t endUTC   = nBinsUTC*fBinWidth;  
147   if (!fIsMC) {
148     Bool_t oldStatus = TH1::AddDirectoryStatus();
149     TH1::AddDirectory(kFALSE);
150     fHistoTimeStampVsUTC = new TH2F ("fHistoTimeStampVsUTC", "fHistoTimeStampVsUTC", nBins, -0.5, end-0.5,  nBinsUTC, -0.5, endUTC-0.5);
151     fListHisto->Add(fHistoTimeStampVsUTC);
152     fHistoTimeStampDiffUTC = new TH1F("fHistoTimeStampDiffUTC", "fHistoTimeStampDiffUTC", nBinsUTC, -0.5, endUTC-0.5);
153     fListHisto->Add(fHistoTimeStampDiffUTC);
154     TH1::AddDirectory(oldStatus);
155   }
156   
157   fPhysicsSelection = new AliPhysicsSelection();
158   fPhysicsSelection->SetUseBXNumbers();
159   if(fIsMC) fPhysicsSelection->SetAnalyzeMC();
160   fPhysicsSelection->SetBin0Callback(this->GetName());
161
162   fPhysicsSelection->SetSkipTriggerClassSelection();// 
163
164   AliBackgroundSelection * bg = new AliBackgroundSelection();
165   bg->SetDeltaPhiCut(10);
166   fPhysicsSelection->AddBackgroundIdentification(bg);
167
168   if (fSkipV0) {
169     fPhysicsSelection->SetSkipV0();
170   }
171
172 }
173
174
175 void AliAnalysisTaskBGvsTime::UserExec(Option_t *)
176 {
177
178   /* PostData(0) is taken care of by AliAnalysisTaskSE */
179   PostData(1,fListWrapper);
180   PostData(2,fPhysicsSelection);
181   
182
183   const float etaCut = 0.8;
184
185
186   fESD = dynamic_cast<AliESDEvent*>(fInputEvent);
187   if (strcmp(fESD->ClassName(),"AliESDEvent")) {
188     AliFatal("Not processing ESDs");
189   }
190
191   if (fUseBunchInt) {
192     fPhysicsSelection->SetComputeBG();
193   }
194
195   // Get V0 flags and trigger flags
196   static AliTriggerAnalysis * triggerAnalysis = new AliTriggerAnalysis();
197   Bool_t v0A   = triggerAnalysis->IsOfflineTriggerFired(fESD, AliTriggerAnalysis::kV0A);
198   Bool_t v0C   = triggerAnalysis->IsOfflineTriggerFired(fESD, AliTriggerAnalysis::kV0C);
199   Bool_t v0ABG = triggerAnalysis->IsOfflineTriggerFired(fESD, AliTriggerAnalysis::kV0ABG);
200   Bool_t v0CBG = triggerAnalysis->IsOfflineTriggerFired(fESD, AliTriggerAnalysis::kV0CBG);
201   Bool_t mb1Offline = triggerAnalysis->IsOfflineTriggerFired(fESD, AliTriggerAnalysis::kMB1);
202   Bool_t isInV0 = !v0ABG && !v0CBG && ((v0A && !v0C) || (v0C && !v0A)); // try to select beam gas in CINT1A/C events: require one v0 interaction (but not the other) and not BG hit in v0. This should select events produced in between the 2 v0s and boosted forward.
203
204
205   // If it is MC: fill histo of generated events for efficiency calculations
206   if (fIsMC) {
207     Bool_t atLeastPt1MC  = kFALSE; 
208     Bool_t atLeastPt05MC = kFALSE; 
209
210     if (!fMCEvent) {
211       AliError("No MC info found");
212     } else {
213       
214       //loop on the MC event
215       for (Int_t ipart=0; ipart<fMCEvent->GetNumberOfTracks(); ipart++) { 
216         AliMCParticle *mcPart  = (AliMCParticle*)fMCEvent->GetTrack(ipart);
217         
218         // We don't care about neutrals and non-physical primaries
219         if(mcPart->Charge() == 0) continue;
220         if(!fMCEvent->Stack()->IsPhysicalPrimary(ipart)) continue;
221         
222         // Kinematic cuts:
223         if (TMath::Abs(mcPart->Eta()) < etaCut) {
224           if (mcPart->Pt() > 0.5) atLeastPt05MC  = kTRUE; 
225           if (mcPart->Pt() > 1.0) atLeastPt1MC   = kTRUE; 
226         }
227         if (atLeastPt1MC && atLeastPt05MC) break; // no need to look for other tracks
228       }
229       if (atLeastPt1MC ) {
230         GetEfficiencyHisto(kEffStepGen)->Fill(kEffPt1);    
231         if(mb1Offline) GetEfficiencyHisto(kEffStepTrig)->Fill(kEffPt1);    
232       }
233       if (atLeastPt05MC) {
234         GetEfficiencyHisto(kEffStepGen)->Fill(kEffPt05 );     
235         if(mb1Offline) GetEfficiencyHisto(kEffStepTrig)->Fill(kEffPt05);    
236       }
237     }
238   }
239   
240
241
242
243   // CUTS
244   const AliMultiplicity* mult = fESD->GetMultiplicity();
245   if (!mult){
246     AliFatal("No multiplicity object"); // TODO: Should this be fatal?
247   }
248   // get number of SPD clusters
249   Int_t spdClusters = 0;
250   for(Int_t ilayer = 0; ilayer < 2; ilayer++){
251     spdClusters += mult->GetNumberOfITSClusters(ilayer);
252   }
253
254   //  Bool_t isZeroBin = kFALSE;
255   Bool_t isZeroBin = IsEventInBinZero();
256   if(fUseZeroBin  && !isZeroBin) return;
257   if(fSkipZeroBin && isZeroBin ) return;
258
259   Bool_t physelDecision = fPhysicsSelection->IsCollisionCandidate(fESD);
260
261   if (fUsePhysicsSelection) {
262     if(!physelDecision) return;
263   }
264   else if (!fNoCuts) {if (spdClusters < 2) return;}// At least 2 clusters 
265   //  else {AliInfo("No Cuts");}  
266   
267   
268
269   // get time stamp
270   Long64_t timeStampBX = 0;
271   timeStampBX = fESD->GetBunchCrossNumber();
272   timeStampBX += (Long64_t) 3564 * (fESD->GetOrbitNumber() + fESD->GetPeriodNumber() * 16777216);
273   timeStampBX = (Long64_t) (25e-9 * timeStampBX);
274   if (fFirstTimeStamp == 0) {
275     fFirstTimeStamp = timeStampBX;   
276     fLastTimeStamp  = timeStampBX;   
277   } 
278   if (timeStampBX < fFirstTimeStamp) {
279     AliError("Time stamp not monothonic!");
280     fFirstTimeStamp = timeStampBX;
281   }
282   if (timeStampBX > fLastTimeStamp) {
283     fLastTimeStamp = timeStampBX;
284   }
285   timeStampBX -= fStartTime;
286
287   Long64_t timeStamp = timeStampBX;
288
289   Long64_t timeStampGDC = fESD->GetTimeStamp();  
290
291   static TDatime timeOffsetDT(2009,12,5,0,0,0);
292   static Long64_t timeOffset = timeOffsetDT.Convert();
293
294
295
296   // Get trigger scalers for dead time calculation (only data)
297   // Only CINT1B (at least for the time being)
298   AliESDHeader* esdheader = (AliESDHeader*)fESD->GetHeader();
299   static ULong64_t L0 = 0;
300   static ULong64_t L2 = 0;
301   if (fESD->IsTriggerClassFired("CINT1B-ABCE-NOPF-ALL")&&!fIsMC) {
302     AliTriggerScalersRecordESD* scalrecord = (AliTriggerScalersRecordESD*)esdheader->GetTriggerScalersRecord();
303     const AliTriggerScalersESD* scalers = scalrecord->GetTriggerScalersForClass(2); //2 is the cint1b class index in the trigger mask
304     L0 = scalers->GetLOCB(); //L0 before any vetos
305     L2 = scalers->GetL2CA(); //L2 after vetos
306   } 
307
308
309   // loop over trigger classes in the event
310   TObjArray * tokens = 0;
311   if(fIsMC) {
312     // in case of montecarlo I override the trigger class to CINT1B for latter compatibility
313     tokens = new TObjArray;
314     tokens->SetOwner();
315     tokens->Add(new TObjString("CINT1B-ABCE-NOPF-ALL")); 
316   }
317   else {  
318     TString trgClasses = fESD->GetFiredTriggerClasses();
319     tokens = trgClasses.Tokenize(" ");
320   }
321   TIter iter(tokens);
322     
323   while(TObjString * tok = (TObjString*) iter.Next()){
324     // clean up trigger name
325     TString trg = tok->GetString();
326     trg.Strip(TString::kTrailing, ' ');
327     trg.Strip(TString::kLeading, ' ');
328     // print selected events in !CIN1B trigs:
329     //    if(!trg.Contains("CINT1B")) 
330 //       Printf("File: %s, IEV: %d, TRG: %s, Orbit: 0x%x, Period: %d, BC: %d\n",
331 //                                     ((TTree*) GetInputData(0))->GetCurrentFile()->GetName(), fESD->GetEventNumberInFile(), 
332 //                                     trg.Data(),
333 //                                     fESD->GetOrbitNumber(),fESD->GetPeriodNumber(),fESD->GetBunchCrossNumber());
334
335
336
337     // Fill histos
338     GetVsTimeHistoAll(trg.Data())->Fill(timeStamp);
339     GetVsTimeHisto(trg.Data(),spdClusters,fESD->GetBunchCrossNumber(),"ALL")->Fill(timeStamp);
340     GetVsTimeHisto(trg.Data(),-1,         fESD->GetBunchCrossNumber(),"ALL")->Fill(timeStamp);
341     GetVsTimeHisto(trg.Data(),spdClusters,-1,                         "ALL")->Fill(timeStamp);
342     GetVsTimeHisto(trg.Data(),-1         ,-1,                         "ALL")->Fill(timeStamp);
343     if (isInV0)     {
344       GetVsTimeHisto(trg.Data(),spdClusters,fESD->GetBunchCrossNumber(),"inV0")->Fill(timeStamp);
345       GetVsTimeHisto(trg.Data(),-1         ,fESD->GetBunchCrossNumber(),"inV0")->Fill(timeStamp);
346       GetVsTimeHisto(trg.Data(),-1         ,-1,                         "inV0")->Fill(timeStamp);
347     }      
348
349     // In order to compute mean multiplicity of spd clusters in a time
350     // bin, we integrate the multiplicity in that bin, and then we
351     // divide for the number of events in that bin in terminate.
352     
353     // Is the error computed correctly if we fill with a weight ? Looping to be sure...
354     for (Int_t iclus = 0; iclus < spdClusters; iclus ++)  { 
355       GetVsTimeHisto((TString("hMultSPDvsTime_")+trg).Data())->Fill(timeStamp);
356       GetVsTimeHisto(trg.Data(),-1,         fESD->GetBunchCrossNumber(),"ALL","MultSPDvsTime")->Fill(timeStamp);
357       GetVsTimeHisto(trg.Data(),spdClusters,fESD->GetBunchCrossNumber(),"ALL","MultSPDvsTime")->Fill(timeStamp);
358       GetVsTimeHisto(trg.Data(),spdClusters,-1,                         "ALL","MultSPDvsTime")->Fill(timeStamp);
359       GetVsTimeHisto(trg.Data(),-1,-1,                                  "ALL","MultSPDvsTime")->Fill(timeStamp);
360       if (isInV0)     {
361         GetVsTimeHisto(trg.Data(),-1,         fESD->GetBunchCrossNumber(),"inV0","MultSPDvsTime")->Fill(timeStamp);
362         GetVsTimeHisto(trg.Data(),spdClusters,fESD->GetBunchCrossNumber(),"inV0","MultSPDvsTime")->Fill(timeStamp);
363         GetVsTimeHisto(trg.Data(),-1,-1,                                  "inV0","MultSPDvsTime")->Fill(timeStamp);
364       }
365
366     }
367
368     // Keep cluster distribution for reference
369     GetDistributionHisto(trg.Data(),kDistSPDMult)->Fill(spdClusters);
370     if(isInV0) GetDistributionHisto(trg.Data(),kDistSPDMult,"_inV0")->Fill(spdClusters);
371     
372     // Distribution of hits per its layer:
373     for(Int_t ilayer = 0; ilayer < 6; ilayer++){
374       GetDistributionHisto(trg.Data(),kDistClsITSLayer)->Fill(ilayer,mult->GetNumberOfITSClusters(ilayer));// fill weighting with the number of CLS
375     }
376
377
378     // Dead time vs time stamp & time offset
379     // WARNING THIS WON'T WORK ON CAF, NOR GRID: REDO IT WITH A NEW MERGEABLE OBJECT
380     if (trg=="CINT1B-ABCE-NOPF-ALL"&&!fIsMC) {
381
382       // Fill time difference histos (only for CINt1B)
383       if (!fIsMC) {
384         fHistoTimeStampVsUTC->Fill(timeStampBX,timeStampGDC-timeOffset);
385         fHistoTimeStampDiffUTC->Fill(timeStampGDC-timeOffset-timeStampBX);
386       }
387
388       static ULong64_t oldL0   = 0;  // L0 counts at the beginning of this bin
389       static ULong64_t oldL2   = 0;  // L2 counts at the beginning of this bin
390       static ULong64_t prevL0   = 0; // L0 counts in the previous event
391       static ULong64_t prevL2   = 0; // L2 counts in the previous event
392
393       static ULong64_t oldTime = 0;  // time stamp at the beginning of this bin
394       //      static ULong64_t previousTime; // timestamp in the previous event
395
396       static Int_t prevbin = -1; // bin in the previous event
397
398       Int_t bin = GetDeadTimeHisto(trg.Data())->FindBin(timeStamp);
399
400       if (prevbin == -1) { // first event
401         prevbin = bin;
402         oldL0  = L0;
403         oldL2  = L2;
404         oldTime = timeStamp;
405
406       } else if (prevbin != bin) {
407         // New bin: let's fill the previous one
408         Double_t dL0 = Double_t(prevL0 - oldL0);
409         Double_t dL2 = Double_t(prevL2 - oldL2);
410
411         //      Double_t deadtime  =  Double_t(1 - dL2/dL0); // interested in relative fraction of dead time
412         Double_t deadtime  =  Double_t(dL2/dL0); // interested in relative fraction of dead time
413         Double_t edeadtime = TMath::Sqrt(dL2*(dL0-dL2)/dL0/dL0/dL0); // Binomial error
414
415 //      cout << "DEADTIME " << endl;
416 //      cout << L0 << " " << dL0 << " " << oldL0 << " " << prevL0 << endl;
417 //      cout << L2 << " " << dL2 << " " << oldL2 << " " << prevL2 << endl;
418 //      cout << deadtime << endl;
419         
420
421         GetDeadTimeHisto(trg.Data())->SetBinContent(prevbin, deadtime );
422         GetDeadTimeHisto(trg.Data())->SetBinError  (prevbin, edeadtime);
423         
424         oldL0  = L0;
425         oldL2  = L2;
426         oldTime = timeStamp;    
427
428       }
429       prevbin = bin;
430       prevL0  = L0;
431       prevL2  = L2;
432         
433     }
434
435     // TPC track multiplicity vs time
436
437     // Selection by andrea.dainese@pd.infn.it
438     // 15.03.2010
439     
440
441     // Primary vertex
442     Bool_t badVertex = kFALSE;
443     const AliESDVertex *vertex = fESD->GetPrimaryVertexTracks();
444     if(vertex->GetNContributors()<1) {
445       // SPD vertex
446       vertex = fESD->GetPrimaryVertexSPD();
447       if(vertex->GetNContributors()<1) {
448         badVertex = kTRUE;
449       }
450     }
451     
452     // Fill vertex distribution 
453     if ( ((vertex->IsFromVertexerZ() && vertex->GetDispersion()<=0.02) || !vertex->IsFromVertexerZ()) && !badVertex ) {
454       GetDistributionHisto(trg.Data(),kDistVertex)->Fill(vertex->GetZ());       
455       if (vertex->IsFromVertexerZ()) GetDistributionHisto(trg.Data(),kDistVertexZ) ->Fill(vertex->GetZ());      
456       else                           GetDistributionHisto(trg.Data(),kDistVertex3D)->Fill(vertex->GetZ());      
457         
458       if(isInV0) GetDistributionHisto(trg.Data(),kDistVertex,"_inV0")->Fill(vertex->GetZ());
459     }
460
461     // apply a cut |zVertex| < CUT, if needed
462     
463     // Track cuts (except d0 cut)
464     //------- TPC track selection --------
465     // Selection by andrea.dainese@pd.infn.it
466     // 15.03.2010
467     
468     Bool_t selectPrimaries=kTRUE;
469     static AliESDtrackCuts* esdtrackCutsITSTPC = AliESDtrackCuts::GetStandardITSTPCTrackCuts2009(selectPrimaries);
470
471     // loop on tracks
472     Int_t ntracks = fESD->GetNumberOfTracks();
473     if(badVertex) ntracks = -1; // skip loop if the vertex is bad
474     
475     // flags for luminosity histos
476     Bool_t atLeastPt1  = kFALSE;
477     Bool_t atLeastPt05 = kFALSE; 
478    
479     for (Int_t iTrack = 0; iTrack<ntracks; iTrack++) {    
480       AliESDtrack * track = dynamic_cast<AliESDtrack*>(fESD->GetTrack(iTrack));
481       // for each track
482       
483       // track quality cuts
484       if(!esdtrackCutsITSTPC->AcceptTrack(track)) continue;
485       
486       // bring it to the primary vertex and compute impact parameters
487       if(!track->RelateToVertex(vertex,fESD->GetMagneticField(),kVeryBig)) continue; // this is already done in AliReconstruction...
488       
489       // track-to-vertex cut (see below)
490       if(!SelectOnImpPar(track)) continue;
491       
492       // Fill histos (TPC Multiplicity vs TIME)
493       GetVsTimeHisto(trg.Data(),-1,         fESD->GetBunchCrossNumber(),"ALL","MultTPCvsTime")->Fill(timeStamp);
494       GetVsTimeHisto(trg.Data(),spdClusters,fESD->GetBunchCrossNumber(),"ALL","MultTPCvsTime")->Fill(timeStamp);
495       GetVsTimeHisto(trg.Data(),spdClusters,-1,                         "ALL","MultTPCvsTime")->Fill(timeStamp);
496       GetVsTimeHisto(trg.Data(),-1,-1,                                  "ALL","MultTPCvsTime")->Fill(timeStamp);
497       if ((v0A || v0C) && !(v0ABG || v0CBG))     {
498         GetVsTimeHisto(trg.Data(),-1,         fESD->GetBunchCrossNumber(),"inV0","MultTPCvsTime")->Fill(timeStamp);
499         GetVsTimeHisto(trg.Data(),spdClusters,fESD->GetBunchCrossNumber(),"inV0","MultTPCvsTime")->Fill(timeStamp);
500         GetVsTimeHisto(trg.Data(),-1,-1,                                  "inV0","MultTPCvsTime")->Fill(timeStamp);
501       }
502       
503
504       // has the event at least one track satisfying the required conditions? (used for rate/luminosity)
505       if (TMath::Abs(track->Eta()) < etaCut) {
506         // Fill histo (pt distribution with standard cuts)
507         GetDistributionHisto(trg.Data(),kDistPt)->Fill(track->Pt());
508         if (track->Pt() > 0.5) {
509           atLeastPt05 = kTRUE;
510         }
511         if (track->Pt() > 1.0) {
512           atLeastPt1  = kTRUE;
513         }
514       }
515     }
516
517     // TEMPORARY LOOP: FILL DISTRIBUTION OF PT FOR 2 CLASSES OF EVENTS
518     for (Int_t iTrack = 0; iTrack<ntracks; iTrack++) {    
519       AliESDtrack * track = dynamic_cast<AliESDtrack*>(fESD->GetTrack(iTrack));
520       // for each track
521       
522       // track quality cuts
523       if(!esdtrackCutsITSTPC->AcceptTrack(track)) continue;
524       
525       // bring it to the primary vertex and compute impact parameters
526       if(!track->RelateToVertex(vertex,fESD->GetMagneticField(),kVeryBig)) continue; // this is already done in AliReconstruction...
527       
528       // track-to-vertex cut (see below)
529       if(!SelectOnImpPar(track)) continue;
530       if (TMath::Abs(track->Eta()) < etaCut){
531         if (atLeastPt05) GetDistributionHisto(trg.Data(),kDistPt, "_atLeast05")->Fill(track->Pt());
532         if (atLeastPt1)  GetDistributionHisto(trg.Data(),kDistPt, "_atLeast1" )->Fill(track->Pt());
533       }
534     }
535     // END OF TEMPORARY LOOP
536
537     // Fill histos for luminosity: rate of events with at least one
538     // track in the pseudo rapidity region |eta| < 0.8 and pt > 0.5 or
539     // 1 GeV
540     if (atLeastPt05) {
541       GetVsTimeHisto(GetVsTimeHistoForLuminosityName(trg.Data(), 0.5))->Fill(timeStamp);
542       if(fIsMC) GetEfficiencyHisto(kEffStepRec)->Fill(kEffPt05);
543     }
544     if (atLeastPt1)  {
545       
546       if(GetVsTimeHisto(GetVsTimeHistoForLuminosityName(trg.Data(), 1.0))->Fill(timeStamp) < 0) {
547         AliWarning(Form("Timestamp out of range %lld", timeStamp));
548       };
549       if(fIsMC) GetEfficiencyHisto(kEffStepRec)->Fill(kEffPt1);
550     }
551     
552
553     // TPC TRACKS: loose selection in order to keep some BG track
554     ntracks = fESD->GetNumberOfTracks(); // Ignore vertex selecion
555     for(Int_t itrack = 0; itrack < ntracks; itrack++){
556       AliESDtrack * track = dynamic_cast<AliESDtrack*>(fESD->GetTrack(itrack));
557       // for each track
558       // Same as AliESDtrackCuts::GetStandardTPCOnlyTrackCuts() , but not using DCA cut
559       
560       AliESDtrackCuts* esdTrackCuts = new AliESDtrackCuts;
561       
562       esdTrackCuts->SetMinNClustersTPC(50);
563       esdTrackCuts->SetMaxChi2PerClusterTPC(4);
564       esdTrackCuts->SetAcceptKinkDaughters(kFALSE);
565       
566 //       esdTrackCuts->SetMaxDCAToVertexZ(3.2);
567 //       esdTrackCuts->SetMaxDCAToVertexXY(2.4);
568 //       esdTrackCuts->SetDCAToVertex2D(kTRUE);
569        
570       if (!esdTrackCuts->AcceptTrack(track)) continue;
571       // Fill pt and DCA distribution
572       // pt
573       GetDistributionHisto(trg.Data(),kDistPtLoose)->Fill(track->Pt());
574       if(isInV0) GetDistributionHisto(trg.Data(),kDistPtLoose, "_inV0")->Fill(track->Pt());
575       // dca (on the xy plane)
576       Float_t xy_dca, z_dca;
577       track->GetImpactParameters(xy_dca,z_dca);
578       GetDistributionHisto(trg.Data(),kDistDCATPC)->Fill(xy_dca);
579       if(isInV0) GetDistributionHisto(trg.Data(),kDistDCATPC, "_inV0")->Fill(track->Pt());
580
581     }
582     
583     
584   }
585
586 }
587
588 void   AliAnalysisTaskBGvsTime::Terminate(Option_t *){
589
590   // normalize and rescale histos
591   AliInfo("Normalizing multiplicity histo") ;
592   
593   fListWrapper = dynamic_cast<AliHistoListWrapper*> (GetOutputData(1));
594   if (!fListWrapper){
595     AliError("Cannot get list wrapper");
596   }
597   fListHisto = fListWrapper->GetList();
598   fHistoTimeStampDiffUTC = (TH1F*) fListHisto->FindObject("fHistoTimeStampDiffUTC");
599   fHistoTimeStampVsUTC   = (TH2F*) fListHisto->FindObject("fHistoTimeStampVsUTC");
600   
601   // Divide rate histos for the number of events
602   TIterator * iter = fListHisto->MakeIterator();
603   TH1 * h = 0;
604   while ((h = (TH1*) iter->Next())) {
605     if((TString(h->GetName())).Contains("hMultSPDvsTime_") || 
606        (TString(h->GetName())).Contains("hMultTPCvsTime_") 
607        ){
608          
609       AliInfo(Form("Normalizing %s",h->GetName()));
610       //      continue;
611       TString histoname = h->GetName();
612       histoname.ReplaceAll("MultSPDvsTime","");
613       histoname.ReplaceAll("MultTPCvsTime","");
614
615       TH1* hev = (TH1*)fListHisto->FindObject(histoname.Data());
616       if(!hev) {
617         AliError(Form(" -> Cannot find events histo %s",histoname.Data()));
618         continue;
619       }
620       AliInfo (Form(" with histo %s",hev->GetName()));
621       // Errors on ev num should be ignored in the division
622       Int_t nbin  = h->GetNbinsX();
623       for(Int_t ibin = 1; ibin <=nbin; ibin++) {
624         if(hev->GetBinContent(ibin) != 0) {
625           h->SetBinContent(ibin, h->GetBinContent(ibin)/ hev->GetBinContent(ibin));
626           h->SetBinError  (ibin, h->GetBinError(ibin)  / hev->GetBinContent(ibin));
627         }
628       }
629     }
630     if((TString(h->GetName())).Contains("hRate")){
631       h->Scale(1.,"width"); // divide for bin width to obtain a rate
632     }
633   }
634
635   // Compute Efficiency:
636   if(fIsMC) {
637     TH1F* hgen =(TH1F*) fListHisto->FindObject("hEffGen");
638     TH1F* htrg =(TH1F*) fListHisto->FindObject("hEffTrig");
639     TH1F* hrec =(TH1F*) fListHisto->FindObject("hEffRec");
640     if (!hgen || !hrec || !htrg) {
641       AliError("Cannot find eff histos");
642     }
643     else {
644       TH1F* heff = (TH1F*) fListHisto->FindObject("hEffRatio");
645       TH1F* hefftrg = (TH1F*) fListHisto->FindObject("hEffRatioTrg");
646       if (heff) {
647         AliWarning("hEffRatio already in output list?");
648       }
649       else {
650         heff = (TH1F*) hgen->Clone("hEffRatio");
651       } 
652       heff->Reset();
653       heff->Divide(hrec,hgen,1,1,"B");
654       fListHisto->Add(heff);
655
656       if (hefftrg) {
657         AliWarning("hEffRatioTrg already in output list?");
658       }
659       else {
660         hefftrg = (TH1F*) hgen->Clone("hEffRatioTrg");
661       }
662       hefftrg->Reset();
663       hefftrg->Divide(htrg,hgen,1,1,"B");
664       fListHisto->Add(hefftrg);
665
666     }
667   }
668   
669
670   AliInfo(Form("Time interval: %lld -- %lld",fFirstTimeStamp,fLastTimeStamp)); 
671
672   AliInfo("Saving physics selection histos");
673   fPhysicsSelection = dynamic_cast<AliPhysicsSelection*> (GetOutputData(2));
674   
675   TFile* fout = new TFile("event_stat.root", "RECREATE");
676   
677   if (fPhysicsSelection)
678       {
679         fPhysicsSelection->Print();
680         fPhysicsSelection->SaveHistograms("physics_selection");
681       }
682   
683   fout->Write();
684   fout->Close();
685
686 }
687
688 TH1F * AliAnalysisTaskBGvsTime::BookVsTimeHisto(const char * name, const char * title){
689
690   // Book istograms vs time
691
692   AliInfo(Form("Booking histo %s",name));
693
694   Bool_t oldStatus = TH1::AddDirectoryStatus();
695   TH1::AddDirectory(kFALSE);
696
697   //  static Int_t nBins =  fEndTime - fStartTime + 1;
698   // Compute bin width and range.
699   // if time interval is not a multiple of bin width drop the last bin
700
701   Float_t lenght =  fEndTime - fStartTime;
702   Int_t nBins = TMath::FloorNint(lenght/fBinWidth)+1;
703   Float_t * bins = new Float_t[nBins+1];
704   for(Int_t ibin = 0; ibin <= nBins; ibin++){
705     Float_t edge = ibin*fBinWidth - 0.5;
706     bins[ibin] = edge < (lenght - 0.5) ? edge  : (lenght-0.5);
707   }
708   
709   //  Int_t end   = nBins*fBinWidth;
710
711   //  TH1F * h = new TH1F(name,title, nBins,  - 0.5, fEndTime - fStartTime + 0.5);
712   TH1F * h = new TH1F(name,title, nBins, bins);
713   fListHisto->Add(h);
714   h->SetXTitle("orbit");
715   h->Sumw2();
716
717   TH1::AddDirectory(oldStatus);
718   
719
720   delete [] bins;
721   return h;
722 }
723
724 TH1F * AliAnalysisTaskBGvsTime::GetVsTimeHisto(const char * name) {
725
726   // Returns vs time histo. If not existing, creates it.
727   
728   TH1F * h = (TH1F*) fListHisto->FindObject(name);
729   if(!h) h = BookVsTimeHisto(name,name);
730   return h;
731
732 }
733
734 TH1F * AliAnalysisTaskBGvsTime::GetEfficiencyHisto(Int_t step) {
735
736   // Return efficiency histo. If not existing, creates it.
737   // 1 bin per category
738
739   // Probability of reconstructing one event with at least one
740   // particle in a given category
741   // This is only created for MC.
742
743   // If the first argument is true, returns the histo at generation
744   // level, otherwise returns the histo at rec level. Fill this histo
745   // with elements of the enum kEffPt1, kEffPt05, ...
746
747   const char * name = 0;
748   switch(step) {
749   case kEffStepGen:
750     name =  "hEffGen";
751     break;
752   case kEffStepRec:
753     name =  "hEffRec";
754     break;
755   case kEffStepTrig:
756     name =  "hEffTrig";
757     break;
758   }
759
760
761   TH1F * h = (TH1F*) fListHisto->FindObject(name);
762   if(!h) {
763     Bool_t oldStatus = TH1::AddDirectoryStatus();
764     TH1::AddDirectory(kFALSE);
765     h = new TH1F (name,name, kNEff, -0.5, kNEff-0.5);
766     h->GetXaxis()->SetBinLabel(h->FindBin(kEffPt1) , "pt > 1.0 GeV");
767     h->GetXaxis()->SetBinLabel(h->FindBin(kEffPt05), "pt > 0.5 GeV");
768     h->Sumw2();
769     fListHisto->Add(h);    
770     TH1::AddDirectory(oldStatus);
771   }
772
773   return h;
774
775 }
776
777 const char * AliAnalysisTaskBGvsTime::GetVsTimeHistoForLuminosityName(const char * triggerClass, Float_t ptmin) {
778
779   // Compose name of rate histos
780
781   static TString name;
782   name = "hRate_";
783   name += triggerClass;
784
785   name += Form ("_etamin_0.8_ptmin_%2.2f",ptmin);
786
787   return name.Data();
788 }
789
790
791 const char * AliAnalysisTaskBGvsTime::GetVsTimeHistoName(const char * triggerClass, Int_t nclusters, Int_t bx, const char * v0flag, const char *prefix){
792   
793   // compose name of vs time histos w/ different cuts
794   
795   static TString name;
796   name = "h";
797   name = name +prefix+"_";
798   name += triggerClass;
799
800   if (nclusters >= 0) { 
801     if(fMultBins){
802       // Add multiplicity label
803       Int_t selected_bin = -1;
804       for(Int_t ibin = 0; ibin < (fNMultBins-1); ibin++){
805         if (nclusters < fMultBins[ibin+1]) {
806           selected_bin = ibin;
807           break;
808         }
809       }
810       if(selected_bin < 0) {
811         AliError(Form("Cannot get mult bin - %d", nclusters));
812         selected_bin = (fNMultBins-1);
813       }
814       name += Form("_SPDCls_%d-%d",fMultBins[selected_bin],fMultBins[selected_bin+1]);
815       //    AliInfo(Form("Mult bin: %d, %d, %s", nclusters, selected_bin, name.Data()));        
816     }
817   } else {
818     name += "_SPDCls_ALL";
819   }
820   if(bx < 0) name = name +"_BXALL_"+v0flag; 
821   else       name = name +"_BX"+long(bx)+"_"+v0flag;
822   return name.Data();
823 }
824 const char * AliAnalysisTaskBGvsTime::GetVsTimeHistoNameAll(const char * triggerClass) {
825
826   // Compose default name of vstime histos in a given trigger class
827
828   static TString name;
829   name = "h_";
830   name += triggerClass;
831   return name.Data();
832
833 }
834
835 TH1F * AliAnalysisTaskBGvsTime::GetDistributionHisto(const char * triggerClass, Int_t dist, const char * suffix) {
836
837   // Returns distributions histos. If not existing, creates it.
838
839   // Possible distributions:
840   // - SPD cluster
841   // - TPC tracks multiplicity
842   // - TPC tracks pt
843   // - Vz
844   // - TPC tracks DCA
845   // - cluster per ITS layer
846
847   TString name  ;
848   TString title ;
849   TString xtitle;
850   Int_t   nbin =0;
851   Float_t   min  =0;
852   Float_t   max  =0;
853
854
855   if (dist == kDistSPDMult) {
856     name  = "hMultSPD_";
857     title = "SPD Cluster Multiplicity (";
858     xtitle = "SPD Clusters";
859     nbin  = 50;
860     min   = 0;
861     max   = 100;
862   } else if (dist == kDistTPCMult) {
863     name  = "hMultTPC_";
864     title = "TPC Tracks Multiplicity (";
865     xtitle = "TPC Tracks";
866     nbin  = 25;
867     min   = 0;
868     max   = 50;
869   } else if (dist == kDistPtLoose) {
870     name  = "hPtLoose_";
871     title = "p_{T} distribution - TPC, loose cuts (";
872     xtitle = "p_{T} (GeV)";
873     nbin  = 50;
874     min   = 0;
875     max   = 10;
876   } else if (dist == kDistPt) {
877     name  = "hPt_";
878     title = "p_{T} distribution - TPC, standard cuts, |#eta|<0.8 (";
879     xtitle = "p_{T} (GeV)";
880     nbin  = 100;
881     min   = 0;
882     max   = 10;
883   } else if (dist == kDistVertex || dist == kDistVertexZ || dist == kDistVertex3D ) {
884     nbin  = 120;
885     min   = -30;
886     max   = 30;
887     name  = "hVz_";
888     title = "V_{z} distribution";
889     if      (dist == kDistVertexZ)  {
890       title += " - Vertexer Z  (";
891       name+= "Z_";
892     }
893     else if (dist == kDistVertex3D) {
894       title += " - Vertexer 3D (";    
895       name+= "3D_";
896     }
897     else    title += " (";
898     xtitle = "V_{z} (cm)";
899   } else if (dist == kDistDCATPC) {
900     nbin  = 50;
901     min   = -0.5;
902     max   = +0.5;
903     name  = "hDCA_";
904     title = "TPC DCA distribution - loose cuts (";    
905     xtitle = "DCA";
906   } else if (dist == kDistClsITSLayer) {
907     nbin  = 6;
908     min   = -0.5;
909     max   = 5.5;
910     name  = "hClsITS_";
911     title = "Cluster per ITS layer (";    
912     xtitle = "ITS Layer";
913   }else {
914     AliError(Form("Distribution type not supported: %d",dist));
915     return 0;
916   } 
917
918
919   name += triggerClass;
920   if (suffix) name += suffix;
921   title = title+name+")";
922
923   TH1F* h = (TH1F*) fListHisto->FindObject(name.Data());
924
925   if(!h) h = BookDistributionHisto(name.Data(), title.Data(), xtitle.Data(), nbin, min, max);
926   return h;
927
928 }
929
930 TH1F * AliAnalysisTaskBGvsTime::BookDistributionHisto(const char * name, const char * title, const char * xtitle, Int_t nbin, Float_t min, Float_t max) {
931
932   // Book distributions histos
933
934   AliInfo(Form("Booking histo %s",name));
935
936   Bool_t oldStatus = TH1::AddDirectoryStatus();
937   TH1::AddDirectory(kFALSE);
938
939   TH1F * h = new TH1F (name,title,nbin,min,max);
940   h->Sumw2();
941   h->SetXTitle(xtitle);
942   //  h->SetYTitle("N");
943   fListHisto->Add(h);
944   TH1::AddDirectory(oldStatus);
945
946   return h;
947
948 }
949
950 TH1F * AliAnalysisTaskBGvsTime::GetDeadTimeHisto(const char * triggerClass) {
951   // returns histo of dead time vs timestamp for a given trigger
952   // class. If the histo does not exist, it books it.
953   TString name  = "hDeadTime_"  ;
954   TString title = "Dead Time vs TimeStamp (";
955
956   name += triggerClass;
957   title = title+triggerClass+")";
958
959   
960   TH1F* h = (TH1F*) fListHisto->FindObject(name.Data());
961
962   if(!h) {
963     h = BookVsTimeHisto(name.Data(), title.Data());
964     h->SetYTitle("deadtime");
965   }
966   return h;
967
968
969 }
970
971
972 // TH2F * AliAnalysisTaskBGvsTime::BookDeadTimeHisto(const char * name, const char * title) {
973 //   // Book dead time vs time stamp histos
974
975 //   AliInfo(Form("Booking histo %s",name));
976
977 //   Bool_t oldStatus = TH1::AddDirectoryStatus();
978 //   TH1::AddDirectory(kFALSE);
979
980 //   Float_t lenght =  fEndTime - fStartTime;
981 //   Int_t nBins = TMath::FloorNint(lenght/fBinWidth)+1;
982 //   Double_t * bins = new Double_t[nBins+1];
983 //   for(Int_t ibin = 0; ibin <= nBins; ibin++){
984 //     Float_t edge = ibin*fBinWidth - 0.5;
985 //     bins[ibin] = edge < (lenght - 0.5) ? edge  : (lenght-0.5);
986 //   }
987
988 //   TH2F * h = new TH2F (name,title,nBins,bins,200,0.,2.);
989 //   h->Sumw2();
990 //   h->SetXTitle("Time (s)");
991 //   h->SetYTitle("Dead Time");
992 //   fListHisto->Add(h);
993 //   TH1::AddDirectory(oldStatus);
994
995 //   delete bins;
996
997 //   return h;
998
999 // }
1000
1001
1002
1003 Bool_t AliAnalysisTaskBGvsTime::IsEventInBinZero() {
1004
1005   // Returns true if an event is to be assigned to the zero bin
1006
1007   Bool_t isZeroBin = kTRUE;
1008   const AliESDEvent* esd=fESD;
1009   const AliMultiplicity* mult = esd->GetMultiplicity();
1010   if (!mult){
1011     Printf("AliAnalysisTaskBGvsTime::IsBinZero: Can't get mult object");
1012     return kFALSE;
1013   }
1014   Int_t ntracklet = mult->GetNumberOfTracklets();
1015   const AliESDVertex * vtxESD = esd->GetPrimaryVertexSPD();
1016   if(vtxESD) {
1017     // If there is a vertex from vertexer z with delta phi > 0.02 we
1018     // don't consider it rec (we keep the event in bin0). If quality
1019     // is good eneough we check the number of tracklets
1020     // if the vertex is more than 15 cm away, this is autamatically bin0
1021     if( TMath::Abs(vtxESD->GetZ()) <= 15 ) {
1022       if (vtxESD->IsFromVertexerZ()) {
1023         if (vtxESD->GetDispersion()<=0.02 ) {
1024           if(ntracklet>0) isZeroBin = kFALSE;
1025         }
1026       } else if(ntracklet>0) isZeroBin = kFALSE; // if the event is not from Vz we chek the n of tracklets
1027     } 
1028   }
1029   return isZeroBin;
1030
1031 }
1032
1033 Bool_t AliAnalysisTaskBGvsTime::SelectOnImpPar(AliESDtrack* t) {
1034   // from andrea dainese
1035   // cut on transverse impact parameter
1036   Float_t d0z0[2],covd0z0[3];
1037   t->GetImpactParameters(d0z0,covd0z0);
1038   Float_t sigma= 0.0050+0.0060/TMath::Power(t->Pt(),0.9);
1039   Float_t d0max = 7.*sigma;
1040   if(TMath::Abs(d0z0[0]) < d0max) return kTRUE;
1041   return kFALSE;
1042 }
1043
1044
1045
1046