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