]> git.uio.no Git - u/mrichter/AliRoot.git/blob - PWGCF/Correlations/DPhi/TriggerPID/AliTwoParticlePIDCorr.cxx
Merge branch 'master' of https://git.cern.ch/reps/AliRoot
[u/mrichter/AliRoot.git] / PWGCF / Correlations / DPhi / TriggerPID / AliTwoParticlePIDCorr.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 #include "AliTwoParticlePIDCorr.h"
17 #include "AliVParticle.h"
18 #include "TFormula.h"
19 #include "TAxis.h"
20 #include "TChain.h"
21 #include "TTree.h"
22 #include "TH1F.h"
23 #include "TH2F.h"
24 #include "TH3F.h"
25 #include "TProfile.h"
26 #include "TList.h"
27 #include "TFile.h"
28 #include "TGrid.h"
29 #include "TExMap.h"
30 #include "AliCentrality.h"
31 #include "Riostream.h"
32
33 #include "AliAnalysisDataSlot.h"
34  #include "AliAnalysisDataContainer.h"
35
36 #include "AliTHn.h"    
37 #include "AliCFContainer.h"
38 #include "THn.h"
39 #include "THnSparse.h"
40 #include "TBits.h"
41 #include <TSpline.h>
42 #include <AliPID.h>
43 #include "AliESDpid.h"
44 #include "AliAODpidUtil.h"
45 #include <AliPIDResponse.h>
46 #include "AliPIDCombined.h"   
47
48 #include <AliInputEventHandler.h>
49 #include "AliAODInputHandler.h"
50
51 #include "AliAnalysisTaskSE.h"
52 #include "AliAnalysisManager.h"
53 #include "AliCentrality.h"
54
55 #include "AliVEvent.h"
56 #include "AliAODEvent.h"
57 #include "AliAODTrack.h"
58 #include "AliVTrack.h"
59 #include "AliAODv0.h"
60 #include "AliAODcascade.h"
61
62 #include "THnSparse.h"
63
64 #include "AliAODMCHeader.h"
65 #include "AliAODMCParticle.h"
66 #include "AliMCEventHandler.h"
67 #include "AliMCEvent.h"
68 #include "AliMCParticle.h"
69 #include "TParticle.h"
70 #include <TDatabasePDG.h>
71 #include <TParticlePDG.h>
72
73 #include "AliGenCocktailEventHeader.h"
74 #include "AliGenEventHeader.h"
75 #include "AliCollisionGeometry.h"
76 #include "AliOADBContainer.h"
77
78 #include "AliEventPoolManager.h"
79 #include "AliAnalysisUtils.h"
80 using namespace AliPIDNameSpace;
81 using namespace std;
82
83 ClassImp(AliTwoParticlePIDCorr)
84 ClassImp(LRCParticlePID)
85
86 const char * kPIDTypeName[]={"TPC","TOF","TPC-TOF"} ;
87 const char * kDetectorName[]={"ITS","TPC","TOF"} ;
88 const char * kParticleSpeciesName[]={"Pions","Kaons","Protons","Undefined"} ;
89 //Source code::dphicorrelations,VnV0, TaskBFpsi, AliHelperPID, 
90
91 //________________________________________________________________________
92 AliTwoParticlePIDCorr::AliTwoParticlePIDCorr() // All data members should be initialised here
93 :AliAnalysisTaskSE(),
94   fOutput(0),
95    fOutputList(0),
96   fList(0),
97   fCentralityMethod("V0A"),
98   fPPVsMultUtils(kFALSE),
99   fSampleType("pPb"),
100  fRequestEventPlane(kFALSE),
101  fRequestEventPlanemixing(kFALSE),
102   fnTracksVertex(1),  // QA tracks pointing to principal vertex (= 3 default)
103   trkVtx(0),
104   zvtx(0),
105   fFilterBit(768),
106   fTrackStatus(0),
107   fSharedClusterCut(-1),
108  fSharedTPCmapCut(-1),
109  fSharedfraction_Pair_cut(-1),
110   fVertextype(1),
111  skipParticlesAbove(0),
112   fzvtxcut(10.0),
113   fVxMax_MC(0.3),
114   fVyMax_MC(0.3),
115   fVzMax_MC(10.),
116   ffilltrigassoUNID(kFALSE),
117   ffilltrigUNIDassoID(kFALSE),
118   ffilltrigIDassoUNID(kTRUE),
119   ffilltrigIDassoID(kFALSE),
120   ffilltrigIDassoIDMCTRUTH(kFALSE),
121   fMaxNofMixingTracks(50000),
122   fPtOrderMCTruth(kTRUE),
123  fPtOrderDataReco(kTRUE),
124   fWeightPerEvent(kFALSE),
125   fTriggerSpeciesSelection(kFALSE),
126   fAssociatedSpeciesSelection(kFALSE),
127  fRandomizeReactionPlane(kFALSE),
128   fTriggerSpecies(SpPion),
129   fAssociatedSpecies(SpPion),
130   fCustomBinning(""),
131   fBinningString(""),
132   fSelectHighestPtTrig(kFALSE),
133   fcontainPIDtrig(kTRUE),
134   fcontainPIDasso(kFALSE),
135   SetChargeAxis(0),
136   frejectPileUp(kFALSE),
137   fminPt(0.2),
138   fmaxPt(20.0),
139   fmineta(-0.8),
140   fmaxeta(0.8),
141   fselectprimaryTruth(kTRUE),
142   fonlyprimarydatareco(kFALSE),
143   fdcacut(kFALSE),
144   fdcacutvalue(3.0),
145   ffillhistQAReco(kFALSE),
146   ffillhistQATruth(kFALSE),
147   kTrackVariablesPair(0),
148   fminPtTrig(0),
149   fmaxPtTrig(0),
150   fminPtComboeff(2.0),
151   fmaxPtComboeff(4.0), 
152   fminPtAsso(0),
153   fmaxPtAsso(0),
154  fmincentmult(0),
155  fmaxcentmult(0), 
156  fPriHistShare(0),
157   fhistcentrality(0),
158  fhistImpactParm(0),
159  fhistImpactParmvsMult(0x0),
160  fNchNpartCorr(0x0),
161   fEventCounter(0),
162   fEtaSpectrasso(0),
163   fphiSpectraasso(0),
164   MCtruthpt(0),
165   MCtrutheta(0),
166   MCtruthphi(0),
167   MCtruthpionpt(0),
168   MCtruthpioneta(0),
169   MCtruthpionphi(0),
170   MCtruthkaonpt(0),
171   MCtruthkaoneta(0),
172   MCtruthkaonphi(0),
173   MCtruthprotonpt(0),
174   MCtruthprotoneta(0),
175   MCtruthprotonphi(0),
176   fPioncont(0),
177   fKaoncont(0),
178   fProtoncont(0),
179   fUNIDcont(0),
180   fEventno(0),
181   fEventnobaryon(0),
182   fEventnomeson(0),
183  fhistJetTrigestimate(0),
184 fTwoTrackDistancePtdip(0x0),
185 fTwoTrackDistancePtdipmix(0x0),
186   fCentralityCorrelation(0x0),
187  fHistVZEROAGainEqualizationMap(0),
188   fHistVZEROCGainEqualizationMap(0),
189  fHistVZEROChannelGainEqualizationMap(0),
190 fCentralityWeights(0),
191  fHistCentStats(0x0),
192  fHistRefmult(0x0),
193  fHistEQVZEROvsTPCmultiplicity(0x0),
194     fHistEQVZEROAvsTPCmultiplicity(0x0),
195     fHistEQVZEROCvsTPCmultiplicity(0x0),
196     fHistVZEROCvsEQVZEROCmultiplicity(0x0),
197     fHistVZEROAvsEQVZEROAmultiplicity(0x0),
198     fHistVZEROCvsVZEROAmultiplicity(0x0),
199     fHistEQVZEROCvsEQVZEROAmultiplicity(0x0),
200     fHistVZEROSignal(0x0),
201 fHistEventPlaneTruth(0x0),
202 fHistPsiMinusPhi(0x0),
203 fEventPlanePID(0x0),
204 evplaneMC(999.),
205  fgPsi2v0a(999.),
206     fgPsi2v0c(999.),
207     fgPsi2tpc(999.),
208     fgPsi3v0a(999.),
209     fgPsi3v0c(999.),
210     fgPsi3tpc(999.),
211     fgPsi2v0aMC(999.),
212     fgPsi2v0cMC(999.),
213     fgPsi2tpcMC(999.),
214     fgPsi3v0aMC(999.),
215     fgPsi3v0cMC(999.),
216     fgPsi3tpcMC(999.),
217  gReactionPlane(999.),
218   fV2(kTRUE),
219  fV3(kFALSE),
220  fIsAfter2011(kTRUE),
221   fRun(-1),
222   fNcluster(70),
223  fEPdet("V0A"),  
224  fMultV0(NULL),
225   fV0Cpol(100),
226   fV0Apol(100),
227  fHResTPCv0A2(NULL),
228 fHResTPCv0C2(NULL),
229 fHResv0Cv0A2(NULL),
230 fHResTPCv0A3(NULL),
231 fHResTPCv0C3(NULL),
232 fHResv0Cv0A3(NULL),
233  fHResMA2(NULL),
234 fHResMC2(NULL),
235 fHResAC2(NULL),
236 fHResMA3(NULL),
237 fHResMC3(NULL),
238 fHResAC3(NULL),
239 fPhiRPTPC(NULL),
240 fPhiRPTPCv3(NULL),
241 fPhiRPv0A(NULL),
242 fPhiRPv0C(NULL),
243 fPhiRPv0Av3(NULL),
244 fPhiRPv0Cv3(NULL),
245  fControlConvResoncances(0),
246   fHistoTPCdEdx(0x0),
247   fHistoTOFbeta(0x0),
248   fTPCTOFPion3d(0),
249   fTPCTOFKaon3d(0),
250   fTPCTOFProton3d(0),
251   fPionPt(0),
252   fPionEta(0),
253   fPionPhi(0),
254   fKaonPt(0),
255   fKaonEta(0),
256   fKaonPhi(0),
257   fProtonPt(0),
258   fProtonEta(0),
259   fProtonPhi(0),
260   fCorrelatonTruthPrimary(0),
261   fCorrelatonTruthPrimarymix(0),
262   fTHnCorrUNID(0),
263   fTHnCorrUNIDmix(0),
264   fTHnCorrID(0),
265   fTHnCorrIDmix(0),
266   fTHnCorrIDUNID(0),
267   fTHnCorrIDUNIDmix(0),
268   fTHnTrigcount(0),
269   fTHnTrigcountMCTruthPrim(0),
270   fPoolMgr(0x0),
271   fArrayMC(0),
272   fAnalysisType("AOD"), 
273   fefffilename(""),
274  ftwoTrackEfficiencyCutDataReco(kTRUE),
275 fTwoTrackCutMinRadius(0.8),
276 fTwoTrackCutMaxRadius(2.5),
277   twoTrackEfficiencyCutValue(0.02),
278   fPID(NULL),
279  fPIDCombined(NULL),
280  eventno(0),
281   fPtTOFPIDmin(0.5),
282   fPtTOFPIDmax(4.0),
283   fRequestTOFPID(kTRUE),
284   fPIDType(NSigmaTPCTOF),
285  fFIllPIDQAHistos(kTRUE),
286   fNSigmaPID(3),
287   fBayesCut(0.8),
288  fdiffPIDcutvalues(kFALSE),
289  fPIDCutval1(0.0),
290  fPIDCutval2(0.0),
291  fPIDCutval3(0.0),
292  fPIDCutval4(0.0),
293  fHighPtKaonNSigmaPID(-1),
294  fHighPtKaonSigma(3.5),
295   fUseExclusiveNSigma(kFALSE),
296   fRemoveTracksT0Fill(kFALSE),
297 fSelectCharge(0),
298 fTriggerSelectCharge(0),
299 fAssociatedSelectCharge(0),
300 fTriggerRestrictEta(-1),
301 fEtaOrdering(kFALSE),
302 fCutConversions(kFALSE),
303 fCutResonances(kFALSE),
304 fRejectResonanceDaughters(-1),
305   fOnlyOneEtaSide(0),
306 fInjectedSignals(kFALSE),
307   fRemoveWeakDecays(kFALSE),
308 fRemoveDuplicates(kFALSE),
309   fapplyTrigefficiency(kFALSE),
310   fapplyAssoefficiency(kFALSE),
311   ffillefficiency(kFALSE),
312   fmesoneffrequired(kFALSE),
313   fkaonprotoneffrequired(kFALSE),
314 fAnalysisUtils(0x0),
315  fDCAXYCut(0),
316  fV0TrigCorr(kFALSE),
317  fUsev0DaughterPID(kFALSE),
318   fMinPtDaughter(1.0),// v0 related cut starts here
319   fMaxPtDaughter(4.0),
320   fDCAToPrimVtx(0.1),
321   fMaxDCADaughter(1.0),
322   fMinCPA(0.998),
323   lMax(100),
324   fHistRawPtCentInvK0s(0x0),
325   fHistRawPtCentInvLambda(0x0),
326   fHistRawPtCentInvAntiLambda(0x0),
327   fHistFinalPtCentInvK0s(0x0),
328   fHistFinalPtCentInvLambda(0x0),
329   fHistFinalPtCentInvAntiLambda(0x0),
330   NCtau(3.0),
331 fCutctauK0s(2.68),
332   fCutctauLambda(7.8),
333   fCutctauAntiLambda(7.8),
334   fRapCutK0s(0.7),
335   fRapCutLambda(0.7),
336 fDaugNClsTPC(70),
337 fFracTPCcls(0) 
338
339
340  for ( Int_t i = 0; i < 16; i++) { 
341     fHistQA[i] = NULL;
342   }
343
344  for ( Int_t i = 0; i < 6; i++ ){
345     fTrackHistEfficiency[i] = NULL;
346     effcorection[i]=NULL;
347     //effmap[i]=NULL;
348   }
349  for ( Int_t i = 0; i < 2; i++ ){
350    fTwoTrackDistancePt[i]=NULL;
351    fTwoTrackDistancePtmix[i]=NULL;
352 }
353
354  for(Int_t ipart=0;ipart<NSpecies;ipart++)
355     for(Int_t ipid=0;ipid<=NSigmaPIDType;ipid++)
356       fnsigmas[ipart][ipid]=999.;
357
358  for(Int_t ipart=0;ipart<NSpecies;ipart++) {fHasDoubleCounting[ipart]=kFALSE;}
359
360   for(Int_t i = 0; i != 2; ++i)
361     for(Int_t j = 0; j != 2; ++j)
362       for(Int_t iC = 0; iC < 9; iC++){
363         fMeanQ[iC][i][j] = 0.;
364         fWidthQ[iC][i][j] = 1.;
365         fMeanQv3[iC][i][j] = 0.;
366         fWidthQv3[iC][i][j] = 1.;
367     }
368
369   }
370 //________________________________________________________________________
371 AliTwoParticlePIDCorr::AliTwoParticlePIDCorr(const char *name) // All data members should be initialised here
372   :AliAnalysisTaskSE(name),
373  fOutput(0),
374    fOutputList(0),
375    fList(0),
376  fCentralityMethod("V0A"),
377   fPPVsMultUtils(kFALSE),
378   fSampleType("pPb"),
379  fRequestEventPlane(kFALSE),
380  fRequestEventPlanemixing(kFALSE),
381   fnTracksVertex(1),  // QA tracks pointing to principal vertex (= 3 default)
382   trkVtx(0),
383   zvtx(0),
384   fFilterBit(768),
385   fTrackStatus(0),
386   fSharedClusterCut(-1),
387   fSharedTPCmapCut(-1),
388  fSharedfraction_Pair_cut(-1),
389   fVertextype(1),
390    skipParticlesAbove(0),
391   fzvtxcut(10.0),
392   fVxMax_MC(0.3),
393   fVyMax_MC(0.3),
394   fVzMax_MC(10.),
395   ffilltrigassoUNID(kFALSE),
396   ffilltrigUNIDassoID(kFALSE),
397   ffilltrigIDassoUNID(kTRUE),
398   ffilltrigIDassoID(kFALSE),
399   ffilltrigIDassoIDMCTRUTH(kFALSE),
400   fMaxNofMixingTracks(50000),
401   fPtOrderMCTruth(kTRUE),
402   fPtOrderDataReco(kTRUE),
403   fWeightPerEvent(kFALSE),
404   fTriggerSpeciesSelection(kFALSE),
405   fAssociatedSpeciesSelection(kFALSE),
406    fRandomizeReactionPlane(kFALSE),
407   fTriggerSpecies(SpPion),
408   fAssociatedSpecies(SpPion),
409   fCustomBinning(""),
410   fBinningString(""),
411   fSelectHighestPtTrig(kFALSE),
412   fcontainPIDtrig(kTRUE),
413   fcontainPIDasso(kFALSE),
414   SetChargeAxis(0),
415   frejectPileUp(kFALSE),
416   fminPt(0.2),
417   fmaxPt(20.0),
418   fmineta(-0.8),
419   fmaxeta(0.8),
420   fselectprimaryTruth(kTRUE),
421   fonlyprimarydatareco(kFALSE),
422    fdcacut(kFALSE),
423   fdcacutvalue(3.0),
424   ffillhistQAReco(kFALSE),
425   ffillhistQATruth(kFALSE),
426  kTrackVariablesPair(0),
427   fminPtTrig(0),
428   fmaxPtTrig(0),
429   fminPtComboeff(2.0),
430   fmaxPtComboeff(4.0), 
431   fminPtAsso(0),
432   fmaxPtAsso(0),
433    fmincentmult(0),
434    fmaxcentmult(0),
435    fPriHistShare(0),
436   fhistcentrality(0),
437    fhistImpactParm(0),
438    fhistImpactParmvsMult(0x0),
439    fNchNpartCorr(0x0),
440   fEventCounter(0),
441   fEtaSpectrasso(0),
442   fphiSpectraasso(0),
443   MCtruthpt(0),
444   MCtrutheta(0),
445   MCtruthphi(0),
446   MCtruthpionpt(0),
447   MCtruthpioneta(0),
448   MCtruthpionphi(0),
449   MCtruthkaonpt(0),
450   MCtruthkaoneta(0),
451   MCtruthkaonphi(0),
452   MCtruthprotonpt(0),
453   MCtruthprotoneta(0),
454   MCtruthprotonphi(0),
455   fPioncont(0),
456   fKaoncont(0),
457   fProtoncont(0),
458    fUNIDcont(0),
459   fEventno(0),
460   fEventnobaryon(0),
461   fEventnomeson(0),
462   fhistJetTrigestimate(0),
463 fTwoTrackDistancePtdip(0x0),
464 fTwoTrackDistancePtdipmix(0x0),
465   fCentralityCorrelation(0x0),
466  fHistVZEROAGainEqualizationMap(0),
467   fHistVZEROCGainEqualizationMap(0),
468    fHistVZEROChannelGainEqualizationMap(0),
469 fCentralityWeights(0),
470   fHistCentStats(0x0),
471   fHistRefmult(0x0),
472     fHistEQVZEROvsTPCmultiplicity(0x0),
473     fHistEQVZEROAvsTPCmultiplicity(0x0),
474     fHistEQVZEROCvsTPCmultiplicity(0x0),
475     fHistVZEROCvsEQVZEROCmultiplicity(0x0),
476     fHistVZEROAvsEQVZEROAmultiplicity(0x0),
477     fHistVZEROCvsVZEROAmultiplicity(0x0),
478     fHistEQVZEROCvsEQVZEROAmultiplicity(0x0),
479     fHistVZEROSignal(0x0),
480 fHistEventPlaneTruth(0x0),
481    fHistPsiMinusPhi(0x0),
482 fEventPlanePID(0x0),
483 evplaneMC(999.),
484  fgPsi2v0a(999.),
485     fgPsi2v0c(999.),
486     fgPsi2tpc(999.),
487     fgPsi3v0a(999.),
488     fgPsi3v0c(999.),
489     fgPsi3tpc(999.),
490     fgPsi2v0aMC(999.),
491     fgPsi2v0cMC(999.),
492     fgPsi2tpcMC(999.),
493     fgPsi3v0aMC(999.),
494     fgPsi3v0cMC(999.),
495     fgPsi3tpcMC(999.),
496    gReactionPlane(999.),
497  fV2(kTRUE),
498  fV3(kFALSE),
499  fIsAfter2011(kTRUE),
500   fRun(-1),
501   fNcluster(70),
502    fEPdet("V0A"),  
503  fMultV0(NULL),
504   fV0Cpol(100),
505   fV0Apol(100),
506  fHResTPCv0A2(NULL),
507 fHResTPCv0C2(NULL),
508 fHResv0Cv0A2(NULL),
509 fHResTPCv0A3(NULL),
510 fHResTPCv0C3(NULL),
511 fHResv0Cv0A3(NULL),
512  fHResMA2(NULL),
513 fHResMC2(NULL),
514 fHResAC2(NULL),
515 fHResMA3(NULL),
516 fHResMC3(NULL),
517 fHResAC3(NULL),
518 fPhiRPTPC(NULL),
519 fPhiRPTPCv3(NULL),
520 fPhiRPv0A(NULL),
521 fPhiRPv0C(NULL),
522 fPhiRPv0Av3(NULL),
523 fPhiRPv0Cv3(NULL),
524   fControlConvResoncances(0), 
525   fHistoTPCdEdx(0x0),
526   fHistoTOFbeta(0x0),
527   fTPCTOFPion3d(0),
528   fTPCTOFKaon3d(0),
529   fTPCTOFProton3d(0),
530   fPionPt(0),
531   fPionEta(0),
532   fPionPhi(0),
533   fKaonPt(0),
534   fKaonEta(0),
535   fKaonPhi(0),
536   fProtonPt(0),
537   fProtonEta(0),
538   fProtonPhi(0),
539   fCorrelatonTruthPrimary(0),
540  fCorrelatonTruthPrimarymix(0),
541   fTHnCorrUNID(0),
542   fTHnCorrUNIDmix(0),
543   fTHnCorrID(0),
544   fTHnCorrIDmix(0),
545   fTHnCorrIDUNID(0),
546   fTHnCorrIDUNIDmix(0),
547   fTHnTrigcount(0),
548   fTHnTrigcountMCTruthPrim(0),
549   fPoolMgr(0x0),
550   fArrayMC(0),
551   fAnalysisType("AOD"),
552   fefffilename(""),
553   ftwoTrackEfficiencyCutDataReco(kTRUE),
554 fTwoTrackCutMinRadius(0.8),
555 fTwoTrackCutMaxRadius(2.5),
556   twoTrackEfficiencyCutValue(0.02),
557   fPID(NULL),
558   fPIDCombined(NULL),
559   eventno(0),
560  fPtTOFPIDmin(0.5),
561   fPtTOFPIDmax(4.0),
562   fRequestTOFPID(kTRUE),
563   fPIDType(NSigmaTPCTOF),
564   fFIllPIDQAHistos(kTRUE),
565   fNSigmaPID(3),
566   fBayesCut(0.8),
567  fdiffPIDcutvalues(kFALSE),
568  fPIDCutval1(0.0),
569  fPIDCutval2(0.0),
570  fPIDCutval3(0.0),
571  fPIDCutval4(0.0),
572 fHighPtKaonNSigmaPID(-1),
573  fHighPtKaonSigma(3.5),
574   fUseExclusiveNSigma(kFALSE),
575   fRemoveTracksT0Fill(kFALSE),
576 fSelectCharge(0),
577 fTriggerSelectCharge(0),
578 fAssociatedSelectCharge(0),
579 fTriggerRestrictEta(-1),
580 fEtaOrdering(kFALSE),
581 fCutConversions(kFALSE),
582 fCutResonances(kFALSE),
583 fRejectResonanceDaughters(-1),
584   fOnlyOneEtaSide(0),
585 fInjectedSignals(kFALSE),
586   fRemoveWeakDecays(kFALSE),
587 fRemoveDuplicates(kFALSE),
588   fapplyTrigefficiency(kFALSE),
589   fapplyAssoefficiency(kFALSE),
590   ffillefficiency(kFALSE),
591  fmesoneffrequired(kFALSE),
592  fkaonprotoneffrequired(kFALSE),
593    fAnalysisUtils(0x0),
594    fDCAXYCut(0),
595  fV0TrigCorr(kFALSE),
596  fUsev0DaughterPID(kFALSE),
597   fMinPtDaughter(1.0),// v0 related cut starts here
598   fMaxPtDaughter(4.0),
599   fDCAToPrimVtx(0.1),
600   fMaxDCADaughter(1.0),
601   fMinCPA(0.998),
602   lMax(100),
603   fHistRawPtCentInvK0s(0x0),
604   fHistRawPtCentInvLambda(0x0),
605   fHistRawPtCentInvAntiLambda(0x0),
606   fHistFinalPtCentInvK0s(0x0),
607   fHistFinalPtCentInvLambda(0x0),
608   fHistFinalPtCentInvAntiLambda(0x0),
609   NCtau(3.0),
610 fCutctauK0s(2.68),
611   fCutctauLambda(7.8),
612   fCutctauAntiLambda(7.8),
613   fRapCutK0s(0.7),
614   fRapCutLambda(0.7),
615 fDaugNClsTPC(70),
616 fFracTPCcls(0)    
617     
618   // The last in the above list should not have a comma after it
619      
620 {
621   
622    for ( Int_t i = 0; i < 16; i++) { 
623     fHistQA[i] = NULL;
624   }
625  
626 for ( Int_t i = 0; i < 6; i++ ){
627     fTrackHistEfficiency[i] = NULL;
628     effcorection[i]=NULL;
629     //effmap[i]=NULL;
630   }
631
632 for ( Int_t i = 0; i < 2; i++ ){
633    fTwoTrackDistancePt[i]=NULL;
634    fTwoTrackDistancePtmix[i]=NULL;
635 }
636
637  for(Int_t ipart=0;ipart<NSpecies;ipart++)
638     for(Int_t ipid=0;ipid<=NSigmaPIDType;ipid++)
639       fnsigmas[ipart][ipid]=999.;
640
641    for(Int_t ipart=0;ipart<NSpecies;ipart++) {fHasDoubleCounting[ipart]=kFALSE;}
642
643   for(Int_t i = 0; i != 2; ++i)
644     for(Int_t j = 0; j != 2; ++j)
645       for(Int_t iC = 0; iC < 9; iC++){
646         fMeanQ[iC][i][j] = 0.;
647         fWidthQ[iC][i][j] = 1.;
648         fMeanQv3[iC][i][j] = 0.;
649         fWidthQv3[iC][i][j] = 1.;
650     }
651   
652   // Constructor
653   // Define input and output slots here (never in the dummy constructor)
654   // Input slot #0 works with a TChain - it is connected to the default input container
655   // Output slot #1 writes into a TH1 container
656      DefineInput(0, TChain::Class());
657
658   DefineOutput(1, TList::Class());                                        // for output list
659   DefineOutput(2, TList::Class());
660   DefineOutput(3, TList::Class());
661
662 }
663
664 //________________________________________________________________________
665 AliTwoParticlePIDCorr::~AliTwoParticlePIDCorr()
666 {
667   // Destructor. Clean-up the output list, but not the histograms that are put inside
668   // (the list is owner and will clean-up these histograms). Protect in PROOF case.
669   if (fOutput && !AliAnalysisManager::GetAnalysisManager()->IsProofMode()) {
670     delete fOutput;
671
672   }
673
674 if (fOutputList && !AliAnalysisManager::GetAnalysisManager()->IsProofMode()) {
675     delete fOutputList;
676
677   }
678
679 if(fRequestEventPlane){
680 if (fList && !AliAnalysisManager::GetAnalysisManager()->IsProofMode()) {
681     delete fList;
682  }
683  }
684
685   if (fPID) delete fPID;
686   if (fPIDCombined) delete fPIDCombined;
687
688   }
689 //________________________________________________________________________
690
691 //////////////////////////////////////////////////////////////////////////////////////////////////
692
693 TH2F* AliTwoParticlePIDCorr::GetHistogram2D(const char * name){
694   // returns histo named name
695   return (TH2F*) fOutputList->FindObject(name);
696 }
697
698 //////////////////////////////////////////////////////////////////////////////////////////////////
699
700 Float_t AliTwoParticlePIDCorr::PhiRange(Float_t DPhi)
701
702 {
703         //
704         // Puts the argument in the range [-pi/2,3 pi/2].
705         //
706         
707         if (DPhi < -TMath::Pi()/2) DPhi += 2*TMath::Pi();
708         if (DPhi > 3*TMath::Pi()/2) DPhi -= 2*TMath::Pi();      
709
710         return DPhi;
711         
712 }
713 //________________________________________________________________________
714 void AliTwoParticlePIDCorr::UserCreateOutputObjects()
715 {
716   // Create histograms
717   // Called once (on the worker node)
718
719 // global switch disabling the reference 
720   // (to avoid "Replacing existing TH1" if several wagons are created in train)
721   Bool_t oldStatus = TH1::AddDirectoryStatus();
722   TH1::AddDirectory(kFALSE);
723
724   const Int_t nPsiTOF = 10;  
725   const Int_t nCentrBin = 9;  
726
727
728   fOutput = new TList();
729   fOutput->SetOwner();  // IMPORTANT!  
730
731   fOutputList = new TList;
732   fOutputList->SetOwner();
733   fOutputList->SetName("PIDQAList");
734
735   if(fRequestEventPlane){
736   fList = new TList;
737   fList->SetOwner();
738   fList->SetName("EPQAList");
739   }
740   fEventCounter = new TH1F("fEventCounter","EventCounter", 19, 0.5,19.5);
741   fEventCounter->GetXaxis()->SetBinLabel(1,"Event Accesed");
742   fEventCounter->GetXaxis()->SetBinLabel(3,"After PileUP Cut");//only for Data
743   fEventCounter->GetXaxis()->SetBinLabel(5,"Have A Vertex");
744   fEventCounter->GetXaxis()->SetBinLabel(7,"After vertex Cut");
745   fEventCounter->GetXaxis()->SetBinLabel(9,"Getting centrality");
746   fEventCounter->GetXaxis()->SetBinLabel(11,"After centrality flattening");
747   fEventCounter->GetXaxis()->SetBinLabel(13,"Within 0-100% centrality");
748   fEventCounter->GetXaxis()->SetBinLabel(15,"Event Analyzed");
749   //fEventCounter->GetXaxis()->SetBinLabel(8,"Event Analysis finished");
750   fOutput->Add(fEventCounter);
751   
752 fEtaSpectrasso=new TH2F("fEtaSpectraasso","fEtaSpectraasso",180,-0.9,0.9,100,0.,20. );
753 fOutput->Add(fEtaSpectrasso);
754
755 fphiSpectraasso=new TH2F("fphiSpectraasso","fphiSpectraasso",72,0,2*TMath::Pi(),100,0.,20.);
756 fOutput->Add(fphiSpectraasso);
757
758  if(fSampleType=="pPb" || fSampleType=="PbPb" || fPPVsMultUtils==kTRUE || fCentralityMethod == "MC_b"){ fCentralityCorrelation = new TH2D("fCentralityCorrelation", ";centrality_ImpactParam;multiplicity", 101, 0, 101, 20000, 0,40000);
759       fOutput->Add(fCentralityCorrelation);
760  }
761
762 if(fCentralityMethod=="V0M" || fCentralityMethod=="V0A" || fCentralityMethod=="V0C" || fCentralityMethod=="CL1" || fCentralityMethod=="ZNA" || fCentralityMethod=="V0AEq" || fCentralityMethod=="V0CEq" || fCentralityMethod=="V0MEq")
763   {
764  TString gCentName[8] = {"V0A","V0C","V0M","V0AEq","V0CEq","V0MEq","CL1","ZNA"};
765   fHistCentStats = new TH2F("fHistCentStats",
766                              "Centrality statistics;;Cent percentile",
767                             8,-0.5,7.5,220,-5,105);
768   for(Int_t i = 1; i <= 8; i++){
769     fHistCentStats->GetXaxis()->SetBinLabel(i,gCentName[i-1].Data());
770     //fHistCentStatsUsed->GetXaxis()->SetBinLabel(i,gCentName[i-1].Data());
771   }
772   fOutput->Add(fHistCentStats);
773   }
774
775 if(fSampleType=="pp_2_76" || fCentralityMethod.EndsWith("_MANUAL") || (fSampleType=="pp_7" && fPPVsMultUtils==kFALSE))
776   {
777 fhistcentrality=new TH1F("fhistcentrality","referencemultiplicity",30001,-0.5,30000.5);
778 fOutput->Add(fhistcentrality);
779   }
780  else{
781 fhistcentrality=new TH1F("fhistcentrality","centrality",220,-5,105);
782 fOutput->Add(fhistcentrality);
783  }
784  if(fCentralityMethod=="MC_b"){
785 fhistImpactParm=new TH1F("fhistImpactParm","Impact_Parameter",300,0,300);
786 fOutput->Add(fhistImpactParm);
787 fhistImpactParmvsMult=new TH2F("fhistImpactParmvsMult","fhistImpactParmvsMult",300,0,300,5001,-0.5,50000.5);
788 fOutput->Add(fhistImpactParmvsMult);
789  }
790
791  if(fAnalysisType =="MCAOD" || fAnalysisType =="MC"){
792 fNchNpartCorr=new TH2F("fNchNpartCorr","fNchNpartCorr",500,0.0,500.0,5001,-0.5,50000.5);
793 fOutput->Add(fNchNpartCorr);
794  }
795
796  TString gmultName[4] = {"V0A_MANUAL","V0C_MANUAL","V0M_MANUAL","TRACKS_MANUAL"};
797   fHistRefmult = new TH2F("fHistRefmult",
798                              "Reference multiplicity",
799                             4,-0.5,3.5,10000,0,20000);
800   for(Int_t i = 1; i <= 4; i++){
801     fHistRefmult->GetXaxis()->SetBinLabel(i,gmultName[i-1].Data());
802   }
803   fOutput->Add(fHistRefmult);
804
805  if(fCentralityMethod == "V0A_MANUAL" || fCentralityMethod == "V0M_MANUAL" || fCentralityMethod == "V0C_MANUAL" ){
806  //TPC vs EQVZERO multiplicity
807     fHistEQVZEROvsTPCmultiplicity = new TH2F("fHistEQVZEROvsTPCmultiplicity","EqVZERO vs TPC multiplicity",10001,-0.5,10000.5,4001,-0.5,4000.5);
808     fHistEQVZEROvsTPCmultiplicity->GetXaxis()->SetTitle("EqVZERO multiplicity (a.u.)");
809     fHistEQVZEROvsTPCmultiplicity->GetYaxis()->SetTitle("TPC multiplicity (a.u.)");
810     fOutput->Add(fHistEQVZEROvsTPCmultiplicity);
811
812
813     fHistEQVZEROAvsTPCmultiplicity = new TH2F("fHistEQVZEROAvsTPCmultiplicity","EqVZERO_A vs TPC multiplicity",10001,-0.5,10000.5,4001,-0.5,4000.5);
814     fHistEQVZEROAvsTPCmultiplicity->GetXaxis()->SetTitle("EqVZERO_A multiplicity (a.u.)");
815     fHistEQVZEROAvsTPCmultiplicity->GetYaxis()->SetTitle("TPC multiplicity (a.u.)");
816     fOutput->Add(fHistEQVZEROAvsTPCmultiplicity);
817
818
819     fHistEQVZEROCvsTPCmultiplicity = new TH2F("fHistEQVZEROCvsTPCmultiplicity","EqVZERO_C vs TPC multiplicity",10001,-0.5,10000.5,4001,-0.5,4000.5);
820     fHistEQVZEROCvsTPCmultiplicity->GetXaxis()->SetTitle("EqVZERO_C multiplicity (a.u.)");
821     fHistEQVZEROCvsTPCmultiplicity->GetYaxis()->SetTitle("TPC multiplicity (a.u.)");
822     fOutput->Add(fHistEQVZEROCvsTPCmultiplicity);
823
824  //EQVZERO vs VZERO multiplicity
825   fHistVZEROCvsEQVZEROCmultiplicity = new TH2F("fHistVZEROCvsEQVZEROCmultiplicity","EqVZERO_C vs VZERO_C multiplicity",10001,-0.5,10000.5,10001,-0.5,10000.5);
826     fHistVZEROCvsEQVZEROCmultiplicity->GetXaxis()->SetTitle("VZERO_C multiplicity (a.u.)");
827     fHistVZEROCvsEQVZEROCmultiplicity->GetYaxis()->SetTitle("EqVZERO_C multiplicity (a.u.)");
828     fOutput->Add(fHistVZEROCvsEQVZEROCmultiplicity);
829
830
831 fHistVZEROAvsEQVZEROAmultiplicity = new TH2F("fHistVZEROAvsEQVZEROAmultiplicity","EqVZERO_A vs VZERO_A multiplicity",10001,-0.5,10000.5,10001,-0.5,10000.5);
832     fHistVZEROAvsEQVZEROAmultiplicity->GetXaxis()->SetTitle("VZERO_A multiplicity (a.u.)");
833     fHistVZEROAvsEQVZEROAmultiplicity->GetYaxis()->SetTitle("EqVZERO_A multiplicity (a.u.)");
834     fOutput->Add(fHistVZEROAvsEQVZEROAmultiplicity);
835
836
837   //VZEROC vs VZEROA multiplicity
838 fHistVZEROCvsVZEROAmultiplicity = new TH2F("fHistVZEROCvsVZEROAmultiplicity","VZERO_C vs VZERO_A multiplicity",10001,-0.5,10000.5,10001,-0.5,10000.5);
839     fHistVZEROCvsVZEROAmultiplicity->GetXaxis()->SetTitle("VZERO_C multiplicity (a.u.)");
840     fHistVZEROCvsVZEROAmultiplicity->GetYaxis()->SetTitle("VZERO_A multiplicity (a.u.)");
841     fOutput->Add(fHistVZEROCvsVZEROAmultiplicity);
842
843
844
845   //EQVZEROC vs EQVZEROA multiplicity
846 fHistEQVZEROCvsEQVZEROAmultiplicity = new TH2F("fHistEQVZEROCvsEQVZEROAmultiplicity","EqVZERO_C vs EqVZERO_A multiplicity",10001,-0.5,10000.5,10001,-0.5,10000.5);
847     fHistEQVZEROCvsEQVZEROAmultiplicity->GetXaxis()->SetTitle("EqVZERO_C multiplicity (a.u.)");
848     fHistEQVZEROCvsEQVZEROAmultiplicity->GetYaxis()->SetTitle("EqVZERO_A multiplicity (a.u.)");
849     fOutput->Add(fHistEQVZEROCvsEQVZEROAmultiplicity);
850
851  fHistVZEROSignal = new TH2F("fHistVZEROSignal","VZERO signal vs VZERO channel;VZERO channel; Signal (a.u.)",64,0.5,64.5,3001,-0.5,30000.5);
852   fOutput->Add(fHistVZEROSignal);
853  }
854
855
856  if(fRequestEventPlane){
857 //Event plane
858  
859   fHistPsiMinusPhi = new TH2D("fHistPsiMinusPhi","",4,-0.5,3.5,100,0,2.*TMath::Pi());
860   fList->Add(fHistPsiMinusPhi);
861
862   fEventPlanePID = new TH3F("fEventPlanePID",";centrality;eventplane;PID",20,0.0,100.0,4,-0.5,3.5,4,-0.5,3.5);
863   fList->Add(fEventPlanePID);
864
865  }
866  
867 if(fCutConversions || fCutResonances)
868     {
869 fControlConvResoncances = new TH2F("fControlConvResoncances", ";id;delta mass", 3, -0.5, 2.5, 100, -0.1, 0.1);
870  fOutput->Add(fControlConvResoncances);
871     }
872
873 fHistoTPCdEdx = new TH2F("fHistoTPCdEdx", ";p_{T} (GeV/c);dE/dx (au.)",200,0.0,10.0,500, 0., 500.);
874 fOutputList->Add(fHistoTPCdEdx);
875 fHistoTOFbeta = new TH2F(Form("fHistoTOFbeta"), ";p_{T} (GeV/c);v/c",100, 0., fmaxPt, 500, 0.1, 1.1);
876   fOutputList->Add(fHistoTOFbeta);
877   
878    fTPCTOFPion3d=new TH3F ("fTPCTOFpion3d", "fTPCTOFpion3d",100,0., 10., 120,-60.,60.,120,-60.,60);
879    fOutputList->Add(fTPCTOFPion3d);
880   
881    fTPCTOFKaon3d=new TH3F ("fTPCTOFKaon3d", "fTPCTOFKaon3d",100,0., 10., 120,-60.,60.,120,-60.,60);
882    fOutputList->Add(fTPCTOFKaon3d);
883
884    fTPCTOFProton3d=new TH3F ("fTPCTOFProton3d", "fTPCTOFProton3d",100,0., 10., 120,-60.,60.,120,-60.,60);
885    fOutputList->Add(fTPCTOFProton3d);
886
887 if(ffillhistQAReco)
888     {
889     fPionPt = new TH1F("fPionPt","p_{T} distribution",200,0.,10.);
890  fOutputList->Add(fPionPt);
891     fPionEta= new TH1F("fPionEta","#eta distribution",360,-1.8,1.8);
892  fOutputList->Add(fPionEta);
893     fPionPhi = new TH1F("fPionPhi","#phi distribution",340,0,6.8);
894  fOutputList->Add(fPionPhi);
895   
896     fKaonPt = new TH1F("fKaonPt","p_{T} distribution",200,0.,10.);
897  fOutputList->Add(fKaonPt);
898     fKaonEta= new TH1F("fKaonEta","#eta distribution",360,-1.8,1.8);
899  fOutputList->Add(fKaonEta);
900     fKaonPhi = new TH1F("fKaonPhi","#phi distribution",340,0,6.8);
901  fOutputList->Add(fKaonPhi);
902   
903     fProtonPt = new TH1F("fProtonPt","p_{T} distribution",200,0.,10.);
904  fOutputList->Add(fProtonPt);
905     fProtonEta= new TH1F("fProtonEta","#eta distribution",360,-1.8,1.8);
906  fOutputList->Add(fProtonEta);
907     fProtonPhi= new TH1F("fProtonPhi","#phi distribution",340,0,6.8);
908  fOutputList->Add(fProtonPhi);
909     }
910
911   fHistQA[0] = new TH1F("fHistQAvx", "Histo Vx All ", 50, -5., 5.);
912   fHistQA[1] = new TH1F("fHistQAvy", "Histo Vy All", 50, -5., 5.);
913   fHistQA[2] = new TH1F("fHistQAvz", "Histo Vz All", 50, -25., 25.);  
914   fHistQA[3] = new TH1F("fHistQAvxA", "Histo Vx  After Cut ", 50, -5., 5.);
915   fHistQA[4] = new TH1F("fHistQAvyA", "Histo Vy After Cut", 50, -5., 5.);
916   fHistQA[5] = new TH1F("fHistQAvzA", "Histo Vz After Cut", 50, -25., 25.);
917   fHistQA[6] = new TH1F("fHistQADcaXyC", "Histo DCAxy after cut", 50, -5., 5.);
918   fHistQA[7] = new TH1F("fHistQADcaZC", "Histo DCAz after cut", 50, -5., 5.);   
919   fHistQA[8] = new TH1F("fHistQAPt","p_{T} distribution",200,0.,10.);
920   fHistQA[9] = new TH1F("fHistQAEta","#eta distribution",360,-1.8,1.8);
921   fHistQA[10] = new TH1F("fHistQAPhi","#phi distribution",340,0,6.8);
922   fHistQA[11] = new TH1F("fHistQANCls","Number of TPC cluster",200,0,200);
923   fHistQA[13] = new TH1F("fHistQAChi2","Chi2 per NDF",100,0,10);
924  fHistQA[12] = new TH1F("fHistQANCls1","Number of TPC cluster1",200,0,200);
925  fHistQA[14] = new TH1F("nCrossedRowsTPC","Number of TPC ccrossed rows",200,0,200);
926  fHistQA[15] = new TH1F("ratioCrossedRowsOverFindableClustersTPC","Number of TPC ccrossed rows find clusters",200,0,2);
927     
928 for(Int_t i = 0; i < 16; i++)
929     {
930       fOutput->Add(fHistQA[i]);
931     }
932
933     fPriHistShare = new TH1F ("fPriHistShare","Shared clusters, primaries;#shared clusters;counts",160,0,160);
934     fOutput->Add(fPriHistShare);
935
936    Int_t eventplaneaxis=0;
937
938    if (fRequestEventPlane) eventplaneaxis=1;
939
940    kTrackVariablesPair=6+SetChargeAxis+eventplaneaxis;
941
942    if(fcontainPIDtrig && !fcontainPIDasso) kTrackVariablesPair=7+SetChargeAxis+eventplaneaxis;
943  
944  if(!fcontainPIDtrig && fcontainPIDasso) kTrackVariablesPair=7+SetChargeAxis+eventplaneaxis;
945  
946  if(fcontainPIDtrig && fcontainPIDasso) kTrackVariablesPair=8+SetChargeAxis+eventplaneaxis;
947  
948  
949 // two particle histograms
950   Int_t anaSteps   = 1;       // analysis steps
951   const char* title = "d^{2}N_{ch}/d#varphid#eta";
952
953   Int_t iBinPair[kTrackVariablesPair];         // binning for track variables
954   Double_t* dBinsPair[kTrackVariablesPair];    // bins for track variables  
955   TString* axisTitlePair;  // axis titles for track variables
956   axisTitlePair=new TString[kTrackVariablesPair];
957
958  TString defaultBinningStr;
959   defaultBinningStr =   "eta: -1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0\n"
960     "p_t_assoc: 0.5, 0.75, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 8.0,10.0\n"
961     "p_t_leading_course: 0.5, 1.0, 2.0, 3.0, 4.0, 6.0, 8.0,10.0\n"
962     "p_t_eff:0.0,0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.25, 3.5, 3.75, 4.0, 4.5, 5.0,5.5, 6.0, 7.0, 8.0,9.0,10.0\n"
963     "vertex: -10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10\n"
964   "delta_phi: -1.570796, -1.483530, -1.396263, -1.308997, -1.221730, -1.134464, -1.047198, -0.959931, -0.872665, -0.785398, -0.698132, -0.610865, -0.523599, -0.436332, -0.349066, -0.261799, -0.174533, -0.087266, 0.0, 0.087266, 0.174533, 0.261799, 0.349066, 0.436332, 0.523599, 0.610865, 0.698132, 0.785398, 0.872665, 0.959931, 1.047198, 1.134464, 1.221730, 1.308997, 1.396263, 1.483530, 1.570796, 1.658063, 1.745329, 1.832596, 1.919862, 2.007129, 2.094395, 2.181662, 2.268928, 2.356194, 2.443461, 2.530727, 2.617994, 2.705260, 2.792527, 2.879793, 2.967060, 3.054326, 3.141593, 3.228859, 3.316126, 3.403392, 3.490659, 3.577925, 3.665191, 3.752458, 3.839724, 3.926991, 4.014257, 4.101524, 4.188790, 4.276057, 4.363323, 4.450590, 4.537856, 4.625123, 4.712389\n" // this binning starts at -pi/2 and is modulo 3 
965         "delta_eta: -2.4, -2.3, -2.2, -2.1, -2.0, -1.9, -1.8, -1.7, -1.6, -1.5, -1.4, -1.3, -1.2, -1.1, -1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0,2.1, 2.2, 2.3, 2.4\n"
966       "multiplicity: 0, 1, 2, 3, 4, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100.1\n"
967       "multiplicity_mixing: 0., 1., 2., 3., 4., 5., 10., 20., 30., 40., 50., 60., 70., 80., 90., 100.1\n";
968
969
970   if(fV0TrigCorr){
971 defaultBinningStr += "InvariantMass:0.200,0.300,0.398,0.399,0.4,0.401,0.402,0.403,0.404,0.405,0.406,0.407,0.408,0.409,0.41,0.411,0.412,0.413,0.414,0.415,0.416,0.417,0.418,0.419,0.42,0.421,0.422,0.423,0.424,0.425,0.426,0.427,0.428,0.429,0.43,0.431,0.432,0.433,0.434,0.435,0.436,0.437,0.438,0.439,0.44,0.441,0.442,0.443,0.444,0.445,0.446,0.447,0.448,0.449,0.45,0.451,0.452,0.453,0.454,0.455,0.456,0.457,0.458,0.459,0.46,0.461,0.462,0.463,0.464,0.465,0.466,0.467,0.468,0.469,0.47,0.471,0.472,0.473,0.474,0.475,0.476,0.477,0.478,0.479,0.48,0.481,0.482,0.483,0.484,0.485,0.486,0.487,0.488,0.489,0.49,0.491,0.492,0.493,0.494,0.495,0.496,0.497,0.498,0.499,0.5,0.501,0.502,0.503,0.504,0.505,0.506,0.507,0.508,0.509,0.51,0.511,0.512,0.513,0.514,0.515,0.516,0.517,0.518,0.519,0.52,0.521,0.522,0.523,0.524,0.525,0.526,0.527,0.528,0.529,0.53,0.531,0.532,0.533,0.534,0.535,0.536,0.537,0.538,0.539,0.54,0.541,0.542,0.543,0.544,0.545,0.546,0.547,0.548,0.549,0.55,0.551,0.552,0.553,0.554,0.555,0.556,0.557,0.558,0.559,0.56,0.561,0.562,0.563,0.564,0.565,0.566,0.567,0.568,0.569,0.57,0.571,0.572,0.573,0.574,0.575,0.576,0.577,0.578,0.579,0.58,0.581,0.582,0.583,0.584,0.585,0.586,0.587,0.588,0.589,0.59,0.591,0.592,0.593,0.594,0.595,0.596,0.597,0.598,0.599,0.600,0.700,0.800,0.900,1.000,1.065,1.066,1.067,1.068,1.069,1.07,1.071,1.072,1.073,1.074,1.075,1.076,1.077,1.078,1.079,1.08,1.081,1.082,1.083,1.084,1.085,1.086,1.087,1.088,1.089,1.09,1.091,1.092,1.093,1.094,1.095,1.096,1.097,1.098,1.099,1.1,1.101,1.102,1.103,1.104,1.105,1.106,1.107,1.108,1.109,1.11,1.111,1.112,1.113,1.114,1.115,1.116,1.117,1.118,1.119,1.12,1.121,1.122,1.123,1.124,1.125,1.126,1.127,1.128,1.129,1.13,1.131,1.132,1.133,1.134,1.135,1.136,1.137,1.138,1.139,1.14,1.141,1.142,1.143,1.144,1.145,1.146,1.147,1.148,1.149,1.15,1.151,1.152,1.153,1.154,1.155,1.156,1.157,1.158,1.159,1.16,1.161,1.162,1.163,1.164,1.165\n";
972   }
973  if(fRequestEventPlane){
974    defaultBinningStr += "eventPlane: -0.5,0.5,1.5,2.5,3.5\n"; // Event Plane Bins (Psi: -0.5->0.5 (in plane), 0.5->1.5 (intermediate), 1.5->2.5 (out of plane), 2.5->3.5 (rest))
975   }
976  if(fRequestEventPlanemixing){
977 defaultBinningStr += "eventPlanemixing: 0.0*TMath::DegToRad(), 30.0*TMath::DegToRad(), 60.0*TMath::DegToRad(), 90.0*TMath::DegToRad(), 120.0*TMath::DegToRad(),150.0*TMath::DegToRad(),180.1*TMath::DegToRad()\n";
978  }
979   if(fcontainPIDtrig){
980       defaultBinningStr += "PIDTrig: -0.5,0.5,1.5,2.5,3.5,4.5,5.5,6.5,7.5,8.5,9.5,10.5\n"; // course
981   }
982   if(fcontainPIDasso){
983       defaultBinningStr += "PIDAsso: -0.5,0.5,1.5,2.5,3.5\n"; // course
984   }
985  
986   if(SetChargeAxis==2){
987       defaultBinningStr += "TrigCharge: -2.0,0.0,2.0\n"; // course
988       defaultBinningStr += "AssoCharge: -2.0,0.0,2.0\n"; // course
989   }
990  // =========================================================
991   // Customization (adopted from AliUEHistograms)
992   // =========================================================
993
994   TObjArray* lines = defaultBinningStr.Tokenize("\n");
995   for (Int_t i=0; i<lines->GetEntriesFast(); i++)
996   {
997     TString line(lines->At(i)->GetName());
998     TString tag = line(0, line.Index(":")+1);
999     if (!fCustomBinning.BeginsWith(tag) && !fCustomBinning.Contains(TString("\n") + tag))
1000       fBinningString += line + "\n";
1001     else
1002       AliInfo(Form("Using custom binning for %s", tag.Data()));
1003   }
1004   delete lines;
1005   fBinningString += fCustomBinning;
1006   
1007   AliInfo(Form("Used AliTHn Binning:\n%s",fBinningString.Data()));
1008
1009  //  =========================================================
1010   // Now set the bins
1011   // =========================================================
1012
1013     dBinsPair[0]       = GetBinning(fBinningString, "multiplicity", iBinPair[0]);
1014     axisTitlePair[0]   = " multiplicity";
1015
1016     dBinsPair[1]     = GetBinning(fBinningString, "vertex", iBinPair[1]);
1017     axisTitlePair[1]  = "v_{Z} (cm)"; 
1018
1019     dBinsPair[2]     = GetBinning(fBinningString, "p_t_leading_course", iBinPair[2]);
1020     axisTitlePair[2]    = "p_{T,trig.} (GeV/c)"; 
1021
1022     dBinsPair[3]     = GetBinning(fBinningString, "p_t_assoc", iBinPair[3]);
1023     axisTitlePair[3]    = "p_{T,assoc.} (GeV/c)";
1024
1025     dBinsPair[4]       = GetBinning(fBinningString, "delta_eta", iBinPair[4]);
1026     axisTitlePair[4]   = "#Delta#eta"; 
1027
1028     dBinsPair[5]       = GetBinning(fBinningString, "delta_phi", iBinPair[5]);
1029     axisTitlePair[5]   = "#Delta#varphi (rad)";  
1030
1031     Int_t dim_val=6;
1032
1033     if(fRequestEventPlane){
1034     dBinsPair[dim_val]       = GetBinning(fBinningString, "eventPlane", iBinPair[dim_val]);
1035     axisTitlePair[dim_val]   = "#varphi - #Psi_{2} (a.u.)";
1036     dim_val=7;
1037     }
1038
1039     if(!fcontainPIDtrig && !fcontainPIDasso && SetChargeAxis==2){
1040     dBinsPair[dim_val]       = GetBinning(fBinningString, "TrigCharge", iBinPair[dim_val]);
1041     axisTitlePair[dim_val]   = "TrigCharge";
1042
1043     dBinsPair[dim_val+1]       = GetBinning(fBinningString, "AssoCharge", iBinPair[dim_val+1]);
1044     axisTitlePair[dim_val+1]   = "AssoCharge";
1045     }
1046
1047  if(fcontainPIDtrig && !fcontainPIDasso){
1048    if(fV0TrigCorr){
1049     dBinsPair[dim_val]       = GetBinning(fBinningString, "InvariantMass", iBinPair[dim_val]);
1050     axisTitlePair[dim_val]   = "InvariantMass"; 
1051    }
1052    else{
1053     dBinsPair[dim_val]       = GetBinning(fBinningString, "PIDTrig", iBinPair[dim_val]);
1054     axisTitlePair[dim_val]   = "PIDTrig"; 
1055    }
1056     if(SetChargeAxis==2){
1057     dBinsPair[dim_val+1]       = GetBinning(fBinningString, "TrigCharge", iBinPair[dim_val+1]);
1058     axisTitlePair[dim_val+1]   = "TrigCharge";
1059
1060     dBinsPair[dim_val+2]       = GetBinning(fBinningString, "AssoCharge", iBinPair[dim_val+2]);
1061     axisTitlePair[dim_val+2]   = "AssoCharge";
1062     }
1063  }
1064
1065  if(!fcontainPIDtrig && fcontainPIDasso){
1066     dBinsPair[dim_val]       = GetBinning(fBinningString, "PIDAsso", iBinPair[dim_val]);
1067     axisTitlePair[dim_val]   = "PIDAsso"; 
1068
1069  if(SetChargeAxis==2){
1070     dBinsPair[dim_val+1]       = GetBinning(fBinningString, "TrigCharge", iBinPair[dim_val+1]);
1071     axisTitlePair[dim_val+1]   = "TrigCharge";
1072
1073     dBinsPair[dim_val+2]       = GetBinning(fBinningString, "AssoCharge", iBinPair[dim_val+2]);
1074     axisTitlePair[dim_val+2]   = "AssoCharge";
1075     }
1076  }
1077
1078 if(fcontainPIDtrig && fcontainPIDasso){
1079
1080    if(fV0TrigCorr){
1081     dBinsPair[dim_val]       = GetBinning(fBinningString, "InvariantMass", iBinPair[dim_val]);
1082     axisTitlePair[dim_val]   = "InvariantMass"; 
1083    }
1084    else{
1085     dBinsPair[dim_val]       = GetBinning(fBinningString, "PIDTrig", iBinPair[dim_val]);
1086     axisTitlePair[dim_val]   = "PIDTrig"; 
1087    }
1088
1089     dBinsPair[dim_val+1]       = GetBinning(fBinningString, "PIDAsso", iBinPair[dim_val+1]);
1090     axisTitlePair[dim_val+1]   = "PIDAsso";
1091
1092     if(SetChargeAxis==2){
1093     dBinsPair[dim_val+2]       = GetBinning(fBinningString, "TrigCharge", iBinPair[dim_val+2]);
1094     axisTitlePair[dim_val+2]   = "TrigCharge";
1095
1096     dBinsPair[dim_val+3]       = GetBinning(fBinningString, "AssoCharge", iBinPair[dim_val+3]);
1097     axisTitlePair[dim_val+3]   = "AssoCharge";
1098     }
1099  }
1100         
1101         Int_t nEtaBin = -1;
1102         Double_t* EtaBin = GetBinning(fBinningString, "eta", nEtaBin);
1103         
1104         Int_t nPteffbin = -1;
1105         Double_t* Pteff = GetBinning(fBinningString, "p_t_eff", nPteffbin);
1106
1107         Int_t multmixbin = -1;
1108         Double_t* multmix = GetBinning(fBinningString, "multiplicity_mixing", multmixbin);
1109
1110
1111         //Set the limits from custom binning
1112         fminPtTrig=dBinsPair[2][0];
1113         fmaxPtTrig=dBinsPair[2][iBinPair[2]];
1114         fminPtAsso=dBinsPair[3][0];
1115         fmaxPtAsso=dBinsPair[3][iBinPair[3]];
1116         fmincentmult=dBinsPair[0][0];
1117         fmaxcentmult=dBinsPair[0][iBinPair[0]];
1118
1119         //event pool manager
1120 Int_t MaxNofEvents=1000;
1121 const Int_t NofVrtxBins=10+(1+10)*2;
1122 Double_t ZvrtxBins[NofVrtxBins+1]={ -10,   -8,  -6,  -4,  -2,   0,   2,   4,   6,   8,  10, 
1123                                        90,  92,  94,  96,  98, 100, 102, 104, 106, 108, 110, 
1124                                     190, 192, 194, 196, 198, 200, 202, 204, 206, 208, 210}; 
1125
1126
1127 if(fRequestEventPlanemixing){
1128     // Event plane angle (Psi) bins for event mixing
1129   
1130     Int_t nPsiBins=-1;; 
1131     Double_t* psibins = GetBinning(fBinningString, "eventPlanemixing", nPsiBins);
1132     fPoolMgr = new AliEventPoolManager(MaxNofEvents,fMaxNofMixingTracks,multmixbin,multmix,NofVrtxBins,ZvrtxBins, nPsiBins, psibins);
1133     if(psibins)  delete [] psibins; 
1134                                     }
1135
1136  else{
1137  const Int_t  nPsiBinsd=1;
1138  Double_t psibinsd[nPsiBinsd+1]={0.0, 2000.0};
1139 fPoolMgr = new AliEventPoolManager(MaxNofEvents,fMaxNofMixingTracks,multmixbin,multmix,NofVrtxBins,ZvrtxBins, nPsiBinsd, psibinsd);
1140
1141  }  
1142 fPoolMgr->SetTargetValues(fMaxNofMixingTracks, 0.1, 5);
1143  
1144    if(!fPoolMgr){
1145       AliError("Event Mixing required, but Pool Manager not initialized...");
1146       return;
1147     }
1148
1149         //fminPtComboeff=fminPtTrig;***then this value will be fixed ,even Setter can't change it's value
1150         //fmaxPtComboeff=fmaxPtTrig;
1151 //THnSparses for calculation of efficiency
1152
1153  if((fAnalysisType =="MCAOD") && ffillefficiency) {
1154 TString Histrename;
1155   Int_t effbin[4];
1156   effbin[0]=iBinPair[0];
1157   effbin[1]=iBinPair[1];
1158   effbin[2]=nPteffbin;
1159   effbin[3]=nEtaBin;
1160   Int_t effsteps=5;//for each species type::primMCParticles(0),primRecoTracksMatched(1),allRecoTracksMatched(2),primRecoTracksMatchedPID(3),allRecoTracksMatchedPID(4)
1161 for(Int_t jj=0;jj<6;jj++)//PID type binning
1162     {
1163      if(jj==5) effsteps=3;//for unidentified particles
1164   Histrename="fTrackHistEfficiency";Histrename+=jj;
1165   fTrackHistEfficiency[jj] = new AliTHn(Histrename.Data(), "Tracking efficiency", effsteps, 4, effbin);
1166   fTrackHistEfficiency[jj]->SetBinLimits(0, dBinsPair[0]);
1167   fTrackHistEfficiency[jj]->SetVarTitle(0, "Centrality");
1168   fTrackHistEfficiency[jj]->SetBinLimits(1, dBinsPair[1]);
1169   fTrackHistEfficiency[jj]->SetVarTitle(1, "zvtx");
1170   fTrackHistEfficiency[jj]->SetBinLimits(2, Pteff);
1171   fTrackHistEfficiency[jj]->SetVarTitle(2, "p_{T} (GeV/c)");
1172   fTrackHistEfficiency[jj]->SetBinLimits(3, EtaBin);
1173   fTrackHistEfficiency[jj]->SetVarTitle(3, "#eta");
1174   fOutput->Add(fTrackHistEfficiency[jj]);
1175     }
1176  }
1177
1178 //AliThns for Correlation plots(data &  MC)
1179  
1180      if(ffilltrigassoUNID)
1181        {
1182     fTHnCorrUNID = new AliTHn("fTHnCorrUNID", title, anaSteps, kTrackVariablesPair, iBinPair);
1183 for (Int_t j=0; j<kTrackVariablesPair; j++) {
1184     fTHnCorrUNID->SetBinLimits(j, dBinsPair[j]);
1185     fTHnCorrUNID->SetVarTitle(j, axisTitlePair[j]);
1186   }
1187   fOutput->Add(fTHnCorrUNID);
1188
1189  fTHnCorrUNIDmix = new AliTHn("fTHnCorrUNIDmix", title, anaSteps, kTrackVariablesPair, iBinPair);
1190 for (Int_t j=0; j<kTrackVariablesPair; j++) {
1191     fTHnCorrUNIDmix->SetBinLimits(j, dBinsPair[j]);
1192     fTHnCorrUNIDmix->SetVarTitle(j, axisTitlePair[j]);
1193   }
1194   fOutput->Add(fTHnCorrUNIDmix);
1195        }
1196
1197      if(ffilltrigIDassoID)
1198        {
1199 fTHnCorrID = new AliTHn("fTHnCorrID", title, anaSteps, kTrackVariablesPair, iBinPair);
1200 for (Int_t j=0; j<kTrackVariablesPair; j++) {
1201     fTHnCorrID->SetBinLimits(j, dBinsPair[j]);
1202     fTHnCorrID->SetVarTitle(j, axisTitlePair[j]);
1203   }
1204   fOutput->Add(fTHnCorrID);
1205
1206 fTHnCorrIDmix = new AliTHn("fTHnCorrIDmix", title, anaSteps, kTrackVariablesPair, iBinPair);
1207 for (Int_t j=0; j<kTrackVariablesPair; j++) {
1208     fTHnCorrIDmix->SetBinLimits(j, dBinsPair[j]);
1209     fTHnCorrIDmix->SetVarTitle(j, axisTitlePair[j]);
1210   }
1211   fOutput->Add(fTHnCorrIDmix);
1212        }
1213
1214      if(ffilltrigUNIDassoID || ffilltrigIDassoUNID)//***********a bit tricky, be careful
1215        {
1216 fTHnCorrIDUNID = new AliTHn("fTHnCorrIDUNID", title, anaSteps, kTrackVariablesPair, iBinPair);
1217 for (Int_t j=0; j<kTrackVariablesPair; j++) {
1218     fTHnCorrIDUNID->SetBinLimits(j, dBinsPair[j]);
1219     fTHnCorrIDUNID->SetVarTitle(j, axisTitlePair[j]);
1220   }
1221   fOutput->Add(fTHnCorrIDUNID);
1222
1223
1224 fTHnCorrIDUNIDmix = new AliTHn("fTHnCorrIDUNIDmix", title, anaSteps, kTrackVariablesPair, iBinPair);
1225 for (Int_t j=0; j<kTrackVariablesPair; j++) {
1226     fTHnCorrIDUNIDmix->SetBinLimits(j, dBinsPair[j]);
1227     fTHnCorrIDUNIDmix->SetVarTitle(j, axisTitlePair[j]);
1228   }
1229   fOutput->Add(fTHnCorrIDUNIDmix);
1230        }
1231
1232
1233
1234   //ThnSparse for Correlation plots(truth MC)
1235      if(ffilltrigIDassoIDMCTRUTH) {//remember that in this case uidentified means other than pions, kaons, protons
1236
1237 fCorrelatonTruthPrimary = new AliTHn("fCorrelatonTruthPrimary", title, anaSteps, kTrackVariablesPair, iBinPair);
1238 for (Int_t j=0; j<kTrackVariablesPair; j++) {
1239     fCorrelatonTruthPrimary->SetBinLimits(j, dBinsPair[j]);
1240     fCorrelatonTruthPrimary->SetVarTitle(j, axisTitlePair[j]);
1241   }
1242   fOutput->Add(fCorrelatonTruthPrimary);
1243
1244
1245 fCorrelatonTruthPrimarymix = new AliTHn("fCorrelatonTruthPrimarymix", title, anaSteps, kTrackVariablesPair, iBinPair);
1246 for (Int_t j=0; j<kTrackVariablesPair; j++) {
1247     fCorrelatonTruthPrimarymix->SetBinLimits(j, dBinsPair[j]);
1248     fCorrelatonTruthPrimarymix->SetVarTitle(j, axisTitlePair[j]);
1249   }
1250   fOutput->Add(fCorrelatonTruthPrimarymix);     
1251  }
1252
1253     //binning for trigger no. counting
1254
1255      Int_t ChargeAxis=0;
1256      if(SetChargeAxis==2) ChargeAxis=1;
1257
1258         Int_t* fBinst;
1259         Int_t dims=3+ChargeAxis+eventplaneaxis;
1260         if(fcontainPIDtrig) dims=4+ChargeAxis+eventplaneaxis;
1261         fBinst= new Int_t[dims];
1262    Double_t* dBinsTrig[dims];    // bins for track variables  
1263    TString* axisTitleTrig;  // axis titles for track variables
1264    axisTitleTrig=new TString[dims];
1265
1266         for(Int_t i=0; i<3;i++)
1267           {
1268             fBinst[i]=iBinPair[i];
1269             dBinsTrig[i]=dBinsPair[i];
1270             axisTitleTrig[i]=axisTitlePair[i];
1271           }
1272         Int_t dim_val_trig=3;
1273     if(fRequestEventPlane){
1274       fBinst[dim_val_trig]=iBinPair[6];//if fRequestEventPlane=TRUE, dim_val already becomes 7.
1275       dBinsTrig[dim_val_trig]=dBinsPair[6];
1276       axisTitleTrig[dim_val_trig]=axisTitlePair[6];
1277       dim_val_trig=4;
1278     }
1279
1280 if(!fcontainPIDtrig && !fcontainPIDasso && ChargeAxis==1){
1281 fBinst[dim_val_trig]=iBinPair[dim_val];
1282 dBinsTrig[dim_val_trig]=dBinsPair[dim_val];
1283 axisTitleTrig[dim_val_trig]=axisTitlePair[dim_val];
1284     }
1285
1286 if(fcontainPIDtrig && !fcontainPIDasso){
1287 fBinst[dim_val_trig]=iBinPair[dim_val];
1288 dBinsTrig[dim_val_trig]=dBinsPair[dim_val];
1289 axisTitleTrig[dim_val_trig]=axisTitlePair[dim_val]; 
1290     if(ChargeAxis==1){
1291 fBinst[dim_val_trig+1]=iBinPair[dim_val+1];
1292 dBinsTrig[dim_val_trig+1]=dBinsPair[dim_val+1];
1293 axisTitleTrig[dim_val_trig+1]=axisTitlePair[dim_val+1];
1294     }
1295  }
1296
1297  if(!fcontainPIDtrig && fcontainPIDasso){
1298  if(ChargeAxis==1){
1299     fBinst[dim_val_trig]=iBinPair[dim_val+1];
1300 dBinsTrig[dim_val_trig]=dBinsPair[dim_val+1];
1301 axisTitleTrig[dim_val_trig]=axisTitlePair[dim_val+1];
1302     }
1303  }
1304
1305 if(fcontainPIDtrig && fcontainPIDasso){
1306   fBinst[dim_val_trig]=iBinPair[dim_val];
1307 dBinsTrig[dim_val_trig]=dBinsPair[dim_val];
1308 axisTitleTrig[dim_val_trig]=axisTitlePair[dim_val]; 
1309     if(ChargeAxis==1){
1310 fBinst[dim_val_trig+1]=iBinPair[dim_val+2];
1311 dBinsTrig[dim_val_trig+1]=dBinsPair[dim_val+2];
1312 axisTitleTrig[dim_val_trig+1]=axisTitlePair[dim_val+2];
1313     }
1314     }
1315  
1316   //ThSparse for trigger counting(data & reco MC)
1317   if(ffilltrigassoUNID || ffilltrigUNIDassoID || ffilltrigIDassoUNID || ffilltrigIDassoID)
1318           {
1319             fTHnTrigcount = new  AliTHn("fTHnTrigcount", "fTHnTrigcount", 2, dims, fBinst); //2 steps;;;;0->same event;;;;;1->mixed event
1320    for(Int_t i=0; i<dims;i++){
1321     fTHnTrigcount->SetBinLimits(i, dBinsTrig[i]);
1322     fTHnTrigcount->SetVarTitle(i, axisTitleTrig[i]);
1323   } 
1324   fOutput->Add(fTHnTrigcount);
1325           }
1326   
1327   if(ffilltrigIDassoIDMCTRUTH) {
1328   //AliTHns for trigger counting(truth MC)
1329   fTHnTrigcountMCTruthPrim = new  AliTHn("fTHnTrigcountMCTruthPrim", "fTHnTrigcountMCTruthPrim", 2, dims, fBinst); //2 steps;;;;0->same event;;;;;1->mixed event
1330  for(Int_t i=0; i<dims;i++){
1331     fTHnTrigcountMCTruthPrim->SetBinLimits(i, dBinsTrig[i]);
1332     fTHnTrigcountMCTruthPrim->SetVarTitle(i, axisTitleTrig[i]);
1333   } 
1334   fOutput->Add(fTHnTrigcountMCTruthPrim);
1335  }
1336
1337 if(fAnalysisType=="MCAOD" || fAnalysisType=="MC"){
1338   if(ffillhistQATruth)
1339     {
1340   MCtruthpt=new TH1F ("MCtruthpt","ptdistributiontruthprim",100,0.,10.);
1341   fOutputList->Add(MCtruthpt);
1342
1343   MCtrutheta=new TH1F ("MCtrutheta","etadistributiontruthprim",360,-1.8,1.8);
1344   fOutputList->Add(MCtrutheta);
1345
1346   MCtruthphi=new TH1F ("MCtruthphi","phidisttruthprim",340,0,6.8);
1347   fOutputList->Add(MCtruthphi);
1348
1349   MCtruthpionpt=new TH1F ("MCtruthpionpt","MCtruthpionpt",100,0.,10.);
1350   fOutputList->Add(MCtruthpionpt);
1351
1352   MCtruthpioneta=new TH1F ("MCtruthpioneta","MCtruthpioneta",360,-1.8,1.8);
1353   fOutputList->Add(MCtruthpioneta);
1354
1355   MCtruthpionphi=new TH1F ("MCtruthpionphi","MCtruthpionphi",340,0,6.8);
1356   fOutputList->Add(MCtruthpionphi);
1357
1358   MCtruthkaonpt=new TH1F ("MCtruthkaonpt","MCtruthkaonpt",100,0.,10.);
1359   fOutputList->Add(MCtruthkaonpt);
1360
1361   MCtruthkaoneta=new TH1F ("MCtruthkaoneta","MCtruthkaoneta",360,-1.8,1.8);
1362   fOutputList->Add(MCtruthkaoneta);
1363
1364   MCtruthkaonphi=new TH1F ("MCtruthkaonphi","MCtruthkaonphi",340,0,6.8);
1365   fOutputList->Add(MCtruthkaonphi);
1366
1367   MCtruthprotonpt=new TH1F ("MCtruthprotonpt","MCtruthprotonpt",100,0.,10.);
1368   fOutputList->Add(MCtruthprotonpt);
1369
1370   MCtruthprotoneta=new TH1F ("MCtruthprotoneta","MCtruthprotoneta",360,-1.8,1.8);
1371   fOutputList->Add(MCtruthprotoneta);
1372
1373   MCtruthprotonphi=new TH1F ("MCtruthprotonphi","MCtruthprotonphi",340,0,6.8);
1374   fOutputList->Add(MCtruthprotonphi);
1375     }
1376  fPioncont=new TH2F("fPioncont", "fPioncont",10,-0.5,9.5,100,0.,10.);
1377   fOutputList->Add(fPioncont);
1378
1379  fKaoncont=new TH2F("fKaoncont","fKaoncont",10,-0.5,9.5,100,0.,10.);
1380   fOutputList->Add(fKaoncont);
1381
1382  fProtoncont=new TH2F("fProtoncont","fProtoncont",10,-0.5,9.5,100,0.,10.);
1383   fOutputList->Add(fProtoncont);
1384
1385 fUNIDcont=new TH2F("fUNIDcont","fUNIDcont",10,-0.5,9.5,100,0.,10.);
1386   fOutputList->Add(fUNIDcont);
1387   }
1388
1389 fEventno=new TH2F("fEventno","fEventno",iBinPair[0], dBinsPair[0],iBinPair[1],dBinsPair[1]);
1390  fEventno->GetXaxis()->SetTitle("Centrality");
1391  fEventno->GetYaxis()->SetTitle("Z_Vtx");
1392 fOutput->Add(fEventno);
1393 fEventnobaryon=new TH2F("fEventnobaryon","fEventnobaryon",iBinPair[0], dBinsPair[0],iBinPair[1],dBinsPair[1]);
1394  fEventnobaryon->GetXaxis()->SetTitle("Centrality");
1395  fEventnobaryon->GetYaxis()->SetTitle("Z_Vtx");
1396 fOutput->Add(fEventnobaryon);
1397 fEventnomeson=new TH2F("fEventnomeson","fEventnomeson",iBinPair[0], dBinsPair[0],iBinPair[1],dBinsPair[1]);
1398  fEventnomeson->GetXaxis()->SetTitle("Centrality");
1399  fEventnomeson->GetYaxis()->SetTitle("Z_Vtx");
1400 fOutput->Add(fEventnomeson);
1401
1402 fhistJetTrigestimate=new TH2F("fhistJetTrigestimate","fhistJetTrigestimate",iBinPair[0],dBinsPair[0],6,-0.5,5.5);
1403 fOutput->Add(fhistJetTrigestimate);
1404
1405    fTwoTrackDistancePtdip = new TH3F("fTwoTrackDistancePtdip", ";#Delta#eta;#Delta#varphi;#Delta p_{T}", 36, -1.8, 1.8, 72,-TMath::Pi()/2, 3*TMath::Pi()/2, 40, 0, 10);
1406   fOutput->Add(fTwoTrackDistancePtdip);
1407
1408 fTwoTrackDistancePtdipmix = new TH3F("fTwoTrackDistancePtdipmix", ";#Delta#eta;#Delta#varphi;#Delta p_{T}", 36, -1.8, 1.8, 72,-TMath::Pi()/2, 3*TMath::Pi()/2, 40, 0, 10);
1409   fOutput->Add(fTwoTrackDistancePtdipmix);
1410
1411   TString Histttrname;
1412 for(Int_t jj=0;jj<2;jj++)// PID type binning
1413     {
1414   Histttrname="fTwoTrackDistancePt";Histttrname+=jj;
1415   fTwoTrackDistancePt[jj] = new TH3F(Histttrname.Data(), ";#Delta#eta;#Delta#varphi^{*}_{min};#Delta p_{T}", 100, -0.15, 0.15, 100, -0.05, 0.05, 20, 0, 10);
1416   fOutput->Add(fTwoTrackDistancePt[jj]);
1417
1418  Histttrname="fTwoTrackDistancePtmix";Histttrname+=jj;
1419   fTwoTrackDistancePtmix[jj] = new TH3F(Histttrname.Data(), ";#Delta#eta;#Delta#varphi^{*}_{min};#Delta p_{T}", 100, -0.15, 0.15, 100, -0.05, 0.05, 20, 0, 10);
1420   fOutput->Add(fTwoTrackDistancePtmix[jj]);
1421     }
1422 //Mixing
1423 //DefineEventPool();
1424
1425   if(fapplyTrigefficiency || fapplyAssoefficiency)
1426    {
1427      const Int_t nDimt = 4;//       cent zvtx  pt   eta
1428      Int_t fBinsCht[nDimt] = {iBinPair[0], iBinPair[1], nPteffbin ,nEtaBin};//*************change it
1429      Double_t fMinCht[nDimt] = { dBinsPair[0][0],dBinsPair[1][0], Pteff[0], EtaBin[0] };
1430      Double_t fMaxCht[nDimt] = {dBinsPair[0][iBinPair[0]], dBinsPair[1][iBinPair[1]], Pteff[nPteffbin], EtaBin[nEtaBin]};
1431
1432   TString Histrexname;
1433 for(Int_t jj=0;jj<6;jj++)// PID type binning
1434     {
1435   Histrexname="effcorection";Histrexname+=jj;
1436   effcorection[jj] = new THnSparseF(Histrexname.Data(),"cent:zvtx::Pt:eta", nDimt, fBinsCht, fMinCht, fMaxCht);
1437   effcorection[jj]->Sumw2(); 
1438   effcorection[jj]->GetAxis(0)->Set(iBinPair[0], dBinsPair[0]);
1439   effcorection[jj]->GetAxis(0)->SetTitle("Centrality");
1440   effcorection[jj]->GetAxis(1)->Set( iBinPair[1],dBinsPair[1]);
1441   effcorection[jj]->GetAxis(1)->SetTitle("zvtx"); 
1442   effcorection[jj]->GetAxis(2)->Set(nPteffbin, Pteff);  
1443   effcorection[jj]->GetAxis(2)->SetTitle("p_{T} (GeV/c)");
1444   effcorection[jj]->GetAxis(3)->Set( nEtaBin,EtaBin);
1445   effcorection[jj]->GetAxis(3)->SetTitle("#eta");
1446   fOutput->Add(effcorection[jj]);
1447     }
1448 // TFile *fsifile = new TFile(fefffilename,"READ");
1449
1450  if (TString(fefffilename).BeginsWith("alien:"))
1451     TGrid::Connect("alien:");
1452  TFile *fileT=TFile::Open(fefffilename);
1453  TString Nameg;
1454 for(Int_t jj=0;jj<6;jj++)//type binning
1455     {
1456 Nameg="effmap";Nameg+=jj;
1457 //effcorection[jj] = (THnSparseF*)fsifile->Get(Nameg.Data());
1458 effcorection[jj] = (THnSparseF*)fileT->Get(Nameg.Data());
1459
1460 //effcorection[jj]->SetDirectory(0);//****************************not present in case oh THnF
1461     }
1462 //fsifile->Close();
1463 fileT->Close();
1464
1465    }
1466
1467  delete [] EtaBin; 
1468  delete [] Pteff; 
1469  delete [] multmix; 
1470
1471  //******************************************************************V0 plots*********************************************//
1472  if(fV0TrigCorr){
1473         //histos for v0
1474         //Double_t BinsV0[]={1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.2,2.4,2.6,2.8,3.0,3.2,3.4,3.6,3.8,4.0,4.5,5.0,5.5,6.5,8.0};
1475         //const Int_t nbinsV0 =sizeof(BinsV0)/sizeof(Double_t)-1;
1476
1477  
1478
1479    fHistRawPtCentInvK0s= new TH3F("fHistRawPtCentInvK0s", "K^{0}_{s}: mass vs #it{p}_{T};Mass (GeV/#it{c}^2);#it{p}_{T} (GeV/#it{c});centrality",100,0.398,0.598,100,0.0,10.0,100,0.0,100.);
1480 fOutput->Add(fHistRawPtCentInvK0s);
1481
1482
1483  fHistRawPtCentInvLambda= new TH3F("fHistRawPtCentInvLambda", "#Lambda: mass vs #it{p}_{T};Mass (GeV/#it{c}^2);#it{p}_{T} (GeV/#it{c});centrality",100,1.065,1.165,100,0.0,10.0,100,0.0,100.);
1484 fOutput->Add(fHistRawPtCentInvLambda);
1485
1486
1487  fHistRawPtCentInvAntiLambda= new TH3F("fHistRawPtCentInvAntiLambda", "#bar{#Lambda} : mass vs #it{p}_{T};Mass (GeV/#it{c}^2);#it{p}_{T} (GeV/#it{c});centrality",100,1.065,1.165,100,0.0,10.0,100,0.0,100.);
1488 fOutput->Add(fHistRawPtCentInvAntiLambda);
1489
1490
1491  fHistFinalPtCentInvK0s= new TH3F("fHistFinalPtCentInvK0s", "K^{0}_{s}: mass vs #it{p}_{T};Mass (GeV/#it{c}^2);#it{p}_{T} (GeV/#it{c});centrality",100,0.398,0.598,100,0.0,10.0,100,0.0,100.);
1492 fOutput->Add(fHistFinalPtCentInvK0s);
1493
1494
1495  fHistFinalPtCentInvLambda= new TH3F("fHistFinalPtCentInvLambda", "#Lambda: mass vs #it{p}_{T};Mass (GeV/#it{c}^2);#it{p}_{T} (GeV/#it{c});centrality",100,1.065,1.165,100,0.0,10.0,100,0.0,100.);
1496 fOutput->Add(fHistFinalPtCentInvLambda);
1497
1498
1499  fHistFinalPtCentInvAntiLambda= new TH3F("fHistFinalPtCentInvAntiLambda", "#bar{#Lambda} : mass vs #it{p}_{T};Mass (GeV/#it{c}^2);#it{p}_{T} (GeV/#it{c});centrality",100,1.065,1.165,100,0.0,10.0,100,0.0,100.);
1500 fOutput->Add(fHistFinalPtCentInvAntiLambda);
1501
1502  }
1503
1504   //*************************************************************EP plots***********************************************//
1505   if(fRequestEventPlane){
1506   // TProfile for resolutions 3 subevents (V0A, V0C, TPC)
1507   // v2
1508   fHResTPCv0A2 = new TProfile("hResTPCv0A2","",nCentrBin,0,nCentrBin);
1509   fHResTPCv0C2 = new TProfile("hResTPCv0C2","",nCentrBin,0,nCentrBin);
1510   fHResv0Cv0A2 = new TProfile("hResv0Cv0A2","",nCentrBin,0,nCentrBin);
1511
1512   fList->Add(fHResTPCv0A2);
1513   fList->Add(fHResTPCv0C2);
1514   fList->Add(fHResv0Cv0A2);
1515
1516   // v3
1517   fHResTPCv0A3 = new TProfile("hResTPCv0A3","",nCentrBin,0,nCentrBin);
1518   fHResTPCv0C3 = new TProfile("hResTPCv0C3","",nCentrBin,0,nCentrBin);
1519   fHResv0Cv0A3 = new TProfile("hResv0Cv0A3","",nCentrBin,0,nCentrBin);
1520
1521   fList->Add(fHResTPCv0A3);
1522   fList->Add(fHResTPCv0C3);
1523   fList->Add(fHResv0Cv0A3);
1524
1525   // MC as in the dataEP resolution (but using MC tracks)
1526   if(fAnalysisType == "MCAOD"  && fV2){
1527     fHResMA2 = new TProfile("hResMA2","",nCentrBin,0,nCentrBin);
1528     fHResMC2 = new TProfile("hResMC2","",nCentrBin,0,nCentrBin);
1529     fHResAC2 = new TProfile("hResAC2","",nCentrBin,0,nCentrBin);
1530     fList->Add(fHResMA2); 
1531     fList->Add(fHResMC2); 
1532     fList->Add(fHResAC2); 
1533   }
1534   if(fAnalysisType == "MCAOD" && fV3){
1535     fHResMA3 = new TProfile("hResMA3","",nCentrBin,0,nCentrBin);
1536     fHResMC3 = new TProfile("hResMC3","",nCentrBin,0,nCentrBin);
1537     fHResAC3 = new TProfile("hResAC3","",nCentrBin,0,nCentrBin);
1538     fList->Add(fHResMA3); 
1539     fList->Add(fHResMC3); 
1540     fList->Add(fHResAC3); 
1541   }
1542
1543
1544   // V0A and V0C event plane distributions
1545   //v2 
1546   fPhiRPTPC = new TH2F("fPhiRPTPCv2","#phi distribution of EP TPC;centrality;#phi (rad)",nCentrBin,0,nCentrBin,nPsiTOF,-TMath::Pi()/2,TMath::Pi()/2);
1547   fPhiRPTPCv3 = new TH2F("fPhiRPTPCv3","#phi distribution of EP TPC;centrality;#phi (rad)",nCentrBin,0,nCentrBin,nPsiTOF,-TMath::Pi()/3,TMath::Pi()/3);
1548   fList->Add(fPhiRPTPC);
1549   fList->Add(fPhiRPTPCv3);
1550
1551   fPhiRPv0A = new TH2F("fPhiRPv0Av2","#phi distribution of EP VZERO-A;centrality;#phi (rad)",nCentrBin,0,nCentrBin,nPsiTOF,-TMath::Pi()/2,TMath::Pi()/2);
1552   fPhiRPv0C = new TH2F("fPhiRPv0Cv2","#phi distribution of EP VZERO-C;centrality;#phi (rad)",nCentrBin,0,nCentrBin,nPsiTOF,-TMath::Pi()/2,TMath::Pi()/2);
1553   fList->Add(fPhiRPv0A);
1554   fList->Add(fPhiRPv0C);
1555
1556   //v3
1557   fPhiRPv0Av3 = new TH2F("fPhiRPv0Av3","#phi distribution of EP VZERO-A;centrality;#phi (rad)",nCentrBin,0,nCentrBin,nPsiTOF,-TMath::Pi()/3,TMath::Pi()/3);
1558   fPhiRPv0Cv3 = new TH2F("fPhiRPv0Cv3","#phi distribution of EP VZERO-C;centrality;#phi (rad)",nCentrBin,0,nCentrBin,nPsiTOF,-TMath::Pi()/3,TMath::Pi()/3);
1559   fList->Add(fPhiRPv0Av3);
1560   fList->Add(fPhiRPv0Cv3);
1561
1562   fHistEventPlaneTruth = new TH2F("fHistEventPlaneTruth","#phi distribution of EP MCTRUTHheader;centrality;#phi (rad)",nCentrBin,0,nCentrBin,nPsiTOF,-TMath::Pi()/2,TMath::Pi()/2);
1563   fList->Add(fHistEventPlaneTruth);
1564
1565   }
1566     
1567   //*****************************************************PIDQA histos*****************************************************//
1568
1569  
1570   //nsigma plot
1571   for(Int_t ipart=0;ipart<NSpecies;ipart++){
1572     for(Int_t ipid=0;ipid<=NSigmaPIDType;ipid++){
1573       Double_t miny=-30;
1574       Double_t maxy=30;
1575       if(ipid==NSigmaTPCTOF){miny=0;maxy=50;}
1576       TH2F *fHistoNSigma=new TH2F(Form("NSigma_%d_%d",ipart,ipid),Form("n#sigma %s %s",kParticleSpeciesName[ipart],kPIDTypeName[ipid]),200,0,10,500,miny,maxy);
1577       fHistoNSigma->GetXaxis()->SetTitle("P_{T} (GeV / c)");
1578       fHistoNSigma->GetYaxis()->SetTitle(Form("n#sigma %s %s",kParticleSpeciesName[ipart],kPIDTypeName[ipid]));
1579       fOutputList->Add(fHistoNSigma);
1580     }
1581   }
1582   
1583   //nsigmaRec plot
1584   for(Int_t ipart=0;ipart<NSpecies;ipart++){
1585     for(Int_t ipid=0;ipid<=NSigmaPIDType;ipid++){
1586       Double_t miny=-10;
1587       Double_t maxy=10;
1588       if(ipid==NSigmaTPCTOF){miny=0;maxy=20;}
1589       TH2F *fHistoNSigma=new TH2F(Form("NSigmaRec_%d_%d",ipart,ipid),
1590                                   Form("n#sigma for reconstructed %s %s",kParticleSpeciesName[ipart],kPIDTypeName[ipid]),200,0,10,500,miny,maxy);
1591       fHistoNSigma->GetXaxis()->SetTitle("P_{T} (GeV / c)");
1592       fHistoNSigma->GetYaxis()->SetTitle(Form("n#sigma %s %s",kParticleSpeciesName[ipart],kPIDTypeName[ipid]));
1593       fOutputList->Add(fHistoNSigma);
1594     }
1595   }
1596
1597   //BayesRec plot
1598   if(fPIDType==Bayes){//use bayesianPID
1599     fPIDCombined = new AliPIDCombined();
1600     fPIDCombined->SetDefaultTPCPriors();//****************************************Need to know about it
1601
1602   for(Int_t ipart=0;ipart<NSpecies;ipart++){
1603     Double_t miny=0.;
1604     Double_t maxy=1;
1605     TH2F *fHistoBayes=new TH2F(Form("BayesRec_%d",ipart),
1606                                Form("probability for reconstructed %s",kParticleSpeciesName[ipart]),200,0,10,500,miny,maxy);
1607     fHistoBayes->GetXaxis()->SetTitle("P_{T} (GeV / c)");
1608     fHistoBayes->GetYaxis()->SetTitle(Form("Bayes prob %s",kParticleSpeciesName[ipart]));
1609     fOutputList->Add(fHistoBayes);
1610
1611
1612    TH2F *fHistoBayesTPC=new TH2F(Form("probBayes_TPC_%d",ipart),
1613                                Form("probability for Tracks as %s",kParticleSpeciesName[ipart]),200,0,10,500,miny,maxy);
1614     fHistoBayesTPC->GetXaxis()->SetTitle("P_{T} (GeV / c)");
1615     fHistoBayesTPC->GetYaxis()->SetTitle(Form("Bayes prob TPC %s",kParticleSpeciesName[ipart]));
1616     fOutputList->Add(fHistoBayesTPC);
1617
1618   TH2F *fHistoBayesTOF=new TH2F(Form("probBayes_TOF_%d",ipart),
1619                                Form("probability for Tracks as %s",kParticleSpeciesName[ipart]),200,0,10,500,miny,maxy);
1620     fHistoBayesTOF->GetXaxis()->SetTitle("P_{T} (GeV / c)");
1621     fHistoBayesTOF->GetYaxis()->SetTitle(Form("Bayes prob TOF %s",kParticleSpeciesName[ipart]));
1622     fOutputList->Add(fHistoBayesTOF);
1623
1624  TH2F *fHistoBayesTPCTOF=new TH2F(Form("probBayes_TPCTOF_%d",ipart),
1625                                Form("probability for Tracks as  %s",kParticleSpeciesName[ipart]),200,0,10,500,miny,maxy);
1626     fHistoBayesTPCTOF->GetXaxis()->SetTitle("P_{T} (GeV / c)");
1627     fHistoBayesTPCTOF->GetYaxis()->SetTitle(Form("Bayes prob TPCTOF %s",kParticleSpeciesName[ipart]));
1628     fOutputList->Add(fHistoBayesTPCTOF);
1629   }
1630   }
1631
1632   //nsigma separation power plot 
1633     for(Int_t ipid=0;ipid<=NSigmaPIDType;ipid++){
1634  Double_t miny=0;
1635  Double_t maxy=10;
1636    TH2F *Pi_Ka_sep=new TH2F(Form("Pi_Ka_sep_%d",ipid),
1637                                Form("Pi_Ka separation in %s",kPIDTypeName[ipid]),50,0,10,200,miny,maxy);
1638     Pi_Ka_sep->GetXaxis()->SetTitle("P_{T} (GeV/C)");
1639     Pi_Ka_sep->GetYaxis()->SetTitle(Form("expected seaparation(n#sigma) in %s",kPIDTypeName[ipid]));
1640     fOutputList->Add(Pi_Ka_sep);
1641
1642    TH2F *Pi_Pr_sep=new TH2F(Form("Pi_Pr_sep_%d",ipid),
1643                                Form("Pi_Pr separation in %s",kPIDTypeName[ipid]),50,0,10,200,miny,maxy);
1644     Pi_Pr_sep->GetXaxis()->SetTitle("P_{T} (GeV/C)");
1645     Pi_Pr_sep->GetYaxis()->SetTitle(Form("expected seaparation(n#sigma) in %s",kPIDTypeName[ipid]));
1646     fOutputList->Add(Pi_Pr_sep);
1647
1648     TH2F *Ka_Pr_sep=new TH2F(Form("Ka_Pr_sep_%d",ipid),
1649                                Form("Ka_Pr separation in %s",kPIDTypeName[ipid]),50,0,10,200,miny,maxy);
1650     Ka_Pr_sep->GetXaxis()->SetTitle("P_{T} (GeV/C)");
1651     Ka_Pr_sep->GetYaxis()->SetTitle(Form("expected seaparation(n#sigma) in %s",kPIDTypeName[ipid]));
1652     fOutputList->Add(Ka_Pr_sep);
1653     }
1654
1655   //nsigmaDC plot
1656   for(Int_t ipart=0;ipart<NSpecies;ipart++){
1657     for(Int_t ipid=0;ipid<=NSigmaPIDType;ipid++){
1658       Double_t miny=-10;
1659       Double_t maxy=10;
1660       if(ipid==NSigmaTPCTOF){miny=0;maxy=20;}
1661       TH2F *fHistoNSigma=new TH2F(Form("NSigmaDC_%d_%d",ipart,ipid),
1662                                   Form("n#sigma for double counting %s %s",kParticleSpeciesName[ipart],kPIDTypeName[ipid]),200,0,10,500,miny,maxy);
1663       fHistoNSigma->GetXaxis()->SetTitle("P_{T} (GeV / c)");
1664       fHistoNSigma->GetYaxis()->SetTitle(Form("n#sigma %s %s",kParticleSpeciesName[ipart],kPIDTypeName[ipid]));
1665       fOutputList->Add(fHistoNSigma);
1666     }
1667   }
1668   
1669   //nsigmaMC plot
1670  if (fAnalysisType == "MCAOD"){
1671   for(Int_t ipart=0;ipart<NSpecies;ipart++){
1672     for(Int_t ipid=0;ipid<=NSigmaPIDType;ipid++){
1673       Double_t miny=-30;
1674       Double_t maxy=30;
1675       if(ipid==NSigmaTPCTOF){miny=0;maxy=50;}
1676       TH2F *fHistoNSigma=new TH2F(Form("NSigmaMC_%d_%d",ipart,ipid),
1677                                   Form("n#sigma for MC %s %s",kParticleSpeciesName[ipart],kPIDTypeName[ipid]),200,0,10,500,miny,maxy);
1678       fHistoNSigma->GetXaxis()->SetTitle("P_{T} (GeV / c)");
1679       fHistoNSigma->GetYaxis()->SetTitle(Form("n#sigma %s %s",kParticleSpeciesName[ipart],kPIDTypeName[ipid]));
1680       fOutputList->Add(fHistoNSigma);
1681     }
1682   }
1683   }
1684   //PID signal plot
1685   for(Int_t idet=0;idet<fNDetectors;idet++){
1686     for(Int_t ipart=0;ipart<NSpecies;ipart++){
1687       Double_t maxy=500;
1688       if(idet==fTOF)maxy=1.1;
1689       TH2F *fHistoPID=new TH2F(Form("PID_%d_%d",idet,ipart),Form("%s signal - %s",kDetectorName[idet],kParticleSpeciesName[ipart]),200,0,10,500,-maxy,maxy);
1690       fHistoPID->GetXaxis()->SetTitle("P (GeV / c)");
1691       fHistoPID->GetYaxis()->SetTitle(Form("%s signal",kDetectorName[idet]));
1692       fOutputList->Add(fHistoPID);
1693     }
1694   }
1695   //PID signal plot, before PID cut
1696   for(Int_t idet=0;idet<fNDetectors;idet++){
1697     Double_t maxy=500;
1698     if(idet==fTOF)maxy=1.1;
1699     TH2F *fHistoPID=new TH2F(Form("PIDAll_%d",idet),Form("%s signal",kDetectorName[idet]),200,0,10,500,-maxy,maxy);
1700     fHistoPID->GetXaxis()->SetTitle("P (GeV / c)");
1701     fHistoPID->GetYaxis()->SetTitle(Form("%s signal",kDetectorName[idet]));
1702     fOutputList->Add(fHistoPID);
1703   }
1704
1705   PostData(1, fOutput);              // Post data for ALL output slots >0 here, to get at least an empty histogram
1706   PostData(2, fOutputList);
1707   if(fRequestEventPlane) PostData(3, fList);
1708   AliInfo("Finished setting up the Output");
1709
1710    TH1::AddDirectory(oldStatus);
1711 }
1712 //-------------------------------------------------------------------------------
1713 void AliTwoParticlePIDCorr::UserExec( Option_t * ){
1714  
1715   if(fAnalysisType == "AOD") {
1716
1717     doAODevent();
1718     
1719   }//AOD--analysis-----
1720
1721   else if(fAnalysisType == "MCAOD" || fAnalysisType == "MC") {
1722   
1723     doMCAODevent();
1724
1725   }
1726   
1727   else return;
1728   
1729 }
1730 //-------------------------------------------------------------------------
1731 void AliTwoParticlePIDCorr::doMCAODevent() 
1732 {
1733
1734   // get the event (for generator level: MCEvent())
1735   AliVEvent* event = NULL;
1736   if(fAnalysisType == "MC") {
1737     event = dynamic_cast<AliVEvent*>(MCEvent());
1738   }
1739   else{
1740     event = dynamic_cast<AliVEvent*>(InputEvent());     
1741   }
1742   if(!event) {
1743     AliError("eventMain not available");
1744     return;
1745   }
1746
1747   Double_t Inv_mass=0.0;//has no meaning for pions, kaons and protons(just set 0.0) to fill the LRCParticlePID position
1748     evplaneMC=999.;
1749     fgPsi2v0aMC=999.;
1750     fgPsi2v0cMC=999.;
1751     fgPsi2tpcMC=999.;
1752     fgPsi3v0aMC=999.;
1753     fgPsi3v0cMC=999.;
1754     fgPsi3tpcMC=999.;
1755     gReactionPlane = 999.;
1756
1757  // get centrality object and check quality(valid for p-Pb and Pb-Pb; coming soon for pp 7 TeV)
1758   Double_t cent_v0=-1.0;
1759   Double_t effcent=1.0;
1760   Double_t refmultReco =0.0;
1761    Double_t nooftrackstruth=0.0;//in case of pp this will give the multiplicity(for truth case) after the track loop(only for unidentified particles that pass  kinematic cuts)
1762
1763
1764 if(fAnalysisType == "MC"){
1765    
1766     AliMCEvent *gMCEvent = dynamic_cast<AliMCEvent*>(event);
1767
1768  if(!gMCEvent) {
1769       AliError("mcEvent not available");
1770       return ;
1771     }
1772 // count all events(physics triggered)   
1773   fEventCounter->Fill(1);
1774
1775         AliGenEventHeader *header = dynamic_cast<AliGenEventHeader*>(gMCEvent->GenEventHeader());
1776         if(!header) return;  
1777           TArrayF gVertexArray;
1778           header->PrimaryVertex(gVertexArray);
1779           Float_t zVtxmc =gVertexArray.At(2);
1780           //cout<<"*****************************************************************************************************hi I am here"<<endl;
1781
1782  
1783           cent_v0=GetAcceptedEventMultiplicity((AliVEvent*)gMCEvent,kFALSE); //b value; 2nd argument has no meaning
1784  
1785  if(cent_v0<0.) return;//mainly returns impact parameter
1786
1787  //get the event plane in case of PbPb
1788    if(fRequestEventPlane){
1789      gReactionPlane=GetEventPlane((AliVEvent*)gMCEvent,kTRUE,cent_v0);//get the truth event plane,middle argument has no meaning in this case
1790    if(gReactionPlane==999.) return;
1791  }
1792
1793
1794 TObjArray* tracksMCtruth=new TObjArray;//for truth MC particles with PID,here unidentified means any particle other than pion, kaon or proton(Basicaly Spundefined of AliHelperPID)******WARNING::different from data and reco MC
1795  tracksMCtruth->SetOwner(kTRUE);  //***********************************IMPORTANT!
1796
1797 for (Int_t iTracks = 0; iTracks < gMCEvent->GetNumberOfPrimaries(); iTracks++) {
1798         AliMCParticle* partMC = dynamic_cast<AliMCParticle *>(gMCEvent->GetTrack(iTracks));
1799         if (!partMC) {
1800           AliError(Form("Could not receive particle %d", iTracks));
1801           continue;
1802         }
1803 //exclude non stable particles
1804         if(fselectprimaryTruth && !(gMCEvent->IsPhysicalPrimary(iTracks))) continue;
1805
1806 //consider only charged particles
1807     if(partMC->Charge() == 0) continue;
1808
1809
1810 //give only kinematic cuts at the generator level  
1811  if (partMC->Eta() < fmineta || partMC->Eta() > fmaxeta) continue;
1812  if (partMC->Pt() < fminPt ||  partMC->Pt() > fmaxPt) continue;
1813
1814  if(!partMC) continue;//for safety
1815
1816           TParticle *particle = partMC->Particle();
1817           if(!particle) continue;
1818            Int_t particletypeTruth=-999;
1819           
1820           Int_t pdgtruth = particle->GetPdgCode();
1821
1822  //To determine multiplicity in case of PP
1823  nooftrackstruth++;
1824  //cout<<"**************************************"<<TMath::Abs(partMC->GetLabel())<<endl;
1825 //only physical primary(all/unidentified)  
1826 if(ffillhistQATruth)
1827     {
1828  MCtruthpt->Fill(partMC->Pt());
1829  MCtrutheta->Fill(partMC->Eta());
1830  MCtruthphi->Fill(partMC->Phi());
1831     }
1832  if (TMath::Abs(pdgtruth)==211)
1833    {
1834  particletypeTruth=SpPion;
1835 if(ffillhistQATruth)
1836     {
1837  MCtruthpionpt->Fill(partMC->Pt());
1838  MCtruthpioneta->Fill(partMC->Eta());
1839  MCtruthpionphi->Fill(partMC->Phi());
1840     }
1841       }
1842  if (TMath::Abs(pdgtruth)==321)
1843    {
1844  particletypeTruth=SpKaon;
1845 if(ffillhistQATruth)
1846     {
1847  MCtruthkaonpt->Fill(partMC->Pt());
1848  MCtruthkaoneta->Fill(partMC->Eta());
1849  MCtruthkaonphi->Fill(partMC->Phi());
1850   }
1851     }
1852 if(TMath::Abs(pdgtruth)==2212)
1853   {
1854  particletypeTruth=SpProton;
1855 if(ffillhistQATruth)
1856     {
1857  MCtruthprotonpt->Fill(partMC->Pt());
1858  MCtruthprotoneta->Fill(partMC->Eta());
1859  MCtruthprotonphi->Fill(partMC->Phi());
1860     }
1861      }
1862  if(TMath::Abs(pdgtruth)!=211 && TMath::Abs(pdgtruth)!=321 && TMath::Abs(pdgtruth)!=2212)  particletypeTruth=unidentified;//*********************WARNING:: situation is different from reco MC and data case(here we don't have SpUndefined particles,because here unidentified=SpUndefined)
1863
1864     if(fRequestEventPlane){
1865       FillPIDEventPlane(cent_v0,particletypeTruth,partMC->Phi(),gReactionPlane);
1866     }
1867     /*
1868 //Exclude resonances
1869         if(fExcludeResonancesInMC) {
1870           TParticle *particle = track->Particle();
1871           if(!particle) continue;
1872           
1873           Bool_t kExcludeParticle = kFALSE;
1874           Int_t gMotherIndex = particle->GetFirstMother();
1875           if(gMotherIndex != -1) {
1876             AliMCParticle* motherTrack = dynamic_cast<AliMCParticle *>(event->GetTrack(gMotherIndex));
1877             if(motherTrack) {
1878               TParticle *motherParticle = motherTrack->Particle();
1879               if(motherParticle) {
1880                 Int_t pdgCodeOfMother = motherParticle->GetPdgCode();
1881                 //if((pdgCodeOfMother == 113)||(pdgCodeOfMother == 213)||(pdgCodeOfMother == 221)||(pdgCodeOfMother == 223)||(pdgCodeOfMother == 331)||(pdgCodeOfMother == 333)) {
1882                 }
1883                 if(pdgCodeOfMother == 113  // rho0
1884                    || pdgCodeOfMother == 213 || pdgCodeOfMother == -213 // rho+
1885                    // || pdgCodeOfMother == 221  // eta
1886                    // || pdgCodeOfMother == 331  // eta'
1887                    // || pdgCodeOfMother == 223  // omega
1888                    // || pdgCodeOfMother == 333  // phi
1889                    || pdgCodeOfMother == 311  || pdgCodeOfMother == -311 // K0
1890                    // || pdgCodeOfMother == 313  || pdgCodeOfMother == -313 // K0*
1891                    // || pdgCodeOfMother == 323  || pdgCodeOfMother == -323 // K+*
1892                    || pdgCodeOfMother == 3122 || pdgCodeOfMother == -3122 // Lambda
1893                    || pdgCodeOfMother == 111  // pi0 Dalitz
1894                    ) {
1895                   kExcludeParticle = kTRUE;
1896                 }
1897               }
1898             }
1899           }
1900           
1901           //Exclude from the analysis decay products of rho0, rho+, eta, eta' and phi
1902           if(kExcludeParticle) continue;
1903         }
1904
1905         //Exclude electrons with PDG
1906         if(fExcludeElectronsInMC) {
1907           
1908           TParticle *particle = track->Particle();
1909           
1910           if (particle){ 
1911             if(TMath::Abs(particle->GetPdgCode()) == 11) continue;
1912           }
1913         }
1914     */
1915
1916  Float_t effmatrixtruth=1.0;//In Truth MC, no case of efficiency correction so it should be always 1.0
1917 if((partMC->Pt()>=fminPtAsso && partMC->Pt()<=fmaxPtAsso) || (partMC->Pt()>=fminPtTrig && partMC->Pt()<=fmaxPtTrig))//to reduce memory consumption in pool
1918   {
1919     Short_t chargeval=0;
1920     if(partMC->Charge()>0)   chargeval=1;
1921     if(partMC->Charge()<0)   chargeval=-1;
1922     if(chargeval==0) continue;
1923     const TBits *clustermap=0;
1924     const TBits *sharemap=0;
1925     LRCParticlePID* copy6 = new LRCParticlePID(particletypeTruth,Inv_mass,chargeval,partMC->Pt(),partMC->Eta(), partMC->Phi(),effmatrixtruth,clustermap,sharemap);
1926 //copy6->SetUniqueID(eventno * 100000 + TMath::Abs(partMC->GetLabel()));
1927  copy6->SetUniqueID(eventno * 100000 + (Int_t)nooftrackstruth);
1928  tracksMCtruth->Add(copy6);//************** TObjArray used for truth correlation function calculation
1929   }
1930  }//track loop ends
1931
1932  if(nooftrackstruth>0.0){
1933 if (fSampleType=="pPb" || fSampleType=="PbPb" || fPPVsMultUtils==kTRUE || fCentralityMethod == "MC_b") fCentralityCorrelation->Fill(cent_v0, nooftrackstruth);//only with unidentified tracks(i.e before PID selection);;;;;can be used to remove centrality outliers??????
1934
1935 AliCollisionGeometry* collGeometry = dynamic_cast<AliCollisionGeometry*>(gMCEvent->GenEventHeader());    
1936  if(collGeometry){
1937 Float_t NpartProj= collGeometry-> ProjectileParticipants();
1938 Float_t NpartTarg = collGeometry->TargetParticipants();
1939  Float_t Npart= (NpartProj + NpartTarg);
1940 fNchNpartCorr->Fill(Npart,nooftrackstruth);
1941  }
1942  }
1943
1944   if (fRandomizeReactionPlane)//only for TRuth MC??
1945   {
1946     Double_t centralityDigits = cent_v0*1000. - (Int_t)(cent_v0*1000.);
1947     Double_t angle = TMath::TwoPi() * centralityDigits;
1948     AliInfo(Form("Shifting phi of all tracks by %f (digits %f)", angle, centralityDigits));
1949     ShiftTracks(tracksMCtruth, angle);  
1950   }
1951  
1952
1953  Float_t weghtval=1.0;
1954  Float_t bSign = 0;
1955
1956 if(nooftrackstruth>0.0 && ffilltrigIDassoIDMCTRUTH)
1957   {
1958  //Fill Correlations for MC truth particles(same event)
1959 if(tracksMCtruth && tracksMCtruth->GetEntriesFast()>0)//hadron triggered correlation
1960   Fillcorrelation(gReactionPlane,tracksMCtruth,0,cent_v0,zVtxmc,weghtval,kFALSE,bSign,fPtOrderMCTruth,kFALSE,kFALSE,"trigIDassoIDMCTRUTH");//mixcase=kFALSE for same event case
1961
1962 //start mixing
1963  AliEventPool* pool2 = fPoolMgr->GetEventPool(cent_v0, zVtxmc+200, gReactionPlane);
1964 if (pool2 && pool2->IsReady())
1965   {//start mixing only when pool->IsReady
1966 if(tracksMCtruth && tracksMCtruth->GetEntriesFast()>0)
1967   {//proceed only when no. of trigger particles >0 in current event
1968     Float_t nmix=(Float_t)pool2->GetCurrentNEvents();  
1969 for (Int_t jMix=0; jMix<pool2->GetCurrentNEvents(); jMix++) 
1970   { //pool event loop start
1971  TObjArray* bgTracks6 = pool2->GetEvent(jMix);
1972   if(!bgTracks6) continue;
1973   Fillcorrelation(gReactionPlane,tracksMCtruth,bgTracks6,cent_v0,zVtxmc,nmix,(jMix == 0),bSign,fPtOrderMCTruth,kFALSE,kTRUE,"trigIDassoIDMCTRUTH");//mixcase=kTRUE for mixing case
1974   
1975    }// pool event loop ends mixing case
1976  }//if(trackstrig && trackstrig->GetEntriesFast()>0) condition ends mixing case
1977 } //if pool->IsReady() condition ends mixing case
1978
1979  //still in main event loop
1980
1981  if(tracksMCtruth){
1982 if(pool2)  pool2->UpdatePool(CloneAndReduceTrackList(tracksMCtruth));//ownership of tracksasso is with pool now, don't delete it
1983  }
1984   }
1985
1986  //still in main event loop
1987
1988 if(tracksMCtruth) delete tracksMCtruth;
1989
1990
1991  }//MC type
1992
1993 //"MC" type analysis is finished but still in event loop
1994
1995  else{//if(fAnalysisType=="MCAOD")
1996
1997   AliAODEvent* aod = dynamic_cast<AliAODEvent*>(event);
1998   if (!aod) {
1999     AliError("Cannot get the AOD event");
2000     return;
2001   }
2002  
2003 // count all events(physics triggered)   
2004   fEventCounter->Fill(1);
2005
2006    
2007
2008 //check the PIDResponse handler
2009      fPID = ((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->GetPIDResponse();
2010     if (!fPID) AliFatal("This Task needs the PID response attached to the inputHandler");
2011     //if (!fPID) return;
2012 // get mag. field required for twotrack efficiency cut
2013  Float_t bSign = 0;
2014  bSign = (aod->GetMagneticField() > 0) ? 1 : -1;
2015
2016  //check for TClonesArray(truth track MC information)
2017 fArrayMC = dynamic_cast<TClonesArray*>(aod->FindListObject(AliAODMCParticle::StdBranchName()));
2018   if (!fArrayMC) {
2019     AliFatal("Error: MC particles branch not found!\n");
2020     return;
2021   }
2022   
2023   //check for AliAODMCHeader(truth event MC information)
2024   AliAODMCHeader *header=NULL;
2025   header=(AliAODMCHeader*)aod->GetList()->FindObject(AliAODMCHeader::StdBranchName());  
2026   if(!header) {
2027     printf("MC header branch not found!\n");
2028     return;
2029   }
2030  
2031 //Only consider MC events within the vtx-z region used also as cut on the reconstructed vertex
2032 Float_t zVtxmc =header->GetVtxZ();
2033  if(TMath::Abs(zVtxmc)>fzvtxcut) return;
2034
2035  // For productions with injected signals, figure out above which label to skip particles/tracks
2036
2037  if (fInjectedSignals)
2038   {
2039     AliGenEventHeader* eventHeader = 0;
2040     Int_t headers = 0;
2041
2042 // AOD
2043       if (!header)
2044       AliFatal("fInjectedSignals set but no MC header found");
2045       
2046       headers = header->GetNCocktailHeaders();
2047       eventHeader = header->GetCocktailHeader(0);
2048
2049  if (!eventHeader)
2050     {
2051       // We avoid AliFatal here, because the AOD productions sometimes have events where the MC header is missing 
2052       // (due to unreadable Kinematics) and we don't want to loose the whole job because of a few events
2053       AliError("First event header not found. Skipping this event.");
2054       //fHistos->FillEvent(centrality, AliUEHist::kCFStepAnaTopology);
2055       return;
2056     }
2057 skipParticlesAbove = eventHeader->NProduced();
2058     AliInfo(Form("Injected signals in this event (%d headers). Keeping events of %s. Will skip particles/tracks above %d.", headers, eventHeader->ClassName(), skipParticlesAbove));
2059   }
2060
2061  if (fSampleType=="pp_2_76" || fCentralityMethod.EndsWith("_MANUAL") || (fSampleType=="pp_7" && fPPVsMultUtils==kFALSE))
2062    {
2063  //make the event selection with reco vertex cut and centrality cut and return the value of the centrality
2064      Double_t refmultTruth = GetAcceptedEventMultiplicity((AliVEvent*)aod,kTRUE);  //incase of ref multiplicity it will return the truth MC ref mullt value; need to determine the ref mult value separately for reco Mc case; in case of centrality this is final and fine
2065      refmultReco = GetAcceptedEventMultiplicity((AliVEvent*)aod,kFALSE); 
2066      if(refmultTruth<=0 || refmultReco<=0) return;
2067      cent_v0=refmultTruth;
2068    }
2069  else {
2070  cent_v0=GetAcceptedEventMultiplicity((AliVEvent*)aod,kFALSE); //centrality value; 2nd argument has no meaning
2071  }
2072
2073  if(cent_v0<0.) return;
2074  effcent=cent_v0;// This will be required for efficiency THn filling(specially in case of pp)
2075
2076   //get the event plane in case of PbPb
2077    if(fRequestEventPlane){
2078      gReactionPlane=GetEventPlane((AliVEvent*)aod,kTRUE,cent_v0);//get the truth event plane
2079    if(gReactionPlane==999.) return;
2080  }
2081  
2082    //TObjArray* tracksMCtruth=0;
2083 TObjArray* tracksMCtruth=new TObjArray;//for truth MC particles with PID,here unidentified means any particle other than pion, kaon or proton(Basicaly Spundefined of AliHelperPID)******WARNING::different from data and reco MC
2084  tracksMCtruth->SetOwner(kTRUE);  //***********************************IMPORTANT!
2085
2086   eventno++;
2087
2088   //There is a small difference between zvtx and zVtxmc?????? 
2089   //cout<<"***********************************************zVtxmc="<<zVtxmc<<endl;
2090   //cout<<"***********************************************zvtx="<<zvtx<<endl;
2091  
2092 //now process the truth particles(for both efficiency & correlation function)
2093 Int_t nMCTrack = fArrayMC->GetEntriesFast();
2094   
2095 for (Int_t iMC = 0; iMC < nMCTrack; iMC++) 
2096 {      //MC truth track loop starts
2097     
2098 AliAODMCParticle *partMC = (AliAODMCParticle*) fArrayMC->At(iMC);
2099     
2100     if(!partMC){
2101       AliError(Form("ERROR: Could not retrieve AODMCtrack %d",iMC));
2102       continue;
2103     }
2104
2105 //consider only charged particles
2106     if(partMC->Charge() == 0) continue;
2107
2108 //consider only primary particles; neglect all secondary particles including from weak decays
2109  if(fselectprimaryTruth && !partMC->IsPhysicalPrimary()) continue;
2110
2111
2112 //remove injected signals(primaries above <maxLabel>)
2113  if (fInjectedSignals && partMC->GetLabel() >= skipParticlesAbove) continue;
2114
2115 //remove duplicates
2116   Bool_t isduplicate=kFALSE;
2117  if (fRemoveDuplicates)
2118    { 
2119  for (Int_t j=iMC+1; j<nMCTrack; ++j) 
2120    {//2nd trutuh loop starts
2121 AliAODMCParticle *partMC2 = (AliAODMCParticle*) fArrayMC->At(j);
2122    if(!partMC2){
2123       AliError(Form("ERROR: Could not retrieve AODMCtrack %d",j));
2124       continue;
2125     }    
2126  if (partMC->GetLabel() == partMC2->GetLabel())
2127    {
2128 isduplicate=kTRUE;
2129  break;  
2130    }    
2131    }//2nd truth loop ends
2132    }
2133  if(fRemoveDuplicates && isduplicate) continue;//remove duplicates
2134
2135 //give only kinematic cuts at the truth level  
2136  if (partMC->Eta() < fmineta || partMC->Eta() > fmaxeta) continue;
2137  if (partMC->Pt() < fminPt ||  partMC->Pt() > fmaxPt) continue;
2138
2139  if(!partMC) continue;//for safety
2140
2141  //To determine multiplicity in case of PP
2142  nooftrackstruth++;
2143  //cout<<"**************************************"<<TMath::Abs(partMC->GetLabel())<<endl;
2144 //only physical primary(all/unidentified)  
2145 if(ffillhistQATruth)
2146     {
2147  MCtruthpt->Fill(partMC->Pt());
2148  MCtrutheta->Fill(partMC->Eta());
2149  MCtruthphi->Fill(partMC->Phi());
2150     }
2151  //get particle ID
2152 Int_t pdgtruth=((AliAODMCParticle*)partMC)->GetPdgCode();
2153 Int_t particletypeTruth=-999;
2154  if (TMath::Abs(pdgtruth)==211)
2155    {
2156  particletypeTruth=SpPion;
2157 if(ffillhistQATruth)
2158     {
2159
2160  MCtruthpionpt->Fill(partMC->Pt());
2161  MCtruthpioneta->Fill(partMC->Eta());
2162  MCtruthpionphi->Fill(partMC->Phi());
2163     }
2164       }
2165  if (TMath::Abs(pdgtruth)==321)
2166    {
2167  particletypeTruth=SpKaon;
2168 if(ffillhistQATruth)
2169     {
2170  MCtruthkaonpt->Fill(partMC->Pt());
2171  MCtruthkaoneta->Fill(partMC->Eta());
2172  MCtruthkaonphi->Fill(partMC->Phi());
2173   }
2174     }
2175 if(TMath::Abs(pdgtruth)==2212)
2176   {
2177  particletypeTruth=SpProton;
2178 if(ffillhistQATruth)
2179     {
2180  MCtruthprotonpt->Fill(partMC->Pt());
2181  MCtruthprotoneta->Fill(partMC->Eta());
2182  MCtruthprotonphi->Fill(partMC->Phi());
2183     }
2184      }
2185  if(TMath::Abs(pdgtruth)!=211 && TMath::Abs(pdgtruth)!=321 && TMath::Abs(pdgtruth)!=2212)  particletypeTruth=unidentified;//*********************WARNING:: situation is different from reco MC and data case(here we don't have SpUndefined particles,because here unidentified=SpUndefined)
2186
2187     if(fRequestEventPlane){
2188       FillPIDEventPlane(cent_v0,particletypeTruth,partMC->Phi(),gReactionPlane);
2189     }
2190
2191  // -- Fill THnSparse for efficiency and contamination calculation
2192     if (fSampleType=="pp_2_76" || fCentralityMethod.EndsWith("_MANUAL") || (fSampleType=="pp_7" && fPPVsMultUtils==kFALSE)) effcent=15.0;//integrated over multiplicity(so put any fixed value for each track so that practically means there is only one bin in multiplicity i.e. multiplicity intregated out )**************Important
2193
2194  Double_t primmctruth[4] = {effcent, zVtxmc,partMC->Pt(), partMC->Eta()};
2195  if(ffillefficiency)
2196   {
2197     fTrackHistEfficiency[5]->Fill(primmctruth,0);//for all primary truth particles(4)
2198     if (TMath::Abs(pdgtruth)==211 || TMath::Abs(pdgtruth)==321) fTrackHistEfficiency[3]->Fill(primmctruth,0);//for  primary truth mesons(3)
2199     if (TMath::Abs(pdgtruth)==2212 || TMath::Abs(pdgtruth)==321) fTrackHistEfficiency[4]->Fill(primmctruth,0);//for  primary truth kaons+protons(4)
2200     if (TMath::Abs(pdgtruth)==211)  fTrackHistEfficiency[0]->Fill(primmctruth,0);//for pions
2201     if (TMath::Abs(pdgtruth)==321)  fTrackHistEfficiency[1]->Fill(primmctruth,0);//for kaons
2202     if (TMath::Abs(pdgtruth)==2212)  fTrackHistEfficiency[2]->Fill(primmctruth,0);//for protons
2203   }
2204    
2205  Float_t effmatrixtruth=1.0;//In Truth MC, no case of efficiency correction so it should be always 1.0
2206 if((partMC->Pt()>=fminPtAsso && partMC->Pt()<=fmaxPtAsso) || (partMC->Pt()>=fminPtTrig && partMC->Pt()<=fmaxPtTrig))//to reduce memory consumption in pool
2207   {
2208     Short_t chargeval=0;
2209     if(partMC->Charge()>0)   chargeval=1;
2210     if(partMC->Charge()<0)   chargeval=-1;
2211     if(chargeval==0) continue;
2212     const TBits *clustermap=0;
2213     const TBits *sharemap=0;
2214     LRCParticlePID* copy6 = new LRCParticlePID(particletypeTruth,Inv_mass,chargeval,partMC->Pt(),partMC->Eta(), partMC->Phi(),effmatrixtruth,clustermap,sharemap);
2215 //copy6->SetUniqueID(eventno * 100000 + TMath::Abs(partMC->GetLabel()));
2216  copy6->SetUniqueID(eventno * 100000 + (Int_t)nooftrackstruth);
2217  tracksMCtruth->Add(copy6);//************** TObjArray used for truth correlation function calculation
2218   }
2219   }//MC truth track loop ends
2220
2221 //*********************still in event loop
2222
2223    if (fRandomizeReactionPlane)//only for TRuth MC??
2224   {
2225     Double_t centralityDigits = cent_v0*1000. - (Int_t)(cent_v0*1000.);
2226     Double_t angle = TMath::TwoPi() * centralityDigits;
2227     AliInfo(Form("Shifting phi of all tracks by %f (digits %f)", angle, centralityDigits));
2228     ShiftTracks(tracksMCtruth, angle);  
2229   }
2230  
2231 if(nooftrackstruth>0.0){
2232 if (fSampleType=="pPb" || fSampleType=="PbPb" || fPPVsMultUtils==kTRUE || fCentralityMethod == "MC_b") fCentralityCorrelation->Fill(cent_v0, nooftrackstruth);//only with unidentified tracks(i.e before PID selection);;;;;can be used to remove centrality outliers??????
2233
2234    AliGenEventHeader* eventHeader = header->GetCocktailHeader(0);  // get first MC header from either ESD/AOD (including cocktail header if available)
2235       if (eventHeader)
2236       {      
2237 AliCollisionGeometry* collGeometry = dynamic_cast <AliCollisionGeometry*> (eventHeader);
2238  if(collGeometry){
2239 Float_t NpartProj= collGeometry-> ProjectileParticipants();
2240 Float_t NpartTarg = collGeometry->TargetParticipants();
2241 Float_t Npart= (NpartProj + NpartTarg);
2242 fNchNpartCorr->Fill(Npart,nooftrackstruth);
2243          }
2244       }    
2245  }
2246  
2247  Float_t weghtval=1.0;
2248
2249 if(nooftrackstruth>0.0 && ffilltrigIDassoIDMCTRUTH)
2250   {
2251  //Fill Correlations for MC truth particles(same event)
2252 if(tracksMCtruth && tracksMCtruth->GetEntriesFast()>0)//hadron triggered correlation
2253   Fillcorrelation(gReactionPlane,tracksMCtruth,0,cent_v0,zVtxmc,weghtval,kFALSE,bSign,fPtOrderMCTruth,kFALSE,kFALSE,"trigIDassoIDMCTRUTH");//mixcase=kFALSE for same event case
2254
2255 //start mixing
2256  AliEventPool* pool2 = fPoolMgr->GetEventPool(cent_v0, zVtxmc+200, gReactionPlane);
2257 if (pool2 && pool2->IsReady())
2258   {//start mixing only when pool->IsReady
2259 if(tracksMCtruth && tracksMCtruth->GetEntriesFast()>0)
2260   {//proceed only when no. of trigger particles >0 in current event
2261     Float_t nmix=(Float_t)pool2->GetCurrentNEvents();  
2262 for (Int_t jMix=0; jMix<pool2->GetCurrentNEvents(); jMix++) 
2263   { //pool event loop start
2264  TObjArray* bgTracks6 = pool2->GetEvent(jMix);
2265   if(!bgTracks6) continue;
2266   Fillcorrelation(gReactionPlane,tracksMCtruth,bgTracks6,cent_v0,zVtxmc,nmix,(jMix == 0),bSign,fPtOrderMCTruth,kFALSE,kTRUE,"trigIDassoIDMCTRUTH");//mixcase=kTRUE for mixing case
2267   
2268    }// pool event loop ends mixing case
2269  }//if(trackstrig && trackstrig->GetEntriesFast()>0) condition ends mixing case
2270 } //if pool->IsReady() condition ends mixing case
2271
2272  //still in main event loop
2273
2274  if(tracksMCtruth){
2275 if(pool2)  pool2->UpdatePool(CloneAndReduceTrackList(tracksMCtruth));//ownership of tracksasso is with pool now, don't delete it
2276  }
2277   }
2278
2279  //still in main event loop
2280
2281 if(tracksMCtruth) delete tracksMCtruth;
2282
2283 //now deal with reco tracks
2284
2285
2286 //Float_t bSign1=aod->GetHeader()->GetMagneticField() ;//used for reconstructed track dca cut
2287    Float_t bSign1=aod->GetMagneticField() ;//used for reconstructed track dca cut
2288
2289
2290 //detrmine the ref mult in case of Reco(not required if we get centrality info from AliCentrality)
2291  if (fSampleType=="pp_2_76" || fCentralityMethod.EndsWith("_MANUAL") || (fSampleType=="pp_7" && fPPVsMultUtils==kFALSE)) cent_v0=refmultReco;
2292  effcent=cent_v0;// This will be required for efficiency THn filling(specially in case of pp)
2293
2294  if(fRequestEventPlane){
2295    gReactionPlane = GetEventPlane((AliVEvent*)aod,kFALSE,cent_v0);//get the reconstructed event plane
2296     if(gReactionPlane==999.) return;
2297  }
2298
2299
2300   TExMap *trackMap = new TExMap();
2301
2302 // --- track loop for mapping matrix
2303  if(fFilterBit==128)
2304    {
2305  for (Int_t itrk = 0; itrk < aod->GetNumberOfTracks(); itrk++) 
2306 { //track loop starts for TObjArray(containing track and event information) filling; used for correlation function calculation 
2307   AliAODTrack* track = dynamic_cast<AliAODTrack*>(aod->GetTrack(itrk));
2308   if (!track) continue;
2309   Int_t tracktype=ClassifyTrack(track,trkVtx,bSign1,kFALSE);//don't fill the histos here
2310   if(tracktype!=1) continue; 
2311
2312   if(!track) continue;//for safety
2313
2314    Int_t gid = track->GetID();
2315    trackMap->Add(gid,itrk);
2316  }//track looop ends
2317    }
2318
2319
2320   
2321    //TObjArray* tracksUNID=0;
2322    TObjArray* tracksUNID = new TObjArray;
2323    tracksUNID->SetOwner(kTRUE);
2324
2325    //TObjArray* tracksID=0;
2326    TObjArray* tracksID = new TObjArray;
2327    tracksID->SetOwner(kTRUE);
2328
2329
2330 //get the selected v0 particle TObjArray
2331    TObjArray* tracksIDV0 = new TObjArray;
2332    tracksIDV0->SetOwner(kTRUE);
2333
2334    Double_t trackscount=0.0;
2335 // loop over reconstructed tracks 
2336   for (Int_t itrk = 0; itrk < aod->GetNumberOfTracks(); itrk++) 
2337 { // reconstructed track loop starts
2338   AliAODTrack* track = dynamic_cast<AliAODTrack*>(aod->GetTrack(itrk));
2339   if (!track) continue;
2340  //get the corresponding MC track at the truth level (doing reco matching)
2341   AliAODMCParticle* recomatched = static_cast<AliAODMCParticle*>(fArrayMC->At(TMath::Abs(track->GetLabel())));
2342   if(!recomatched) continue;//if a reco track doesn't have corresponding truth track at generated level is a fake track(label==0), ignore it
2343
2344 //remove injected signals 
2345  if(fInjectedSignals)
2346    {
2347     AliAODMCParticle* mother = recomatched;
2348
2349       while (!mother->IsPhysicalPrimary())
2350       {// find the primary mother;the first stable mother is searched and checked if it is <= <maxLabel>
2351         if (mother->GetMother() < 0)
2352         {
2353           mother = 0;
2354           break;
2355         }
2356           
2357    mother =(AliAODMCParticle*) fArrayMC->At(((AliAODMCParticle*)mother)->GetMother());
2358         if (!mother)
2359           break;
2360       }
2361  if (!mother)
2362     {
2363       Printf("WARNING: No mother found for particle %d:", recomatched->GetLabel());
2364       continue;
2365     }
2366  if (mother->GetLabel() >= skipParticlesAbove) continue;//remove injected signals(primaries above <maxLabel>)
2367    }//remove injected signals
2368
2369  if (fRemoveWeakDecays && ((AliAODMCParticle*) recomatched)->IsSecondaryFromWeakDecay()) continue;//remove weak decays
2370         
2371   Bool_t isduplicate2=kFALSE;
2372 if (fRemoveDuplicates)
2373    {
2374   for (Int_t j =itrk+1; j < aod->GetNumberOfTracks(); j++) 
2375     {//2nd loop starts
2376  AliAODTrack* track2 = dynamic_cast<AliAODTrack*>(aod->GetTrack(j));
2377  if (!track2) continue;
2378  AliAODMCParticle* recomatched2 = static_cast<AliAODMCParticle*>(fArrayMC->At(TMath::Abs(track2->GetLabel())));
2379 if(!recomatched2) continue;
2380
2381 if (track->GetLabel() == track2->GetLabel())
2382    {
2383 isduplicate2=kTRUE;
2384  break;  
2385    }
2386     }//2nd loop ends
2387    }
2388  if(fRemoveDuplicates && isduplicate2) continue;//remove duplicates
2389      
2390   fHistQA[11]->Fill(track->GetTPCNcls());
2391   Int_t tracktype=ClassifyTrack(track,trkVtx,bSign1,kTRUE);//dcacut=kFALSE,onlyprimary=kFALSE
2392
2393  if(tracktype==0) continue; 
2394  if(tracktype==1)//tracks "not" passed AliAODTrack::kPrimary at reconstructed level & have proper TPC PID response(?)
2395 {
2396   if(!track) continue;//for safety
2397  //accepted all(primaries+secondary) reconstructed tracks(pt 0.2 to 10.0,,eta -0.8 to 0.8)
2398
2399  if(fV0TrigCorr){ 
2400 if(IsTrackFromV0(aod,track)) continue;// remove auto correlation
2401   }
2402
2403   AliAODTrack *PIDtrack=track;//for PID purpose, mainly important for TPC only tracks
2404
2405   if(fFilterBit==128){
2406 Int_t gid1 = track->GetID();
2407 //if(gid1>=0) PIDtrack = track;
2408  PIDtrack =(AliAODTrack*) aod->GetTrack(trackMap->GetValue(-1-gid1));
2409 if(!PIDtrack) continue;//for safety; so that each of the TPC only tracks have corresponding global track along with it
2410   }
2411
2412   trackscount++;
2413
2414 //check for eta , phi holes
2415  fEtaSpectrasso->Fill(track->Eta(),track->Pt());
2416  fphiSpectraasso->Fill(track->Phi(),track->Pt());
2417
2418   Int_t particletypeMC=-9999;
2419
2420 //tag all particles as unidentified
2421  particletypeMC=unidentified;
2422
2423  Float_t effmatrix=1.;
2424
2425 // -- Fill THnSparse for efficiency calculation
2426  if (fSampleType=="pp_2_76" || fCentralityMethod.EndsWith("_MANUAL") || (fSampleType=="pp_7" && fPPVsMultUtils==kFALSE)) effcent=15.0;//integrated over multiplicity(so put any fixed value for each track so that practically means there is only one bin in multiplicity i.e. multiplicity intregated out )**************Important
2427  //NOTE:: this will be used for fillinfg THnSparse of efficiency & also to get the the track by track eff. factor on the fly(only in case of pp)
2428
2429  //Clone & Reduce track list(TObjArray) for unidentified particles
2430 if((track->Pt()>=fminPtAsso && track->Pt()<=fmaxPtAsso) || (track->Pt()>=fminPtTrig && track->Pt()<=fmaxPtTrig))//to reduce memory consumption in pool
2431   {
2432      Short_t chargeval=0;
2433     if(track->Charge()>0)   chargeval=1;
2434     if(track->Charge()<0)   chargeval=-1;
2435     if(chargeval==0) continue;
2436  if (fapplyTrigefficiency || fapplyAssoefficiency)//get the trackingefficiency x contamination factor for unidentified particles
2437    effmatrix=GetTrackbyTrackeffvalue(track,effcent,zvtx,particletypeMC);
2438  LRCParticlePID* copy = new LRCParticlePID(particletypeMC,Inv_mass,chargeval,track->Pt(),track->Eta(), track->Phi(),effmatrix,track->GetTPCClusterMapPtr(),track->GetTPCSharedMapPtr());
2439    copy->SetUniqueID(eventno * 100000 +(Int_t)trackscount);
2440    tracksUNID->Add(copy);//track information Storage for UNID correlation function(tracks that pass the filterbit & kinematic cuts only)
2441   }
2442
2443 //get the pdg code of the corresponding truth particle
2444  Int_t pdgCode = ((AliAODMCParticle*)recomatched)->GetPdgCode();
2445
2446  Double_t allrecomatchedpid[4] = {effcent, zVtxmc,recomatched->Pt(), recomatched->Eta()};
2447  if(ffillefficiency) {
2448 fTrackHistEfficiency[5]->Fill(allrecomatchedpid,2);//for allreco matched
2449  if(TMath::Abs(pdgCode)==211 ||  TMath::Abs(pdgCode)==321)   fTrackHistEfficiency[3]->Fill(allrecomatchedpid,2);//for mesons
2450  if(TMath::Abs(pdgCode)==321 ||  TMath::Abs(pdgCode)==2212)   fTrackHistEfficiency[4]->Fill(allrecomatchedpid,2);//for kaons+protons
2451  if(TMath::Abs(pdgCode)==211)  fTrackHistEfficiency[0]->Fill(allrecomatchedpid,2);//for pions  
2452  if(TMath::Abs(pdgCode)==321)  fTrackHistEfficiency[1]->Fill(allrecomatchedpid,2);//for kaons
2453  if(TMath::Abs(pdgCode)==2212) fTrackHistEfficiency[2]->Fill(allrecomatchedpid,2);//for protons
2454
2455  if (((AliAODMCParticle*)recomatched)->IsPhysicalPrimary()) {
2456  fTrackHistEfficiency[5]->Fill(allrecomatchedpid,1);//for primreco matched
2457  if(TMath::Abs(pdgCode)==211 ||  TMath::Abs(pdgCode)==321)   fTrackHistEfficiency[3]->Fill(allrecomatchedpid,1);//for mesons
2458  if(TMath::Abs(pdgCode)==321 ||  TMath::Abs(pdgCode)==2212)   fTrackHistEfficiency[4]->Fill(allrecomatchedpid,1);//for kaons+protons
2459  if( TMath::Abs(pdgCode)==211)  fTrackHistEfficiency[0]->Fill(allrecomatchedpid,1);//for pions  
2460  if( TMath::Abs(pdgCode)==321)  fTrackHistEfficiency[1]->Fill(allrecomatchedpid,1);//for kaons
2461  if( TMath::Abs(pdgCode)==2212) fTrackHistEfficiency[2]->Fill(allrecomatchedpid,1);//for protons
2462  }
2463  }
2464
2465 switch(TMath::Abs(pdgCode)){
2466   case 2212:
2467     if(fFIllPIDQAHistos){
2468       for(Int_t ipid=0;ipid<=NSigmaPIDType;ipid++){
2469         if((ipid!=NSigmaTPC) && (!HasTOFPID(PIDtrack)))continue;//not filling TOF and combined if no TOF PID
2470         TH2F *h=GetHistogram2D(Form("NSigmaMC_%d_%d",SpProton,ipid));
2471         h->Fill(track->Pt(),fnsigmas[SpProton][ipid]);
2472       }
2473     }
2474     break;
2475   case 321:
2476     if(fFIllPIDQAHistos){
2477       for(Int_t ipid=0;ipid<=NSigmaPIDType;ipid++){
2478         if((ipid!=NSigmaTPC) && (!HasTOFPID(PIDtrack)))continue;//not filling TOF and combined if no TOF PID
2479         TH2F *h=GetHistogram2D(Form("NSigmaMC_%d_%d",SpKaon,ipid));
2480         h->Fill(track->Pt(),fnsigmas[SpKaon][ipid]);
2481       }
2482     }
2483     break;
2484   case 211:
2485     if(fFIllPIDQAHistos){
2486       for(Int_t ipid=0;ipid<=NSigmaPIDType;ipid++){
2487         if((ipid!=NSigmaTPC) && (!HasTOFPID(PIDtrack)))continue;//not filling TOF and combined if no TOF PID
2488         TH2F *h=GetHistogram2D(Form("NSigmaMC_%d_%d",SpPion,ipid));
2489         h->Fill(track->Pt(),fnsigmas[SpPion][ipid]);
2490       }
2491     }
2492     break;
2493   }
2494
2495
2496  //now start the particle identification process:)
2497
2498 Float_t dEdx = PIDtrack->GetTPCsignal();
2499  fHistoTPCdEdx->Fill(track->Pt(), dEdx);
2500
2501  if(HasTOFPID(PIDtrack))
2502 {
2503 Double_t beta = GetBeta(PIDtrack);
2504 fHistoTOFbeta->Fill(track->Pt(), beta);
2505  }
2506
2507  //remove the tracks which don't have proper TOF response-otherwise the misIDentification rate values will be wrong
2508 if(fRequestTOFPID && track->Pt()>fPtTOFPIDmin && (!HasTOFPID(PIDtrack)) ) continue;
2509  
2510
2511 //do track identification(nsigma method)
2512   particletypeMC=GetParticle(PIDtrack,fFIllPIDQAHistos);//******************************problem is here
2513
2514 //2-d TPCTOF map(for each Pt interval)
2515   if(HasTOFPID(PIDtrack)){
2516  fTPCTOFPion3d->Fill(track->Pt(),fnsigmas[SpPion][NSigmaTOF],fnsigmas[SpPion][NSigmaTPC]);
2517  fTPCTOFKaon3d->Fill(track->Pt(),fnsigmas[SpKaon][NSigmaTOF],fnsigmas[SpKaon][NSigmaTPC]);
2518  fTPCTOFProton3d->Fill(track->Pt(),fnsigmas[SpProton][NSigmaTOF],fnsigmas[SpProton][NSigmaTPC]); 
2519   }
2520
2521  //Pt, Eta , Phi distribution of the reconstructed identified particles
2522 if(ffillhistQAReco)
2523     {
2524 if (particletypeMC==SpPion)
2525   {
2526     fPionPt->Fill(track->Pt());
2527     fPionEta->Fill(track->Eta());
2528     fPionPhi->Fill(track->Phi());
2529   }
2530 if (particletypeMC==SpKaon)
2531   {
2532     fKaonPt->Fill(track->Pt());
2533     fKaonEta->Fill(track->Eta());
2534     fKaonPhi->Fill(track->Phi());
2535   }
2536 if (particletypeMC==SpProton)
2537   {
2538     fProtonPt->Fill(track->Pt());
2539     fProtonEta->Fill(track->Eta());
2540     fProtonPhi->Fill(track->Phi());
2541   }
2542     }
2543
2544  //fill tracking efficiency
2545  if(ffillefficiency)
2546    {
2547  if(particletypeMC==SpPion || particletypeMC==SpKaon)
2548    {
2549      if(TMath::Abs(pdgCode)==211 ||  TMath::Abs(pdgCode)==321) {
2550        fTrackHistEfficiency[3]->Fill(allrecomatchedpid,4);//for mesons
2551  if (((AliAODMCParticle*)recomatched)->IsPhysicalPrimary())  fTrackHistEfficiency[3]->Fill(allrecomatchedpid,3);//for mesons
2552      }
2553    }
2554  if(particletypeMC==SpKaon || particletypeMC==SpProton)
2555    {
2556      if(TMath::Abs(pdgCode)==321 ||  TMath::Abs(pdgCode)==2212) {
2557        fTrackHistEfficiency[4]->Fill(allrecomatchedpid,4);//for kaons+protons
2558  if (((AliAODMCParticle*)recomatched)->IsPhysicalPrimary())  fTrackHistEfficiency[4]->Fill(allrecomatchedpid,3);
2559      }
2560    }
2561  if(particletypeMC==SpPion && TMath::Abs(pdgCode)==211)  {
2562    fTrackHistEfficiency[0]->Fill(allrecomatchedpid,4);//for pions
2563  if (((AliAODMCParticle*)recomatched)->IsPhysicalPrimary())  fTrackHistEfficiency[0]->Fill(allrecomatchedpid,3);
2564  } 
2565  if(particletypeMC==SpKaon && TMath::Abs(pdgCode)==321) {
2566    fTrackHistEfficiency[1]->Fill(allrecomatchedpid,4);//for kaons
2567 if (((AliAODMCParticle*)recomatched)->IsPhysicalPrimary())  fTrackHistEfficiency[1]->Fill(allrecomatchedpid,3);
2568  }
2569  if(particletypeMC==SpProton && TMath::Abs(pdgCode)==2212){
2570    fTrackHistEfficiency[2]->Fill(allrecomatchedpid,4);//for protons
2571 if (((AliAODMCParticle*)recomatched)->IsPhysicalPrimary())  fTrackHistEfficiency[2]->Fill(allrecomatchedpid,3);
2572  }
2573    }
2574
2575
2576  //for misidentification fraction calculation(do it with tuneonPID)
2577  if(particletypeMC==SpPion )
2578    {
2579      if(TMath::Abs(pdgCode)==211) fPioncont->Fill(1.,track->Pt());
2580      if(TMath::Abs(pdgCode)==321) fPioncont->Fill(3.,track->Pt());
2581      if(TMath::Abs(pdgCode)==2212) fPioncont->Fill(5.,track->Pt());
2582      if(TMath::Abs(pdgCode)!=211 && TMath::Abs(pdgCode)!=321 && TMath::Abs(pdgCode)!=2212) fPioncont->Fill(7.,track->Pt());
2583    }
2584 if(particletypeMC==SpKaon )
2585    {
2586      if(TMath::Abs(pdgCode)==211) fKaoncont->Fill(1.,track->Pt());
2587      if(TMath::Abs(pdgCode)==321) fKaoncont->Fill(3.,track->Pt());
2588      if(TMath::Abs(pdgCode)==2212) fKaoncont->Fill(5.,track->Pt());
2589      if(TMath::Abs(pdgCode)!=211 && TMath::Abs(pdgCode)!=321 && TMath::Abs(pdgCode)!=2212) fKaoncont->Fill(7.,track->Pt());
2590    }
2591  if(particletypeMC==SpProton )
2592    {
2593      if(TMath::Abs(pdgCode)==211) fProtoncont->Fill(1.,track->Pt());
2594      if(TMath::Abs(pdgCode)==321) fProtoncont->Fill(3.,track->Pt());
2595      if(TMath::Abs(pdgCode)==2212) fProtoncont->Fill(5.,track->Pt());
2596      if(TMath::Abs(pdgCode)!=211 && TMath::Abs(pdgCode)!=321 && TMath::Abs(pdgCode)!=2212) fProtoncont->Fill(7.,track->Pt());
2597    }
2598  if(particletypeMC==SpUndefined )//these undefined are not due to absence of proper TOF response, rather due to the PID method only
2599    {
2600      if(TMath::Abs(pdgCode)==211) fUNIDcont->Fill(1.,track->Pt());
2601      if(TMath::Abs(pdgCode)==321) fUNIDcont->Fill(3.,track->Pt());
2602      if(TMath::Abs(pdgCode)==2212) fUNIDcont->Fill(5.,track->Pt());
2603      if(TMath::Abs(pdgCode)!=211 && TMath::Abs(pdgCode)!=321 && TMath::Abs(pdgCode)!=2212) fUNIDcont->Fill(7.,track->Pt());
2604    }
2605
2606  if(particletypeMC==SpUndefined) continue;
2607
2608     if(fRequestEventPlane){
2609       FillPIDEventPlane(cent_v0,particletypeMC,track->Phi(),gReactionPlane);
2610     }
2611
2612 if((track->Pt()>=fminPtAsso && track->Pt()<=fmaxPtAsso) || (track->Pt()>=fminPtTrig && track->Pt()<=fmaxPtTrig))//to reduce memory consumption in pool
2613   {
2614     Short_t chargeval=0;
2615     if(track->Charge()>0)   chargeval=1;
2616     if(track->Charge()<0)   chargeval=-1;
2617     if(chargeval==0) continue;
2618 if (fapplyTrigefficiency || fapplyAssoefficiency)
2619     effmatrix=GetTrackbyTrackeffvalue(track,effcent,zvtx,particletypeMC);//get the tracking eff x TOF matching eff x PID eff x contamination factor for identified particles 
2620  LRCParticlePID* copy1 = new LRCParticlePID(particletypeMC,Inv_mass,chargeval,track->Pt(),track->Eta(), track->Phi(),effmatrix,track->GetTPCClusterMapPtr(),track->GetTPCSharedMapPtr());
2621     copy1->SetUniqueID(eventno * 100000 + (Int_t)trackscount);
2622     tracksID->Add(copy1);
2623   }
2624   }// if(tracktype==1) condition structure ands
2625
2626 }//reco track loop ends
2627
2628   //*************************************************************still in event loop
2629  
2630
2631 if(trackscount>0.0)
2632   { 
2633 //fill the centrality/multiplicity distribution of the selected events
2634  fhistcentrality->Fill(cent_v0);//*********************************WARNING::binning of cent_v0 is different for pp and pPb/PbPb case
2635
2636  if (fSampleType=="pPb" || fSampleType=="PbPb" || fPPVsMultUtils==kTRUE || fCentralityMethod == "MC_b") fCentralityCorrelation->Fill(cent_v0, trackscount);//only with unidentified tracks(i.e before PID selection);;;;;can be used to remove centrality outliers??????
2637
2638 //count selected events having centrality betn 0-100%
2639  fEventCounter->Fill(13);
2640
2641 //***************************************event no. counting
2642 Bool_t isbaryontrig=kFALSE;
2643 Bool_t ismesontrig=kFALSE;
2644 if(tracksUNID && tracksUNID->GetEntriesFast()>0) fEventno->Fill(cent_v0,zvtx);
2645
2646 if(tracksID && tracksID->GetEntriesFast()>0)
2647   {
2648 for(Int_t i=0;i<tracksID->GetEntriesFast();i++)
2649     {  //trigger loop starts
2650       LRCParticlePID *trig=(LRCParticlePID*)(tracksID->UncheckedAt(i));
2651       if(!trig) continue;
2652       if(trig->Pt()<fminPtTrig || trig->Pt()>fmaxPtTrig) continue;
2653       Int_t particlepidtrig=trig->getparticle(); //either 1 or 2
2654       if(particlepidtrig==SpProton) isbaryontrig=kTRUE;
2655       if(particlepidtrig==SpPion) ismesontrig=kTRUE;
2656     }//trig loop ends
2657  if (isbaryontrig) fEventnobaryon->Fill(cent_v0,zvtx); 
2658  if (ismesontrig) fEventnomeson->Fill(cent_v0,zvtx);
2659   }
2660
2661
2662  if(fV0TrigCorr){
2663  tracksIDV0=GetV0Particles((AliVEvent*) aod, cent_v0);
2664  if(tracksIDV0->GetEntriesFast()<=0) return;
2665  }
2666  //same event delte-eta, delta-phi plot
2667 if(tracksUNID && tracksUNID->GetEntriesFast()>0)//hadron triggered correlation
2668   {//same event calculation starts
2669     if(ffilltrigassoUNID) Fillcorrelation(gReactionPlane,tracksUNID,0,cent_v0,zvtx,weghtval,kFALSE,bSign,fPtOrderDataReco,ftwoTrackEfficiencyCutDataReco,kFALSE,"trigassoUNID");//mixcase=kFALSE (hadron-hadron correlation)
2670     if(tracksID && tracksID->GetEntriesFast()>0 && ffilltrigUNIDassoID)  Fillcorrelation(gReactionPlane,tracksUNID,tracksID,cent_v0,zvtx,weghtval,kFALSE,bSign,fPtOrderDataReco,ftwoTrackEfficiencyCutDataReco,kFALSE,"trigUNIDassoID");//mixcase=kFALSE (hadron-ID correlation)
2671   }
2672
2673 if(tracksID && tracksID->GetEntriesFast()>0)//ID triggered correlation
2674   {//same event calculation starts
2675     if(tracksUNID && tracksUNID->GetEntriesFast()>0 && ffilltrigIDassoUNID) {
2676       if(fV0TrigCorr) Fillcorrelation(gReactionPlane,tracksIDV0,tracksUNID,cent_v0,zvtx,weghtval,kFALSE,bSign,fPtOrderDataReco,ftwoTrackEfficiencyCutDataReco,kFALSE,"trigIDassoUNID");//mixcase=kFALSE (ID-hadron correlation)
2677       
2678  else Fillcorrelation(gReactionPlane,tracksID,tracksUNID,cent_v0,zvtx,weghtval,kFALSE,bSign,fPtOrderDataReco,ftwoTrackEfficiencyCutDataReco,kFALSE,"trigIDassoUNID");//mixcase=kFALSE (ID-hadron correlation)
2679     }
2680     if(ffilltrigIDassoID)   Fillcorrelation(gReactionPlane,tracksID,0,cent_v0,zvtx,weghtval,kFALSE,bSign,fPtOrderDataReco,ftwoTrackEfficiencyCutDataReco,kFALSE,"trigIDassoID");//mixcase=kFALSE (ID-ID correlation)
2681   }
2682
2683 //still in  main event loop
2684 //start mixing
2685  if(ffilltrigassoUNID || ffilltrigIDassoUNID){//mixing with unidentified particles
2686   AliEventPool* pool = fPoolMgr->GetEventPool(cent_v0, zvtx,gReactionPlane);//In the pool there is tracksUNID(i.e associateds are unidentified)
2687 if (pool && pool->IsReady())
2688   {//start mixing only when pool->IsReady
2689     Float_t nmix1=(Float_t)pool->GetCurrentNEvents();  
2690  for (Int_t jMix=0; jMix<pool->GetCurrentNEvents(); jMix++) 
2691   { //pool event loop start
2692  TObjArray* bgTracks = pool->GetEvent(jMix);
2693   if(!bgTracks) continue;
2694   if(ffilltrigassoUNID && tracksUNID && tracksUNID->GetEntriesFast()>0)//*******************************hadron trggered mixing
2695     Fillcorrelation(gReactionPlane,tracksUNID,bgTracks,cent_v0,zvtx,nmix1,(jMix == 0),bSign,fPtOrderDataReco,ftwoTrackEfficiencyCutDataReco,kTRUE,"trigassoUNID");//mixcase=kTRUE
2696  if(ffilltrigIDassoUNID && tracksID && tracksID->GetEntriesFast()>0)//***********************************ID trggered mixing
2697    {
2698      if(fV0TrigCorr) Fillcorrelation(gReactionPlane,tracksIDV0,bgTracks,cent_v0,zvtx,nmix1,(jMix == 0),bSign,fPtOrderDataReco,ftwoTrackEfficiencyCutDataReco,kTRUE,"trigIDassoUNID");//mixcase=kTRUE 
2699      
2700  else  Fillcorrelation(gReactionPlane,tracksID,bgTracks,cent_v0,zvtx,nmix1,(jMix == 0),bSign,fPtOrderDataReco,ftwoTrackEfficiencyCutDataReco,kTRUE,"trigIDassoUNID");//mixcase=kTRUE 
2701    }
2702    }// pool event loop ends mixing case
2703
2704 } //if pool->IsReady() condition ends mixing case
2705  if(tracksUNID) {
2706 if(pool)
2707   pool->UpdatePool(CloneAndReduceTrackList(tracksUNID));
2708  }
2709  }//mixing with unidentified particles
2710
2711  if(ffilltrigUNIDassoID || ffilltrigIDassoID){//mixing with identified particles
2712   AliEventPool* pool1 = fPoolMgr->GetEventPool(cent_v0, zvtx+100,gReactionPlane);//In the pool1 there is tracksID(i.e associateds are identified)
2713 if (pool1 && pool1->IsReady())
2714   {//start mixing only when pool->IsReady
2715   Float_t nmix2=(Float_t)pool1->GetCurrentNEvents();  
2716 for (Int_t jMix=0; jMix<pool1->GetCurrentNEvents(); jMix++) 
2717   { //pool event loop start
2718  TObjArray* bgTracks2 = pool1->GetEvent(jMix);
2719   if(!bgTracks2) continue;
2720 if(ffilltrigUNIDassoID && tracksUNID && tracksUNID->GetEntriesFast()>0)
2721   Fillcorrelation(gReactionPlane,tracksUNID,bgTracks2,cent_v0,zvtx,nmix2,(jMix == 0),bSign,fPtOrderDataReco,ftwoTrackEfficiencyCutDataReco,kTRUE,"trigUNIDassoID");//mixcase=kTRUE  
2722 if(ffilltrigIDassoID && tracksID && tracksID->GetEntriesFast()>0)
2723   Fillcorrelation(gReactionPlane,tracksID,bgTracks2,cent_v0,zvtx,nmix2,(jMix == 0),bSign,fPtOrderDataReco,ftwoTrackEfficiencyCutDataReco,kTRUE,"trigIDassoID");//mixcase=kTRUE
2724
2725    }// pool event loop ends mixing case
2726 } //if pool1->IsReady() condition ends mixing case
2727
2728 if(tracksID) {
2729 if(pool1) 
2730   pool1->UpdatePool(CloneAndReduceTrackList(tracksID));//ownership of tracksasso is with pool now, don't delete it(tracksUNID is with pool)
2731  }
2732  }//mixing with identified particles
2733
2734   //no. of events analyzed
2735 fEventCounter->Fill(15);
2736   }
2737
2738 if(tracksUNID)  delete tracksUNID;
2739
2740 if(tracksID) delete tracksID;
2741 if(fV0TrigCorr) {
2742   if(tracksIDV0) delete tracksIDV0;
2743   }
2744
2745
2746 }//AOD || MCAOD condition
2747
2748 //still in the main event loop
2749
2750 }
2751 //________________________________________________________________________
2752 void AliTwoParticlePIDCorr::doAODevent() 
2753 {
2754
2755   //get AOD
2756   AliVEvent *event = InputEvent();
2757   if (!event) { Printf("ERROR: Could not retrieve event"); return; }
2758   AliAODEvent* aod = dynamic_cast<AliAODEvent*>(event);
2759   if (!aod) {
2760     AliError("Cannot get the AOD event");
2761     return;
2762   }
2763   Double_t Inv_mass=0.0;
2764
2765 // count all events   
2766   fEventCounter->Fill(1);
2767
2768    fPID = ((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->GetPIDResponse();
2769     if (!fPID) AliFatal("This Task needs the PID response attached to the inputHandler");
2770     //if (!fPID) return;//this should be available with each event even if we don't do PID selection
2771
2772     fgPsi2v0a=999.;
2773     fgPsi2v0c=999.;
2774     fgPsi2tpc=999.;
2775     fgPsi3v0a=999.;
2776     fgPsi3v0c=999.;
2777     fgPsi3tpc=999.;
2778     gReactionPlane = 999.;
2779     
2780   Double_t cent_v0=   -999.;
2781   Double_t effcent=1.0;
2782   Float_t bSign = 0.;
2783   Double_t trackscount=0;//counts particles passed filterbit cuts and kinematic cuts used in this analysis
2784
2785
2786  bSign = (aod->GetMagneticField() > 0) ? 1 : -1;//for two track efficiency cut in correlation function calculation
2787  Float_t bSign1=aod->GetMagneticField() ;//for dca cut in ClassifyTrack(), i.e in track loop
2788
2789
2790 // check event cuts and fill event histograms and return the centrality or reference multiplicity value
2791  if((cent_v0 = GetAcceptedEventMultiplicity((AliVEvent*)aod,kFALSE)) < 0){ 
2792     return;
2793   }
2794  effcent=cent_v0;//required for efficiency correction case********Extremely Important
2795   //get the event plane in case of PbPb
2796     if(fRequestEventPlane){
2797       gReactionPlane = GetEventPlane((AliVEvent*)aod,kFALSE,cent_v0);
2798     if(gReactionPlane==999.) return;
2799     }    
2800     
2801
2802 TExMap *trackMap = new TExMap();
2803 // --- track loop for mapping matrix
2804  if(fFilterBit==128)
2805    {
2806  for (Int_t itrk = 0; itrk < aod->GetNumberOfTracks(); itrk++) 
2807 { //track loop starts for TObjArray(containing track and event information) filling; used for correlation function calculation 
2808   AliAODTrack* track = dynamic_cast<AliAODTrack*>(aod->GetTrack(itrk));
2809   if (!track) continue;
2810   Int_t tracktype=ClassifyTrack(track,trkVtx,bSign1,kFALSE);//don't fill the histos here
2811   if(tracktype!=1) continue; 
2812
2813   if(!track) continue;//for safety
2814
2815    Int_t gid = track->GetID();
2816    trackMap->Add(gid,itrk);
2817  }//track looop ends
2818    }
2819
2820    TObjArray*  tracksUNID= new TObjArray;//track info before doing PID
2821    tracksUNID->SetOwner(kTRUE);  // IMPORTANT!
2822
2823    TObjArray* tracksID= new TObjArray;//only pions, kaons,protons i.e. after doing the PID selection
2824    tracksID->SetOwner(kTRUE);  // IMPORTANT!
2825  
2826    //get the selected v0 particle TObjArray
2827    TObjArray*  tracksIDV0= new TObjArray;
2828    tracksIDV0->SetOwner(kTRUE);  // IMPORTANT!
2829     
2830     eventno++;
2831
2832     Bool_t fTrigPtmin1=kFALSE;
2833     Bool_t fTrigPtmin2=kFALSE;
2834     Bool_t fTrigPtJet=kFALSE;
2835
2836  for (Int_t itrk = 0; itrk < aod->GetNumberOfTracks(); itrk++) 
2837 { //track loop starts for TObjArray(containing track and event information) filling; used for correlation function calculation 
2838   AliAODTrack* track = dynamic_cast<AliAODTrack*>(aod->GetTrack(itrk));
2839   if (!track) continue;
2840   fHistQA[11]->Fill(track->GetTPCNcls());
2841   Int_t particletype=-9999;//required for PID filling
2842   Int_t tracktype=ClassifyTrack(track,trkVtx,bSign1,kTRUE);//dcacut=kFALSE,onlyprimary=kFALSE
2843   if(tracktype!=1) continue; 
2844
2845   if(!track) continue;//for safety
2846
2847   if(fV0TrigCorr){ 
2848 if(IsTrackFromV0(aod,track)) continue;// remove auto correlation
2849   }
2850 AliAODTrack *PIDtrack=track;//for PID purpose, mainly important for TPC only tracks
2851
2852   if(fFilterBit==128){
2853 Int_t gid1 = track->GetID();
2854 //if(gid1>=0) PIDtrack = track;
2855  PIDtrack =(AliAODTrack*) aod->GetTrack(trackMap->GetValue(-1-gid1));
2856 if(!PIDtrack) continue;//for safety; so that each of the TPC only tracks have corresponding global track along with it
2857   }
2858
2859 //check for eta , phi holes
2860  fEtaSpectrasso->Fill(track->Eta(),track->Pt());
2861  fphiSpectraasso->Fill(track->Phi(),track->Pt());
2862
2863  trackscount++;
2864
2865  //if no applyefficiency , set the eff factor=1.0
2866  Float_t effmatrix=1.0;
2867
2868  //tag all particles as unidentified that passed filterbit & kinematic cuts 
2869  particletype=unidentified;
2870
2871  //To count the no. of tracks having an accepted track in a certain PT(e.g. Jet Pt) range
2872  if(track->Pt()>=fminPtTrig) fTrigPtmin1=kTRUE;
2873  if(track->Pt()>=(fminPtTrig+0.5)) fTrigPtmin2=kTRUE;
2874  if(track->Pt()>=fmaxPtTrig) fTrigPtJet=kTRUE;
2875
2876
2877 if (fSampleType=="pp_2_76" || fCentralityMethod.EndsWith("_MANUAL") || (fSampleType=="pp_7" && fPPVsMultUtils==kFALSE)) effcent=15.0;//integrated over multiplicity [i.e each track has multiplicity 15.0](so put any fixed value for each track so that practically means there is only one bin in multiplicityi.e multiplicity intregated out )**************Important for efficiency related issues
2878
2879
2880  //to reduce memory consumption in pool
2881   if((track->Pt()>=fminPtAsso && track->Pt()<=fmaxPtAsso) || (track->Pt()>=fminPtTrig && track->Pt()<=fmaxPtTrig)) 
2882   {
2883  //Clone & Reduce track list(TObjArray) for unidentified particles
2884     Short_t chargeval=0;
2885     if(track->Charge()>0)   chargeval=1;
2886     if(track->Charge()<0)   chargeval=-1;
2887     if(chargeval==0) continue;
2888  if (fapplyTrigefficiency || fapplyAssoefficiency)//get the trackingefficiency x contamination factor for unidentified particles
2889    effmatrix=GetTrackbyTrackeffvalue(track,effcent,zvtx,particletype);
2890  LRCParticlePID* copy = new LRCParticlePID(particletype,Inv_mass,chargeval,track->Pt(),track->Eta(), track->Phi(),effmatrix,track->GetTPCClusterMapPtr(),track->GetTPCSharedMapPtr());
2891   copy->SetUniqueID(eventno * 100000 + (Int_t)trackscount);
2892   tracksUNID->Add(copy);//track information Storage for UNID correlation function(tracks that pass the filterbit & kinematic cuts only)
2893   }
2894
2895 //now start the particle identificaion process:) 
2896
2897 //track passing filterbit 768 have proper TPC response,or need to be checked explicitly before doing PID????
2898
2899   Float_t dEdx = PIDtrack->GetTPCsignal();
2900   fHistoTPCdEdx->Fill(track->Pt(), dEdx);
2901
2902   //fill beta vs Pt plots only for tracks having proper TOF response(much less tracks compared to the no. that pass the filterbit & kinematic cuts)
2903  if(HasTOFPID(PIDtrack))
2904 {
2905   Double_t beta = GetBeta(PIDtrack);
2906   fHistoTOFbeta->Fill(track->Pt(), beta);
2907  }
2908   
2909  //remove the tracks which don't have proper TOF response-otherwise the misIDentification rate values will be wrong(in MC)
2910 if(fRequestTOFPID && track->Pt()>fPtTOFPIDmin && (!HasTOFPID(PIDtrack)) ) continue;
2911  
2912 //track identification(using nsigma method)
2913      particletype=GetParticle(PIDtrack,fFIllPIDQAHistos);//*******************************change may be required(It should return only pion,kaon, proton and Spundefined; NOT unidentifed***************be careful)
2914
2915 //2-d TPCTOF map(for each Pt interval)
2916   if(HasTOFPID(PIDtrack)){
2917  fTPCTOFPion3d->Fill(track->Pt(),fnsigmas[SpPion][NSigmaTOF],fnsigmas[SpPion][NSigmaTPC]);
2918  fTPCTOFKaon3d->Fill(track->Pt(),fnsigmas[SpKaon][NSigmaTOF],fnsigmas[SpKaon][NSigmaTPC]);
2919  fTPCTOFProton3d->Fill(track->Pt(),fnsigmas[SpProton][NSigmaTOF],fnsigmas[SpProton][NSigmaTPC]); 
2920   }
2921
2922 //ignore the Spundefined particles as they also contain pion, kaon, proton outside the nsigma cut(also if tracks don't have proper TOF PID in a certain Pt interval) & these tracks are actually counted when we do the the efficiency correction, so considering them as unidentified particles & doing the efficiency correction(i.e defining unidentified=pion+Kaon+proton+SpUndefined is right only without efficiency correction) for them will be two times wrong!!!!! 
2923   if (particletype==SpUndefined) continue;//this condition creating a modulated structure in delphi projection in mixed event case(only when we are dealing with identified particles i.e. tracksID)!!!!!!!!!!!
2924
2925     if(fRequestEventPlane){
2926       FillPIDEventPlane(cent_v0,particletype,track->Phi(),gReactionPlane);
2927     }
2928
2929
2930  //Pt, Eta , Phi distribution of the reconstructed identified particles
2931 if(ffillhistQAReco)
2932     {
2933 if (particletype==SpPion)
2934   {
2935     fPionPt->Fill(track->Pt());
2936     fPionEta->Fill(track->Eta());
2937     fPionPhi->Fill(track->Phi());
2938   }
2939 if (particletype==SpKaon)
2940   {
2941     fKaonPt->Fill(track->Pt());
2942     fKaonEta->Fill(track->Eta());
2943     fKaonPhi->Fill(track->Phi());
2944   }
2945 if (particletype==SpProton)
2946   {
2947     fProtonPt->Fill(track->Pt());
2948     fProtonEta->Fill(track->Eta());
2949     fProtonPhi->Fill(track->Phi());
2950   }
2951     }
2952  
2953  if((track->Pt()>=fminPtAsso && track->Pt()<=fmaxPtAsso) || (track->Pt()>=fminPtTrig && track->Pt()<=fmaxPtTrig)) 
2954   {
2955     Short_t chargeval=0;
2956     if(track->Charge()>0)   chargeval=1;
2957     if(track->Charge()<0)   chargeval=-1;
2958     if(chargeval==0) continue;
2959 if (fapplyTrigefficiency || fapplyAssoefficiency)
2960   effmatrix=GetTrackbyTrackeffvalue(track,effcent,zvtx,particletype);//get the tracking eff x TOF matching eff x PID eff x contamination factor for identified particles; Bool_t mesoneffrequired=kFALSE
2961  LRCParticlePID* copy1 = new LRCParticlePID(particletype,Inv_mass,chargeval,track->Pt(),track->Eta(), track->Phi(),effmatrix,track->GetTPCClusterMapPtr(),track->GetTPCSharedMapPtr());
2962     copy1->SetUniqueID(eventno * 100000 + (Int_t)trackscount);
2963     tracksID->Add(copy1);
2964   }
2965 } //track loop ends but still in event loop
2966
2967 if(trackscount<1.0){
2968   if(tracksUNID) delete tracksUNID;
2969   if(tracksID) delete tracksID;
2970   return;
2971  }
2972
2973  if (fTrigPtmin1) fhistJetTrigestimate->Fill(cent_v0,0.0);
2974  if (fTrigPtmin2) fhistJetTrigestimate->Fill(cent_v0,2.0);
2975  if (fTrigPtJet) fhistJetTrigestimate->Fill(cent_v0,4.0);
2976
2977  Float_t weightval=1.0;
2978
2979
2980   
2981 //fill the centrality/multiplicity distribution of the selected events
2982  fhistcentrality->Fill(cent_v0);//*********************************WARNING::binning of cent_v0 is different for pp and pPb/PbPb case
2983
2984 if(fSampleType=="pPb" || fSampleType=="PbPb" || fPPVsMultUtils==kTRUE) fCentralityCorrelation->Fill(cent_v0, trackscount);//only with unidentified tracks(i.e before PID selection);;;;;can be used to remove centrality outliers??????
2985
2986 //count selected events having centrality betn 0-100%
2987  fEventCounter->Fill(13);
2988
2989 //***************************************event no. counting
2990 Bool_t isbaryontrig=kFALSE;
2991 Bool_t ismesontrig=kFALSE;
2992 if(tracksUNID && tracksUNID->GetEntriesFast()>0) fEventno->Fill(cent_v0,zvtx);
2993
2994 if(tracksID && tracksID->GetEntriesFast()>0)
2995   {
2996 for(Int_t i=0;i<tracksID->GetEntriesFast();i++)
2997     {  //trigger loop starts
2998       LRCParticlePID *trig=(LRCParticlePID*)(tracksID->UncheckedAt(i));
2999       if(!trig) continue;
3000       if(trig->Pt()<fminPtTrig || trig->Pt()>fmaxPtTrig) continue;
3001       Int_t particlepidtrig=trig->getparticle(); //either 1 or 2
3002       if(particlepidtrig==SpProton) isbaryontrig=kTRUE;
3003       if(particlepidtrig==SpPion) ismesontrig=kTRUE;
3004     }//trig loop ends
3005  if (isbaryontrig) fEventnobaryon->Fill(cent_v0,zvtx); 
3006  if (ismesontrig) fEventnomeson->Fill(cent_v0,zvtx);
3007   }
3008
3009 //Get the TObjArray of V0 particles
3010  if(fV0TrigCorr){
3011  tracksIDV0=GetV0Particles((AliVEvent*) aod,cent_v0);
3012  if(tracksIDV0->GetEntriesFast()<=0) return;
3013  }
3014
3015 //same event delta-eta-deltaphi plot 
3016 if(tracksUNID && tracksUNID->GetEntriesFast()>0)//hadron triggered correlation
3017   {//same event calculation starts
3018     if(ffilltrigassoUNID) Fillcorrelation(gReactionPlane,tracksUNID,0,cent_v0,zvtx,weightval,kFALSE,bSign,fPtOrderDataReco,ftwoTrackEfficiencyCutDataReco,kFALSE,"trigassoUNID");//mixcase=kFALSE (hadron-hadron correlation)
3019     if(tracksID && tracksID->GetEntriesFast()>0 && ffilltrigUNIDassoID) Fillcorrelation(gReactionPlane,tracksUNID,tracksID,cent_v0,zvtx,weightval,kFALSE,bSign,fPtOrderDataReco,ftwoTrackEfficiencyCutDataReco,kFALSE,"trigUNIDassoID");//mixcase=kFALSE (hadron-ID correlation)
3020     
3021   }
3022
3023 if(tracksID && tracksID->GetEntriesFast()>0)//ID triggered correlation
3024   {//same event calculation starts
3025     if(tracksUNID && tracksUNID->GetEntriesFast()>0 && ffilltrigIDassoUNID){
3026 if(fV0TrigCorr)  Fillcorrelation(gReactionPlane,tracksIDV0,tracksUNID,cent_v0,zvtx,weightval,kFALSE,bSign,fPtOrderDataReco,ftwoTrackEfficiencyCutDataReco,kFALSE,"trigIDassoUNID");//mixcase=kFALSE (ID-hadron correlation)
3027 else  Fillcorrelation(gReactionPlane,tracksID,tracksUNID,cent_v0,zvtx,weightval,kFALSE,bSign,fPtOrderDataReco,ftwoTrackEfficiencyCutDataReco,kFALSE,"trigIDassoUNID");//mixcase=kFALSE (ID-hadron correlation)
3028     }
3029     if(ffilltrigIDassoID)   Fillcorrelation(gReactionPlane,tracksID,0,cent_v0,zvtx,weightval,kFALSE,bSign,fPtOrderDataReco,ftwoTrackEfficiencyCutDataReco,kFALSE,"trigIDassoID");//mixcase=kFALSE (ID-ID correlation)
3030   }
3031
3032 //still in  main event loop
3033
3034
3035 //start mixing
3036  if(ffilltrigassoUNID || ffilltrigIDassoUNID){//mixing with unidentified particles
3037 AliEventPool* pool = fPoolMgr->GetEventPool(cent_v0, zvtx,gReactionPlane);//In the pool there is tracksUNID(i.e associateds are unidentified)
3038 if (pool && pool->IsReady())
3039   {//start mixing only when pool->IsReady
3040   Float_t nmix1=(Float_t)pool->GetCurrentNEvents();  
3041  for (Int_t jMix=0; jMix<pool->GetCurrentNEvents(); jMix++) 
3042   { //pool event loop start
3043  TObjArray* bgTracks = pool->GetEvent(jMix);
3044   if(!bgTracks) continue;
3045   if(ffilltrigassoUNID && tracksUNID && tracksUNID->GetEntriesFast()>0)//*******************************hadron trggered mixing
3046     Fillcorrelation(gReactionPlane,tracksUNID,bgTracks,cent_v0,zvtx,nmix1,(jMix == 0),bSign,fPtOrderDataReco,ftwoTrackEfficiencyCutDataReco,kTRUE,"trigassoUNID");//mixcase=kTRUE
3047  if(ffilltrigIDassoUNID && tracksID && tracksID->GetEntriesFast()>0)//***********************************ID trggered mixing
3048    {
3049 if(fV0TrigCorr)   Fillcorrelation(gReactionPlane,tracksIDV0,bgTracks,cent_v0,zvtx,nmix1,(jMix == 0),bSign,fPtOrderDataReco,ftwoTrackEfficiencyCutDataReco,kTRUE,"trigIDassoUNID");//mixcase=kTRUE
3050 else  Fillcorrelation(gReactionPlane,tracksID,bgTracks,cent_v0,zvtx,nmix1,(jMix == 0),bSign,fPtOrderDataReco,ftwoTrackEfficiencyCutDataReco,kTRUE,"trigIDassoUNID");//mixcase=kTRUE
3051    } 
3052    }// pool event loop ends mixing case
3053 } //if pool->IsReady() condition ends mixing case
3054  if(tracksUNID) {
3055 if(pool)
3056   pool->UpdatePool(CloneAndReduceTrackList(tracksUNID));
3057  }
3058  }//mixing with unidentified particles
3059
3060
3061  if(ffilltrigUNIDassoID || ffilltrigIDassoID){//mixing with identified particles
3062  AliEventPool* pool1 = fPoolMgr->GetEventPool(cent_v0, zvtx+100,gReactionPlane);//In the pool1 there is tracksID(i.e associateds are identified)
3063 if (pool1 && pool1->IsReady())
3064   {//start mixing only when pool->IsReady
3065   Float_t nmix2=(Float_t)pool1->GetCurrentNEvents();  
3066 for (Int_t jMix=0; jMix<pool1->GetCurrentNEvents(); jMix++) 
3067   { //pool event loop start
3068  TObjArray* bgTracks2 = pool1->GetEvent(jMix);
3069   if(!bgTracks2) continue;
3070 if(ffilltrigUNIDassoID && tracksUNID && tracksUNID->GetEntriesFast()>0)
3071   Fillcorrelation(gReactionPlane,tracksUNID,bgTracks2,cent_v0,zvtx,nmix2,(jMix == 0),bSign,fPtOrderDataReco,ftwoTrackEfficiencyCutDataReco,kTRUE,"trigUNIDassoID");//mixcase=kTRUE  
3072 if(ffilltrigIDassoID && tracksID && tracksID->GetEntriesFast()>0)
3073   Fillcorrelation(gReactionPlane,tracksID,bgTracks2,cent_v0,zvtx,nmix2,(jMix == 0),bSign,fPtOrderDataReco,ftwoTrackEfficiencyCutDataReco,kTRUE,"trigIDassoID");//mixcase=kTRUE
3074
3075    }// pool event loop ends mixing case
3076 } //if pool1->IsReady() condition ends mixing case
3077
3078 if(tracksID) {
3079 if(pool1) 
3080   pool1->UpdatePool(CloneAndReduceTrackList(tracksID));//ownership of tracksasso is with pool now, don't delete it(tracksUNID is with pool)
3081  }
3082  }//mixing with identified particles
3083
3084
3085   //no. of events analyzed
3086 fEventCounter->Fill(15);
3087  
3088 //still in main event loop
3089
3090
3091 if(tracksUNID)  delete tracksUNID;
3092
3093 if(tracksID) delete tracksID;
3094
3095 if(fV0TrigCorr) {
3096   if(tracksIDV0) delete tracksIDV0;
3097   }
3098
3099 } // *************************event loop ends******************************************
3100 //_______________________________________________________________________
3101 TObjArray* AliTwoParticlePIDCorr::CloneAndReduceTrackList(TObjArray* tracks)
3102 {
3103   // clones a track list by using AliDPhiBasicParticle which uses much less memory (used for event mixing)
3104   
3105   TObjArray* tracksClone = new TObjArray;
3106   tracksClone->SetOwner(kTRUE);
3107   
3108   for (Int_t i=0; i<tracks->GetEntriesFast(); i++)
3109   {
3110     LRCParticlePID* particle = (LRCParticlePID*) tracks->UncheckedAt(i);
3111     LRCParticlePID* copy100 = new LRCParticlePID(particle->getparticle(),particle->GetInvMass(),particle->Charge(), particle->Pt(),particle->Eta(), particle->Phi(), particle->geteffcorrectionval(),particle->GetTPCPadMap(),particle->GetTPCSharedMap());
3112     copy100->SetUniqueID(particle->GetUniqueID());
3113     tracksClone->Add(copy100);
3114   }
3115   
3116   return tracksClone;
3117 }
3118
3119 //--------------------------------------------------------------------------------
3120 void AliTwoParticlePIDCorr::Fillcorrelation(Float_t ReactionPlane,TObjArray *trackstrig,TObjArray *tracksasso,Double_t cent,Float_t vtx,Float_t weight,Bool_t firstTime,Float_t bSign,Bool_t fPtOrder,Bool_t twoTrackEfficiencyCut,Bool_t mixcase,TString fillup)
3121 {
3122
3123   //before calling this function check that either trackstrig & tracksasso are available 
3124
3125  // Eta() is extremely time consuming, therefore cache it for the inner loop here:
3126   TObjArray* input = (tracksasso) ? tracksasso : trackstrig;
3127   TArrayF eta(input->GetEntriesFast());
3128   for (Int_t i=0; i<input->GetEntriesFast(); i++)
3129     eta[i] = ((LRCParticlePID*) input->UncheckedAt(i))->Eta();
3130
3131   //if(trackstrig)
3132     Int_t jmax=trackstrig->GetEntriesFast();
3133   if(tracksasso)
3134      jmax=tracksasso->GetEntriesFast();
3135
3136 // identify K, Lambda candidates and flag those particles
3137     // a TObject bit is used for this
3138 const UInt_t kResonanceDaughterFlag = 1 << 14;
3139     if (fRejectResonanceDaughters > 0)
3140     {
3141       Double_t resonanceMass = -1;
3142       Double_t massDaughter1 = -1;
3143       Double_t massDaughter2 = -1;
3144       const Double_t interval = 0.02;
3145  switch (fRejectResonanceDaughters)
3146       {
3147         case 1: resonanceMass = 0.9; massDaughter1 = 0.1396; massDaughter2 = 0.9383; break; // method test
3148         case 2: resonanceMass = 0.4976; massDaughter1 = 0.1396; massDaughter2 = massDaughter1; break; // k0
3149         case 3: resonanceMass = 1.115; massDaughter1 = 0.1396; massDaughter2 = 0.9383; break; // lambda
3150         default: AliFatal(Form("Invalid setting %d", fRejectResonanceDaughters));
3151       }      
3152
3153 for (Int_t i=0; i<trackstrig->GetEntriesFast(); i++)
3154         trackstrig->UncheckedAt(i)->ResetBit(kResonanceDaughterFlag);
3155  for (Int_t i=0; tracksasso->GetEntriesFast(); i++)
3156           tracksasso->UncheckedAt(i)->ResetBit(kResonanceDaughterFlag);
3157
3158  for (Int_t i=0; i<trackstrig->GetEntriesFast(); i++)
3159       {
3160       LRCParticlePID *trig=(LRCParticlePID*)(trackstrig->UncheckedAt(i));
3161 for (Int_t j=0; tracksasso->GetEntriesFast(); j++)
3162         {
3163         LRCParticlePID *asso=(LRCParticlePID*)(tracksasso->UncheckedAt(j));
3164
3165  // check if both particles point to the same element (does not occur for mixed events, but if subsets are mixed within the same event)
3166 if (trig->IsEqual(asso)) continue;
3167
3168 if (trig->Charge() * asso->Charge() > 0) continue;
3169
3170  Float_t mass = GetInvMassSquaredCheap(trig->Pt(), trig->Eta(), trig->Phi(), asso->Pt(), asso->Eta(), asso->Phi(), massDaughter1, massDaughter2);
3171      
3172 if (TMath::Abs(mass - resonanceMass*resonanceMass) < interval*5)
3173           {
3174             mass = GetInvMassSquared(trig->Pt(), trig->Eta(), trig->Phi(), asso->Pt(), asso->Eta(), asso->Phi(), massDaughter1, massDaughter2);
3175
3176             if (mass > (resonanceMass-interval)*(resonanceMass-interval) && mass < (resonanceMass+interval)*(resonanceMass+interval))
3177             {
3178               trig->SetBit(kResonanceDaughterFlag);
3179               asso->SetBit(kResonanceDaughterFlag);
3180               
3181 //            Printf("Flagged %d %d %f", i, j, TMath::Sqrt(mass));
3182             }
3183           }
3184         }
3185       }
3186     }
3187
3188       //Select the highest Pt trigger particle in an event (within a given Pt trigger range)
3189
3190     Float_t TriggerPtMin=fminPtTrig;
3191     Float_t TriggerPtMax=fmaxPtTrig;
3192     Int_t HighestPtTriggerIndx=-99999;
3193     TH1* triggerWeighting = 0;
3194
3195 if(fSelectHighestPtTrig || fWeightPerEvent)//**************add this data member to the constructor
3196       {
3197 if (fWeightPerEvent)
3198     {
3199       TAxis* axis=0;
3200    if(ffilltrigassoUNID || ffilltrigUNIDassoID || ffilltrigIDassoUNID || ffilltrigIDassoID) axis = fTHnTrigcount->GetGrid(0)->GetGrid()->GetAxis(2);                                          
3201   if((fAnalysisType =="MCAOD") && ffilltrigIDassoIDMCTRUTH)    axis = fTHnTrigcountMCTruthPrim->GetGrid(0)->GetGrid()->GetAxis(2);
3202       triggerWeighting = new TH1F("triggerWeighting", "", axis->GetNbins(), axis->GetXbins()->GetArray());
3203     }
3204 for(Int_t i=0;i<trackstrig->GetEntriesFast();i++)
3205     {  //trigger loop starts(highest Pt trigger selection)
3206       LRCParticlePID *trig=(LRCParticlePID*)(trackstrig->UncheckedAt(i));
3207       if(!trig) continue;
3208       Float_t trigpt=trig->Pt();
3209     //to avoid overflow qnd underflow
3210       if(trigpt<fminPtTrig || trigpt>fmaxPtTrig) continue;
3211       Int_t particlepidtrig=trig->getparticle();
3212       if(fTriggerSpeciesSelection){ if (particlepidtrig!=fTriggerSpecies) continue;}
3213
3214       Float_t trigeta=trig->Eta();
3215
3216       // some optimization
3217  if (fTriggerRestrictEta > 0 && TMath::Abs(trigeta) > fTriggerRestrictEta)
3218         continue;
3219
3220 if (fOnlyOneEtaSide != 0)
3221       {
3222         if (fOnlyOneEtaSide * trigeta < 0)
3223           continue;
3224       }
3225   if (fTriggerSelectCharge != 0)
3226         if (trig->Charge() * fTriggerSelectCharge < 0)
3227           continue;
3228         
3229       if (fRejectResonanceDaughters > 0)
3230         if (trig->TestBit(kResonanceDaughterFlag)) continue;
3231
3232       if(fSelectHighestPtTrig){
3233  if(trigpt>TriggerPtMin && trigpt<=TriggerPtMax)
3234           {         
3235           HighestPtTriggerIndx=(Int_t)trig->GetUniqueID();
3236           TriggerPtMin=trigpt;
3237           }
3238       }
3239
3240 if (fWeightPerEvent)  triggerWeighting->Fill(trigpt);
3241
3242     }//trigger loop ends(highest Pt trigger selection)
3243
3244       }//******************(fSelectHighestPtTrig || fWeightPerEvent) condition ends
3245
3246
3247  //two particle correlation filling
3248 for(Int_t i=0;i<trackstrig->GetEntriesFast();i++)
3249     {  //trigger loop starts
3250       LRCParticlePID *trig=(LRCParticlePID*)(trackstrig->UncheckedAt(i));
3251       if(!trig) continue;
3252       Float_t trigpt=trig->Pt();
3253     //to avoid overflow qnd underflow
3254       if(trigpt<fminPtTrig || trigpt>fmaxPtTrig) continue;
3255       Double_t ParticlePID_InvMass=0.0;
3256       if(fV0TrigCorr) ParticlePID_InvMass=trig->GetInvMass();
3257       else{
3258       Int_t particlepidtrig=trig->getparticle();
3259       ParticlePID_InvMass=(Double_t) particlepidtrig;
3260       if(fTriggerSpeciesSelection){ if (particlepidtrig!=fTriggerSpecies) continue;}//***********************************forks,lam.Alam their PID numbers have no meaning, only their Inv_mass will be stored
3261       }
3262
3263       Float_t trigeta=trig->Eta();
3264
3265       // some optimization
3266  if (fTriggerRestrictEta > 0 && TMath::Abs(trigeta) > fTriggerRestrictEta)
3267         continue;
3268
3269 if (fOnlyOneEtaSide != 0)
3270       {
3271         if (fOnlyOneEtaSide * trigeta < 0)
3272           continue;
3273       }
3274   if (fTriggerSelectCharge != 0)
3275         if (trig->Charge() * fTriggerSelectCharge < 0)
3276           continue;
3277         
3278       if (fRejectResonanceDaughters > 0)
3279         if (trig->TestBit(kResonanceDaughterFlag)) continue;
3280
3281       if(fSelectHighestPtTrig && HighestPtTriggerIndx!=-99999) {
3282         if(trig->GetUniqueID()!=(UInt_t)HighestPtTriggerIndx) continue;
3283       }
3284
3285       Float_t trigphi=trig->Phi();
3286       Float_t trackefftrig=1.0;
3287       if(fapplyTrigefficiency) trackefftrig=trig->geteffcorrectionval();
3288
3289     // Event plane (determine psi bin)
3290     Double_t gPsiMinusPhi    =   0.;
3291     Double_t gPsiMinusPhiBin = -10.;
3292 if(fRequestEventPlane){
3293     gPsiMinusPhi   = TMath::Abs(trigphi - ReactionPlane);
3294     //in-plane(Note thet event plane angle has to be defined within 0 to 180 degree(do not use this if event ), otherwise the definition of in plane and out plane particles is wrong)
3295     if((gPsiMinusPhi <= 7.5*TMath::DegToRad())||
3296       (gPsiMinusPhi >= 352.5*TMath::DegToRad())||
3297        ((172.5*TMath::DegToRad() <= gPsiMinusPhi)&&(gPsiMinusPhi <= 187.5*TMath::DegToRad())))
3298       gPsiMinusPhiBin = 0.0;
3299     /*
3300  if((gPsiMinusPhi <= 7.5*TMath::DegToRad())||
3301        ((172.5*TMath::DegToRad() <= gPsiMinusPhi)&&(gPsiMinusPhi <= 187.5*TMath::DegToRad())))
3302       gPsiMinusPhiBin = 0.0;
3303     */
3304     //intermediate
3305     else if(((37.5*TMath::DegToRad() <= gPsiMinusPhi)&&(gPsiMinusPhi <= 52.5*TMath::DegToRad()))||
3306             ((127.5*TMath::DegToRad() <= gPsiMinusPhi)&&(gPsiMinusPhi <= 142.5*TMath::DegToRad()))||
3307             ((217.5*TMath::DegToRad() <= gPsiMinusPhi)&&(gPsiMinusPhi <= 232.5*TMath::DegToRad()))||
3308             ((307.5*TMath::DegToRad() <= gPsiMinusPhi)&&(gPsiMinusPhi <= 322.5*TMath::DegToRad())))
3309       gPsiMinusPhiBin = 1.0;
3310     //out of plane
3311     else if(((82.5*TMath::DegToRad() <= gPsiMinusPhi)&&(gPsiMinusPhi <= 97.5*TMath::DegToRad()))||
3312             ((262.5*TMath::DegToRad() <= gPsiMinusPhi)&&(gPsiMinusPhi <= 277.5*TMath::DegToRad())))
3313       gPsiMinusPhiBin = 2.0;
3314     //everything else
3315     else 
3316       gPsiMinusPhiBin = 3.0;
3317     
3318     fHistPsiMinusPhi->Fill(gPsiMinusPhiBin,gPsiMinusPhi);
3319  }
3320
3321       //cout<<"*******************trackefftrig="<<trackefftrig<<endl;
3322         Double_t* trigval;
3323         Int_t dim=3;
3324         Int_t eventplaneAxis=0;
3325         if(fRequestEventPlane) eventplaneAxis=1;
3326         if(fcontainPIDtrig && SetChargeAxis==0) dim=4+eventplaneAxis;
3327         if(!fcontainPIDtrig && SetChargeAxis==2) dim=4+eventplaneAxis;
3328         if(fcontainPIDtrig && SetChargeAxis==2) dim=5+eventplaneAxis;
3329         trigval= new Double_t[dim];
3330       trigval[0] = cent;
3331       trigval[1] = vtx;
3332       trigval[2] = trigpt;
3333
3334       if(fRequestEventPlane){
3335       trigval[3] = gPsiMinusPhiBin;
3336       if(fcontainPIDtrig && SetChargeAxis==0) trigval[4] = ParticlePID_InvMass;
3337       if(!fcontainPIDtrig && SetChargeAxis==2) trigval[4] = trig->Charge();
3338       if(fcontainPIDtrig && SetChargeAxis==2) {
3339       trigval[4] = ParticlePID_InvMass;
3340       trigval[5] = trig->Charge();
3341        }
3342       }
3343
3344   if(!fRequestEventPlane){
3345       if(fcontainPIDtrig && SetChargeAxis==0) trigval[3] = ParticlePID_InvMass;
3346       if(!fcontainPIDtrig && SetChargeAxis==2) trigval[3] = trig->Charge();
3347       if(fcontainPIDtrig && SetChargeAxis==2) {
3348       trigval[3] = ParticlePID_InvMass;
3349       trigval[4] = trig->Charge();
3350        }
3351       }
3352
3353  
3354
3355         if (fWeightPerEvent)
3356         {
3357           // leads effectively to a filling of one entry per filled trigger particle pT bin
3358           Int_t weightBin = triggerWeighting->GetXaxis()->FindBin(trigval[2]);
3359 //        Printf("Using weight %f", triggerWeighting->GetBinContent(weightBin));
3360           trackefftrig *= triggerWeighting->GetBinContent(weightBin);
3361         }
3362
3363
3364       //trigger particle counting for both same and mixed event case;;;;;step=0->same event case;;;;;step=1->mixed event case;;;;;;
3365 if(ffilltrigassoUNID==kTRUE && ffilltrigUNIDassoID==kTRUE){
3366       if(fillup=="trigassoUNID" ) {
3367 if(mixcase==kFALSE)   fTHnTrigcount->Fill(trigval,0,1.0/trackefftrig); 
3368 if(mixcase==kTRUE && firstTime)   fTHnTrigcount->Fill(trigval,1,1.0/trackefftrig); 
3369       }
3370     }
3371  if(ffilltrigassoUNID==kTRUE && ffilltrigUNIDassoID==kFALSE){
3372    if(fillup=="trigassoUNID" )  
3373      {
3374 if(mixcase==kFALSE)   fTHnTrigcount->Fill(trigval,0,1.0/trackefftrig); 
3375 if(mixcase==kTRUE && firstTime)   fTHnTrigcount->Fill(trigval,1,1.0/trackefftrig); 
3376      }
3377     }
3378 if(ffilltrigassoUNID==kFALSE && ffilltrigUNIDassoID==kTRUE){
3379   if(fillup=="trigUNIDassoID")  
3380     {
3381 if(mixcase==kFALSE)   fTHnTrigcount->Fill(trigval,0,1.0/trackefftrig); 
3382 if(mixcase==kTRUE && firstTime)   fTHnTrigcount->Fill(trigval,1,1.0/trackefftrig); 
3383     }
3384     }
3385  //ensure that trigIDassoID , trigassoUNID, trigIDassoUNID & trigUNIDassoID  case FillCorrelation called only once in the event loop for same event correlation function calculation, otherwise there will be multiple counting of pion, kaon,proton,unidentified
3386 if(ffilltrigIDassoUNID==kTRUE && ffilltrigIDassoID==kTRUE){
3387   if(fillup=="trigIDassoID")  
3388     {
3389 if(mixcase==kFALSE)   fTHnTrigcount->Fill(trigval,0,1.0/trackefftrig); 
3390 if(mixcase==kTRUE && firstTime)   fTHnTrigcount->Fill(trigval,1,1.0/trackefftrig); 
3391     }
3392     }
3393  if(ffilltrigIDassoUNID==kTRUE && ffilltrigIDassoID==kFALSE){
3394    if(fillup=="trigIDassoUNID" ) 
3395      {
3396 if(mixcase==kFALSE)   fTHnTrigcount->Fill(trigval,0,1.0/trackefftrig); 
3397 if(mixcase==kTRUE && firstTime)   fTHnTrigcount->Fill(trigval,1,1.0/trackefftrig); 
3398      } 
3399     }
3400 if(ffilltrigIDassoUNID==kFALSE && ffilltrigIDassoID==kTRUE){
3401   if(fillup=="trigIDassoID")  
3402     {
3403 if(mixcase==kFALSE)   fTHnTrigcount->Fill(trigval,0,1.0/trackefftrig); 
3404 if(mixcase==kTRUE && firstTime)   fTHnTrigcount->Fill(trigval,1,1.0/trackefftrig); 
3405     }
3406     }
3407
3408  if(fillup=="trigIDassoIDMCTRUTH") { //In truth MC case "Unidentified" means any particle other than pion,kaon or proton and no efficiency correction(default value 1.0)************************be careful!!!! 
3409 if(mixcase==kFALSE)   fTHnTrigcountMCTruthPrim->Fill(trigval,0,1.0/trackefftrig); 
3410 if(mixcase==kTRUE && firstTime)   fTHnTrigcountMCTruthPrim->Fill(trigval,1,1.0/trackefftrig); 
3411   }
3412
3413     //asso loop starts within trigger loop
3414    for(Int_t j=0;j<jmax;j++)
3415              {
3416     LRCParticlePID *asso=0;
3417     if(!tracksasso)
3418     asso=(LRCParticlePID*)(trackstrig->UncheckedAt(j));
3419     else
3420     asso=(LRCParticlePID*)(tracksasso->UncheckedAt(j));
3421
3422     if(!asso) continue;
3423
3424     //to avoid overflow and underflow
3425  if(asso->Pt()<fminPtAsso || asso->Pt()>fmaxPtAsso) continue;//***********************Important
3426
3427  //if(fmaxPtAsso==fminPtTrig) {if(asso->Pt()==fminPtTrig) continue;}//******************Think about it!
3428
3429   if(!tracksasso && j==i) continue;
3430
3431    // check if both particles point to the same element (does not occur for mixed events, but if subsets are mixed within the same event,i.e. both Trig and asso TObjArray belongs to the same Pt range but say Trig is Unidentified but asso is identified then the serial no. wise particles are not same and and j==i doesn't aplly)
3432    // if (tracksasso && trig->IsEqual(asso))  continue;
3433
3434   if (tracksasso && (trig->GetUniqueID()==asso->GetUniqueID())) continue;
3435           
3436  if (fPtOrder)
3437  if (asso->Pt() >= trig->Pt()) continue;
3438
3439   Int_t particlepidasso=asso->getparticle(); 
3440   if(fAssociatedSpeciesSelection){ if (particlepidasso!=fAssociatedSpecies) continue;}
3441             
3442
3443 if (fAssociatedSelectCharge != 0)
3444 if (asso->Charge() * fAssociatedSelectCharge < 0) continue;
3445             
3446  if (fSelectCharge > 0)
3447         {
3448           // skip like sign
3449           if (fSelectCharge == 1 && asso->Charge() * trig->Charge() > 0)
3450             continue;
3451             
3452           // skip unlike sign
3453           if (fSelectCharge == 2 && asso->Charge() * trig->Charge() < 0)
3454             continue;
3455         }
3456
3457 if (fEtaOrdering)
3458         {
3459           if (trigeta < 0 && asso->Eta() < trigeta)
3460             continue;
3461           if (trigeta > 0 && asso->Eta() > trigeta)
3462             continue;
3463         }
3464
3465 if (fRejectResonanceDaughters > 0)
3466           if (asso->TestBit(kResonanceDaughterFlag))
3467           {
3468 //          Printf("Skipped j=%d", j);
3469             continue;
3470           }
3471
3472         // conversions
3473         if (fCutConversions && asso->Charge() * trig->Charge() < 0)
3474         {
3475           Float_t mass = GetInvMassSquaredCheap(trig->Pt(), trigeta, trig->Phi(), asso->Pt(),eta[j], asso->Phi(), 0.510e-3, 0.510e-3);
3476           
3477           if (mass < 0.1)
3478           {
3479             mass = GetInvMassSquared(trig->Pt(), trigeta, trig->Phi(), asso->Pt(), eta[j], asso->Phi(), 0.510e-3, 0.510e-3);
3480             
3481             fControlConvResoncances->Fill(0.0, mass);
3482
3483             if (mass < 0.04*0.04) 
3484               continue;
3485           }
3486         }
3487
3488         // K0s
3489         if (fCutResonances && asso->Charge() * trig->Charge() < 0)
3490         {
3491           Float_t mass = GetInvMassSquaredCheap(trig->Pt(), trigeta, trig->Phi(), asso->Pt(), eta[j], asso->Phi(), 0.1396, 0.1396);
3492           
3493           const Float_t kK0smass = 0.4976;
3494           
3495           if (TMath::Abs(mass - kK0smass*kK0smass) < 0.1)
3496           {
3497             mass = GetInvMassSquared(trig->Pt(), trigeta, trig->Phi(), asso->Pt(),eta[j], asso->Phi(), 0.1396, 0.1396);
3498             
3499             fControlConvResoncances->Fill(1, mass - kK0smass*kK0smass);
3500
3501             if (mass > (kK0smass-0.02)*(kK0smass-0.02) && mass < (kK0smass+0.02)*(kK0smass+0.02))
3502               continue;
3503           }
3504         }
3505         
3506         // Lambda
3507         if (fCutResonances && asso->Charge() * trig->Charge() < 0)
3508         {
3509           Float_t mass1 = GetInvMassSquaredCheap(trig->Pt(), trigeta, trig->Phi(), asso->Pt(), eta[j], asso->Phi(), 0.1396, 0.9383);
3510           Float_t mass2 = GetInvMassSquaredCheap(trig->Pt(), trigeta, trig->Phi(), asso->Pt(),eta[j] , asso->Phi(), 0.9383, 0.1396);
3511           
3512           const Float_t kLambdaMass = 1.115;
3513
3514           if (TMath::Abs(mass1 - kLambdaMass*kLambdaMass) < 0.1)
3515           {
3516             mass1 = GetInvMassSquared(trig->Pt(), trigeta, trig->Phi(), asso->Pt(),eta[j], asso->Phi(), 0.1396, 0.9383);
3517
3518             fControlConvResoncances->Fill(2, mass1 - kLambdaMass*kLambdaMass);
3519             
3520             if (mass1 > (kLambdaMass-0.02)*(kLambdaMass-0.02) && mass1 < (kLambdaMass+0.02)*(kLambdaMass+0.02))
3521               continue;
3522           }
3523           if (TMath::Abs(mass2 - kLambdaMass*kLambdaMass) < 0.1)
3524           {
3525             mass2 = GetInvMassSquared(trig->Pt(), trigeta, trig->Phi(), asso->Pt(),eta[j] , asso->Phi(), 0.9383, 0.1396);
3526
3527             fControlConvResoncances->Fill(2, mass2 - kLambdaMass*kLambdaMass);
3528
3529             if (mass2 > (kLambdaMass-0.02)*(kLambdaMass-0.02) && mass2 < (kLambdaMass+0.02)*(kLambdaMass+0.02))
3530               continue;
3531           }
3532         }
3533
3534         if (twoTrackEfficiencyCut)
3535         {
3536           // the variables & cuthave been developed by the HBT group 
3537           // see e.g. https://indico.cern.ch/materialDisplay.py?contribId=36&sessionId=6&materialId=slides&confId=142700
3538           Float_t phi1 = trig->Phi();
3539           Float_t pt1 = trig->Pt();
3540           Float_t charge1 = trig->Charge();
3541           Float_t phi2 = asso->Phi();
3542           Float_t pt2 = asso->Pt();
3543           Float_t charge2 = asso->Charge();
3544
3545           Float_t deta= trigeta - eta[j]; 
3546     
3547  // optimization
3548           if (TMath::Abs(deta) < twoTrackEfficiencyCutValue * 2.5 * 3)
3549           {
3550
3551   // check first boundaries to see if is worth to loop and find the minimum
3552             Float_t dphistar1 = GetDPhiStar(phi1, pt1, charge1, phi2, pt2, charge2, fTwoTrackCutMinRadius, bSign);
3553             Float_t dphistar2 = GetDPhiStar(phi1, pt1, charge1, phi2, pt2, charge2, fTwoTrackCutMaxRadius, bSign);
3554
3555  const Float_t kLimit = twoTrackEfficiencyCutValue * 3;
3556
3557             Float_t dphistarminabs = 1e5;
3558             Float_t dphistarmin = 1e5;
3559
3560  if (TMath::Abs(dphistar1) < kLimit || TMath::Abs(dphistar2) < kLimit || dphistar1 * dphistar2 < 0)
3561             {
3562               for (Double_t rad=fTwoTrackCutMinRadius; rad<=fTwoTrackCutMaxRadius; rad+=0.01) 
3563               {
3564                 Float_t dphistar = GetDPhiStar(phi1, pt1, charge1, phi2, pt2, charge2, rad, bSign);
3565
3566                 Float_t dphistarabs = TMath::Abs(dphistar);
3567
3568         if (dphistarabs < dphistarminabs)
3569                 {
3570                   dphistarmin = dphistar;
3571                   dphistarminabs = dphistarabs;
3572                 }
3573               }
3574               if(mixcase==kFALSE)  fTwoTrackDistancePt[0]->Fill(deta, dphistarmin, TMath::Abs(pt1 - pt2));//for same event
3575               if(mixcase==kTRUE)  fTwoTrackDistancePtmix[0]->Fill(deta, dphistarmin, TMath::Abs(pt1 - pt2));//for mixed event
3576
3577 if (dphistarminabs < twoTrackEfficiencyCutValue && TMath::Abs(deta) < twoTrackEfficiencyCutValue)
3578               {
3579 //              Printf("Removed track pair %d %d with %f %f %f %f %f %f %f %f %f", i, j, deta, dphistarminabs, phi1, pt1, charge1, phi2, pt2, charge2, bSign);
3580                 continue;
3581               }
3582              if(mixcase==kFALSE) fTwoTrackDistancePt[1]->Fill(deta, dphistarmin, TMath::Abs(pt1 - pt2));//for same event
3583              if(mixcase==kTRUE) fTwoTrackDistancePtmix[1]->Fill(deta, dphistarmin, TMath::Abs(pt1 - pt2));//for mixed event
3584
3585             }
3586           }
3587         }
3588
3589         //pair sharedfraction cut(only between the trig and asso track)
3590    if(fillup!="trigIDassoIDMCTRUTH")//******************************************NOT for TRUTH MC particles
3591   {
3592     if(fSharedfraction_Pair_cut>=0){
3593         Bool_t passsharedfractionpaircut=CalculateSharedFraction(trig->GetTPCPadMap(),asso->GetTPCPadMap(),trig->GetTPCSharedMap(),asso->GetTPCSharedMap());
3594         if(!passsharedfractionpaircut) continue;
3595     }
3596   }
3597         Float_t weightperevent=weight;
3598         Float_t trackeffasso=1.0;
3599         if(fapplyAssoefficiency) trackeffasso=asso->geteffcorrectionval();
3600         //cout<<"*******************trackeffasso="<<trackeffasso<<endl;
3601         Float_t deleta=trigeta-eta[j];
3602         Float_t delphi=PhiRange(trigphi-asso->Phi()); 
3603
3604         Float_t delpt=trigpt-asso->Pt();
3605         //fill it with/without two track efficiency cut    
3606         if(mixcase==kFALSE)  fTwoTrackDistancePtdip->Fill(deleta, delphi, TMath::Abs(delpt));//for same event
3607         if(mixcase==kTRUE)  fTwoTrackDistancePtdipmix->Fill(deleta, delphi, TMath::Abs(delpt));//for mixed event
3608
3609  //here get the two particle efficiency correction factor
3610         Float_t effweight=trackefftrig*trackeffasso*weightperevent;
3611         // if(mixcase==kFALSE)  cout<<"*******************effweight="<<effweight<<endl;
3612         Double_t* vars;
3613         Int_t dimused=kTrackVariablesPair+eventplaneAxis;
3614         vars= new Double_t[dimused];
3615         vars[0]=cent;
3616         vars[1]=vtx;
3617         vars[2]=trigpt;
3618         vars[3]=asso->Pt();
3619         vars[4]=deleta;
3620         vars[5]=delphi;
3621
3622         Int_t dimension=6;
3623         if(fRequestEventPlane) 
3624         {
3625        vars[6]=gPsiMinusPhiBin;
3626        dimension=7;
3627         }
3628
3629 if(!fcontainPIDtrig && !fcontainPIDasso && SetChargeAxis==2){
3630         vars[dimension]=trig->Charge();
3631         vars[dimension+1]=asso->Charge();
3632  }
3633 if(fcontainPIDtrig && !fcontainPIDasso){
3634         vars[dimension]=ParticlePID_InvMass;
3635 if(SetChargeAxis==2){
3636         vars[dimension+1]=trig->Charge();
3637         vars[dimension+2]=asso->Charge();
3638  }
3639         }
3640 if(!fcontainPIDtrig && fcontainPIDasso){
3641         vars[dimension]=particlepidasso;
3642 if(SetChargeAxis==2){
3643         vars[dimension+1]=trig->Charge();
3644         vars[dimension+2]=asso->Charge();
3645    }
3646  }
3647  if(fcontainPIDtrig && fcontainPIDasso){
3648         vars[dimension]=ParticlePID_InvMass;
3649         vars[dimension+1]=particlepidasso;
3650 if(SetChargeAxis==2){
3651         vars[dimension+2]=trig->Charge();
3652         vars[dimension+3]=asso->Charge();
3653    }
3654  }
3655
3656         if (fWeightPerEvent)
3657         {
3658           Int_t weightBin = triggerWeighting->GetXaxis()->FindBin(vars[2]);
3659 //        Printf("Using weight %f", triggerWeighting->GetBinContent(weightBin));
3660          effweight *= triggerWeighting->GetBinContent(weightBin);
3661         }
3662     
3663
3664         //Fill Correlation ThnSparses
3665     if(fillup=="trigassoUNID")
3666       {
3667     if(mixcase==kFALSE)  fTHnCorrUNID->Fill(vars,0,1.0/effweight);
3668     if(mixcase==kTRUE)   fTHnCorrUNIDmix->Fill(vars,0,1.0/effweight);
3669       }
3670     if(fillup=="trigIDassoID")
3671       {
3672         if(mixcase==kFALSE)  fTHnCorrID->Fill(vars,0,1.0/effweight);
3673         if(mixcase==kTRUE)  fTHnCorrIDmix->Fill(vars,0,1.0/effweight);
3674       }
3675     if(fillup=="trigIDassoIDMCTRUTH")//******************************************for TRUTH MC particles
3676       {//in this case effweight should be 1 always 
3677         if(mixcase==kFALSE)  fCorrelatonTruthPrimary->Fill(vars,0,1.0/effweight); 
3678         if(mixcase==kTRUE) fCorrelatonTruthPrimarymix->Fill(vars,0,1.0/effweight);
3679     }   
3680     if(fillup=="trigIDassoUNID" || fillup=="trigUNIDassoID")//****************************be careful
3681       {
3682         if(mixcase==kFALSE)  fTHnCorrIDUNID->Fill(vars,0,1.0/effweight);
3683         if(mixcase==kTRUE)   fTHnCorrIDUNIDmix->Fill(vars,0,1.0/effweight);
3684        }
3685         
3686 delete[] vars;
3687    }//asso loop ends 
3688 delete[] trigval;
3689  }//trigger loop ends 
3690
3691  if (triggerWeighting)
3692     {
3693       delete triggerWeighting;
3694       triggerWeighting = 0;
3695     }
3696 }
3697
3698 //------------------------------------------------------------------------------------------------
3699 Bool_t AliTwoParticlePIDCorr:: CalculateSharedFraction(const TBits *triggerPadMap,const TBits *assocPadMap,const TBits *triggerShareMap,const TBits *assocShareMap)
3700 {//source code-AliFemtoShareQualityPairCut.cxx
3701 Double_t nofhits=0;
3702 Double_t nofsharedhits=0;
3703
3704 for(UInt_t imap=0;imap< (triggerPadMap->GetNbits() );imap++)
3705 {
3706 //if they are in same pad
3707 //cout<<triggerPadMap->TestBitNumber(imap)<<"    "<< assocPadMap->TestBitNumber(imap)<<endl;
3708 if (triggerPadMap->TestBitNumber(imap) &&
3709       assocPadMap->TestBitNumber(imap))
3710 {
3711 //if they share
3712 //cout<<triggerShareMap->TestBitNumber(imap)<<"   "<<assocShareMap->TestBitNumber(imap)<<endl;
3713 if (triggerShareMap->TestBitNumber(imap) &&
3714       assocShareMap->TestBitNumber(imap))
3715 {
3716   //cout<<triggerShareMap->TestBitNumber(imap)<<"   "<<assocShareMap->TestBitNumber(imap)<<endl;
3717 nofhits+=2;
3718 nofsharedhits+=2;
3719 }
3720
3721
3722
3723 //not shared
3724     else {
3725      
3726       nofhits+=2;
3727     }
3728
3729
3730 }
3731 //different pad
3732
3733 //cout<< (triggerPadMap->TestBitNumber(imap) || assocPadMap->TestBitNumber(imap))<<endl;
3734 else if (triggerPadMap->TestBitNumber(imap) ||
3735       assocPadMap->TestBitNumber(imap)) {
3736     // One track has a hit, the other does not
3737    
3738     nofhits++;
3739     //cout<<"No hits :"<<nofhits<<endl;
3740    
3741       }
3742
3743
3744
3745 }
3746
3747 Double_t SharedFraction=0.0;
3748 if(nofhits>0) SharedFraction=(nofsharedhits/nofhits);
3749
3750 //cout<<"Fraction shared hits :"<<SharedFraction<<endl;
3751
3752 if(SharedFraction>fSharedfraction_Pair_cut) return kFALSE;
3753
3754 return kTRUE;
3755
3756 }
3757
3758 //________________________________________________________________________________________________
3759 Float_t AliTwoParticlePIDCorr::GetTrackbyTrackeffvalue(AliAODTrack* track,Double_t cent,Float_t evzvtx, Int_t parpid)
3760 {
3761   //This function is called only when applyefficiency=kTRUE; also ensure that "track" is present before calling that function
3762  Int_t effVars[4];
3763  Float_t effvalue=1.; 
3764
3765   if(parpid==unidentified)
3766             {
3767             effVars[0] = effcorection[5]->GetAxis(0)->FindBin(cent);
3768             effVars[1] = effcorection[5]->GetAxis(1)->FindBin(evzvtx); 
3769             effVars[2] = effcorection[5]->GetAxis(2)->FindBin(track->Pt()); 
3770             effVars[3] = effcorection[5]->GetAxis(3)->FindBin(track->Eta()); 
3771             effvalue=effcorection[5]->GetBinContent(effVars);
3772             }
3773 if(parpid==SpPion || parpid==SpKaon)
3774             {
3775               if(fmesoneffrequired && !fkaonprotoneffrequired && track->Pt()>=fminPtComboeff && track->Pt()<=fmaxPtComboeff)
3776                 {
3777             effVars[0] = effcorection[3]->GetAxis(0)->FindBin(cent);
3778             effVars[1] = effcorection[3]->GetAxis(1)->FindBin(evzvtx); 
3779             effVars[2] = effcorection[3]->GetAxis(2)->FindBin(track->Pt()); 
3780             effVars[3] = effcorection[3]->GetAxis(3)->FindBin(track->Eta());
3781             effvalue=effcorection[3]->GetBinContent(effVars);
3782                 }
3783               else{
3784  if(parpid==SpPion)
3785             {
3786             effVars[0] = effcorection[0]->GetAxis(0)->FindBin(cent);
3787             effVars[1] = effcorection[0]->GetAxis(1)->FindBin(evzvtx); 
3788             effVars[2] = effcorection[0]->GetAxis(2)->FindBin(track->Pt()); 
3789             effVars[3] = effcorection[0]->GetAxis(3)->FindBin(track->Eta()); 
3790             effvalue=effcorection[0]->GetBinContent(effVars);
3791             }
3792             
3793  if(parpid==SpKaon)
3794             {
3795             effVars[0] = effcorection[1]->GetAxis(0)->FindBin(cent);
3796             effVars[1] =  effcorection[1]->GetAxis(1)->FindBin(evzvtx); 
3797             effVars[2] =  effcorection[1]->GetAxis(2)->FindBin(track->Pt()); 
3798             effVars[3] =  effcorection[1]->GetAxis(3)->FindBin(track->Eta()); 
3799             effvalue=effcorection[1]->GetBinContent(effVars);
3800             }
3801               }
3802             }   
3803              
3804  if(parpid==SpProton)
3805             {
3806             effVars[0] =  effcorection[2]->GetAxis(0)->FindBin(cent);
3807             effVars[1] = effcorection[2]->GetAxis(1)->FindBin(evzvtx); 
3808             effVars[2] = effcorection[2]->GetAxis(2)->FindBin(track->Pt()); 
3809             effVars[3] = effcorection[2]->GetAxis(3)->FindBin(track->Eta()); 
3810             effvalue=effcorection[2]->GetBinContent(effVars);
3811             }
3812
3813  if(fkaonprotoneffrequired && !fmesoneffrequired && track->Pt()>=fminPtComboeff && track->Pt()<=fmaxPtComboeff)
3814                 {
3815   if(parpid==SpProton || parpid==SpKaon)
3816             {
3817             effVars[0] = effcorection[4]->GetAxis(0)->FindBin(cent);
3818             effVars[1] = effcorection[4]->GetAxis(1)->FindBin(evzvtx); 
3819             effVars[2] = effcorection[4]->GetAxis(2)->FindBin(track->Pt()); 
3820             effVars[3] = effcorection[4]->GetAxis(3)->FindBin(track->Eta());
3821             effvalue=effcorection[4]->GetBinContent(effVars);
3822             }
3823                 }           
3824             //    Printf("%d %d %d %d %f", effVars[0], effVars[1], effVars[2], effVars[3], fEfficiencyCorrectionAssociated->GetBinContent(effVars));
3825      if(effvalue==0.) effvalue=1.;
3826
3827      return effvalue; 
3828
3829 }
3830 //---------------------------------------------------------------------------------
3831
3832 Int_t AliTwoParticlePIDCorr::ClassifyTrack(AliAODTrack* track,AliAODVertex* vertex,Float_t magfield, Bool_t fill)
3833 {  
3834  
3835   if(!track) return 0;
3836   Bool_t trackOK = track->TestFilterBit(fFilterBit);
3837   if(!trackOK) return 0;
3838   if (fTrackStatus != 0 && !CheckTrack(track)) return 0;
3839   //select only primary traks(for data & reco MC tracks) 
3840   if(fonlyprimarydatareco && track->GetType()!=AliAODTrack::kPrimary) return 0;
3841   if(track->Charge()==0) return 0;
3842   if (fill) fHistQA[12]->Fill(track->GetTPCNcls());  
3843   Float_t dxy, dz;                
3844   dxy = track->DCA();
3845   dz = track->ZAtDCA();
3846   if (fill) fHistQA[6]->Fill(dxy);
3847   if (fill) fHistQA[7]->Fill(dz);
3848   Float_t chi2ndf = track->Chi2perNDF();
3849   if (fill) fHistQA[13]->Fill(chi2ndf);  
3850   // Float_t nCrossedRowsTPC = track->GetTPCClusterInfo(2,1);
3851   Float_t nCrossedRowsTPC = track->GetTPCNCrossedRows();
3852   if (fill) fHistQA[14]->Fill(nCrossedRowsTPC); 
3853   //Float_t  ratioCrossedRowsOverFindableClustersTPC = 1.0;
3854   if (track->GetTPCNclsF()>0) {
3855    Float_t  ratioCrossedRowsOverFindableClustersTPC = nCrossedRowsTPC/track->GetTPCNclsF();
3856    if (fill) fHistQA[15]->Fill(ratioCrossedRowsOverFindableClustersTPC);
3857     }
3858 //accepted tracks  
3859      Float_t pt=track->Pt();
3860      if(pt< fminPt || pt> fmaxPt) return 0;
3861      if(TMath::Abs(track->Eta())> fmaxeta) return 0;
3862      if(track->Phi()<0. || track->Phi()>2*TMath::Pi()) return 0;
3863      //if (!HasTPCPID(track)) return 0;//trigger & associated particles must have TPC PID,Is it required???
3864 // DCA XY
3865         if (fdcacut && fDCAXYCut)
3866         {
3867           if (!vertex)
3868             return 0;
3869           
3870           Double_t pos[2];
3871           Double_t covar[3];
3872           AliAODTrack* clone =(AliAODTrack*) track->Clone();
3873           Bool_t success = clone->PropagateToDCA(vertex, magfield, fdcacutvalue, pos, covar);
3874           delete clone;
3875           if (!success)
3876             return 0;
3877
3878 //        Printf("%f", ((AliAODTrack*)part)->DCA());
3879 //        Printf("%f", pos[0]);
3880           if (TMath::Abs(pos[0]) > fDCAXYCut->Eval(track->Pt()))
3881             return 0;
3882         }
3883
3884         if (fSharedClusterCut >= 0)
3885         {
3886           Double_t frac = Double_t(((AliAODTrack*)track)->GetTPCnclsS()) / Double_t(((AliAODTrack*)track)->GetTPCncls());
3887           if (frac > fSharedClusterCut)
3888             return 0;
3889         }
3890
3891    // Rejects tracks with shared clusters after filling a control histogram
3892    // This overload is used for primaries
3893
3894      // Get the shared maps
3895       const TBits sharedMap = track->GetTPCSharedMap();
3896      // Fill a control histogram
3897       fPriHistShare->Fill(sharedMap.CountBits());
3898
3899     // Reject shared clusters
3900        if (fSharedTPCmapCut >= 0)
3901         {     
3902       if((sharedMap.CountBits()) >= 1)  return 0;// Bad track, has too many shared clusters!
3903         }
3904
3905      if (fill) fHistQA[8]->Fill(pt);
3906      if (fill) fHistQA[9]->Fill(track->Eta());
3907      if (fill) fHistQA[10]->Fill(track->Phi());
3908      return 1;
3909   }
3910   //________________________________________________________________________________
3911 void AliTwoParticlePIDCorr::CalculateNSigmas(AliAODTrack *track, Bool_t FIllQAHistos) 
3912 {
3913 //This function is called within the func GetParticle() for accepted tracks only i.e.after call of Classifytrack() & for those tracks which have proper TPC PID response . combined nsigma(circular) cut only for particles having pt upto  4.0 Gev/c and beyond that use the asymmetric nsigma cut around pion's mean position in TPC ( while filling the  TObjArray for trig & asso )
3914 Float_t pt=track->Pt();
3915
3916 //plot the separation power
3917
3918 Double_t bethe[AliPID::kSPECIES]={0.};
3919 Double_t sigma_TPC[AliPID::kSPECIES]={0.}; 
3920
3921  Double_t Pi_Ka_sep[NSigmaPIDType+1]={0.};
3922  Double_t Pi_Pr_sep[NSigmaPIDType+1]={0.};
3923  Double_t Ka_Pr_sep[NSigmaPIDType+1]={0.};
3924
3925
3926     Double_t ptpc = track->GetTPCmomentum();
3927     Int_t dEdxN = track->GetTPCsignalN();
3928  for (Int_t ipart = 0; ipart < AliPID::kSPECIES; ipart++) {
3929        bethe[ipart] = fPID->GetTPCResponse().GetExpectedSignal(ptpc, (AliPID::EParticleType)ipart);
3930       //Double_t diff = dEdx - bethe;
3931        sigma_TPC[ipart] = fPID->GetTPCResponse().GetExpectedSigma(ptpc, dEdxN, (AliPID::EParticleType)ipart);
3932       //nSigma[ipart] = diff / sigma;
3933     }
3934  Pi_Ka_sep[NSigmaTPC]=TMath::Abs(bethe[AliPID::kPion]-bethe[AliPID::kKaon])/((sigma_TPC[AliPID::kPion]+sigma_TPC[AliPID::kKaon])/2.0);
3935  Pi_Pr_sep[NSigmaTPC]=TMath::Abs(bethe[AliPID::kPion]-bethe[AliPID::kProton])/((sigma_TPC[AliPID::kPion]+sigma_TPC[AliPID::kProton])/2.0);
3936  Ka_Pr_sep[NSigmaTPC]=TMath::Abs(bethe[AliPID::kKaon]-bethe[AliPID::kProton])/((sigma_TPC[AliPID::kKaon]+sigma_TPC[AliPID::kProton])/2.0);
3937
3938
3939 Double_t sigma_TOF[AliPID::kSPECIES]={0.}; 
3940
3941 if(HasTOFPID(track) && pt>fPtTOFPIDmin)
3942    {
3943  Double_t timei[AliPID::kSPECIES];
3944  track->GetIntegratedTimes(timei);
3945  for (Int_t ipart = 0; ipart < AliPID::kSPECIES; ipart++) {  sigma_TOF[ipart]= fPID->GetTOFResponse().GetExpectedSigma(track->P(), timei[ipart], AliPID::ParticleMass(ipart));}
3946  Pi_Ka_sep[NSigmaTOF]=TMath::Abs(timei[AliPID::kPion]-timei[AliPID::kKaon])/((sigma_TOF[AliPID::kPion]+sigma_TOF[AliPID::kKaon])/2.0);
3947  Pi_Pr_sep[NSigmaTOF]=TMath::Abs(timei[AliPID::kPion]-timei[AliPID::kProton])/((sigma_TOF[AliPID::kPion]+sigma_TOF[AliPID::kProton])/2.0);
3948  Ka_Pr_sep[NSigmaTOF]=TMath::Abs(timei[AliPID::kKaon]-timei[AliPID::kProton])/((sigma_TOF[AliPID::kKaon]+sigma_TOF[AliPID::kProton])/2.0);
3949
3950   Pi_Ka_sep[NSigmaTPCTOF]=TMath::Abs(Pi_Ka_sep[NSigmaTPC]*Pi_Ka_sep[NSigmaTPC]+Pi_Ka_sep[NSigmaTOF]*Pi_Ka_sep[NSigmaTOF]);
3951   Pi_Pr_sep[NSigmaTPCTOF]=TMath::Abs(Pi_Pr_sep[NSigmaTPC]*Pi_Pr_sep[NSigmaTPC]+Pi_Pr_sep[NSigmaTOF]*Pi_Pr_sep[NSigmaTOF]);
3952   Ka_Pr_sep[NSigmaTPCTOF]=TMath::Abs(Ka_Pr_sep[NSigmaTPC]*Ka_Pr_sep[NSigmaTPC]+Ka_Pr_sep[NSigmaTOF]*Ka_Pr_sep[NSigmaTOF]);
3953    }
3954
3955
3956 //fill separation power histograms
3957  for(Int_t ipid=0;ipid<=NSigmaPIDType;ipid++){
3958    if(ipid==0){
3959         TH2F *h=GetHistogram2D(Form("Pi_Ka_sep_%d",ipid));
3960         h->Fill(track->Pt(),Pi_Ka_sep[ipid]);
3961         TH2F *h1=GetHistogram2D(Form("Pi_Pr_sep_%d",ipid));
3962         h1->Fill(track->Pt(),Pi_Pr_sep[ipid]);
3963         TH2F *h2=GetHistogram2D(Form("Ka_Pr_sep_%d",ipid));
3964         h2->Fill(track->Pt(),Ka_Pr_sep[ipid]);
3965    }
3966    if(HasTOFPID(track) && pt>fPtTOFPIDmin && ipid!=0){
3967        TH2F *h=GetHistogram2D(Form("Pi_Ka_sep_%d",ipid));
3968         h->Fill(track->Pt(),Pi_Ka_sep[ipid]);
3969         TH2F *h1=GetHistogram2D(Form("Pi_Pr_sep_%d",ipid));
3970         h1->Fill(track->Pt(),Pi_Pr_sep[ipid]);
3971         TH2F *h2=GetHistogram2D(Form("Ka_Pr_sep_%d",ipid));
3972         h2->Fill(track->Pt(),Ka_Pr_sep[ipid]);
3973    }
3974  }
3975
3976
3977 //it is assumed that every track that passed the filterbit have proper TPC response(!!)
3978 Float_t nsigmaTPCkPion =fPID->NumberOfSigmasTPC(track, AliPID::kPion);
3979 Float_t nsigmaTPCkKaon =fPID->NumberOfSigmasTPC(track, AliPID::kKaon);
3980 Float_t nsigmaTPCkProton =fPID->NumberOfSigmasTPC(track, AliPID::kProton);
3981
3982 Float_t nsigmaTOFkProton=999.,nsigmaTOFkKaon=999.,nsigmaTOFkPion=999.;
3983 Float_t nsigmaTPCTOFkProton=999.,nsigmaTPCTOFkKaon=999.,nsigmaTPCTOFkPion=999.;
3984
3985  if(HasTOFPID(track) && pt>fPtTOFPIDmin)
3986    {
3987
3988 nsigmaTOFkPion =fPID->NumberOfSigmasTOF(track, AliPID::kPion);
3989 nsigmaTOFkKaon =fPID->NumberOfSigmasTOF(track, AliPID::kKaon);
3990 nsigmaTOFkProton =fPID->NumberOfSigmasTOF(track, AliPID::kProton);
3991 //---combined
3992 nsigmaTPCTOFkPion   = TMath::Sqrt(nsigmaTPCkPion*nsigmaTPCkPion+nsigmaTOFkPion*nsigmaTOFkPion);
3993 nsigmaTPCTOFkKaon   = TMath::Sqrt(nsigmaTPCkKaon*nsigmaTPCkKaon+nsigmaTOFkKaon*nsigmaTOFkKaon);
3994 nsigmaTPCTOFkProton = TMath::Sqrt(nsigmaTPCkProton*nsigmaTPCkProton+nsigmaTOFkProton*nsigmaTOFkProton);
3995
3996
3997    }
3998 else{
3999     // --- combined
4000     // if TOF is missing and below fPtTOFPID only the TPC information is used
4001     nsigmaTPCTOFkProton = TMath::Abs(nsigmaTPCkProton);
4002     nsigmaTPCTOFkKaon   = TMath::Abs(nsigmaTPCkKaon);
4003     nsigmaTPCTOFkPion   = TMath::Abs(nsigmaTPCkPion);
4004
4005   }
4006
4007 //set data member fnsigmas
4008   fnsigmas[SpPion][NSigmaTPC]=nsigmaTPCkPion;
4009   fnsigmas[SpKaon][NSigmaTPC]=nsigmaTPCkKaon;
4010   fnsigmas[SpProton][NSigmaTPC]=nsigmaTPCkProton;
4011
4012   //for all tracks below fPtTOFPIDmin  and also for tracks above fPtTOFPIDmin without proper TOF response these TOF nsigma values will be 999.
4013   fnsigmas[SpPion][NSigmaTOF]=nsigmaTOFkPion;
4014   fnsigmas[SpKaon][NSigmaTOF]=nsigmaTOFkKaon;
4015   fnsigmas[SpProton][NSigmaTOF]=nsigmaTOFkProton;
4016
4017  //for all tracks below fPtTOFPIDmin  and also for tracks above fPtTOFPIDmin without proper TOF response these TPCTOF nsigma values will be TMath::Abs(TPC only nsigma)
4018   fnsigmas[SpPion][NSigmaTPCTOF]=nsigmaTPCTOFkPion;
4019   fnsigmas[SpKaon][NSigmaTPCTOF]=nsigmaTPCTOFkKaon;
4020   fnsigmas[SpProton][NSigmaTPCTOF]=nsigmaTPCTOFkProton;
4021
4022  if(FIllQAHistos){
4023     //Fill NSigma SeparationPlot
4024     for(Int_t ipart=0;ipart<NSpecies;ipart++){
4025       for(Int_t ipid=0;ipid<=NSigmaPIDType;ipid++){
4026         if((ipid!=NSigmaTPC) && (!HasTOFPID(track)))continue;//not filling TOF and combined if no TOF PID
4027         TH2F *h=GetHistogram2D(Form("NSigma_%d_%d",ipart,ipid));
4028         h->Fill(track->Pt(),fnsigmas[ipart][ipid]);
4029       }
4030     }
4031   }
4032
4033 }
4034 //----------------------------------------------------------------------------
4035 Int_t AliTwoParticlePIDCorr::FindMinNSigma(AliAODTrack *track,Bool_t FillQAHistos) 
4036 {
4037   //this function is always called after calling the function CalculateNSigmas(AliAODTrack *track)
4038 if(fRequestTOFPID && track->Pt()>fPtTOFPIDmin && (!HasTOFPID(track)) )return SpUndefined;//so any track having Pt>0.6 withot having proper TOF response will be defined as SpUndefined
4039 //get the identity of the particle with the minimum Nsigma
4040   Float_t nsigmaPion=999., nsigmaKaon=999., nsigmaProton=999.;
4041   switch (fPIDType){
4042   case NSigmaTPC:
4043     nsigmaProton  =  TMath::Abs(fnsigmas[SpProton][NSigmaTPC]);
4044     nsigmaKaon    =  TMath::Abs(fnsigmas[SpKaon][NSigmaTPC])  ;
4045     nsigmaPion    =  TMath::Abs(fnsigmas[SpPion][NSigmaTPC])  ;
4046     break;
4047   case NSigmaTOF:
4048     nsigmaProton  =  TMath::Abs(fnsigmas[SpProton][NSigmaTOF]);
4049     nsigmaKaon    =  TMath::Abs(fnsigmas[SpKaon][NSigmaTOF])  ;
4050     nsigmaPion    =  TMath::Abs(fnsigmas[SpPion][NSigmaTOF])  ;
4051     break;
4052   case NSigmaTPCTOF://In case of no TOF matching the combined nsigma is the TPC one
4053     nsigmaProton  =  TMath::Abs(fnsigmas[SpProton][NSigmaTPCTOF]);
4054     nsigmaKaon    =  TMath::Abs(fnsigmas[SpKaon][NSigmaTPCTOF])  ;
4055     nsigmaPion    =  TMath::Abs(fnsigmas[SpPion][NSigmaTPCTOF])  ;
4056     break;
4057   case Bayes://the nsigma in the bayesian is used to clean with a very large n-sigma value
4058     nsigmaProton  =  TMath::Abs(fnsigmas[SpProton][NSigmaTPCTOF]);
4059     nsigmaKaon    =  TMath::Abs(fnsigmas[SpKaon][NSigmaTPCTOF])  ;
4060     nsigmaPion    =  TMath::Abs(fnsigmas[SpPion][NSigmaTPCTOF])  ;
4061     break;
4062   }
4063
4064
4065 if(fdiffPIDcutvalues){
4066   if(track->Pt()<=4) fNSigmaPID=fPIDCutval1;
4067   if(track->Pt()>4 && track->Pt()<=6) fNSigmaPID=fPIDCutval2;
4068   if(track->Pt()>6 && track->Pt()<=8) fNSigmaPID=fPIDCutval3;
4069   if(track->Pt()>8) fNSigmaPID=fPIDCutval4;
4070   }
4071
4072  // guess the particle based on the smaller nsigma (within fNSigmaPID)
4073   if( ( nsigmaKaon==nsigmaPion ) && ( nsigmaKaon==nsigmaProton )) return SpUndefined;//it is the default value for the three
4074
4075   if( ( nsigmaKaon   < nsigmaPion ) && ( nsigmaKaon < nsigmaProton ) && (nsigmaKaon < fNSigmaPID)){
4076     if((fHighPtKaonNSigmaPID>0) && (track->Pt()>fHighPtKaonSigma) && (nsigmaKaon > fHighPtKaonNSigmaPID)) return SpUndefined;//different nsigma cut for kaons above a particular Pt range(within the TPC-TOF PID range)
4077 if(FillQAHistos){
4078       for(Int_t ipid=0;ipid<=NSigmaPIDType;ipid++){
4079         if((ipid!=NSigmaTPC) && (!HasTOFPID(track)))continue;//not filling TOF and combined if no TOF PID
4080         TH2F *h=GetHistogram2D(Form("NSigmaRec_%d_%d",SpKaon,ipid));
4081         h->Fill(track->Pt(),fnsigmas[SpKaon][ipid]);
4082       }
4083     }
4084  return SpKaon;
4085   }
4086   if( ( nsigmaPion   < nsigmaKaon ) && ( nsigmaPion < nsigmaProton ) && (nsigmaPion < fNSigmaPID)) {
4087  if(FillQAHistos){
4088       for(Int_t ipid=0;ipid<=NSigmaPIDType;ipid++){
4089         if((ipid!=NSigmaTPC) && (!HasTOFPID(track)))continue;//not filling TOF and combined if no TOF PID
4090         TH2F *h=GetHistogram2D(Form("NSigmaRec_%d_%d",SpPion,ipid));
4091         h->Fill(track->Pt(),fnsigmas[SpPion][ipid]);
4092       }
4093     }
4094 return SpPion;
4095   }
4096   if( ( nsigmaProton < nsigmaKaon ) && ( nsigmaProton < nsigmaPion ) && (nsigmaProton < fNSigmaPID)) {
4097 if(FillQAHistos){
4098       for(Int_t ipid=0;ipid<=NSigmaPIDType;ipid++){
4099         if((ipid!=NSigmaTPC) && (!HasTOFPID(track)))continue;//not filling TOF and combined if no TOF PID
4100         TH2F *h=GetHistogram2D(Form("NSigmaRec_%d_%d",SpProton,ipid));
4101         h->Fill(track->Pt(),fnsigmas[SpProton][ipid]);
4102       }
4103  }
4104 return SpProton;
4105   }
4106
4107 // else, return undefined
4108   return SpUndefined;
4109   
4110  
4111 }
4112
4113 //------------------------------------------------------------------------------------------
4114 Bool_t* AliTwoParticlePIDCorr::GetDoubleCounting(AliAODTrack * trk,Bool_t FIllQAHistos){ 
4115   //this function is always called after calling the function CalculateNSigmas(AliAODTrack *track)
4116
4117   //if a particle has double counting set fHasDoubleCounting[ipart]=kTRUE
4118   //fill DC histos
4119   for(Int_t ipart=0;ipart<NSpecies;ipart++)fHasDoubleCounting[ipart]=kFALSE;//array with kTRUE for second (or third) identity of the track
4120   
4121   Int_t MinNSigma=FindMinNSigma(trk,kFALSE);//not filling the NSigmaRec histos
4122   
4123   
4124   if(MinNSigma==SpUndefined)return fHasDoubleCounting;//in case of undefined no Double counting
4125   
4126   Float_t nsigmaPion=999., nsigmaKaon=999., nsigmaProton=999.;
4127   switch (fPIDType) {
4128   case NSigmaTPC:
4129     nsigmaProton  =  TMath::Abs(fnsigmas[SpProton][NSigmaTPC]);
4130     nsigmaKaon    =  TMath::Abs(fnsigmas[SpKaon][NSigmaTPC])  ;
4131     nsigmaPion    =  TMath::Abs(fnsigmas[SpPion][NSigmaTPC])  ;
4132     break;
4133   case NSigmaTOF:
4134     nsigmaProton  =  TMath::Abs(fnsigmas[SpProton][NSigmaTOF]);
4135     nsigmaKaon    =  TMath::Abs(fnsigmas[SpKaon][NSigmaTOF])  ;
4136     nsigmaPion    =  TMath::Abs(fnsigmas[SpPion][NSigmaTOF])  ;
4137     break;
4138   case NSigmaTPCTOF://In case of no TOF matching the combined nsigma is the TPC one
4139     nsigmaProton  =  TMath::Abs(fnsigmas[SpProton][NSigmaTPCTOF]);
4140     nsigmaKaon    =  TMath::Abs(fnsigmas[SpKaon][NSigmaTPCTOF])  ;
4141     nsigmaPion    =  TMath::Abs(fnsigmas[SpPion][NSigmaTPCTOF])  ;
4142     break;
4143   case Bayes://the nsigma in the bayesian is used to clean with a very large n-sigma value
4144     nsigmaProton  =  TMath::Abs(fnsigmas[SpProton][NSigmaTPCTOF]);
4145     nsigmaKaon    =  TMath::Abs(fnsigmas[SpKaon][NSigmaTPCTOF])  ;
4146     nsigmaPion    =  TMath::Abs(fnsigmas[SpPion][NSigmaTPCTOF])  ;
4147     break;
4148   }
4149
4150   // Actually the tracks in the overlapping region(in TPC-TOF nSigma plane) will be ignored
4151
4152   if(nsigmaPion<fNSigmaPID && MinNSigma!=SpPion)fHasDoubleCounting[SpPion]=kTRUE;
4153   if(nsigmaKaon<fNSigmaPID && MinNSigma!=SpKaon)fHasDoubleCounting[SpKaon]=kTRUE;
4154   if(nsigmaProton<fNSigmaPID && MinNSigma!=SpProton)fHasDoubleCounting[SpProton]=kTRUE;
4155      
4156   
4157
4158 if(FIllQAHistos){
4159     //fill NSigma distr for double counting
4160     for(Int_t ipart=0;ipart<NSpecies;ipart++){
4161       if(fHasDoubleCounting[ipart]){//this may be kTRUE only for particles having Pt<=4.0 GeV/C, so this histo contains all the particles having Pt<=4.0 GeV/C in the nsigma overlapping region in TPC/TPC-TOF plane 
4162         for(Int_t ipid=0;ipid<=NSigmaPIDType;ipid++){
4163           if((ipid!=NSigmaTPC) && (!HasTOFPID(trk)))continue;//not filling TOF and combined if no TOF PID
4164           TH2F *h=GetHistogram2D(Form("NSigmaDC_%d_%d",ipart,ipid));
4165           h->Fill(trk->Pt(),fnsigmas[ipart][ipid]);
4166         }
4167       }
4168     }
4169   }
4170  
4171  
4172   return fHasDoubleCounting;
4173 }
4174
4175 //////////////////////////////////////////////////////////////////////////////////////////////////
4176
4177 Bool_t* AliTwoParticlePIDCorr::GetAllCompatibleIdentitiesNSigma(AliAODTrack * trk,Bool_t FIllQAHistos){ 
4178  //mainly intended to check the probability of the PID of the tracks which are in the overlapping nSigma regions and near about the middle position from the   mean position of two ID particle
4179   Bool_t *IDs=GetDoubleCounting(trk,FIllQAHistos);
4180   IDs[FindMinNSigma(trk,FIllQAHistos)]=kTRUE;
4181   return IDs;
4182   
4183 }
4184 //////////////////////////////////////////////////////////////////////////////////////////////////
4185
4186 UInt_t AliTwoParticlePIDCorr::CalcPIDCombined(AliAODTrack *track, Int_t detMask, Double_t* prob) const{
4187   //
4188   // Bayesian PID calculation
4189   //
4190   for(Int_t i=0;i<AliPID::kSPECIES;i++)
4191     {
4192       prob[i]=0.;
4193     }
4194   fPIDCombined->SetDetectorMask(detMask);
4195   
4196   return fPIDCombined->ComputeProbabilities((AliAODTrack*)track, fPID, prob);
4197 }
4198
4199 //////////////////////////////////////////////////////////////////////////////////////////////////
4200
4201 Int_t AliTwoParticlePIDCorr::GetIDBayes(AliAODTrack * trk, Bool_t FIllQAHistos){ 
4202   
4203   Bool_t *IDs=GetAllCompatibleIdentitiesNSigma(trk,FIllQAHistos);
4204
4205
4206   //Filling of Probability histos
4207         Double_t probTPC[AliPID::kSPECIES]={0.};
4208         Double_t probTOF[AliPID::kSPECIES]={0.};
4209         Double_t probTPCTOF[AliPID::kSPECIES]={0.};
4210
4211         UInt_t detUsedTPC = 0;
4212         UInt_t detUsedTOF = 0;
4213         UInt_t detUsedTPCTOF = 0;
4214
4215  //get the TPC probability
4216           fPIDCombined->SetDetectorMask(AliPIDResponse::kDetTPC);
4217           detUsedTPC = fPIDCombined->ComputeProbabilities(trk, fPID, probTPC);
4218 if(detUsedTPC == AliPIDResponse::kDetTPC)
4219   {
4220 for(Int_t ipart=0;ipart<NSpecies;ipart++){
4221
4222         TH2F *h=GetHistogram2D(Form("probBayes_TPC_%d",ipart));
4223         if(ipart==0)    h->Fill(trk->Pt(),probTPC[AliPID::kPion]);
4224         if(ipart==1)    h->Fill(trk->Pt(),probTPC[AliPID::kKaon]);
4225         if(ipart==2)    h->Fill(trk->Pt(),probTPC[AliPID::kProton]);
4226  }
4227   }
4228
4229   //get the TOF probability
4230           fPIDCombined->SetDetectorMask(AliPIDResponse::kDetTOF);
4231           detUsedTOF = fPIDCombined->ComputeProbabilities(trk, fPID, probTOF);
4232 if(detUsedTOF == AliPIDResponse::kDetTOF)
4233   {
4234 for(Int_t ipart=0;ipart<NSpecies;ipart++){
4235         TH2F *h=GetHistogram2D(Form("probBayes_TOF_%d",ipart));
4236         if(ipart==0)    h->Fill(trk->Pt(),probTOF[AliPID::kPion]);
4237         if(ipart==1)    h->Fill(trk->Pt(),probTOF[AliPID::kKaon]);
4238         if(ipart==2)    h->Fill(trk->Pt(),probTOF[AliPID::kProton]);
4239  }
4240   }
4241
4242  //get the TPC-TOF probability
4243           fPIDCombined->SetDetectorMask(AliPIDResponse::kDetTOF|AliPIDResponse::kDetTPC);
4244           detUsedTPCTOF = fPIDCombined->ComputeProbabilities(trk, fPID, probTPCTOF);
4245 if(detUsedTPCTOF == (AliPIDResponse::kDetTOF|AliPIDResponse::kDetTPC))
4246   {
4247 for(Int_t ipart=0;ipart<NSpecies;ipart++){
4248         TH2F *h=GetHistogram2D(Form("probBayes_TPCTOF_%d",ipart));
4249         if(ipart==0)    h->Fill(trk->Pt(),probTPCTOF[AliPID::kPion]);
4250         if(ipart==1)    h->Fill(trk->Pt(),probTPCTOF[AliPID::kKaon]);
4251         if(ipart==2)    h->Fill(trk->Pt(),probTPCTOF[AliPID::kProton]); 
4252 }
4253   }
4254
4255   
4256   Double_t probBayes[AliPID::kSPECIES];
4257   
4258   UInt_t detUsed= 0;
4259   if(HasTOFPID(trk) && trk->Pt()>fPtTOFPIDmin){//use TOF information
4260     detUsed = CalcPIDCombined(trk, AliPIDResponse::kDetTOF|AliPIDResponse::kDetTPC, probBayes);
4261     if(detUsed != (AliPIDResponse::kDetTOF|AliPIDResponse::kDetTPC))return SpUndefined;//check that TPC and TOF are used
4262   }else{
4263     detUsed = CalcPIDCombined(trk,AliPIDResponse::kDetTPC, probBayes);
4264     if(detUsed != AliPIDResponse::kDetTPC)return SpUndefined;//check that TPC is used
4265   }
4266   
4267   //the probability has to be normalized to one, we check it
4268   Double_t sump=0.;
4269   for(Int_t ipart=0;ipart<AliPID::kSPECIES;ipart++)sump+=probBayes[ipart];
4270   if(sump<.99 && sump>1.01){//FIXME precision problem in the sum, workaround
4271     AliFatal("Bayesian probability not normalized to one");
4272   }
4273
4274   if(fdiffPIDcutvalues){
4275   if(trk->Pt()<=4) fBayesCut=fPIDCutval1;
4276   if(trk->Pt()>4 && trk->Pt()<=6) fBayesCut=fPIDCutval2;
4277   if(trk->Pt()>6 && trk->Pt()<=8) fBayesCut=fPIDCutval3;
4278   if(trk->Pt()>8) fBayesCut=fPIDCutval4;
4279   }
4280
4281   
4282   //probabilities are normalized to one, if the cut is above .5 there is no problem
4283   if(probBayes[AliPID::kPion]>fBayesCut && IDs[SpPion]==1){
4284     TH2F *h=GetHistogram2D(Form("BayesRec_%d",SpPion));
4285     h->Fill(trk->Pt(),probBayes[AliPID::kPion]);
4286     return SpPion;
4287   }
4288   else if(probBayes[AliPID::kKaon]>fBayesCut && IDs[SpKaon]==1){
4289     TH2F *h=GetHistogram2D(Form("BayesRec_%d",SpKaon));
4290     h->Fill(trk->Pt(),probBayes[AliPID::kKaon]);
4291     return SpKaon;
4292   }
4293   else if(probBayes[AliPID::kProton]>fBayesCut && IDs[SpProton]==1){
4294     TH2F *h=GetHistogram2D(Form("BayesRec_%d",SpProton));
4295     h->Fill(trk->Pt(),probBayes[AliPID::kProton]);
4296     return SpProton;
4297   }
4298   else{
4299     return SpUndefined;
4300   }
4301 }
4302
4303
4304 //////////////////////////////////////////////////////////////////////////////////////////////////
4305 Int_t AliTwoParticlePIDCorr::GetParticle(AliAODTrack * trk, Bool_t FIllQAHistos){ 
4306   //return the specie according to the minimum nsigma value
4307   //no double counting, this has to be evaluated using CheckDoubleCounting()
4308   
4309   Int_t ID=SpUndefined;
4310
4311   CalculateNSigmas(trk,FIllQAHistos);//fill the data member fnsigmas with the nsigmas value [ipart][iPID]
4312
4313
4314  //Do PID
4315   if(fPIDType==Bayes){//use bayesianPID
4316     
4317     if(!fPIDCombined) {
4318       AliFatal("PIDCombined object has to be set in the steering macro");
4319     }
4320     
4321     ID = GetIDBayes(trk,FIllQAHistos);
4322     
4323   }else{ //use nsigma PID  
4324
4325    ID=FindMinNSigma(trk,FIllQAHistos);
4326 if(fUseExclusiveNSigma){ //if one particle has double counting and exclusive nsigma is requested ID = kSpUndefined
4327       Bool_t *HasDC;
4328       HasDC=GetDoubleCounting(trk,FIllQAHistos);
4329       for(Int_t ipart=0;ipart<NSpecies;ipart++){
4330         if(HasDC[ipart]==kTRUE)  ID = SpUndefined;
4331       }
4332     }
4333   }
4334 //Fill PID signal plot
4335   if(ID != SpUndefined){
4336     for(Int_t idet=0;idet<fNDetectors;idet++){
4337       TH2F *h=GetHistogram2D(Form("PID_%d_%d",idet,ID));
4338       if(idet==fITS)h->Fill(trk->P(),trk->GetITSsignal()*trk->Charge());
4339       if(idet==fTPC)h->Fill(trk->P(),trk->GetTPCsignal()*trk->Charge());
4340       if(idet==fTOF && HasTOFPID(trk))h->Fill(trk->P(),GetBeta(trk)*trk->Charge());
4341     }
4342   }
4343   //Fill PID signal plot without cuts
4344   for(Int_t idet=0;idet<fNDetectors;idet++){
4345     TH2F *h=GetHistogram2D(Form("PIDAll_%d",idet));
4346     if(idet==fITS)h->Fill(trk->P(),trk->GetITSsignal()*trk->Charge());
4347     if(idet==fTPC)h->Fill(trk->P(),trk->GetTPCsignal()*trk->Charge());
4348     if(idet==fTOF && HasTOFPID(trk))h->Fill(trk->P(),GetBeta(trk)*trk->Charge());
4349   }
4350   
4351   return ID;
4352 }
4353
4354 //-------------------------------------------------------------------------------------
4355 Bool_t
4356 AliTwoParticlePIDCorr::HasTPCPID(AliAODTrack *track) const
4357 {  
4358   // check PID signal 
4359    AliPIDResponse::EDetPidStatus statustpc = fPID->CheckPIDStatus(AliPIDResponse::kTPC,track);
4360    if(statustpc!=AliPIDResponse::kDetPidOk) return kFALSE;
4361    //ULong_t status=track->GetStatus();
4362    //if  (!( (status & AliAODTrack::kTPCpid  ) == AliAODTrack::kTPCpid  )) return kFALSE;//remove light nuclei
4363    //if (track->GetTPCsignal() <= 0.) return kFALSE;
4364    // if(track->GetTPCsignalN() < 60) return kFALSE;//tracks with TPCsignalN< 60 have questionable dEdx,cutting on TPCsignalN > 70 or > 60 shouldn't make too much difference in statistics,also  it is IMO safe to use TPC also for MIPs.
4365    
4366   return kTRUE;  
4367 }
4368 //___________________________________________________________
4369
4370 Bool_t
4371 AliTwoParticlePIDCorr::HasTOFPID(AliAODTrack *track) const
4372 {
4373   // check TOF matched track 
4374   //ULong_t status=track->GetStatus();
4375   //if  (!( (status & AliAODTrack::kITSin  ) == AliAODTrack::kITSin  )) return kFALSE;
4376  AliPIDResponse::EDetPidStatus statustof = fPID->CheckPIDStatus(AliPIDResponse::kTOF,track);
4377  if(statustof!= AliPIDResponse::kDetPidOk) return kFALSE;
4378   if(track->Pt()<=fPtTOFPIDmin) return kFALSE;
4379  //if(!((status & AliAODTrack::kTOFpid  ) == AliAODTrack::kTOFpid  )) return kFALSE;
4380  //Float_t probMis = fPIDresponse->GetTOFMismatchProbability(track);
4381  // if (probMis > 0.01) return kFALSE;
4382 if(fRemoveTracksT0Fill)
4383     {
4384 Int_t startTimeMask = fPID->GetTOFResponse().GetStartTimeMask(track->P());
4385       if (startTimeMask < 0)return kFALSE; 
4386     }
4387   return kTRUE;
4388 }
4389
4390 //________________________________________________________________________
4391 Double_t AliTwoParticlePIDCorr :: GetBeta(AliAODTrack *track)
4392 {
4393   //it is called only when TOF PID is available
4394 //TOF beta calculation
4395   Double_t tofTime=track->GetTOFsignal();
4396   
4397   Double_t c=TMath::C()*1.E-9;// m/ns
4398   Float_t startTime = fPID->GetTOFResponse().GetStartTime(((AliVTrack*)track)->P());//in ps
4399   Double_t length= fPID->GetTOFResponse().GetExpectedSignal(track,AliPID::kElectron)*1E-3*c;
4400   tofTime -= startTime;      // subtract startTime to the signal
4401   Double_t tof= tofTime*1E-3; // ns, average T0 fill subtracted, no info from T0detector         
4402   tof=tof*c;
4403   return length/tof;
4404
4405
4406   /*
4407   Double_t p = track->P();
4408   Double_t time=track->GetTOFsignal()-fPID->GetTOFResponse().GetStartTime(p);
4409   Double_t timei[5];
4410   track->GetIntegratedTimes(timei);
4411   return timei[0]/time;
4412   */
4413 }
4414 //------------------------------------------------------------------------------------------------------
4415
4416 Float_t AliTwoParticlePIDCorr::GetInvMassSquared(Float_t pt1, Float_t eta1, Float_t phi1, Float_t pt2, Float_t eta2, Float_t phi2, Float_t m0_1, Float_t m0_2)
4417 {
4418   // calculate inv mass squared
4419   // same can be achieved, but with more computing time with
4420   /*TLorentzVector photon, p1, p2;
4421   p1.SetPtEtaPhiM(triggerParticle->Pt(), triggerEta, triggerParticle->Phi(), 0.510e-3);
4422   p2.SetPtEtaPhiM(particle->Pt(), eta[j], particle->Phi(), 0.510e-3);
4423   photon = p1+p2;
4424   photon.M()*/
4425   
4426   Float_t tantheta1 = 1e10;
4427   
4428   if (eta1 < -1e-10 || eta1 > 1e-10)
4429     tantheta1 = 2 * TMath::Exp(-eta1) / ( 1 - TMath::Exp(-2*eta1));
4430   
4431   Float_t tantheta2 = 1e10;
4432   if (eta2 < -1e-10 || eta2 > 1e-10)
4433     tantheta2 = 2 * TMath::Exp(-eta2) / ( 1 - TMath::Exp(-2*eta2));
4434   
4435   Float_t e1squ = m0_1 * m0_1 + pt1 * pt1 * (1.0 + 1.0 / tantheta1 / tantheta1);
4436   Float_t e2squ = m0_2 * m0_2 + pt2 * pt2 * (1.0 + 1.0 / tantheta2 / tantheta2);
4437   
4438   Float_t mass2 = m0_1 * m0_1 + m0_2 * m0_2 + 2 * ( TMath::Sqrt(e1squ * e2squ) - ( pt1 * pt2 * ( TMath::Cos(phi1 - phi2) + 1.0 / tantheta1 / tantheta2 ) ) );
4439   
4440   return mass2;
4441 }
4442 //---------------------------------------------------------------------------------
4443
4444 Float_t AliTwoParticlePIDCorr::GetInvMassSquaredCheap(Float_t pt1, Float_t eta1, Float_t phi1, Float_t pt2, Float_t eta2, Float_t phi2, Float_t m0_1, Float_t m0_2)
4445 {
4446   // calculate inv mass squared approximately
4447   
4448   Float_t tantheta1 = 1e10;
4449   
4450   if (eta1 < -1e-10 || eta1 > 1e-10)
4451   {
4452     Float_t expTmp = 1.0-eta1+eta1*eta1/2-eta1*eta1*eta1/6+eta1*eta1*eta1*eta1/24;
4453     tantheta1 = 2.0 * expTmp / ( 1.0 - expTmp*expTmp);
4454   }
4455   
4456   Float_t tantheta2 = 1e10;
4457   if (eta2 < -1e-10 || eta2 > 1e-10)
4458   {
4459     Float_t expTmp = 1.0-eta2+eta2*eta2/2-eta2*eta2*eta2/6+eta2*eta2*eta2*eta2/24;
4460     tantheta2 = 2.0 * expTmp / ( 1.0 - expTmp*expTmp);
4461   }
4462   
4463   Float_t e1squ = m0_1 * m0_1 + pt1 * pt1 * (1.0 + 1.0 / tantheta1 / tantheta1);
4464   Float_t e2squ = m0_2 * m0_2 + pt2 * pt2 * (1.0 + 1.0 / tantheta2 / tantheta2);
4465   
4466   // fold onto 0...pi
4467   Float_t deltaPhi = TMath::Abs(phi1 - phi2);
4468   while (deltaPhi > TMath::TwoPi())
4469     deltaPhi -= TMath::TwoPi();
4470   if (deltaPhi > TMath::Pi())
4471     deltaPhi = TMath::TwoPi() - deltaPhi;
4472   
4473   Float_t cosDeltaPhi = 0;
4474   if (deltaPhi < TMath::Pi()/3)
4475     cosDeltaPhi = 1.0 - deltaPhi*deltaPhi/2 + deltaPhi*deltaPhi*deltaPhi*deltaPhi/24;
4476   else if (deltaPhi < 2*TMath::Pi()/3)
4477     cosDeltaPhi = -(deltaPhi - TMath::Pi()/2) + 1.0/6 * TMath::Power((deltaPhi - TMath::Pi()/2), 3);
4478   else
4479     cosDeltaPhi = -1.0 + 1.0/2.0*(deltaPhi - TMath::Pi())*(deltaPhi - TMath::Pi()) - 1.0/24.0 * TMath::Power(deltaPhi - TMath::Pi(), 4);
4480   
4481   Float_t mass2 = m0_1 * m0_1 + m0_2 * m0_2 + 2 * ( TMath::Sqrt(e1squ * e2squ) - ( pt1 * pt2 * ( cosDeltaPhi + 1.0 / tantheta1 / tantheta2 ) ) );
4482   
4483 //   Printf(Form("%f %f %f %f %f %f %f %f %f", pt1, eta1, phi1, pt2, eta2, phi2, m0_1, m0_2, mass2));
4484   
4485   return mass2;
4486 }
4487 //--------------------------------------------------------------------------------
4488 Float_t  AliTwoParticlePIDCorr::GetDPhiStar(Float_t phi1, Float_t pt1, Float_t charge1, Float_t phi2, Float_t pt2, Float_t charge2, Float_t radius, Float_t bSign)
4489
4490   //
4491   // calculates dphistar
4492   //
4493   
4494   Float_t dphistar = phi1 - phi2 - charge1 * bSign * TMath::ASin(0.075 * radius / pt1) + charge2 * bSign * TMath::ASin(0.075 * radius / pt2);
4495   
4496   static const Double_t kPi = TMath::Pi();
4497   
4498   // circularity
4499 //   if (dphistar > 2 * kPi)
4500 //     dphistar -= 2 * kPi;
4501 //   if (dphistar < -2 * kPi)
4502 //     dphistar += 2 * kPi;
4503   
4504   if (dphistar > kPi)
4505     dphistar = kPi * 2 - dphistar;
4506   if (dphistar < -kPi)
4507     dphistar = -kPi * 2 - dphistar;
4508   if (dphistar > kPi) // might look funny but is needed
4509     dphistar = kPi * 2 - dphistar;
4510   
4511   return dphistar;
4512 }
4513
4514 //------------------------------------------------------------------------
4515 Double_t* AliTwoParticlePIDCorr::GetBinning(const char* configuration, const char* tag, Int_t& nBins)
4516 {
4517   // This method is a copy from AliUEHist::GetBinning
4518   // takes the binning from <configuration> identified by <tag>
4519   // configuration syntax example:
4520   // eta: 2.4, -2.3, -2.2, -2.1, -2.0, -1.9, -1.8, -1.7, -1.6, -1.5, -1.4, -1.3, -1.2, -1.1, -1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.1, 2.2, 2.3, 2.4
4521   // phi: .....
4522   //
4523   // returns bin edges which have to be deleted by the caller
4524   
4525   TString config(configuration);
4526   TObjArray* lines = config.Tokenize("\n");
4527   for (Int_t i=0; i<lines->GetEntriesFast(); i++)
4528   {
4529     TString line(lines->At(i)->GetName());
4530     if (line.BeginsWith(TString(tag) + ":"))
4531     {
4532       line.Remove(0, strlen(tag) + 1);
4533       line.ReplaceAll(" ", "");
4534       TObjArray* binning = line.Tokenize(",");
4535       Double_t* bins = new Double_t[binning->GetEntriesFast()];
4536       for (Int_t j=0; j<binning->GetEntriesFast(); j++)
4537         bins[j] = TString(binning->At(j)->GetName()).Atof();
4538       
4539       nBins = binning->GetEntriesFast() - 1;
4540
4541       delete binning;
4542       delete lines;
4543       return bins;
4544     }
4545   }
4546   
4547   delete lines;
4548   AliFatal(Form("Tag %s not found in %s", tag, configuration));
4549   return 0;
4550 }
4551
4552 //____________________________________________________________________
4553
4554 Bool_t AliTwoParticlePIDCorr::CheckTrack(AliAODTrack * part)
4555 {
4556   // check if the track status flags are set
4557   
4558   UInt_t status=((AliAODTrack*)part)->GetStatus();
4559   if ((status & fTrackStatus) == fTrackStatus)
4560     return kTRUE;
4561   return kFALSE;
4562 }
4563 //________________________________________________________________________
4564
4565 Bool_t AliTwoParticlePIDCorr::AcceptEventCentralityWeight(Double_t centrality)
4566 {
4567   // rejects "randomly" events such that the centrality gets flat
4568   // uses fCentralityWeights histogram
4569
4570   // TODO code taken and adapted from AliRDHFCuts; waiting for general class AliCentralityFlattening
4571   
4572   Double_t weight = fCentralityWeights->GetBinContent(fCentralityWeights->FindBin(centrality));
4573   Double_t centralityDigits = centrality*100. - (Int_t)(centrality*100.);
4574   
4575   Bool_t result = kFALSE;
4576   if (centralityDigits < weight) 
4577     result = kTRUE;
4578   
4579   AliInfo(Form("Centrality: %f; Digits: %f; Weight: %f; Result: %d", centrality, centralityDigits, weight, result));
4580   
4581   return result;
4582 }
4583
4584 //____________________________________________________________________
4585 void AliTwoParticlePIDCorr::ShiftTracks(TObjArray* tracks, Double_t angle)
4586 {
4587   // shifts the phi angle of all tracks by angle
4588   // 0 <= angle <= 2pi
4589   
4590   for (Int_t i=0; i<tracks->GetEntriesFast(); ++i) 
4591   {
4592    LRCParticlePID *part=(LRCParticlePID*)(tracks->UncheckedAt(i));
4593
4594     Double_t newAngle = part->Phi() + angle; 
4595     if (newAngle >= TMath::TwoPi())
4596       newAngle -= TMath::TwoPi();
4597     
4598     part->SetPhi(newAngle);
4599   }
4600 }
4601
4602
4603 //________________________________________________________________________
4604 void  AliTwoParticlePIDCorr::SetVZEROCalibrationFile(const char* filename,const char* lhcPeriod) {
4605   //Function to setup the VZERO gain equalization
4606     //============Get the equilization map============//
4607   TFile *calibrationFile = TFile::Open(filename);
4608   if((!calibrationFile)||(!calibrationFile->IsOpen())) {
4609     Printf("No calibration file found!!!");
4610     return;
4611   }
4612
4613   TList *list = dynamic_cast<TList *>(calibrationFile->Get(lhcPeriod));
4614   if(!list) {
4615     Printf("Calibration TList not found!!!");
4616     return;
4617   }
4618
4619   fHistVZEROAGainEqualizationMap = dynamic_cast<TH1F *>(list->FindObject("gHistVZEROAGainEqualizationMap"));
4620   if(!fHistVZEROAGainEqualizationMap) {
4621     Printf("VZERO-A calibration object not found!!!");
4622     return;
4623   }
4624   fHistVZEROCGainEqualizationMap = dynamic_cast<TH1F *>(list->FindObject("gHistVZEROCGainEqualizationMap"));
4625   if(!fHistVZEROCGainEqualizationMap) {
4626     Printf("VZERO-C calibration object not found!!!");
4627     return;
4628   }
4629
4630   fHistVZEROChannelGainEqualizationMap = dynamic_cast<TH2F *>(list->FindObject("gHistVZEROChannelGainEqualizationMap"));
4631   if(!fHistVZEROChannelGainEqualizationMap) {
4632     Printf("VZERO channel calibration object not found!!!");
4633     return;
4634   }
4635 }
4636
4637 //________________________________________________________________________
4638 Double_t AliTwoParticlePIDCorr::GetChannelEqualizationFactor(Int_t run,Int_t channel) {
4639   //
4640   if(!fHistVZEROAGainEqualizationMap) return 1.0;
4641
4642   for(Int_t iBinX = 1; iBinX <= fHistVZEROChannelGainEqualizationMap->GetNbinsX(); iBinX++) {
4643     Int_t gRunNumber = atoi(fHistVZEROChannelGainEqualizationMap->GetXaxis()->GetBinLabel(iBinX));
4644     if(gRunNumber == run)
4645       return fHistVZEROChannelGainEqualizationMap->GetBinContent(iBinX,channel+1);
4646   }
4647
4648   return 1.0;
4649 }
4650
4651 //________________________________________________________________________
4652 Double_t AliTwoParticlePIDCorr::GetEqualizationFactor(Int_t run, const char* side) {
4653   //
4654   if(!fHistVZEROAGainEqualizationMap) return 1.0;
4655
4656   TString gVZEROSide = side;
4657   for(Int_t iBinX = 1; iBinX < fHistVZEROAGainEqualizationMap->GetNbinsX(); iBinX++) {
4658     Int_t gRunNumber = atoi(fHistVZEROAGainEqualizationMap->GetXaxis()->GetBinLabel(iBinX));
4659     //cout<<"Looking for run "<<run<<" - current run: "<<gRunNumber<<endl;
4660     if(gRunNumber == run) {
4661       if(gVZEROSide == "A") 
4662         return fHistVZEROAGainEqualizationMap->GetBinContent(iBinX);
4663       else if(gVZEROSide == "C") 
4664         return fHistVZEROCGainEqualizationMap->GetBinContent(iBinX);
4665     }
4666   }
4667
4668   return 1.0;
4669 }
4670 //________________________________________________________________________
4671 Double_t AliTwoParticlePIDCorr::GetReferenceMultiplicityVZEROFromAOD(AliVEvent *mainevent){
4672   //Function that returns the reference multiplicity from AODs (data or reco MC, Not for Truth)
4673   //Different ref. mult. implemented: V0M, V0A, V0C, TPC
4674   if(!mainevent) return -1;
4675
4676       AliAODEvent* event = dynamic_cast<AliAODEvent*>(mainevent);
4677
4678   Double_t gRefMultiplicity = 0., gRefMultiplicityTPC = 0.;
4679   Double_t gRefMultiplicityVZERO = 0., gRefMultiplicityVZEROA = 0., gRefMultiplicityVZEROC = 0.;
4680
4681   AliAODHeader *header = dynamic_cast<AliAODHeader *>(event->GetHeader());
4682   if(!header) {
4683     Printf("ERROR: AOD header not available");
4684     return -999;
4685   }
4686   Int_t gRunNumber = header->GetRunNumber();
4687  Float_t bSign1=header->GetMagneticField() ;//for dca cut in ClassifyTrack(), i.e in track loop
4688
4689
4690  for (Int_t itrk = 0; itrk < event->GetNumberOfTracks(); itrk++) 
4691 { //track loop starts for TObjArray(containing track and event information) filling; used for correlation function calculation 
4692   AliAODTrack* track = dynamic_cast<AliAODTrack*>(event->GetTrack(itrk));
4693   if (!track) continue;
4694   Int_t tracktype=ClassifyTrack(track,trkVtx,bSign1,kFALSE);//don't fill the histos here
4695   if(tracktype!=1) continue; 
4696
4697   if(!track) continue;//for safety
4698
4699     gRefMultiplicityTPC += 1.0;
4700
4701  }//track looop ends
4702
4703  if(fCentralityMethod == "V0A_MANUAL" || fCentralityMethod == "V0M_MANUAL" || fCentralityMethod == "V0C_MANUAL" ){
4704   //VZERO segmentation in two detectors (0-31: VZERO-C, 32-63: VZERO-A)
4705   for(Int_t iChannel = 0; iChannel < 64; iChannel++) {
4706     fHistVZEROSignal->Fill(iChannel,event->GetVZEROEqMultiplicity(iChannel));
4707     
4708     if(iChannel < 32) 
4709       gRefMultiplicityVZEROC += event->GetVZEROEqMultiplicity(iChannel);
4710     else if(iChannel >= 32) 
4711       gRefMultiplicityVZEROA += event->GetVZEROEqMultiplicity(iChannel);
4712   }//loop over PMTs
4713   
4714   //Equalization of gain
4715   Double_t gFactorA = GetEqualizationFactor(gRunNumber,"A");
4716   if(gFactorA != 0)
4717     gRefMultiplicityVZEROA /= gFactorA;
4718   Double_t gFactorC = GetEqualizationFactor(gRunNumber,"C");
4719   if(gFactorC != 0)
4720     gRefMultiplicityVZEROC /= gFactorC;
4721   if((gFactorA != 0)&&(gFactorC != 0)) 
4722     gRefMultiplicityVZERO = (gRefMultiplicityVZEROA/gFactorA)+(gRefMultiplicityVZEROC/gFactorC);
4723
4724       
4725   //EQVZERO vs TPC multiplicity
4726   fHistEQVZEROvsTPCmultiplicity->Fill(gRefMultiplicityVZERO,gRefMultiplicityTPC);
4727   fHistEQVZEROAvsTPCmultiplicity->Fill(gRefMultiplicityVZEROA,gRefMultiplicityTPC);
4728   fHistEQVZEROCvsTPCmultiplicity->Fill(gRefMultiplicityVZEROC,gRefMultiplicityTPC);
4729
4730   //EQVZERO vs VZERO multiplicity
4731   fHistVZEROCvsEQVZEROCmultiplicity->Fill(event->GetVZEROData()->GetMTotV0C(),gRefMultiplicityVZEROC);
4732   fHistVZEROAvsEQVZEROAmultiplicity->Fill(event->GetVZEROData()->GetMTotV0A(),gRefMultiplicityVZEROA);
4733
4734   //VZEROC vs VZEROA multiplicity
4735   fHistVZEROCvsVZEROAmultiplicity->Fill(event->GetVZEROData()->GetMTotV0C(),event->GetVZEROData()->GetMTotV0A());
4736
4737   //EQVZEROC vs EQVZEROA multiplicity
4738   fHistEQVZEROCvsEQVZEROAmultiplicity->Fill(gRefMultiplicityVZEROC,gRefMultiplicityVZEROA);
4739  }
4740     fHistRefmult->Fill(3.,gRefMultiplicityTPC);
4741     fHistRefmult->Fill(2.,gRefMultiplicityVZERO);
4742     fHistRefmult->Fill(0.,gRefMultiplicityVZEROA);
4743     fHistRefmult->Fill(1.,gRefMultiplicityVZEROC);
4744
4745
4746  if(fCentralityMethod == "TRACKS_MANUAL") gRefMultiplicity = gRefMultiplicityTPC;
4747    
4748  else if(fCentralityMethod == "V0M_MANUAL") gRefMultiplicity = gRefMultiplicityVZERO;
4749
4750  else if(fCentralityMethod == "V0A_MANUAL")  gRefMultiplicity = gRefMultiplicityVZEROA;
4751    
4752  else if(fCentralityMethod == "V0C_MANUAL") gRefMultiplicity = gRefMultiplicityVZEROC;
4753  
4754  else gRefMultiplicity = gRefMultiplicityTPC;
4755  
4756   return gRefMultiplicity;
4757 }
4758
4759 //-------------------------------------------------------------------------------------------------------
4760 Double_t AliTwoParticlePIDCorr::GetRefMultiOrCentrality(AliVEvent *mainevent, Bool_t truth){
4761
4762   if(!mainevent) return -1;
4763   // get centrality object and check quality
4764   Double_t cent_v0=-1;
4765   Bool_t shift_to_TRACKS_MANUAL=kFALSE;//in case of wrong setting automatic shift to Tracks_Manual method
4766
4767   Double_t gRefMultiplicityTPC_Truth = 0.;
4768   Double_t gRefMultiplicityVZERO_Truth = 0., gRefMultiplicityVZEROA_Truth = 0., gRefMultiplicityVZEROC_Truth = 0.;
4769
4770   if(fAnalysisType == "AOD"|| fAnalysisType == "MCAOD") { //centrality in AOD header  //++++++++++++++
4771       AliAODEvent* event = dynamic_cast<AliAODEvent*>(mainevent);
4772
4773 if(fCentralityMethod=="V0M" || fCentralityMethod=="V0A" || fCentralityMethod=="V0C" || fCentralityMethod=="CL1" || fCentralityMethod=="ZNA" || fCentralityMethod=="V0AEq" || fCentralityMethod=="V0CEq" || fCentralityMethod=="V0MEq")//for PbPb, pPb, pp7TeV(still to be introduced)//data or RecoMC and also for TRUTH
4774     {
4775                    
4776 if(fSampleType=="pp_7" && fPPVsMultUtils)
4777    {//for pp 7 TeV case only using Alianalysisutils class
4778         if(fAnalysisUtils) cent_v0 = fAnalysisUtils->GetMultiplicityPercentile((AliVEvent*)event,fCentralityMethod);
4779         else cent_v0 = -1;
4780   fHistCentStats->Fill(0.,fAnalysisUtils->GetMultiplicityPercentile((AliVEvent*)event,"V0A"));
4781   fHistCentStats->Fill(1.,fAnalysisUtils->GetMultiplicityPercentile((AliVEvent*)event,"V0C"));
4782   fHistCentStats->Fill(2.,fAnalysisUtils->GetMultiplicityPercentile((AliVEvent*)event,"V0M"));   
4783   fHistCentStats->Fill(3.,fAnalysisUtils->GetMultiplicityPercentile((AliVEvent*)event,"V0AEq"));//only available for LHC10d at present (Quantile info)
4784   fHistCentStats->Fill(4.,fAnalysisUtils->GetMultiplicityPercentile((AliVEvent*)event,"V0CEq"));//only available for LHC10d at present (Quantile info)
4785   fHistCentStats->Fill(5.,fAnalysisUtils->GetMultiplicityPercentile((AliVEvent*)event,"V0MEq"));//only available for LHC10d at present (Quantile info)
4786       }
4787               
4788 else if(fSampleType=="pPb" || fSampleType=="PbPb")
4789   {
4790   AliCentrality *centralityObj=0;
4791   AliAODHeader *header = (AliAODHeader*) event->GetHeader();
4792   if(!header) return -1;
4793   centralityObj = header->GetCentralityP();
4794   // if (centrality->GetQuality() != 0) return ;
4795   if(centralityObj){
4796   fHistCentStats->Fill(0.,centralityObj->GetCentralityPercentile("V0A"));
4797   fHistCentStats->Fill(1.,centralityObj->GetCentralityPercentile("V0C"));
4798   fHistCentStats->Fill(2.,centralityObj->GetCentralityPercentile("V0M"));
4799   fHistCentStats->Fill(3.,centralityObj->GetCentralityPercentile("V0AEq"));//only available for LHC10d at present (Quantile info)
4800   fHistCentStats->Fill(4.,centralityObj->GetCentralityPercentile("V0CEq"));//only available for LHC10d at present (Quantile info)
4801   fHistCentStats->Fill(5.,centralityObj->GetCentralityPercentile("V0MEq"));//only available for LHC10d at present (Quantile info)
4802
4803   fHistCentStats->Fill(6.,centralityObj->GetCentralityPercentile("CL1"));
4804   fHistCentStats->Fill(7.,centralityObj->GetCentralityPercentile("ZNA")); 
4805
4806    cent_v0 = centralityObj->GetCentralityPercentile(fCentralityMethod);
4807     }
4808   else cent_v0= -1;    
4809   }
4810  else shift_to_TRACKS_MANUAL=kTRUE;    
4811
4812     }//centralitymethod condition
4813
4814  else if(fCentralityMethod=="V0M_MANUAL" || fCentralityMethod=="V0A_MANUAL" || fCentralityMethod=="V0C_MANUAL" || fCentralityMethod=="TRACKS_MANUAL" || shift_to_TRACKS_MANUAL)//data or RecoMc and also for TRUTH
4815    {
4816      if(!truth){//for data or RecoMC
4817        cent_v0 = GetReferenceMultiplicityVZEROFromAOD((AliVEvent*)event);
4818    }//for data or RecoMC
4819
4820     if(truth && (fAnalysisType == "MCAOD")){//condition for TRUTH case
4821 //check for TClonesArray(truth track MC information)
4822 fArrayMC = dynamic_cast<TClonesArray*>(event->FindListObject(AliAODMCParticle::StdBranchName()));
4823   if (!fArrayMC) {
4824     //AliFatal("Error: MC particles branch not found!\n");
4825     return -1;
4826   }
4827 //now process the truth particles(for both efficiency & correlation function)
4828 Int_t nMCTrack = fArrayMC->GetEntriesFast();
4829   
4830 for (Int_t iMC = 0; iMC < nMCTrack; iMC++) 
4831 {//MC truth track loop starts
4832     
4833 AliAODMCParticle *partMC = (AliAODMCParticle*) fArrayMC->At(iMC);
4834     
4835     if(!partMC){
4836       AliError(Form("ERROR: Could not retrieve AODMCtrack %d",iMC));
4837       continue;
4838     }
4839
4840 //consider only charged particles
4841     if(partMC->Charge() == 0) continue;
4842
4843 //consider only primary particles; neglect all secondary particles including from weak decays
4844  if(fselectprimaryTruth && !partMC->IsPhysicalPrimary()) continue;
4845
4846
4847 //remove injected signals(primaries above <maxLabel>)
4848  if (fInjectedSignals && partMC->GetLabel() >= skipParticlesAbove) continue;
4849
4850 //remove duplicates
4851   Bool_t isduplicate=kFALSE;
4852  if (fRemoveDuplicates)
4853    { 
4854  for (Int_t j=iMC+1; j<nMCTrack; ++j) 
4855    {//2nd trutuh loop starts
4856 AliAODMCParticle *partMC2 = (AliAODMCParticle*) fArrayMC->At(j);
4857    if(!partMC2){
4858       AliError(Form("ERROR: Could not retrieve AODMCtrack %d",j));
4859       continue;
4860     }    
4861  if (partMC->GetLabel() == partMC2->GetLabel())
4862    {
4863 isduplicate=kTRUE;
4864  break;  
4865    }    
4866    }//2nd truth loop ends
4867    }
4868  if(fRemoveDuplicates && isduplicate) continue;//remove duplicates
4869
4870
4871        //  if (fCentralityMethod=="V0M_MANUAL") 
4872         if((partMC->Eta() < 5.1 && partMC->Eta() > 2.8) || (partMC->Eta() > -3.7 && partMC->Eta() < -1.7)) gRefMultiplicityVZERO_Truth+=1;
4873         //   else if (fCentralityMethod=="V0A_MANUAL") {
4874         if(partMC->Eta() < 5.1 && partMC->Eta() > 2.8)  gRefMultiplicityVZEROA_Truth+=1;
4875         // else if (fCentralityMethod=="V0C_MANUAL") {
4876         if(partMC->Eta() < -1.7 && partMC->Eta() > -3.7)  gRefMultiplicityVZEROC_Truth+=1;
4877         //else if (fCentralityMethod=="TRACKS_MANUAL") {
4878         if (partMC->Eta() > fmineta && partMC->Eta() < fmaxeta) {
4879           if (partMC->Pt() > fminPt &&  partMC->Pt() < fmaxPt) gRefMultiplicityTPC_Truth+=1;
4880            }
4881      
4882  }//truth track loop ends
4883
4884  fHistRefmult->Fill(3.,gRefMultiplicityTPC_Truth);
4885  fHistRefmult->Fill(2.,gRefMultiplicityVZERO_Truth); 
4886  fHistRefmult->Fill(0.,gRefMultiplicityVZEROA_Truth);
4887  fHistRefmult->Fill(1.,gRefMultiplicityVZEROC_Truth);
4888
4889  if(fCentralityMethod == "TRACKS_MANUAL")   cent_v0=gRefMultiplicityTPC_Truth;
4890
4891  else if(fCentralityMethod == "V0M_MANUAL")  cent_v0=gRefMultiplicityVZERO_Truth;
4892
4893  else if(fCentralityMethod == "V0A_MANUAL")  cent_v0=gRefMultiplicityVZEROA_Truth;
4894
4895  else if(fCentralityMethod == "V0C_MANUAL")  cent_v0=gRefMultiplicityVZEROC_Truth;
4896  
4897  else      cent_v0=gRefMultiplicityTPC_Truth;
4898
4899     }//condition for TRUTH case
4900
4901    }//end of MANUAL method
4902
4903  else if ((fAnalysisType == "MCAOD") && (fCentralityMethod == "MC_b"))//TRUTH MC in AOD production
4904     {
4905     AliAODMCHeader* header = (AliAODMCHeader*) event->GetList()->FindObject(AliAODMCHeader::StdBranchName());
4906     if (!header)
4907     return -1;
4908     
4909       AliGenEventHeader* eventHeader = header->GetCocktailHeader(0);  // get first MC header from either ESD/AOD (including cocktail header if available)
4910       if (!eventHeader)
4911       {
4912         // We avoid AliFatal here, because the AOD productions sometimes have events where the MC header is missing 
4913         // (due to unreadable Kinematics) and we don't want to loose the whole job because of a few events
4914         AliError("Event header not found. Skipping this event.");
4915         return -1;
4916       }
4917       
4918       AliCollisionGeometry* collGeometry = dynamic_cast<AliCollisionGeometry*> (eventHeader);
4919      
4920       
4921       if (collGeometry) {
4922   cent_v0 = collGeometry->ImpactParameter();
4923   fhistImpactParm->Fill(cent_v0);
4924       }
4925       else cent_v0=-1.;
4926     }//end of Impact parameter method
4927
4928 //else return -1
4929  else cent_v0=-1.;
4930 }//AOD OR MCAOD condition
4931
4932
4933 else if(fAnalysisType == "MC"){
4934     Double_t gImpactParameter = -1.;
4935     AliMCEvent *gMCEvent = dynamic_cast<AliMCEvent*>(mainevent);
4936     if(gMCEvent){
4937       AliCollisionGeometry* headerH = dynamic_cast<AliCollisionGeometry*>(gMCEvent->GenEventHeader());      
4938       if(headerH){
4939         gImpactParameter = headerH->ImpactParameter();
4940
4941  for(Int_t iParticle = 0; iParticle < gMCEvent->GetNumberOfPrimaries(); iParticle++) {
4942       AliMCParticle* track = dynamic_cast<AliMCParticle *>(gMCEvent->GetTrack(iParticle));
4943       if (!track) {
4944         AliError(Form("Could not receive particle %d", iParticle));
4945         continue;
4946       }
4947       
4948       //exclude non stable particles
4949       if(!(gMCEvent->IsPhysicalPrimary(iParticle))) continue;
4950
4951       if(track->Charge() == 0) continue;
4952
4953  //  if (fCentralityMethod=="V0M_MANUAL") 
4954         if((track->Eta() < 5.1 && track->Eta() > 2.8) || (track->Eta() > -3.7 && track->Eta() < -1.7)) gRefMultiplicityVZERO_Truth+=1;
4955         //   else if (fCentralityMethod=="V0A_MANUAL") {
4956         if(track->Eta() < 5.1 && track->Eta() > 2.8)  gRefMultiplicityVZEROA_Truth+=1;
4957         // else if (fCentralityMethod=="V0C_MANUAL") {
4958         if(track->Eta() < -1.7 && track->Eta() > -3.7)  gRefMultiplicityVZEROC_Truth+=1;
4959         //else if (fCentralityMethod=="TRACKS_MANUAL") {
4960         if (track->Eta() > fmineta && track->Eta() < fmaxeta) {
4961           if (track->Pt() > fminPt &&  track->Pt() < fmaxPt) gRefMultiplicityTPC_Truth+=1;}
4962
4963      }//loop over primaries
4964
4965  fHistRefmult->Fill(3.,gRefMultiplicityTPC_Truth);
4966  fHistRefmult->Fill(2.,gRefMultiplicityVZERO_Truth); 
4967  fHistRefmult->Fill(0.,gRefMultiplicityVZEROA_Truth);
4968  fHistRefmult->Fill(1.,gRefMultiplicityVZEROC_Truth);
4969  if (fCentralityMethod == "MC_b"){
4970        cent_v0=gImpactParameter;
4971        fhistImpactParm->Fill(gImpactParameter);
4972        fhistImpactParmvsMult->Fill(gImpactParameter,gRefMultiplicityTPC_Truth);
4973  }
4974
4975  else if(fCentralityMethod == "TRACKS_MANUAL")   cent_v0=gRefMultiplicityTPC_Truth;
4976
4977  else if(fCentralityMethod == "V0M_MANUAL")  cent_v0=gRefMultiplicityVZERO_Truth;
4978
4979  else if(fCentralityMethod == "V0A_MANUAL")  cent_v0=gRefMultiplicityVZEROA_Truth;
4980
4981  else if(fCentralityMethod == "V0C_MANUAL")  cent_v0=gRefMultiplicityVZEROC_Truth;
4982  
4983  else      cent_v0=gImpactParameter;//default value is the impact parameter
4984     }//MC event header
4985     }//MC event cast
4986     else   cent_v0 = -1.;
4987   }//MC condition
4988
4989   else{
4990     cent_v0 = -1.;
4991   }
4992  return cent_v0;
4993 }
4994 //-----------------------------------------------------------------------------------------
4995 Double_t AliTwoParticlePIDCorr::GetAcceptedEventMultiplicity(AliVEvent *event,Bool_t truth){
4996   //do the event selection(zvtx, pileup, centrality/multiplicity cut) and then return the value of the centrality of that event
4997   if(!event) return -1;
4998
4999   Float_t gRefMultiplicity = -1.;
5000
5001    //***********************************SOURCE CODE-TASKBFPsi
5002
5003    // Event Vertex MC
5004     if(fAnalysisType == "MC") {
5005     AliMCEvent *mcevent = dynamic_cast<AliMCEvent*>(event);
5006       if(!mcevent) {
5007        AliError("mcEvent not available");
5008       return -1.;
5009       }
5010       
5011       if(mcevent){
5012         AliGenEventHeader *header = dynamic_cast<AliGenEventHeader*>(mcevent->GenEventHeader());
5013         if(header){  
5014           TArrayF gVertexArray;
5015           header->PrimaryVertex(gVertexArray);
5016  //count events having a proper vertex
5017           fEventCounter->Fill(5);         
5018
5019 fHistQA[0]->Fill((gVertexArray.At(0)));fHistQA[1]->Fill((gVertexArray.At(1)));fHistQA[2]->Fill((gVertexArray.At(2))); //for trkVtx only before vertex cut |zvtx|<10 cm
5020
5021        if(TMath::Abs(gVertexArray.At(0)) < fVxMax_MC) {
5022             if(TMath::Abs(gVertexArray.At(1)) < fVyMax_MC) {
5023               if(TMath::Abs(gVertexArray.At(2)) < fVzMax_MC) {
5024 //count events after vertex cut
5025                  fEventCounter->Fill(7);
5026  fHistQA[3]->Fill((gVertexArray.At(0)));fHistQA[4]->Fill((gVertexArray.At(1)));fHistQA[5]->Fill((gVertexArray.At(2)));//after vertex cut,for trkVtx only
5027
5028                 // get the reference multiplicty or centrality
5029  gRefMultiplicity = GetRefMultiOrCentrality((AliVEvent*)mcevent,kFALSE);//2nd argument has no meaning
5030
5031                if(gRefMultiplicity<0) return -1;
5032
5033  // take events only within the  multiplicity class mentioned in the custom binning
5034   if(gRefMultiplicity < fmincentmult || gRefMultiplicity > fmaxcentmult) return -1;
5035
5036 //count events having proper centrality/ref multiplicity
5037                     fEventCounter->Fill(9);
5038
5039               }//Vz cut
5040             }//Vy cut
5041           }//Vx cut
5042         }//header    
5043       }//MC event object
5044     }//MC
5045
5046     else  if(fAnalysisType == "MCAOD" || fAnalysisType == "AOD"){// if(fAnalysisType == "MCAOD" || fAnalysisType == "AOD"
5047   //vertex selection(is it fine for PP?)
5048   AliAODEvent* aod = dynamic_cast<AliAODEvent*>(event);
5049
5050
5051  // check first event in chunk (is not needed for new reconstructions)
5052   if(fCheckFirstEventInChunk){
5053     AliAnalysisUtils ut;
5054     if(ut.IsFirstEventInChunk(aod)) 
5055       return -1.;
5056   }
5057
5058  if(frejectPileUp){
5059     AliAnalysisUtils ut;
5060     ut.SetUseMVPlpSelection(kTRUE);
5061     ut.SetUseOutOfBunchPileUp(kTRUE);
5062     if(ut.IsPileUpEvent(aod))
5063       return -1.;
5064   }
5065
5066 //count events after pileup selection
5067    fEventCounter->Fill(3);
5068
5069  if (fVertextype==1){//for pPb basically if(!fAnalysisUtils->IsVertexSelected2013pA(aod)) return; 
5070    trkVtx = aod->GetPrimaryVertex();
5071   if (!trkVtx || trkVtx->GetNContributors()<=0) return -1;
5072   TString vtxTtl = trkVtx->GetTitle();
5073   if (!vtxTtl.Contains("VertexerTracks")) return -1;
5074    zvtx = trkVtx->GetZ();
5075   const AliAODVertex* spdVtx = aod->GetPrimaryVertexSPD();
5076   if (!spdVtx || spdVtx->GetNContributors()<=0) return -1;
5077   TString vtxTyp = spdVtx->GetTitle();
5078   Double_t cov[6]={0};
5079   spdVtx->GetCovarianceMatrix(cov);
5080   Double_t zRes = TMath::Sqrt(cov[5]);
5081   if (vtxTyp.Contains("vertexer:Z") && (zRes>0.25)) return -1;
5082    if (TMath::Abs(spdVtx->GetZ() - trkVtx->GetZ())>0.5) return -1;
5083   }
5084   else if(fVertextype==2) {//for pp and pb-pb case , taken from Jan's code
5085         Int_t nVertex = aod->GetNumberOfVertices();
5086         if( nVertex > 0 ) { 
5087      trkVtx = aod->GetPrimaryVertex();
5088                 Int_t nTracksPrim = trkVtx->GetNContributors();
5089                  zvtx = trkVtx->GetZ();
5090                 //if (fDebug > 1)AliInfo(Form(" Vertex in = %f with %d particles by  %s data ...",zVertex,nTracksPrim,vertex->GetName()));
5091                 // Reject TPC only vertex
5092                 TString name(trkVtx->GetName());
5093                 if (name.CompareTo("PrimaryVertex") && name.CompareTo("SPDVertex"))return -1;
5094
5095                 // Select a quality vertex by number of tracks?
5096                 if( nTracksPrim < fnTracksVertex ) {
5097                   //if (fDebug > 1) AliInfo(" Primary-vertex Selection: event REJECTED ...");
5098                         return -1;
5099                         }
5100                 // TODO remove vertexer Z events with dispersion > 0.02: Doesn't work for AOD at present
5101                 //if (strcmp(vertex->GetTitle(), "AliVertexerZ") == 0 && vertex->GetDispersion() > 0.02)
5102                 //  return kFALSE;
5103                 //      if (fDebug > 1) AliInfo(" Primary-vertex Selection: event ACCEPTED...");
5104         }
5105         else return -1;
5106
5107   }
5108  else if(fVertextype==0){//default case
5109   trkVtx =(AliAODVertex*) aod->GetPrimaryVertex();
5110   if (!trkVtx || trkVtx->GetNContributors()<=0) return -1;//proper number of contributors
5111   zvtx = trkVtx->GetZ();
5112   Double32_t fCov[6];
5113   trkVtx->GetCovarianceMatrix(fCov);
5114   if(fCov[5] == 0) return -1;//proper vertex resolution
5115   }
5116   else {
5117    AliInfo("Wrong Vertextype set for Primary-vertex Selection: event REJECTED ...");
5118    return -1;//as there is no proper sample type
5119   }
5120
5121 fHistQA[0]->Fill((trkVtx->GetX()));fHistQA[1]->Fill((trkVtx->GetY()));fHistQA[2]->Fill((trkVtx->GetZ())); //for trkVtx only before vertex cut |zvtx|<10 cm
5122
5123 //count events having a proper vertex
5124    fEventCounter->Fill(5);
5125
5126  if (TMath::Abs(zvtx) > fzvtxcut) return -1;
5127
5128 //count events after vertex cut
5129   fEventCounter->Fill(7);
5130
5131
5132  //if(!fAnalysisUtils->IsVertexSelected2013pA(aod)) return;
5133   
5134  fHistQA[3]->Fill((trkVtx->GetX()));fHistQA[4]->Fill((trkVtx->GetY()));fHistQA[5]->Fill((trkVtx->GetZ()));//after vertex cut,for trkVtx only
5135
5136  //get the centrality or multiplicity
5137  if(truth)  {gRefMultiplicity = GetRefMultiOrCentrality((AliVEvent*)aod,kTRUE);}//kTRUE-->for Truth case(only meaningful in case of ref multiplicity,in case of centrality it has no meaning)
5138
5139  else {gRefMultiplicity = GetRefMultiOrCentrality((AliVEvent*)aod,kFALSE);}//kFALSE-->for data and RecoMc case(only meaningful in case of ref multiplicity,in case of centrality it has no meaning)
5140
5141   if(gRefMultiplicity<0) return -1;
5142
5143  // take events only within the  multiplicity class mentioned in the custom binning
5144   if(gRefMultiplicity < fmincentmult || gRefMultiplicity > fmaxcentmult) return -1;
5145
5146 //count events having proper centrality/ref multiplicity
5147   fEventCounter->Fill(9);
5148
5149
5150 // centrality weighting (optional for 2011 if central and semicentral triggers are used);only for data and recoMC
5151  if (fCentralityWeights && !AcceptEventCentralityWeight(gRefMultiplicity))//**********************
5152   {
5153     AliInfo(Form("Rejecting event because of centrality weighting: %f", gRefMultiplicity));
5154     return -1;
5155   }
5156
5157 //count events after rejection due to centrality weighting
5158   fEventCounter->Fill(11);
5159
5160     }
5161     else gRefMultiplicity=-1;
5162
5163   return gRefMultiplicity;
5164
5165 }
5166 //--------------------------------------------------------------------------------------------------------
5167 Float_t AliTwoParticlePIDCorr::GetEventPlane(AliVEvent *mainevent,Bool_t truth, Double_t v0Centr)
5168 {
5169   Float_t eventplane=999.;
5170   // Get the event plane
5171   if(!mainevent) return 999.;
5172
5173
5174  //MC: from reaction plane
5175   if(fAnalysisType == "MC"){
5176     if(!mainevent) {
5177       AliError("mcEvent not available");
5178       return 999.;
5179     }
5180
5181     AliMCEvent *gMCEvent = dynamic_cast<AliMCEvent*>(mainevent);
5182     if(gMCEvent){
5183       AliCollisionGeometry* headerH = dynamic_cast<AliCollisionGeometry*>(gMCEvent->GenEventHeader());    
5184       if (headerH) {
5185  Int_t iC = -1;  
5186     // Impact parameter bins(it is only for Pb-Pb)
5187     if(v0Centr < 3.50) iC = 0;
5188     else if(v0Centr < 4.94) iC = 1;
5189     else if(v0Centr < 6.98) iC = 2;
5190     else if(v0Centr < 8.55) iC = 3;
5191     else if(v0Centr < 9.88) iC = 4;
5192     else if(v0Centr < 11.04) iC = 5;
5193     else if(v0Centr < 12.09) iC = 6;
5194     else if(v0Centr < 13.05) iC = 7;
5195     else iC = 8;
5196
5197         eventplane = headerH->ReactionPlaneAngle();
5198         if(eventplane > TMath::Pi()/2 && eventplane <=  TMath::Pi()*3/2) eventplane-=TMath::Pi(); 
5199          if(eventplane > TMath::Pi()*3/2) eventplane-=2*TMath::Pi();
5200          fHistEventPlaneTruth->Fill(iC,eventplane);
5201         //gReactionPlane *= TMath::RadToDeg();
5202       }//MC header
5203     }//MC event cast
5204   }//MC
5205   
5206   else  if(fAnalysisType == "MCAOD" || fAnalysisType == "AOD") {
5207  //reset Q vector info  
5208
5209   AliAODEvent* event = dynamic_cast<AliAODEvent*>(mainevent);
5210
5211
5212     Int_t run = event->GetRunNumber();
5213
5214     if(run != fRun){
5215         // Load the calibrations run dependent
5216       if(! fIsAfter2011) OpenInfoCalbration(run);
5217       fRun=run;
5218     }
5219
5220
5221   Int_t iC = -1;  
5222   if (v0Centr > 80) return 999.; // analysis only for 0-80% centrality classes
5223  // centrality bins
5224     if(v0Centr < 5) iC = 0;
5225     else if(v0Centr < 10) iC = 1;
5226     else if(v0Centr < 20) iC = 2;
5227     else if(v0Centr < 30) iC = 3;
5228     else if(v0Centr < 40) iC = 4;
5229     else if(v0Centr < 50) iC = 5;
5230     else if(v0Centr < 60) iC = 6;
5231     else if(v0Centr < 70) iC = 7;
5232     else iC = 8;
5233
5234
5235      Int_t iCcal = iC;
5236
5237  //reset Q vector info   
5238     Double_t Qxa2 = 0, Qya2 = 0;
5239     Double_t Qxc2 = 0, Qyc2 = 0;
5240     Double_t Qxa3 = 0, Qya3 = 0;
5241     Double_t Qxc3 = 0, Qyc3 = 0;
5242
5243
5244   //MC: from reaction plane
5245  if(truth)
5246 {
5247     AliAODMCHeader* header = (AliAODMCHeader*) event->GetList()->FindObject(AliAODMCHeader::StdBranchName());
5248     if (header){
5249       evplaneMC = header->GetReactionPlaneAngle();//[0, 360]
5250         //make it within [-pi/2,pi/2] to make it general
5251         if(evplaneMC > TMath::Pi()/2 && evplaneMC <=  TMath::Pi()*3/2) evplaneMC-=TMath::Pi(); 
5252          if(evplaneMC > TMath::Pi()*3/2) evplaneMC-=2*TMath::Pi();
5253          fHistEventPlaneTruth->Fill(iC,evplaneMC);
5254         /*
5255         AliGenEventHeader* eventHeader = header->GetCocktailHeader(0);  // get first MC header from either ESD/AOD (including cocktail header if available)
5256       if (eventHeader)
5257       {
5258               
5259         AliCollisionGeometry* collGeometry = dynamic_cast<AliCollisionGeometry*> (eventHeader);     
5260       
5261         if (collGeometry){//get the reaction plane from MC header   
5262           gReactionPlane = collGeometry->ReactionPlaneAngle();//[0,180]
5263  }
5264       }
5265         */   
5266      //taken from vnv0 code(get the TPC, V0A, V0C event plane using truth tracks)
5267        TClonesArray *mcArray = NULL;
5268         mcArray = (TClonesArray*)event->GetList()->FindObject(AliAODMCParticle::StdBranchName());
5269         if(mcArray){
5270           Float_t QxMCv2[3] = {0,0,0};
5271           Float_t QyMCv2[3] = {0,0,0};
5272           Float_t QxMCv3[3] = {0,0,0};
5273           Float_t QyMCv3[3] = {0,0,0};
5274           Float_t EvPlaneMCV2[3] = {0,0,0};
5275           Float_t EvPlaneMCV3[3] = {0,0,0};
5276           Float_t etaMin[3] = {2.8,-3.6,-0.8}; // A-side, C-side M-barrel
5277           Float_t etaMax[3] = {4.88,-1.8,0.8};
5278
5279           // analysis on MC tracks
5280           Int_t nMCtrack = mcArray->GetEntries() ;
5281
5282           // EP computation with MC tracks
5283           for(Int_t iT=0;iT < nMCtrack;iT++){
5284             AliAODMCParticle *mctr = (AliAODMCParticle*) mcArray->At(iT);
5285             if(!mctr || !(mctr->IsPrimary()) || !(mctr->Charge()) || mctr->Pt() < 0.2) continue;
5286             
5287             Float_t eta = mctr->Eta();
5288   for(Int_t iD=0;iD<3;iD++){
5289               if(eta > etaMin[iD] && eta < etaMax[iD]){
5290                 Float_t phi = mctr->Phi();
5291                 QxMCv2[iD] += TMath::Cos(2*phi);
5292                 QyMCv2[iD] += TMath::Sin(2*phi);
5293                 QxMCv3[iD] += TMath::Cos(3*phi);
5294                 QyMCv3[iD] += TMath::Sin(3*phi);
5295               }
5296             }
5297           }
5298
5299             EvPlaneMCV2[0] = TMath::ATan2(QyMCv2[0],QxMCv2[0])/2.;
5300             EvPlaneMCV2[1] = TMath::ATan2(QyMCv2[1],QxMCv2[1])/2.;
5301             EvPlaneMCV2[2] = TMath::ATan2(QyMCv2[2],QxMCv2[2])/2.;
5302             fHResMA2->Fill(Double_t(iC), TMath::Cos(2*(EvPlaneMCV2[2]-EvPlaneMCV2[0])));
5303             fHResMC2->Fill(Double_t(iC), TMath::Cos(2*(EvPlaneMCV2[2]-EvPlaneMCV2[1])));
5304             fHResAC2->Fill(Double_t(iC), TMath::Cos(2*(EvPlaneMCV2[0]-EvPlaneMCV2[1])));
5305             fgPsi2v0aMC = EvPlaneMCV2[0];
5306             fgPsi2v0cMC = EvPlaneMCV2[1];
5307             fgPsi2tpcMC = EvPlaneMCV2[2];
5308           
5309
5310             EvPlaneMCV3[0] = TMath::ATan2(QyMCv3[0],QxMCv3[0])/3.;
5311             EvPlaneMCV3[1] = TMath::ATan2(QyMCv3[1],QxMCv3[1])/3.;
5312             EvPlaneMCV3[2] = TMath::ATan2(QyMCv3[2],QxMCv3[2])/3.;
5313             fHResMA3->Fill(Double_t(iC), TMath::Cos(3*(EvPlaneMCV3[2]-EvPlaneMCV3[0])));
5314             fHResMC3->Fill(Double_t(iC), TMath::Cos(3*(EvPlaneMCV3[2]-EvPlaneMCV3[1])));
5315             fHResAC3->Fill(Double_t(iC), TMath::Cos(3*(EvPlaneMCV3[0]-EvPlaneMCV3[1])));
5316             fgPsi3v0aMC = EvPlaneMCV3[0];
5317             fgPsi3v0cMC = EvPlaneMCV3[1];
5318             fgPsi3tpcMC = EvPlaneMCV3[2];
5319           
5320         }    
5321     }
5322
5323     }
5324  else{
5325     Int_t nAODTracks = event->GetNumberOfTracks();
5326
5327 // TPC EP needed for resolution studies (TPC subevent)
5328    //AliEventplane * ep = (fAOD->GetHeader())->GetEventplaneP();
5329    //Double_t psiTPC = ep->GetEventplane("Q", fAOD, 2); // in range of [0, pi]
5330     Double_t Qx2 = 0, Qy2 = 0;
5331     Double_t Qx3 = 0, Qy3 = 0;
5332
5333     for(Int_t iT = 0; iT < nAODTracks; iT++) {
5334       
5335       AliAODTrack* aodTrack =(AliAODTrack*) event->GetTrack(iT);
5336       
5337       if (!aodTrack){
5338         continue;
5339       }
5340       
5341       Bool_t trkFlag = aodTrack->TestFilterBit(1);
5342
5343       if ((TMath::Abs(aodTrack->Eta()) > 0.8) || (aodTrack->Pt() < 0.2) || (aodTrack->GetTPCNcls() < fNcluster)  || !trkFlag) 
5344         continue;
5345         
5346       Double_t b[2] = {-99., -99.};
5347       Double_t bCov[3] = {-99., -99., -99.};
5348
5349
5350       AliAODTrack param(*aodTrack);
5351       if (!param.PropagateToDCA(event->GetPrimaryVertex(), event->GetMagneticField(), 100., b, bCov)){
5352         continue;
5353       }
5354             
5355       if ((TMath::Abs(b[0]) > 3.0) || (TMath::Abs(b[1]) > 2.4))
5356         continue;
5357       
5358       Qx2 += TMath::Cos(2*aodTrack->Phi()); 
5359       Qy2 += TMath::Sin(2*aodTrack->Phi());
5360       Qx3 += TMath::Cos(3*aodTrack->Phi()); 
5361       Qy3 += TMath::Sin(3*aodTrack->Phi());
5362       
5363     }
5364     
5365    Float_t evPlAng2 = TMath::ATan2(Qy2, Qx2)/2.;
5366    Float_t evPlAng3 = TMath::ATan2(Qy3, Qx3)/3.;
5367
5368     fgPsi2tpc = evPlAng2;
5369     fgPsi3tpc = evPlAng3;
5370
5371      fPhiRPTPC->Fill(iC,evPlAng2);
5372      fPhiRPTPCv3->Fill(iC,evPlAng3);
5373
5374
5375
5376 //V0 info    
5377     AliAODVZERO* aodV0 = event->GetVZEROData();
5378
5379     for (Int_t iv0 = 0; iv0 < 64; iv0++) {
5380       Double_t phiV0 = TMath::PiOver4()*(0.5 + iv0 % 8);
5381       Float_t multv0 = aodV0->GetMultiplicity(iv0);
5382
5383       if(! fIsAfter2011){
5384         if(fAnalysisType == "AOD"){//not for reco MC tracks, only for real data
5385           if (iv0 < 32){ // V0C
5386             Qxc2 += TMath::Cos(2*phiV0) * multv0*fV0Cpol/fMultV0->GetBinContent(iv0+1);
5387             Qyc2 += TMath::Sin(2*phiV0) * multv0*fV0Cpol/fMultV0->GetBinContent(iv0+1);
5388             Qxc3 += TMath::Cos(3*phiV0) * multv0*fV0Cpol/fMultV0->GetBinContent(iv0+1);
5389             Qyc3 += TMath::Sin(3*phiV0) * multv0*fV0Cpol/fMultV0->GetBinContent(iv0+1);
5390           } else {       // V0A
5391             Qxa2 += TMath::Cos(2*phiV0) * multv0*fV0Apol/fMultV0->GetBinContent(iv0+1);
5392             Qya2 += TMath::Sin(2*phiV0) * multv0*fV0Apol/fMultV0->GetBinContent(iv0+1);
5393             Qxa3 += TMath::Cos(3*phiV0) * multv0*fV0Apol/fMultV0->GetBinContent(iv0+1);
5394             Qya3 += TMath::Sin(3*phiV0) * multv0*fV0Apol/fMultV0->GetBinContent(iv0+1);
5395           }
5396         }
5397         else{
5398           if (iv0 < 32){ // V0C
5399             Qxc2 += TMath::Cos(2*phiV0) * multv0;//*fV0Cpol/fMultV0->GetBinContent(iv0+1);
5400             Qyc2 += TMath::Sin(2*phiV0) * multv0;//*fV0Cpol/fMultV0->GetBinContent(iv0+1);
5401             Qxc3 += TMath::Cos(3*phiV0) * multv0;//*fV0Cpol/fMultV0->GetBinContent(iv0+1);
5402             Qyc3 += TMath::Sin(3*phiV0) * multv0;//*fV0Cpol/fMultV0->GetBinContent(iv0+1);
5403           } else {       // V0A
5404             Qxa2 += TMath::Cos(2*phiV0) * multv0;//*fV0Apol/fMultV0->GetBinContent(iv0+1);
5405             Qya2 += TMath::Sin(2*phiV0) * multv0;//*fV0Apol/fMultV0->GetBinContent(iv0+1);
5406             Qxa3 += TMath::Cos(3*phiV0) * multv0;//*fV0Apol/fMultV0->GetBinContent(iv0+1);
5407             Qya3 += TMath::Sin(3*phiV0) * multv0;//*fV0Apol/fMultV0->GetBinContent(iv0+1);
5408           }
5409         }
5410       }
5411     }
5412    //grab for each centrality the proper histo with the Qx and Qy to do the recentering
5413     Double_t Qxamean2 = fMeanQ[iCcal][1][0];
5414     Double_t Qxarms2  = fWidthQ[iCcal][1][0];
5415     Double_t Qyamean2 = fMeanQ[iCcal][1][1];
5416     Double_t Qyarms2  = fWidthQ[iCcal][1][1];
5417     Double_t Qxamean3 = fMeanQv3[iCcal][1][0];
5418     Double_t Qxarms3  = fWidthQv3[iCcal][1][0];
5419     Double_t Qyamean3 = fMeanQv3[iCcal][1][1];
5420     Double_t Qyarms3  = fWidthQv3[iCcal][1][1];
5421     
5422     Double_t Qxcmean2 = fMeanQ[iCcal][0][0];
5423     Double_t Qxcrms2  = fWidthQ[iCcal][0][0];
5424     Double_t Qycmean2 = fMeanQ[iCcal][0][1];
5425     Double_t Qycrms2  = fWidthQ[iCcal][0][1];   
5426     Double_t Qxcmean3 = fMeanQv3[iCcal][0][0];
5427     Double_t Qxcrms3  = fWidthQv3[iCcal][0][0];
5428     Double_t Qycmean3 = fMeanQv3[iCcal][0][1];
5429     Double_t Qycrms3  = fWidthQv3[iCcal][0][1]; 
5430     
5431     Double_t QxaCor2 = (Qxa2 - Qxamean2)/Qxarms2;
5432     Double_t QyaCor2 = (Qya2 - Qyamean2)/Qyarms2;
5433     Double_t QxcCor2 = (Qxc2 - Qxcmean2)/Qxcrms2;
5434     Double_t QycCor2 = (Qyc2 - Qycmean2)/Qycrms2;
5435     Double_t QxaCor3 = (Qxa3 - Qxamean3)/Qxarms3;
5436     Double_t QyaCor3 = (Qya3 - Qyamean3)/Qyarms3;
5437     Double_t QxcCor3 = (Qxc3 - Qxcmean3)/Qxcrms3;
5438     Double_t QycCor3 = (Qyc3 - Qycmean3)/Qycrms3;
5439     /*
5440     //to calculate 2nd order event plane with v0M
5441  Double_t QxCor2 = (Qxa2 - Qxamean2 + Qxc2 - Qxcmean2)
5442     /TMath::Sqrt(Qxarms2*Qxarms2 + Qxcrms2*Qxcrms2);
5443   Double_t QyCor2 = (Qya2 - Qyamean2 + Qyc2 - Qycmean2)
5444     /TMath::Sqrt(Qyarms2*Qyarms2 + Qycrms2*Qycrms2);
5445
5446   //here the calculated event plane is within -Pi to +Pi(delete it , no use here , only for definition)
5447   Double_t psiV0A =(TMath::Pi() + TMath::ATan2(-QyaCor2, -QxaCor2))/2.;
5448   Double_t psiV0C = (TMath::Pi() + TMath::ATan2(-QycCor2, -QxcCor2))/2.;
5449   Double_t psiVZero = (TMath::Pi() + TMath::ATan2(-QyCor2, -QxCor2))/2.;
5450
5451     */
5452
5453     Float_t evPlAngV0ACor2=999.;
5454     Float_t evPlAngV0CCor2=999.;
5455     Float_t evPlAngV0ACor3=999.;
5456     Float_t evPlAngV0CCor3=999.;
5457
5458    if(! fIsAfter2011){
5459       if(fAnalysisType == "AOD"){
5460         evPlAngV0ACor2 = TMath::ATan2(QyaCor2, QxaCor2)/2.;
5461         evPlAngV0CCor2 = TMath::ATan2(QycCor2, QxcCor2)/2.;
5462         evPlAngV0ACor3 = TMath::ATan2(QyaCor3, QxaCor3)/3.;
5463         evPlAngV0CCor3 = TMath::ATan2(QycCor3, QxcCor3)/3.;
5464       }
5465       else{
5466         evPlAngV0ACor2 = TMath::ATan2(Qya2, Qxa2)/2.;
5467         evPlAngV0CCor2 = TMath::ATan2(Qyc2, Qxc2)/2.;
5468         evPlAngV0ACor3 = TMath::ATan2(Qya3, Qxa3)/3.;
5469         evPlAngV0CCor3 = TMath::ATan2(Qyc3, Qxc3)/3.;
5470       }
5471     }
5472     else{
5473       AliEventplane *ep =  event->GetEventplane();
5474       evPlAngV0ACor2 = ep->GetEventplane("V0A", event, 2);
5475       evPlAngV0CCor2 = ep->GetEventplane("V0C", event, 2);
5476       evPlAngV0ACor3 = ep->GetEventplane("V0A", event, 3);
5477       evPlAngV0CCor3 = ep->GetEventplane("V0C", event, 3);
5478     }
5479
5480     fgPsi2v0a = evPlAngV0ACor2;
5481     fgPsi2v0c = evPlAngV0CCor2;
5482     fgPsi3v0a = evPlAngV0ACor3;
5483     fgPsi3v0c = evPlAngV0CCor3;
5484
5485  // Fill EP distribution histograms evPlAng
5486     
5487      fPhiRPv0A->Fill(iC,evPlAngV0ACor2);
5488      fPhiRPv0C->Fill(iC,evPlAngV0CCor2);
5489     
5490      fPhiRPv0Av3->Fill(iC,evPlAngV0ACor3);
5491      fPhiRPv0Cv3->Fill(iC,evPlAngV0CCor3);
5492
5493     // Fill histograms needed for resolution evaluation
5494     fHResTPCv0A2->Fill(Double_t(iC), TMath::Cos(2*(evPlAng2 - evPlAngV0ACor2)));
5495     fHResTPCv0C2->Fill(Double_t(iC), TMath::Cos(2*(evPlAng2 - evPlAngV0CCor2)));
5496     fHResv0Cv0A2->Fill(Double_t(iC), TMath::Cos(2*(evPlAngV0ACor2 - evPlAngV0CCor2)));
5497     
5498     fHResTPCv0A3->Fill(Double_t(iC), TMath::Cos(3*(evPlAng3 - evPlAngV0ACor3)));
5499     fHResTPCv0C3->Fill(Double_t(iC), TMath::Cos(3*(evPlAng3 - evPlAngV0CCor3)));
5500     fHResv0Cv0A3->Fill(Double_t(iC), TMath::Cos(3*(evPlAngV0ACor3 - evPlAngV0CCor3)));
5501
5502
5503     /*   
5504  Float_t gVZEROEventPlane    = -10.;
5505   Float_t gReactionPlane      = -10.;
5506   Double_t qxTot = 0.0, qyTot = 0.0;
5507
5508     AliEventplane *ep = event->GetEventplane();
5509     if(ep){ 
5510       gVZEROEventPlane = ep->CalculateVZEROEventPlane(event,10,2,qxTot,qyTot);
5511       if(gVZEROEventPlane < 0.) gVZEROEventPlane += TMath::Pi();
5512       //gReactionPlane = gVZEROEventPlane*TMath::RadToDeg();
5513       gReactionPlane = gVZEROEventPlane;
5514     }
5515     */
5516   }//AOD,ESD,ESDMC
5517  //return gReactionPlane;
5518
5519  //make the final 2nd order event plane within 0 to Pi
5520      //using data and reco tracks only
5521       if(fgPsi2v0a!=999. && fgPsi2v0a < 0.) fgPsi2v0a += TMath::Pi();
5522       if(fgPsi2v0c!=999. && fgPsi2v0c < 0.) fgPsi2v0c += TMath::Pi();
5523       if(fgPsi2tpc!=999. && fgPsi2tpc < 0.) fgPsi2tpc += TMath::Pi();
5524       //using truth tracks only
5525       if(evplaneMC!=999. && evplaneMC < 0.) evplaneMC += TMath::Pi();
5526       if(fgPsi2v0aMC!=999. && fgPsi2v0aMC < 0.) fgPsi2v0aMC += TMath::Pi();
5527       if(fgPsi2v0cMC!=999. && fgPsi2v0cMC < 0.) fgPsi2v0cMC += TMath::Pi();
5528       if(fgPsi2tpcMC!=999. && fgPsi2tpcMC < 0.) fgPsi2tpcMC += TMath::Pi();
5529       //for the time being leave the 3rd order event planes within -pi/3 t0 +pi/3
5530
5531       if(truth){//for truth MC
5532         if(fV2 && fEPdet=="header")eventplane=evplaneMC;
5533         if(fV2 && fEPdet=="V0A")eventplane=fgPsi2v0aMC;
5534         if(fV2 && fEPdet=="V0C")eventplane=fgPsi2v0cMC;
5535         if(fV2 && fEPdet=="TPC")eventplane=fgPsi2tpcMC;
5536
5537         if(fV3 && fEPdet=="V0A")eventplane=fgPsi3v0aMC;
5538         if(fV3 && fEPdet=="V0C")eventplane=fgPsi3v0cMC;
5539         if(fV3 && fEPdet=="TPC")eventplane=fgPsi3tpcMC;
5540 }
5541       else{//for data and recoMC
5542         if(fV2 && fEPdet=="V0A")eventplane=fgPsi2v0a;
5543         if(fV2 && fEPdet=="V0C")eventplane=fgPsi2v0c;
5544         if(fV2 && fEPdet=="TPC")eventplane=fgPsi2tpc;
5545
5546         if(fV3 && fEPdet=="V0A")eventplane=fgPsi3v0a;
5547         if(fV3 && fEPdet=="V0C")eventplane=fgPsi3v0c;
5548         if(fV3 && fEPdet=="TPC")eventplane=fgPsi3tpc;
5549
5550       }
5551      
5552
5553   }//AOD/MCAOD condition
5554
5555   else eventplane=999.;
5556  
5557   return eventplane;
5558
5559 }
5560 //------------------------------------------------------------------------------------------------------------------
5561 void AliTwoParticlePIDCorr::OpenInfoCalbration(Int_t run){
5562     TString oadbfilename = "$ALICE_ROOT/OADB/PWGCF/VZERO/VZEROcalibEP.root";
5563     TFile *foadb = TFile::Open(oadbfilename.Data());
5564
5565     if(!foadb){
5566         printf("OADB file %s cannot be opened\n",oadbfilename.Data());
5567         return;
5568     }
5569
5570     AliOADBContainer *cont = (AliOADBContainer*) foadb->Get("hMultV0BefCorr");
5571     if(!cont){
5572         printf("OADB object hMultV0BefCorr is not available in the file\n");
5573         return; 
5574     }
5575
5576     if(!(cont->GetObject(run))){
5577         printf("OADB object hMultV0BefCorr is not available for run %i (used run 137366)\n",run);
5578         run = 137366;
5579     }
5580     fMultV0 = ((TH2F *) cont->GetObject(run))->ProfileX();
5581
5582     TF1 *fpol0 = new TF1("fpol0","pol0"); 
5583     fMultV0->Fit(fpol0,"","",0,31);
5584     fV0Cpol = fpol0->GetParameter(0);
5585     fMultV0->Fit(fpol0,"","",32,64);
5586     fV0Apol = fpol0->GetParameter(0);
5587
5588     for(Int_t iside=0;iside<2;iside++){
5589         for(Int_t icoord=0;icoord<2;icoord++){
5590             for(Int_t i=0;i  < 9;i++){
5591                 char namecont[100];
5592                 if(iside==0 && icoord==0)
5593                   snprintf(namecont,100,"hQxc2_%i",i);
5594                 else if(iside==1 && icoord==0)
5595                   snprintf(namecont,100,"hQxa2_%i",i);
5596                 else if(iside==0 && icoord==1)
5597                   snprintf(namecont,100,"hQyc2_%i",i);
5598                 else if(iside==1 && icoord==1)
5599                   snprintf(namecont,100,"hQya2_%i",i);
5600
5601                 cont = (AliOADBContainer*) foadb->Get(namecont);
5602                 if(!cont){
5603                     printf("OADB object %s is not available in the file\n",namecont);
5604                     return;     
5605                 }
5606                 
5607                 if(!(cont->GetObject(run))){
5608                     printf("OADB object %s is not available for run %i (used run 137366)\n",namecont,run);
5609                     run = 137366;
5610                 }
5611                 fMeanQ[i][iside][icoord] = ((TH1F *) cont->GetObject(run))->GetMean();
5612                 fWidthQ[i][iside][icoord] = ((TH1F *) cont->GetObject(run))->GetRMS();
5613
5614                 //for v3
5615                 if(iside==0 && icoord==0)
5616                   snprintf(namecont,100,"hQxc3_%i",i);
5617                 else if(iside==1 && icoord==0)
5618                   snprintf(namecont,100,"hQxa3_%i",i);
5619                 else if(iside==0 && icoord==1)
5620                   snprintf(namecont,100,"hQyc3_%i",i);
5621                 else if(iside==1 && icoord==1)
5622                   snprintf(namecont,100,"hQya3_%i",i);
5623
5624                 cont = (AliOADBContainer*) foadb->Get(namecont);
5625                 if(!cont){
5626                     printf("OADB object %s is not available in the file\n",namecont);
5627                     return;     
5628                 }
5629                 
5630                 if(!(cont->GetObject(run))){
5631                     printf("OADB object %s is not available for run %i (used run 137366)\n",namecont,run);
5632                     run = 137366;
5633                 }
5634                 fMeanQv3[i][iside][icoord] = ((TH1F *) cont->GetObject(run))->GetMean();
5635                 fWidthQv3[i][iside][icoord] = ((TH1F *) cont->GetObject(run))->GetRMS();
5636
5637             }
5638         }
5639     }
5640 }
5641 //____________________________________________________________________
5642 void AliTwoParticlePIDCorr::FillPIDEventPlane(Double_t centrality,Int_t par,Float_t trigphi,Float_t fReactionPlane) 
5643 {
5644
5645  // Event plane (determine psi bin)
5646     Double_t gPsiMinusPhi    =   0.;
5647     Double_t gPsiMinusPhiBin = -10.;
5648 if(fRequestEventPlane){
5649     gPsiMinusPhi   = TMath::Abs(trigphi - fReactionPlane);
5650     //in-plane
5651     if((gPsiMinusPhi <= 7.5*TMath::DegToRad())||
5652       (gPsiMinusPhi >= 352.5*TMath::DegToRad())||
5653        ((172.5*TMath::DegToRad() <= gPsiMinusPhi)&&(gPsiMinusPhi <= 187.5*TMath::DegToRad())))
5654       gPsiMinusPhiBin = 0.0;
5655     //intermediate
5656     else if(((37.5*TMath::DegToRad() <= gPsiMinusPhi)&&(gPsiMinusPhi <= 52.5*TMath::DegToRad()))||
5657             ((127.5*TMath::DegToRad() <= gPsiMinusPhi)&&(gPsiMinusPhi <= 142.5*TMath::DegToRad()))||
5658             ((217.5*TMath::DegToRad() <= gPsiMinusPhi)&&(gPsiMinusPhi <= 232.5*TMath::DegToRad()))||
5659             ((307.5*TMath::DegToRad() <= gPsiMinusPhi)&&(gPsiMinusPhi <= 322.5*TMath::DegToRad())))
5660       gPsiMinusPhiBin = 1.0;
5661     //out of plane
5662     else if(((82.5*TMath::DegToRad() <= gPsiMinusPhi)&&(gPsiMinusPhi <= 97.5*TMath::DegToRad()))||
5663             ((262.5*TMath::DegToRad() <= gPsiMinusPhi)&&(gPsiMinusPhi <= 277.5*TMath::DegToRad())))
5664       gPsiMinusPhiBin = 2.0;
5665     //everything else
5666     else 
5667       gPsiMinusPhiBin = 3.0;
5668
5669     fEventPlanePID->Fill(centrality,gPsiMinusPhiBin,(Float_t)par); 
5670  }
5671 }
5672
5673 //____________________________________________________________________________________________________
5674
5675 TObjArray* AliTwoParticlePIDCorr::GetV0Particles(AliVEvent* event,Double_t Centrality)
5676 {
5677
5678   AliAODEvent* fAOD = dynamic_cast<AliAODEvent*>(event);
5679
5680  //function to select v0's from AODs
5681   trkVtx=fAOD->GetPrimaryVertex();
5682   Float_t xv=trkVtx->GetX(), yv=trkVtx->GetY(), zv=trkVtx->GetZ();
5683   Int_t nV0sTot = fAOD->GetNumberOfV0s();
5684
5685         TObjArray * selectedV0s = new TObjArray;
5686         selectedV0s->SetOwner(kTRUE);
5687
5688  for (Int_t iV0 = 0; iV0 < nV0sTot; iV0++) 
5689     {
5690     
5691     AliAODv0 *v0=fAOD->GetV0(iV0);
5692     if (!v0) continue;
5693     if(!CheckStatusv0(v0)) continue;
5694
5695     AliAODTrack *ptrack=(AliAODTrack*)v0->GetDaughter(0);
5696     AliAODTrack *ntrack=(AliAODTrack*)v0->GetDaughter(1);
5697
5698     Bool_t cutK0sPID=kFALSE;
5699     Bool_t cutLambdaPID=kFALSE;
5700     Bool_t cutAntiLambdaPID=kFALSE;
5701
5702     if(fUsev0DaughterPID)
5703 {
5704         //use fHelperPID check PID of the daughter tracks
5705         //v0 daughter PID may be helpful in distangling k0S and (Anti)Lamda
5706                                                                                           
5707         Int_t PIDptrack = GetParticle(ptrack,kFALSE);
5708         Int_t PIDntrack = GetParticle(ntrack ,kFALSE);
5709
5710         if(PIDptrack ==0 &&  PIDntrack == 0) cutK0sPID=kTRUE;
5711
5712         if(PIDptrack==2 && PIDntrack ==0) cutLambdaPID=kTRUE;
5713
5714         if (PIDptrack ==0 && PIDntrack == 2) cutAntiLambdaPID=kTRUE;
5715
5716       }
5717
5718  // effective mass calculations for each hypothesis(without daughter PID)
5719     Double_t InvMassK0s = v0->MassK0Short();
5720     Double_t InvMassAntiLambda = v0->MassAntiLambda();
5721     Double_t InvMassLambda = v0->MassLambda();
5722
5723     Float_t v0Pt=TMath::Sqrt(v0->Pt2V0());
5724     Float_t v0Eta=v0->Eta();
5725     Float_t v0Phi=v0->Phi();
5726
5727     //This is simply raw v0 without any specialised cut
5728     fHistRawPtCentInvK0s->Fill(InvMassK0s,v0Pt,Centrality);
5729     fHistRawPtCentInvLambda->Fill(InvMassLambda,v0Pt,Centrality);
5730     fHistRawPtCentInvAntiLambda->Fill(InvMassAntiLambda,v0Pt,Centrality);
5731
5732   // Decay vertex
5733     Double_t xyz[3];   
5734     v0->GetSecondaryVtx(xyz);
5735     Float_t dx,dy,dz;
5736      dx=xyz[0]-xv, dy=xyz[1]-yv, dz=xyz[2]-zv;
5737
5738      //  Float_t v0DecayRadius=TMath::Sqrt(dx*dx + dy*dy);
5739     Float_t v0DecayLength=TMath::Sqrt(dx*dx + dy*dy + dz*dz);
5740     // VO's main characteristics to check the reconstruction cuts
5741     // Float_t DcaV0Daughters    = v0->DcaV0Daughters();
5742     Float_t V0cosPointAngle   = v0->CosPointingAngle(trkVtx);
5743     // Float_t DcaPosToPrimVertex = v0->DcaPosToPrimVertex();
5744     //Float_t DcaNegToPrimVertex = v0->DcaNegToPrimVertex();   
5745     //Float_t Dcav0PVz   = v0->DcaV0ToPrimVertex(); 
5746     Float_t v0Pz=v0->Pz();
5747     Float_t v0P= TMath::Sqrt(v0Pt*v0Pt + v0Pz*v0Pz);
5748
5749     Float_t ctauLambda =999.;
5750     Float_t ctauAntiLambda = 999.;
5751     Float_t ctauK0s = 999.;
5752  if(v0P > 0.0)
5753       {
5754          ctauLambda = (v0DecayLength*InvMassLambda)/v0P;
5755          ctauAntiLambda = (v0DecayLength*InvMassAntiLambda)/v0P;
5756          ctauK0s = (v0DecayLength*InvMassK0s)/v0P;
5757       }
5758     
5759     Bool_t ctauCutK0s= ctauK0s < NCtau*fCutctauK0s ; //ctauK0s 2.68 cm, mean life time of K0s is 8.95 x10^(-11)
5760     Bool_t ctauCutLambda = ctauLambda    < NCtau*fCutctauLambda; //ctauLambda 7.8 cm ,mean life is 2.6 x10 ^(-10) ***** 3xctau is the accepted limit
5761     Bool_t ctauCutAntiLambda= ctauAntiLambda < NCtau*fCutctauAntiLambda;
5762
5763     Bool_t RapCutK0s = v0->RapK0Short() < fRapCutK0s;
5764     Bool_t RapCutLambda = v0->RapLambda() < fRapCutLambda; 
5765     Bool_t RapCutAntiLambda = v0->Y(-3122) < fRapCutLambda;
5766
5767     Bool_t CPACut= V0cosPointAngle > fMinCPA; //cosine of pointing angle with v0 should be greater than 0.998
5768
5769     //Now we put a loose mass cut which will be tightened later 
5770     Bool_t MassCutLooseK0s=(TMath::Abs(InvMassK0s - 0.497614) < 0.1);
5771     Bool_t MassCutLooseLambda=(TMath::Abs(InvMassLambda - 1.115683) < 0.1); // cut is same for Anti-Lambda
5772     Bool_t MassCutLooseAntiLambda=(TMath::Abs(InvMassAntiLambda - 1.115683) < 0.1); // cut is same for Anti-Lambda
5773
5774  //Special Cut for Kshort arementeros podalanski plot
5775     Bool_t ArmenterosCut =kFALSE;
5776     if(ctauCutK0s && RapCutK0s && CPACut && MassCutLooseK0s)
5777       {
5778
5779     Float_t lAlphaV0      =  v0->AlphaV0();
5780     Float_t lPtArmV0      =  v0->PtArmV0();
5781
5782      ArmenterosCut = lPtArmV0 > TMath::Abs(0.2*lAlphaV0);
5783
5784       }
5785
5786     Bool_t IskShortOk=(ctauCutK0s && RapCutK0s && CPACut && MassCutLooseK0s && ArmenterosCut);
5787
5788     Bool_t IsLambdaOk=(ctauCutLambda && RapCutLambda && CPACut && MassCutLooseLambda);
5789
5790     Bool_t IsAntiLambdaOk=(ctauCutAntiLambda && RapCutAntiLambda && CPACut && MassCutLooseAntiLambda);
5791
5792 //Difference on Lambda and Anti-Lambda can be made through daughter PID
5793
5794
5795     Int_t particletype=999;
5796
5797         if( IskShortOk || cutK0sPID )
5798         {
5799          fHistFinalPtCentInvK0s->Fill(InvMassK0s,v0Pt,Centrality);
5800          particletype=SpKs0;
5801
5802     Short_t chargeval=0;
5803     Float_t effmatrix=1.0;
5804     LRCParticlePID* copy1 = new LRCParticlePID(particletype,InvMassK0s,chargeval,v0Pt,v0Eta, v0Phi,effmatrix,ptrack->GetTPCSharedMapPtr(),ntrack->GetTPCSharedMapPtr());
5805     copy1->SetUniqueID(eventno * 200000 + (Int_t)iV0);
5806     selectedV0s->Add(copy1);
5807   
5808         }
5809
5810
5811         if(IsLambdaOk ||  cutLambdaPID)
5812         {
5813          fHistFinalPtCentInvLambda->Fill(InvMassLambda,v0Pt,Centrality);
5814 //Add in the LRCParticle and give Lambda a tag 5
5815          particletype=SpLam;
5816  
5817     Short_t chargeval=0;
5818     Float_t effmatrix=1.0;
5819     LRCParticlePID* copy1 = new LRCParticlePID(particletype,InvMassLambda,chargeval,v0Pt,v0Eta, v0Phi,effmatrix,ptrack->GetTPCSharedMapPtr(),ntrack->GetTPCSharedMapPtr());
5820     copy1->SetUniqueID(eventno * 200000 + (Int_t)iV0);
5821     selectedV0s->Add(copy1);
5822         }
5823
5824         if(IsAntiLambdaOk ||  cutAntiLambdaPID)
5825         {
5826          fHistFinalPtCentInvLambda->Fill(InvMassAntiLambda,v0Pt,Centrality);
5827 //Add in the LRCParticle and give Lambda a tag 6
5828          particletype=SpALam;
5829     Short_t chargeval=0;
5830     Float_t effmatrix=1.0;
5831     LRCParticlePID* copy1 = new LRCParticlePID(particletype,InvMassAntiLambda,chargeval,v0Pt,v0Eta, v0Phi,effmatrix,ptrack->GetTPCSharedMapPtr(),ntrack->GetTPCSharedMapPtr());
5832     copy1->SetUniqueID(eventno * 200000 + (Int_t)iV0);
5833     selectedV0s->Add(copy1);
5834         }
5835
5836
5837     }//v0 loop
5838
5839   return selectedV0s;    
5840 }
5841
5842 //___________________________________________________________________
5843   Bool_t AliTwoParticlePIDCorr :: CheckStatusv0Daughter(AliAODTrack *t1 ,AliAODTrack *t2)
5844   {
5845   if (!t1->IsOn(AliAODTrack::kTPCrefit) || !t2->IsOn(AliAODTrack::kTPCrefit)) return kFALSE;
5846   // Float_t nCrossedRowsTPC = t->GetTPCClusterInfo(2,1); 
5847 if(t1->GetTPCClusterInfo(2,1)<fDaugNClsTPC || t2->GetTPCClusterInfo(2,1)<fDaugNClsTPC) return kFALSE ;
5848
5849 // ---------------- Fraction of TPC Shared Cluster 
5850      Float_t fracPosDaugTPCSharedMap = GetFractionTPCSharedCls(t1);
5851      Float_t fracNegDaugTPCSharedMap = GetFractionTPCSharedCls(t2);
5852
5853  if(  (fracPosDaugTPCSharedMap > fFracTPCcls) || (fracNegDaugTPCSharedMap > fFracTPCcls) )
5854         return kFALSE;
5855   
5856   return kTRUE; 
5857
5858   }
5859 //___________________________________________________________________________________________
5860    
5861  Float_t AliTwoParticlePIDCorr :: GetFractionTPCSharedCls( AliAODTrack *track)
5862 {
5863   // Rejects tracks with shared clusters after filling a control histogram
5864   // This overload is used for primaries
5865  
5866   // Get the shared maps
5867   const TBits sharedMap = track->GetTPCSharedMap();
5868
5869   return 1.*sharedMap.CountBits()/track->GetTPCNclsF();
5870   
5871 }
5872 //______________________________________________________________________
5873   Bool_t AliTwoParticlePIDCorr :: CheckStatusv0(AliAODv0 *v1)
5874   {
5875
5876     // Offline reconstructed V0 only
5877     if (v1->GetOnFlyStatus()) return kFALSE;
5878
5879      AliAODTrack *ptrack=(AliAODTrack *)v1->GetDaughter(0);
5880      AliAODTrack *ntrack=(AliAODTrack *)v1->GetDaughter(1);
5881
5882     if(!ptrack || !ntrack) return kFALSE;
5883
5884     if(ptrack->Charge()==-1 || ntrack->Charge()==1) return kFALSE; //remove wrongly identified charge pairs 
5885
5886     if(ptrack->Charge()==0 || ntrack->Charge()==0) return kFALSE; //remove uncharged pairs
5887
5888     if(ptrack->Charge() == ntrack->Charge()) return kFALSE; //remove like sign pairs 
5889
5890     if(!CheckStatusv0Daughter(ptrack,ntrack)) return kFALSE;//daughters need to pass some basic cuts    
5891
5892     if(TMath::Abs(ptrack->Eta()) > fmaxeta || TMath::Abs(ntrack->Eta()) > fmaxeta) return kFALSE; // remove daughters beyond eta bound |0.8|
5893
5894     if(ptrack->Pt() < fMinPtDaughter || ntrack->Pt() < fMinPtDaughter) return kFALSE; // remove daughter tracks below minmum p |1.0 GeV/c|
5895
5896     if(ptrack->Pt() > fMaxPtDaughter || ntrack->Pt() > fMaxPtDaughter) return kFALSE; // remove daughter tracks above maximum p ** to make it compatiable with AliHelperPID**|4.0 GeV/C|
5897
5898     // Daughters: Impact parameter of daughter to prim vtx
5899     Float_t xy = v1->DcaPosToPrimVertex();
5900     if (TMath::Abs(xy)<fDCAToPrimVtx) return kFALSE; //0.1 cm
5901     xy = v1->DcaNegToPrimVertex();
5902     if (TMath::Abs(xy)<fDCAToPrimVtx) return kFALSE; //0.1 cm
5903
5904     // Daughters: DCA
5905     Float_t dca = v1->DcaV0Daughters();
5906     if (dca>fMaxDCADaughter) return kFALSE; //1.0 cm
5907     
5908     // V0: Cosine of the pointing angle
5909     Float_t cpa=v1->CosPointingAngle(trkVtx); //0.997
5910     if (cpa<fMinCPA) return kFALSE;
5911
5912     // V0: Fiducial volume
5913     Double_t xyz[3]; v1->GetSecondaryVtx(xyz);
5914     Float_t r2=xyz[0]*xyz[0] + xyz[1]*xyz[1];
5915     if (r2<5.*5.) return kFALSE;
5916     if (r2>lMax*lMax) return kFALSE; //lmax=100 cm
5917
5918     return kTRUE;
5919
5920
5921   }
5922 //__________________________________________________________________________________________
5923 Bool_t AliTwoParticlePIDCorr::IsTrackFromV0(AliAODEvent* fAOD,AliAODTrack* track)
5924 {
5925 //to check whether a daughter being taken as associated
5926         Int_t assoID = track->GetID();
5927
5928         for(int i=0; i<fAOD->GetNumberOfV0s(); i++){ // loop over V0s
5929                 AliAODv0* aodV0 = fAOD->GetV0(i);
5930                 
5931                 AliAODTrack *trackPos=(AliAODTrack *)(aodV0->GetDaughter(0));
5932                 AliAODTrack *trackNeg=(AliAODTrack *)(aodV0->GetDaughter(1));
5933                         
5934                 
5935                 Int_t negID = trackNeg->GetID();
5936                 Int_t posID = trackPos->GetID();
5937                 
5938                 if ((TMath::Abs(negID)+1)==(TMath::Abs(assoID))){ return kTRUE;}
5939                 if ((TMath::Abs(posID)+1)==(TMath::Abs(assoID))){ return kTRUE;}
5940                 //----------------------------------
5941         }
5942         return kFALSE;
5943 }
5944
5945
5946
5947 //----------------------------------------------------------
5948 void AliTwoParticlePIDCorr::Terminate(Option_t *) 
5949 {
5950   // Draw result to screen, or perform fitting, normalizations
5951   // Called once at the end of the query
5952   fOutput = dynamic_cast<TList*> (GetOutputData(1));
5953   if(!fOutput) { Printf("ERROR: could not retrieve TList fOutput"); return; }
5954   
5955   
5956 }
5957 //------------------------------------------------------------------