]> git.uio.no Git - u/mrichter/AliRoot.git/blob - PWGHF/hfe/AliAnalysisTaskHFE.cxx
Update for aod pp lego train
[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 "AliAnalysisManager.h"
47 #include "AliAODInputHandler.h"
48 #include "AliAODMCParticle.h"
49 #include "AliAODTrack.h"
50 #include "AliAODVertex.h"
51 #include "AliCentrality.h"
52 #include "AliCFContainer.h"
53 #include "AliCFManager.h"
54 #include "AliESDEvent.h"
55 #include "AliESDInputHandler.h"
56 #include "AliESDtrack.h"
57 #include "AliLog.h"
58 #include "AliMCEvent.h"
59 #include "AliMCEventHandler.h"
60 #include "AliMCParticle.h"
61 #include "AliMultiplicity.h"
62 #include "AliPID.h"
63 #include "AliPIDResponse.h"
64 #include "AliOADBContainer.h"
65 #include "AliStack.h"
66 #include "AliTriggerAnalysis.h"
67 #include "AliVVertex.h"
68
69 #include "AliHFEcollection.h"
70 #include "AliHFEcontainer.h"
71 #include "AliHFEcuts.h"
72 #include "AliHFEelecbackground.h"
73 #include "AliHFEmcQA.h"
74 #include "AliHFEpairs.h"
75 #include "AliHFEpid.h"
76 #include "AliHFEpidQAmanager.h"
77 #include "AliHFEpostAnalysis.h"
78 #include "AliHFEsecVtxs.h"
79 #include "AliHFEsecVtx.h"
80 #include "AliHFEsignalCuts.h"
81 #include "AliHFEtaggedTrackAnalysis.h"
82 #include "AliHFEtools.h"
83 #include "AliHFEvarManager.h"
84 #include "AliAnalysisTaskHFE.h"
85
86 ClassImp(AliAnalysisTaskHFE)
87
88 //____________________________________________________________
89 AliAnalysisTaskHFE::AliAnalysisTaskHFE():
90   AliAnalysisTaskSE("PID efficiency Analysis")
91   , fQAlevel(0)
92   , fPlugins(0)
93   , fFillSignalOnly(kTRUE)
94   , fFillNoCuts(kFALSE)
95   , fUseFlagAOD(kTRUE)
96   , fApplyCutAOD(kFALSE)
97   , fFlags(1<<4)
98   , fBackGroundFactorApply(kFALSE)
99   , fRemovePileUp(kFALSE)
100   , fIdentifiedAsPileUp(kFALSE)
101   , fIdentifiedAsOutInz(kFALSE)
102   , fPassTheEventCut(kFALSE)
103   , fRejectKinkMother(kTRUE)
104   , fisppMultiBin(kFALSE)
105   , fPbPbUserCentralityBinning(kFALSE)
106   , fisNonHFEsystematics(kFALSE)
107   , fSpecialTrigger(NULL)
108   , fCentralityF(-1)
109   , fCentralityPercent(-1)
110   , fContributors(0.5)
111   , fWeightBackGround(0.)
112   , fVz(0.0)
113   , fHadronBackgroundOADB(NULL)
114   , fContainer(NULL)
115   , fVarManager(NULL)
116   , fSignalCuts(NULL)
117   , fCFM(NULL)
118   , fTriggerAnalysis(NULL)
119   , fPID(NULL)
120   , fPIDqa(NULL)
121   , fPIDpreselect(NULL)
122   , fCuts(NULL)
123   , fTaggedTrackCuts(NULL)
124   , fCleanTaggedTrack(kFALSE)
125   , fVariablesTRDTaggedTrack(kFALSE)
126   , fCutspreselect(NULL)
127   , fSecVtx(NULL)
128   , fElecBackGround(NULL)
129   , fMCQA(NULL)
130   , fTaggedTrackAnalysis(NULL)
131   , fExtraCuts(NULL)
132   , fQA(NULL)
133   , fOutput(NULL)
134   , fHistMCQA(NULL)
135   , fHistSECVTX(NULL)
136   , fHistELECBACKGROUND(NULL)
137   , fQACollection(NULL)
138 {
139   //
140   // Dummy constructor
141   //
142   memset(fElecBackgroundFactor, 0, sizeof(Double_t) * kElecBgSpecies * kBgPtBins * kCentBins * kBgLevels);
143   memset(fkBackGroundFactorArray, 0, sizeof(TF1 *) * 12);
144   memset(fBinLimit, 0, sizeof(Double_t) * (kBgPtBins+1));
145   memset(&fisppMultiBin, kFALSE, sizeof(fisppMultiBin));
146   memset(fCentralityLimits, 0, sizeof(Float_t) * 12);
147
148
149 }
150
151 //____________________________________________________________
152 AliAnalysisTaskHFE::AliAnalysisTaskHFE(const char * name):
153   AliAnalysisTaskSE(name)
154   , fQAlevel(0)
155   , fPlugins(0)
156   , fFillSignalOnly(kTRUE)
157   , fFillNoCuts(kFALSE)
158   , fUseFlagAOD(kTRUE)
159   , fApplyCutAOD(kFALSE)
160   , fFlags(1<<4)
161   , fBackGroundFactorApply(kFALSE)
162   , fRemovePileUp(kFALSE)
163   , fIdentifiedAsPileUp(kFALSE)
164   , fIdentifiedAsOutInz(kFALSE)
165   , fPassTheEventCut(kFALSE)  
166   , fRejectKinkMother(kTRUE)
167   , fisppMultiBin(kFALSE)
168   , fPbPbUserCentralityBinning(kFALSE)
169   , fisNonHFEsystematics(kFALSE)
170   , fSpecialTrigger(NULL)
171   , fCentralityF(-1)
172   , fCentralityPercent(-1)
173   , fContributors(0.5)
174   , fWeightBackGround(0.)
175   , fVz(0.0)
176   , fHadronBackgroundOADB(NULL)
177   , fContainer(NULL)
178   , fVarManager(NULL)
179   , fSignalCuts(NULL)
180   , fCFM(NULL)
181   , fTriggerAnalysis(NULL)
182   , fPID(NULL)
183   , fPIDqa(NULL)
184   , fPIDpreselect(NULL)
185   , fCuts(NULL)
186   , fTaggedTrackCuts(NULL)
187   , fCleanTaggedTrack(kFALSE)
188   , fVariablesTRDTaggedTrack(kFALSE)
189   , fCutspreselect(NULL)
190   , fSecVtx(NULL)
191   , fElecBackGround(NULL)
192   , fMCQA(NULL)
193   , fTaggedTrackAnalysis(NULL)
194   , fExtraCuts(NULL)
195   , fQA(NULL)
196   , fOutput(NULL)
197   , fHistMCQA(NULL)
198   , fHistSECVTX(NULL)
199   , fHistELECBACKGROUND(NULL)
200   , fQACollection(0x0)
201 {
202   //
203   // Default constructor
204   // 
205   DefineOutput(1, TList::Class());
206   DefineOutput(2, TList::Class());
207
208   fPID = new AliHFEpid("hfePid");
209   fPIDqa = new AliHFEpidQAmanager;
210   fVarManager = new AliHFEvarManager("hfeVarManager");
211
212   memset(fElecBackgroundFactor, 0, sizeof(Double_t) * kElecBgSpecies * kBgPtBins * kCentBins * kBgLevels);
213   memset(fkBackGroundFactorArray, 0, sizeof(TF1 *) * 12);
214   memset(fBinLimit, 0, sizeof(Double_t) * (kBgPtBins+1));
215   memset(&fisppMultiBin, kFALSE, sizeof(fisppMultiBin));
216   memset(fCentralityLimits, 0, sizeof(Float_t) * 12);
217
218 }
219
220 //____________________________________________________________
221 AliAnalysisTaskHFE::AliAnalysisTaskHFE(const AliAnalysisTaskHFE &ref):
222   AliAnalysisTaskSE(ref)
223   , fQAlevel(0)
224   , fPlugins(0)
225   , fFillSignalOnly(ref.fFillSignalOnly)
226   , fFillNoCuts(ref.fFillNoCuts)
227   , fUseFlagAOD(ref.fUseFlagAOD)
228   , fApplyCutAOD(ref.fApplyCutAOD)
229   , fFlags(ref.fFlags) 
230   , fBackGroundFactorApply(ref.fBackGroundFactorApply)
231   , fRemovePileUp(ref.fRemovePileUp)
232   , fIdentifiedAsPileUp(ref.fIdentifiedAsPileUp)
233   , fIdentifiedAsOutInz(ref.fIdentifiedAsOutInz)
234   , fPassTheEventCut(ref.fPassTheEventCut)
235   , fRejectKinkMother(ref.fRejectKinkMother)
236   , fisppMultiBin(ref.fisppMultiBin)
237   , fPbPbUserCentralityBinning(ref.fPbPbUserCentralityBinning)
238   , fisNonHFEsystematics(ref.fisNonHFEsystematics)
239   , fSpecialTrigger(ref.fSpecialTrigger)
240   , fCentralityF(ref.fCentralityF)
241   , fCentralityPercent(ref.fCentralityPercent)
242   , fContributors(ref.fContributors)
243   , fWeightBackGround(ref.fWeightBackGround)
244   , fVz(ref.fVz)
245   , fHadronBackgroundOADB(ref.fHadronBackgroundOADB)
246   , fContainer(NULL)
247   , fVarManager(NULL)
248   , fSignalCuts(NULL)
249   , fCFM(NULL)
250   , fTriggerAnalysis(NULL)
251   , fPID(NULL)
252   , fPIDqa(NULL)
253   , fPIDpreselect(NULL)
254   , fCuts(NULL)
255   , fTaggedTrackCuts(NULL)
256   , fCleanTaggedTrack(ref.fCleanTaggedTrack)
257   , fVariablesTRDTaggedTrack(ref.fVariablesTRDTaggedTrack)
258   , fCutspreselect(NULL)
259   , fSecVtx(NULL)
260   , fElecBackGround(NULL)
261   , fMCQA(NULL)
262   , fTaggedTrackAnalysis(NULL)
263   , fExtraCuts(NULL)
264   , fQA(NULL)
265   , fOutput(NULL)
266   , fHistMCQA(NULL)
267   , fHistSECVTX(NULL)
268   , fHistELECBACKGROUND(NULL)
269   , fQACollection(NULL)
270 {
271   //
272   // Copy Constructor
273   //
274   ref.Copy(*this);
275 }
276
277 //____________________________________________________________
278 AliAnalysisTaskHFE &AliAnalysisTaskHFE::operator=(const AliAnalysisTaskHFE &ref){
279   //
280   // Assignment operator
281   //
282   if(this == &ref) 
283     ref.Copy(*this);
284   return *this;
285 }
286
287 //____________________________________________________________
288 void AliAnalysisTaskHFE::Copy(TObject &o) const {
289   // 
290   // Copy into object o
291   //
292   AliAnalysisTaskHFE &target = dynamic_cast<AliAnalysisTaskHFE &>(o);
293   target.fQAlevel = fQAlevel;
294   target.fPlugins = fPlugins;
295   target.fFillSignalOnly = fFillSignalOnly;
296   target.fFillNoCuts = fFillNoCuts;
297   target.fUseFlagAOD = fUseFlagAOD;
298   target.fApplyCutAOD = fApplyCutAOD;
299   target.fFlags = fFlags;
300   target.fBackGroundFactorApply = fBackGroundFactorApply;
301   target.fRemovePileUp = fRemovePileUp;
302   target.fIdentifiedAsPileUp = fIdentifiedAsPileUp;
303   target.fIdentifiedAsOutInz = fIdentifiedAsOutInz;
304   target.fPassTheEventCut = fPassTheEventCut;
305   target.fRejectKinkMother = fRejectKinkMother;
306   target.fisppMultiBin =   fisppMultiBin;
307   target.fPbPbUserCentralityBinning = fPbPbUserCentralityBinning;
308   target.fisNonHFEsystematics = fisNonHFEsystematics;
309   target.fSpecialTrigger = fSpecialTrigger;
310   target.fCentralityF = fCentralityF;
311   target.fCentralityPercent = fCentralityPercent;
312   target.fContributors = fContributors;
313   target.fWeightBackGround = fWeightBackGround;
314   target.fVz = fVz;
315   target.fHadronBackgroundOADB = fHadronBackgroundOADB;
316   target.fContainer = fContainer;
317   target.fVarManager = fVarManager;
318   target.fSignalCuts = fSignalCuts;
319   target.fCFM = fCFM;
320   target.fTriggerAnalysis = fTriggerAnalysis;
321   target.fPID = fPID;
322   target.fPIDqa = fPIDqa;
323   target.fPIDpreselect = fPIDpreselect;
324   target.fCuts = fCuts;
325   target.fTaggedTrackCuts = fTaggedTrackCuts;
326   target.fCleanTaggedTrack = fCleanTaggedTrack;
327   target.fVariablesTRDTaggedTrack = fVariablesTRDTaggedTrack;
328   target.fCutspreselect = fCutspreselect;
329   target.fSecVtx = fSecVtx;
330   target.fElecBackGround = fElecBackGround;
331   target.fMCQA = fMCQA;
332   target.fTaggedTrackAnalysis = fTaggedTrackAnalysis;
333   target.fExtraCuts = fExtraCuts;
334   target.fQA = fQA;
335   target.fOutput = fOutput;
336   target.fHistMCQA = fHistMCQA;
337   target.fHistSECVTX = fHistSECVTX;
338   target.fHistELECBACKGROUND = fHistELECBACKGROUND;
339   target.fQACollection = fQACollection;
340 }
341
342 //____________________________________________________________
343 AliAnalysisTaskHFE::~AliAnalysisTaskHFE(){
344   //
345   // Destructor
346   //
347   if(fPID) delete fPID;
348   if(fPIDpreselect) delete fPIDpreselect;
349   if(fVarManager) delete fVarManager;
350   if(fCFM) delete fCFM;
351   if(fTriggerAnalysis) delete fTriggerAnalysis;
352   if(fSignalCuts) delete fSignalCuts;
353   if(fSecVtx) delete fSecVtx;
354   if(fMCQA) delete fMCQA;
355   if(fElecBackGround) delete fElecBackGround;
356   if(fSpecialTrigger) delete fSpecialTrigger;
357   // Delete output objects only if we are not running in PROOF mode because otherwise this produces a crash during merging
358   AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
359   if(mgr && mgr->GetAnalysisType() != AliAnalysisManager::kProofAnalysis){
360     if(fPIDqa) delete fPIDqa;
361     if(fOutput) delete fOutput;
362     if(fQA) delete fQA;
363   }
364 }
365
366 //____________________________________________________________
367 void AliAnalysisTaskHFE::UserCreateOutputObjects(){
368   //
369   // Creating output container and output objects
370   // Here we also Initialize the correction framework container and 
371   // the objects for
372   // - PID
373   // - MC QA
374   // - SecVtx
375   // QA histograms are created if requested
376   // Called once per worker
377   //
378   AliDebug(3, "Creating Output Objects");
379   // Automatic determination of the analysis mode
380   AliVEventHandler *inputHandler = dynamic_cast<AliVEventHandler *>(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler());
381   if(!TString(inputHandler->IsA()->GetName()).CompareTo("AliAODInputHandler")){
382     SetAODAnalysis();
383   } else {
384     SetESDAnalysis();
385     if(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler())
386       SetHasMCData();
387   }
388   printf("Analysis Mode: %s Analysis\n", IsAODanalysis() ? "AOD" : "ESD");
389   printf("MC Data available %s\n", HasMCData() ? "Yes" : "No");
390
391   // Enable Trigger Analysis
392   fTriggerAnalysis = new AliTriggerAnalysis;
393   fTriggerAnalysis->EnableHistograms();
394   fTriggerAnalysis->SetAnalyzeMC(HasMCData());
395
396
397   // Make lists for Output
398   if(!fQA) fQA = new TList;
399   fQA->SetOwner();
400   if(!fOutput) fOutput = new TList;
401   fOutput->SetOwner();
402
403   // First Part: Make QA histograms
404   fQACollection = new AliHFEcollection("TaskQA", "QA histos from the Electron Task");
405   fQACollection->CreateTH1F("nElectronTracksEvent", "Number of Electron Candidates", 100, 0, 100);
406   fQACollection->CreateTH1F("nElectron", "Number of electrons", 100, 0, 100);
407   fQACollection->CreateTH2F("radius", "Production Vertex", 100, 0.0, 5.0, 100, 0.0, 5.0);
408   fQACollection->CreateTH2F("TPCdEdxBeforePID", "TPC dE/dx; p (GeV/c); TPC dE/dx (a.u.)", 1000, 0., 10., 200, 0., 200.); 
409   fQACollection->CreateTH2F("TPCnSigmaBeforePID", "TPC dE/dx; p (GeV/c); TPC dE/dx - <TPC dE/dx>|_{el} (#sigma)", 1000, 0., 10., 1000, -10., 10.);
410  
411   InitPIDperformanceQA();
412   InitContaminationQA();
413   InitHistoITScluster();
414   fQA->Add(fQACollection);
415
416   // Initialize PID
417   fPID->SetHasMCData(HasMCData());
418   if(!fPID->GetNumberOfPIDdetectors()) fPID->AddDetector("TPC", 0);
419   if(IsQAOn(kPIDqa)){
420     AliInfo("PID QA switched on");
421     fPIDqa->Initialize(fPID);
422     fQA->Add(fPIDqa->MakeList("HFEpidQA"));
423   }
424   fPID->SortDetectors();
425
426   // Initialize correction Framework and Cuts
427   const Int_t kNcutSteps = AliHFEcuts::kNcutStepsMCTrack + AliHFEcuts::kNcutStepsRecTrack + AliHFEcuts::kNcutStepsDETrack + AliHFEcuts::kNcutStepsSecvtxTrack;
428   fCFM = new AliCFManager;
429   fCFM->SetNStepParticle(kNcutSteps);
430   MakeParticleContainer();
431   MakeEventContainer();
432   // Temporary fix: Initialize particle cuts with NULL
433   for(Int_t istep = 0; istep < kNcutSteps; istep++)
434     fCFM->SetParticleCutsList(istep, NULL);
435   if(!fCuts){
436     AliWarning("Cuts not available. Default cuts will be used");
437     fCuts = new AliHFEcuts;
438     fCuts->CreateStandardCuts();
439   }
440   if(IsAODanalysis()) fCuts->SetAOD();
441   // Make clone for V0 tagging step
442   fCuts->Initialize(fCFM);
443   if(fCuts->IsQAOn()) fQA->Add(fCuts->GetQAhistograms());
444   fSignalCuts = new AliHFEsignalCuts("HFEsignalCuts", "HFE MC Signal definition");
445   fVarManager->SetSignalCuts(fSignalCuts);
446  
447   // add output objects to the List
448   fOutput->AddAt(fContainer, 0);
449   fOutput->AddAt(fCFM->GetEventContainer(), 1);
450   
451   // mcQA----------------------------------
452   if (HasMCData() && IsQAOn(kMCqa)) {
453     AliInfo("MC QA on");
454     if(!fMCQA) fMCQA = new AliHFEmcQA;
455     if(!fHistMCQA) fHistMCQA = new TList();
456     fHistMCQA->SetOwner();
457     if(IsPbPb()) fMCQA->SetPbPb();
458     if(fisppMultiBin) fMCQA->SetPPMultiBin();
459     if(TestBit(kTreeStream)){
460       fMCQA->EnableDebugStreamer();
461     }
462     fMCQA->CreatDefaultHistograms(fHistMCQA);
463     fMCQA->SetBackgroundWeightFactor(fElecBackgroundFactor[0][0][0],fBinLimit);
464     fQA->Add(fHistMCQA);
465   } 
466
467   // secvtx----------------------------------
468   if (GetPlugin(kSecVtx)) {
469     AliInfo("Secondary Vertex Analysis on");
470     if(!fSecVtx) fSecVtx = new AliHFEsecVtx;
471     fSecVtx->SetHasMCData(HasMCData());
472
473     if(!fHistSECVTX) fHistSECVTX = new TList();
474     fHistSECVTX->SetOwner();
475     fSecVtx->CreateHistograms(fHistSECVTX);
476     fOutput->Add(fHistSECVTX);
477   }
478   
479   // background----------------------------------
480   if (GetPlugin(kIsElecBackGround)) {
481     AliInfo("Electron BackGround Analysis on");
482     if(!fElecBackGround){
483       AliWarning("ElecBackGround not available. Default elecbackground will be used");
484       fElecBackGround = new AliHFEelecbackground;
485     }
486     fElecBackGround->SetHasMCData(HasMCData());
487
488     if(!fHistELECBACKGROUND) fHistELECBACKGROUND = new TList();
489     fHistELECBACKGROUND->SetOwner();
490     fElecBackGround->CreateHistograms(fHistELECBACKGROUND);
491     fOutput->Add(fHistELECBACKGROUND);
492   }  
493
494   // tagged tracks
495   if(GetPlugin(kTaggedTrackAnalysis)){
496     AliInfo("Analysis on V0-tagged tracks enabled");
497     fTaggedTrackAnalysis = new AliHFEtaggedTrackAnalysis(Form("taggedTrackAnalysis%s", GetName()));
498     fTaggedTrackAnalysis->SetCuts(fTaggedTrackCuts);
499     fTaggedTrackAnalysis->SetClean(fCleanTaggedTrack);
500     AliHFEvarManager *varManager = fTaggedTrackAnalysis->GetVarManager();
501     TObjArray *array = fVarManager->GetVariables();
502     Int_t nvars = array->GetEntriesFast();
503     TString namee;
504     for(Int_t v = 0; v < nvars; v++) {
505       AliHFEvarManager::AliHFEvariable *variable = (AliHFEvarManager::AliHFEvariable *) array->At(v);
506       if(!variable) continue;
507       TString name(((AliHFEvarManager::AliHFEvariable *)variable)->GetName());
508       if(!name.CompareTo("source")) namee = TString("species");
509       else namee = TString(name);
510       Int_t nbins = variable->GetNumberOfBins();
511       if(variable->HasUserDefinedBinning()){
512         varManager->AddVariable(namee, nbins, variable->GetBinning());
513       } else {
514         varManager->AddVariable(namee, nbins, variable->GetMinimum(), variable->GetMaximum());
515       }
516       //printf("For AliTaggedTrackAnalysis, had the variable %s and the one used %s\n",(const char*)variable->GetName(),(const char*) namee);
517     }
518     if(fPIDqa->HasHighResolutionHistos()) 
519       fTaggedTrackAnalysis->GetPIDqa()->SetHighResolutionHistos();
520     fTaggedTrackAnalysis->SetPID(fPID);
521     fTaggedTrackAnalysis->SetVariablesTRD(fVariablesTRDTaggedTrack);
522     fTaggedTrackAnalysis->InitContainer();
523     fOutput->Add(fTaggedTrackAnalysis->GetContainer());
524     fQA->Add(fTaggedTrackAnalysis->GetPIDQA());
525     fQA->Add(fTaggedTrackAnalysis->GetCutQA());
526     fQA->Add(fTaggedTrackAnalysis->GetQAcollection());
527   }
528
529   PrintStatus();
530   // Done!!!
531   PostData(1, fOutput);
532   PostData(2, fQA);
533 }
534
535 //____________________________________________________________
536 void AliAnalysisTaskHFE::UserExec(Option_t *){
537   //
538   // Run the analysis
539   // 
540   AliDebug(3, "Starting Single Event Analysis");
541   if(!fInputEvent){
542     AliError("Reconstructed Event not available");
543     return;
544   }
545   if(HasMCData()){
546     AliDebug(4, Form("MC Event: %p", fMCEvent));
547     if(!fMCEvent){
548       AliError("No MC Event, but MC Data required");
549       return;
550     }
551   }
552   if(!fCuts){
553     AliError("HFE cuts not available");
554     return;
555   }
556   if(!fPID->IsInitialized()){
557     // Initialize PID with the given run number
558     fPID->InitializePID(fInputEvent->GetRunNumber());
559   }
560
561   // Initialize hadronic background from OADB Container
562   AliDebug(2, Form("Apply background factors: %s, OADB Container %p", fBackGroundFactorApply ? "Yes" : "No", fHadronBackgroundOADB));
563   if(fBackGroundFactorApply && !TestBit(kBackgroundInitialized)){ 
564     AliDebug(2, "Initializing Background from OADB");
565     if(!InitializeHadronBackground(fInputEvent->GetRunNumber())) AliError("Failed initializing hadronic background parameterization from OADB");
566     else AliDebug(2, "Successfully loaded Background from OADB");
567     SetBit(kBackgroundInitialized); 
568   }
569
570   if(IsESDanalysis() && HasMCData()){
571     // Protect against missing MC trees
572     AliMCEventHandler *mcH = dynamic_cast<AliMCEventHandler *>(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler());
573     if(!mcH){ 
574       AliError("No MC Event Handler available");
575       return;
576     }
577     if(!mcH->InitOk()) return;
578     if(!mcH->TreeK()) return;
579     if(!mcH->TreeTR()) return;
580   }
581
582   // need the centrality for everything (MC also)
583   fCentralityF = -1;
584   if(!ReadCentrality()) fCentralityF = -1;
585   //printf("pass centrality\n");
586   //printf("Reading fCentralityF %f\n",fCentralityF);
587   
588   // See if pile up and z in the range
589   RejectionPileUpVertexRangeEventCut();
590
591   // Protect agains missing 
592   if(HasMCData()){
593     //printf("Has MC data\n");
594     fSignalCuts->SetMCEvent(fMCEvent);
595     ProcessMC();  // Run the MC loop + MC QA in case MC Data are available
596   }
597
598   AliPIDResponse *pidResponse = fInputHandler->GetPIDResponse();
599   if(!pidResponse){
600     AliDebug(1, "Using default PID Response");
601     pidResponse = AliHFEtools::GetDefaultPID(HasMCData(), fInputEvent->IsA() == AliESDEvent::Class());
602   }
603   fPID->SetPIDResponse(pidResponse);
604   if(fPIDpreselect) fPIDpreselect->SetPIDResponse(pidResponse);
605
606   // Event loop
607   if(IsAODanalysis()){
608     //printf("test\n");
609     ProcessAOD();
610   } else {
611     const char *specialTrigger = GetSpecialTrigger(fInputEvent->GetRunNumber());
612     // Check Trigger selection
613     if(specialTrigger){
614       AliDebug(2, Form("Special Trigger requested: %s", specialTrigger));
615       AliESDEvent *ev = dynamic_cast<AliESDEvent *>(fInputEvent);
616       if(!(ev && ev->IsTriggerClassFired(specialTrigger))){
617         AliDebug(2, "Event not selected"); 
618         return;
619       } else AliDebug(2, "Event Selected");
620     } else AliDebug(2, "No Special Trigger requested");
621
622     ProcessESD();
623   }
624   // Done!!!
625   PostData(1, fOutput);
626   PostData(2, fQA);
627 }
628
629 //____________________________________________________________
630 void AliAnalysisTaskHFE::Terminate(Option_t *){
631   //
632   // Terminate not implemented at the moment
633   //
634   if(GetPlugin(kPostProcess)){
635     fOutput = dynamic_cast<TList *>(GetOutputData(1));
636     fQA = dynamic_cast<TList *>(GetOutputData(2));
637     if(!fOutput){
638       AliError("Results not available");
639       return;
640     }
641     if(!fQA){
642       AliError("QA output not available");
643       return;
644     }
645     fContainer = dynamic_cast<AliHFEcontainer *>(fOutput->FindObject("trackContainer")); 
646     if(!fContainer){
647       AliError("Track container not found");
648       return;
649     }
650     AliHFEpostAnalysis postanalysis;
651     postanalysis.SetTaskResults(fContainer);
652     TList *qalist = dynamic_cast<TList *>(fQA->FindObject("list_TaskQA"));
653     if(!qalist){
654       AliError("QA List not found");
655       return;
656     }
657     postanalysis.SetTaskQA(qalist);
658     printf("Running post analysis\n");
659     //if(HasMCData())
660     postanalysis.DrawMCSignal2Background();
661     postanalysis.DrawEfficiency();
662     postanalysis.DrawPIDperformance();
663     postanalysis.DrawCutEfficiency();
664
665     if (GetPlugin(kIsElecBackGround)) {
666       AliHFEelecbackground elecBackGround;
667       TList *oe = 0x0;
668       if(!(oe = (TList*)dynamic_cast<TList *>(fOutput->FindObject("HFEelecbackground")))){
669         return;
670       }
671       elecBackGround.Load(oe);
672       elecBackGround.Plot();
673       elecBackGround.PostProcess();      
674     }
675   }
676 }
677 //_______________________________________________________________
678 Bool_t AliAnalysisTaskHFE::IsEventInBinZero() {
679   //
680   //
681   //
682
683   //printf("test in IsEventInBinZero\n");
684   if(!fInputEvent){
685     AliError("Reconstructed Event not available");
686     return kFALSE;
687   }
688
689   // check vertex
690   const AliVVertex *vertex = fInputEvent->GetPrimaryVertex();
691   if(!vertex) return kTRUE;
692   //if(vertex) return kTRUE;
693
694   // check tracks
695   if(fInputEvent->GetNumberOfTracks()<=0) return kTRUE;
696   //if(fInputEvent->GetNumberOfTracks()>0) return kTRUE;
697   
698   
699   return kFALSE;
700   
701 }
702 //____________________________________________________________
703 void AliAnalysisTaskHFE::ProcessMC(){
704   //
705   // Runs the MC Loop (filling the container for the MC Cut Steps with the observables pt, eta and phi)
706   // In case MC QA is on also MC QA loop is done
707   //
708   AliDebug(3, "Processing MC Information");
709   Double_t eventContainer [4];
710   eventContainer[0] = fMCEvent->GetPrimaryVertex()->GetZ();
711   eventContainer[2] = fCentralityF;
712   eventContainer[3] = fContributors;
713   fVz = eventContainer[0];
714   //printf("z position is %f\n",eventContainer[0]);
715   //if(fCFM->CheckEventCuts(AliHFEcuts::kEventStepGenerated, fMCEvent)) 
716   fCFM->GetEventContainer()->Fill(eventContainer,AliHFEcuts::kEventStepGenerated);
717   Int_t nElectrons = 0;
718   if(IsESDanalysis()){
719    if(!((fIdentifiedAsPileUp) || (TMath::Abs(fVz) > fCuts->GetVertexRange()) || (fCentralityF < 0))){ //kStepMCGeneratedZOutNoPileUpCentralityFine
720     if (HasMCData() && IsQAOn(kMCqa)) {
721       AliDebug(2, "Running MC QA");
722
723       if(fMCEvent->Stack()){
724         fMCQA->SetMCEvent(fMCEvent);
725         fMCQA->SetGenEventHeader(fMCEvent->GenEventHeader());
726         fMCQA->SetCentrality(fCentralityF);
727         fMCQA->SetPercentrality(fCentralityPercent);
728         if(IsPbPb()) { fMCQA->SetPbPb();}
729         else
730         {
731             if(fisppMultiBin) fMCQA->SetPPMultiBin();
732             else fMCQA->SetPP();
733         }
734         fMCQA->Init();
735
736         fMCQA->GetMesonKine();
737
738         // loop over all tracks for decayed electrons
739         for (Int_t igen = 0; igen < fMCEvent->GetNumberOfTracks(); igen++){
740           TParticle* mcpart = fMCEvent->Stack()->Particle(igen);
741           if(!mcpart) continue;
742           fMCQA->GetQuarkKine(mcpart, igen, AliHFEmcQA::kCharm);
743           fMCQA->GetQuarkKine(mcpart, igen, AliHFEmcQA::kBeauty);
744           fMCQA->GetHadronKine(mcpart, AliHFEmcQA::kCharm);
745           fMCQA->GetHadronKine(mcpart, AliHFEmcQA::kBeauty);
746           fMCQA->GetDecayedKine(mcpart, AliHFEmcQA::kCharm,  AliHFEmcQA::kElectronPDG); // no accept cut
747           fMCQA->GetDecayedKine(mcpart, AliHFEmcQA::kBeauty, AliHFEmcQA::kElectronPDG); // no accept cut
748           fMCQA->GetDecayedKine(mcpart, AliHFEmcQA::kOthers, AliHFEmcQA::kElectronPDG); // no accept cut
749         }
750         //fMCQA->EndOfEventAna(AliHFEmcQA::kCharm);
751         //fMCQA->EndOfEventAna(AliHFEmcQA::kBeauty);
752       }
753
754     } // end of MC QA loop
755    }
756    // -----------------------------------------------------------------
757    fCFM->SetMCEventInfo(fMCEvent);
758    // fCFM->CheckEventCuts(AliCFManager::kEvtRecCuts, fESD);
759   } else {
760     fCFM->SetMCEventInfo(fInputEvent);
761   }
762   // Run MC loop
763   AliVParticle *mctrack = NULL;
764   AliDebug(3, Form("Number of Tracks: %d", fMCEvent->GetNumberOfTracks()));
765   for(Int_t imc = 0; imc <fMCEvent->GetNumberOfTracks(); imc++){
766     if(!(mctrack = fMCEvent->GetTrack(imc))) continue;
767     AliDebug(4, "Next MC Track");
768     if(ProcessMCtrack(mctrack)) nElectrons++;
769   }
770
771   // fCFM->CheckEventCuts(AliCFManager::kEvtRecCuts, fESD);
772   fQACollection->Fill("nElectron", nElectrons);
773 }
774
775 //____________________________________________________________
776 void AliAnalysisTaskHFE::ProcessESD(){
777   //
778   // Run Analysis of reconstructed event in ESD Mode
779   // Loop over Tracks, filter according cut steps defined in AliHFEcuts
780   //
781   AliDebug(1, Form("Task %s", GetName()));
782   AliDebug(3, "Processing ESD Event");
783   AliESDEvent *fESD = dynamic_cast<AliESDEvent *>(fInputEvent);
784   if(!fESD){
785     AliError("ESD Event required for ESD Analysis");
786     return;
787   }
788
789   // Set magnetic field if V0 task on
790   if(fTaggedTrackAnalysis) {
791     fTaggedTrackAnalysis->SetMagneticField(fESD->GetMagneticField());
792     fTaggedTrackAnalysis->SetCentrality(fCentralityF);
793     if(IsPbPb()) fTaggedTrackAnalysis->SetPbPb();
794     else fTaggedTrackAnalysis->SetPP();
795   }
796
797   // Do event Normalization
798   Double_t eventContainer[4];
799   eventContainer[0] = 0.; 
800   if(HasMCData()) eventContainer[0] = fVz;
801   else {
802     if(fESD->GetPrimaryVertexSPD()) eventContainer[0] = fESD->GetPrimaryVertexSPD()->GetZ();
803   }
804   eventContainer[1] = 0.;
805   eventContainer[2] = fCentralityF;
806   eventContainer[3] = fContributors;
807   if(fTriggerAnalysis->IsOfflineTriggerFired(fESD, AliTriggerAnalysis::kV0AND))
808     eventContainer[1] = 1.;
809
810   //
811   fCFM->GetEventContainer()->Fill(eventContainer, AliHFEcuts::kEventStepRecNoCut);
812
813   //
814   if(fIdentifiedAsPileUp) return; 
815   fCFM->GetEventContainer()->Fill(eventContainer, AliHFEcuts::kEventStepRecNoPileUp);
816
817   //
818   if(TMath::Abs(fCentralityF) < 0) return; 
819   fCFM->GetEventContainer()->Fill(eventContainer, AliHFEcuts::kEventStepRecCentralityOk);
820   //printf("In ProcessESD %f\n",fCentralityF);
821
822   //
823   if(fIdentifiedAsOutInz) return;
824   fCFM->GetEventContainer()->Fill(eventContainer, AliHFEcuts::kEventStepZRange);  
825
826   //
827   if(!fPassTheEventCut) return;
828   fCFM->GetEventContainer()->Fill(eventContainer, AliHFEcuts::kEventStepReconstructed);
829
830
831   fContainer->NewEvent();
832
833   if (GetPlugin(kIsElecBackGround)) { 
834     fElecBackGround->SetEvent(fESD);
835   }
836   if (GetPlugin(kSecVtx)) {
837     fSecVtx->SetEvent(fESD);
838     fSecVtx->GetPrimaryCondition();
839   }
840
841   if(HasMCData()){
842     if (GetPlugin(kSecVtx)) { 
843       fSecVtx->SetMCEvent(fMCEvent);
844       fSecVtx->SetMCQA(fMCQA); 
845     }
846     if (GetPlugin(kIsElecBackGround)) { 
847       fElecBackGround->SetMCEvent(fMCEvent);
848     }
849   }
850
851   Double_t container[10];
852   memset(container, 0, sizeof(Double_t) * 10);
853   // container for the output THnSparse
854   Double_t dataE[6]; // [pT, eta, Phi, type, 'C' or 'B']
855   Double_t dataDca[6]; // [source, pT, dca, centrality]
856   Int_t nElectronCandidates = 0;
857   AliESDtrack *track = NULL, *htrack = NULL;
858   AliMCParticle *mctrack = NULL;
859   AliMCParticle *mctrackmother = NULL;
860   Int_t pid = 0;
861
862   Bool_t signal = kTRUE;
863
864   fCFM->SetRecEventInfo(fESD);
865
866   // minjung for IP QA(temporary ~ 2weeks)
867   if(!fExtraCuts){
868     fExtraCuts = new AliHFEextraCuts("hfetmpCuts","HFE tmp Cuts");
869   }   
870   fExtraCuts->SetRecEventInfo(fESD);
871
872   // Electron background analysis 
873   if (GetPlugin(kIsElecBackGround)) {
874     
875     AliDebug(2, "Running BackGround Analysis");
876     
877     fElecBackGround->Reset();
878     
879   } // end of electron background analysis
880   //
881   // Loop ESD
882   //
883   AliDebug(3, Form("Number of Tracks: %d", fESD->GetNumberOfTracks()));
884   for(Int_t itrack = 0; itrack < fESD->GetNumberOfTracks(); itrack++){
885     AliDebug(4, "New ESD track");
886     track = fESD->GetTrack(itrack);
887     track->SetESDEvent(fESD);
888
889     // fill counts of v0-identified particles
890     Int_t v0pid = -1;
891     if(track->TestBit(BIT(14))) v0pid = AliPID::kElectron;
892     else if(track->TestBit(BIT(15))) v0pid = AliPID::kPion;
893     else if(track->TestBit(BIT(16))) v0pid = AliPID::kProton;
894     // here the tagged track analysis will run
895     if(fTaggedTrackAnalysis && v0pid > -1){ 
896       AliDebug(1, Form("Track identified as %s", AliPID::ParticleName(v0pid)));
897       fTaggedTrackAnalysis->ProcessTrack(track, v0pid);
898       AliDebug(1, "V0 PID done");
899     }
900  
901
902     //Fill non-HFE source containers at reconstructed events cut step
903     AliDebug(3, Form("Doing track %d, %p", itrack, track));
904
905
906     //////////////////////////////////////
907     // preselect
908     /////////////////////////////////////
909     if(fPIDpreselect && fCutspreselect) {
910       if(!PreSelectTrack(track)) continue;
911     }
912
913     signal = kTRUE;
914     
915     // Fill step without any cut
916           
917     if(HasMCData()){
918       // Check if it is electrons near the vertex
919       if(!(mctrack = dynamic_cast<AliMCParticle *>(fMCEvent->GetTrack(TMath::Abs(track->GetLabel()))))) continue;
920
921       if(fFillSignalOnly && !fCFM->CheckParticleCuts(AliHFEcuts::kStepMCGenerated, mctrack)) signal = kFALSE; 
922       else AliDebug(3, "Signal Electron");
923
924       // Fill K pt for Ke3 contributions
925       if(mctrack && (TMath::Abs(mctrack->Particle()->GetPdgCode())==321)) fQACollection->Fill("Kptspectra",mctrack->Pt());
926       else if(mctrack && (TMath::Abs(mctrack->Particle()->GetPdgCode())==130)) fQACollection->Fill("K0Lptspectra",mctrack->Pt());
927     } 
928     // Cache new Track information inside the var manager
929     fVarManager->NewTrack(track, mctrack, fCentralityF, -1, signal);
930
931     if(fFillNoCuts) {
932       if(signal || !fFillSignalOnly){
933         fVarManager->FillContainer(fContainer, "recTrackContReco", AliHFEcuts::kStepRecNoCut, kFALSE);
934         fVarManager->FillContainer(fContainer, "recTrackContMC", AliHFEcuts::kStepRecNoCut, kTRUE);
935       }
936     }
937         
938     if(fisNonHFEsystematics && IsPbPb())  {
939       //FillProductionVertex(track);     
940       if(fMCQA && signal){ 
941         fMCQA->SetCentrality(fCentralityF);
942         if(mctrack && (TMath::Abs(mctrack->Particle()->GetPdgCode()) == 11)){
943           Double_t weightElecBgV0[kBgLevels] = {0.,0.,0.};
944           
945           fMCQA->SetTrkKine(track->Pt(),track->Eta(), track->Phi());
946           fMCQA->SetContainerStep(4);
947           
948           weightElecBgV0[0] = fMCQA->GetWeightFactor(mctrack, 0); // positive:conversion e, negative: nonHFE 
949           
950           //Fill additional containers for electron source distinction
951           Int_t elecSource = 0;
952           elecSource = fMCQA->GetElecSource(mctrack->Particle());
953           const Char_t *sourceName[kElecBgSpecies]={"Pion","Eta","Omega","Phi","EtaPrime","Rho"};
954           const Char_t *levelName[kBgLevels]={"Best","Lower","Upper"};
955           Int_t iName = 0;
956           for(Int_t iSource = AliHFEmcQA::kPi0; iSource <=  AliHFEmcQA::kGammaRho0; iSource++){
957             if((iSource == AliHFEmcQA::kElse)||(iSource == AliHFEmcQA::kMisID)) continue;
958             if(elecSource == iSource){
959               
960               if(weightElecBgV0[0]>0){ 
961                 fVarManager->FillContainer(fContainer, Form("conversionElecs%s%s",sourceName[iName], levelName[0]), 4, kTRUE, weightElecBgV0[0]);
962               } 
963               else if(weightElecBgV0[0]<0){ 
964                 fVarManager->FillContainer(fContainer, Form("mesonElecs%s%s",sourceName[iName], levelName[0]), 4, kTRUE, -1*weightElecBgV0[0]);
965               }           
966               break;
967             }
968             iName++;
969             if(iName == kElecBgSpecies)iName = 0;
970           }
971         }
972       }
973     }
974   
975     // RecKine: ITSTPC cuts  
976     if(!ProcessCutStep(AliHFEcuts::kStepRecKineITSTPC, track)) continue;
977     
978     
979     // RecPrim
980     if(fRejectKinkMother) { 
981       if(track->GetKinkIndex(0) != 0) continue; } // Quick and dirty fix to reject both kink mothers and daughters
982     if(!ProcessCutStep(AliHFEcuts::kStepRecPrim, track)) continue;
983
984     // HFEcuts: ITS layers cuts
985     if(!ProcessCutStep(AliHFEcuts::kStepHFEcutsITS, track)) continue;
986   
987     // HFE cuts: TOF PID and mismatch flag
988     if(!ProcessCutStep(AliHFEcuts::kStepHFEcutsTOF, track)) continue;
989
990     // HFE cuts: TPC PID cleanup
991     if(!ProcessCutStep(AliHFEcuts::kStepHFEcutsTPC, track)) continue;
992
993     // HFEcuts: Nb of tracklets TRD0
994     if(!ProcessCutStep(AliHFEcuts::kStepHFEcutsTRD, track)) continue;
995
996     // Fill correlation maps before PID
997     if(signal && fContainer->GetCorrelationMatrix("correlationstepbeforePID")) {
998       //printf("Fill correlation maps before PID\n");
999       fVarManager->FillCorrelationMatrix(fContainer->GetCorrelationMatrix("correlationstepbeforePID"));
1000     }
1001
1002     if(HasMCData()){
1003       FillProductionVertex(track);
1004
1005       if(fMCQA && signal){
1006         fMCQA->SetCentrality(fCentralityF);
1007         if(mctrack && (TMath::Abs(mctrack->Particle()->GetPdgCode()) == 11)){
1008          Double_t weightElecBgV0[kBgLevels] = {0.,0.,0.};
1009          Double_t hfeimpactRtmp=0., hfeimpactnsigmaRtmp=0.;
1010          fExtraCuts->GetHFEImpactParameters(track, hfeimpactRtmp, hfeimpactnsigmaRtmp);
1011          UChar_t itsPixel = track->GetITSClusterMap();
1012          Double_t ilyrhit=0, ilyrstat=0;
1013          for(Int_t ilyr=0; ilyr<6; ilyr++){
1014            if(TESTBIT(itsPixel, ilyr)) ilyrhit += TMath::Power(2,ilyr);
1015            if(fExtraCuts->CheckITSstatus(fExtraCuts->GetITSstatus(track,ilyr))) ilyrstat += TMath::Power(2,ilyr);
1016          }
1017          fMCQA->SetITSInfo(ilyrhit,ilyrstat);
1018          fMCQA->SetHFEImpactParameters(hfeimpactRtmp, hfeimpactnsigmaRtmp);
1019          fMCQA->SetTrkKine(track->Pt(),track->Eta(), track->Phi());
1020          fMCQA->SetContainerStep(3);
1021          for(Int_t iLevel = 0; iLevel < kBgLevels; iLevel++){
1022            weightElecBgV0[iLevel] = fMCQA->GetWeightFactor(mctrack, iLevel); // positive:conversion e, negative: nonHFE 
1023            if(!fisNonHFEsystematics || IsPbPb())break;   
1024          }
1025          
1026          if(fisNonHFEsystematics){
1027            //Fill additional containers for electron source distinction
1028            Int_t elecSource = 0;
1029            elecSource = fMCQA->GetElecSource(mctrack->Particle());
1030            const Char_t *sourceName[kElecBgSpecies]={"Pion","Eta","Omega","Phi","EtaPrime","Rho"};
1031            const Char_t *levelName[kBgLevels]={"Best","Lower","Upper"};
1032            Int_t iName = 0;
1033            for(Int_t iSource = AliHFEmcQA::kPi0; iSource <=  AliHFEmcQA::kGammaRho0; iSource++){
1034              if((iSource == AliHFEmcQA::kElse)||(iSource == AliHFEmcQA::kMisID)) continue;
1035              if(elecSource == iSource){
1036                for(Int_t iLevel = 0; iLevel < kBgLevels; iLevel++){
1037                  if(weightElecBgV0[iLevel]>0){ 
1038                    fVarManager->FillContainer(fContainer, Form("conversionElecs%s%s",sourceName[iName], levelName[iLevel]), 3, kFALSE, weightElecBgV0[iLevel]);
1039                  } 
1040                  else if(weightElecBgV0[iLevel]<0){ 
1041                    fVarManager->FillContainer(fContainer, Form("mesonElecs%s%s",sourceName[iName], levelName[iLevel]), 3, kFALSE, -1*weightElecBgV0[iLevel]);
1042                  }
1043                  if(IsPbPb())break;
1044                }
1045                break;
1046              }
1047              iName++;
1048              if(iName == kElecBgSpecies)iName = 0;
1049            }
1050          }
1051          //else{
1052            if(weightElecBgV0[0]>0) {
1053              fVarManager->FillContainer(fContainer, "conversionElecs", 3, kFALSE, weightElecBgV0[0]);
1054              fVarManager->FillContainer(fContainer, "conversionElecs", 4, kTRUE, weightElecBgV0[0]);
1055            }
1056            else if(weightElecBgV0[0]<0) {
1057              fVarManager->FillContainer(fContainer, "mesonElecs", 3, kFALSE, -1*weightElecBgV0[0]);
1058              fVarManager->FillContainer(fContainer, "mesonElecs", 4, kTRUE, -1*weightElecBgV0[0]);
1059            }
1060            //}
1061         }
1062       }
1063
1064       Double_t hfeimpactR4all=0., hfeimpactnsigmaR4all=0.;
1065       Int_t sourceDca =-1;
1066       if(mctrack && (TMath::Abs(mctrack->Particle()->GetPdgCode()) == 211)){
1067         if(track->Pt()>4.){
1068           fExtraCuts->GetHFEImpactParameters(track, hfeimpactR4all, hfeimpactnsigmaR4all);
1069           dataDca[0]=0; //pion
1070           dataDca[1]=track->Pt();
1071           dataDca[2]=hfeimpactR4all;
1072           dataDca[3]=fCentralityF;
1073           dataDca[4] = v0pid;
1074           dataDca[5] = double(track->Charge());
1075           fQACollection->Fill("Dca", dataDca);
1076         }
1077       }
1078       else if(mctrack && (TMath::Abs(mctrack->Particle()->GetPdgCode()) == 11)){ // to increas statistics for Martin
1079         if(signal){
1080           fExtraCuts->GetHFEImpactParameters(track, hfeimpactR4all, hfeimpactnsigmaR4all);
1081           if(fSignalCuts->IsCharmElectron(track)){
1082             sourceDca=1;
1083           }
1084           else if(fSignalCuts->IsBeautyElectron(track)){
1085             sourceDca=2;
1086           }
1087           else if(fSignalCuts->IsGammaElectron(track)){
1088             sourceDca=3;
1089           }
1090           else if(fSignalCuts->IsNonHFElectron(track)){
1091             sourceDca=4;
1092           }
1093           else if(fSignalCuts->IsJpsiElectron(track)){
1094             sourceDca=5;
1095           }
1096           else {
1097             sourceDca=6;
1098           }
1099           dataDca[0]=sourceDca;
1100           dataDca[1]=track->Pt();
1101           dataDca[2]=hfeimpactR4all;
1102           dataDca[3]=fCentralityF;
1103           dataDca[4] = v0pid;
1104           dataDca[5] = double(track->Charge());
1105           if(signal) fQACollection->Fill("Dca", dataDca);
1106         }
1107       }
1108     }
1109
1110     if(TMath::Abs(track->Eta()) < 0.5){
1111       if(track->GetInnerParam())
1112         fQACollection->Fill("TPCdEdxBeforePID", track->GetInnerParam()->P(), track->GetTPCsignal());
1113       fQACollection->Fill("TPCnSigmaBeforePID", track->P(), fInputHandler->GetPIDResponse()->NumberOfSigmasTPC(track, AliPID::kElectron));
1114     }
1115
1116     AliHFEpidObject hfetrack;
1117     hfetrack.SetAnalysisType(AliHFEpidObject::kESDanalysis);
1118     hfetrack.SetRecTrack(track);
1119     if(HasMCData()) hfetrack.SetMCTrack(mctrack);
1120     hfetrack.SetCentrality(fCentralityF);
1121     if(IsPbPb()) hfetrack.SetPbPb();
1122     else hfetrack.SetPP();
1123     fPID->SetVarManager(fVarManager);
1124     if(!fPID->IsSelected(&hfetrack, fContainer, "recTrackCont", fPIDqa)) continue;
1125     nElectronCandidates++;
1126
1127     // Temporary histogram for chi2/ITS cluster
1128     if(IsPbPb()) {
1129             TBits shared = track->GetTPCSharedMap();
1130             Int_t sharebit=0;
1131             if(shared.CountBits() >= 2) sharebit=1;
1132
1133             Double_t itschi2percluster = 0.0;
1134             Double_t itsnbcls = static_cast<Double_t>(track->GetNcls(0));
1135             if(itsnbcls > 0) itschi2percluster = track->GetITSchi2()/itsnbcls;
1136
1137             Double_t itsChi2[7] = {track->Pt(),track->Eta(), track->Phi(),
1138                                    fCentralityF,track->GetTPCsignalN(), sharebit,itschi2percluster};
1139             fQACollection->Fill("fChi2perITScluster", itsChi2);
1140     }
1141     else{
1142
1143       Double_t itschi2percluster = 0.0;
1144       Double_t itsnbcls = static_cast<Double_t>(track->GetNcls(0));
1145       if(itsnbcls > 0) itschi2percluster = track->GetITSchi2()/itsnbcls;
1146
1147       Double_t itsChi2[3] = {track->Pt(), fCentralityF, itschi2percluster};
1148       fQACollection->Fill("fChi2perITScluster", itsChi2);
1149     }
1150
1151     // Fill Histogram for Hadronic Background
1152     if(HasMCData()){
1153       if(mctrack && (TMath::Abs(mctrack->Particle()->GetPdgCode()) != 11))
1154         fVarManager->FillContainer(fContainer, "hadronicBackground", UInt_t(0), kFALSE);
1155       else if(mctrack){
1156         // Fill Ke3 contributions
1157         Int_t glabel=TMath::Abs(mctrack->GetMother());
1158         if((mctrackmother = dynamic_cast<AliMCParticle *>(fMCEvent->GetTrack(glabel)))){
1159           if(TMath::Abs(mctrackmother->Particle()->GetPdgCode())==321)
1160             fQACollection->Fill("Ke3Kecorr",mctrack->Pt(),mctrackmother->Pt());
1161           else if(TMath::Abs(mctrackmother->Particle()->GetPdgCode())==130)
1162             fQACollection->Fill("Ke3K0Lecorr",mctrack->Pt(),mctrackmother->Pt());
1163         }
1164       }
1165     }
1166
1167     // Fill Containers
1168     if(signal) {
1169       // Apply weight for background contamination
1170             if(fBackGroundFactorApply) {
1171               if(IsPbPb() && fCentralityF >= 0) fWeightBackGround =  fkBackGroundFactorArray[fCentralityF >= 0 ? fCentralityF : 0]->Eval(TMath::Abs(track->P()));
1172               else    fWeightBackGround =  fkBackGroundFactorArray[0]->Eval(TMath::Abs(track->P())); // pp case
1173
1174               if(fWeightBackGround < 0.0) fWeightBackGround = 0.0;
1175               else if(fWeightBackGround > 1.0) fWeightBackGround = 1.0;
1176         // weightBackGround as special weight
1177         fVarManager->FillContainer(fContainer, "hadronicBackground", 1, kFALSE, fWeightBackGround);
1178       }
1179       fVarManager->FillCorrelationMatrix(fContainer->GetCorrelationMatrix("correlationstepafterPID"));
1180     }
1181
1182     Bool_t bTagged=kFALSE;
1183     if(GetPlugin(kSecVtx)) {
1184       AliDebug(2, "Running Secondary Vertex Analysis");
1185       if(fSecVtx->Process(track) && signal) {
1186         fVarManager->FillContainer(fContainer, "recTrackContSecvtxReco", AliHFEcuts::kStepHFEcutsSecvtx, kFALSE);
1187         fVarManager->FillContainer(fContainer, "recTrackContSecvtxMC", AliHFEcuts::kStepHFEcutsSecvtx, kTRUE);
1188         bTagged=kTRUE;
1189       }
1190     }
1191
1192     if(HasMCData()){
1193       dataE[0] = track->Pt();
1194       dataE[1] = track->Eta();
1195       dataE[2] = track->Phi();
1196       dataE[3] = track->Charge();
1197       dataE[4] = -1.;
1198       dataE[5] = -1.;
1199
1200       // Track selected: distinguish between true and fake
1201       AliDebug(1, Form("Candidate Selected, filling THnSparse, PID: %d\n", mctrack->Particle()->GetPdgCode()));
1202       if((pid = TMath::Abs(mctrack->Particle()->GetPdgCode())) == 11){
1203         Int_t type = 0;
1204         if(fSignalCuts->IsCharmElectron(track))
1205           type = 1;
1206         else if(fSignalCuts->IsBeautyElectron(track))
1207           type = 2;
1208         AliDebug(1, Form("Type: %d\n", type));
1209         if(type){
1210                 dataE[5] = type; // beauty[1] or charm[2]
1211                 dataE[4] = 2;  // signal electron
1212         }
1213         else{
1214                 dataE[4] = 1; // not a signal electron
1215                 dataE[5] = 0;
1216         }
1217       } 
1218       else {
1219         // Fill THnSparse with the information for Fake Electrons
1220         dataE[4] = 0;
1221         dataE[5] = 0;
1222       }
1223       // fill the performance THnSparse, if the mc origin could be defined
1224       if(dataE[4] > -1){
1225         AliDebug(1, Form("Entries: [%.3f|%.3f|%.3f|%f|%f|%f]\n", dataE[0],dataE[1],dataE[2],dataE[3],dataE[4],dataE[5]));
1226         fQACollection->Fill("PIDperformance", dataE);
1227       }
1228     }
1229
1230     // Electron background analysis 
1231     if (GetPlugin(kIsElecBackGround)) {
1232       
1233       AliDebug(2, "Running BackGround Analysis");
1234       
1235       for(Int_t jtrack = 0; jtrack < fESD->GetNumberOfTracks(); jtrack++){
1236         htrack = fESD->GetTrack(jtrack);
1237         if ( itrack == jtrack ) continue;  
1238         fElecBackGround->PairAnalysis(track, htrack); 
1239       }
1240     } // end of electron background analysis
1241
1242     if (GetPlugin(kDEstep)) { 
1243       Double_t weightElecBgV0[kBgLevels] = {0.,0.,0.,};
1244       Int_t elecSource = 0;
1245       Double_t hfeimpactR=0., hfeimpactnsigmaR=0.;
1246       fExtraCuts->GetHFEImpactParameters(track, hfeimpactR, hfeimpactnsigmaR);
1247       if(HasMCData())
1248       {
1249         if(mctrack && (TMath::Abs(mctrack->Particle()->GetPdgCode()) != 11)){
1250             fQACollection->Fill("hadronsBeforeIPcut",track->Pt());
1251         } 
1252         if(fMCQA && signal) {
1253           
1254           fMCQA->SetContainerStep(0);
1255           for(Int_t iLevel = 0; iLevel < kBgLevels; iLevel++){
1256             weightElecBgV0[iLevel] = fMCQA->GetWeightFactor(mctrack, iLevel); // positive:conversion e, negative: nonHFE 
1257             if(!fisNonHFEsystematics || IsPbPb())break;        
1258           }
1259           
1260           if(fisNonHFEsystematics){
1261             //Fill additional containers for electron source distinction           
1262             elecSource = fMCQA->GetElecSource(mctrack->Particle());
1263             const Char_t *sourceName[kElecBgSpecies]={"Pion","Eta","Omega","Phi","EtaPrime","Rho"};
1264             const Char_t *levelName[kBgLevels]={"Best","Lower","Upper"};
1265             Int_t iName = 0;
1266             for(Int_t iSource = AliHFEmcQA::kPi0; iSource <=  AliHFEmcQA::kGammaRho0; iSource++){
1267               if((iSource == AliHFEmcQA::kElse)||(iSource == AliHFEmcQA::kMisID)) continue;
1268               if(elecSource == iSource){
1269                 for(Int_t iLevel = 0; iLevel < kBgLevels; iLevel++){
1270                   if(weightElecBgV0[iLevel]>0) fVarManager->FillContainer(fContainer, Form("conversionElecs%s%s",sourceName[iName], levelName[iLevel]), 0, kFALSE, weightElecBgV0[iLevel]);
1271                   else if(weightElecBgV0[iLevel]<0) fVarManager->FillContainer(fContainer, Form("mesonElecs%s%s",sourceName[iName], levelName[iLevel]), 0, kFALSE, -1*weightElecBgV0[iLevel]);
1272                   if(IsPbPb())break;
1273                 }
1274                 break;
1275               }
1276               iName++;
1277               if(iName == kElecBgSpecies)iName = 0;
1278             }
1279           }
1280           //else{
1281           if(weightElecBgV0[0]>0) {
1282             fVarManager->FillContainer(fContainer, "conversionElecs", 0, kFALSE, weightElecBgV0[0]);
1283             fVarManager->FillContainer(fContainer, "conversionElecs", 5, kTRUE, weightElecBgV0[0]);
1284           }
1285           else if(weightElecBgV0[0]<0) {
1286             fVarManager->FillContainer(fContainer, "mesonElecs", 0, kFALSE, -1*weightElecBgV0[0]);
1287             fVarManager->FillContainer(fContainer, "mesonElecs", 5, kTRUE, -1*weightElecBgV0[0]);
1288           }  
1289           //}
1290           if(bTagged){ // bg estimation for the secondary vertex tagged signals
1291             if(weightElecBgV0[0]>0) fVarManager->FillContainer(fContainer, "conversionElecs", 2, kFALSE, weightElecBgV0[0]);
1292             else if(weightElecBgV0[0]<0) fVarManager->FillContainer(fContainer, "mesonElecs", 2, kFALSE, -1*weightElecBgV0[0]);
1293           }
1294         }
1295       } // end of MC
1296
1297       dataDca[0]=-1; //for data, don't know the origin
1298       dataDca[1]=track->Pt();
1299       dataDca[2]=hfeimpactR;
1300       dataDca[3]=fCentralityF;
1301       dataDca[4] = v0pid;
1302       dataDca[5] = double(track->Charge());
1303       if (!HasMCData()) fQACollection->Fill("Dca", dataDca);
1304
1305       // Fill Containers for impact parameter analysis
1306       if(!fCFM->CheckParticleCuts(AliHFEcuts::kStepHFEcutsDca + AliHFEcuts::kNcutStepsMCTrack + AliHFEcuts::kNcutStepsRecTrack,track)) continue;
1307       if(HasMCData()){
1308         if(fMCQA && signal) {
1309           fMCQA->SetContainerStep(1);
1310           for(Int_t iLevel = 0; iLevel < kBgLevels; iLevel++){
1311             weightElecBgV0[iLevel] = fMCQA->GetWeightFactor(mctrack, iLevel); // positive:conversion e, negative: nonHFE 
1312             if(!fisNonHFEsystematics || IsPbPb())break;        
1313           }       
1314           if(fisNonHFEsystematics){
1315             //Fill additional containers for electron source distinction             
1316             elecSource = fMCQA->GetElecSource(mctrack->Particle());
1317             const Char_t *sourceName[kElecBgSpecies]={"Pion","Eta","Omega","Phi","EtaPrime","Rho"};
1318             const Char_t *levelName[kBgLevels]={"Best","Lower","Upper"};
1319             Int_t iName = 0;
1320             for(Int_t iSource = AliHFEmcQA::kPi0; iSource <=  AliHFEmcQA::kGammaRho0; iSource++){
1321               if((iSource == AliHFEmcQA::kElse)||(iSource == AliHFEmcQA::kMisID)) continue;
1322               if(elecSource == iSource){
1323                 for(Int_t iLevel = 0; iLevel < kBgLevels; iLevel++){
1324                   if(weightElecBgV0[iLevel]>0) fVarManager->FillContainer(fContainer, Form("conversionElecs%s%s",sourceName[iName], levelName[iLevel]), 1, kFALSE, weightElecBgV0[iLevel]);
1325                   else if(weightElecBgV0[iLevel]<0) fVarManager->FillContainer(fContainer, Form("mesonElecs%s%s",sourceName[iName], levelName[iLevel]), 1, kFALSE, -1*weightElecBgV0[iLevel]);
1326                   if(IsPbPb())break;
1327                 }
1328                 break;
1329               }
1330               iName++;
1331               if(iName == kElecBgSpecies)iName = 0;
1332             }
1333           }
1334           // else{
1335             if(weightElecBgV0[0]>0) {
1336               fVarManager->FillContainer(fContainer, "conversionElecs", 1, kFALSE, weightElecBgV0[0]);
1337               fVarManager->FillContainer(fContainer, "conversionElecs", 6, kTRUE, weightElecBgV0[0]);
1338             }
1339             else if(weightElecBgV0[0]<0) {
1340               fVarManager->FillContainer(fContainer, "mesonElecs", 1, kFALSE, -1*weightElecBgV0[0]);
1341               fVarManager->FillContainer(fContainer, "mesonElecs", 6, kTRUE, -1*weightElecBgV0[0]);
1342             }
1343             //}
1344         }
1345       }
1346       if(signal) {
1347         fVarManager->FillContainer(fContainer, "recTrackContDEReco", AliHFEcuts::kStepHFEcutsDca, kFALSE);
1348         fVarManager->FillContainer(fContainer, "recTrackContDEMC", AliHFEcuts::kStepHFEcutsDca, kTRUE);
1349         fVarManager->FillCorrelationMatrix(fContainer->GetCorrelationMatrix("correlationstepafterDE"));
1350       }
1351       if(HasMCData()){
1352         if(mctrack && (TMath::Abs(mctrack->Particle()->GetPdgCode()) != 11)){
1353           fQACollection->Fill("hadronsAfterIPcut",track->Pt());
1354         }
1355       }
1356     }
1357
1358   }
1359   fQACollection->Fill("nElectronTracksEvent", nElectronCandidates);
1360 }
1361
1362 //____________________________________________________________
1363 void AliAnalysisTaskHFE::ProcessAOD(){
1364   //
1365   // Run Analysis in AOD Mode
1366   // Function is still in development
1367   //
1368   //printf("Process AOD\n");
1369   AliDebug(3, "Processing AOD Event");
1370   Double_t eventContainer[4];
1371   eventContainer[0] = 0.0;
1372   if(HasMCData()) eventContainer[0] = fVz;
1373   else {
1374     if(fInputEvent->GetPrimaryVertex()) eventContainer[0] = fInputEvent->GetPrimaryVertex()->GetZ();
1375   }
1376   eventContainer[1] = 1.; // No Information available in AOD analysis, assume all events have V0AND
1377   eventContainer[2] = fCentralityF; 
1378   eventContainer[3] = fContributors; 
1379   
1380   //printf("value event container %f, %f, %f, %f\n",eventContainer[0],eventContainer[1],eventContainer[2],eventContainer[3]);
1381
1382   AliAODEvent *fAOD = dynamic_cast<AliAODEvent *>(fInputEvent);
1383   if(!fAOD){
1384     AliError("AOD Event required for AOD Analysis");
1385       return;
1386   }
1387   
1388   //printf("Will fill\n");
1389   //
1390   fCFM->GetEventContainer()->Fill(eventContainer, AliHFEcuts::kEventStepRecNoCut);
1391   //printf("Fill\n");
1392   //
1393   if(fIdentifiedAsPileUp) return; 
1394   fCFM->GetEventContainer()->Fill(eventContainer, AliHFEcuts::kEventStepRecNoPileUp);
1395
1396   //
1397   if(fIdentifiedAsOutInz) return;
1398   fCFM->GetEventContainer()->Fill(eventContainer, AliHFEcuts::kEventStepZRange);  
1399
1400   //
1401   if(!fPassTheEventCut) return;
1402   fCFM->GetEventContainer()->Fill(eventContainer, AliHFEcuts::kEventStepReconstructed);
1403   //printf("pass\n");
1404
1405   fContainer->NewEvent();
1406
1407   fCFM->SetRecEventInfo(fAOD);
1408
1409   // Look for kink mother
1410   Int_t numberofvertices = fAOD->GetNumberOfVertices();
1411   Double_t listofmotherkink[numberofvertices];
1412   Int_t numberofmotherkink = 0;
1413   for(Int_t ivertex=0; ivertex < numberofvertices; ivertex++) {
1414     AliAODVertex *aodvertex = fAOD->GetVertex(ivertex);
1415     if(!aodvertex) continue;
1416     if(aodvertex->GetType()==AliAODVertex::kKink) {
1417       AliAODTrack *mother = (AliAODTrack *) aodvertex->GetParent();
1418       if(!mother) continue;
1419       Int_t idmother = mother->GetID();
1420       listofmotherkink[numberofmotherkink] = idmother;
1421       //printf("ID %d\n",idmother);
1422       numberofmotherkink++;
1423     }
1424   }
1425   //printf("Number of kink mother in the events %d\n",numberofmotherkink);
1426
1427
1428     // Loop over tracks
1429   AliAODTrack *track = NULL;
1430   AliAODMCParticle *mctrack = NULL;
1431   Double_t dataE[6]; // [pT, eta, Phi, Charge, type, 'C' or 'B']
1432   Int_t nElectronCandidates = 0;
1433   Int_t pid;
1434   Bool_t signal;
1435   //printf("Number of track %d\n",(Int_t) fAOD->GetNumberOfTracks());
1436   for(Int_t itrack = 0; itrack < fAOD->GetNumberOfTracks(); itrack++){
1437     track = fAOD->GetTrack(itrack); mctrack = NULL;
1438     if(!track) continue;
1439     if(fUseFlagAOD){
1440       if(track->GetFlags() != fFlags) continue;  // Only process AOD tracks where the HFE is set
1441     }
1442     //printf("Pass the flag\n");
1443
1444     signal = kTRUE;
1445     if(HasMCData()){
1446
1447       Int_t label = TMath::Abs(track->GetLabel());
1448       if(label)
1449         mctrack = dynamic_cast<AliAODMCParticle *>(fMCEvent->GetTrack(label));
1450         if(fFillSignalOnly && !fCFM->CheckParticleCuts(AliHFEcuts::kStepMCGenerated, mctrack)) signal = kFALSE;
1451     }
1452     fVarManager->NewTrack(track, mctrack, fCentralityF, -1, kTRUE);
1453     
1454     if(fFillNoCuts) {
1455       if(signal || !fFillSignalOnly){
1456         fVarManager->FillContainer(fContainer, "recTrackContReco", AliHFEcuts::kStepRecNoCut, kFALSE);
1457         fVarManager->FillContainer(fContainer, "recTrackContMC", AliHFEcuts::kStepRecNoCut, kTRUE);
1458       }
1459     }
1460
1461     if(fApplyCutAOD) {
1462       // RecKine: ITSTPC cuts  
1463       if(!ProcessCutStep(AliHFEcuts::kStepRecKineITSTPC, track)) continue;
1464
1465       // Reject kink mother
1466       Bool_t kinkmotherpass = kTRUE;
1467       for(Int_t kinkmother = 0; kinkmother < numberofmotherkink; kinkmother++) {
1468         if(track->GetID() == listofmotherkink[kinkmother]) {
1469           kinkmotherpass = kFALSE;
1470           continue;
1471         }
1472       }
1473       if(!kinkmotherpass) continue;
1474       
1475       // RecPrim
1476       if(!ProcessCutStep(AliHFEcuts::kStepRecPrim, track)) continue;
1477
1478       // HFEcuts: ITS layers cuts
1479       if(!ProcessCutStep(AliHFEcuts::kStepHFEcutsITS, track)) continue;
1480       
1481       // HFE cuts: TOF PID and mismatch flag
1482       if(!ProcessCutStep(AliHFEcuts::kStepHFEcutsTOF, track)) continue;
1483       
1484       // HFE cuts: TPC PID cleanup
1485       if(!ProcessCutStep(AliHFEcuts::kStepHFEcutsTPC, track)) continue;
1486       
1487       // HFEcuts: Nb of tracklets TRD0
1488       if(!ProcessCutStep(AliHFEcuts::kStepHFEcutsTRD, track)) continue;
1489     }
1490
1491     // Fill correlation maps before PID
1492     if(signal && fContainer->GetCorrelationMatrix("correlationstepbeforePID")) {
1493       //printf("Fill correlation maps before PID\n");
1494       fVarManager->FillCorrelationMatrix(fContainer->GetCorrelationMatrix("correlationstepbeforePID"));
1495     }
1496
1497     //printf("Will process to PID\n");
1498
1499     // track accepted, do PID
1500     AliHFEpidObject hfetrack;
1501     hfetrack.SetAnalysisType(AliHFEpidObject::kAODanalysis);
1502     hfetrack.SetRecTrack(track);
1503     if(HasMCData()) hfetrack.SetMCTrack(mctrack);
1504     hfetrack.SetCentrality(fCentralityF);
1505     if(IsPbPb()) hfetrack.SetPbPb();
1506     else hfetrack.SetPP();
1507     fPID->SetVarManager(fVarManager);
1508     if(!fPID->IsSelected(&hfetrack, fContainer, "recTrackCont", fPIDqa)) continue;    // we will do PID here as soon as possible
1509
1510     
1511     // Apply weight for background contamination
1512     //Double_t weightBackGround = 1.0;
1513     if(signal) {
1514       // Apply weight for background contamination
1515       if(fBackGroundFactorApply) {
1516         if(IsPbPb() && fCentralityF >= 0) fWeightBackGround =  fkBackGroundFactorArray[fCentralityF >= 0 ? fCentralityF : 0]->Eval(TMath::Abs(track->P()));
1517         else    fWeightBackGround =  fkBackGroundFactorArray[0]->Eval(TMath::Abs(track->P())); // pp case
1518         
1519         if(fWeightBackGround < 0.0) fWeightBackGround = 0.0;
1520         else if(fWeightBackGround > 1.0) fWeightBackGround = 1.0;
1521         // weightBackGround as special weight
1522         fVarManager->FillContainer(fContainer, "hadronicBackground", 1, kFALSE, fWeightBackGround);
1523       }
1524       fVarManager->FillCorrelationMatrix(fContainer->GetCorrelationMatrix("correlationstepafterPID"));
1525     }
1526     
1527     nElectronCandidates++;    
1528     if(HasMCData()){
1529       dataE[0] = track->Pt();
1530       dataE[1] = track->Eta();
1531       dataE[2] = track->Phi();
1532       dataE[3] = track->Charge();
1533       dataE[4] = -1;
1534       dataE[5] = -1;
1535       // Track selected: distinguish between true and fake
1536       AliDebug(1, Form("Candidate Selected, filling THnSparse, PID: %d\n", mctrack ? mctrack->GetPdgCode(): -1));
1537       if(mctrack && ((pid = TMath::Abs(mctrack->GetPdgCode())) == 11)){
1538       
1539         Int_t type = 0;
1540         if(fSignalCuts->IsCharmElectron(track))
1541           type = 1;
1542         else if(fSignalCuts->IsBeautyElectron(track))
1543           type = 2;
1544         AliDebug(1, Form("Type: %d\n", type));
1545         if(type){
1546                 dataE[5] = type; // beauty[1] or charm[2]
1547                 dataE[4] = 2;  // signal electron
1548         }
1549         else{
1550                 dataE[4] = 1; // not a signal electron
1551                 dataE[5] = 0;
1552         }
1553       } 
1554       else {
1555         // Fill THnSparse with the information for Fake Electrons
1556         dataE[4] = 0;
1557         dataE[5] = 0;
1558       }
1559       // fill the performance THnSparse, if the mc origin could be defined
1560       if(dataE[4] > -1){
1561         AliDebug(1, Form("Entries: [%.3f|%.3f|%.3f|%f|%f|%f]\n", dataE[0],dataE[1],dataE[2],dataE[3],dataE[4],dataE[5]));
1562         fQACollection->Fill("PIDperformance", dataE);
1563       }
1564     }
1565   }
1566   fQACollection->Fill("nElectronTracksEvent", nElectronCandidates);
1567 }
1568
1569 //____________________________________________________________
1570 Bool_t AliAnalysisTaskHFE::ProcessMCtrack(AliVParticle *track){
1571   //
1572   // Filter the Monte Carlo Track
1573   // Additionally Fill a THnSparse for Signal To Background Studies
1574   // Works for AOD and MC analysis Type
1575   //
1576   fVarManager->NewTrack(track, NULL, fCentralityF, -1, kTRUE);
1577   Double_t signalContainer[6];
1578
1579   signalContainer[0] = track->Pt();
1580   signalContainer[1] = track->Eta();
1581   signalContainer[2] = track->Phi();
1582   signalContainer[3] = track->Charge()/3;
1583
1584   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)
1585   if(IsESDanalysis()){
1586     AliMCParticle *mctrack = dynamic_cast<AliMCParticle *>(track);
1587     if(mctrack){
1588       vertex[0] = mctrack->Particle()->Vx();
1589       vertex[1] = mctrack->Particle()->Vy();
1590     }
1591   } else {
1592     AliAODMCParticle *aodmctrack = dynamic_cast<AliAODMCParticle *>(track);
1593     if(aodmctrack) aodmctrack->XvYvZv(vertex);
1594   }
1595
1596   if(!fCFM->CheckParticleCuts(AliHFEcuts::kStepMCGenerated, track)) return kFALSE;
1597   fVarManager->FillContainer(fContainer, "MCTrackCont", AliHFEcuts::kStepMCGenerated, kFALSE);
1598   signalContainer[4] = 0;
1599   if(fSignalCuts->IsSelected(track)){
1600     //fVarManager->FillContainer(fContainer, "MCTrackCont", AliHFEcuts::kStepMCsignal, kFALSE);
1601     // Filling of the Signal/Background histogram using the 
1602     // definition of the codes for charm and beauty as below in
1603     // th crearion of the histogram
1604     if(fSignalCuts->IsCharmElectron(track))
1605       signalContainer[4] = 1;
1606     else 
1607       signalContainer[4] = 2;
1608   } else {
1609     signalContainer[4] = 0; // (and other background)
1610   }
1611   signalContainer[5] = 0;
1612   // apply cut on the sqrt of the production vertex
1613   Double_t radVertex = TMath::Sqrt(vertex[0]*vertex[0] + vertex[1] * vertex[1]);
1614   if(radVertex < 3.5){
1615     // Within first ITS layer(2) -> Background we cannot reject by ITS cut, let it pass
1616     signalContainer[5] = 1;
1617   } else if (radVertex < 7.5){
1618     signalContainer[5] = 2;
1619   }
1620   fQACollection->Fill("SignalToBackgroundMC", signalContainer);
1621
1622   // Step GeneratedZOutNoPileUp
1623   if((fIdentifiedAsPileUp) || (TMath::Abs(fVz) > fCuts->GetVertexRange()) || (fCentralityF < 0)) return kFALSE;
1624   fVarManager->FillContainer(fContainer, "MCTrackCont", AliHFEcuts::kStepMCGeneratedZOutNoPileUpCentralityFine, kFALSE);
1625   //printf("In ProcessMCtrack %f\n",fCentralityF);
1626
1627   // Step Generated Event Cut
1628   if(!fPassTheEventCut) return kFALSE;
1629   fVarManager->FillContainer(fContainer, "MCTrackCont", AliHFEcuts::kStepMCGeneratedEventCut, kFALSE);
1630
1631   if(!fCFM->CheckParticleCuts(AliHFEcuts::kStepMCInAcceptance, track)) return kFALSE;
1632   fVarManager->FillContainer(fContainer, "MCTrackCont", AliHFEcuts::kStepMCInAcceptance, kFALSE);
1633   return kTRUE;
1634 }
1635
1636 //____________________________________________________________
1637 Bool_t AliAnalysisTaskHFE::PreSelectTrack(AliESDtrack *track) const {
1638   //
1639   // Preselect tracks
1640   //
1641   
1642
1643   Bool_t survived = kTRUE;
1644   
1645   if(!fCutspreselect->CheckParticleCuts(AliHFEcuts::kStepRecKineITSTPC, track)) {
1646     survived = kFALSE;
1647     //printf("Did not pass AliHFEcuts::kStepRecKineITSTPC\n");
1648   }
1649   //else printf("Pass AliHFEcuts::kStepRecKineITSTPC\n");
1650   if(!fCutspreselect->CheckParticleCuts(AliHFEcuts::kStepRecPrim, track)) {
1651     survived = kFALSE;
1652     //printf("Did not pass AliHFEcuts::kStepRecPrim\n");
1653   }
1654   //else printf("Pass AliHFEcuts::kStepRecPrim\n");
1655   if(!fCutspreselect->CheckParticleCuts(AliHFEcuts::kStepHFEcutsITS, track)) {
1656     survived = kFALSE;
1657     //printf("Did not pass AliHFEcuts::kStepHFEcutsITS\n");
1658   }
1659   //else printf("Pass AliHFEcuts::kStepHFEcutsITS\n");
1660   if(!fCutspreselect->CheckParticleCuts(AliHFEcuts::kStepHFEcutsTOF, track)) {
1661     survived = kFALSE;
1662     //printf("Did not pass AliHFEcuts::kStepHFEcutsTOF\n");
1663   }
1664   //else printf("Pass AliHFEcuts::kStepHFEcutsTOF\n");
1665   if(!fCutspreselect->CheckParticleCuts(AliHFEcuts::kStepHFEcutsTRD, track)) {
1666     survived = kFALSE;
1667     //printf("Did not pass AliHFEcuts::kStepHFEcutsTRD\n");
1668   }
1669   //else printf("Pass AliHFEcuts::kStepHFEcutsTRD\n");
1670   
1671   if(survived){
1672     // Apply PID
1673     AliHFEpidObject hfetrack;
1674     hfetrack.SetAnalysisType(AliHFEpidObject::kESDanalysis);
1675     hfetrack.SetRecTrack(track);
1676     if(!fPIDpreselect->IsSelected(&hfetrack)) {
1677       //printf("Did not pass AliHFEcuts::kPID\n");
1678       survived = kFALSE;
1679     }
1680     //else printf("Pass AliHFEcuts::kPID\n");
1681   }
1682
1683   return survived; 
1684       
1685 }
1686 //____________________________________________________________
1687 void AliAnalysisTaskHFE::MakeEventContainer(){
1688   //
1689   // Create the event container for the correction framework and link it
1690   // 1st bin: Vertex z-position
1691   // 2nd bin: V0AND decision (normalization to sigma_inel)
1692   // 3rd bin: Centrality class (for pp defined as number of contributors in vertex.)
1693   // 4th bin: Number of contributors > 0
1694   //
1695   
1696   const Int_t kNvar = 4;  // number of variables on the grid: 
1697   Int_t nBins[kNvar] = {120, 2, 11, 2};
1698   Double_t binMin[kNvar] = {-30. , 0., 0.0, 0.};
1699   Double_t binMax[kNvar] = {30., 2., 11.0, 2.};
1700   
1701   AliCFContainer *evCont = new AliCFContainer("eventContainer", "Container for events", AliHFEcuts::kNcutStepsEvent, kNvar, nBins);
1702   
1703   Double_t *vertexBins = AliHFEtools::MakeLinearBinning(nBins[0], binMin[0], binMax[0]);
1704   Double_t *v0andBins = AliHFEtools::MakeLinearBinning(nBins[1], binMin[1], binMax[1]);
1705   Double_t *centralityBins = AliHFEtools::MakeLinearBinning(nBins[2], binMin[2], binMax[2]);
1706   Double_t *contributorsBins = AliHFEtools::MakeLinearBinning(nBins[3], binMin[3], binMax[3]);
1707   evCont->SetBinLimits(0, vertexBins);
1708   evCont->SetBinLimits(1, v0andBins);
1709   evCont->SetBinLimits(2, centralityBins);
1710   evCont->SetBinLimits(3, contributorsBins);
1711   delete[] vertexBins; delete[] v0andBins; delete[] centralityBins; delete[] contributorsBins;
1712     
1713   fCFM->SetEventContainer(evCont);
1714 }
1715
1716 //____________________________________________________________
1717 void AliAnalysisTaskHFE::MakeParticleContainer(){
1718   //
1719   // Create the particle container for the correction framework manager and 
1720   // link it
1721   //
1722   if(!fContainer) fContainer = new AliHFEcontainer("trackContainer");
1723   fVarManager->DefineVariables(fContainer);
1724
1725   // Create Correction Framework containers
1726   fContainer->CreateContainer("MCTrackCont", "Track Container filled with MC information", AliHFEcuts::kNcutStepsMCTrack);
1727   fContainer->CreateContainer("recTrackContReco", "Track Container filled with MC information", AliHFEcuts::kNcutStepsRecTrack + fPID->GetNumberOfPIDdetectors());
1728   fContainer->CreateContainer("recTrackContMC", "Track Container filled with MC information", AliHFEcuts::kNcutStepsRecTrack + fPID->GetNumberOfPIDdetectors());
1729   
1730   fContainer->CreateContainer("hadronicBackground", "Container for Hadronic Background", 2);
1731   fContainer->CreateContainer("recTrackContDEReco", "Container for displaced electron analysis with Reco information", 1);
1732   fContainer->CreateContainer("recTrackContDEMC", "Container for displaced electron analysis with MC information", 1);
1733   fContainer->CreateContainer("recTrackContSecvtxReco", "Container for secondary vertexing analysis with Reco information", 1);
1734   fContainer->CreateContainer("recTrackContSecvtxMC", "Container for secondary vertexing analysis with MC information", 1);
1735
1736   if(HasMCData()){
1737     fContainer->CreateContainer("conversionElecs", "Container for weighted conversion electrons",7);
1738     fContainer->CreateContainer("mesonElecs", "Container for weighted electrons from meson decays",7);
1739     fContainer->Sumw2("conversionElecs");
1740     fContainer->Sumw2("mesonElecs");
1741    
1742     if(fisNonHFEsystematics){
1743       const Char_t *sourceName[kElecBgSpecies]={"Pion","Eta","Omega","Phi","EtaPrime","Rho"};
1744       const Char_t *levelName[kBgLevels]={"Best","Lower","Upper"};
1745       for(Int_t iSource = 0; iSource < kElecBgSpecies; iSource++){
1746         for(Int_t iLevel = 0; iLevel < kBgLevels; iLevel++){
1747           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);
1748           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);
1749           fContainer->Sumw2(Form("conversionElecs%s%s",sourceName[iSource],levelName[iLevel]));
1750           fContainer->Sumw2(Form("mesonElecs%s%s",sourceName[iSource],levelName[iLevel]));
1751           if(IsPbPb())break;
1752         }
1753       }
1754     }
1755     //fContainer->CreateContainer("charmElecs", "Container for weighted charm electrons",2);
1756   }
1757
1758   fContainer->CreateCorrelationMatrix("correlationstepafterPID","THnSparse with correlations");
1759   fContainer->CreateCorrelationMatrix("correlationstepafterDE","THnSparse with correlations");
1760   if(!fVarManager->IsVariableDefined("centrality")) {
1761     //printf("Create the two other correlation maps\n");
1762     fContainer->CreateCorrelationMatrix("correlationstepbeforePID","THnSparse with correlations");
1763     fContainer->CreateCorrelationMatrix("correlationstepafterTOF","THnSparse with correlations");
1764   }
1765
1766   // Define the step names
1767   for(UInt_t istep = 0; istep < AliHFEcuts::kNcutStepsMCTrack; istep++){
1768     fContainer->SetStepTitle("MCTrackCont", AliHFEcuts::MCCutName(istep), istep);
1769   }
1770   for(UInt_t istep = 0; istep < AliHFEcuts::kNcutStepsRecTrack; istep++){
1771     fContainer->SetStepTitle("recTrackContReco", AliHFEcuts::RecoCutName(istep), istep);
1772     fContainer->SetStepTitle("recTrackContMC", AliHFEcuts::RecoCutName(istep), istep);
1773   }
1774   for(UInt_t ipid = 0; ipid < fPID->GetNumberOfPIDdetectors(); ipid++){
1775     fContainer->SetStepTitle("recTrackContReco", fPID->SortedDetectorName(ipid), AliHFEcuts::kNcutStepsRecTrack + ipid);
1776     fContainer->SetStepTitle("recTrackContMC", fPID->SortedDetectorName(ipid), AliHFEcuts::kNcutStepsRecTrack + ipid);
1777   }
1778 }
1779
1780 //____________________________________________________________
1781 void AliAnalysisTaskHFE::InitPIDperformanceQA(){
1782   // Add a histogram for Fake electrons
1783   const Int_t nDim=6;
1784   Int_t nBin[nDim] = {40, 8, 18, 2, 3, 3};
1785   //number of variables on the grid:pt,eta,phi,charge,
1786   const Double_t kPtbound[2] = {0.1, 20.};
1787   const Double_t kEtabound[2] = {-0.8, 0.8};
1788   const Double_t kPhibound[2] = {0., 2. * TMath::Pi()}; 
1789   const Double_t kChargebound[2] = {-1.1, 1.1};
1790   const Double_t kAddInf1bound[2] = {0., 3.};
1791   const Double_t kAddInf2bound[2] = {0., 3.};
1792   Double_t minima[nDim] = {kPtbound[0], kEtabound[0], kPhibound[0], kChargebound[0], kAddInf1bound[0], kAddInf2bound[0]}; 
1793   Double_t maxima[nDim] = {kPtbound[1], kEtabound[1], kPhibound[1], kChargebound[1], kAddInf1bound[1], kAddInf2bound[1]}; 
1794   
1795   fQACollection->CreateTHnSparse("PIDperformance", "PID performance; pT [GeV/c]; theta [rad]; phi [rad]; charge; type (0 - not el, 1 - other el, 2 - HF el; flavor (0 - no, 1 - charm, 2 - bottom)", nDim, nBin, minima, maxima);
1796   fQACollection->CreateTHnSparse("SignalToBackgroundMC", "PID performance; pT [GeV/c]; theta [rad]; phi [rad]; charge; flavor (0 - no, 1 - charm, 2 - bottom); ITS Cluster (0 - no, 1 - first (and maybe second), 2 - second)", nDim, nBin, minima, maxima);
1797
1798   fQACollection->BinLogAxis("PIDperformance", 0);
1799   fQACollection->BinLogAxis("SignalToBackgroundMC", 0);
1800   fQACollection->Sumw2("PIDperformance");
1801   fQACollection->Sumw2("SignalToBackgroundMC");
1802 }
1803
1804 //____________________________________________________________
1805 void AliAnalysisTaskHFE::InitContaminationQA(){
1806   // 
1807   // Add QA for Impact Parameter cut
1808   //
1809
1810   TObjArray *array = fVarManager->GetVariables();
1811   Int_t nvars = array->GetEntriesFast();
1812   for(Int_t v = 0; v < nvars; v++) {
1813     AliHFEvarManager::AliHFEvariable *variable = (AliHFEvarManager::AliHFEvariable *) array->At(v);
1814     if(!variable) continue;
1815     TString name(((AliHFEvarManager::AliHFEvariable *)variable)->GetName());
1816     if(!name.CompareTo("pt")) {
1817       const Int_t nBinPt  = variable->GetNumberOfBins();
1818       const Double_t *kPtRange = variable->GetBinning();
1819
1820       fQACollection->CreateTH1Farray("hadronsBeforeIPcut", "Hadrons before IP cut", nBinPt, kPtRange);
1821       fQACollection->CreateTH1Farray("hadronsAfterIPcut", "Hadrons after IP cut", nBinPt, kPtRange);
1822
1823       fQACollection->CreateTH2Farray("Ke3Kecorr", "Ke3 decay e and K correlation; Ke3K p_{t}; Ke3e p_{t}; ", nBinPt, kPtRange, 20,0.,20.);
1824       fQACollection->CreateTH2Farray("Ke3K0Lecorr", "Ke3 decay e and K0L correlation; Ke3K0L p_{t}; Ke3e p_{t}; ", nBinPt, kPtRange, 20,0.,20.);
1825       fQACollection->CreateTH1Farray("Kptspectra", "Charged Kaons: MC p_{t} ", nBinPt, kPtRange);
1826       fQACollection->CreateTH1Farray("K0Lptspectra", "K0L: MC p_{t} ", nBinPt, kPtRange);
1827
1828       const Double_t kDCAbound[2] = {-0.2, 0.2};
1829
1830       const Int_t nDimDca=6;
1831       const Int_t nBinDca[nDimDca] = { 8, nBinPt, 800, 12,  6, 2};
1832       Double_t minimaDca[nDimDca]  = { -1., 0., kDCAbound[0], -1., -1, -1.1};
1833       Double_t maximaDca[nDimDca]  = { 7., 20., kDCAbound[1], 11.,  5, 1.1};
1834
1835       Double_t *sourceBins = AliHFEtools::MakeLinearBinning(nBinDca[0], minimaDca[0], maximaDca[0]);
1836       Double_t *dcaBins = AliHFEtools::MakeLinearBinning(nBinDca[2], minimaDca[2], maximaDca[2]);
1837       Double_t *centralityBins = AliHFEtools::MakeLinearBinning(nBinDca[3], minimaDca[3], maximaDca[3]);
1838       Double_t *v0PIDBins = AliHFEtools::MakeLinearBinning(nBinDca[4], minimaDca[4], maximaDca[4]);
1839       Double_t *chargeBins = AliHFEtools::MakeLinearBinning(nBinDca[5], minimaDca[5], maximaDca[5]);
1840
1841       fQACollection->CreateTHnSparseNoLimits("Dca", "Dca; source (0-all, 1-charm,etc); pT [GeV/c]; dca; centrality bin; v0pid; charge", nDimDca, nBinDca);
1842       ((THnSparse*)(fQACollection->Get("Dca")))->SetBinEdges(0, sourceBins);
1843       ((THnSparse*)(fQACollection->Get("Dca")))->SetBinEdges(1, kPtRange);
1844       ((THnSparse*)(fQACollection->Get("Dca")))->SetBinEdges(2, dcaBins);
1845       ((THnSparse*)(fQACollection->Get("Dca")))->SetBinEdges(3, centralityBins);
1846       ((THnSparse*)(fQACollection->Get("Dca")))->SetBinEdges(4, v0PIDBins);
1847       ((THnSparse*)(fQACollection->Get("Dca")))->SetBinEdges(5, chargeBins);
1848
1849       break;
1850     }  
1851   }
1852
1853 }
1854
1855 //____________________________________________________________
1856 void AliAnalysisTaskHFE::InitHistoITScluster(){
1857   //
1858     // Initialize a temporary histogram to monitor the chi2/ITS cluster
1859     if(IsPbPb()) {
1860         const Int_t kNDim = 7;
1861         const Int_t kNBins[kNDim] = {88, 20,90,11, 160, 2, 1000};
1862         const Double_t kMin[kNDim] = {0.1, -1,0,  0.,0., 0,  0.};
1863         const Double_t kMax[kNDim] = {20., 1, 2.*TMath::Pi(), 11.,160, 2, 100.};
1864         fQACollection->CreateTHnSparse("fChi2perITScluster", "chi2/ITS cluster; p_{T} (GeV/c);eta;phi; centrality class;nclus;sharebit; #chi^{2}/ITS cluster", kNDim, kNBins, kMin, kMax);
1865         fQACollection->BinLogAxis("fChi2perITScluster", 0);
1866     }
1867     else
1868     {
1869         const Int_t kNDim = 3;
1870         const Int_t kNBins[kNDim] = {44, 11, 1000};
1871         const Double_t kMin[kNDim] = {0.1, 0., 0.};
1872         const Double_t kMax[kNDim] = {20., 11., 100.};
1873         fQACollection->CreateTHnSparse("fChi2perITScluster", "chi2/ITS cluster; p_{T} (GeV/c); centrality class; #chi^{2}/ITS cluster", kNDim, kNBins, kMin, kMax);
1874         fQACollection->BinLogAxis("fChi2perITScluster", 0);
1875     }
1876 }
1877
1878 //____________________________________________________________
1879 void AliAnalysisTaskHFE::SelectSpecialTrigger(const Char_t *trgclust, Int_t runMin, Int_t runMax){
1880   //
1881   // Select only events triggered by a special trigeer cluster
1882   //
1883   if(!fSpecialTrigger) fSpecialTrigger = new AliOADBContainer("SpecialTrigger");
1884   fSpecialTrigger->AppendObject(new TObjString(trgclust), runMin, runMax);
1885 }
1886
1887 //____________________________________________________________
1888 const Char_t * AliAnalysisTaskHFE::GetSpecialTrigger(Int_t run){
1889   //
1890   // Derive selected trigger string for given run
1891   //
1892   if(!fSpecialTrigger) return NULL;
1893   TObjString *trg = dynamic_cast<TObjString *>(fSpecialTrigger->GetObject(run));
1894   if(!trg) return NULL;
1895   return trg->String().Data();
1896 }
1897
1898 //____________________________________________________________
1899 void AliAnalysisTaskHFE::PrintStatus() const {
1900   //
1901   // Print Analysis status
1902   //
1903   printf("\n\tAnalysis Settings\n\t========================================\n\n");
1904   printf("\tSecondary Vertex finding: %s\n", GetPlugin(kSecVtx) ? "YES" : "NO");
1905   printf("\tPrimary Vertex resolution: %s\n", GetPlugin(kPriVtx) ? "YES" : "NO");
1906   printf("\tDisplaced electron analysis step: %s\n", GetPlugin(kDEstep) ? "YES" : "NO");
1907   printf("\tTagged Track Analysis: %s\n", GetPlugin(kTaggedTrackAnalysis) ? "YES" : "NO");
1908   printf("\n");
1909   printf("\tParticle Identification Detectors:\n");
1910   fPID->PrintStatus();
1911   printf("\n");
1912   printf("\tQA: \n");
1913   printf("\t\tPID: %s\n", IsQAOn(kPIDqa) ? "YES" :  "NO");
1914   printf("\t\tCUTS: %s\n", (fCuts != NULL && fCuts->IsQAOn()) ? "YES" : "NO");
1915   printf("\t\tMC: %s\n", IsQAOn(kMCqa) ? "YES" : "NO");
1916   printf("\n");
1917 }
1918
1919 //____________________________________________________________
1920 Bool_t AliAnalysisTaskHFE::FillProductionVertex(const AliVParticle * const track) const{
1921   //
1922   // Find the production vertex of the associated MC track
1923   //
1924   if(!fMCEvent) return kFALSE;
1925   const AliVParticle *mctrack = NULL;
1926   TString objectType = track->IsA()->GetName();
1927   if(objectType.CompareTo("AliESDtrack") == 0 || objectType.CompareTo("AliAODTrack") == 0){
1928     // Reconstructed track
1929     mctrack = fMCEvent->GetTrack(TMath::Abs(track->GetLabel()));
1930   } else {
1931     // MCParticle
1932     mctrack = track;
1933   }
1934
1935   if(!mctrack) return kFALSE;
1936
1937   Double_t xv = 0.0;
1938   Double_t yv = 0.0;
1939  
1940   if(TString(mctrack->IsA()->GetName()).CompareTo("AliMCParticle") == 0){
1941     // case MCParticle
1942     const AliMCParticle *mcpart = dynamic_cast<const AliMCParticle *>(mctrack);
1943     if(mcpart){
1944       xv =  mcpart->Xv();
1945       yv =  mcpart->Yv();
1946     }
1947   } else {
1948     // case AODMCParticle
1949     const AliAODMCParticle *mcpart = dynamic_cast<const AliAODMCParticle *>(mctrack);
1950     if(mcpart){
1951       xv =  mcpart->Xv();
1952       yv =  mcpart->Yv();
1953     }
1954   }
1955
1956   //printf("xv %f, yv %f\n",xv,yv);
1957   fQACollection->Fill("radius", TMath::Abs(xv),TMath::Abs(yv));
1958
1959   return kTRUE;
1960
1961 }
1962 //__________________________________________
1963 void AliAnalysisTaskHFE::SwitchOnPlugin(Int_t plug){
1964   //
1965   // Switch on Plugin
1966   // Available:
1967   //  - Primary vertex studies
1968   //  - Secondary vertex Studies
1969   //  - Post Processing
1970   //
1971   switch(plug){
1972     case kPriVtx: SETBIT(fPlugins, plug); break;
1973     case kSecVtx: SETBIT(fPlugins, plug); break;
1974     case kIsElecBackGround: SETBIT(fPlugins, plug); break;
1975     case kPostProcess: SETBIT(fPlugins, plug); break;
1976     case kDEstep: SETBIT(fPlugins, plug); break;
1977     case kTaggedTrackAnalysis: SETBIT(fPlugins, plug); break;
1978     default: AliError("Unknown Plugin");
1979   };
1980 }
1981 //__________________________________________
1982 Bool_t AliAnalysisTaskHFE::ProcessCutStep(Int_t cutStep, AliVParticle *track){
1983   //
1984   // Check single track cuts for a given cut step
1985   // Fill the particle container
1986   //
1987   const Int_t kMCOffset = AliHFEcuts::kNcutStepsMCTrack;
1988   if(!fCFM->CheckParticleCuts(cutStep + kMCOffset, track)) return kFALSE;
1989   if(fVarManager->IsSignalTrack()) {
1990     fVarManager->FillContainer(fContainer, "recTrackContReco", cutStep, kFALSE);
1991     fVarManager->FillContainer(fContainer, "recTrackContMC", cutStep, kTRUE);
1992   }
1993   return kTRUE;
1994 }
1995 //___________________________________________________
1996 Bool_t AliAnalysisTaskHFE::ReadCentrality() {
1997   //
1998   // Recover the centrality of the event from ESD or AOD
1999   //
2000   
2001   Float_t fCentralityLimitstemp[12];
2002   Float_t fCentralityLimitsdefault[12]= {0.,5.,10., 20., 30., 40., 50., 60.,70.,80., 90., 100.};
2003   if(!fPbPbUserCentralityBinning) memcpy(fCentralityLimitstemp,fCentralityLimitsdefault,sizeof(fCentralityLimitsdefault));
2004   else memcpy(fCentralityLimitstemp,fCentralityLimits,sizeof(fCentralityLimitsdefault));
2005   
2006
2007   Int_t bin = -1;
2008   if(IsPbPb()) {
2009     // Centrality
2010     AliCentrality *centrality = fInputEvent->GetCentrality();
2011     fCentralityPercent = centrality->GetCentralityPercentile("V0M");
2012     //printf("centrality %f\n",fCentralityPercent);
2013
2014     for(Int_t ibin = 0; ibin < 11; ibin++){
2015       if(fCentralityPercent >= fCentralityLimitstemp[ibin] && fCentralityPercent < fCentralityLimitstemp[ibin+1]){
2016         bin = ibin;
2017         //printf("test bin %f, low %f, high %f, %d\n",fCentralityPercent,fCentralityLimitstemp[ibin],fCentralityLimitstemp[ibin+1],ibin);
2018         break;
2019       }
2020     }
2021     
2022     if(bin == -1) bin = 11; // Overflow
2023   } else {
2024     // PP: Tracklet multiplicity, use common definition
2025     Int_t itsMultiplicity = GetITSMultiplicity(fInputEvent);
2026     Int_t multiplicityLimits[8] = {0, 1, 9, 17, 25, 36, 60, 500};
2027     for(Int_t ibin = 0; ibin < 7; ibin++){  
2028       if(itsMultiplicity >= multiplicityLimits[ibin] && itsMultiplicity < multiplicityLimits[ibin + 1]){
2029         bin = ibin;
2030         break;
2031       }
2032     }
2033     if(bin == -1) bin = 7;  // Overflow
2034   }
2035   fCentralityF = bin;
2036   AliDebug(2, Form("Centrality class %d\n", fCentralityF));
2037
2038  
2039   // contributors, to be outsourced
2040   const AliVVertex *vtx;
2041   if(IsAODanalysis()){
2042     AliAODEvent *fAOD = dynamic_cast<AliAODEvent *>(fInputEvent);
2043     if(!fAOD){
2044       AliError("AOD Event required for AOD Analysis");
2045       return kFALSE;
2046     }
2047     vtx = fAOD->GetPrimaryVertex();
2048   } else {
2049     AliESDEvent *fESD = dynamic_cast<AliESDEvent *>(fInputEvent);
2050     if(!fESD){
2051       AliError("ESD Event required for ESD Analysis");
2052       return kFALSE;
2053     }
2054     vtx = fESD->GetPrimaryVertexSPD();
2055   }
2056   if(!vtx){ 
2057     fContributors = 0.5;
2058     return kFALSE;
2059   }
2060   else {
2061     Int_t contributorstemp = vtx->GetNContributors();
2062     if( contributorstemp <=  0) {
2063       fContributors =  0.5;
2064       //printf("Number of contributors %d and vz %f\n",contributorstemp,vtx->GetZ());
2065     }
2066     else fContributors = 1.5;
2067     //printf("Number of contributors %d\n",contributorstemp);
2068   }
2069   return kTRUE;
2070 }
2071
2072 //___________________________________________________
2073 Int_t AliAnalysisTaskHFE::GetITSMultiplicity(AliVEvent *ev){
2074   //
2075   // Definition of the Multiplicity according to the JPSI group (F. Kramer)
2076   //
2077   Int_t nTracklets = 0;
2078   Int_t nAcc = 0;
2079   Double_t etaRange = 1.6;
2080
2081   if (ev->IsA() == AliAODEvent::Class()) {
2082     AliAODTracklets *tracklets = ((AliAODEvent*)ev)->GetTracklets();
2083     nTracklets = tracklets->GetNumberOfTracklets();
2084     for (Int_t nn = 0; nn < nTracklets; nn++) {
2085       Double_t theta = tracklets->GetTheta(nn);
2086       Double_t eta = -TMath::Log(TMath::Tan(theta/2.0));
2087       if (TMath::Abs(eta) < etaRange) nAcc++;
2088     }
2089   } else if (ev->IsA() == AliESDEvent::Class()) {
2090     nTracklets = ((AliESDEvent*)ev)->GetMultiplicity()->GetNumberOfTracklets();
2091     for (Int_t nn = 0; nn < nTracklets; nn++) {
2092        Double_t eta = ((AliESDEvent*)ev)->GetMultiplicity()->GetEta(nn);
2093       if (TMath::Abs(eta) < etaRange) nAcc++;
2094     }
2095   } else return -1;
2096
2097   return nAcc;
2098 }
2099
2100 //___________________________________________________
2101 Bool_t AliAnalysisTaskHFE::InitializeHadronBackground(Int_t run){
2102   //
2103   // Initialize background factors array from the AliOADBContainer
2104   // The container is expected to provide a TObjArray with the name
2105   // "hadronBackground" and the size 12 for the given run number
2106   //
2107   AliDebug(1, "Deriving hadronic background parameterization from OADB container");
2108   TObjArray *functions = dynamic_cast<TObjArray *>(fHadronBackgroundOADB->GetObject(run, "hadronBackground"));
2109   if(!functions){
2110     AliDebug(1, "Content in the OADB Container is not a TObjArray");
2111     fBackGroundFactorApply = kFALSE;
2112     return kFALSE;
2113   } 
2114   if(functions->GetSize() < 12){
2115     AliDebug(1, Form("Size not matching: 12 expected, %d provided", functions->GetSize()));
2116     fBackGroundFactorApply = kFALSE;
2117     return kFALSE;
2118   }
2119   for(Int_t icent = 0; icent < 12; icent++) fkBackGroundFactorArray[icent] = dynamic_cast<const TF1 *>(functions->UncheckedAt(icent));
2120   return kTRUE;
2121 }
2122
2123 //___________________________________________________
2124 void AliAnalysisTaskHFE::RejectionPileUpVertexRangeEventCut() {
2125   //
2126   // Recover the centrality of the event from ESD or AOD
2127   //
2128  if(IsAODanalysis()){
2129
2130    AliAODEvent *fAOD = dynamic_cast<AliAODEvent *>(fInputEvent);
2131    if(!fAOD){
2132      AliError("AOD Event required for AOD Analysis");
2133        return;
2134    }
2135    // PileUp
2136    fIdentifiedAsPileUp = kFALSE;
2137    if(fRemovePileUp && fAOD->IsPileupFromSPD()) fIdentifiedAsPileUp = kTRUE; 
2138    // Z vertex
2139    fIdentifiedAsOutInz = kFALSE;
2140    //printf("Z vertex %f and out %f\n",fAOD->GetPrimaryVertex()->GetZ(),fCuts->GetVertexRange());
2141    if(TMath::Abs(fAOD->GetPrimaryVertex()->GetZ()) > fCuts->GetVertexRange()) fIdentifiedAsOutInz = kTRUE;
2142    // Event Cut
2143    fPassTheEventCut = kTRUE;
2144    if(!fCFM->CheckEventCuts(AliHFEcuts::kEventStepReconstructed, fAOD)) fPassTheEventCut = kFALSE; 
2145    
2146    
2147  } else {
2148    
2149    AliDebug(3, "Processing ESD Centrality");
2150    AliESDEvent *fESD = dynamic_cast<AliESDEvent *>(fInputEvent);
2151    if(!fESD){
2152      AliError("ESD Event required for ESD Analysis");
2153        return;
2154    }
2155    // PileUp
2156    fIdentifiedAsPileUp = kFALSE;
2157    if(fRemovePileUp && fESD->IsPileupFromSPD()) fIdentifiedAsPileUp = kTRUE; 
2158    // Z vertex
2159    fIdentifiedAsOutInz = kFALSE;
2160    if (IsPbPb()) {
2161      //printf("PbPb\n");
2162      if(fESD->GetPrimaryVertex()){
2163        if(TMath::Abs(fESD->GetPrimaryVertex()->GetZ()) > fCuts->GetVertexRange()) fIdentifiedAsOutInz = kTRUE;
2164      }
2165    }
2166    else {
2167      //printf("pp\n");
2168      if(fESD->GetPrimaryVertexTracks()){
2169        if(TMath::Abs(fESD->GetPrimaryVertexTracks()->GetZ()) > fCuts->GetVertexRange()) fIdentifiedAsOutInz = kTRUE;
2170      }
2171    }
2172    //Event Cut
2173    fPassTheEventCut = kTRUE;
2174    if(!fCFM->CheckEventCuts(AliHFEcuts::kEventStepReconstructed, fESD)) fPassTheEventCut = kFALSE;   
2175   
2176
2177  }
2178
2179 }
2180