]> git.uio.no Git - u/mrichter/AliRoot.git/blob - PWGHF/hfe/AliAnalysisTaskHFE.cxx
Update HFE code
[u/mrichter/AliRoot.git] / PWGHF / hfe / AliAnalysisTaskHFE.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 // The analysis task:
17 // Filling an AliCFContainer with the quantities pt, eta and phi
18 // for tracks which survivied the particle cuts (MC resp. ESD tracks)
19 // Track selection is done using the AliHFE package
20 // 
21 // Author:
22 //  Raphaelle Bailhache <R.Bailhache@gsi.de>
23 //  Markus Fasel <M.Fasel@gsi.de>
24 //  Matus Kalisky <matus.kalisky@cern.ch>
25 //  MinJung Kweon <minjung@physi.uni-heidelberg.de>
26 //
27 #include <TAxis.h>
28 #include <TBits.h>
29 #include <TCanvas.h>
30 #include <TChain.h>
31 #include <TDirectory.h>
32 #include <TFile.h>
33 #include <TH3D.h>
34 #include <TIterator.h>
35 #include <TList.h>
36 #include <TLegend.h>
37 #include <TMath.h>
38 #include <TObjArray.h>
39 #include <TObjString.h>
40 #include <TParticle.h>
41 #include <TProfile.h>
42 #include <TString.h>
43 #include <TF1.h>
44 #include <TTree.h>
45
46 #include "AliESDtrackCuts.h"
47 #include "AliAnalysisManager.h"
48 #include "AliAnalysisUtils.h"
49 #include "AliAODInputHandler.h"
50 #include "AliAODMCParticle.h"
51 #include "AliAODTrack.h"
52 #include "AliAODVertex.h"
53 #include "AliCentrality.h"
54 #include "AliCFContainer.h"
55 #include "AliCFManager.h"
56 #include "AliESDEvent.h"
57 #include "AliESDInputHandler.h"
58 #include "AliESDtrack.h"
59 #include "AliLog.h"
60 #include "AliMCEvent.h"
61 #include "AliMCEventHandler.h"
62 #include "AliMCParticle.h"
63 #include "AliMultiplicity.h"
64 #include "AliPID.h"
65 #include "AliPIDResponse.h"
66 #include "AliOADBContainer.h"
67 #include "AliStack.h"
68 #include "AliTriggerAnalysis.h"
69 #include "AliTRDTriggerAnalysis.h"
70 #include "AliVVertex.h"
71
72 #include "AliHFEcollection.h"
73 #include "AliHFEcontainer.h"
74 #include "AliHFEcuts.h"
75 #include "AliHFEelecbackground.h"
76 #include "AliHFENonPhotonicElectron.h"
77 #include "AliHFEmcQA.h"
78 #include "AliHFEpairs.h"
79 #include "AliHFEpid.h"
80 #include "AliHFEpidQAmanager.h"
81 #include "AliHFEsecVtxs.h"
82 #include "AliHFEsecVtx.h"
83 #include "AliHFEsignalCuts.h"
84 #include "AliHFEtaggedTrackAnalysis.h"
85 #include "AliHFEtools.h"
86 #include "AliHFEV0taginfo.h"
87 #include "AliHFEvarManager.h"
88 #include "AliAnalysisTaskHFE.h"
89 #include "AliAODMCHeader.h"
90 #include "TClonesArray.h"
91
92 ClassImp(AliAnalysisTaskHFE)
93
94 //____________________________________________________________
95 AliAnalysisTaskHFE::AliAnalysisTaskHFE():
96 AliAnalysisTaskSE("PID efficiency Analysis")
97   , fAODMCHeader(NULL)
98   , fAODArrayMCInfo(NULL)
99   , fQAlevel(0)
100   , fPlugins(0)
101   , fCollisionSystem(3)
102   , fFillSignalOnly(kTRUE)
103   , fRejectMCFakeTracks(kFALSE)
104   , fFillNoCuts(kFALSE)
105   , fBackGroundFactorApply(kFALSE)
106   , fRemovePileUp(kFALSE)
107   , fIdentifiedAsPileUp(kFALSE)
108   , fIdentifiedAsOutInz(kFALSE)
109   , fPassTheEventCut(kFALSE)
110   , fRejectKinkMother(kTRUE)
111   , fisppMultiBin(kFALSE)
112   , fPbPbUserCentralityBinning(kFALSE)
113   , fRemoveFirstEvent(kFALSE)
114   , fisNonHFEsystematics(kFALSE)
115   , fSpecialTrigger(NULL)
116   , fCentralityF(-1)
117   , fCentralityPercent(-1)
118   , fCentralityEstimator("V0M")
119   , fContributors(0.5)
120   , fWeightBackGround(0.)
121   , fVz(0.0)
122   , fContainer(NULL)
123   , fVarManager(NULL)
124   , fSignalCuts(NULL)
125   , fCFM(NULL)
126   , fTriggerAnalysis(NULL)
127   , fPID(NULL)
128   , fPIDqa(NULL)
129   , fTRDTriggerAnalysismb(NULL)
130   , fTRDTriggerAnalysistrg(NULL)
131   , fPIDpreselect(NULL)
132   , fCuts(NULL)
133   , fTaggedTrackCuts(NULL)
134   , fCleanTaggedTrack(kFALSE)
135   , fVariablesTRDTaggedTrack(kFALSE)
136   , fAnalysisUtils(NULL)
137   , fCutspreselect(NULL)
138   , fSecVtx(NULL)
139   , fElecBackGround(NULL)
140   , fMCQA(NULL)
141   , fTaggedTrackAnalysis(NULL)
142   , fExtraCuts(NULL)
143   , fBackgroundSubtraction(NULL)
144   , fTRDTrigger(kFALSE)
145   , fWhichTRDTrigger(0)
146   , fV0Tagger(NULL)
147   , fQA(NULL)
148   , fOutput(NULL)
149   , fHistMCQA(NULL)
150   , fHistSECVTX(NULL)
151   , fHistELECBACKGROUND(NULL)
152   , fQACollection(NULL)
153 {
154   //
155   // Dummy constructor
156   //
157   memset(fElecBackgroundFactor, 0, sizeof(Double_t) * kElecBgSpecies * kBgPtBins * kCentBins * kBgLevels);
158   memset(fkBackGroundFactorArray, 0, sizeof(TF1 *) * 12);
159   memset(fBinLimit, 0, sizeof(Double_t) * (kBgPtBins+1));
160   memset(&fisppMultiBin, kFALSE, sizeof(fisppMultiBin));
161   memset(fCentralityLimits, 0, sizeof(Float_t) * 12);
162
163   SetppAnalysis();
164 }
165
166 //____________________________________________________________
167 AliAnalysisTaskHFE::AliAnalysisTaskHFE(const char * name):
168   AliAnalysisTaskSE(name)
169   , fAODMCHeader(NULL)
170   , fAODArrayMCInfo(NULL)
171   , fQAlevel(0)
172   , fPlugins(0)
173   , fCollisionSystem(3)
174   , fFillSignalOnly(kTRUE)
175   , fRejectMCFakeTracks(kFALSE)
176   , fFillNoCuts(kFALSE)
177   , fBackGroundFactorApply(kFALSE)
178   , fRemovePileUp(kFALSE)
179   , fIdentifiedAsPileUp(kFALSE)
180   , fIdentifiedAsOutInz(kFALSE)
181   , fPassTheEventCut(kFALSE)  
182   , fRejectKinkMother(kTRUE)
183   , fisppMultiBin(kFALSE)
184   , fPbPbUserCentralityBinning(kFALSE)
185   , fRemoveFirstEvent(kFALSE)
186   , fisNonHFEsystematics(kFALSE)
187   , fSpecialTrigger(NULL)
188   , fCentralityF(-1)
189   , fCentralityPercent(-1)
190   , fCentralityEstimator("V0M")
191   , fContributors(0.5)
192   , fWeightBackGround(0.)
193   , fVz(0.0)
194   , fContainer(NULL)
195   , fVarManager(NULL)
196   , fSignalCuts(NULL)
197   , fCFM(NULL)
198   , fTriggerAnalysis(NULL)
199   , fPID(NULL)
200   , fPIDqa(NULL)
201   , fTRDTriggerAnalysismb(NULL)
202   , fTRDTriggerAnalysistrg(NULL)
203   , fPIDpreselect(NULL)
204   , fCuts(NULL)
205   , fTaggedTrackCuts(NULL)
206   , fCleanTaggedTrack(kFALSE)
207   , fVariablesTRDTaggedTrack(kFALSE)
208   , fAnalysisUtils(NULL)
209   , fCutspreselect(NULL)
210   , fSecVtx(NULL)
211   , fElecBackGround(NULL)
212   , fMCQA(NULL)
213   , fTaggedTrackAnalysis(NULL)
214   , fExtraCuts(NULL)
215   , fBackgroundSubtraction(NULL)
216   , fTRDTrigger(kFALSE)
217   , fWhichTRDTrigger(0)
218   , fV0Tagger(NULL)
219   , fQA(NULL)
220   , fOutput(NULL)
221   , fHistMCQA(NULL)
222   , fHistSECVTX(NULL)
223   , fHistELECBACKGROUND(NULL)
224   , fQACollection(0x0)
225 {
226   //
227   // Default constructor
228   // 
229   DefineOutput(1, TList::Class());
230   DefineOutput(2, TList::Class());
231
232   fV0Tagger = new AliHFEV0taginfo("Tagger");
233   fPID = new AliHFEpid("hfePid");
234   fPIDqa = new AliHFEpidQAmanager;
235   fVarManager = new AliHFEvarManager("hfeVarManager");
236   fAnalysisUtils = new AliAnalysisUtils;
237   fTRDTriggerAnalysismb = new AliTRDTriggerAnalysis();
238   fTRDTriggerAnalysistrg = new AliTRDTriggerAnalysis();
239   fTRDTriggerAnalysistrg->SetRequireMatchElectron(kTRUE);
240
241   memset(fElecBackgroundFactor, 0, sizeof(Double_t) * kElecBgSpecies * kBgPtBins * kCentBins * kBgLevels);
242   memset(fkBackGroundFactorArray, 0, sizeof(TF1 *) * 12);
243   memset(fBinLimit, 0, sizeof(Double_t) * (kBgPtBins+1));
244   memset(&fisppMultiBin, kFALSE, sizeof(fisppMultiBin));
245   memset(fCentralityLimits, 0, sizeof(Float_t) * 12);
246
247   SetppAnalysis();
248 }
249
250 //____________________________________________________________
251 AliAnalysisTaskHFE::AliAnalysisTaskHFE(const AliAnalysisTaskHFE &ref):
252   AliAnalysisTaskSE(ref)
253   , fAODMCHeader(NULL)
254   , fAODArrayMCInfo(NULL)
255   , fQAlevel(0)
256   , fPlugins(0)
257   , fCollisionSystem(ref.fCollisionSystem)
258   , fFillSignalOnly(ref.fFillSignalOnly)
259   , fRejectMCFakeTracks(ref.fRejectMCFakeTracks)
260   , fFillNoCuts(ref.fFillNoCuts)
261   , fBackGroundFactorApply(ref.fBackGroundFactorApply)
262   , fRemovePileUp(ref.fRemovePileUp)
263   , fIdentifiedAsPileUp(ref.fIdentifiedAsPileUp)
264   , fIdentifiedAsOutInz(ref.fIdentifiedAsOutInz)
265   , fPassTheEventCut(ref.fPassTheEventCut)
266   , fRejectKinkMother(ref.fRejectKinkMother)
267   , fisppMultiBin(ref.fisppMultiBin)
268   , fPbPbUserCentralityBinning(ref.fPbPbUserCentralityBinning)
269   , fRemoveFirstEvent(ref.fRemoveFirstEvent)
270   , fisNonHFEsystematics(ref.fisNonHFEsystematics)
271   , fSpecialTrigger(ref.fSpecialTrigger)
272   , fCentralityF(ref.fCentralityF)
273   , fCentralityPercent(ref.fCentralityPercent)
274   , fCentralityEstimator(ref.fCentralityEstimator)
275   , fContributors(ref.fContributors)
276   , fWeightBackGround(ref.fWeightBackGround)
277   , fVz(ref.fVz)
278   , fContainer(NULL)
279   , fVarManager(NULL)
280   , fSignalCuts(NULL)
281   , fCFM(NULL)
282   , fTriggerAnalysis(NULL)
283   , fPID(NULL)
284   , fPIDqa(NULL)
285   , fTRDTriggerAnalysismb(NULL)
286   , fTRDTriggerAnalysistrg(NULL)
287   , fPIDpreselect(NULL)
288   , fCuts(NULL)
289   , fTaggedTrackCuts(NULL)
290   , fCleanTaggedTrack(ref.fCleanTaggedTrack)
291   , fVariablesTRDTaggedTrack(ref.fVariablesTRDTaggedTrack)
292   , fAnalysisUtils(NULL)
293   , fCutspreselect(NULL)
294   , fSecVtx(NULL)
295   , fElecBackGround(NULL)
296   , fMCQA(NULL)
297   , fTaggedTrackAnalysis(NULL)
298   , fExtraCuts(NULL)
299   , fBackgroundSubtraction(NULL)
300   , fTRDTrigger(ref.fTRDTrigger)
301   , fWhichTRDTrigger(ref.fWhichTRDTrigger)
302   , fV0Tagger(NULL)
303   , fQA(NULL)
304   , fOutput(NULL)
305   , fHistMCQA(NULL)
306   , fHistSECVTX(NULL)
307   , fHistELECBACKGROUND(NULL)
308   , fQACollection(NULL)
309 {
310   //
311   // Copy Constructor
312   //
313   ref.Copy(*this);
314 }
315
316 //____________________________________________________________
317 AliAnalysisTaskHFE &AliAnalysisTaskHFE::operator=(const AliAnalysisTaskHFE &ref){
318   //
319   // Assignment operator
320   //
321   if(this == &ref) 
322     ref.Copy(*this);
323   return *this;
324 }
325
326 //____________________________________________________________
327 void AliAnalysisTaskHFE::Copy(TObject &o) const {
328   // 
329   // Copy into object o
330   //
331   AliAnalysisTaskHFE &target = dynamic_cast<AliAnalysisTaskHFE &>(o);
332   target.fAODMCHeader = fAODMCHeader;
333   target.fAODArrayMCInfo = fAODArrayMCInfo;
334   target.fQAlevel = fQAlevel;
335   target.fPlugins = fPlugins;
336   target.fCollisionSystem = fCollisionSystem;
337   target.fFillSignalOnly = fFillSignalOnly;
338   target.fRejectMCFakeTracks = fRejectMCFakeTracks;
339   target.fFillNoCuts = fFillNoCuts;
340   target.fBackGroundFactorApply = fBackGroundFactorApply;
341   target.fRemovePileUp = fRemovePileUp;
342   target.fIdentifiedAsPileUp = fIdentifiedAsPileUp;
343   target.fIdentifiedAsOutInz = fIdentifiedAsOutInz;
344   target.fPassTheEventCut = fPassTheEventCut;
345   target.fRejectKinkMother = fRejectKinkMother;
346   target.fisppMultiBin =   fisppMultiBin;
347   target.fPbPbUserCentralityBinning = fPbPbUserCentralityBinning;
348   target.fRemoveFirstEvent = fRemoveFirstEvent;
349   target.fisNonHFEsystematics = fisNonHFEsystematics;
350   target.fSpecialTrigger = fSpecialTrigger;
351   target.fCentralityF = fCentralityF;
352   target.fCentralityPercent = fCentralityPercent;
353   target.fCentralityEstimator = fCentralityEstimator;
354   target.fContributors = fContributors;
355   target.fWeightBackGround = fWeightBackGround;
356   target.fVz = fVz;
357   target.fContainer = fContainer;
358   target.fVarManager = fVarManager;
359   target.fSignalCuts = fSignalCuts;
360   target.fCFM = fCFM;
361   target.fTriggerAnalysis = fTriggerAnalysis;
362   target.fPID = fPID;
363   target.fPIDqa = fPIDqa;
364   target.fTRDTriggerAnalysismb = fTRDTriggerAnalysismb;
365   target.fTRDTriggerAnalysistrg = fTRDTriggerAnalysistrg;
366   target.fPIDpreselect = fPIDpreselect;
367   target.fCuts = fCuts;
368   target.fTaggedTrackCuts = fTaggedTrackCuts;
369   target.fCleanTaggedTrack = fCleanTaggedTrack;
370   target.fVariablesTRDTaggedTrack = fVariablesTRDTaggedTrack;
371   target.fAnalysisUtils = fAnalysisUtils;
372   target.fCutspreselect = fCutspreselect;
373   target.fSecVtx = fSecVtx;
374   target.fElecBackGround = fElecBackGround;
375   target.fMCQA = fMCQA;
376   target.fTaggedTrackAnalysis = fTaggedTrackAnalysis;
377   target.fExtraCuts = fExtraCuts;
378   target.fBackgroundSubtraction = fBackgroundSubtraction;
379   target.fTRDTrigger = fTRDTrigger;
380   target.fWhichTRDTrigger = fWhichTRDTrigger;
381   target.fV0Tagger = fV0Tagger;
382   target.fQA = fQA;
383   target.fOutput = fOutput;
384   target.fHistMCQA = fHistMCQA;
385   target.fHistSECVTX = fHistSECVTX;
386   target.fHistELECBACKGROUND = fHistELECBACKGROUND;
387   target.fQACollection = fQACollection;
388 }
389
390 //____________________________________________________________
391 AliAnalysisTaskHFE::~AliAnalysisTaskHFE(){
392   //
393   // Destructor
394   //
395   if(fPID) delete fPID;
396   if(fPIDpreselect) delete fPIDpreselect;
397   if(fVarManager) delete fVarManager;
398   if(fTRDTriggerAnalysismb) delete fTRDTriggerAnalysismb;
399   if(fTRDTriggerAnalysistrg) delete fTRDTriggerAnalysistrg;
400   if(fCFM) delete fCFM;
401   if(fTriggerAnalysis) delete fTriggerAnalysis;
402   if(fSignalCuts) delete fSignalCuts;
403   if(fSecVtx) delete fSecVtx;
404   if(fMCQA) delete fMCQA;
405   if(fElecBackGround) delete fElecBackGround;
406   if(fBackgroundSubtraction) delete fBackgroundSubtraction;
407   if(fSpecialTrigger) delete fSpecialTrigger;
408   if(fAnalysisUtils) delete fAnalysisUtils;
409   if(fV0Tagger) delete fV0Tagger;
410   // Delete output objects only if we are not running in PROOF mode because otherwise this produces a crash during merging
411   AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
412   if(mgr && mgr->GetAnalysisType() != AliAnalysisManager::kProofAnalysis){
413     if(fPIDqa) delete fPIDqa;
414     if(fOutput) delete fOutput;
415     if(fQA) delete fQA;
416   }
417 }
418
419 //____________________________________________________________
420 void AliAnalysisTaskHFE::UserCreateOutputObjects(){
421   //
422   // Creating output container and output objects
423   // Here we also Initialize the correction framework container and 
424   // the objects for
425   // - PID
426   // - MC QA
427   // - SecVtx
428   // QA histograms are created if requested
429   // Called once per worker
430   //
431   AliDebug(3, "Creating Output Objects");
432   
433   // Make lists for Output
434   if(!fQA) fQA = new TList;
435   fQA->SetOwner();
436   if(!fOutput) fOutput = new TList;
437   fOutput->SetOwner();
438   
439   // Automatic determination of the analysis mode
440   AliVEventHandler *inputHandler = dynamic_cast<AliVEventHandler *>(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler());
441   if(!TString(inputHandler->IsA()->GetName()).CompareTo("AliAODInputHandler")){
442     SetAODAnalysis();
443   } else {
444     SetESDAnalysis();
445     if(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler())
446       SetHasMCData();
447   }
448   printf("Analysis Mode: %s Analysis\n", IsAODanalysis() ? "AOD" : "ESD");
449   printf("MC Data available %s\n", HasMCData() ? "Yes" : "No");
450
451   // Enable Trigger Analysis
452   fTriggerAnalysis = new AliTriggerAnalysis;
453   fTriggerAnalysis->EnableHistograms();
454   fTriggerAnalysis->SetAnalyzeMC(HasMCData());
455
456   // First Part: Make QA histograms
457   fQACollection = new AliHFEcollection("TaskQA", "QA histos from the Electron Task");
458   fQACollection->CreateTH1F("nElectronTracksEvent", "Number of Electron Candidates", 100, 0, 100);
459   fQACollection->CreateTH1F("nElectron", "Number of electrons", 100, 0, 100);
460   fQACollection->CreateTH2F("radius", "Production Vertex", 100, 0.0, 5.0, 100, 0.0, 5.0);
461   fQACollection->CreateTH1F("nTriggerBit", "Histo Trigger Bit", 22, 0, 22);
462   fQACollection->CreateTH2F("TriggerAnalysis","TRD Trigger Analysis",10,0.,10.,10,0.,10.);
463   fQACollection->CreateTH1F("Filterbegin", "AOD filter of tracks after all cuts", 21, -1, 20);
464   fQACollection->CreateTH1F("Filterend", "AOD filter of tracks after all cuts", 21, -1, 20);
465   fQACollection->CreateTH2F("Kinkbefore", "Kink status before filter; p_{T} (GeV/c); kink status", 100, 0., 20., 3, -0.5, 2.5);
466   fQACollection->CreateTH2F("Kinkafter", "Kink status after filter; p_{T} (GeV/c); kink status", 100, 0., 20., 3, -0.5, 2.5);
467   fQACollection->CreateTH1F("HFPuzzle", "Source definition for electrons from HF", 11, -0.5, 10.5);
468   InitHistoRadius();
469   InitHistoITScluster();
470   InitContaminationQA();
471   fQA->Add(fQACollection);
472
473   // Initialize PID
474   fPID->SetHasMCData(HasMCData());
475   if(!fPID->GetNumberOfPIDdetectors()) fPID->AddDetector("TPC", 0);
476   if(IsQAOn(kPIDqa)){
477     AliInfo("PID QA switched on");
478     fPIDqa->Initialize(fPID);
479     fQA->Add(fPIDqa->MakeList("HFEpidQA"));
480   }
481   fPID->SortDetectors();
482
483   // Background subtraction-------------------------------------------------------------------
484   if (GetPlugin(kNonPhotonicElectron)||GetPlugin(kNonPhotonicElectronBeauty)) {
485     if(!fBackgroundSubtraction) fBackgroundSubtraction = new AliHFENonPhotonicElectron();
486     if(IsAODanalysis()) fBackgroundSubtraction->SetAOD(kTRUE);
487     fBackgroundSubtraction->Init();
488     fOutput->Add(fBackgroundSubtraction->GetListOutput());
489   }
490   //------------------------------------------------------------------------------------------
491
492
493   // Initialize correction Framework and Cuts
494   const Int_t kNcutSteps = AliHFEcuts::kNcutStepsMCTrack + AliHFEcuts::kNcutStepsRecTrack + AliHFEcuts::kNcutStepsDETrack + AliHFEcuts::kNcutStepsSecvtxTrack;
495   fCFM = new AliCFManager;
496   fCFM->SetNStepParticle(kNcutSteps);
497   MakeParticleContainer();
498   MakeEventContainer();
499   // Temporary fix: Initialize particle cuts with NULL
500   for(Int_t istep = 0; istep < kNcutSteps; istep++)
501     fCFM->SetParticleCutsList(istep, NULL);
502   if(!fCuts){
503     AliWarning("Cuts not available. Default cuts will be used");
504     fCuts = new AliHFEcuts;
505     fCuts->CreateStandardCuts();
506   }
507   if(IsAODanalysis()) fCuts->SetAOD();
508   // Make clone for V0 tagging step
509   fCuts->Initialize(fCFM);
510   if(fCuts->IsQAOn()) fQA->Add(fCuts->GetQAhistograms());
511   fSignalCuts = new AliHFEsignalCuts("HFEsignalCuts", "HFE MC Signal definition");
512   fVarManager->SetSignalCuts(fSignalCuts);
513  
514   // add output objects to the List
515   fOutput->AddAt(fContainer, 0);
516   fOutput->AddAt(fCFM->GetEventContainer(), 1);
517   
518   // mcQA----------------------------------
519   if (HasMCData() && IsQAOn(kMCqa)) {
520     AliInfo("MC QA on");
521     if(!fMCQA) fMCQA = new AliHFEmcQA;
522     if(!fHistMCQA) fHistMCQA = new TList();
523     fHistMCQA->SetOwner();
524     if(IsPbPb()) fMCQA->SetPbPb();
525     if(fisppMultiBin) fMCQA->SetPPMultiBin();
526     if(TestBit(kTreeStream)){
527       fMCQA->EnableDebugStreamer();
528     }
529     if(TestBit(kWeightHist)){
530       fMCQA->EnableGetWeightHist();
531     }
532     fMCQA->CreatDefaultHistograms(fHistMCQA);
533     fMCQA->SetBackgroundWeightFactor(fElecBackgroundFactor[0][0][0],fBinLimit);
534     fQA->Add(fHistMCQA);
535   } 
536
537   // secvtx----------------------------------
538   if (GetPlugin(kSecVtx)) {
539     AliInfo("Secondary Vertex Analysis on");
540     if(!fSecVtx) fSecVtx = new AliHFEsecVtx;
541     fSecVtx->SetHasMCData(HasMCData());
542
543     if(!fHistSECVTX) fHistSECVTX = new TList();
544     fHistSECVTX->SetOwner();
545     fSecVtx->CreateHistograms(fHistSECVTX);
546     fOutput->Add(fHistSECVTX);
547   }
548
549   // background----------------------------------
550   if (GetPlugin(kIsElecBackGround)) {
551     AliInfo("Electron BackGround Analysis on");
552     if(!fElecBackGround){
553       AliWarning("ElecBackGround not available. Default elecbackground will be used");
554       fElecBackGround = new AliHFEelecbackground;
555     }
556     fElecBackGround->SetHasMCData(HasMCData());
557
558     if(!fHistELECBACKGROUND) fHistELECBACKGROUND = new TList();
559     fHistELECBACKGROUND->SetOwner();
560     fElecBackGround->CreateHistograms(fHistELECBACKGROUND);
561     fOutput->Add(fHistELECBACKGROUND);
562   }  
563
564   // tagged tracks
565   if(GetPlugin(kTaggedTrackAnalysis)){
566     AliInfo("Analysis on V0-tagged tracks enabled");
567     fTaggedTrackAnalysis = new AliHFEtaggedTrackAnalysis(Form("taggedTrackAnalysis%s", GetName()));
568     fTaggedTrackAnalysis->SetCuts(fTaggedTrackCuts);
569     fTaggedTrackAnalysis->SetClean(fCleanTaggedTrack);
570     if(IsAODanalysis()) fTaggedTrackAnalysis->SetAOD();
571     AliHFEvarManager *varManager = fTaggedTrackAnalysis->GetVarManager();
572     TObjArray *array = fVarManager->GetVariables();
573     Int_t nvars = array->GetEntriesFast();
574     TString namee;
575     for(Int_t v = 0; v < nvars; v++) {
576       AliHFEvarManager::AliHFEvariable *variable = (AliHFEvarManager::AliHFEvariable *) array->At(v);
577       if(!variable) continue;
578       TString name(((AliHFEvarManager::AliHFEvariable *)variable)->GetName());
579       if(!name.CompareTo("source")) namee = TString("species");
580       else namee = TString(name);
581       Int_t nbins = variable->GetNumberOfBins();
582       if(variable->HasUserDefinedBinning()){
583         varManager->AddVariable(namee, nbins, variable->GetBinning());
584       } else {
585         varManager->AddVariable(namee, nbins, variable->GetMinimum(), variable->GetMaximum());
586       }
587       //printf("For AliTaggedTrackAnalysis, had the variable %s and the one used %s\n",(const char*)variable->GetName(),(const char*) namee);
588     }
589     if(fPIDqa->HasHighResolutionHistos()) 
590       fTaggedTrackAnalysis->GetPIDqa()->SetHighResolutionHistos();
591     fTaggedTrackAnalysis->SetPID(fPID);
592     fTaggedTrackAnalysis->SetVariablesTRD(fVariablesTRDTaggedTrack);
593     fTaggedTrackAnalysis->InitContainer();
594     fOutput->Add(fTaggedTrackAnalysis->GetContainer());
595     fQA->Add(fTaggedTrackAnalysis->GetPIDQA());
596     fQA->Add(fTaggedTrackAnalysis->GetCutQA());
597     fQA->Add(fTaggedTrackAnalysis->GetQAcollection());
598   }
599
600   //fQA->Print();
601
602   PrintStatus();
603   // Done!!!
604   PostData(1, fOutput);
605   PostData(2, fQA);
606 }
607
608 //____________________________________________________________
609 void AliAnalysisTaskHFE::UserExec(Option_t *){
610   //
611   // Run the analysis
612   // 
613
614   //printf("test00\n");
615
616   AliDebug(3, "Starting Single Event Analysis");
617   if(!fInputEvent){
618     AliError("Reconstructed Event not available");
619     //printf("Reconstructed Event not available");
620     return;
621   }
622   if(HasMCData() && IsESDanalysis()){
623     AliDebug(4, Form("MC Event: %p", fMCEvent));
624     if(!fMCEvent){
625       AliError("No MC Event, but MC Data required");
626       //printf("No MC Event, but MC Data required");
627       return;
628     }
629   }
630   if(!fCuts){
631     AliError("HFE cuts not available");
632     //printf("HFE cuts not available");
633     return;
634   }
635   if(!fPID->IsInitialized()){
636     // Initialize PID with the given run number
637     fPID->InitializePID(fInputEvent->GetRunNumber());
638   }
639
640   if(fRemoveFirstEvent){
641     if(fAnalysisUtils->IsFirstEventInChunk(fInputEvent)) return;
642   }
643
644   AliESDEvent *ev = dynamic_cast<AliESDEvent *>(fInputEvent);
645   if(ev && fTRDTrigger && (fWhichTRDTrigger<6))
646   {
647       if(!CheckTRDTriggerESD(ev)) return;
648   }
649   if(fInputEvent && fTRDTrigger && (fWhichTRDTrigger>5))
650   {
651       if(!CheckTRDTrigger(fInputEvent)) return;
652   }
653
654   if(IsESDanalysis() && HasMCData()){
655     // Protect against missing MC trees
656     AliMCEventHandler *mcH = dynamic_cast<AliMCEventHandler *>(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler());
657     if(!mcH){ 
658       AliError("No MC Event Handler available");
659       return;
660     }
661     if(!mcH->InitOk()) return;
662     if(!mcH->TreeK()) return;
663     if(!mcH->TreeTR()) return;
664
665     // Background subtraction-------------------------------------------------------------------
666     if(GetPlugin(kNonPhotonicElectron)) fBackgroundSubtraction->SetMCEvent(fMCEvent);
667     //------------------------------------------------------------------------------------------
668   }
669
670   if(IsAODanalysis() && HasMCData()){
671     // take MC info
672     AliAODEvent *aodE = dynamic_cast<AliAODEvent *>(fInputEvent);
673     if(!aodE){ 
674       AliError("No AOD Event");
675       return;
676     }
677     fAODMCHeader = dynamic_cast<AliAODMCHeader *>(fInputEvent->FindListObject(AliAODMCHeader::StdBranchName()));
678     if(!fAODMCHeader){ 
679       AliError("No AliAODMCHeader");
680       //printf("No AliAODMCHeader");
681       return;
682     }
683     fAODArrayMCInfo = dynamic_cast<TClonesArray *>(fInputEvent->FindListObject(AliAODMCParticle::StdBranchName()));
684     if(!fAODArrayMCInfo){ 
685       AliError("No AOD MC particles");
686       //printf("No AOD MC particles");
687       return;
688     }
689     fSignalCuts->SetMCAODInfo(fAODArrayMCInfo);
690     // Background subtraction-------------------------------------------------------------------
691     if (GetPlugin(kNonPhotonicElectron)||GetPlugin(kNonPhotonicElectronBeauty)) fBackgroundSubtraction->SetAODArrayMCInfo(fAODArrayMCInfo);
692     //------------------------------------------------------------------------------------------
693   }
694
695   //printf("test2\n");
696
697   // need the centrality for everything (MC also)
698   fCentralityF = -1;
699   if(!ReadCentrality()) fCentralityF = -1;
700   //printf("pass centrality\n");
701   //printf("Reading fCentralityF %d\n",fCentralityF);
702   
703   // See if pile up and z in the range
704   RejectionPileUpVertexRangeEventCut();
705
706   //printf("test3\n");
707
708   // Protect agains missing 
709   if(HasMCData()){
710     //printf("Has MC data\n");
711     fSignalCuts->SetMCEvent(fMCEvent);
712     ProcessMC();  // Run the MC loop + MC QA in case MC Data are available
713   }
714   
715   AliPIDResponse *pidResponse = fInputHandler->GetPIDResponse();
716   if(!pidResponse){
717     AliDebug(1, "Using default PID Response");
718     pidResponse = AliHFEtools::GetDefaultPID(HasMCData(), fInputEvent->IsA() == AliESDEvent::Class());
719   }
720   fPID->SetPIDResponse(pidResponse);
721   if(fPIDpreselect) fPIDpreselect->SetPIDResponse(pidResponse);
722
723   // Background subtraction-------------------------------------------------------------------
724   if(GetPlugin(kNonPhotonicElectron)||GetPlugin(kNonPhotonicElectronBeauty)) fBackgroundSubtraction->InitRun(fInputEvent,pidResponse);
725   //------------------------------------------------------------------------------------------
726
727   // Event loop
728   if(IsAODanalysis()){
729     //printf("test4\n");
730     ProcessAOD();
731   } else {
732     const char *specialTrigger = GetSpecialTrigger(fInputEvent->GetRunNumber());
733     // Check Trigger selection
734     if(specialTrigger){
735       AliDebug(2, Form("Special Trigger requested: %s", specialTrigger));
736       if(!(ev && ev->IsTriggerClassFired(specialTrigger))){
737         AliDebug(2, "Event not selected"); 
738         return;
739       } else AliDebug(2, "Event Selected");
740     } else AliDebug(2, "No Special Trigger requested");
741     
742     ProcessESD();
743   }
744   // Done!!!
745   PostData(1, fOutput);
746   PostData(2, fQA);
747 }
748
749 //____________________________________________________________
750 void AliAnalysisTaskHFE::Terminate(Option_t *){
751   //
752   // Terminate not implemented at the moment
753   //
754 }
755
756 //_______________________________________________________________
757 Bool_t AliAnalysisTaskHFE::IsEventInBinZero() {
758   //
759   //
760   //
761
762   //printf("test in IsEventInBinZero\n");
763   if(!fInputEvent){
764     AliError("Reconstructed Event not available");
765     return kFALSE;
766   }
767
768   // check vertex
769   const AliVVertex *vertex = fInputEvent->GetPrimaryVertex();
770   if(!vertex) return kTRUE;
771   //if(vertex) return kTRUE;
772
773   // check tracks
774   if(fInputEvent->GetNumberOfTracks()<=0) return kTRUE;
775   //if(fInputEvent->GetNumberOfTracks()>0) return kTRUE;
776   
777   
778   return kFALSE;
779   
780 }
781 //____________________________________________________________
782 void AliAnalysisTaskHFE::ProcessMC(){
783   //
784   // Runs the MC Loop (filling the container for the MC Cut Steps with the observables pt, eta and phi)
785   // In case MC QA is on also MC QA loop is done
786   //
787   AliDebug(3, "Processing MC Information");
788   Double_t eventContainer [4] = {0., 0., 0., 0.};
789   if(IsESDanalysis()) eventContainer[0] = fMCEvent->GetPrimaryVertex()->GetZ();
790   else eventContainer[0] = fAODMCHeader->GetVtxZ();
791   eventContainer[2] = fCentralityF;
792   eventContainer[3] = fContributors;
793   fVz = eventContainer[0];
794   //printf("z position is %f\n",eventContainer[0]);
795   //if(fCFM->CheckEventCuts(AliHFEcuts::kEventStepGenerated, fMCEvent)) 
796   fCFM->GetEventContainer()->Fill(eventContainer,AliHFEcuts::kEventStepGenerated);
797   Int_t nElectrons = 0;
798   if(IsESDanalysis()){
799    if(!((fIdentifiedAsPileUp) || (TMath::Abs(fVz) > fCuts->GetVertexRange()) || (fCentralityF < 0))){ //kStepMCGeneratedZOutNoPileUpCentralityFine
800     if (HasMCData() && IsQAOn(kMCqa)) {
801       AliDebug(2, "Running MC QA");
802
803       if(fMCEvent->Stack()){
804         fMCQA->SetMCEvent(fMCEvent);
805         fMCQA->SetGenEventHeader(fMCEvent->GenEventHeader());
806         fMCQA->SetCentrality(fCentralityF);
807         fMCQA->SetPercentrality(static_cast<Int_t>(fCentralityPercent));
808         if(IsPbPb()) { fMCQA->SetPbPb();}
809         else
810         {
811             if(fisppMultiBin) fMCQA->SetPPMultiBin();
812             else fMCQA->SetPP();
813         }
814         fMCQA->Init();
815
816         fMCQA->GetMesonKine();
817
818         // loop over all tracks for decayed electrons
819         for (Int_t igen = 0; igen < fMCEvent->GetNumberOfTracks(); igen++){
820           TParticle* mcpart = fMCEvent->Stack()->Particle(igen);
821           if(!mcpart) continue;
822           fMCQA->GetQuarkKine(mcpart, igen, AliHFEmcQA::kCharm);
823           fMCQA->GetQuarkKine(mcpart, igen, AliHFEmcQA::kBeauty);
824           fMCQA->GetHadronKine(mcpart, AliHFEmcQA::kCharm);
825           fMCQA->GetHadronKine(mcpart, AliHFEmcQA::kBeauty);
826           fMCQA->GetDecayedKine(mcpart, AliHFEmcQA::kCharm,  AliHFEmcQA::kElectronPDG); // no accept cut
827           fMCQA->GetDecayedKine(mcpart, AliHFEmcQA::kBeauty, AliHFEmcQA::kElectronPDG); // no accept cut
828           fMCQA->GetDecayedKine(mcpart, AliHFEmcQA::kOthers, AliHFEmcQA::kElectronPDG); // no accept cut
829         }
830         //fMCQA->EndOfEventAna(AliHFEmcQA::kCharm);
831         //fMCQA->EndOfEventAna(AliHFEmcQA::kBeauty);
832       }
833
834     } // end of MC QA loop
835    }
836    // -----------------------------------------------------------------
837    fCFM->SetMCEventInfo(fMCEvent);
838    // fCFM->CheckEventCuts(AliCFManager::kEvtRecCuts, fESD);
839   } else {
840     fMCQA->SetMCArray(fAODArrayMCInfo);
841
842     if(!((fIdentifiedAsPileUp) || (TMath::Abs(fVz) > fCuts->GetVertexRange()) || (fCentralityF < 0))){ //kStepMCGeneratedZOutNoPileUpCentralityFine
843       if (HasMCData() && IsQAOn(kMCqa)) {
844         AliDebug(2, "Running MC QA");
845
846         fMCQA->SetCentrality(fCentralityF);
847         fMCQA->SetPercentrality(static_cast<Int_t>(fCentralityPercent));
848
849         if(IsPbPb()) { fMCQA->SetPbPb();}
850         else
851         {
852             if(fisppMultiBin) fMCQA->SetPPMultiBin();
853             else fMCQA->SetPP();
854         }
855         fMCQA->Init();
856
857         //fMCQA->GetMesonKine();
858
859         // loop over all tracks for decayed electrons
860         AliAODMCParticle * mcpart;
861         for (Int_t igen = 0; igen < fAODArrayMCInfo->GetEntriesFast(); igen++){
862           mcpart = dynamic_cast<AliAODMCParticle *>(fAODArrayMCInfo->At(igen));
863           if(!mcpart) continue;
864           fMCQA->GetDecayedKine(mcpart, AliHFEmcQA::kCharm,  AliHFEmcQA::kElectronPDG); // no accept cut
865           fMCQA->GetDecayedKine(mcpart, AliHFEmcQA::kBeauty, AliHFEmcQA::kElectronPDG); // no accept cut
866           fMCQA->GetDecayedKine(mcpart, AliHFEmcQA::kOthers, AliHFEmcQA::kElectronPDG); // no accept cut
867         }
868
869       } // end of MC QA loop
870     }
871
872     fCFM->SetMCEventInfo(fInputEvent);
873   }
874   // Run MC loop
875   AliVParticle *mctrack = NULL;
876   Int_t numberofmctracks = 0;
877   if(IsESDanalysis()){
878     numberofmctracks = fMCEvent->GetNumberOfTracks();
879   }
880   else {
881     numberofmctracks = fAODArrayMCInfo->GetEntriesFast();
882   }
883   AliDebug(3, Form("Number of Tracks: %d",numberofmctracks));
884   //printf("Number of MC track %d\n",numberofmctracks);
885   for(Int_t imc = 0; imc <numberofmctracks; imc++){
886     if(IsESDanalysis()) {
887       if(!(mctrack = fMCEvent->GetTrack(imc))) continue;
888     }
889     else {
890       if(!(mctrack = (AliVParticle *) fAODArrayMCInfo->At(imc))) continue;
891     }
892     //printf("Test in ProcessMC\n");
893     AliDebug(4, "Next MC Track");
894     if(ProcessMCtrack(mctrack)) nElectrons++;
895   }
896
897   // fCFM->CheckEventCuts(AliCFManager::kEvtRecCuts, fESD);
898   fQACollection->Fill("nElectron", nElectrons);
899 }
900
901 //____________________________________________________________
902 void AliAnalysisTaskHFE::ProcessESD(){
903   //
904   // Run Analysis of reconstructed event in ESD Mode
905   // Loop over Tracks, filter according cut steps defined in AliHFEcuts
906   //
907   AliDebug(1, Form("Task %s", GetName()));
908   AliDebug(3, "Processing ESD Event");
909   AliESDEvent *fESD = dynamic_cast<AliESDEvent *>(fInputEvent);
910   if(!fESD){
911     AliError("ESD Event required for ESD Analysis");
912     return;
913   }
914
915   // Set magnetic field if V0 task on
916   if(fTaggedTrackAnalysis) {
917     // Tag all v0s in current event
918     if(fV0Tagger){
919       fV0Tagger->Reset();
920       fV0Tagger->TagV0Tracks(fESD);
921     }
922     fTaggedTrackAnalysis->SetMagneticField(fESD->GetMagneticField());
923     fTaggedTrackAnalysis->SetCentrality(fCentralityF);
924     if(IsPbPb()) fTaggedTrackAnalysis->SetPbPb();
925     else {
926             if(IspPb()) fTaggedTrackAnalysis->SetpPb();
927             else fTaggedTrackAnalysis->SetPP();
928     }
929   }
930
931   // Do event Normalization
932   Double_t eventContainer[4];
933   eventContainer[0] = 0.; 
934   if(HasMCData()) eventContainer[0] = fVz;
935   else {
936     const AliESDVertex* vtxESD = fESD->GetPrimaryVertex();
937     if(vtxESD) eventContainer[0] = vtxESD->GetZ();
938   }
939   eventContainer[1] = 0.;
940   eventContainer[2] = fCentralityF;
941   eventContainer[3] = fContributors;
942   if(fTriggerAnalysis->IsOfflineTriggerFired(fESD, AliTriggerAnalysis::kV0AND))
943     eventContainer[1] = 1.;
944
945   //
946   fCFM->GetEventContainer()->Fill(eventContainer, AliHFEcuts::kEventStepRecNoCut);
947
948   //
949   if(fIdentifiedAsPileUp) return; 
950   fCFM->GetEventContainer()->Fill(eventContainer, AliHFEcuts::kEventStepRecNoPileUp);
951
952   //
953   if(TMath::Abs(fCentralityF) < 0) return; 
954   fCFM->GetEventContainer()->Fill(eventContainer, AliHFEcuts::kEventStepRecCentralityOk);
955   //printf("In ProcessESD %f\n",fCentralityF);
956
957   //
958   if(fIdentifiedAsOutInz) return;
959   fCFM->GetEventContainer()->Fill(eventContainer, AliHFEcuts::kEventStepZRange);  
960
961   //
962   if(!fPassTheEventCut) return;
963   fCFM->GetEventContainer()->Fill(eventContainer, AliHFEcuts::kEventStepReconstructed);
964
965
966   fContainer->NewEvent();
967
968   if (GetPlugin(kIsElecBackGround)) { 
969     fElecBackGround->SetEvent(fESD);
970   }
971   if (GetPlugin(kSecVtx)) {
972     fSecVtx->SetEvent(fESD);
973     fSecVtx->GetPrimaryCondition();
974   }
975
976   if(HasMCData()){
977     if (GetPlugin(kSecVtx)) { 
978       fSecVtx->SetMCEvent(fMCEvent);
979       fSecVtx->SetMCQA(fMCQA); 
980     }
981     if (GetPlugin(kIsElecBackGround)) { 
982       fElecBackGround->SetMCEvent(fMCEvent);
983     }
984   }
985
986   Double_t container[10];
987   memset(container, 0, sizeof(Double_t) * 10);
988   // container for the output THnSparse
989   Double_t dataDca[6]; // [source, pT, dca, centrality]
990   Int_t nElectronCandidates = 0;
991   AliESDtrack *track = NULL, *htrack = NULL;
992   AliMCParticle *mctrack = NULL;
993   AliMCParticle *mctrackmother = NULL;
994
995   Bool_t signal = kTRUE;
996
997   fCFM->SetRecEventInfo(fESD);
998
999   // Get Number of contributors to the primary vertex for multiplicity-dependent correction
1000   Int_t ncontribVtx = 0;
1001   const AliESDVertex *priVtx = fESD->GetPrimaryVertexTracks();
1002   if(priVtx){
1003     ncontribVtx = priVtx->GetNContributors();
1004   }
1005
1006   // minjung for IP QA(temporary ~ 2weeks)
1007   if(!fExtraCuts){
1008     fExtraCuts = new AliHFEextraCuts("hfetmpCuts","HFE tmp Cuts");
1009   }
1010   fExtraCuts->SetRecEventInfo(fESD);
1011
1012   // Electron background analysis 
1013   if (GetPlugin(kIsElecBackGround)) {
1014
1015     AliDebug(2, "Running BackGround Analysis");
1016
1017     fElecBackGround->Reset();
1018
1019   } // end of electron background analysis
1020
1021
1022   // Background subtraction-------------------------------------------------------------------
1023   if (GetPlugin(kNonPhotonicElectron)) fBackgroundSubtraction->FillPoolAssociatedTracks(fInputEvent, fCentralityF);
1024   //------------------------------------------------------------------------------------------
1025
1026   //
1027   // Loop ESD
1028   //
1029   AliDebug(3, Form("Number of Tracks: %d", fESD->GetNumberOfTracks()));
1030   Bool_t kinkmother(kFALSE), kinkdaughter(kFALSE); Double_t kinkstatus(0);
1031   for(Int_t itrack = 0; itrack < fESD->GetNumberOfTracks(); itrack++){
1032     AliDebug(4, "New ESD track");
1033     track = fESD->GetTrack(itrack);
1034     track->SetESDEvent(fESD);
1035     kinkmother = track->GetKinkIndex(0) < 0; kinkdaughter = track->GetKinkIndex(0) > 0;
1036     kinkstatus = 0.;
1037     if(kinkmother) kinkstatus = 1.;
1038     else if(kinkdaughter) kinkstatus = 2.;
1039
1040     // fill counts of v0-identified particles
1041     AliPID::EParticleType v0pid = fV0Tagger ? fV0Tagger->GetV0Info(track->GetID()) : AliPID::kUnknown;
1042     // here the tagged track analysis will run
1043     if(fTaggedTrackAnalysis && v0pid != AliPID::kUnknown){ 
1044       AliDebug(1, Form("Track identified as %s", AliPID::ParticleName(v0pid)));
1045       fTaggedTrackAnalysis->ProcessTrack(track, v0pid);
1046       AliDebug(1, "V0 PID done");
1047     }
1048  
1049
1050     //Fill non-HFE source containers at reconstructed events cut step
1051     AliDebug(3, Form("Doing track %d, %p", itrack, track));
1052
1053
1054     //////////////////////////////////////
1055     // preselect
1056     //////////////////////////////////////
1057     if(fPIDpreselect || fCutspreselect) {
1058       if(!PreSelectTrack(track)) continue;
1059     }
1060
1061     signal = kTRUE;
1062     
1063     // Fill step without any cut
1064           
1065     if(HasMCData()){
1066       // Check if it is electrons near the vertex
1067       if(!(mctrack = dynamic_cast<AliMCParticle *>(fMCEvent->GetTrack(TMath::Abs(track->GetLabel()))))) continue;
1068
1069       if(fFillSignalOnly && !fCFM->CheckParticleCuts(AliHFEcuts::kStepMCGenerated, mctrack)) signal = kFALSE; 
1070       if(fRejectMCFakeTracks && IsMCFakeTrack(track)) signal = kFALSE;
1071       else AliDebug(3, "Signal Electron");
1072
1073       // Fill K pt for Ke3 contributions
1074       if(mctrack && (TMath::Abs(mctrack->Particle()->GetPdgCode())==321)) fQACollection->Fill("Kptspectra",mctrack->Pt());
1075       else if(mctrack && (TMath::Abs(mctrack->Particle()->GetPdgCode())==130)) fQACollection->Fill("K0Lptspectra",mctrack->Pt());
1076     } 
1077     // Cache new Track information inside the var manager
1078     fVarManager->NewTrack(track, mctrack, fCentralityF, -1, signal);
1079
1080     if(fFillNoCuts) {
1081       if(signal || !fFillSignalOnly){
1082         fVarManager->FillContainer(fContainer, "recTrackContReco", AliHFEcuts::kStepRecNoCut, kFALSE);
1083         fVarManager->FillContainer(fContainer, "recTrackContMC", AliHFEcuts::kStepRecNoCut, kTRUE);
1084       }
1085     }
1086   
1087     // RecKine: ITSTPC cuts  
1088     if(!ProcessCutStep(AliHFEcuts::kStepRecKineITSTPC, track)) continue;
1089     
1090     fQACollection->Fill("Kinkbefore", track->Pt(), kinkstatus); 
1091     // RecPrim
1092     if(fRejectKinkMother) { 
1093       if(track->GetKinkIndex(0) != 0) continue; } // Quick and dirty fix to reject both kink mothers and daughters
1094     if(!ProcessCutStep(AliHFEcuts::kStepRecPrim, track)) continue;
1095     fQACollection->Fill("Kinkafter", track->Pt(), kinkstatus); 
1096
1097     // production radius
1098     Double_t pradius[3] = {fCentralityF,track->Pt(),-1.};
1099     Bool_t fill = kFALSE;
1100     if(HasMCData()){
1101       Int_t labelr = track->GetLabel();
1102       if(labelr >=0) {
1103         AliMCParticle *mctrackk = dynamic_cast<AliMCParticle *>(fMCEvent->GetTrack(labelr));
1104         if((mctrackk>=0) && (TMath::Abs(mctrackk->Particle()->GetPdgCode()) == 11)) {
1105           Int_t motherlabel = mctrackk->Particle()->GetFirstMother();
1106           if(motherlabel >= 0){
1107             AliMCParticle *mothertrack = NULL;
1108             if((mothertrack = dynamic_cast<AliMCParticle *>(fMCEvent->GetTrack(motherlabel)))){
1109               TParticle * mother = mothertrack->Particle();
1110               Int_t  pdgmother = mother->GetPdgCode();
1111               if(pdgmother == 22) {
1112                 pradius[2] = mctrackk->Particle()->R();
1113                 fill = kTRUE;
1114               }
1115             }
1116           }
1117         }
1118       }
1119       if(fill)  fQACollection->Fill("RadiusBefore", pradius); 
1120     }
1121
1122     // HFEcuts: ITS layers cuts
1123     if(!ProcessCutStep(AliHFEcuts::kStepHFEcutsITS, track)) continue;
1124   
1125     // production vertex
1126     if(fill)  {
1127       fQACollection->Fill("RadiusAfter", pradius); 
1128       FillProductionVertex(track);
1129     }
1130   
1131     // HFE cuts: TOF PID and mismatch flag
1132     if(!ProcessCutStep(AliHFEcuts::kStepHFEcutsTOF, track)) continue;
1133
1134     // HFE cuts: TPC PID cleanup
1135     if(!ProcessCutStep(AliHFEcuts::kStepHFEcutsTPC, track)) continue;
1136
1137     // HFEcuts: Nb of tracklets TRD0
1138     if(!ProcessCutStep(AliHFEcuts::kStepHFEcutsTRD, track)) continue;
1139
1140     // Fill correlation maps before PID
1141     if(signal && fContainer->GetCorrelationMatrix("correlationstepbeforePID")) {
1142       //printf("Fill correlation maps before PID\n");
1143       fVarManager->FillCorrelationMatrix(fContainer->GetCorrelationMatrix("correlationstepbeforePID"));
1144     }
1145
1146     if(HasMCData()){
1147       //FillProductionVertex(track);
1148
1149       if(fMCQA && signal){
1150         fMCQA->SetCentrality(fCentralityF);
1151         if(mctrack && (TMath::Abs(mctrack->Particle()->GetPdgCode()) == 11)){
1152          Double_t weightElecBgV0[kBgLevels] = {0.,0.,0.};
1153          Double_t hfeimpactRtmp=0., hfeimpactnsigmaRtmp=0.;
1154          fExtraCuts->GetHFEImpactParameters(track, hfeimpactRtmp, hfeimpactnsigmaRtmp);
1155          UChar_t itsPixel = track->GetITSClusterMap();
1156          Double_t ilyrhit=0, ilyrstat=0;
1157          for(Int_t ilyr=0; ilyr<6; ilyr++){
1158            if(TESTBIT(itsPixel, ilyr)) ilyrhit += TMath::Power(2,ilyr);
1159            if(fExtraCuts->CheckITSstatus(fExtraCuts->GetITSstatus(track,ilyr))) ilyrstat += TMath::Power(2,ilyr);
1160          }
1161          fMCQA->SetITSInfo(ilyrhit,ilyrstat);
1162          fMCQA->SetHFEImpactParameters(hfeimpactRtmp, hfeimpactnsigmaRtmp);
1163          fMCQA->SetTrkKine(track->Pt(),track->Eta(), track->Phi());
1164          fMCQA->SetContainerStep(3);
1165          for(Int_t iLevel = 0; iLevel < kBgLevels; iLevel++){
1166            weightElecBgV0[iLevel] = fMCQA->GetWeightFactor(mctrack, iLevel); // positive:conversion e, negative: nonHFE 
1167            if(!fisNonHFEsystematics || IsPbPb())break;   
1168          }
1169          
1170          if(fisNonHFEsystematics){
1171            //Fill additional containers for electron source distinction
1172            Int_t elecSource = 0;
1173            elecSource = fMCQA->GetElecSource(mctrack->Particle(), kTRUE);
1174            const Char_t *sourceName[kElecBgSpecies]={"Pion","Eta","Omega","Phi","EtaPrime","Rho"};
1175            const Char_t *levelName[kBgLevels]={"Best","Lower","Upper"};
1176            Int_t iName = 0;
1177            for(Int_t iSource = AliHFEmcQA::kPi0; iSource <=  AliHFEmcQA::kGammaRho0; iSource++){
1178              if((iSource == AliHFEmcQA::kElse)||(iSource == AliHFEmcQA::kMisID)) continue;
1179              if(elecSource == iSource){
1180                for(Int_t iLevel = 0; iLevel < kBgLevels; iLevel++){
1181                  if(weightElecBgV0[iLevel]>0){ 
1182                    fVarManager->FillContainer(fContainer, Form("conversionElecs%s%s",sourceName[iName], levelName[iLevel]), 3, kFALSE, weightElecBgV0[iLevel]);
1183                  } 
1184                  else if(weightElecBgV0[iLevel]<0){ 
1185                    fVarManager->FillContainer(fContainer, Form("mesonElecs%s%s",sourceName[iName], levelName[iLevel]), 3, kFALSE, -1*weightElecBgV0[iLevel]);
1186                  }
1187                  if(IsPbPb())break;
1188                }
1189                break;
1190              }
1191              iName++;
1192              if(iName == kElecBgSpecies)iName = 0;
1193            }
1194          }
1195          //else{
1196            if(weightElecBgV0[0]>0) {
1197              fVarManager->FillContainer(fContainer, "conversionElecs", 3, kFALSE, weightElecBgV0[0]);
1198              fVarManager->FillContainer(fContainer, "conversionElecs", 4, kTRUE, weightElecBgV0[0]);
1199            }
1200            else if(weightElecBgV0[0]<0) {
1201              fVarManager->FillContainer(fContainer, "mesonElecs", 3, kFALSE, -1*weightElecBgV0[0]);
1202              fVarManager->FillContainer(fContainer, "mesonElecs", 4, kTRUE, -1*weightElecBgV0[0]);
1203            }
1204            //}
1205         }
1206       }
1207
1208       Double_t hfeimpactR4all=0., hfeimpactnsigmaR4all=0.;
1209       Int_t sourceDca =-1;
1210       if(mctrack && (TMath::Abs(mctrack->Particle()->GetPdgCode()) == 211)){
1211         if(track->Pt()>4.){
1212           fExtraCuts->GetHFEImpactParameters(track, hfeimpactR4all, hfeimpactnsigmaR4all);
1213           dataDca[0]=0; //pion
1214           dataDca[1]=track->Pt();
1215           dataDca[2]=hfeimpactR4all;
1216           dataDca[3]=fCentralityF;
1217           dataDca[4] = v0pid;
1218           dataDca[5] = double(track->Charge());
1219           fQACollection->Fill("Dca", dataDca);
1220         }
1221       }
1222       else if(mctrack && (TMath::Abs(mctrack->Particle()->GetPdgCode()) == 11)){ // to increas statistics for Martin
1223         if(signal){
1224           fExtraCuts->GetHFEImpactParameters(track, hfeimpactR4all, hfeimpactnsigmaR4all);
1225           if(fSignalCuts->IsCharmElectron(track)){
1226             sourceDca=1;
1227           }
1228           else if(fSignalCuts->IsBeautyElectron(track)){
1229             sourceDca=2;
1230           }
1231           else if(fSignalCuts->IsGammaElectron(track)){
1232             sourceDca=3;
1233           }
1234           else if(fSignalCuts->IsNonHFElectron(track)){
1235             sourceDca=4;
1236           }
1237           else if(fSignalCuts->IsJpsiElectron(track)){
1238             sourceDca=5;
1239           }
1240           else {
1241             sourceDca=6;
1242           }
1243           dataDca[0]=sourceDca;
1244           dataDca[1]=track->Pt();
1245           dataDca[2]=hfeimpactR4all;
1246           dataDca[3]=fCentralityF;
1247           dataDca[4] = v0pid;
1248           dataDca[5] = double(track->Charge());
1249           if(signal) fQACollection->Fill("Dca", dataDca);
1250         }
1251       }
1252     }
1253
1254     AliHFEpidObject hfetrack;
1255     hfetrack.SetAnalysisType(AliHFEpidObject::kESDanalysis);
1256     hfetrack.SetRecTrack(track);
1257     if(HasMCData()) hfetrack.SetMCTrack(mctrack);
1258     hfetrack.SetCentrality(fCentralityF);
1259     hfetrack.SetMulitplicity(ncontribVtx);
1260     if(IsPbPb()) hfetrack.SetPbPb();
1261     else {
1262         if(IspPb()) hfetrack.SetpPb();
1263         else hfetrack.SetPP();
1264     }
1265     fPID->SetVarManager(fVarManager);
1266     if(!fPID->IsSelected(&hfetrack, fContainer, "recTrackCont", fPIDqa)) continue;
1267     nElectronCandidates++;
1268     
1269     // Background subtraction------------------------------------------------------------------------------------------
1270     if (GetPlugin(kNonPhotonicElectron)) {
1271       Int_t indexmother = -1;
1272       Int_t mcsource = -1;
1273       Int_t mcQAsource = -1;
1274       Double_t weightNonPhotonicFactor = 1.; 
1275       if(HasMCData()){
1276         mcsource = fBackgroundSubtraction->FindMother(mctrack->GetLabel(),indexmother);
1277         if(fBackgroundSubtraction->GetLevelBack()>=0) {
1278           if(fMCQA) {
1279             mcQAsource = fMCQA->GetElecSource(mctrack, kTRUE);
1280             weightNonPhotonicFactor = TMath::Abs(fMCQA->GetWeightFactor(mctrack, fBackgroundSubtraction->GetLevelBack())); // positive:conversion e, negative: nonHFE 
1281           }
1282         }
1283       }
1284       fBackgroundSubtraction->LookAtNonHFE(itrack, track, fInputEvent, weightNonPhotonicFactor, fCentralityF, -1, mcsource, indexmother,mcQAsource);
1285     }
1286     //-----------------------------------------------------------------------------------------------------------------
1287
1288     // Temporary histogram for chi2/ITS cluster
1289     if(IsPbPb()) {
1290       TBits shared = track->GetTPCSharedMap();
1291             Int_t sharebit=0;
1292       if(shared.CountBits() >= 2) sharebit=1;
1293
1294             Double_t itschi2percluster = 0.0;
1295             Double_t itsnbcls = static_cast<Double_t>(track->GetNcls(0));
1296             if(itsnbcls > 0) itschi2percluster = track->GetITSchi2()/itsnbcls;
1297
1298       Double_t itsChi2[7] = {track->Pt(),track->Eta(), track->Phi(),
1299                         static_cast<Double_t>(fCentralityF),static_cast<Double_t>(track->GetTPCsignalN()), static_cast<Double_t>(sharebit),itschi2percluster};
1300       fQACollection->Fill("fChi2perITScluster", itsChi2);
1301     }
1302     else{
1303
1304       Double_t itschi2percluster = 0.0;
1305       Double_t itsnbcls = static_cast<Double_t>(track->GetNcls(0));
1306       if(itsnbcls > 0) itschi2percluster = track->GetITSchi2()/itsnbcls;
1307
1308       Double_t itsChi2[3] = {track->Pt(), static_cast<Double_t>(fCentralityF), itschi2percluster};
1309       fQACollection->Fill("fChi2perITScluster", itsChi2);
1310     }
1311
1312     // Fill Histogram for Hadronic Background
1313     if(HasMCData()){
1314       if(mctrack && (TMath::Abs(mctrack->Particle()->GetPdgCode()) != 11))
1315         fVarManager->FillContainer(fContainer, "hadronicBackground", UInt_t(0), kFALSE);
1316       else if(mctrack){
1317         // Fill Ke3 contributions
1318         Int_t glabel=TMath::Abs(mctrack->GetMother());
1319         if((mctrackmother = dynamic_cast<AliMCParticle *>(fMCEvent->GetTrack(glabel)))){
1320           if(TMath::Abs(mctrackmother->Particle()->GetPdgCode())==321)
1321             fQACollection->Fill("Ke3Kecorr",mctrack->Pt(),mctrackmother->Pt());
1322           else if(TMath::Abs(mctrackmother->Particle()->GetPdgCode())==130)
1323             fQACollection->Fill("Ke3K0Lecorr",mctrack->Pt(),mctrackmother->Pt());
1324         }
1325       }
1326     }
1327
1328     // Fill Containers
1329     if(signal) {
1330       // Apply weight for background contamination
1331       if(fBackGroundFactorApply) {
1332         if(IsPbPb() && fCentralityF >= 0) fWeightBackGround =  fkBackGroundFactorArray[fCentralityF >= 0 ? fCentralityF : 0]->Eval(TMath::Abs(track->P()));
1333         else    fWeightBackGround =  fkBackGroundFactorArray[0]->Eval(TMath::Abs(track->P())); // for pp and pPb
1334
1335         if(fWeightBackGround < 0.0) fWeightBackGround = 0.0;
1336         else if(fWeightBackGround > 1.0) fWeightBackGround = 1.0;
1337         // weightBackGround as special weight
1338         fVarManager->FillContainer(fContainer, "hadronicBackground", 1, kFALSE, fWeightBackGround);
1339       }
1340       fVarManager->FillCorrelationMatrix(fContainer->GetCorrelationMatrix("correlationstepafterPID"));
1341     }
1342
1343     Bool_t bTagged=kFALSE;
1344     if(GetPlugin(kSecVtx)) {
1345       AliDebug(2, "Running Secondary Vertex Analysis");
1346       if(fSecVtx->Process(track) && signal) {
1347         fVarManager->FillContainer(fContainer, "recTrackContSecvtxReco", AliHFEcuts::kStepHFEcutsSecvtx, kFALSE);
1348         fVarManager->FillContainer(fContainer, "recTrackContSecvtxMC", AliHFEcuts::kStepHFEcutsSecvtx, kTRUE);
1349         bTagged=kTRUE;
1350       }
1351     }
1352
1353     // Electron background analysis 
1354     if (GetPlugin(kIsElecBackGround)) {
1355       
1356       AliDebug(2, "Running BackGround Analysis");
1357       
1358       for(Int_t jtrack = 0; jtrack < fESD->GetNumberOfTracks(); jtrack++){
1359         htrack = fESD->GetTrack(jtrack);
1360         if ( itrack == jtrack ) continue;  
1361         fElecBackGround->PairAnalysis(track, htrack); 
1362       }
1363     } // end of electron background analysis
1364
1365     if (GetPlugin(kDEstep)) { 
1366       Double_t weightElecBgV0[kBgLevels] = {0.,0.,0.,};
1367       Int_t elecSource = 0;
1368       Double_t hfeimpactR=0., hfeimpactnsigmaR=0.;
1369       fExtraCuts->GetHFEImpactParameters(track, hfeimpactR, hfeimpactnsigmaR);
1370       if(HasMCData())
1371       {
1372         if(mctrack && (TMath::Abs(mctrack->Particle()->GetPdgCode()) != 11)){
1373             fQACollection->Fill("hadronsBeforeIPcut",track->Pt());
1374         } 
1375         if(fMCQA && signal) {
1376           
1377           fMCQA->SetContainerStep(0);
1378           for(Int_t iLevel = 0; iLevel < kBgLevels; iLevel++){
1379             weightElecBgV0[iLevel] = fMCQA->GetWeightFactor(mctrack, iLevel); // positive:conversion e, negative: nonHFE 
1380             if(!fisNonHFEsystematics || IsPbPb())break;        
1381           }
1382           
1383           if(fisNonHFEsystematics){
1384             //Fill additional containers for electron source distinction           
1385             elecSource = fMCQA->GetElecSource(mctrack->Particle(), kTRUE);
1386             const Char_t *sourceName[kElecBgSpecies]={"Pion","Eta","Omega","Phi","EtaPrime","Rho"};
1387             const Char_t *levelName[kBgLevels]={"Best","Lower","Upper"};
1388             Int_t iName = 0;
1389             for(Int_t iSource = AliHFEmcQA::kPi0; iSource <=  AliHFEmcQA::kGammaRho0; iSource++){
1390               if((iSource == AliHFEmcQA::kElse)||(iSource == AliHFEmcQA::kMisID)) continue;
1391               if(elecSource == iSource){
1392                 for(Int_t iLevel = 0; iLevel < kBgLevels; iLevel++){
1393                   if(weightElecBgV0[iLevel]>0) fVarManager->FillContainer(fContainer, Form("conversionElecs%s%s",sourceName[iName], levelName[iLevel]), 0, kFALSE, weightElecBgV0[iLevel]);
1394                   else if(weightElecBgV0[iLevel]<0) fVarManager->FillContainer(fContainer, Form("mesonElecs%s%s",sourceName[iName], levelName[iLevel]), 0, kFALSE, -1*weightElecBgV0[iLevel]);
1395                   if(IsPbPb())break;
1396                 }
1397                 break;
1398               }
1399               iName++;
1400               if(iName == kElecBgSpecies)iName = 0;
1401             }
1402           }
1403           //else{
1404           if(weightElecBgV0[0]>0) {
1405             fVarManager->FillContainer(fContainer, "conversionElecs", 0, kFALSE, weightElecBgV0[0]);
1406             fVarManager->FillContainer(fContainer, "conversionElecs", 5, kTRUE, weightElecBgV0[0]);
1407           }
1408           else if(weightElecBgV0[0]<0) {
1409             fVarManager->FillContainer(fContainer, "mesonElecs", 0, kFALSE, -1*weightElecBgV0[0]);
1410             fVarManager->FillContainer(fContainer, "mesonElecs", 5, kTRUE, -1*weightElecBgV0[0]);
1411           }  
1412           //}
1413           if(bTagged){ // bg estimation for the secondary vertex tagged signals
1414             if(weightElecBgV0[0]>0) fVarManager->FillContainer(fContainer, "conversionElecs", 2, kFALSE, weightElecBgV0[0]);
1415             else if(weightElecBgV0[0]<0) fVarManager->FillContainer(fContainer, "mesonElecs", 2, kFALSE, -1*weightElecBgV0[0]);
1416           }
1417         }
1418       } // end of MC
1419
1420       dataDca[0]=-1; //for data, don't know the origin
1421       dataDca[1]=track->Pt();
1422       dataDca[2]=hfeimpactR;
1423       dataDca[3]=fCentralityF;
1424       dataDca[4] = v0pid;
1425       dataDca[5] = double(track->Charge());
1426       if (!HasMCData()) fQACollection->Fill("Dca", dataDca);
1427
1428       // Fill Containers for impact parameter analysis
1429       if(!fCFM->CheckParticleCuts(AliHFEcuts::kStepHFEcutsDca + AliHFEcuts::kNcutStepsMCTrack + AliHFEcuts::kNcutStepsRecTrack,track)) continue;
1430       if(signal) {
1431         // Apply weight for background contamination after ip cut
1432         if(fBackGroundFactorApply) {
1433               fWeightBackGround =  fkBackGroundFactorArray[0]->Eval(TMath::Abs(track->P())); // pp case
1434               if(fWeightBackGround < 0.0) fWeightBackGround = 0.0;
1435               else if(fWeightBackGround > 1.0) fWeightBackGround = 1.0;
1436               // weightBackGround as special weight
1437               fVarManager->FillContainer(fContainer, "hadronicBackground", 2, kFALSE, fWeightBackGround);
1438         }
1439       }
1440
1441       if(HasMCData()){
1442         if(fMCQA && signal) {
1443           fMCQA->SetContainerStep(1);
1444           for(Int_t iLevel = 0; iLevel < kBgLevels; iLevel++){
1445             weightElecBgV0[iLevel] = fMCQA->GetWeightFactor(mctrack, iLevel); // positive:conversion e, negative: nonHFE 
1446             if(!fisNonHFEsystematics || IsPbPb())break;        
1447           }       
1448           if(fisNonHFEsystematics){
1449             //Fill additional containers for electron source distinction             
1450             elecSource = fMCQA->GetElecSource(mctrack->Particle(), kTRUE);
1451             const Char_t *sourceName[kElecBgSpecies]={"Pion","Eta","Omega","Phi","EtaPrime","Rho"};
1452             const Char_t *levelName[kBgLevels]={"Best","Lower","Upper"};
1453             Int_t iName = 0;
1454             for(Int_t iSource = AliHFEmcQA::kPi0; iSource <=  AliHFEmcQA::kGammaRho0; iSource++){
1455               if((iSource == AliHFEmcQA::kElse)||(iSource == AliHFEmcQA::kMisID)) continue;
1456               if(elecSource == iSource){
1457                 for(Int_t iLevel = 0; iLevel < kBgLevels; iLevel++){
1458                   if(weightElecBgV0[iLevel]>0) fVarManager->FillContainer(fContainer, Form("conversionElecs%s%s",sourceName[iName], levelName[iLevel]), 1, kFALSE, weightElecBgV0[iLevel]);
1459                   else if(weightElecBgV0[iLevel]<0) fVarManager->FillContainer(fContainer, Form("mesonElecs%s%s",sourceName[iName], levelName[iLevel]), 1, kFALSE, -1*weightElecBgV0[iLevel]);
1460                   if(IsPbPb())break;
1461                 }
1462                 break;
1463               }
1464               iName++;
1465               if(iName == kElecBgSpecies)iName = 0;
1466             }
1467           }
1468           // else{
1469             if(weightElecBgV0[0]>0) {
1470               fVarManager->FillContainer(fContainer, "conversionElecs", 1, kFALSE, weightElecBgV0[0]);
1471               fVarManager->FillContainer(fContainer, "conversionElecs", 6, kTRUE, weightElecBgV0[0]);
1472             }
1473             else if(weightElecBgV0[0]<0) {
1474               fVarManager->FillContainer(fContainer, "mesonElecs", 1, kFALSE, -1*weightElecBgV0[0]);
1475               fVarManager->FillContainer(fContainer, "mesonElecs", 6, kTRUE, -1*weightElecBgV0[0]);
1476             }
1477             //}
1478         }
1479       }
1480       if(signal) {
1481         fVarManager->FillContainer(fContainer, "recTrackContDEReco", AliHFEcuts::kStepHFEcutsDca, kFALSE);
1482         fVarManager->FillContainer(fContainer, "recTrackContDEMC", AliHFEcuts::kStepHFEcutsDca, kTRUE);
1483         fVarManager->FillCorrelationMatrix(fContainer->GetCorrelationMatrix("correlationstepafterDE"));
1484       }
1485       if(HasMCData()){
1486         if(mctrack && (TMath::Abs(mctrack->Particle()->GetPdgCode()) != 11)){
1487           fQACollection->Fill("hadronsAfterIPcut",track->Pt());
1488         }
1489       }
1490     }
1491
1492   }
1493
1494   // Background subtraction-------------------------------------------------------------------
1495   if (GetPlugin(kNonPhotonicElectron)) fBackgroundSubtraction->CountPoolAssociated(fInputEvent, fCentralityF);
1496   //------------------------------------------------------------------------------------------
1497
1498   fQACollection->Fill("nElectronTracksEvent", nElectronCandidates);
1499 }
1500
1501 //____________________________________________________________
1502 void AliAnalysisTaskHFE::ProcessAOD(){
1503   //
1504   // Run Analysis in AOD Mode
1505   // Function is still in development
1506   //
1507   //printf("Process AOD\n");
1508   AliDebug(3, "Processing AOD Event");
1509   Double_t eventContainer[4];
1510   eventContainer[0] = 0.0;
1511   if(HasMCData()) eventContainer[0] = fVz;
1512   else {
1513     if(fInputEvent->GetPrimaryVertex()) eventContainer[0] = fInputEvent->GetPrimaryVertex()->GetZ();
1514   }
1515   eventContainer[1] = 1.; // No Information available in AOD analysis, assume all events have V0AND
1516   eventContainer[2] = fCentralityF; 
1517   eventContainer[3] = fContributors; 
1518   
1519   //printf("value event container %f, %f, %f, %f\n",eventContainer[0],eventContainer[1],eventContainer[2],eventContainer[3]);
1520
1521   AliAODEvent *fAOD = dynamic_cast<AliAODEvent *>(fInputEvent);
1522   if(!fAOD){
1523     AliError("AOD Event required for AOD Analysis");
1524       return;
1525   }
1526
1527   // Set magnetic field if V0 task on
1528   if(fTaggedTrackAnalysis) {
1529     // Tag all v0s in current event
1530     if(fV0Tagger){
1531       fV0Tagger->Reset();
1532       fV0Tagger->TagV0Tracks(fAOD);
1533     }
1534     fTaggedTrackAnalysis->SetMagneticField(fAOD->GetMagneticField());
1535     fTaggedTrackAnalysis->SetCentrality(fCentralityF);
1536     if(IsPbPb()) fTaggedTrackAnalysis->SetPbPb();
1537     else {
1538       if(IspPb()) fTaggedTrackAnalysis->SetpPb();
1539       else fTaggedTrackAnalysis->SetPP();
1540     }
1541   }
1542   
1543   //printf("Will fill\n");
1544   //
1545   fCFM->GetEventContainer()->Fill(eventContainer, AliHFEcuts::kEventStepRecNoCut);
1546   //printf("Fill\n");
1547   //
1548   if(fIdentifiedAsPileUp) return; 
1549   fCFM->GetEventContainer()->Fill(eventContainer, AliHFEcuts::kEventStepRecNoPileUp);
1550
1551   //
1552   if(fIdentifiedAsOutInz) return;
1553   fCFM->GetEventContainer()->Fill(eventContainer, AliHFEcuts::kEventStepZRange);  
1554
1555   //
1556   if(!fPassTheEventCut) return;
1557   fCFM->GetEventContainer()->Fill(eventContainer, AliHFEcuts::kEventStepReconstructed);
1558   //printf("pass\n");
1559
1560   fContainer->NewEvent();
1561
1562   fCFM->SetRecEventInfo(fAOD);
1563
1564   if(!fExtraCuts){
1565     fExtraCuts = new AliHFEextraCuts("hfeExtraCuts","HFE Extra Cuts");
1566   }
1567   fExtraCuts->SetRecEventInfo(fAOD);
1568
1569   // Get Number of contributors to the primary vertex for multiplicity-dependent correction
1570   Int_t ncontribVtx = 0;
1571   AliAODVertex *priVtx = fAOD->GetPrimaryVertex();
1572   if(priVtx){
1573     ncontribVtx = priVtx->GetNContributors();
1574   }
1575
1576   // Look for kink mother
1577   Int_t numberofvertices = fAOD->GetNumberOfVertices();
1578   Double_t listofmotherkink[numberofvertices];
1579   Int_t numberofmotherkink = 0;
1580   for(Int_t ivertex=0; ivertex < numberofvertices; ivertex++) {
1581     AliAODVertex *aodvertex = fAOD->GetVertex(ivertex);
1582     if(!aodvertex) continue;
1583     if(aodvertex->GetType()==AliAODVertex::kKink) {
1584       AliAODTrack *mother = (AliAODTrack *) aodvertex->GetParent();
1585       if(!mother) continue;
1586       Int_t idmother = mother->GetID();
1587       listofmotherkink[numberofmotherkink] = idmother;
1588       //printf("ID %d\n",idmother);
1589       numberofmotherkink++;
1590     }
1591   }
1592   //printf("Number of kink mother in the events %d\n",numberofmotherkink);
1593
1594   // Background subtraction-------------------------------------------------------------------
1595   if (GetPlugin(kNonPhotonicElectron)||GetPlugin(kNonPhotonicElectronBeauty)) fBackgroundSubtraction->FillPoolAssociatedTracks(fInputEvent, fCentralityF);
1596   //------------------------------------------------------------------------------------------
1597
1598   // Loop over tracks
1599   AliAODTrack *track = NULL;
1600   AliAODMCParticle *mctrack = NULL;
1601   Double_t dataDca[6]; // [source, pT, dca, centrality]
1602   Int_t nElectronCandidates = 0;
1603   Bool_t signal;
1604
1605   //printf("Number of track %d\n",(Int_t) fAOD->GetNumberOfTracks());
1606   Bool_t kinkmother(kFALSE), kinkdaughter(kFALSE); Double_t kinkstatus(0);
1607   for(Int_t itrack = 0; itrack < fAOD->GetNumberOfTracks(); itrack++){
1608     kinkmother=kFALSE;
1609     kinkdaughter=kFALSE;
1610     kinkstatus = 0.;
1611     track = fAOD->GetTrack(itrack); mctrack = NULL;
1612     if(!track) continue;
1613
1614     for(int ivx = 0; ivx < numberofmotherkink; ivx++){
1615       if(track->GetID() == listofmotherkink[ivx]){
1616         kinkmother = kTRUE;
1617         break;
1618       }
1619     }
1620     AliAODVertex *pvx = track->GetProdVertex();
1621     if(pvx && (pvx->GetType() == AliAODVertex::kKink)) kinkdaughter = kTRUE;
1622     kinkstatus = 0.;
1623     if(kinkmother) kinkstatus = 1.;
1624     else if(kinkdaughter) kinkstatus = 2.;
1625
1626     // fill counts of v0-identified particles
1627     AliPID::EParticleType v0pid = fV0Tagger ? fV0Tagger->GetV0Info(track->GetID()) : AliPID::kUnknown;
1628     // here the tagged track analysis will run
1629     if(fTaggedTrackAnalysis && v0pid != AliPID::kUnknown){ 
1630       AliDebug(1, Form("Track identified as %s", AliPID::ParticleName(v0pid)));
1631       fTaggedTrackAnalysis->ProcessTrack(track, v0pid);
1632       AliDebug(1, "V0 PID done");
1633     }
1634     
1635     signal = kTRUE;
1636     if(HasMCData()){
1637       Int_t label = TMath::Abs(track->GetLabel());
1638       if(label && label < fAODArrayMCInfo->GetEntriesFast())
1639         mctrack = dynamic_cast<AliAODMCParticle *>(fAODArrayMCInfo->At(label));
1640         if(fFillSignalOnly && !fCFM->CheckParticleCuts(AliHFEcuts::kStepMCGenerated, mctrack)) signal = kFALSE;
1641         if(fRejectMCFakeTracks && IsMCFakeTrack(track)) signal = kFALSE;
1642     }
1643     
1644     fVarManager->NewTrack(track, mctrack, fCentralityF, -1, signal);
1645     
1646     if(fFillNoCuts) {
1647       if(signal || !fFillSignalOnly){
1648         fVarManager->FillContainer(fContainer, "recTrackContReco", AliHFEcuts::kStepRecNoCut, kFALSE);
1649         fVarManager->FillContainer(fContainer, "recTrackContMC", AliHFEcuts::kStepRecNoCut, kTRUE);
1650       }
1651     }
1652
1653     // begin AOD QA
1654     fQACollection->Fill("Filterbegin", -1);  
1655     for(Int_t k=0; k<20; k++) {
1656       Int_t u = 1<<k;
1657       if((track->TestFilterBit(u))) {
1658             fQACollection->Fill("Filterbegin", k);
1659       }
1660     }
1661
1662     // RecKine: ITSTPC cuts  
1663     if(!ProcessCutStep(AliHFEcuts::kStepRecKineITSTPC, track)) continue;
1664
1665     fQACollection->Fill("Kinkbefore", track->Pt(), kinkstatus); 
1666     // Reject kink mother
1667     if(fRejectKinkMother) {
1668       Bool_t kinkmotherpass = kTRUE;
1669       for(Int_t ikinkmother = 0; ikinkmother < numberofmotherkink; ikinkmother++) {
1670         if(track->GetID() == listofmotherkink[ikinkmother]) {
1671           kinkmotherpass = kFALSE;
1672           continue;
1673         }
1674       }
1675       if(!kinkmotherpass) continue;
1676     }       
1677
1678     // RecPrim
1679     if(!ProcessCutStep(AliHFEcuts::kStepRecPrim, track)) continue;
1680     fQACollection->Fill("Kinkafter", track->Pt(), kinkstatus); 
1681
1682     // production radius
1683     Double_t pradius[3] = {fCentralityF,track->Pt(),-1.};
1684     Bool_t fill = kFALSE;
1685     if(HasMCData()){
1686       Int_t labelr = track->GetLabel();
1687       if(labelr>=0) {
1688         AliAODMCParticle *mctrackk = dynamic_cast<AliAODMCParticle *>(fAODArrayMCInfo->At(labelr));
1689         if(mctrackk && (TMath::Abs(mctrackk->GetPdgCode()) == 11)) {
1690           Int_t motherlabel = mctrackk->GetMother();
1691           if((motherlabel>=0) && (motherlabel < fAODArrayMCInfo->GetEntriesFast())) {
1692             AliAODMCParticle *mcmothertrack = dynamic_cast<AliAODMCParticle *>(fAODArrayMCInfo->At(motherlabel));
1693             if(mcmothertrack && (TMath::Abs(mcmothertrack->GetPdgCode()) == 22)) {
1694               pradius[2] = TMath::Sqrt(mctrackk->Xv()*mctrackk->Xv()+mctrackk->Yv()*mctrackk->Yv());
1695               fill = kTRUE;
1696             }
1697           }
1698         }
1699       }
1700       if(fill)  fQACollection->Fill("RadiusBefore", pradius); 
1701     }
1702
1703     // HFEcuts: ITS layers cuts
1704     if(!ProcessCutStep(AliHFEcuts::kStepHFEcutsITS, track)) continue;
1705
1706     // production radius
1707     if(fill) fQACollection->Fill("RadiusAfter", pradius); 
1708       
1709     // HFE cuts: TOF PID and mismatch flag
1710     if(!ProcessCutStep(AliHFEcuts::kStepHFEcutsTOF, track)) continue;
1711       
1712     // HFE cuts: TPC PID cleanup
1713     if(!ProcessCutStep(AliHFEcuts::kStepHFEcutsTPC, track)) continue;
1714     
1715     // HFEcuts: Nb of tracklets TRD0
1716     if(!ProcessCutStep(AliHFEcuts::kStepHFEcutsTRD, track)) continue;
1717
1718     // Fill correlation maps before PID
1719     if(signal && fContainer->GetCorrelationMatrix("correlationstepbeforePID")) {
1720       //printf("Fill correlation maps before PID\n");
1721       fVarManager->FillCorrelationMatrix(fContainer->GetCorrelationMatrix("correlationstepbeforePID"));
1722     }
1723
1724     if(HasMCData()){
1725
1726       if(fMCQA && signal){
1727         fMCQA->SetCentrality(fCentralityF);
1728         if(mctrack && (TMath::Abs(mctrack->GetPdgCode()) == 11)){
1729          Double_t weightElecBgV0[kBgLevels] = {0.,0.,0.};
1730          for(Int_t iLevel = 0; iLevel < kBgLevels; iLevel++){
1731            weightElecBgV0[iLevel] = fMCQA->GetWeightFactor(mctrack, iLevel); // positive:conversion e, negative: nonHFE 
1732          }
1733          if(weightElecBgV0[0]>0) {
1734              fVarManager->FillContainer(fContainer, "conversionElecs", 3, kFALSE, weightElecBgV0[0]);
1735              fVarManager->FillContainer(fContainer, "conversionElecs", 4, kTRUE, weightElecBgV0[0]);
1736          }
1737          else if(weightElecBgV0[0]<0) {
1738              fVarManager->FillContainer(fContainer, "mesonElecs", 3, kFALSE, -1*weightElecBgV0[0]);
1739              fVarManager->FillContainer(fContainer, "mesonElecs", 4, kTRUE, -1*weightElecBgV0[0]);
1740          }
1741         }
1742       }
1743
1744       Double_t hfeimpactR4all=0., hfeimpactnsigmaR4all=0.;
1745       Int_t sourceDca =-1;
1746       if(mctrack && (TMath::Abs(mctrack->GetPdgCode()) == 211)){
1747         if(track->Pt()>4.){
1748           fExtraCuts->GetHFEImpactParameters(track, hfeimpactR4all, hfeimpactnsigmaR4all);
1749           dataDca[0]=0; //pion
1750           dataDca[1]=track->Pt();
1751           dataDca[2]=hfeimpactR4all;
1752           dataDca[3]=fCentralityF;
1753           dataDca[4] = -1; // not store V0 for the moment
1754           dataDca[5] = double(track->Charge());
1755           fQACollection->Fill("Dca", dataDca);
1756         }
1757       }
1758       else if(mctrack && (TMath::Abs(mctrack->GetPdgCode()) == 11)){ // to increas statistics for Martin
1759         if(signal){
1760           fExtraCuts->GetHFEImpactParameters(track, hfeimpactR4all, hfeimpactnsigmaR4all);
1761           if(fSignalCuts->IsCharmElectron(track)){
1762             sourceDca=1;
1763           }
1764           else if(fSignalCuts->IsBeautyElectron(track)){
1765             sourceDca=2;
1766           }
1767           else if(fSignalCuts->IsGammaElectron(track)){
1768             sourceDca=3;
1769           }
1770           else if(fSignalCuts->IsNonHFElectron(track)){
1771             sourceDca=4;
1772           }
1773           else if(fSignalCuts->IsJpsiElectron(track)){
1774             sourceDca=5;
1775           }
1776           else {
1777             sourceDca=6;
1778           }
1779           dataDca[0]=sourceDca;
1780           dataDca[1]=track->Pt();
1781           dataDca[2]=hfeimpactR4all;
1782           dataDca[3]=fCentralityF;
1783           dataDca[4] = -1; // not store V0 for the moment
1784           dataDca[5] = double(track->Charge());
1785           if(signal) fQACollection->Fill("Dca", dataDca);
1786         }
1787       }
1788     }
1789
1790     //printf("Will process to PID\n");
1791
1792     // track accepted, do PID
1793     AliHFEpidObject hfetrack;
1794     hfetrack.SetAnalysisType(AliHFEpidObject::kAODanalysis);
1795     hfetrack.SetRecTrack(track);
1796     if(HasMCData()) hfetrack.SetMCTrack(mctrack);
1797     hfetrack.SetCentrality(fCentralityF);
1798     hfetrack.SetMulitplicity(ncontribVtx); // for correction
1799     if(IsPbPb()) hfetrack.SetPbPb();
1800     else{
1801       if(IspPb()) hfetrack.SetpPb();
1802       else hfetrack.SetPP();
1803     }
1804     fPID->SetVarManager(fVarManager);
1805     if(!fPID->IsSelected(&hfetrack, fContainer, "recTrackCont", fPIDqa)) continue;   
1806     // we will do PID here as soon as possible
1807
1808     // Background subtraction----------------------------------------------------------------------------------------------
1809     if (GetPlugin(kNonPhotonicElectron)&&!GetPlugin(kNonPhotonicElectronBeauty)) {
1810       Int_t indexmother = -1;
1811       Int_t mcsource = -1;  
1812       Int_t mcQAsource = -1;
1813       Double_t weightNonPhotonicFactor = 1.; 
1814       //printf("weight %f \n",weightNonPhotonicFactor);
1815       if(HasMCData() && mctrack){  
1816         mcsource = fBackgroundSubtraction->FindMother(TMath::Abs(track->GetLabel()),indexmother);
1817         if(fBackgroundSubtraction->GetLevelBack()>=0) {
1818           if(fMCQA) {
1819             mcQAsource = fMCQA->GetElecSource(mctrack, kTRUE);
1820             weightNonPhotonicFactor = TMath::Abs(fMCQA->GetWeightFactor(mctrack, fBackgroundSubtraction->GetLevelBack())); // positive:conversion e, negative: nonHFE 
1821             //weightNonPhotonicFactor = TMath::Abs(fMCQA->GetWeightFactorForPrimaries(mctrack, fBackgroundSubtraction->GetLevelBack())); // positive:conversion e, negative: nonHFE 
1822           }
1823         }
1824       }
1825         fBackgroundSubtraction->LookAtNonHFE(itrack, track, fInputEvent, weightNonPhotonicFactor, fCentralityF, -1,mcsource, indexmother,mcQAsource);
1826     }
1827     //---------------------------------------------------------------------------------------------------------------------
1828
1829     // end AOD QA
1830     fQACollection->Fill("Filterend", -1);  
1831     for(Int_t k=0; k<20; k++) {
1832       Int_t u = 1<<k;
1833       if((track->TestFilterBit(u))) {
1834               fQACollection->Fill("Filterend", k);
1835       }
1836     }
1837        
1838     // Apply weight for background contamination
1839     //Double_t weightBackGround = 1.0;
1840     if(signal) {
1841       // Apply weight for background contamination
1842       if(fBackGroundFactorApply) {
1843               if(IsPbPb() && fCentralityF >= 0) fWeightBackGround =  fkBackGroundFactorArray[fCentralityF >= 0 ? fCentralityF : 0]->Eval(TMath::Abs(track->P()));
1844               else    fWeightBackGround =  fkBackGroundFactorArray[0]->Eval(TMath::Abs(track->P())); // pp case
1845         
1846               if(fWeightBackGround < 0.0) fWeightBackGround = 0.0;
1847               else if(fWeightBackGround > 1.0) fWeightBackGround = 1.0;
1848         // weightBackGround as special weight
1849         fVarManager->FillContainer(fContainer, "hadronicBackground", 1, kFALSE, fWeightBackGround);
1850       }
1851       fVarManager->FillCorrelationMatrix(fContainer->GetCorrelationMatrix("correlationstepafterPID"));
1852     }
1853     
1854     nElectronCandidates++;    
1855
1856     if (GetPlugin(kDEstep)) {
1857       if (!HasMCData()){
1858         Double_t hfeimpactR=0., hfeimpactnsigmaR=0.;
1859         fExtraCuts->GetHFEImpactParameters(track, hfeimpactR, hfeimpactnsigmaR);
1860         dataDca[0]=-1; //for data, don't know the origin
1861         dataDca[1]=track->Pt();
1862         dataDca[2]=hfeimpactR;
1863         dataDca[3]=fCentralityF;
1864         dataDca[4] = -1; // not store V0 for the moment
1865         dataDca[5] = double(track->Charge());
1866         fQACollection->Fill("Dca", dataDca);
1867       }
1868
1869       // Fill Containers for impact parameter analysis
1870       if(!fCFM->CheckParticleCuts(AliHFEcuts::kStepHFEcutsDca + AliHFEcuts::kNcutStepsMCTrack + AliHFEcuts::kNcutStepsRecTrack,track)) continue;
1871       if(signal) {
1872         // Apply weight for background contamination after ip cut
1873         if(fBackGroundFactorApply) {
1874               fWeightBackGround =  fkBackGroundFactorArray[0]->Eval(TMath::Abs(track->P())); // pp case
1875               if(fWeightBackGround < 0.0) fWeightBackGround = 0.0;
1876               else if(fWeightBackGround > 1.0) fWeightBackGround = 1.0;
1877               // weightBackGround as special weight
1878               fVarManager->FillContainer(fContainer, "hadronicBackground", 2, kFALSE, fWeightBackGround);
1879         }
1880
1881         fVarManager->FillContainer(fContainer, "recTrackContDEReco", AliHFEcuts::kStepHFEcutsDca, kFALSE);
1882         fVarManager->FillContainer(fContainer, "recTrackContDEMC", AliHFEcuts::kStepHFEcutsDca, kTRUE);
1883         fVarManager->FillCorrelationMatrix(fContainer->GetCorrelationMatrix("correlationstepafterDE"));
1884       }
1885     }
1886
1887     // Background subtraction----------------------------------------------------------------------------------------------
1888     if (!GetPlugin(kNonPhotonicElectron)&&GetPlugin(kNonPhotonicElectronBeauty)) {
1889       Int_t indexmother = -1;
1890       Int_t mcsource = -1;  
1891       Int_t mcQAsource = -1;
1892       Double_t weightNonPhotonicFactor = 1.; 
1893       //printf("weight %f \n",weightNonPhotonicFactor);
1894       if(HasMCData() && mctrack){  
1895         mcsource = fBackgroundSubtraction->FindMother(TMath::Abs(track->GetLabel()),indexmother);
1896         if(fBackgroundSubtraction->GetLevelBack()>=0) {
1897           if(fMCQA) {
1898             mcQAsource = fMCQA->GetElecSource(mctrack, kTRUE);
1899             weightNonPhotonicFactor = TMath::Abs(fMCQA->GetWeightFactor(mctrack, fBackgroundSubtraction->GetLevelBack())); // positive:conversion e, negative: nonHFE 
1900           }
1901         }
1902       }
1903       fBackgroundSubtraction->LookAtNonHFE(itrack, track, fInputEvent, weightNonPhotonicFactor, fCentralityF, -1,mcsource, indexmother,mcQAsource);
1904     }
1905     //---------------------------------------------------------------------------------------------------------------------
1906
1907   }
1908
1909   // Background subtraction-------------------------------------------------------------------
1910   if (GetPlugin(kNonPhotonicElectron)||GetPlugin(kNonPhotonicElectronBeauty)) fBackgroundSubtraction->CountPoolAssociated(fInputEvent, fCentralityF);
1911   //------------------------------------------------------------------------------------------
1912
1913   fQACollection->Fill("nElectronTracksEvent", nElectronCandidates);
1914 }
1915
1916 //____________________________________________________________
1917 Bool_t AliAnalysisTaskHFE::ProcessMCtrack(AliVParticle *track){
1918   //
1919   // Filter the Monte Carlo Track
1920   // Additionally Fill a THnSparse for Signal To Background Studies
1921   // Works for AOD and MC analysis Type
1922   //
1923   fVarManager->NewTrack(track, NULL, fCentralityF, -1, kTRUE);
1924
1925
1926   Double_t vertex[3] = {0.,0.,0.}; // Production vertex cut to mask gammas which are NOT supposed to have hits in the first ITS layer(s)
1927   if(IsESDanalysis()){
1928     AliMCParticle *mctrack = dynamic_cast<AliMCParticle *>(track);
1929     if(mctrack){
1930       vertex[0] = mctrack->Particle()->Vx();
1931       vertex[1] = mctrack->Particle()->Vy();
1932     }
1933   } else {
1934     AliAODMCParticle *aodmctrack = dynamic_cast<AliAODMCParticle *>(track);
1935     if(aodmctrack) aodmctrack->XvYvZv(vertex);
1936   }
1937
1938   //printf("MC Generated\n");
1939   if(!fCFM->CheckParticleCuts(AliHFEcuts::kStepMCGenerated, track)) return kFALSE;
1940   //printf("MC Generated pass\n");
1941   fVarManager->FillContainer(fContainer, "MCTrackCont", AliHFEcuts::kStepMCGenerated, kFALSE);
1942
1943   // Step GeneratedZOutNoPileUp
1944   if((fIdentifiedAsPileUp) || (TMath::Abs(fVz) > fCuts->GetVertexRange()) || (fCentralityF < 0)) return kFALSE;
1945   fVarManager->FillContainer(fContainer, "MCTrackCont", AliHFEcuts::kStepMCGeneratedZOutNoPileUpCentralityFine, kFALSE);
1946   //printf("In ProcessMCtrack %f\n",fCentralityF);
1947
1948   // Step Generated Event Cut
1949   if(!fPassTheEventCut) return kFALSE;
1950   fVarManager->FillContainer(fContainer, "MCTrackCont", AliHFEcuts::kStepMCGeneratedEventCut, kFALSE);
1951
1952   if(IsESDanalysis()){
1953     if(!fCFM->CheckParticleCuts(AliHFEcuts::kStepMCInAcceptance, track)) return kFALSE;
1954     fVarManager->FillContainer(fContainer, "MCTrackCont", AliHFEcuts::kStepMCInAcceptance, kFALSE);
1955   }
1956   return kTRUE;
1957 }
1958
1959 //____________________________________________________________
1960 Bool_t AliAnalysisTaskHFE::PreSelectTrack(AliESDtrack *track) const {
1961   //
1962   // Preselect tracks
1963   //
1964   
1965
1966   Bool_t survived = kTRUE;
1967
1968   if(fCutspreselect) {
1969     //printf("test preselect\n");
1970     if(!fCutspreselect->IsSelected(track)) survived=kFALSE;
1971   }
1972   //printf("survived %d\n",(Int_t)survived);
1973   
1974   if(survived && fPIDpreselect){
1975     // Apply PID
1976     AliHFEpidObject hfetrack;
1977     hfetrack.SetAnalysisType(AliHFEpidObject::kESDanalysis);
1978     hfetrack.SetRecTrack(track);
1979     if(!fPIDpreselect->IsSelected(&hfetrack)) {
1980       //printf("Did not pass AliHFEcuts::kPID\n");
1981       survived = kFALSE;
1982     }
1983     //else printf("Pass AliHFEcuts::kPID\n");
1984   }
1985
1986   return survived; 
1987       
1988 }
1989 //____________________________________________________________
1990 void AliAnalysisTaskHFE::MakeEventContainer(){
1991   //
1992   // Create the event container for the correction framework and link it
1993   // 1st bin: Vertex z-position
1994   // 2nd bin: V0AND decision (normalization to sigma_inel)
1995   // 3rd bin: Centrality class (for pp defined as number of contributors in vertex.)
1996   // 4th bin: Number of contributors > 0
1997   //
1998   
1999   const Int_t kNvar = 4;  // number of variables on the grid: 
2000   Int_t nBins[kNvar] = {120, 2, 11, 2};
2001   Double_t binMin[kNvar] = {-30. , 0., 0.0, 0.};
2002   Double_t binMax[kNvar] = {30., 2., 11.0, 2.};
2003   
2004   AliCFContainer *evCont = new AliCFContainer("eventContainer", "Container for events", AliHFEcuts::kNcutStepsEvent, kNvar, nBins);
2005   
2006   Double_t *vertexBins = AliHFEtools::MakeLinearBinning(nBins[0], binMin[0], binMax[0]);
2007   Double_t *v0andBins = AliHFEtools::MakeLinearBinning(nBins[1], binMin[1], binMax[1]);
2008   Double_t *centralityBins = AliHFEtools::MakeLinearBinning(nBins[2], binMin[2], binMax[2]);
2009   Double_t *contributorsBins = AliHFEtools::MakeLinearBinning(nBins[3], binMin[3], binMax[3]);
2010   evCont->SetBinLimits(0, vertexBins);
2011   evCont->SetBinLimits(1, v0andBins);
2012   evCont->SetBinLimits(2, centralityBins);
2013   evCont->SetBinLimits(3, contributorsBins);
2014   delete[] vertexBins; delete[] v0andBins; delete[] centralityBins; delete[] contributorsBins;
2015     
2016   fCFM->SetEventContainer(evCont);
2017 }
2018
2019 //____________________________________________________________
2020 void AliAnalysisTaskHFE::MakeParticleContainer(){
2021   //
2022   // Create the particle container for the correction framework manager and 
2023   // link it
2024   //
2025   if(!fContainer) fContainer = new AliHFEcontainer("trackContainer");
2026   fVarManager->DefineVariables(fContainer);
2027
2028   // Create Correction Framework containers
2029   fContainer->CreateContainer("MCTrackCont", "Track Container filled with MC information", AliHFEcuts::kNcutStepsMCTrack);
2030   fContainer->CreateContainer("recTrackContReco", "Track Container filled with MC information", AliHFEcuts::kNcutStepsRecTrack + fPID->GetNumberOfPIDdetectors());
2031   fContainer->CreateContainer("recTrackContMC", "Track Container filled with MC information", AliHFEcuts::kNcutStepsRecTrack + fPID->GetNumberOfPIDdetectors());
2032   
2033   fContainer->CreateContainer("hadronicBackground", "Container for Hadronic Background", 3);
2034   fContainer->CreateContainer("recTrackContDEReco", "Container for displaced electron analysis with Reco information", 1);
2035   fContainer->CreateContainer("recTrackContDEMC", "Container for displaced electron analysis with MC information", 1);
2036   fContainer->CreateContainer("recTrackContSecvtxReco", "Container for secondary vertexing analysis with Reco information", 1);
2037   fContainer->CreateContainer("recTrackContSecvtxMC", "Container for secondary vertexing analysis with MC information", 1);
2038
2039   if(HasMCData()){
2040     fContainer->CreateContainer("conversionElecs", "Container for weighted conversion electrons",7);
2041     fContainer->CreateContainer("mesonElecs", "Container for weighted electrons from meson decays",7);
2042     fContainer->Sumw2("conversionElecs");
2043     fContainer->Sumw2("mesonElecs");
2044    
2045     if(fisNonHFEsystematics){
2046       const Char_t *sourceName[kElecBgSpecies]={"Pion","Eta","Omega","Phi","EtaPrime","Rho"};
2047       const Char_t *levelName[kBgLevels]={"Best","Lower","Upper"};
2048       for(Int_t iSource = 0; iSource < kElecBgSpecies; iSource++){
2049         for(Int_t iLevel = 0; iLevel < kBgLevels; iLevel++){
2050           fContainer->CreateContainer(Form("conversionElecs%s%s",sourceName[iSource],levelName[iLevel]), Form("Container for weighted conversion electrons from %s grandm., %s level",sourceName[iSource],levelName[iLevel]),5);
2051           fContainer->CreateContainer(Form("mesonElecs%s%s",sourceName[iSource],levelName[iLevel]), Form("Container for weighted electrons from %s decays, %s level",sourceName[iSource],levelName[iLevel]),5);
2052           fContainer->Sumw2(Form("conversionElecs%s%s",sourceName[iSource],levelName[iLevel]));
2053           fContainer->Sumw2(Form("mesonElecs%s%s",sourceName[iSource],levelName[iLevel]));
2054           if(IsPbPb())break;
2055         }
2056       }
2057     }
2058     //fContainer->CreateContainer("charmElecs", "Container for weighted charm electrons",2);
2059   }
2060
2061   fContainer->CreateCorrelationMatrix("correlationstepafterPID","THnSparse with correlations");
2062   fContainer->CreateCorrelationMatrix("correlationstepafterDE","THnSparse with correlations");
2063   if(!fVarManager->IsVariableDefined("centrality")) {
2064     //printf("Create the two other correlation maps\n");
2065     fContainer->CreateCorrelationMatrix("correlationstepbeforePID","THnSparse with correlations");
2066     fContainer->CreateCorrelationMatrix("correlationstepafterTOF","THnSparse with correlations");
2067   }
2068
2069   // Define the step names
2070   for(UInt_t istep = 0; istep < AliHFEcuts::kNcutStepsMCTrack; istep++){
2071     fContainer->SetStepTitle("MCTrackCont", AliHFEcuts::MCCutName(istep), istep);
2072   }
2073   for(UInt_t istep = 0; istep < AliHFEcuts::kNcutStepsRecTrack; istep++){
2074     fContainer->SetStepTitle("recTrackContReco", AliHFEcuts::RecoCutName(istep), istep);
2075     fContainer->SetStepTitle("recTrackContMC", AliHFEcuts::RecoCutName(istep), istep);
2076   }
2077   for(UInt_t ipid = 0; ipid < fPID->GetNumberOfPIDdetectors(); ipid++){
2078     fContainer->SetStepTitle("recTrackContReco", fPID->SortedDetectorName(ipid), AliHFEcuts::kNcutStepsRecTrack + ipid);
2079     fContainer->SetStepTitle("recTrackContMC", fPID->SortedDetectorName(ipid), AliHFEcuts::kNcutStepsRecTrack + ipid);
2080   }
2081 }
2082 //____________________________________________________________
2083 void AliAnalysisTaskHFE::InitContaminationQA(){
2084   // 
2085   // Add QA for Impact Parameter cut
2086   //
2087
2088   TObjArray *array = fVarManager->GetVariables();
2089   Int_t nvars = array->GetEntriesFast();
2090   for(Int_t v = 0; v < nvars; v++) {
2091     AliHFEvarManager::AliHFEvariable *variable = (AliHFEvarManager::AliHFEvariable *) array->At(v);
2092     if(!variable) continue;
2093     TString name(((AliHFEvarManager::AliHFEvariable *)variable)->GetName());
2094     if(!name.CompareTo("pt")) {
2095       const Int_t nBinPt  = variable->GetNumberOfBins();
2096       const Double_t *kPtRange = variable->GetBinning();
2097
2098       fQACollection->CreateTH1Farray("hadronsBeforeIPcut", "Hadrons before IP cut", nBinPt, kPtRange);
2099       fQACollection->CreateTH1Farray("hadronsAfterIPcut", "Hadrons after IP cut", nBinPt, kPtRange);
2100
2101       fQACollection->CreateTH2Farray("Ke3Kecorr", "Ke3 decay e and K correlation; Ke3K p_{t}; Ke3e p_{t}; ", nBinPt, kPtRange, 20,0.,20.);
2102       fQACollection->CreateTH2Farray("Ke3K0Lecorr", "Ke3 decay e and K0L correlation; Ke3K0L p_{t}; Ke3e p_{t}; ", nBinPt, kPtRange, 20,0.,20.);
2103       fQACollection->CreateTH1Farray("Kptspectra", "Charged Kaons: MC p_{t} ", nBinPt, kPtRange);
2104       fQACollection->CreateTH1Farray("K0Lptspectra", "K0L: MC p_{t} ", nBinPt, kPtRange);
2105
2106       const Double_t kDCAbound[2] = {-0.2, 0.2};
2107
2108       const Int_t nDimDca=6;
2109       const Int_t nBinDca[nDimDca] = { 8, nBinPt, 800, 12,  6, 2};
2110       Double_t minimaDca[nDimDca]  = { -1., 0., kDCAbound[0], -1., -1, -1.1};
2111       Double_t maximaDca[nDimDca]  = { 7., 20., kDCAbound[1], 11.,  5, 1.1};
2112
2113       Double_t *sourceBins = AliHFEtools::MakeLinearBinning(nBinDca[0], minimaDca[0], maximaDca[0]);
2114       Double_t *dcaBins = AliHFEtools::MakeLinearBinning(nBinDca[2], minimaDca[2], maximaDca[2]);
2115       Double_t *centralityBins = AliHFEtools::MakeLinearBinning(nBinDca[3], minimaDca[3], maximaDca[3]);
2116       Double_t *v0PIDBins = AliHFEtools::MakeLinearBinning(nBinDca[4], minimaDca[4], maximaDca[4]);
2117       Double_t *chargeBins = AliHFEtools::MakeLinearBinning(nBinDca[5], minimaDca[5], maximaDca[5]);
2118
2119       fQACollection->CreateTHnSparseNoLimits("Dca", "Dca; source (0-all, 1-charm,etc); pT [GeV/c]; dca; centrality bin; v0pid; charge", nDimDca, nBinDca);
2120       ((THnSparse*)(fQACollection->Get("Dca")))->SetBinEdges(0, sourceBins);
2121       ((THnSparse*)(fQACollection->Get("Dca")))->SetBinEdges(1, kPtRange);
2122       ((THnSparse*)(fQACollection->Get("Dca")))->SetBinEdges(2, dcaBins);
2123       ((THnSparse*)(fQACollection->Get("Dca")))->SetBinEdges(3, centralityBins);
2124       ((THnSparse*)(fQACollection->Get("Dca")))->SetBinEdges(4, v0PIDBins);
2125       ((THnSparse*)(fQACollection->Get("Dca")))->SetBinEdges(5, chargeBins);
2126
2127       break;
2128     }  
2129   }
2130
2131 }
2132 //____________________________________________________________
2133 void AliAnalysisTaskHFE::InitHistoRadius(){
2134   //
2135   
2136   // Before   
2137   const Int_t kNDim = 3;
2138   const Int_t kNBins[kNDim] = {11, 35, 100};
2139   const Double_t kMin[kNDim] = {0,0.1,0.01};
2140   const Double_t kMax[kNDim] = {11,20.,500.};
2141   fQACollection->CreateTHnSparse("RadiusBefore", "RadiusBefore; centrality; p_{T} (GeV/c);radius [cm]", kNDim, kNBins, kMin, kMax);
2142   fQACollection->BinLogAxis("RadiusBefore", 1);
2143   fQACollection->BinLogAxis("RadiusBefore", 2);
2144
2145   // After
2146   fQACollection->CreateTHnSparse("RadiusAfter", "RadiusAfter; centrality; p_{T} (GeV/c);radius [cm]", kNDim, kNBins, kMin, kMax);
2147   fQACollection->BinLogAxis("RadiusAfter", 1);
2148   fQACollection->BinLogAxis("RadiusAfter", 2);
2149
2150
2151 }
2152
2153 //____________________________________________________________
2154 void AliAnalysisTaskHFE::InitHistoITScluster(){
2155   //
2156     // Initialize a temporary histogram to monitor the chi2/ITS cluster
2157     if(IsPbPb()) {
2158         const Int_t kNDim = 7;
2159         const Int_t kNBins[kNDim] = {88, 20,90,11, 160, 2, 1000};
2160         const Double_t kMin[kNDim] = {0.1, -1,0,  0.,0., 0,  0.};
2161         const Double_t kMax[kNDim] = {20., 1, 2.*TMath::Pi(), 11.,160, 2, 100.};
2162         fQACollection->CreateTHnSparse("fChi2perITScluster", "chi2/ITS cluster; p_{T} (GeV/c);eta;phi; centrality class;nclus;sharebit; #chi^{2}/ITS cluster", kNDim, kNBins, kMin, kMax);
2163         fQACollection->BinLogAxis("fChi2perITScluster", 0);
2164     }
2165     else
2166     {
2167         const Int_t kNDim = 3;
2168         const Int_t kNBins[kNDim] = {44, 11, 1000};
2169         const Double_t kMin[kNDim] = {0.1, 0., 0.};
2170         const Double_t kMax[kNDim] = {20., 11., 100.};
2171         fQACollection->CreateTHnSparse("fChi2perITScluster", "chi2/ITS cluster; p_{T} (GeV/c); centrality class; #chi^{2}/ITS cluster", kNDim, kNBins, kMin, kMax);
2172         fQACollection->BinLogAxis("fChi2perITScluster", 0);
2173     }
2174 }
2175
2176 //____________________________________________________________
2177 void AliAnalysisTaskHFE::SelectSpecialTrigger(const Char_t *trgclust, Int_t runMin, Int_t runMax){
2178   //
2179   // Select only events triggered by a special trigeer cluster
2180   //
2181   if(!fSpecialTrigger) fSpecialTrigger = new AliOADBContainer("SpecialTrigger");
2182   fSpecialTrigger->AppendObject(new TObjString(trgclust), runMin, runMax);
2183 }
2184
2185 //____________________________________________________________
2186 const Char_t * AliAnalysisTaskHFE::GetSpecialTrigger(Int_t run){
2187   //
2188   // Derive selected trigger string for given run
2189   //
2190   if(!fSpecialTrigger) return NULL;
2191   TObjString *trg = dynamic_cast<TObjString *>(fSpecialTrigger->GetObject(run));
2192   if(!trg) return NULL;
2193   return trg->String().Data();
2194 }
2195
2196 //____________________________________________________________
2197 void AliAnalysisTaskHFE::PrintStatus() const {
2198   //
2199   // Print Analysis status
2200   //
2201   printf("\n\tAnalysis Settings\n\t========================================\n\n");
2202   printf("\tSecondary Vertex finding: %s\n", GetPlugin(kSecVtx) ? "YES" : "NO");
2203   printf("\tPrimary Vertex resolution: %s\n", GetPlugin(kPriVtx) ? "YES" : "NO");
2204   printf("\tDisplaced electron analysis step: %s\n", GetPlugin(kDEstep) ? "YES" : "NO");
2205   printf("\tTagged Track Analysis: %s\n", GetPlugin(kTaggedTrackAnalysis) ? "YES" : "NO");
2206   printf("\n");
2207   printf("\tParticle Identification Detectors:\n");
2208   fPID->PrintStatus();
2209   printf("\n");
2210   printf("\tQA: \n");
2211   printf("\t\tPID: %s\n", IsQAOn(kPIDqa) ? "YES" :  "NO");
2212   printf("\t\tCUTS: %s\n", (fCuts != NULL && fCuts->IsQAOn()) ? "YES" : "NO");
2213   printf("\t\tMC: %s\n", IsQAOn(kMCqa) ? "YES" : "NO");
2214   printf("\n");
2215 }
2216
2217 //____________________________________________________________
2218 Bool_t AliAnalysisTaskHFE::FillProductionVertex(const AliVParticle * const track) const{
2219   //
2220   // Find the production vertex of the associated MC track
2221   //
2222   if(!fMCEvent) return kFALSE;
2223   const AliVParticle *mctrack = NULL;
2224   TString objectType = track->IsA()->GetName();
2225   if(objectType.CompareTo("AliESDtrack") == 0 || objectType.CompareTo("AliAODTrack") == 0){
2226     // Reconstructed track
2227     mctrack = fMCEvent->GetTrack(TMath::Abs(track->GetLabel()));
2228   } else {
2229     // MCParticle
2230     mctrack = track;
2231   }
2232
2233   if(!mctrack) return kFALSE;
2234
2235   Double_t xv = 0.0;
2236   Double_t yv = 0.0;
2237  
2238   if(TString(mctrack->IsA()->GetName()).CompareTo("AliMCParticle") == 0){
2239     // case MCParticle
2240     const AliMCParticle *mcpart = dynamic_cast<const AliMCParticle *>(mctrack);
2241     if(mcpart){
2242       xv =  mcpart->Xv();
2243       yv =  mcpart->Yv();
2244     }
2245   } else {
2246     // case AODMCParticle
2247     const AliAODMCParticle *mcpart = dynamic_cast<const AliAODMCParticle *>(mctrack);
2248     if(mcpart){
2249       xv =  mcpart->Xv();
2250       yv =  mcpart->Yv();
2251     }
2252   }
2253
2254   //printf("xv %f, yv %f\n",xv,yv);
2255   fQACollection->Fill("radius", TMath::Abs(xv),TMath::Abs(yv));
2256
2257   return kTRUE;
2258
2259 }
2260 //__________________________________________
2261 void AliAnalysisTaskHFE::SwitchOnPlugin(Int_t plug){
2262   //
2263   // Switch on Plugin
2264   // Available:
2265   //  - Primary vertex studies
2266   //  - Secondary vertex Studies
2267   //  - Post Processing
2268   //
2269   switch(plug){
2270     case kPriVtx: SETBIT(fPlugins, plug); break;
2271     case kSecVtx: SETBIT(fPlugins, plug); break;
2272     case kIsElecBackGround: SETBIT(fPlugins, plug); break;
2273     case kPostProcess: SETBIT(fPlugins, plug); break;
2274     case kDEstep: SETBIT(fPlugins, plug); break;
2275     case kTaggedTrackAnalysis: SETBIT(fPlugins, plug); break;
2276     case kNonPhotonicElectron: SETBIT(fPlugins, plug); break; 
2277     case kNonPhotonicElectronBeauty: SETBIT(fPlugins, plug); break; 
2278     default: AliError("Unknown Plugin");
2279   };
2280 }
2281 //__________________________________________
2282 Bool_t AliAnalysisTaskHFE::ProcessCutStep(Int_t cutStep, AliVParticle *track){
2283   //
2284   // Check single track cuts for a given cut step
2285   // Fill the particle container
2286   //
2287   const Int_t kMCOffset = AliHFEcuts::kNcutStepsMCTrack;
2288   if(!fCFM->CheckParticleCuts(cutStep + kMCOffset, track)) return kFALSE;
2289   if(fVarManager->IsSignalTrack()) {
2290     fVarManager->FillContainer(fContainer, "recTrackContReco", cutStep, kFALSE);
2291     fVarManager->FillContainer(fContainer, "recTrackContMC", cutStep, kTRUE);
2292   }
2293   return kTRUE;
2294 }
2295 //___________________________________________________
2296 Bool_t AliAnalysisTaskHFE::ReadCentrality() {
2297   //
2298   // Recover the centrality of the event from ESD or AOD
2299   //
2300   
2301   Float_t fCentralityLimitstemp[12];
2302   Float_t fCentralityLimitsdefault[12]= {0.,5.,10., 20., 30., 40., 50., 60.,70.,80., 90., 100.00001};
2303   if(!fPbPbUserCentralityBinning) memcpy(fCentralityLimitstemp,fCentralityLimitsdefault,sizeof(fCentralityLimitsdefault));
2304   else memcpy(fCentralityLimitstemp,fCentralityLimits,sizeof(fCentralityLimitsdefault));
2305   
2306
2307   Int_t bin = -1;
2308   if(IsPbPb()||IspPb()) {
2309     // Centrality
2310     AliCentrality *centrality = fInputEvent->GetCentrality();
2311     fCentralityPercent = centrality->GetCentralityPercentile(fCentralityEstimator.Data());
2312     //printf("centrality %f\n",fCentralityPercent);
2313
2314     for(Int_t ibin = 0; ibin < 11; ibin++){
2315       if(fCentralityPercent >= fCentralityLimitstemp[ibin] && fCentralityPercent < fCentralityLimitstemp[ibin+1]){
2316         bin = ibin;
2317         //printf("test bin %f, low %f, high %f, %d\n",fCentralityPercent,fCentralityLimitstemp[ibin],fCentralityLimitstemp[ibin+1],ibin);
2318         break;
2319       }
2320     }
2321     
2322     if(bin == -1) bin = 11; // Overflow
2323   } else {
2324     // PP: Tracklet multiplicity, use common definition
2325     Int_t itsMultiplicity = GetITSMultiplicity(fInputEvent);
2326     Int_t multiplicityLimits[8] = {0, 1, 9, 17, 25, 36, 60, 500};
2327     for(Int_t ibin = 0; ibin < 7; ibin++){  
2328       if(itsMultiplicity >= multiplicityLimits[ibin] && itsMultiplicity < multiplicityLimits[ibin + 1]){
2329         bin = ibin;
2330         break;
2331       }
2332     }
2333     if(bin == -1) bin = 7;  // Overflow
2334   }
2335   fCentralityF = bin;
2336   AliDebug(2, Form("Centrality class %d\n", fCentralityF));
2337
2338  
2339   // contributors, to be outsourced
2340   const AliVVertex *vtx;
2341   if(IsAODanalysis()){
2342     AliAODEvent *fAOD = dynamic_cast<AliAODEvent *>(fInputEvent);
2343     if(!fAOD){
2344       AliError("AOD Event required for AOD Analysis");
2345       return kFALSE;
2346     }
2347     vtx = fAOD->GetPrimaryVertex();
2348   } else {
2349     AliESDEvent *fESD = dynamic_cast<AliESDEvent *>(fInputEvent);
2350     if(!fESD){
2351       AliError("ESD Event required for ESD Analysis");
2352       return kFALSE;
2353     }
2354     vtx = fESD->GetPrimaryVertex() ;
2355   }
2356   if(!vtx){ 
2357     fContributors = 0.5;
2358     return kFALSE;
2359   }
2360   else {
2361     Int_t contributorstemp = vtx->GetNContributors();
2362     if( contributorstemp <=  0) {
2363       fContributors =  0.5;
2364       //printf("Number of contributors %d and vz %f\n",contributorstemp,vtx->GetZ());
2365     }
2366     else fContributors = 1.5;
2367     //printf("Number of contributors %d\n",contributorstemp);
2368   }
2369   return kTRUE;
2370 }
2371
2372 //___________________________________________________
2373 Int_t AliAnalysisTaskHFE::GetITSMultiplicity(AliVEvent *ev){
2374   //
2375   // Definition of the Multiplicity according to the JPSI group (F. Kramer)
2376   //
2377   Int_t nTracklets = 0;
2378   Int_t nAcc = 0;
2379   Double_t etaRange = 1.6;
2380
2381   if (ev->IsA() == AliAODEvent::Class()) {
2382     AliAODTracklets *tracklets = ((AliAODEvent*)ev)->GetTracklets();
2383     nTracklets = tracklets->GetNumberOfTracklets();
2384     for (Int_t nn = 0; nn < nTracklets; nn++) {
2385       Double_t theta = tracklets->GetTheta(nn);
2386       Double_t eta = -TMath::Log(TMath::Tan(theta/2.0));
2387       if (TMath::Abs(eta) < etaRange) nAcc++;
2388     }
2389   } else if (ev->IsA() == AliESDEvent::Class()) {
2390     nTracklets = ((AliESDEvent*)ev)->GetMultiplicity()->GetNumberOfTracklets();
2391     for (Int_t nn = 0; nn < nTracklets; nn++) {
2392        Double_t eta = ((AliESDEvent*)ev)->GetMultiplicity()->GetEta(nn);
2393       if (TMath::Abs(eta) < etaRange) nAcc++;
2394     }
2395   } else return -1;
2396
2397   return nAcc;
2398 }
2399
2400 //___________________________________________________
2401 void AliAnalysisTaskHFE::RejectionPileUpVertexRangeEventCut() {
2402   //
2403   // Recover the centrality of the event from ESD or AOD
2404   //
2405  if(IsAODanalysis()){
2406
2407    AliAODEvent *fAOD = dynamic_cast<AliAODEvent *>(fInputEvent);
2408    if(!fAOD){
2409      AliError("AOD Event required for AOD Analysis");
2410        return;
2411    }
2412    // PileUp
2413    fIdentifiedAsPileUp = kFALSE;
2414    if(fRemovePileUp && fAOD->IsPileupFromSPD()) fIdentifiedAsPileUp = kTRUE; 
2415    // Z vertex
2416    fIdentifiedAsOutInz = kFALSE;
2417    //printf("Z vertex %f and out %f\n",fAOD->GetPrimaryVertex()->GetZ(),fCuts->GetVertexRange());
2418    if(TMath::Abs(fAOD->GetPrimaryVertex()->GetZ()) > fCuts->GetVertexRange()) fIdentifiedAsOutInz = kTRUE;
2419    // Event Cut
2420    fPassTheEventCut = kTRUE;
2421    if(!fCFM->CheckEventCuts(AliHFEcuts::kEventStepReconstructed, fAOD)) fPassTheEventCut = kFALSE; 
2422    
2423    
2424  } else {
2425    
2426    AliDebug(3, "Processing ESD Centrality");
2427    AliESDEvent *fESD = dynamic_cast<AliESDEvent *>(fInputEvent);
2428    if(!fESD){
2429      AliError("ESD Event required for ESD Analysis");
2430        return;
2431    }
2432    // PileUp
2433    fIdentifiedAsPileUp = kFALSE;
2434    if(fRemovePileUp && fESD->IsPileupFromSPD()) fIdentifiedAsPileUp = kTRUE; 
2435    
2436
2437
2438    // Z vertex
2439    fIdentifiedAsOutInz = kFALSE;
2440    Bool_t findvertex = kTRUE;
2441    const AliESDVertex* vtxESD = fESD->GetPrimaryVertex();
2442    if((!vtxESD) || (vtxESD->GetNContributors() <= 0)) findvertex = kFALSE;
2443    if(findvertex) {
2444      if(TMath::Abs(vtxESD->GetZ()) > fCuts->GetVertexRange()) fIdentifiedAsOutInz = kTRUE;
2445    }
2446    
2447    //Event Cut
2448    fPassTheEventCut = kTRUE;
2449    if(!fCFM->CheckEventCuts(AliHFEcuts::kEventStepReconstructed, fESD)) fPassTheEventCut = kFALSE;   
2450   
2451  }
2452
2453 }
2454
2455 //___________________________________________________
2456 Bool_t AliAnalysisTaskHFE::CheckTRDTriggerESD(AliESDEvent *ev) {
2457 //
2458 // Check TRD trigger; pPb settings
2459 //
2460     Bool_t cint8=kFALSE;
2461     Bool_t cint7=kFALSE;
2462     Bool_t cint5=kFALSE;
2463     Bool_t cint8s=kFALSE;
2464     Bool_t cint7s=kFALSE;
2465     Bool_t cint7ppb=kFALSE;
2466     Bool_t trdtrgevent=kFALSE;
2467
2468   //  printf("TRIGGERS %s \n",ev->GetFiredTriggerClasses().Data());
2469
2470     if(fWhichTRDTrigger==4) fTRDTriggerAnalysistrg->CalcTriggers(ev);
2471     else fTRDTriggerAnalysismb->CalcTriggers(ev);
2472
2473
2474     // mb selection of WU events
2475     if(fWhichTRDTrigger==1)
2476     {
2477 //      if(ev->IsTriggerClassFired("CINT7WU-B-NOPF-ALL"))
2478         if((ev->IsTriggerClassFired("CINT7WU-B-NOPF-ALL"))||(ev->IsTriggerClassFired("CINT7WU-S-NOPF-ALL"))||(ev->IsTriggerClassFired("CINT8WU-S-NOPF-ALL")))
2479         {
2480             DrawTRDTrigger(ev);
2481             DrawTRDTriggerAnalysis(ev);
2482             return kTRUE;
2483         }
2484         else return kFALSE;
2485     }
2486
2487
2488     // HSE no cleanup
2489     if(fWhichTRDTrigger==2)
2490     {
2491         cint8= ev->IsTriggerClassFired("CINT8WUHSE-B-NOPF-CENT");
2492         cint7= ev->IsTriggerClassFired("CINT7WUHSE-B-NOPF-CENT");  // pPb rare
2493         cint7ppb= ev->IsTriggerClassFired("CINT7WUHSE-B-NOPF-ALL"); // pPb mb
2494         cint8s= ev->IsTriggerClassFired("CINT7WUHSE-S-NOPF-CENT");
2495         cint7s= ev->IsTriggerClassFired("CINT8WUHSE-S-NOPF-CENT");
2496         cint5= (ev->IsTriggerClassFired("CINT5WU-B-NOPF-ALL")) &&
2497             (ev->GetHeader()->GetL1TriggerInputs() & (1 << 10));
2498 //        printf("hse trigger %i %i %i %i %i \n",cint7,cint7ppb,cint8,cint7s,cint8s);
2499         if((cint7==kFALSE)&&(cint7ppb==kFALSE)&&(cint8==kFALSE)&&(cint7s==kFALSE)&&(cint8s==kFALSE)&&(cint5==kFALSE)) return kFALSE;
2500         else
2501         {
2502             DrawTRDTrigger(ev);
2503             DrawTRDTriggerAnalysis(ev);
2504             return kTRUE;
2505         }
2506     }
2507
2508    
2509
2510     //HQU no cleanup
2511     if(fWhichTRDTrigger==3)
2512     {
2513         cint8= ev->IsTriggerClassFired("CINT8WUHQU-B-NOPF-CENT");
2514         cint7= ev->IsTriggerClassFired("CINT7WUHQU-B-NOPF-CENT");    // pPb rare
2515         cint7ppb= ev->IsTriggerClassFired("CINT7WUHQU-B-NOPF-ALL"); // pPb mb
2516         cint8s= ev->IsTriggerClassFired("CINT7WUHQU-S-NOPF-CENT");
2517         cint7s= ev->IsTriggerClassFired("CINT8WUHQU-S-NOPF-CENT");
2518         cint5= (ev->IsTriggerClassFired("CINT5WU-B-NOPF-ALL")) &&
2519             (ev->GetHeader()->GetL1TriggerInputs() & (1 << 12));
2520  //       printf("hqu trigger %i %i %i %i %i \n",cint7,cint7ppb,cint8,cint7s,cint8s);
2521         if((cint7==kFALSE)&&(cint7ppb==kFALSE)&&(cint8==kFALSE)&&(cint7s==kFALSE)&&(cint8s==kFALSE)&&(cint5==kFALSE)) return kFALSE;
2522         else
2523         {
2524             DrawTRDTrigger(ev);
2525             DrawTRDTriggerAnalysis(ev);
2526             return kTRUE;
2527         }
2528     }
2529
2530     if(fWhichTRDTrigger==4)
2531     {
2532 //      printf("trigger %i %i \n", ev->GetHeader()->IsTriggerInputFired("1HSE"),(ev->GetHeader()->GetL1TriggerInputs() & (1 << 10))); // bug in IsTriggerInputFired; reported in savannah
2533
2534 //      if(ev->IsTriggerClassFired("CINT7WU-B-NOPF-ALL"))
2535 //      {
2536 //          Int_t trginput=0;
2537 //          trginput=ev->GetHeader()->GetL1TriggerInputs() & (1 << 10);  // HSE
2538             //      if(trginput==1024)
2539 //          if(fTRDTriggerAnalysismb->CheckCondition(AliTRDTriggerAnalysis::kHSE))
2540         //          if(fTRDTriggerAnalysismb->HasTriggered(AliTRDTriggerAnalysis::kHSE))
2541
2542 //      if(fTRDTriggerAnalysismb->HasFired(AliTRDTriggerAnalysis::kHSE)) // for mb analysis
2543         if(fTRDTriggerAnalysistrg->HasFired(AliTRDTriggerAnalysis::kHSE)) // just to check clean-up effect
2544         {
2545             // check if pre-trigger fired
2546             if((ev->IsTriggerClassFired("CINT7WU-B-NOPF-ALL"))||(ev->IsTriggerClassFired("CINT7WU-S-NOPF-ALL"))||(ev->IsTriggerClassFired("CINT8WU-S-NOPF-ALL")))
2547             {
2548                 DrawTRDTrigger(ev);
2549                 DrawTRDTriggerAnalysis(ev);
2550                 return kTRUE;
2551             } else return kFALSE;
2552         }
2553     }// else return kFALSE;
2554 //    }
2555     if(fWhichTRDTrigger==5)
2556     {
2557 //      printf("trigger %i %i \n", ev->GetHeader()->IsTriggerInputFired("1HQU"),(ev->GetHeader()->GetL1TriggerInputs() & (1 << 12))); // bug in IsTriggerInputFired; reported in savannah
2558 //      if(ev->IsTriggerClassFired("CINT7WU-B-NOPF-ALL"))
2559 //      {
2560
2561 //          Int_t trginput=0;
2562 //          trginput=ev->GetHeader()->GetL1TriggerInputs() & (1 << 12);  //HQU
2563             //        printf("triggerinput %i \n",trginput);
2564             //      if(trginput==4096)
2565 //          if(fTRDTriggerAnalysismb->CheckCondition(AliTRDTriggerAnalysis::kHQU))
2566 //      if(fTRDTriggerAnalysismb->HasTriggered(AliTRDTriggerAnalysis::kHQU))
2567         if(fTRDTriggerAnalysismb->HasFired(AliTRDTriggerAnalysis::kHQU)) // for mb analysis
2568             {
2569                 // check if pre-trigger fired
2570                 if((ev->IsTriggerClassFired("CINT7WU-B-NOPF-ALL"))||(ev->IsTriggerClassFired("CINT7WU-S-NOPF-ALL"))||(ev->IsTriggerClassFired("CINT8WU-S-NOPF-ALL")))
2571                 {
2572                     DrawTRDTrigger(ev);
2573                     DrawTRDTriggerAnalysis(ev);
2574                     return kTRUE;
2575                 } else return kFALSE;
2576             }
2577     } //else return kFALSE;
2578 //    }
2579
2580   
2581
2582
2583
2584
2585     return trdtrgevent;
2586
2587 }
2588
2589
2590 //___________________________________________________
2591 Bool_t AliAnalysisTaskHFE::CheckTRDTrigger(AliVEvent *ev) {
2592 //
2593 // Check TRD trigger; pPb settings
2594 //
2595
2596     if(fWhichTRDTrigger<10) fTRDTriggerAnalysistrg->CalcTriggers(ev);
2597     else fTRDTriggerAnalysismb->CalcTriggers(ev);
2598
2599     // HSE cleanup
2600     if(fWhichTRDTrigger==6)
2601     {
2602         if(fTRDTriggerAnalysistrg->HasTriggeredConfirmed(AliTRDTriggerAnalysis::kHSE)) // for rare period physics analysis
2603         {
2604             //   DrawTRDTrigger(ev);
2605             DrawTRDTriggerAnalysis(ev);
2606             return kTRUE;
2607         } else return kFALSE;
2608     }
2609
2610  
2611
2612     // HQU cleanup
2613     if(fWhichTRDTrigger==7)
2614     {
2615
2616         if(fTRDTriggerAnalysistrg->HasTriggeredConfirmed(AliTRDTriggerAnalysis::kHQU)) // for rare period physics analysis
2617         {
2618             //     DrawTRDTrigger(ev);
2619             DrawTRDTriggerAnalysis(ev);
2620             return kTRUE;
2621         } else return kFALSE;
2622     }
2623
2624     // HSE or HQU cleanup
2625     if(fWhichTRDTrigger==8)
2626     {
2627         if((fTRDTriggerAnalysistrg->HasTriggeredConfirmed(AliTRDTriggerAnalysis::kHSE))||(fTRDTriggerAnalysistrg->HasTriggeredConfirmed(AliTRDTriggerAnalysis::kHQU)))
2628         {
2629             //    DrawTRDTrigger(ev);
2630             DrawTRDTriggerAnalysis(ev);
2631             return kTRUE;
2632         }
2633         else
2634         {
2635             return kFALSE; 
2636         }
2637     }
2638
2639     // HEE cleanup
2640     if(fWhichTRDTrigger==9)
2641     {
2642
2643         if(fTRDTriggerAnalysistrg->HasTriggeredConfirmed(AliTRDTriggerAnalysis::kHEE)) // for rare period physics analysis
2644         {
2645             //     DrawTRDTrigger(ev);
2646             DrawTRDTriggerAnalysis(ev);
2647             return kTRUE;
2648         } else return kFALSE;
2649     }
2650
2651
2652     if(fWhichTRDTrigger==11)
2653     {
2654         if(fTRDTriggerAnalysismb->HasTriggered(AliTRDTriggerAnalysis::kHSE))
2655         {
2656           //  DrawTRDTrigger(ev);
2657             DrawTRDTriggerAnalysis(ev);
2658             return kTRUE;
2659         }   else return kFALSE;
2660     }
2661     if(fWhichTRDTrigger==12)
2662     {
2663         if(fTRDTriggerAnalysismb->HasTriggered(AliTRDTriggerAnalysis::kHQU))
2664         {
2665           //  DrawTRDTrigger(ev);
2666             DrawTRDTriggerAnalysis(ev);
2667             return kTRUE;
2668         }   else return kFALSE;
2669     }
2670     if(fWhichTRDTrigger==13)
2671     {
2672         if(fTRDTriggerAnalysismb->HasTriggered(AliTRDTriggerAnalysis::kHEE))
2673         {
2674           //  DrawTRDTrigger(ev);
2675             DrawTRDTriggerAnalysis(ev);
2676             return kTRUE;
2677         }   else return kFALSE;
2678     }
2679
2680     return kFALSE;
2681
2682 }
2683
2684 //___________________________________________________
2685 void AliAnalysisTaskHFE::DrawTRDTrigger(AliESDEvent *ev) {
2686
2687     Int_t ntriggerbit=0;
2688     fQACollection->Fill("nTriggerBit",ntriggerbit);
2689     if(ev->IsTriggerClassFired("CINT7-B-NOPF-ALLNOTRD"))
2690     {
2691         ntriggerbit=2;
2692         fQACollection->Fill("nTriggerBit",ntriggerbit);
2693     }
2694     if(ev->IsTriggerClassFired("CINT7WU-B-NOPF-ALL"))
2695     {
2696         ntriggerbit=3;
2697         fQACollection->Fill("nTriggerBit",ntriggerbit);
2698         if(ev->IsTriggerClassFired("CINT7WUHSE-B-NOPF-CENT")) {
2699             ntriggerbit=18;
2700             fQACollection->Fill("nTriggerBit",ntriggerbit);
2701         }
2702         if(ev->IsTriggerClassFired("CINT7WUHQU-B-NOPF-CENT")) {
2703             ntriggerbit=19;
2704             fQACollection->Fill("nTriggerBit",ntriggerbit);
2705         }
2706     }
2707     if(ev->IsTriggerClassFired("CINT7WUHJT-B-NOPF-CENT"))
2708     {
2709         ntriggerbit=4;
2710         fQACollection->Fill("nTriggerBit",ntriggerbit);
2711
2712         if(ev->IsTriggerClassFired("CINT7WUHSE-B-NOPF-CENT")) {
2713             ntriggerbit=13;
2714             fQACollection->Fill("nTriggerBit",ntriggerbit);
2715         }
2716         if(ev->IsTriggerClassFired("CINT7WUHQU-B-NOPF-CENT")) {
2717             ntriggerbit=14;
2718             fQACollection->Fill("nTriggerBit",ntriggerbit);
2719             if(ev->IsTriggerClassFired("CINT7WUHSE-B-NOPF-CENT")) {
2720                 ntriggerbit=17;
2721                 fQACollection->Fill("nTriggerBit",ntriggerbit);
2722             }
2723         }
2724     }
2725     if(ev->IsTriggerClassFired("CINT7WUHQU-B-NOPF-CENT"))
2726     {
2727         ntriggerbit=5;
2728         fQACollection->Fill("nTriggerBit",ntriggerbit);
2729         if(ev->IsTriggerClassFired("CINT7WUHSE-B-NOPF-CENT")) {
2730             ntriggerbit=11;
2731             fQACollection->Fill("nTriggerBit",ntriggerbit);
2732         }
2733         if((!(ev->IsTriggerClassFired("CINT7WUHSE-B-NOPF-CENT")))&&(!(ev->IsTriggerClassFired("CINT7WUHJT-B-NOPF-CENT")))) {
2734             ntriggerbit=21;
2735             fQACollection->Fill("nTriggerBit",ntriggerbit);
2736
2737             /*
2738             Int_t nTrdTracks = ev->GetNumberOfTrdTracks();
2739             for (Int_t iTrack = 0; iTrack < nTrdTracks; ++iTrack) {
2740                 AliESDTrdTrack* trdTrack = ev->GetTrdTrack(iTrack);
2741                 printf("GTU track %3i: pt = %5.1f, PID = %3i\n", iTrack, trdTrack->Pt(), trdTrack->GetPID());
2742             }*/
2743
2744
2745         }
2746
2747     }
2748     if(ev->IsTriggerClassFired("CINT7WUHSE-B-NOPF-CENT"))
2749     {
2750         ntriggerbit=6;
2751         fQACollection->Fill("nTriggerBit",ntriggerbit);
2752         if(ev->IsTriggerClassFired("CINT7WUHQU-B-NOPF-CENT")) {
2753             ntriggerbit=12;
2754             fQACollection->Fill("nTriggerBit",ntriggerbit);
2755         }
2756         if(ev->IsTriggerClassFired("CINT7WUHSE-B-NOPF-FAST")){
2757             ntriggerbit=15;
2758             fQACollection->Fill("nTriggerBit",ntriggerbit);
2759
2760             if((!(ev->IsTriggerClassFired("CINT7WUHQU-B-NOPF-CENT")))&&(!(ev->IsTriggerClassFired("CINT7WUHJT-B-NOPF-CENT")))) {
2761                 ntriggerbit=20;
2762                 fQACollection->Fill("nTriggerBit",ntriggerbit);
2763                 /*
2764                  Int_t nTrdTracks = ev->GetNumberOfTrdTracks();
2765                  for (Int_t iTrack = 0; iTrack < nTrdTracks; ++iTrack) {
2766                  AliESDTrdTrack* trdTrack = ev->GetTrdTrack(iTrack);
2767                  printf("HSE GTU track %3i: pt = %5.1f, PID = %3i\n", iTrack, trdTrack->Pt(), trdTrack->GetPID());
2768                  }                          */
2769
2770             }
2771
2772         }
2773
2774     }
2775     if(ev->IsTriggerClassFired("CEMC7WUHEE-B-NOPF-CENT")) {
2776         ntriggerbit=7;
2777         fQACollection->Fill("nTriggerBit",ntriggerbit);
2778     }
2779     if(ev->IsTriggerClassFired("CINT7WUHJT-B-NOPF-FAST")){
2780         ntriggerbit=8;
2781         fQACollection->Fill("nTriggerBit",ntriggerbit);
2782     }
2783     if(ev->IsTriggerClassFired("CINT7WUHQU-B-NOPF-FAST")){
2784         ntriggerbit=9;
2785         fQACollection->Fill("nTriggerBit",ntriggerbit);
2786     }
2787     if(ev->IsTriggerClassFired("CINT7WUHSE-B-NOPF-FAST")){
2788         ntriggerbit=10;
2789         fQACollection->Fill("nTriggerBit",ntriggerbit);
2790         if(ev->IsTriggerClassFired("CINT7WUHSE-B-NOPF-CENT")) {
2791             ntriggerbit=16;
2792             fQACollection->Fill("nTriggerBit",ntriggerbit);
2793         }
2794     }
2795     if(ntriggerbit==0) fQACollection->Fill("nTriggerBit",1);
2796
2797 }
2798
2799
2800 //___________________________________________________
2801 void AliAnalysisTaskHFE::DrawTRDTriggerAnalysis(AliVEvent *ev) {
2802
2803     fTRDTriggerAnalysistrg->CalcTriggers(ev);
2804     for(Int_t itrg=0;itrg<AliTRDTriggerAnalysis::kHlast;itrg++)
2805     {
2806         Int_t trdtrgstatus=0;
2807         if(fTRDTriggerAnalysistrg->CheckCondition((AliTRDTriggerAnalysis::TRDTrigger_t) itrg))trdtrgstatus=1;
2808         if(fTRDTriggerAnalysistrg->HasFired((AliTRDTriggerAnalysis::TRDTrigger_t) itrg))trdtrgstatus=2;
2809         if(fTRDTriggerAnalysistrg->HasTriggered((AliTRDTriggerAnalysis::TRDTrigger_t) itrg))trdtrgstatus=3;
2810         if(fTRDTriggerAnalysistrg->HasTriggeredConfirmed((AliTRDTriggerAnalysis::TRDTrigger_t) itrg))trdtrgstatus=4;
2811         fQACollection->Fill("TriggerAnalysis",(Float_t)itrg,(Float_t)trdtrgstatus);
2812     }
2813 }
2814
2815 //___________________________________________________
2816 Bool_t AliAnalysisTaskHFE::IsMCFakeTrack(const AliVTrack *const trk) const {
2817   //
2818   // Check whether track is MC Fake track using the sign of the track label
2819   //
2820   return trk->GetLabel() < 0;
2821 }