]> git.uio.no Git - u/mrichter/AliRoot.git/blob - PWGCF/Correlations/DPhi/AliAnalysisTaskPhiCorrelations.cxx
adding course centrality binning
[u/mrichter/AliRoot.git] / PWGCF / Correlations / DPhi / AliAnalysisTaskPhiCorrelations.cxx
1 /**************************************************************************
2  * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
3  *                                                                        *
4  * Author: The ALICE Off-line Project.                                    *
5  * Contributors are mentioned in the code where appropriate.              *
6  *                                                                        *
7  * Permission to use, copy, modify and distribute this software and its   *
8  * documentation strictly for non-commercial purposes is hereby granted   *
9  * without fee, provided that the above copyright notice appears in all   *
10  * copies and that both the copyright notice and this permission notice   *
11  * appear in the supporting documentation. The authors make no claims     *
12  * about the suitability of this software for any purpose. It is          *
13  * provided "as is" without express or implied warranty.                  *
14  **************************************************************************/
15
16 /* $Id:$ */
17
18 #include <TROOT.h>
19 #include <TChain.h>
20 #include <TFile.h>
21 #include <TList.h>
22 #include <TMath.h>
23 #include <TTree.h>
24 #include <TH2F.h>
25 #include <TRandom.h>
26
27 #include "AliAnalysisTaskPhiCorrelations.h"
28 #include "AliAnalyseLeadingTrackUE.h"
29 #include "AliUEHistograms.h"
30 #include "AliUEHist.h"
31
32 #include "AliAnalysisManager.h"
33 #include "AliAODHandler.h"
34 #include "AliAODInputHandler.h"
35 #include "AliAODMCParticle.h"
36 #include "AliInputEventHandler.h"
37 #include "AliLog.h"
38 #include "AliMCEventHandler.h"
39 #include "AliVParticle.h"
40 #include "AliCFContainer.h"
41
42 #include "AliESDEvent.h"
43 #include "AliESDInputHandler.h"
44 #include "AliMultiplicity.h"
45 #include "AliCentrality.h"
46 #include "AliStack.h"
47 #include "AliAODMCHeader.h"
48 #include "AliGenCocktailEventHeader.h"
49 #include "AliGenEventHeader.h"
50
51 #include "AliEventPoolManager.h"
52
53 #include "AliESDZDC.h"
54
55
56 ////////////////////////////////////////////////////////////////////////
57 //
58 // Analysis class for azimuthal correlation studies
59 // Based on the UE task from Sara Vallero and Jan Fiete
60 //
61 // This class needs input AODs.
62 // The output is a list of analysis-specific containers.
63 //
64 // The AOD can be either connected to the InputEventHandler  
65 // for a chain of AOD files 
66 // or 
67 // to the OutputEventHandler
68 // for a chain of ESD files,
69 // in this case the class should be in the train after the jet-finder
70 //
71 //    Authors:
72 //    Jan Fiete Grosse-Oetringhaus
73 // 
74 ////////////////////////////////////////////////////////////////////////
75
76
77 ClassImp( AliAnalysisTaskPhiCorrelations )
78 ClassImp( AliDPhiBasicParticle )
79
80 //____________________________________________________________________
81 AliAnalysisTaskPhiCorrelations:: AliAnalysisTaskPhiCorrelations(const char* name):
82 AliAnalysisTask(name,""),
83 // general configuration
84 fDebug(0),
85 fMode(0),
86 fReduceMemoryFootprint(kFALSE),
87 fFillMixed(kTRUE),
88 fMixingTracks(50000),
89 fCompareCentralities(kFALSE),
90 fTwoTrackEfficiencyStudy(kFALSE),
91 fTwoTrackEfficiencyCut(0),
92 fUseVtxAxis(kFALSE),
93 fCourseCentralityBinning(kFALSE),
94 fSkipTrigger(kFALSE),
95 fInjectedSignals(kFALSE),
96 // pointers to UE classes
97 fAnalyseUE(0x0),
98 fHistos(0x0),
99 fHistosMixed(0),
100 fkTrackingEfficiency(0x0),
101 // handlers and events
102 fAOD(0x0),
103 fESD(0x0),
104 fArrayMC(0x0),
105 fInputHandler(0x0),
106 fMcEvent(0x0),
107 fMcHandler(0x0),
108 fPoolMgr(0x0),
109 // histogram settings
110 fListOfHistos(0x0), 
111 // event QA
112 fnTracksVertex(1),  // QA tracks pointing to principal vertex (= 3 default) 
113 fZVertex(7.),
114 fCentralityMethod("V0M"),
115 // track cuts
116 fTrackEtaCut(0.8),
117 fOnlyOneEtaSide(0),
118 fPtMin(0.5),
119 fFilterBit(0xFF),
120 fSelectBit(AliVEvent::kMB|AliVEvent::kUserDefined),
121 fUseChargeHadrons(kFALSE),
122 fSelectCharge(0),
123 fTriggerSelectCharge(0),
124 fTriggerRestrictEta(-1),
125 fEtaOrdering(kFALSE),
126 fCutConversions(kFALSE),
127 fCutResonances(kFALSE),
128 fFillOnlyStep0(kFALSE),
129 fSkipStep6(kFALSE),
130 fRejectCentralityOutliers(kFALSE),
131 fFillpT(kFALSE)
132 {
133   // Default constructor
134   // Define input and output slots here
135   // Input slot #0 works with a TChain
136   DefineInput(0, TChain::Class());
137   // Output slot #0 writes into a TList container
138   DefineOutput(0, TList::Class());
139 }
140
141 AliAnalysisTaskPhiCorrelations::~AliAnalysisTaskPhiCorrelations() 
142
143   // destructor
144   
145   if (fListOfHistos  && !AliAnalysisManager::GetAnalysisManager()->IsProofMode()) 
146     delete fListOfHistos;
147 }
148
149 //____________________________________________________________________
150 void AliAnalysisTaskPhiCorrelations::ConnectInputData(Option_t* /*option*/)
151 {
152   
153   // Connect the input data  
154   if (fDebug > 1) AliInfo("ConnectInputData() ");
155   
156   // Since AODs can either be connected to the InputEventHandler
157   // or to the OutputEventHandler ( the AOD is created by a previus task in the train )
158   // we need to get the pointer to the AODEvent correctly.
159   
160   // Delta AODs are also accepted.
161   
162   TObject* handler = AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler();
163   
164   if( handler && handler->InheritsFrom("AliAODInputHandler") ) 
165   { // input AOD
166     fAOD = ((AliAODInputHandler*)handler)->GetEvent();
167     if (fDebug > 1) AliInfo(" ==== Tracks and Jets from AliAODInputHandler");
168   } 
169   else 
170   {  //output AOD
171     handler = AliAnalysisManager::GetAnalysisManager()->GetOutputEventHandler();
172     if (handler && handler->InheritsFrom("AliAODHandler") ) 
173     {
174       fAOD = ((AliAODHandler*)handler)->GetAOD();
175       if (fDebug > 1) AliInfo(" ==== Tracks and Jets from AliAODHandler");
176     } 
177     else 
178     {  // no AOD
179       AliWarning("I can't get any AOD Event Handler");
180     }
181   }
182   
183   if (handler && handler->InheritsFrom("AliESDInputHandler") ) 
184   { // input ESD
185     // pointer received per event in ::Exec
186     if (fDebug > 1) AliInfo(" ==== Tracks and Jets from AliESDInputHandler");
187   } 
188   
189   // Initialize common pointers
190   Initialize();
191 }
192
193 //____________________________________________________________________
194 void  AliAnalysisTaskPhiCorrelations::CreateOutputObjects()
195 {
196   // Create the output container
197   
198   if (fDebug > 1) AliInfo("CreateOutputObjects()");
199    
200   // Initialize class with main algorithms, event and track selection. 
201   fAnalyseUE = new AliAnalyseLeadingTrackUE();
202   fAnalyseUE->SetParticleSelectionCriteria(fFilterBit, fUseChargeHadrons, fTrackEtaCut, fPtMin);
203   fAnalyseUE->SetDebug(fDebug); 
204   fAnalyseUE->DefineESDCuts(fFilterBit);
205   fAnalyseUE->SetEventSelection(fSelectBit);
206
207   // Initialize output list of containers
208   if (fListOfHistos != NULL){
209         delete fListOfHistos;
210         fListOfHistos = NULL;
211         }
212   if (!fListOfHistos){
213         fListOfHistos = new TList();
214         fListOfHistos->SetOwner(kTRUE); 
215         }
216
217   // Initialize class to handle histograms 
218   TString histType = "4R";
219   if (fUseVtxAxis)
220     histType = "5R";
221   if (fCourseCentralityBinning)
222     histType += "C";
223   fHistos = new AliUEHistograms("AliUEHistogramsSame", histType);
224   fHistosMixed = new AliUEHistograms("AliUEHistogramsMixed", histType);
225   
226   fHistos->SetSelectCharge(fSelectCharge);
227   fHistosMixed->SetSelectCharge(fSelectCharge);
228   
229   fHistos->SetSelectTriggerCharge(fTriggerSelectCharge);
230   fHistosMixed->SetSelectTriggerCharge(fTriggerSelectCharge);
231
232   fHistos->SetTriggerRestrictEta(fTriggerRestrictEta);
233   fHistosMixed->SetTriggerRestrictEta(fTriggerRestrictEta);
234   
235   fHistos->SetOnlyOneEtaSide(fOnlyOneEtaSide);
236   fHistosMixed->SetOnlyOneEtaSide(fOnlyOneEtaSide);
237   
238   fHistos->SetEtaOrdering(fEtaOrdering);
239   fHistosMixed->SetEtaOrdering(fEtaOrdering);
240
241   fHistos->SetPairCuts(fCutConversions, fCutResonances);
242   fHistosMixed->SetPairCuts(fCutConversions, fCutResonances);
243   
244   // add histograms to list
245   fListOfHistos->Add(fHistos);
246   fListOfHistos->Add(fHistosMixed);
247   
248   fListOfHistos->Add(new TH2F("trackletsVsV0Cent", ";L1 clusters;v0 centrality", 100, -0.5, 9999.5, 101, 0, 101));
249   fListOfHistos->Add(new TH2F("processIDs", ";#Delta#phi;process id", 100, -0.5 * TMath::Pi(), 1.5 * TMath::Pi(), kPNoProcess + 1, -0.5, kPNoProcess + 0.5));
250   fListOfHistos->Add(new TH1F("eventStat", ";;events", 4, -0.5, 3.5));
251   fListOfHistos->Add(new TH2F("mixedDist", ";centrality;tracks;events", 101, 0, 101, 200, 0, fMixingTracks * 1.5));
252   fListOfHistos->Add(new TH1F("pids", ";pdg;tracks", 2001, -1000.5, 1000.5));
253   
254   PostData(0,fListOfHistos);
255   
256   // Add task configuration to output list 
257   AddSettingsTree();
258
259   // event mixing
260   Int_t trackDepth = fMixingTracks; 
261   Int_t poolsize   = 1000;  // Maximum number of events, ignored in the present implemented of AliEventPoolManager
262    
263   Int_t nCentralityBins  = fHistos->GetUEHist(2)->GetEventHist()->GetNBins(1);
264   Double_t* centralityBins = (Double_t*) fHistos->GetUEHist(2)->GetEventHist()->GetAxis(1, 0)->GetXbins()->GetArray();
265   
266   Int_t nZvtxBins  = 7+1+7;
267   // bins for second buffer are shifted by 100 cm
268   Double_t vertexBins[] = { -7, -5, -3, -1, 1, 3, 5, 7, 93, 95, 97, 99, 101, 103, 105, 107 };
269   Double_t* zvtxbin = vertexBins;
270
271   if (fHistos->GetUEHist(2)->GetEventHist()->GetNVar() > 2)
272   {
273     nZvtxBins = fHistos->GetUEHist(2)->GetEventHist()->GetNBins(2);
274     zvtxbin = (Double_t*) fHistos->GetUEHist(2)->GetEventHist()->GetAxis(2, 0)->GetXbins()->GetArray();
275   }
276
277   fPoolMgr = new AliEventPoolManager(poolsize, trackDepth, nCentralityBins, centralityBins, nZvtxBins, zvtxbin);
278 }
279
280 //____________________________________________________________________
281 void  AliAnalysisTaskPhiCorrelations::Exec(Option_t */*option*/)
282 {
283   // receive ESD pointer if we are not running AOD analysis
284   if (!fAOD)
285   {
286     AliVEventHandler* handler = AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler();
287     if (handler && handler->InheritsFrom("AliESDInputHandler"))
288       fESD = ((AliESDInputHandler*)handler)->GetEvent();
289   }
290
291   if (fMode)
292   {
293     // correction mode
294     
295     if (fMcHandler)
296       fMcEvent = fMcHandler->MCEvent();
297
298     if (fAOD)
299     {
300       // array of MC particles
301       fArrayMC = dynamic_cast<TClonesArray*>(fAOD->FindListObject(AliAODMCParticle::StdBranchName()));
302       if (!fArrayMC)
303         AliFatal("No array of MC particles found !!!");
304     }
305     
306     AnalyseCorrectionMode();
307   }
308   else AnalyseDataMode();
309 }
310
311 /******************** ANALYSIS METHODS *****************************/
312
313 //____________________________________________________________________
314 void  AliAnalysisTaskPhiCorrelations::AddSettingsTree()
315 {
316   //Write settings to output list
317   TTree *settingsTree   = new TTree("UEAnalysisSettings","Analysis Settings in UE estimation");
318   settingsTree->Branch("fnTracksVertex", &fnTracksVertex,"nTracksVertex/I");
319   settingsTree->Branch("fZVertex", &fZVertex,"ZVertex/D");
320   //settingsTree->Branch("fCentralityMethod", fCentralityMethod.Data(),"CentralityMethod/C");
321   settingsTree->Branch("fTrackEtaCut", &fTrackEtaCut, "TrackEtaCut/D");
322   settingsTree->Branch("fOnlyOneEtaSide", &fOnlyOneEtaSide,"OnlyOneEtaSide/I");
323   settingsTree->Branch("fPtMin", &fPtMin, "PtMin/D");
324   settingsTree->Branch("fFilterBit", &fFilterBit,"FilterBit/I");
325   settingsTree->Branch("fSelectBit", &fSelectBit,"EventSelectionBit/I");
326   settingsTree->Branch("fUseChargeHadrons", &fUseChargeHadrons,"UseChHadrons/O");
327   settingsTree->Branch("fSelectCharge", &fSelectCharge,"SelectCharge/I");
328   settingsTree->Branch("fTriggerSelectCharge", &fTriggerSelectCharge,"TriggerSelectCharge/I");
329   settingsTree->Branch("fTriggerRestrictEta", &fTriggerRestrictEta,"TriggerRestrictEta/D");
330   settingsTree->Branch("fEtaOrdering", &fEtaOrdering,"EtaOrdering/O");
331   settingsTree->Branch("fCutConversions", &fCutConversions,"CutConversions/O");
332   settingsTree->Branch("fCutResonances", &fCutResonances,"CutResonances/O");
333   settingsTree->Branch("fFillpT", &fFillpT,"FillpT/O");
334   settingsTree->Branch("fkTrackingEfficiency", "TH1D", &fkTrackingEfficiency);
335   settingsTree->Branch("fMixingTracks", &fMixingTracks,"MixingTracks/I");
336   settingsTree->Branch("fSkipTrigger", &fSkipTrigger,"SkipTrigger/O");
337   settingsTree->Branch("fInjectedSignals", &fInjectedSignals,"SkipTrigger/O");
338   settingsTree->Branch("fRejectCentralityOutliers", &fRejectCentralityOutliers,"RejectCentralityOutliers/O");
339   
340   settingsTree->Fill();
341   fListOfHistos->Add(settingsTree);
342 }  
343
344 //____________________________________________________________________
345 void  AliAnalysisTaskPhiCorrelations::AnalyseCorrectionMode()
346 {
347   // Run the analysis on MC to get the correction maps
348   //
349  
350   if ( fDebug > 3 ) AliInfo( " Processing event in Corrections mode ..." );
351   
352   Double_t centrality = 0;
353   
354   if (fCentralityMethod.Length() > 0)
355   {
356     AliCentrality *centralityObj = 0;
357     if (fAOD)
358       centralityObj = fAOD->GetHeader()->GetCentralityP();
359     else if (fESD)
360       centralityObj = fESD->GetCentrality();
361     
362     if (centralityObj)
363     {
364       centrality = centralityObj->GetCentralityPercentileUnchecked(fCentralityMethod);
365       AliInfo(Form("Centrality is %f", centrality));
366     }
367     else
368     {
369       Printf("WARNING: Centrality object is 0");
370       centrality = -1;
371      }
372   }
373   
374   // Support for ESD and AOD based analysis
375   AliVEvent* inputEvent = fAOD;
376   if (!inputEvent)
377     inputEvent = fESD;
378
379   Float_t bSign = 0;
380   
381   if (inputEvent)
382   {
383     fHistos->SetRunNumber(inputEvent->GetRunNumber());
384     bSign = (inputEvent->GetMagneticField() > 0) ? 1 : -1;
385   }
386     
387   TObject* mc = fArrayMC;
388   if (!mc)
389     mc = fMcEvent;
390   
391   // count all events
392   fHistos->FillEvent(centrality, -1);
393   
394   // Only consider MC events within the vtx-z region used also as cut on the reconstructed vertex
395   TObject* vertexSupplier = fMcEvent;
396   if (fAOD) // AOD
397     vertexSupplier = fAOD->FindListObject(AliAODMCHeader::StdBranchName());
398     
399   if (!fAnalyseUE->VertexSelection(vertexSupplier, 0, fZVertex)) 
400     return;
401   
402   Float_t zVtx = 0;
403   if (fAOD)
404     zVtx = ((AliAODMCHeader*) vertexSupplier)->GetVtxZ();
405   else
406     zVtx = fMcEvent->GetPrimaryVertex()->GetZ();
407   Float_t weight = 1;
408   if (fFillpT)
409     weight = -1;
410   
411   // For productions with injected signals, figure out above which label to skip particles/tracks
412   Int_t skipParticlesAbove = 0;
413   if (fInjectedSignals)
414   {
415     AliGenEventHeader* eventHeader = 0;
416     Int_t headers = 0;
417
418     if (fMcEvent)
419     {
420       // ESD
421       AliHeader* header = (AliHeader*) fMcEvent->Header();
422       if (!header)
423         AliFatal("fInjectedSignals set but no MC header found");
424         
425       AliGenCocktailEventHeader* cocktailHeader = dynamic_cast<AliGenCocktailEventHeader*> (header->GenEventHeader());
426       if (!cocktailHeader)
427       {
428         header->Dump();
429         AliFatal("fInjectedSignals set but no MC cocktail header found");
430       }
431
432       headers = cocktailHeader->GetHeaders()->GetEntries();
433       eventHeader = dynamic_cast<AliGenEventHeader*> (cocktailHeader->GetHeaders()->First());
434     }
435     else
436     {
437       // AOD
438       AliAODMCHeader* header = (AliAODMCHeader*) fAOD->GetList()->FindObject(AliAODMCHeader::StdBranchName());
439       if (!header)
440         AliFatal("fInjectedSignals set but no MC header found");
441       
442       headers = header->GetNCocktailHeaders();
443       eventHeader = header->GetCocktailHeader(0);
444     }
445     
446     if (!eventHeader)
447     {
448       // We avoid AliFatal here, because the AOD productions sometimes have events where the MC header is missing 
449       // (due to unreadable Kinematics) and we don't want to loose the whole job because of a few events
450       AliError("First event header not found. Skipping this event.");
451       fHistos->FillEvent(centrality, AliUEHist::kCFStepAnaTopology);
452       return;
453     }
454     
455     skipParticlesAbove = eventHeader->NProduced();
456     AliInfo(Form("Injected signals in this event (%d headers). Keeping events of %s. Will skip particles/tracks above %d.", headers, eventHeader->ClassName(), skipParticlesAbove));
457   }
458   
459   // Get MC primaries
460   TObjArray* tmpList = fAnalyseUE->GetAcceptedParticles(mc, 0, kTRUE, -1, kTRUE);
461   if (fInjectedSignals)
462     fAnalyseUE->RemoveInjectedSignals(tmpList, mc, skipParticlesAbove);
463   TObjArray* tracksMC = CloneAndReduceTrackList(tmpList);
464   delete tmpList;
465   
466   /*
467   if (fAOD)
468   {
469     for (Int_t i=0; i<fArrayMC->GetEntriesFast(); i++)
470       ((TH1F*) fListOfHistos->FindObject("pids"))->Fill(((AliAODMCParticle*) fArrayMC->At(i))->PdgCode());
471   }
472   else
473   {
474     for (Int_t i=0; i<fMcEvent->GetNumberOfTracks(); i++)
475       ((TH1F*) fListOfHistos->FindObject("pids"))->Fill(fMcEvent->GetTrack(i)->PdgCode());
476   }
477   */
478   
479   if (fFillOnlyStep0)
480     zVtx = 0;
481   
482   // (MC-true all particles)
483   // STEP 0
484   fHistos->FillCorrelations(centrality, zVtx, AliUEHist::kCFStepAll, tracksMC, 0, weight);
485   
486   // mixed event
487   if (fFillMixed)
488   {
489     AliEventPool* pool = fPoolMgr->GetEventPool(centrality, zVtx);
490     //pool->PrintInfo();
491     if (pool->IsReady() || pool->NTracksInPool() > fMixingTracks / 10 || pool->GetCurrentNEvents() >= 5) 
492       for (Int_t jMix=0; jMix<pool->GetCurrentNEvents(); jMix++) 
493         fHistosMixed->FillCorrelations(centrality, zVtx, AliUEHist::kCFStepAll, tracksMC, pool->GetEvent(jMix), 1.0 / pool->GetCurrentNEvents(), (jMix == 0));
494     pool->UpdatePool(CloneAndReduceTrackList(tracksMC));
495   }
496   
497 //   Printf("trigger: %d", ((AliInputEventHandler*)fInputHandler)->IsEventSelected());
498   
499   // Trigger selection ************************************************
500   if (!fFillOnlyStep0 && (fSkipTrigger || fAnalyseUE->TriggerSelection(fInputHandler)))
501   {  
502     // (MC-true all particles)
503     // STEP 1
504     if (!fReduceMemoryFootprint)
505       fHistos->FillCorrelations(centrality, zVtx, AliUEHist::kCFStepTriggered, tracksMC, 0, weight);
506     else
507       fHistos->FillEvent(centrality, AliUEHist::kCFStepTriggered);
508       
509     if (!inputEvent) {
510       AliFatal("UNEXPECTED: inputEvent is 0. Trigger selection should have failed");
511       return;
512     }
513     
514     // Vertex selection *************************************************
515     if (fAnalyseUE->VertexSelection(inputEvent, fnTracksVertex, fZVertex))
516     {
517       // fill here for tracking efficiency
518       // loop over particle species
519       
520       for (Int_t particleSpecies = 0; particleSpecies < 4; particleSpecies++)
521       {
522         TObjArray* primMCParticles = fAnalyseUE->GetAcceptedParticles(mc, 0x0, kTRUE, particleSpecies, kTRUE);
523         TObjArray* primRecoTracksMatched = fAnalyseUE->GetAcceptedParticles(inputEvent, mc, kTRUE, particleSpecies, kTRUE);
524         TObjArray* allRecoTracksMatched = fAnalyseUE->GetAcceptedParticles(inputEvent, mc, kFALSE, particleSpecies, kTRUE);
525         
526         if (fInjectedSignals)
527         {
528           fAnalyseUE->RemoveInjectedSignals(primMCParticles, mc, skipParticlesAbove);
529           fAnalyseUE->RemoveInjectedSignals(primRecoTracksMatched, mc, skipParticlesAbove);
530           fAnalyseUE->RemoveInjectedSignals(allRecoTracksMatched, mc, skipParticlesAbove);
531         }
532       
533         fHistos->FillTrackingEfficiency(primMCParticles, primRecoTracksMatched, allRecoTracksMatched, 0, particleSpecies, centrality);
534         
535 //      Printf("%d --> %d %d %d", particleSpecies, primMCParticles->GetEntries(), primRecoTracksMatched->GetEntries(), allRecoTracksMatched->GetEntries());
536
537         delete primMCParticles;
538         delete primRecoTracksMatched;
539         delete allRecoTracksMatched;
540       }
541       TObjArray* fakeParticles = fAnalyseUE->GetFakeParticles(inputEvent, mc, kFALSE, -1, kTRUE);
542       if (fInjectedSignals)
543       {
544         fAnalyseUE->RemoveInjectedSignals((TObjArray*) fakeParticles->At(0), mc, skipParticlesAbove);
545         fAnalyseUE->RemoveInjectedSignals((TObjArray*) fakeParticles->At(1), mc, skipParticlesAbove);
546       }
547       fHistos->FillTrackingEfficiency(0, 0, 0, (TObjArray*) fakeParticles->At(2), -1, centrality);
548       fHistos->FillFakePt(fakeParticles, centrality);
549 //       Printf(">>>>> %d %d %d fakes", ((TObjArray*) fakeParticles->At(0))->GetEntriesFast(), ((TObjArray*) fakeParticles->At(1))->GetEntriesFast(), ((TObjArray*) fakeParticles->At(2))->GetEntriesFast());
550       delete fakeParticles;
551     
552       // (MC-true all particles)
553       // STEP 2
554       if (!fReduceMemoryFootprint)
555         fHistos->FillCorrelations(centrality, zVtx, AliUEHist::kCFStepVertex, tracksMC, 0, weight);
556       else
557         fHistos->FillEvent(centrality, AliUEHist::kCFStepVertex);
558       
559       // Get MC primaries that match reconstructed track
560       TObjArray* tracksRecoMatchedPrim = fAnalyseUE->GetAcceptedParticles(inputEvent, mc, kTRUE, -1, kTRUE);
561       if (fInjectedSignals)
562         fAnalyseUE->RemoveInjectedSignals(tracksRecoMatchedPrim, mc, skipParticlesAbove);
563       
564       // (RECO-matched (quantities from MC particle) primary particles)
565       // STEP 4
566       fHistos->FillCorrelations(centrality, zVtx, AliUEHist::kCFStepTrackedOnlyPrim, tracksRecoMatchedPrim, 0, weight);
567       
568       // Get MC primaries + secondaries that match reconstructed track
569       TObjArray* tracksRecoMatchedAll = fAnalyseUE->GetAcceptedParticles(inputEvent, mc, kFALSE, -1, kTRUE);
570       if (fInjectedSignals)
571         fAnalyseUE->RemoveInjectedSignals(tracksRecoMatchedAll, mc, skipParticlesAbove);
572       
573       // (RECO-matched (quantities from MC particle) all particles)
574       // STEP 5
575       fHistos->FillCorrelations(centrality, zVtx, AliUEHist::kCFStepTracked, tracksRecoMatchedAll, 0, weight);
576       
577       // Get RECO tracks
578       TObjArray* tracks = fAnalyseUE->GetAcceptedParticles(inputEvent, 0, kTRUE, -1, kTRUE);
579       if (fInjectedSignals)
580         fAnalyseUE->RemoveInjectedSignals(tracks, mc, skipParticlesAbove);
581      
582       // (RECO all tracks)
583       // STEP 6
584       if (!fSkipStep6)
585         fHistos->FillCorrelations(centrality, zVtx, AliUEHist::kCFStepReconstructed, tracks, 0, weight);
586       
587       // two track cut, STEP 8
588       if (fTwoTrackEfficiencyCut > 0)
589         fHistos->FillCorrelations(centrality, zVtx, AliUEHist::kCFStepBiasStudy, tracks, 0, weight, kTRUE, kTRUE, bSign, fTwoTrackEfficiencyCut);
590
591       // mixed event
592       if (fFillMixed && !fSkipStep6)
593       {
594         AliEventPool* pool2 = fPoolMgr->GetEventPool(centrality, zVtx + 100);
595         //pool2->PrintInfo();
596         if (pool2->IsReady() || pool2->NTracksInPool() > fMixingTracks / 10 || pool2->GetCurrentNEvents() >= 5) 
597           for (Int_t jMix=0; jMix<pool2->GetCurrentNEvents(); jMix++)
598           {
599             // STEP 6
600             fHistosMixed->FillCorrelations(centrality, zVtx, AliUEHist::kCFStepReconstructed, tracks, pool2->GetEvent(jMix), 1.0 / pool2->GetCurrentNEvents(), (jMix == 0));
601             
602             // two track cut, STEP 8
603             if (fTwoTrackEfficiencyCut > 0)
604               fHistosMixed->FillCorrelations(centrality, zVtx, AliUEHist::kCFStepBiasStudy, tracks, pool2->GetEvent(jMix), 1.0 / pool2->GetCurrentNEvents(), (jMix == 0), kTRUE, bSign, fTwoTrackEfficiencyCut);
605           }
606         pool2->UpdatePool(CloneAndReduceTrackList(tracks));
607       }
608
609       if (0 && !fReduceMemoryFootprint)
610       {
611         // make list of secondaries (matched with MC)
612         TObjArray* tracksRecoMatchedSecondaries = new TObjArray;
613         for (Int_t i=0; i<tracksRecoMatchedAll->GetEntriesFast(); i++)
614           if (((AliAODMCParticle*)tracksRecoMatchedAll->At(i))->IsPhysicalPrimary() == kFALSE)
615             tracksRecoMatchedSecondaries->Add(tracksRecoMatchedAll->At(i));
616       
617         // Study: Use only secondaries as trigger particles and plot the correlation vs. all particles; store in step 9
618         fHistos->FillCorrelations(centrality, zVtx, AliUEHist::kCFStepBiasStudy2, tracksRecoMatchedSecondaries, tracksRecoMatchedAll, weight);
619         
620         // Study: Use only primaries as trigger particles and plot the correlation vs. secondaries; store in step 8
621         fHistos->FillCorrelations(centrality, zVtx, AliUEHist::kCFStepBiasStudy, tracksRecoMatchedPrim, tracksRecoMatchedSecondaries, weight);
622       
623         // plot delta phi vs process id of secondaries
624         // trigger particles: primaries in 4 < pT < 10
625         // associated particles: secondaries in 1 < pT < 10
626         
627         for (Int_t i=0; i<tracksRecoMatchedPrim->GetEntriesFast(); i++)
628         {
629           AliVParticle* triggerParticle = (AliVParticle*) tracksRecoMatchedPrim->At(i);
630           
631           if (triggerParticle->Pt() < 4 || triggerParticle->Pt() > 10)
632             continue;
633           
634           for (Int_t j=0; j<tracksRecoMatchedSecondaries->GetEntriesFast(); j++)
635           {
636             AliAODMCParticle* particle = (AliAODMCParticle*) tracksRecoMatchedSecondaries->At(j);
637             
638             if (particle->Pt() < 1 || particle->Pt() > 10)
639               continue;
640             
641             if (particle->Pt() > triggerParticle->Pt())
642               continue;
643               
644             Double_t deltaPhi = triggerParticle->Phi() - particle->Phi();
645             if (deltaPhi > 1.5 * TMath::Pi()) 
646               deltaPhi -= TMath::TwoPi();
647             if (deltaPhi < -0.5 * TMath::Pi())
648               deltaPhi += TMath::TwoPi();
649               
650             Int_t processID = fMcEvent->Stack()->Particle(particle->GetLabel())->GetUniqueID();
651               
652             ((TH2F*) fListOfHistos->FindObject("processIDs"))->Fill(deltaPhi, processID);
653           }
654         }
655         
656         delete tracksRecoMatchedSecondaries;
657       }
658   
659       delete tracksRecoMatchedPrim;
660       delete tracksRecoMatchedAll;
661       delete tracks;
662     }
663   }
664   
665   delete tracksMC;
666 }
667
668 //____________________________________________________________________
669 void  AliAnalysisTaskPhiCorrelations::AnalyseDataMode()
670 {
671
672   // Run the analysis on DATA or MC to get raw distributions
673  
674   if ( fDebug > 3 ) AliInfo( " Processing event in Data mode ..." );
675
676   ((TH1F*) fListOfHistos->FindObject("eventStat"))->Fill(0);
677
678   if (!fInputHandler)
679     return;
680     
681   // skip not selected events here (the AOD is not updated for those)
682   if (!fSkipTrigger && !(fInputHandler->IsEventSelected() & fSelectBit))
683     return;
684
685   Double_t centrality = 0;
686   
687   AliCentrality *centralityObj = 0;
688   if (fCentralityMethod.Length() > 0)
689   {
690     if (fCentralityMethod == "ZNA_MANUAL")
691     {
692       Bool_t zna = kFALSE;
693       for(Int_t j = 0; j < 4; ++j) {
694         if (fESD->GetZDCData()->GetZDCTDCData(12,j) != 0) {
695           zna = kTRUE;
696         }
697       }
698
699 //       Printf("%d %f", zna, fZNAtower[0]);
700       if (zna)
701       {
702         // code from Chiara O (23.10.12)
703         const Double_t *fZNAtower = fESD->GetZDCData()->GetZN2TowerEnergy();
704         Float_t znacut[3] = {680., 562., 412.};
705
706         if(fZNAtower[0]>znacut[0]) centrality = 1;
707         else if(fZNAtower[0]<=znacut[0] && fZNAtower[0]>znacut[1]) centrality = 21;
708         else if(fZNAtower[0]<=znacut[1] && fZNAtower[0]>znacut[2]) centrality = 41;
709         else if(fZNAtower[0]<=znacut[2]) centrality = 61;
710       }
711       else
712         centrality = -1;
713     }
714     else
715     {
716       if (fAOD)
717         centralityObj = fAOD->GetHeader()->GetCentralityP();
718       else if (fESD)
719         centralityObj = fESD->GetCentrality();
720       
721       if (centralityObj)
722         centrality = centralityObj->GetCentralityPercentile(fCentralityMethod);
723         //centrality = centralityObj->GetCentralityPercentileUnchecked(fCentralityMethod);
724       else
725         centrality = -1;
726
727       if (fAOD)
728       {
729         // remove outliers
730         if (centrality == 0)
731         {
732           if (fAOD->GetVZEROData())
733           {
734             Float_t multV0 = 0;
735             for (Int_t i=0; i<64; i++)
736               multV0 += fAOD->GetVZEROData()->GetMultiplicity(i);
737             if (multV0 < 19500)
738             {
739               centrality = -1;
740               AliInfo("Rejecting event due to too small V0 multiplicity");
741             }
742           }
743         }
744       }
745     }
746     
747     AliInfo(Form("Centrality is %f", centrality));
748   }
749   
750   // Support for ESD and AOD based analysis
751   AliVEvent* inputEvent = fAOD;
752   if (!inputEvent)
753     inputEvent = fESD;
754
755   Float_t bSign = (inputEvent->GetMagneticField() > 0) ? 1 : -1;
756
757   fHistos->SetRunNumber(inputEvent->GetRunNumber());
758   
759   // Fill the "event-counting-container", it is needed to get the number of events remaining after each event-selection cut
760   fHistos->FillEvent(centrality, AliUEHist::kCFStepAll);
761   
762   // Trigger selection ************************************************
763   if (!fSkipTrigger && !fAnalyseUE->TriggerSelection(fInputHandler)) return;
764   
765   // Fill the "event-counting-container", it is needed to get the number of events remaining after each event-selection cut
766   fHistos->FillEvent(centrality, AliUEHist::kCFStepTriggered);
767   
768   // Vertex selection *************************************************
769   if(!fAnalyseUE->VertexSelection(inputEvent, fnTracksVertex, fZVertex)) return;
770   
771   // Fill the "event-counting-container", it is needed to get the number of events remaining after each event-selection cut
772   fHistos->FillEvent(centrality, AliUEHist::kCFStepVertex);
773  
774   // optimization
775   if (centrality < 0 && !fCompareCentralities)
776     return;
777
778   TObjArray* tracks = fAnalyseUE->GetAcceptedParticles(inputEvent, 0, kTRUE, -1, kTRUE);
779   
780   // check for outlier in centrality vs number of tracks (rough constants extracted from correlation histgram)
781   Bool_t reject = kFALSE;
782   if (fRejectCentralityOutliers)
783   {
784     if (centrality > 40 && centrality <= 50 && tracks->GetEntriesFast() > 1160)
785       reject = kTRUE;
786     if (centrality > 50 && centrality <= 60 && tracks->GetEntriesFast() > 650)
787       reject = kTRUE;
788     if (centrality > 60 && centrality <= 70 && tracks->GetEntriesFast() > 370)
789       reject = kTRUE;
790     if (centrality > 70 && centrality <= 80 && tracks->GetEntriesFast() > 220)
791       reject = kTRUE;
792     if (centrality > 80 && centrality <= 90 && tracks->GetEntriesFast() > 130)
793       reject = kTRUE;
794     if (centrality > 90 && tracks->GetEntriesFast() > 75)
795       reject = kTRUE;
796   }
797   
798   if (reject)
799   {
800     AliInfo(Form("Rejecting event due to centrality vs tracks correlation: %f %d", centrality, tracks->GetEntriesFast()));
801     fHistos->FillEvent(centrality, AliUEHist::kCFStepAnaTopology);
802     delete tracks;
803     return;
804   }
805
806   
807   // create a list of reduced objects. This speeds up processing and reduces memory consumption for the event pool
808   TObjArray* tracksClone = CloneAndReduceTrackList(tracks);
809   delete tracks;
810   
811   //Printf("Accepted %d tracks", tracks->GetEntries());
812   
813   const AliVVertex* vertex = inputEvent->GetPrimaryVertex();
814   Double_t zVtx = vertex->GetZ();
815   
816   Float_t weight = 1;
817   if (fFillpT)
818     weight = -1;
819
820   // fill two different centralities (syst study)
821   // the zvtx axis is used to distinguish the results of both centralities: configured centrality in zvtx = 0, SPD in zvtx = 2
822   if (fCompareCentralities)
823     zVtx = 0;
824   
825   // Fill containers at STEP 6 (reconstructed)
826   if (centrality >= 0)
827   {
828     if (!fSkipStep6)
829       fHistos->FillCorrelations(centrality, zVtx, AliUEHist::kCFStepReconstructed, tracksClone, 0, weight);
830     
831     ((TH1F*) fListOfHistos->FindObject("eventStat"))->Fill(1);
832     
833     if (fTwoTrackEfficiencyCut > 0)
834       fHistos->FillCorrelations(centrality, zVtx, AliUEHist::kCFStepBiasStudy, tracksClone, 0, weight, kTRUE, kTRUE, bSign, fTwoTrackEfficiencyCut);
835   }
836
837   // fill second time with SPD centrality
838   if (fCompareCentralities && centralityObj)
839   {
840     centrality = centralityObj->GetCentralityPercentile("CL1");
841     if (centrality >= 0 && !fSkipStep6)
842       fHistos->FillCorrelations(centrality, 2, AliUEHist::kCFStepReconstructed, tracksClone, 0, weight);
843   }
844   
845   if (fFillMixed)
846   {
847     // event mixing
848     
849     // 1. First get an event pool corresponding in mult (cent) and
850     //    zvertex to the current event. Once initialized, the pool
851     //    should contain nMix (reduced) events. This routine does not
852     //    pre-scan the chain. The first several events of every chain
853     //    will be skipped until the needed pools are filled to the
854     //    specified depth. If the pool categories are not too rare, this
855     //    should not be a problem. If they are rare, you could lose
856     //    statistics.
857
858     // 2. Collect the whole pool's content of tracks into one TObjArray
859     //    (bgTracks), which is effectively a single background super-event.
860
861     // 3. The reduced and bgTracks arrays must both be passed into
862     //    FillCorrelations(). Also nMix should be passed in, so a weight
863     //    of 1./nMix can be applied.
864
865     AliEventPool* pool = fPoolMgr->GetEventPool(centrality, zVtx);
866     
867     if (!pool)
868       AliFatal(Form("No pool found for centrality = %f, zVtx = %f", centrality, zVtx));
869     
870     //pool->SetDebug(1);
871      
872     if (pool->IsReady() || pool->NTracksInPool() > fMixingTracks / 10 || pool->GetCurrentNEvents() >= 5) 
873     {
874       
875       Int_t nMix = pool->GetCurrentNEvents();
876 //       cout << "nMix = " << nMix << " tracks in pool = " << pool->NTracksInPool() << endl;
877       
878       ((TH1F*) fListOfHistos->FindObject("eventStat"))->Fill(2);
879       ((TH2F*) fListOfHistos->FindObject("mixedDist"))->Fill(centrality, pool->NTracksInPool());
880       if (pool->IsReady())
881         ((TH1F*) fListOfHistos->FindObject("eventStat"))->Fill(3);
882     
883       // Fill mixed-event histos here  
884       for (Int_t jMix=0; jMix<nMix; jMix++) 
885       {
886         TObjArray* bgTracks = pool->GetEvent(jMix);
887         
888         if (!fSkipStep6)
889           fHistosMixed->FillCorrelations(centrality, zVtx, AliUEHist::kCFStepReconstructed, tracksClone, bgTracks, 1.0 / nMix, (jMix == 0));
890
891         if (fTwoTrackEfficiencyCut > 0)
892           fHistosMixed->FillCorrelations(centrality, zVtx, AliUEHist::kCFStepBiasStudy, tracksClone, bgTracks, 1.0 / nMix, (jMix == 0), kTRUE, bSign, fTwoTrackEfficiencyCut);
893       }
894     }
895     
896     // ownership is with the pool now
897     pool->UpdatePool(tracksClone);
898     //pool->PrintInfo();
899   }
900   else
901     delete tracksClone;
902 }
903
904 TObjArray* AliAnalysisTaskPhiCorrelations::CloneAndReduceTrackList(TObjArray* tracks)
905 {
906   // clones a track list by using AliDPhiBasicParticle which uses much less memory (used for event mixing)
907   
908   TObjArray* tracksClone = new TObjArray;
909   tracksClone->SetOwner(kTRUE);
910   
911   for (Int_t i=0; i<tracks->GetEntriesFast(); i++)
912   {
913     AliVParticle* particle = (AliVParticle*) tracks->At(i);
914     tracksClone->Add(new AliDPhiBasicParticle(particle->Eta(), particle->Phi(), particle->Pt(), particle->Charge()));
915   }
916   
917   return tracksClone;
918 }
919
920 //____________________________________________________________________
921 void  AliAnalysisTaskPhiCorrelations::Initialize()
922 {
923   // input handler
924   fInputHandler = (AliInputEventHandler*)
925          ((AliAnalysisManager::GetAnalysisManager())->GetInputEventHandler());
926   // MC handler
927   fMcHandler = dynamic_cast<AliMCEventHandler*> (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler());
928 }