]> git.uio.no Git - u/mrichter/AliRoot.git/blob - STEER/STEERBase/AliPIDResponse.cxx
Merge branch 'master' of https://git.cern.ch/reps/AliRoot
[u/mrichter/AliRoot.git] / STEER / STEERBase / AliPIDResponse.cxx
1 /**************************************************************************
2  * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
3  *                                                                        *
4  * Author: The ALICE Off-line Project.                                    *
5  * Contributors are mentioned in the code where appropriate.              *
6  *                                                                        *
7  * Permission to use, copy, modify and distribute this software and its   *
8  * documentation strictly for non-commercial purposes is hereby granted   *
9  * without fee, provided that the above copyright notice appears in all   *
10  * copies and that both the copyright notice and this permission notice   *
11  * appear in the supporting documentation. The authors make no claims     *
12  * about the suitability of this software for any purpose. It is          *
13  * provided "as is" without express or implied warranty.                  *
14  **************************************************************************/
15
16 /* $Id: AliPIDResponse.cxx 46193 2010-12-21 09:00:14Z wiechula $ */
17
18 //-----------------------------------------------------------------
19 //        Base class for handling the pid response               //
20 //        functions of all detectors                             //
21 //        and give access to the nsigmas                         //
22 //                                                               //
23 //   Origin: Jens Wiechula, Uni Tuebingen, jens.wiechula@cern.ch //
24 //-----------------------------------------------------------------
25
26 #include <TList.h>
27 #include <TObjArray.h>
28 #include <TPRegexp.h>
29 #include <TF1.h>
30 #include <TH2D.h>
31 #include <TSpline.h>
32 #include <TFile.h>
33 #include <TArrayI.h>
34 #include <TArrayF.h>
35 #include <TLinearFitter.h>
36 #include <TSystem.h>
37 #include <TMD5.h>
38
39 #include <AliVEvent.h>
40 #include <AliVTrack.h>
41 #include <AliLog.h>
42 #include <AliPID.h>
43 #include <AliOADBContainer.h>
44 #include <AliTRDPIDResponseObject.h>
45 #include <AliTOFPIDParams.h>
46 #include <AliHMPIDPIDParams.h>
47
48 #include "AliPIDResponse.h"
49 #include "AliDetectorPID.h"
50
51 #include "AliCentrality.h"
52
53 ClassImp(AliPIDResponse);
54
55 AliPIDResponse::AliPIDResponse(Bool_t isMC/*=kFALSE*/) :
56 TNamed("PIDResponse","PIDResponse"),
57 fITSResponse(isMC),
58 fTPCResponse(),
59 fTRDResponse(),
60 fTOFResponse(),
61 fHMPIDResponse(),
62 fEMCALResponse(),
63 fRange(5.),
64 fITSPIDmethod(kITSTruncMean),
65 fTuneMConData(kFALSE),
66 fTuneMConDataMask(kDetTOF|kDetTPC),
67 fIsMC(isMC),
68 fCachePID(kTRUE),
69 fOADBPath(),
70 fCustomTPCpidResponse(),
71 fBeamType("PP"),
72 fLHCperiod(),
73 fMCperiodTPC(),
74 fMCperiodUser(),
75 fCurrentFile(),
76 fCurrentAliRootRev(-1),
77 fRecoPass(0),
78 fRecoPassUser(-1),
79 fRun(-1),
80 fOldRun(-1),
81 fResT0A(75.),
82 fResT0C(65.),
83 fResT0AC(55.),
84 fArrPidResponseMaster(NULL),
85 fResolutionCorrection(NULL),
86 fOADBvoltageMaps(NULL),
87 fUseTPCEtaCorrection(kFALSE),
88 fUseTPCMultiplicityCorrection(kFALSE),
89 fTRDPIDResponseObject(NULL),
90 fTOFtail(0.9),
91 fTOFPIDParams(NULL),
92 fHMPIDPIDParams(NULL),
93 fEMCALPIDParams(NULL),
94 fCurrentEvent(NULL),
95 fCurrCentrality(0.0)
96 {
97   //
98   // default ctor
99   //
100   AliLog::SetClassDebugLevel("AliPIDResponse",0);
101   AliLog::SetClassDebugLevel("AliESDpid",0);
102   AliLog::SetClassDebugLevel("AliAODpidUtil",0);
103
104 }
105
106 //______________________________________________________________________________
107 AliPIDResponse::~AliPIDResponse()
108 {
109   //
110   // dtor
111   //
112   delete fArrPidResponseMaster;
113   delete fTRDPIDResponseObject;
114   delete fTOFPIDParams;
115 }
116
117 //______________________________________________________________________________
118 AliPIDResponse::AliPIDResponse(const AliPIDResponse &other) :
119 TNamed(other),
120 fITSResponse(other.fITSResponse),
121 fTPCResponse(other.fTPCResponse),
122 fTRDResponse(other.fTRDResponse),
123 fTOFResponse(other.fTOFResponse),
124 fHMPIDResponse(other.fHMPIDResponse),
125 fEMCALResponse(other.fEMCALResponse),
126 fRange(other.fRange),
127 fITSPIDmethod(other.fITSPIDmethod),
128 fTuneMConData(other.fTuneMConData),
129 fTuneMConDataMask(other.fTuneMConDataMask),
130 fIsMC(other.fIsMC),
131 fCachePID(other.fCachePID),
132 fOADBPath(other.fOADBPath),
133 fCustomTPCpidResponse(other.fCustomTPCpidResponse),
134 fBeamType("PP"),
135 fLHCperiod(),
136 fMCperiodTPC(),
137 fMCperiodUser(other.fMCperiodUser),
138 fCurrentFile(),
139 fCurrentAliRootRev(other.fCurrentAliRootRev),
140 fRecoPass(0),
141 fRecoPassUser(other.fRecoPassUser),
142 fRun(-1),
143 fOldRun(-1),
144 fResT0A(75.),
145 fResT0C(65.),
146 fResT0AC(55.),
147 fArrPidResponseMaster(NULL),
148 fResolutionCorrection(NULL),
149 fOADBvoltageMaps(NULL),
150 fUseTPCEtaCorrection(other.fUseTPCEtaCorrection),
151 fUseTPCMultiplicityCorrection(other.fUseTPCMultiplicityCorrection),
152 fTRDPIDResponseObject(NULL),
153 fTOFtail(0.9),
154 fTOFPIDParams(NULL),
155 fHMPIDPIDParams(NULL),
156 fEMCALPIDParams(NULL),
157 fCurrentEvent(NULL),
158 fCurrCentrality(0.0)
159 {
160   //
161   // copy ctor
162   //
163 }
164
165 //______________________________________________________________________________
166 AliPIDResponse& AliPIDResponse::operator=(const AliPIDResponse &other)
167 {
168   //
169   // copy ctor
170   //
171   if(this!=&other) {
172     delete fArrPidResponseMaster;
173     TNamed::operator=(other);
174     fITSResponse=other.fITSResponse;
175     fTPCResponse=other.fTPCResponse;
176     fTRDResponse=other.fTRDResponse;
177     fTOFResponse=other.fTOFResponse;
178     fHMPIDResponse=other.fHMPIDResponse;
179     fEMCALResponse=other.fEMCALResponse;
180     fRange=other.fRange;
181     fITSPIDmethod=other.fITSPIDmethod;
182     fOADBPath=other.fOADBPath;
183     fCustomTPCpidResponse=other.fCustomTPCpidResponse;
184     fTuneMConData=other.fTuneMConData;
185     fTuneMConDataMask=other.fTuneMConDataMask;
186     fIsMC=other.fIsMC;
187     fCachePID=other.fCachePID;
188     fBeamType="PP";
189     fLHCperiod="";
190     fMCperiodTPC="";
191     fMCperiodUser=other.fMCperiodUser;
192     fCurrentFile="";
193     fCurrentAliRootRev=other.fCurrentAliRootRev;
194     fRecoPass=0;
195     fRecoPassUser=other.fRecoPassUser;
196     fRun=-1;
197     fOldRun=-1;
198     fResT0A=75.;
199     fResT0C=65.;
200     fResT0AC=55.;
201     fArrPidResponseMaster=NULL;
202     fResolutionCorrection=NULL;
203     fOADBvoltageMaps=NULL;
204     fUseTPCEtaCorrection=other.fUseTPCEtaCorrection;
205     fUseTPCMultiplicityCorrection=other.fUseTPCMultiplicityCorrection;
206     fTRDPIDResponseObject=NULL;
207     fEMCALPIDParams=NULL;
208     fTOFtail=0.9;
209     fTOFPIDParams=NULL;
210     fHMPIDPIDParams=NULL;
211     fCurrentEvent=other.fCurrentEvent;
212
213   }
214   return *this;
215 }
216
217 //______________________________________________________________________________
218 Float_t AliPIDResponse::NumberOfSigmas(EDetector detector, const AliVParticle *vtrack, AliPID::EParticleType type) const
219 {
220   //
221   // NumberOfSigmas for 'detCode'
222   //
223   
224   const AliVTrack *track=static_cast<const AliVTrack*>(vtrack);
225   // look for cached value first
226   const AliDetectorPID *detPID=track->GetDetectorPID();
227   
228   if ( detPID && detPID->HasNumberOfSigmas(detector)){
229     return detPID->GetNumberOfSigmas(detector, type);
230   } else if (fCachePID) {
231     FillTrackDetectorPID(track, detector);
232     detPID=track->GetDetectorPID();
233     return detPID->GetNumberOfSigmas(detector, type);
234   }
235   
236   return GetNumberOfSigmas(detector, track, type);
237 }
238
239 //______________________________________________________________________________
240 AliPIDResponse::EDetPidStatus AliPIDResponse::NumberOfSigmas(EDetector detCode, const AliVParticle *track,
241                                                              AliPID::EParticleType type, Double_t &val) const
242 {
243   //
244   // NumberOfSigmas with detector status as return value
245   //
246   
247   val=NumberOfSigmas(detCode, track, type);
248   return CheckPIDStatus(detCode, (AliVTrack*)track);
249 }
250
251 //______________________________________________________________________________
252 // public buffered versions of the PID calculation
253 //
254
255 //______________________________________________________________________________
256 Float_t AliPIDResponse::NumberOfSigmasITS(const AliVParticle *vtrack, AliPID::EParticleType type) const
257 {
258   //
259   // Calculate the number of sigmas in the ITS
260   //
261   
262   return NumberOfSigmas(kITS, vtrack, type);
263 }
264
265 //______________________________________________________________________________
266 Float_t AliPIDResponse::NumberOfSigmasTPC(const AliVParticle *vtrack, AliPID::EParticleType type) const
267 {
268   //
269   // Calculate the number of sigmas in the TPC
270   //
271   
272   return NumberOfSigmas(kTPC, vtrack, type);
273 }
274
275 //______________________________________________________________________________
276 Float_t AliPIDResponse::NumberOfSigmasTPC( const AliVParticle *vtrack, 
277                                            AliPID::EParticleType type,
278                                            AliTPCPIDResponse::ETPCdEdxSource dedxSource) const
279 {
280   //get number of sigmas according the selected TPC gain configuration scenario
281   const AliVTrack *track=static_cast<const AliVTrack*>(vtrack);
282
283   Float_t nSigma=fTPCResponse.GetNumberOfSigmas(track, type, dedxSource, fUseTPCEtaCorrection, fUseTPCMultiplicityCorrection);
284
285   return nSigma;
286 }
287
288 //______________________________________________________________________________
289 Float_t AliPIDResponse::NumberOfSigmasTOF(const AliVParticle *vtrack, AliPID::EParticleType type) const
290 {
291   //
292   // Calculate the number of sigmas in the TOF
293   //
294   
295   return NumberOfSigmas(kTOF, vtrack, type);
296 }
297
298 //______________________________________________________________________________
299 Float_t AliPIDResponse::NumberOfSigmasHMPID(const AliVParticle *vtrack, AliPID::EParticleType type) const
300 {
301   //
302   // Calculate the number of sigmas in the EMCAL
303   //
304   
305   return NumberOfSigmas(kHMPID, vtrack, type);
306 }
307
308 //______________________________________________________________________________
309 Float_t AliPIDResponse::NumberOfSigmasEMCAL(const AliVParticle *vtrack, AliPID::EParticleType type) const
310 {
311   //
312   // Calculate the number of sigmas in the EMCAL
313   //
314   
315   return NumberOfSigmas(kEMCAL, vtrack, type);
316 }
317
318 //______________________________________________________________________________
319 Float_t  AliPIDResponse::NumberOfSigmasEMCAL(const AliVParticle *vtrack, AliPID::EParticleType type, Double_t &eop, Double_t showershape[4])  const
320 {
321   //
322   // emcal nsigma with eop and showershape
323   //
324   AliVTrack *track=(AliVTrack*)vtrack;
325   
326   AliVCluster *matchedClus = NULL;
327
328   Double_t mom     = -1.; 
329   Double_t pt      = -1.; 
330   Double_t EovP    = -1.;
331   Double_t fClsE   = -1.;
332
333   // initialize eop and shower shape parameters
334   eop = -1.;
335   for(Int_t i = 0; i < 4; i++){
336     showershape[i] = -1.;
337   }
338   
339   Int_t nMatchClus = -1;
340   Int_t charge     = 0;
341   
342   // Track matching
343   nMatchClus = track->GetEMCALcluster();
344   if(nMatchClus > -1){
345
346     mom    = track->P();
347     pt     = track->Pt();
348     charge = track->Charge();
349     
350     matchedClus = (AliVCluster*)fCurrentEvent->GetCaloCluster(nMatchClus);
351     
352     if(matchedClus){
353       
354       // matched cluster is EMCAL
355       if(matchedClus->IsEMCAL()){
356         
357         fClsE       = matchedClus->E();
358         EovP        = fClsE/mom;
359         
360         // fill used EMCAL variables here
361         eop            = EovP; // E/p
362         showershape[0] = matchedClus->GetNCells(); // number of cells in cluster
363         showershape[1] = matchedClus->GetM02(); // long axis
364         showershape[2] = matchedClus->GetM20(); // short axis
365         showershape[3] = matchedClus->GetDispersion(); // dispersion
366
367         // look for cached value first
368         const AliDetectorPID *detPID=track->GetDetectorPID();
369         const EDetector detector=kEMCAL;
370         
371         if ( detPID && detPID->HasNumberOfSigmas(detector)){
372           return detPID->GetNumberOfSigmas(detector, type);
373         } else if (fCachePID) {
374           FillTrackDetectorPID(track, detector);
375           detPID=track->GetDetectorPID();
376           return detPID->GetNumberOfSigmas(detector, type);
377         }
378         
379         // NSigma value really meaningful only for electrons!
380         return fEMCALResponse.GetNumberOfSigmas(pt,EovP,type,charge);
381       }
382     }
383   }
384   return -999;
385 }
386
387 //______________________________________________________________________________
388 AliPIDResponse::EDetPidStatus AliPIDResponse::GetSignalDelta(EDetector detector, const AliVParticle *track, AliPID::EParticleType type, Double_t &val, Bool_t ratio/*=kFALSE*/) const
389 {
390   //
391   //
392   //
393   val=-9999.;
394   switch (detector){
395     case kITS:   return GetSignalDeltaITS(track,type,val,ratio); break;
396     case kTPC:   return GetSignalDeltaTPC(track,type,val,ratio); break;
397     case kTOF:   return GetSignalDeltaTOF(track,type,val,ratio); break;
398     case kHMPID: return GetSignalDeltaHMPID(track,type,val,ratio); break;
399     default: return kDetNoSignal;
400   }
401   return kDetNoSignal;
402 }
403
404 //______________________________________________________________________________
405 Double_t AliPIDResponse::GetSignalDelta(EDetector detCode, const AliVParticle *track, AliPID::EParticleType type, Bool_t ratio/*=kFALSE*/) const
406 {
407   //
408   //
409   //
410   Double_t val=-9999.;
411   EDetPidStatus stat=GetSignalDelta(detCode, track, type, val, ratio);
412   if ( stat==kDetNoSignal ) val=-9999.;
413   return val;
414 }
415
416 //______________________________________________________________________________
417 AliPIDResponse::EDetPidStatus AliPIDResponse::ComputePIDProbability  (EDetCode  detCode, const AliVTrack *track, Int_t nSpecies, Double_t p[]) const
418 {
419   // Compute PID response of 'detCode'
420   
421   // find detector code from detector bit mask
422   Int_t detector=-1;
423   for (Int_t idet=0; idet<kNdetectors; ++idet) if ( (detCode&(1<<idet)) ) { detector=idet; break; }
424   if (detector==-1) return kDetNoSignal;
425
426   return ComputePIDProbability((EDetector)detector, track, nSpecies, p);
427 }
428
429 //______________________________________________________________________________
430 AliPIDResponse::EDetPidStatus AliPIDResponse::ComputePIDProbability  (EDetector detector,  const AliVTrack *track, Int_t nSpecies, Double_t p[]) const
431 {
432   //
433   // Compute PID response of 'detector'
434   //
435
436   const AliDetectorPID *detPID=track->GetDetectorPID();
437
438   if ( detPID && detPID->HasRawProbability(detector)){
439     return detPID->GetRawProbability(detector, p, nSpecies);
440   } else if (fCachePID) {
441     FillTrackDetectorPID(track, detector);
442     detPID=track->GetDetectorPID();
443     return detPID->GetRawProbability(detector, p, nSpecies);
444   }
445   
446   //if no caching return values calculated from scratch
447   return GetComputePIDProbability(detector, track, nSpecies, p);
448 }
449
450 //______________________________________________________________________________
451 AliPIDResponse::EDetPidStatus AliPIDResponse::ComputeITSProbability  (const AliVTrack *track, Int_t nSpecies, Double_t p[]) const
452 {
453   // Compute PID response for the ITS
454   return ComputePIDProbability(kITS, track, nSpecies, p);
455 }
456
457 //______________________________________________________________________________
458 AliPIDResponse::EDetPidStatus AliPIDResponse::ComputeTPCProbability  (const AliVTrack *track, Int_t nSpecies, Double_t p[]) const
459 {
460   // Compute PID response for the TPC
461   return ComputePIDProbability(kTPC, track, nSpecies, p);
462 }
463
464 //______________________________________________________________________________
465 AliPIDResponse::EDetPidStatus AliPIDResponse::ComputeTOFProbability  (const AliVTrack *track, Int_t nSpecies, Double_t p[]) const
466 {
467   // Compute PID response for the
468   return ComputePIDProbability(kTOF, track, nSpecies, p);
469 }
470
471 //______________________________________________________________________________
472 AliPIDResponse::EDetPidStatus AliPIDResponse::ComputeTRDProbability  (const AliVTrack *track, Int_t nSpecies, Double_t p[]) const
473 {
474   // Compute PID response for the
475   return ComputePIDProbability(kTRD, track, nSpecies, p);
476 }
477
478 //______________________________________________________________________________
479 AliPIDResponse::EDetPidStatus AliPIDResponse::ComputeEMCALProbability  (const AliVTrack *track, Int_t nSpecies, Double_t p[]) const
480 {
481   // Compute PID response for the EMCAL
482   return ComputePIDProbability(kEMCAL, track, nSpecies, p);
483 }
484 //______________________________________________________________________________
485 AliPIDResponse::EDetPidStatus AliPIDResponse::ComputePHOSProbability (const AliVTrack */*track*/, Int_t nSpecies, Double_t p[]) const
486 {
487   // Compute PID response for the PHOS
488   
489   // set flat distribution (no decision)
490   for (Int_t j=0; j<nSpecies; j++) p[j]=1./nSpecies;
491   return kDetNoSignal;
492 }
493
494 //______________________________________________________________________________
495 AliPIDResponse::EDetPidStatus AliPIDResponse::ComputeHMPIDProbability(const AliVTrack *track, Int_t nSpecies, Double_t p[]) const
496 {
497   // Compute PID response for the HMPID
498   return ComputePIDProbability(kHMPID, track, nSpecies, p);
499 }
500
501 //______________________________________________________________________________
502 AliPIDResponse::EDetPidStatus AliPIDResponse::ComputeTRDProbability  (const AliVTrack *track, Int_t nSpecies, Double_t p[],AliTRDPIDResponse::ETRDPIDMethod PIDmethod) const
503 {
504   // Compute PID response for the
505   return GetComputeTRDProbability(track, nSpecies, p, PIDmethod);
506 }
507
508 //______________________________________________________________________________
509 AliPIDResponse::EDetPidStatus AliPIDResponse::CheckPIDStatus(EDetector detector, const AliVTrack *track) const
510 {
511   // calculate detector pid status
512   
513   const Int_t iDetCode=(Int_t)detector;
514   if (iDetCode<0||iDetCode>=kNdetectors) return kDetNoSignal;
515   const AliDetectorPID *detPID=track->GetDetectorPID();
516   
517   if ( detPID ){
518     return detPID->GetPIDStatus(detector);
519   } else if (fCachePID) {
520     FillTrackDetectorPID(track, detector);
521     detPID=track->GetDetectorPID();
522     return detPID->GetPIDStatus(detector);
523   }
524   
525   // if not buffered and no buffering is requested
526   return GetPIDStatus(detector, track);
527 }
528
529 //______________________________________________________________________________
530 void AliPIDResponse::InitialiseEvent(AliVEvent *event, Int_t pass, Int_t run)
531 {
532   //
533   // Apply settings for the current event
534   //
535   fRecoPass=pass;
536   
537
538   fCurrentEvent=NULL;
539   if (!event) return;
540   fCurrentEvent=event;
541   if (run>0) fRun=run;
542   else fRun=event->GetRunNumber();
543   
544   if (fRun!=fOldRun){
545     ExecNewRun();
546     fOldRun=fRun;
547   }
548   
549   //TPC resolution parametrisation PbPb
550   if ( fResolutionCorrection ){
551     Double_t corrSigma=fResolutionCorrection->Eval(GetTPCMultiplicityBin(event));
552     fTPCResponse.SetSigma(3.79301e-03*corrSigma, 2.21280e+04);
553   }
554   
555   // Set up TPC multiplicity for PbPb
556   if (fUseTPCMultiplicityCorrection) {
557     Int_t numESDtracks = event->GetNumberOfESDTracks();
558     if (numESDtracks < 0) {
559       AliError("Cannot obtain event multiplicity (number of ESD tracks < 0). If you are using AODs, this might be a too old production. Please disable the multiplicity correction to get a reliable PID result!");
560       numESDtracks = 0;
561     }
562     fTPCResponse.SetCurrentEventMultiplicity(numESDtracks);
563   }
564   else
565     fTPCResponse.SetCurrentEventMultiplicity(0);
566   
567   //TOF resolution
568   SetTOFResponse(event, (AliPIDResponse::EStartTimeType_t)fTOFPIDParams->GetStartTimeMethod());
569
570
571   // Get and set centrality
572   AliCentrality *centrality = event->GetCentrality();
573   if(centrality){
574     fCurrCentrality = centrality->GetCentralityPercentile("V0M");
575   }
576   else{
577     fCurrCentrality = -1;
578   }
579
580   // Set centrality percentile for EMCAL
581   fEMCALResponse.SetCentrality(fCurrCentrality);
582
583   // switch off some TOF channel according to OADB to match data TOF matching eff 
584   if (fTuneMConData && ((fTuneMConDataMask & kDetTOF) == kDetTOF) && fTOFPIDParams->GetTOFmatchingLossMC() > 0.01){
585     Int_t ntrk = event->GetNumberOfTracks();
586     for(Int_t i=0;i < ntrk;i++){
587       AliVParticle *trk = event->GetTrack(i);
588       Int_t channel = GetTOFResponse().GetTOFchannel(trk);
589       Int_t swoffEachOfThem = Int_t(100./fTOFPIDParams->GetTOFmatchingLossMC() + 0.5);
590       if(!(channel%swoffEachOfThem)) ((AliVTrack *) trk)->ResetStatus(AliVTrack::kTOFout);
591     }
592   }
593
594 }
595
596 //______________________________________________________________________________
597 void AliPIDResponse::ExecNewRun()
598 {
599   //
600   // Things to Execute upon a new run
601   //
602   SetRecoInfo();
603   
604   SetITSParametrisation();
605   
606   SetTPCPidResponseMaster();
607   SetTPCParametrisation();
608   SetTPCEtaMaps();
609
610   SetTRDPidResponseMaster(); 
611   InitializeTRDResponse();
612
613   SetEMCALPidResponseMaster(); 
614   InitializeEMCALResponse();
615   
616   SetTOFPidResponseMaster();
617   InitializeTOFResponse();
618
619   SetHMPIDPidResponseMaster();
620   InitializeHMPIDResponse();
621
622   if (fCurrentEvent) fTPCResponse.SetMagField(fCurrentEvent->GetMagneticField());
623 }
624
625 //______________________________________________________________________________
626 Double_t AliPIDResponse::GetTPCMultiplicityBin(const AliVEvent * const event)
627 {
628   //
629   // Get TPC multiplicity in bins of 150
630   //
631   
632   const AliVVertex* vertexTPC = event->GetPrimaryVertex();
633   Double_t tpcMulti=0.;
634   if(vertexTPC){
635     Double_t vertexContribTPC=vertexTPC->GetNContributors();
636     tpcMulti=vertexContribTPC/150.;
637     if (tpcMulti>20.) tpcMulti=20.;
638   }
639   
640   return tpcMulti;
641 }
642
643 //______________________________________________________________________________
644 void AliPIDResponse::SetRecoInfo()
645 {
646   //
647   // Set reconstruction information
648   //
649   
650   //reset information
651   fLHCperiod="";
652   fMCperiodTPC="";
653   
654   fBeamType="";
655     
656   fBeamType="PP";
657
658   Bool_t hasProdInfo=(fCurrentFile.BeginsWith("LHC"));
659   
660   TPRegexp reg(".*(LHC1[1-3][a-z]+[0-9]+[a-z_]*)/.*");
661   if (hasProdInfo) reg=TPRegexp("LHC1[1-2][a-z]+[0-9]+[a-z_]*");
662   TPRegexp reg12a17("LHC1[2-3][a-z]");
663
664   //find the period by run number (UGLY, but not stored in ESD and AOD... )
665   if (fRun>=114737&&fRun<=117223)      { fLHCperiod="LHC10B"; fMCperiodTPC="LHC10D1";  }
666   else if (fRun>=118503&&fRun<=121040) { fLHCperiod="LHC10C"; fMCperiodTPC="LHC10D1";  }
667   else if (fRun>=122195&&fRun<=126437) { fLHCperiod="LHC10D"; fMCperiodTPC="LHC10F6A"; }
668   else if (fRun>=127710&&fRun<=130850) { fLHCperiod="LHC10E"; fMCperiodTPC="LHC10F6A"; }
669   else if (fRun>=133004&&fRun<=135029) { fLHCperiod="LHC10F"; fMCperiodTPC="LHC10F6A"; }
670   else if (fRun>=135654&&fRun<=136377) { fLHCperiod="LHC10G"; fMCperiodTPC="LHC10F6A"; }
671   else if (fRun>=136851&&fRun<=139846) {
672     fLHCperiod="LHC10H";
673     fMCperiodTPC="LHC10H8";
674     if (reg.MatchB(fCurrentFile)) fMCperiodTPC="LHC11A10";
675     // exception for 13d2 and later
676     if (fCurrentAliRootRev >= 62714) fMCperiodTPC="LHC13D2";
677     fBeamType="PBPB";
678   }
679   else if (fRun>=139847&&fRun<=146974) { fLHCperiod="LHC11A"; fMCperiodTPC="LHC10F6A"; }
680   //TODO: periods 11B (146975-150721), 11C (150722-155837) are not yet treated assume 11d for the moment
681   else if (fRun>=146975&&fRun<=155837) { fLHCperiod="LHC11D"; fMCperiodTPC="LHC10F6A"; }
682   else if (fRun>=155838&&fRun<=159649) { fLHCperiod="LHC11D"; fMCperiodTPC="LHC10F6A"; }
683   // also for 11e (159650-162750),f(162751-165771) use 11d
684   else if (fRun>=159650&&fRun<=162750) { fLHCperiod="LHC11D"; fMCperiodTPC="LHC10F6A"; }
685   else if (fRun>=162751&&fRun<=165771) { fLHCperiod="LHC11D"; fMCperiodTPC="LHC10F6A"; }
686   
687   else if (fRun>=165772 && fRun<=170718) {
688     fLHCperiod="LHC11H";
689     fMCperiodTPC="LHC11A10";
690     fBeamType="PBPB";
691     if (reg12a17.MatchB(fCurrentFile)) fMCperiodTPC="LHC12A17";
692   }
693   if (fRun>=170719 && fRun<=177311) { fLHCperiod="LHC12A"; fBeamType="PP"; /*fMCperiodTPC="";*/ }
694   // for the moment use LHC12b parameters up to LHC12d
695   if (fRun>=177312 /*&& fRun<=179356*/) { fLHCperiod="LHC12B"; fBeamType="PP"; /*fMCperiodTPC="";*/ }
696 //   if (fRun>=179357 && fRun<=183173) { fLHCperiod="LHC12C"; fBeamType="PP"; /*fMCperiodTPC="";*/ }
697 //   if (fRun>=183174 && fRun<=186345) { fLHCperiod="LHC12D"; fBeamType="PP"; /*fMCperiodTPC="";*/ }
698 //   if (fRun>=186346 && fRun<=186635) { fLHCperiod="LHC12E"; fBeamType="PP"; /*fMCperiodTPC="";*/ }
699
700 //   if (fRun>=186636 && fRun<=188166) { fLHCperiod="LHC12F"; fBeamType="PP"; /*fMCperiodTPC="";*/ }
701 //   if (fRun >= 188167 && fRun <= 188355 ) { fLHCperiod="LHC12G"; fBeamType="PP"; /*fMCperiodTPC="";*/ }
702 //   if (fRun >= 188356 && fRun <= 188503 ) { fLHCperiod="LHC12G"; fBeamType="PPB"; /*fMCperiodTPC="";*/ }
703 // for the moment use 12g parametrisation for all full gain runs (LHC12e+)
704   if (fRun >= 186346 && fRun < 194480) { fLHCperiod="LHC12G"; fBeamType="PPB"; fMCperiodTPC="LHC12G"; }
705
706   // New parametrisation for 2013 pPb runs
707   if (fRun >= 194480) { 
708     fLHCperiod="LHC13B"; 
709     fBeamType="PPB";
710     fMCperiodTPC="LHC12G";
711   
712     if (fCurrentAliRootRev >= 61605)
713       fMCperiodTPC="LHC13B2_FIX";
714     if (fCurrentAliRootRev >= 62714)
715       fMCperiodTPC="LHC13B2_FIXn1";
716     
717     // High luminosity pPb runs require different parametrisations
718     if (fRun >= 195875 && fRun <= 197411) {
719       fLHCperiod="LHC13F"; 
720     }
721   }
722
723   //exception new pp MC productions from 2011 (11a periods have 10f6a splines!)
724   if (fBeamType=="PP" && reg.MatchB(fCurrentFile) && !fCurrentFile.Contains("LHC11a")) { fMCperiodTPC="LHC11B2"; fBeamType="PP"; }
725   // exception for 11f1
726   if (fCurrentFile.Contains("LHC11f1")) fMCperiodTPC="LHC11F1";
727   // exception for 12f1a, 12f1b and 12i3
728   if (fCurrentFile.Contains("LHC12f1") || fCurrentFile.Contains("LHC12i3")) fMCperiodTPC="LHC12F1";
729   // exception for 12c4
730   if (fCurrentFile.Contains("LHC12c4")) fMCperiodTPC="LHC12C4";
731         // exception for 12d and 13d pp periods
732         if (fBeamType=="PP" && fCurrentAliRootRev >= 61605) fMCperiodTPC="LHC13D1";
733 }
734
735 //______________________________________________________________________________
736 void AliPIDResponse::SetITSParametrisation()
737 {
738   //
739   // Set the ITS parametrisation
740   //
741 }
742
743  
744 //______________________________________________________________________________
745 void AliPIDResponse::AddPointToHyperplane(TH2D* h, TLinearFitter* linExtrapolation, Int_t binX, Int_t binY)
746 {
747   if (h->GetBinContent(binX, binY) <= 1e-4)
748     return; // Reject bins without content (within some numerical precision) or with strange content
749     
750   Double_t coord[2] = {0, 0};
751   coord[0] = h->GetXaxis()->GetBinCenter(binX);
752   coord[1] = h->GetYaxis()->GetBinCenter(binY);
753   Double_t binError = h->GetBinError(binX, binY);
754   if (binError <= 0) {
755     binError = 1000; // Should not happen because bins without content are rejected for the map (TH2D* h)
756     printf("ERROR: This should never happen: Trying to add bin in addPointToHyperplane with error not set....\n");
757   }
758   linExtrapolation->AddPoint(coord, h->GetBinContent(binX, binY, binError));
759 }
760
761
762 //______________________________________________________________________________
763 TH2D* AliPIDResponse::RefineHistoViaLinearInterpolation(TH2D* h, Double_t refineFactorX, Double_t refineFactorY)
764 {
765   if (!h)
766     return 0x0;
767   
768   // Interpolate to finer map
769   TLinearFitter* linExtrapolation = new TLinearFitter(2, "hyp2", "");
770   
771   Double_t upperMapBoundY = h->GetYaxis()->GetBinUpEdge(h->GetYaxis()->GetNbins());
772   Double_t lowerMapBoundY = h->GetYaxis()->GetBinLowEdge(1);
773   Int_t nBinsX = 30;
774   // Binning was find to yield good results, if 40 bins are chosen for the range 0.0016 to 0.02. For the new variable range,
775   // scale the number of bins correspondingly
776   Int_t nBinsY = TMath::Nint((upperMapBoundY - lowerMapBoundY) / (0.02 - 0.0016) * 40);
777   Int_t nBinsXrefined = nBinsX * refineFactorX;
778   Int_t nBinsYrefined = nBinsY * refineFactorY; 
779   
780   TH2D* hRefined = new TH2D(Form("%s_refined", h->GetName()),  Form("%s (refined)", h->GetTitle()),
781                             nBinsXrefined, h->GetXaxis()->GetBinLowEdge(1), h->GetXaxis()->GetBinUpEdge(h->GetXaxis()->GetNbins()),
782                             nBinsYrefined, lowerMapBoundY, upperMapBoundY);
783   
784   for (Int_t binX = 1; binX <= nBinsXrefined; binX++)  {
785     for (Int_t binY = 1; binY <= nBinsYrefined; binY++)  {
786       
787       hRefined->SetBinContent(binX, binY, 1); // Default value is 1
788       
789       Double_t centerX = hRefined->GetXaxis()->GetBinCenter(binX);
790       Double_t centerY = hRefined->GetYaxis()->GetBinCenter(binY);
791       
792       /*OLD
793       linExtrapolation->ClearPoints();
794       
795       // For interpolation: Just take the corresponding bin from the old histo.
796       // For extrapolation: take the last available bin from the old histo.
797       // If the boundaries are to be skipped, also skip the corresponding bins
798       Int_t oldBinX = h->GetXaxis()->FindBin(centerX);
799       if (oldBinX < 1)  
800         oldBinX = 1;
801       if (oldBinX > nBinsX)
802         oldBinX = nBinsX;
803       
804       Int_t oldBinY = h->GetYaxis()->FindBin(centerY);
805       if (oldBinY < 1)  
806         oldBinY = 1;
807       if (oldBinY > nBinsY)
808         oldBinY = nBinsY;
809       
810       // Neighbours left column
811       if (oldBinX >= 2) {
812         if (oldBinY >= 2) {
813           AddPointToHyperplane(h, linExtrapolation, oldBinX - 1, oldBinY - 1);
814         }
815         
816         AddPointToHyperplane(h, linExtrapolation, oldBinX - 1, oldBinY);
817         
818         if (oldBinY < nBinsY) {
819           AddPointToHyperplane(h, linExtrapolation, oldBinX - 1, oldBinY + 1);
820         }
821       }
822       
823       // Neighbours (and point itself) same column
824       if (oldBinY >= 2) {
825         AddPointToHyperplane(h, linExtrapolation, oldBinX, oldBinY - 1);
826       }
827         
828       AddPointToHyperplane(h, linExtrapolation, oldBinX, oldBinY);
829         
830       if (oldBinY < nBinsY) {
831         AddPointToHyperplane(h, linExtrapolation, oldBinX, oldBinY + 1);
832       }
833       
834       // Neighbours right column
835       if (oldBinX < nBinsX) {
836         if (oldBinY >= 2) {
837           AddPointToHyperplane(h, linExtrapolation, oldBinX + 1, oldBinY - 1);
838         }
839         
840         AddPointToHyperplane(h, linExtrapolation, oldBinX + 1, oldBinY);
841         
842         if (oldBinY < nBinsY) {
843           AddPointToHyperplane(h, linExtrapolation, oldBinX + 1, oldBinY + 1);
844         }
845       }
846       
847       
848       // Fit 2D-hyperplane
849       if (linExtrapolation->GetNpoints() <= 0)
850         continue;
851         
852       if (linExtrapolation->Eval() != 0)// EvalRobust -> Takes much, much, [...], much more time (~hours instead of seconds)
853         continue;
854       
855       // Fill the bin of the refined histogram with the extrapolated value
856       Double_t interpolatedValue = linExtrapolation->GetParameter(0) + linExtrapolation->GetParameter(1) * centerX
857                                  + linExtrapolation->GetParameter(2) * centerY;
858       */
859       Double_t interpolatedValue = h->Interpolate(centerX, centerY) ;
860       hRefined->SetBinContent(binX, binY, interpolatedValue);      
861     }
862   } 
863   
864   
865   // Problem: Interpolation does not work before/beyond center of first/last bin (as the name suggests).
866   // Therefore, for each row in dEdx: Take last bin from old map and interpolate values from center and edge.
867   // Assume line through these points and extropolate to last bin of refined map
868   const Double_t firstOldXbinUpEdge = h->GetXaxis()->GetBinUpEdge(1);
869   const Double_t firstOldXbinCenter = h->GetXaxis()->GetBinCenter(1);
870   
871   const Double_t oldXbinHalfWidth = firstOldXbinUpEdge - firstOldXbinCenter;
872   
873   const Double_t lastOldXbinLowEdge = h->GetXaxis()->GetBinLowEdge(h->GetNbinsX());
874   const Double_t lastOldXbinCenter = h->GetXaxis()->GetBinCenter(h->GetNbinsX());
875   
876   for (Int_t binY = 1; binY <= nBinsYrefined; binY++)  {
877     Double_t centerY = hRefined->GetYaxis()->GetBinCenter(binY);
878     
879     const Double_t interpolatedCenterFirstXbin = h->Interpolate(firstOldXbinCenter, centerY);
880     const Double_t interpolatedUpEdgeFirstXbin = h->Interpolate(firstOldXbinUpEdge, centerY);
881     
882     const Double_t extrapolationSlopeFirstXbin = (interpolatedUpEdgeFirstXbin - interpolatedCenterFirstXbin) / oldXbinHalfWidth;
883     const Double_t extrapolationOffsetFirstXbin = interpolatedCenterFirstXbin;
884     
885     
886     const Double_t interpolatedCenterLastXbin = h->Interpolate(lastOldXbinCenter, centerY);
887     const Double_t interpolatedLowEdgeLastXbin = h->Interpolate(lastOldXbinLowEdge, centerY);
888     
889     const Double_t extrapolationSlopeLastXbin = (interpolatedCenterLastXbin - interpolatedLowEdgeLastXbin) / oldXbinHalfWidth;
890     const Double_t extrapolationOffsetLastXbin = interpolatedCenterLastXbin;
891
892     for (Int_t binX = 1; binX <= nBinsXrefined; binX++)  {
893       Double_t centerX = hRefined->GetXaxis()->GetBinCenter(binX);
894      
895       if (centerX < firstOldXbinCenter) {
896         Double_t extrapolatedValue = extrapolationOffsetFirstXbin + (centerX - firstOldXbinCenter) * extrapolationSlopeFirstXbin;
897         hRefined->SetBinContent(binX, binY, extrapolatedValue);      
898       }
899       else if (centerX <= lastOldXbinCenter) {
900         continue;
901       }
902       else {
903         Double_t extrapolatedValue = extrapolationOffsetLastXbin + (centerX - lastOldXbinCenter) * extrapolationSlopeLastXbin;
904         hRefined->SetBinContent(binX, binY, extrapolatedValue);     
905       }
906     }
907   } 
908   
909   delete linExtrapolation;
910   
911   return hRefined;
912 }
913
914 //______________________________________________________________________________
915 void AliPIDResponse::SetTPCEtaMaps(Double_t refineFactorMapX, Double_t refineFactorMapY,
916                                    Double_t refineFactorSigmaMapX, Double_t refineFactorSigmaMapY)
917 {
918   //
919   // Load the TPC eta correction maps from the OADB
920   //
921   
922   if (fUseTPCEtaCorrection == kFALSE) {
923     // Disable eta correction via setting no maps
924     if (!fTPCResponse.SetEtaCorrMap(0x0))
925       AliInfo("Request to disable TPC eta correction -> Eta correction has been disabled"); 
926     else
927       AliError("Request to disable TPC eta correction -> Some error occured when unloading the correction maps");
928     
929     if (!fTPCResponse.SetSigmaParams(0x0, 0))
930       AliInfo("Request to disable TPC eta correction -> Using old parametrisation for sigma"); 
931     else
932       AliError("Request to disable TPC eta correction -> Some error occured when unloading the sigma maps");
933     
934     return;
935   }
936   
937   TString dataType = "DATA";
938   TString period = fLHCperiod.IsNull() ? "No period information" : fLHCperiod;
939   
940   if (fIsMC)  {
941     if (!(fTuneMConData && ((fTuneMConDataMask & kDetTPC) == kDetTPC))) {
942       period=fMCperiodTPC;
943       dataType="MC";
944     }
945     fRecoPass = 1;
946     
947     if (!(fTuneMConData && ((fTuneMConDataMask & kDetTPC) == kDetTPC)) && fMCperiodTPC.IsNull()) {
948       AliFatal("MC detected, but no MC period set -> Not changing eta maps!");
949       return;
950     }
951   }
952
953   Int_t recopass = fRecoPass;
954   if (fTuneMConData && ((fTuneMConDataMask & kDetTPC) == kDetTPC) )
955     recopass = fRecoPassUser;
956   
957   TString defaultObj = Form("Default_%s_pass%d", dataType.Data(), recopass);
958   
959   AliInfo(Form("Current period and reco pass: %s.pass%d", period.Data(), recopass));
960   
961   // Invalidate old maps
962   fTPCResponse.SetEtaCorrMap(0x0);
963   fTPCResponse.SetSigmaParams(0x0, 0);
964   
965   // Load the eta correction maps
966   AliOADBContainer etaMapsCont(Form("TPCetaMaps_%s_pass%d", dataType.Data(), recopass)); 
967   
968   Int_t statusCont = etaMapsCont.InitFromFile(Form("%s/COMMON/PID/data/TPCetaMaps.root", fOADBPath.Data()),
969                                               Form("TPCetaMaps_%s_pass%d", dataType.Data(), recopass));
970   if (statusCont) {
971     AliError("Failed initializing TPC eta correction maps from OADB -> Disabled eta correction");
972     fUseTPCEtaCorrection = kFALSE;
973   }
974   else {
975     AliInfo(Form("Loading TPC eta correction map from %s/COMMON/PID/data/TPCetaMaps.root", fOADBPath.Data()));
976     
977     TH2D* etaMap = 0x0;
978     
979     if (fIsMC && !(fTuneMConData && ((fTuneMConDataMask & kDetTPC) == kDetTPC))) {
980       TString searchMap = Form("TPCetaMaps_%s_%s_pass%d", dataType.Data(), period.Data(), recopass);
981       etaMap = dynamic_cast<TH2D *>(etaMapsCont.GetDefaultObject(searchMap.Data()));
982       if (!etaMap) {
983         // Try default object
984         etaMap = dynamic_cast<TH2D *>(etaMapsCont.GetDefaultObject(defaultObj.Data()));
985       }
986     }
987     else {
988       etaMap = dynamic_cast<TH2D *>(etaMapsCont.GetObject(fRun, defaultObj.Data()));
989     }
990     
991         
992     if (!etaMap) {
993       AliError(Form("TPC eta correction map not found for run %d and also no default map found -> Disabled eta correction!!!", fRun));
994       fUseTPCEtaCorrection = kFALSE;
995     }
996     else {
997       TH2D* etaMapRefined = RefineHistoViaLinearInterpolation(etaMap, refineFactorMapX, refineFactorMapY);
998       
999       if (etaMapRefined) {
1000         if (!fTPCResponse.SetEtaCorrMap(etaMapRefined)) {
1001           AliError(Form("Failed to set TPC eta correction map for run %d -> Disabled eta correction!!!", fRun));
1002           fTPCResponse.SetEtaCorrMap(0x0);
1003           fUseTPCEtaCorrection = kFALSE;
1004         }
1005         else {
1006           AliInfo(Form("Loaded TPC eta correction map (refine factors %.2f/%.2f) from %s/COMMON/PID/data/TPCetaMaps.root: %s (MD5(map) = %s)", 
1007                        refineFactorMapX, refineFactorMapY, fOADBPath.Data(), fTPCResponse.GetEtaCorrMap()->GetTitle(),
1008                        GetChecksum(fTPCResponse.GetEtaCorrMap()).Data()));
1009         }
1010         
1011         delete etaMapRefined;
1012       }
1013       else {
1014         AliError(Form("Failed to set TPC eta correction map for run %d (map was loaded, but couldn't be refined) -> Disabled eta correction!!!", fRun));
1015         fUseTPCEtaCorrection = kFALSE;
1016       }
1017     }
1018   }
1019   
1020   // If there was some problem loading the eta maps, it makes no sense to load the sigma maps (that require eta corrected data)
1021   if (fUseTPCEtaCorrection == kFALSE) {
1022     AliError("Failed to load TPC eta correction map required by sigma maps -> Using old parametrisation for sigma"); 
1023     return;
1024   }
1025   
1026   // Load the sigma parametrisation (1/dEdx vs tanTheta_local (~eta))
1027   AliOADBContainer etaSigmaMapsCont(Form("TPCetaSigmaMaps_%s_pass%d", dataType.Data(), recopass)); 
1028   
1029   statusCont = etaSigmaMapsCont.InitFromFile(Form("%s/COMMON/PID/data/TPCetaMaps.root", fOADBPath.Data()),
1030                                              Form("TPCetaSigmaMaps_%s_pass%d", dataType.Data(), recopass));
1031   if (statusCont) {
1032     AliError("Failed initializing TPC eta sigma maps from OADB -> Using old sigma parametrisation");
1033   }
1034   else {
1035     AliInfo(Form("Loading TPC eta sigma map from %s/COMMON/PID/data/TPCetaMaps.root", fOADBPath.Data()));
1036     
1037     TObjArray* etaSigmaPars = 0x0;
1038     
1039     if (fIsMC && !(fTuneMConData && ((fTuneMConDataMask & kDetTPC) == kDetTPC))) {
1040       TString searchMap = Form("TPCetaSigmaMaps_%s_%s_pass%d", dataType.Data(), period.Data(), recopass);
1041       etaSigmaPars = dynamic_cast<TObjArray *>(etaSigmaMapsCont.GetDefaultObject(searchMap.Data()));
1042       if (!etaSigmaPars) {
1043         // Try default object
1044         etaSigmaPars = dynamic_cast<TObjArray *>(etaSigmaMapsCont.GetDefaultObject(defaultObj.Data()));
1045       }
1046     }
1047     else {
1048       etaSigmaPars = dynamic_cast<TObjArray *>(etaSigmaMapsCont.GetObject(fRun, defaultObj.Data()));
1049     }
1050     
1051     if (!etaSigmaPars) {
1052       AliError(Form("TPC eta sigma parametrisation not found for run %d -> Using old sigma parametrisation!!!", fRun));
1053     }
1054     else {
1055       TH2D* etaSigmaPar1Map = dynamic_cast<TH2D *>(etaSigmaPars->FindObject("sigmaPar1Map"));
1056       TNamed* sigmaPar0Info = dynamic_cast<TNamed *>(etaSigmaPars->FindObject("sigmaPar0"));
1057       Double_t sigmaPar0 = 0.0;
1058       
1059       if (sigmaPar0Info) {
1060         TString sigmaPar0String = sigmaPar0Info->GetTitle();
1061         sigmaPar0 = sigmaPar0String.Atof();
1062       }
1063       else {
1064         // Something is weired because the object for parameter 0 could not be loaded -> New sigma parametrisation can not be used!
1065         etaSigmaPar1Map = 0x0;
1066       }
1067       
1068       TH2D* etaSigmaPar1MapRefined = RefineHistoViaLinearInterpolation(etaSigmaPar1Map, refineFactorSigmaMapX, refineFactorSigmaMapY);
1069       
1070       
1071       if (etaSigmaPar1MapRefined) {
1072         if (!fTPCResponse.SetSigmaParams(etaSigmaPar1MapRefined, sigmaPar0)) {
1073           AliError(Form("Failed to set TPC eta sigma map for run %d -> Using old sigma parametrisation!!!", fRun));
1074           fTPCResponse.SetSigmaParams(0x0, 0);
1075         }
1076         else {
1077           AliInfo(Form("Loaded TPC sigma correction map (refine factors %.2f/%.2f) from %s/COMMON/PID/data/TPCetaMaps.root: %s (MD5(map) = %s, sigmaPar0 = %f)", 
1078                        refineFactorSigmaMapX, refineFactorSigmaMapY, fOADBPath.Data(), fTPCResponse.GetSigmaPar1Map()->GetTitle(),
1079                        GetChecksum(fTPCResponse.GetSigmaPar1Map()).Data(), sigmaPar0));
1080         }
1081         
1082         delete etaSigmaPar1MapRefined;
1083       }
1084       else {
1085         AliError(Form("Failed to set TPC eta sigma map for run %d (map was loaded, but couldn't be refined) -> Using old sigma parametrisation!!!",
1086                       fRun));
1087       }
1088     }
1089   }
1090 }
1091
1092 //______________________________________________________________________________
1093 void AliPIDResponse::SetTPCPidResponseMaster()
1094 {
1095   //
1096   // Load the TPC pid response functions from the OADB
1097   // Load the TPC voltage maps from OADB
1098   //
1099   //don't load twice for the moment
1100    if (fArrPidResponseMaster) return;
1101  
1102
1103   //reset the PID response functions
1104   delete fArrPidResponseMaster;
1105   fArrPidResponseMaster=NULL;
1106   
1107   TString fileName(Form("%s/COMMON/PID/data/TPCPIDResponse.root", fOADBPath.Data()));
1108   TFile *f=NULL;
1109   if (!fCustomTPCpidResponse.IsNull()) fileName=fCustomTPCpidResponse;
1110   
1111   TString fileNamePIDresponse(Form("%s/COMMON/PID/data/TPCPIDResponse.root", fOADBPath.Data()));
1112   f=TFile::Open(fileNamePIDresponse.Data());
1113   if (f && f->IsOpen() && !f->IsZombie()){
1114     fArrPidResponseMaster=dynamic_cast<TObjArray*>(f->Get("TPCPIDResponse"));
1115   }
1116   delete f;
1117
1118   TString fileNameVoltageMaps(Form("%s/COMMON/PID/data/TPCvoltageSettings.root", fOADBPath.Data()));
1119   f=TFile::Open(fileNameVoltageMaps.Data());
1120   if (f && f->IsOpen() && !f->IsZombie()){
1121     fOADBvoltageMaps=dynamic_cast<AliOADBContainer*>(f->Get("TPCvoltageSettings"));
1122   }
1123   delete f;
1124   
1125   if (!fArrPidResponseMaster){
1126     AliFatal(Form("Could not retrieve the TPC pid response from: %s",fileNamePIDresponse.Data()));
1127     return;
1128   }
1129   fArrPidResponseMaster->SetOwner();
1130
1131   if (!fOADBvoltageMaps)
1132   {
1133     AliFatal(Form("Could not retrieve the TPC voltage maps from: %s",fileNameVoltageMaps.Data()));
1134   }
1135   fArrPidResponseMaster->SetOwner();
1136 }
1137
1138 //______________________________________________________________________________
1139 void AliPIDResponse::SetTPCParametrisation()
1140 {
1141   //
1142   // Change BB parametrisation for current run
1143   //
1144   
1145   //
1146   //reset old splines
1147   //
1148   fTPCResponse.ResetSplines();
1149   
1150   if (fLHCperiod.IsNull()) {
1151     AliError("No period set, not changing parametrisation");
1152     return;
1153   }
1154   
1155   //
1156   // Set default parametrisations for data and MC
1157   //
1158   
1159   //data type
1160   TString datatype="DATA";
1161   //in case of mc fRecoPass is per default 1
1162   if (fIsMC) {
1163       if(!(fTuneMConData && ((fTuneMConDataMask & kDetTPC) == kDetTPC))) datatype="MC";
1164       fRecoPass=1;
1165   }
1166
1167   // period
1168   TString period=fLHCperiod;
1169   if (fIsMC && !(fTuneMConData && ((fTuneMConDataMask & kDetTPC) == kDetTPC))) period=fMCperiodTPC;
1170
1171   Int_t recopass = fRecoPass;
1172   if(fTuneMConData && ((fTuneMConDataMask & kDetTPC) == kDetTPC)) recopass = fRecoPassUser;
1173     
1174   AliInfo(Form("Searching splines for: %s %s PASS%d %s",datatype.Data(),period.Data(),recopass,fBeamType.Data()));
1175   Bool_t found=kFALSE;
1176   //
1177   //set the new PID splines
1178   //
1179   if (fArrPidResponseMaster){
1180     //for MC don't use period information
1181     //if (fIsMC) period="[A-Z0-9]*";
1182     //for MC use MC period information
1183     //pattern for the default entry (valid for all particles)
1184     TPRegexp reg(Form("TSPLINE3_%s_([A-Z]*)_%s_PASS%d_%s_MEAN(_*)([A-Z1-9]*)",datatype.Data(),period.Data(),recopass,fBeamType.Data()));
1185
1186     //find particle id and gain scenario
1187     for (Int_t igainScenario=0; igainScenario<AliTPCPIDResponse::fgkNumberOfGainScenarios; igainScenario++)
1188     {
1189       TObject *grAll=NULL;
1190       TString gainScenario = AliTPCPIDResponse::GainScenarioName(igainScenario);
1191       gainScenario.ToUpper();
1192       //loop over entries and filter them
1193       for (Int_t iresp=0; iresp<fArrPidResponseMaster->GetEntriesFast();++iresp)
1194       {
1195         TObject *responseFunction=fArrPidResponseMaster->At(iresp);
1196         if (responseFunction==NULL) continue;
1197         TString responseName=responseFunction->GetName();
1198          
1199         if (!reg.MatchB(responseName)) continue;
1200
1201         TObjArray *arr=reg.MatchS(responseName); if (!arr) continue;
1202         TObject* tmp=NULL;
1203         tmp=arr->At(1); if (!tmp) continue;
1204         TString particleName=tmp->GetName();
1205         tmp=arr->At(3); if (!tmp) continue;
1206         TString gainScenarioName=tmp->GetName();
1207         delete arr;
1208         if (particleName.IsNull()) continue;
1209         if (!grAll && particleName=="ALL" && gainScenarioName==gainScenario) grAll=responseFunction;
1210         else 
1211         {
1212           for (Int_t ispec=0; ispec<(AliTPCPIDResponse::fgkNumberOfParticleSpecies); ++ispec)
1213           {
1214             TString particle=AliPID::ParticleName(ispec);
1215             particle.ToUpper();
1216             //std::cout<<responseName<<" "<<particle<<" "<<particleName<<" "<<gainScenario<<" "<<gainScenarioName<<std::endl;
1217             if ( particle == particleName && gainScenario == gainScenarioName )
1218             {
1219               fTPCResponse.SetResponseFunction( responseFunction,
1220                                                 (AliPID::EParticleType)ispec,
1221                                                 (AliTPCPIDResponse::ETPCgainScenario)igainScenario );
1222               fTPCResponse.SetUseDatabase(kTRUE);
1223               AliInfo(Form("Adding graph: %d %d - %s (MD5(spline) = %s)",ispec,igainScenario,responseFunction->GetName(),
1224                            GetChecksum((TSpline3*)responseFunction).Data()));
1225               found=kTRUE;
1226               break;
1227             }
1228           }
1229         }
1230       }
1231       
1232       // Retrieve responsefunction for pions - will (if available) be used for muons if there are no dedicated muon splines.
1233       // For light nuclei, try to set the proton spline, if no dedicated splines are available.
1234       // In both cases: Use default splines, if no dedicated splines and no pion/proton splines are available.
1235       TObject* responseFunctionPion = fTPCResponse.GetResponseFunction( (AliPID::EParticleType)AliPID::kPion,                             
1236                                                                         (AliTPCPIDResponse::ETPCgainScenario)igainScenario);
1237       TObject* responseFunctionProton = fTPCResponse.GetResponseFunction( (AliPID::EParticleType)AliPID::kProton,                             
1238                                                                           (AliTPCPIDResponse::ETPCgainScenario)igainScenario);
1239       
1240       for (Int_t ispec=0; ispec<(AliTPCPIDResponse::fgkNumberOfParticleSpecies); ++ispec)
1241       {
1242         if (!fTPCResponse.GetResponseFunction( (AliPID::EParticleType)ispec,
1243           (AliTPCPIDResponse::ETPCgainScenario)igainScenario))
1244         {
1245           if (ispec == AliPID::kMuon) { // Muons
1246             if (responseFunctionPion) {
1247               fTPCResponse.SetResponseFunction( responseFunctionPion,
1248                                                 (AliPID::EParticleType)ispec,
1249                                                 (AliTPCPIDResponse::ETPCgainScenario)igainScenario );
1250               fTPCResponse.SetUseDatabase(kTRUE);
1251               AliInfo(Form("Adding graph: %d %d - %s (MD5(spline) = %s)",ispec,igainScenario,responseFunctionPion->GetName(),
1252                            GetChecksum((TSpline3*)responseFunctionPion).Data()));
1253               found=kTRUE;  
1254             }
1255             else if (grAll) {
1256               fTPCResponse.SetResponseFunction( grAll,
1257                                                 (AliPID::EParticleType)ispec,
1258                                                 (AliTPCPIDResponse::ETPCgainScenario)igainScenario );
1259               fTPCResponse.SetUseDatabase(kTRUE);
1260               AliInfo(Form("Adding graph: %d %d - %s (MD5(spline) = %s)",ispec,igainScenario,grAll->GetName(),
1261                            GetChecksum((TSpline3*)grAll).Data()));
1262               found=kTRUE;
1263             }
1264             //else
1265             //  AliError(Form("No splines found for muons (also no pion splines and no default splines) for gain scenario %d!", igainScenario));
1266           }
1267           else if (ispec >= AliPID::kSPECIES) { // Light nuclei
1268             if (responseFunctionProton) {
1269               fTPCResponse.SetResponseFunction( responseFunctionProton,
1270                                                 (AliPID::EParticleType)ispec,
1271                                                 (AliTPCPIDResponse::ETPCgainScenario)igainScenario );
1272               fTPCResponse.SetUseDatabase(kTRUE);
1273               AliInfo(Form("Adding graph: %d %d - %s (MD5(spline) = %s)",ispec,igainScenario,responseFunctionProton->GetName(),
1274                            GetChecksum((TSpline3*)responseFunctionProton).Data()));
1275               found=kTRUE;  
1276             }
1277             else if (grAll) {
1278               fTPCResponse.SetResponseFunction( grAll,
1279                                                 (AliPID::EParticleType)ispec,
1280                                                 (AliTPCPIDResponse::ETPCgainScenario)igainScenario );
1281               fTPCResponse.SetUseDatabase(kTRUE);
1282               AliInfo(Form("Adding graph: %d %d - %s (MD5(spline) = %s)",ispec,igainScenario,grAll->GetName(),
1283                            GetChecksum((TSpline3*)grAll).Data()));
1284               found=kTRUE;
1285             }
1286             //else
1287             //  AliError(Form("No splines found for species %d (also no proton splines and no default splines) for gain scenario %d!",
1288             //                ispec, igainScenario));
1289           }
1290         }
1291       }
1292     }
1293   }
1294   else AliInfo("no fArrPidResponseMaster");
1295
1296   if (!found){
1297     AliError(Form("No splines found for: %s %s PASS%d %s",datatype.Data(),period.Data(),recopass,fBeamType.Data()));
1298   }
1299
1300
1301   //
1302   // Setup multiplicity correction (only used for non-pp collisions)
1303   //
1304   
1305   const Bool_t isPP = (fBeamType.CompareTo("PP") == 0);
1306   
1307   // 2013 pPb data taking at low luminosity
1308   const Bool_t isPPb2013LowLuminosity = period.Contains("LHC13B") || period.Contains("LHC13C") || period.Contains("LHC13D");
1309   // PbPb 2010, period 10h.pass2
1310   //TODO Needs further development const Bool_t is10hpass2 = period.Contains("LHC10H") && recopass == 2;
1311   
1312   
1313   // In case of MC without(!) tune on data activated for the TPC, don't use the multiplicity correction for the moment
1314   Bool_t isMCandNotTPCtuneOnData = fIsMC && !(fTuneMConData && ((fTuneMConDataMask & kDetTPC) == kDetTPC));
1315   
1316   // If correction is available, but disabled (highly NOT recommended!), print warning
1317   if (!fUseTPCMultiplicityCorrection && !isPP && !isMCandNotTPCtuneOnData) {
1318     //TODO: Needs further development if (is10hpass2 || isPPb2013LowLuminosity) {
1319     if (isPPb2013LowLuminosity) {
1320       AliWarning("Mulitplicity correction disabled, but correction parameters for this period exist. It is highly recommended to use enable the correction. Otherwise the splines might be off!");
1321     }
1322   }
1323   
1324   if (fUseTPCMultiplicityCorrection && !isPP && !isMCandNotTPCtuneOnData) {
1325     AliInfo("Multiplicity correction enabled!");
1326     
1327     //TODO After testing, load parameters from outside       
1328     /*TODO no correction for MC
1329     if (period.Contains("LHC11A10"))  {//LHC11A10A
1330       AliInfo("Using multiplicity correction parameters for 11a10!");
1331       fTPCResponse.SetParameterMultiplicityCorrection(0, 6.90133e-06);
1332       fTPCResponse.SetParameterMultiplicityCorrection(1, -1.22123e-03);
1333       fTPCResponse.SetParameterMultiplicityCorrection(2, 1.80220e-02);
1334       fTPCResponse.SetParameterMultiplicityCorrection(3, 0.1);
1335       fTPCResponse.SetParameterMultiplicityCorrection(4, 6.45306e-03);
1336       
1337       fTPCResponse.SetParameterMultiplicityCorrectionTanTheta(0, -2.85505e-07);
1338       fTPCResponse.SetParameterMultiplicityCorrectionTanTheta(1, -1.31911e-06);
1339       fTPCResponse.SetParameterMultiplicityCorrectionTanTheta(2, -0.5);
1340
1341       fTPCResponse.SetParameterMultiplicitySigmaCorrection(0, -4.29665e-05);
1342       fTPCResponse.SetParameterMultiplicitySigmaCorrection(1, 1.37023e-02);
1343       fTPCResponse.SetParameterMultiplicitySigmaCorrection(2, -6.36337e-01);
1344       fTPCResponse.SetParameterMultiplicitySigmaCorrection(3, 1.13479e-02);
1345     }
1346     else*/ if (isPPb2013LowLuminosity)  {// 2013 pPb data taking at low luminosity
1347       AliInfo("Using multiplicity correction parameters for 13b.pass2 (at least also valid for 13{c,d} and pass 3)!");
1348       
1349       fTPCResponse.SetParameterMultiplicityCorrection(0, -5.906e-06);
1350       fTPCResponse.SetParameterMultiplicityCorrection(1, -5.064e-04);
1351       fTPCResponse.SetParameterMultiplicityCorrection(2, -3.521e-02);
1352       fTPCResponse.SetParameterMultiplicityCorrection(3, 2.469e-02);
1353       fTPCResponse.SetParameterMultiplicityCorrection(4, 0);
1354       
1355       fTPCResponse.SetParameterMultiplicityCorrectionTanTheta(0, -5.32e-06);
1356       fTPCResponse.SetParameterMultiplicityCorrectionTanTheta(1, 1.177e-05);
1357       fTPCResponse.SetParameterMultiplicityCorrectionTanTheta(2, -0.5);
1358       
1359       fTPCResponse.SetParameterMultiplicitySigmaCorrection(0, 0.);
1360       fTPCResponse.SetParameterMultiplicitySigmaCorrection(1, 0.);
1361       fTPCResponse.SetParameterMultiplicitySigmaCorrection(2, 0.);
1362       fTPCResponse.SetParameterMultiplicitySigmaCorrection(3, 0.);
1363       
1364       /* Not too bad, but far from perfect in the details
1365       fTPCResponse.SetParameterMultiplicityCorrection(0, -6.27187e-06);
1366       fTPCResponse.SetParameterMultiplicityCorrection(1, -4.60649e-04);
1367       fTPCResponse.SetParameterMultiplicityCorrection(2, -4.26450e-02);
1368       fTPCResponse.SetParameterMultiplicityCorrection(3, 2.40590e-02);
1369       fTPCResponse.SetParameterMultiplicityCorrection(4, 0);
1370       
1371       fTPCResponse.SetParameterMultiplicityCorrectionTanTheta(0, -5.338e-06);
1372       fTPCResponse.SetParameterMultiplicityCorrectionTanTheta(1, 1.220e-05);
1373       fTPCResponse.SetParameterMultiplicityCorrectionTanTheta(2, -0.5);
1374       
1375       fTPCResponse.SetParameterMultiplicitySigmaCorrection(0, 7.89237e-05);
1376       fTPCResponse.SetParameterMultiplicitySigmaCorrection(1, -1.30662e-02);
1377       fTPCResponse.SetParameterMultiplicitySigmaCorrection(2, 8.91548e-01);
1378       fTPCResponse.SetParameterMultiplicitySigmaCorrection(3, 1.47931e-02);
1379       */
1380     }
1381     /*TODO: Needs further development
1382     else if (is10hpass2) {    
1383       AliInfo("Using multiplicity correction parameters for 10h.pass2!");
1384       fTPCResponse.SetParameterMultiplicityCorrection(0, 3.21636e-07);
1385       fTPCResponse.SetParameterMultiplicityCorrection(1, -6.65876e-04);
1386       fTPCResponse.SetParameterMultiplicityCorrection(2, 1.28786e-03);
1387       fTPCResponse.SetParameterMultiplicityCorrection(3, 1.47677e-02);
1388       fTPCResponse.SetParameterMultiplicityCorrection(4, 0);
1389       
1390       fTPCResponse.SetParameterMultiplicityCorrectionTanTheta(0, 7.23591e-08);
1391       fTPCResponse.SetParameterMultiplicityCorrectionTanTheta(1, 2.7469e-06);
1392       fTPCResponse.SetParameterMultiplicityCorrectionTanTheta(2, -0.5);
1393       
1394       fTPCResponse.SetParameterMultiplicitySigmaCorrection(0, -1.22590e-05);
1395       fTPCResponse.SetParameterMultiplicitySigmaCorrection(1, 6.88888e-03);
1396       fTPCResponse.SetParameterMultiplicitySigmaCorrection(2, -3.20788e-01);
1397       fTPCResponse.SetParameterMultiplicitySigmaCorrection(3, 1.07345e-02);
1398     }
1399     */
1400     else {
1401       AliError(Form("Multiplicity correction is enabled, but no multiplicity correction parameters have been found for period %s.pass%d -> Mulitplicity correction DISABLED!", period.Data(), recopass));
1402       fUseTPCMultiplicityCorrection = kFALSE;
1403       fTPCResponse.ResetMultiplicityCorrectionFunctions();
1404     }
1405   }
1406   else {
1407     // Just set parameters such that overall correction factor is 1, i.e. no correction.
1408     // This is just a reasonable choice for the parameters for safety reasons. Disabling
1409     // the multiplicity correction will anyhow skip the calculation of the corresponding
1410     // correction factor inside THIS class. Nevertheless, experts can access the TPCPIDResponse
1411     // directly and use it for calculations - which should still give valid results, even if
1412     // the multiplicity correction is explicitely enabled in such expert calls.
1413     
1414     TString reasonForDisabling = "requested by user";
1415     if (fUseTPCMultiplicityCorrection) {
1416       if (isPP)
1417         reasonForDisabling = "pp collisions";
1418       else
1419         reasonForDisabling = "MC w/o tune on data";
1420     }
1421     
1422     AliInfo(Form("Multiplicity correction %sdisabled (%s)!", fUseTPCMultiplicityCorrection ? "automatically " : "",
1423                  reasonForDisabling.Data()));
1424     
1425     fUseTPCMultiplicityCorrection = kFALSE;
1426     fTPCResponse.ResetMultiplicityCorrectionFunctions();
1427   }
1428   
1429   if (fUseTPCMultiplicityCorrection) {
1430     for (Int_t i = 0; i <= 4 + 1; i++) {
1431       AliInfo(Form("parMultCorr: %d, %e", i, fTPCResponse.GetMultiplicityCorrectionFunction()->GetParameter(i)));
1432     }
1433     for (Int_t j = 0; j <= 2 + 1; j++) {
1434       AliInfo(Form("parMultCorrTanTheta: %d, %e", j, fTPCResponse.GetMultiplicityCorrectionFunctionTanTheta()->GetParameter(j)));
1435     }
1436     for (Int_t j = 0; j <= 3 + 1; j++) {
1437       AliInfo(Form("parMultSigmaCorr: %d, %e", j, fTPCResponse.GetMultiplicitySigmaCorrectionFunction()->GetParameter(j)));
1438     }
1439   }
1440   
1441   //
1442   // Setup old resolution parametrisation
1443   //
1444   
1445   //default
1446   fTPCResponse.SetSigma(3.79301e-03, 2.21280e+04);
1447   
1448   if (fRun>=122195){ //LHC10d
1449     fTPCResponse.SetSigma(2.30176e-02, 5.60422e+02);
1450   }
1451   
1452   if (fRun>=170719){ // LHC12a
1453     fTPCResponse.SetSigma(2.95714e-03, 1.01953e+05);
1454   }
1455   
1456   if (fRun>=177312){ // LHC12b
1457     fTPCResponse.SetSigma(3.74633e-03, 7.11829e+04 );
1458   }
1459   
1460   if (fRun>=186346){ // LHC12e
1461     fTPCResponse.SetSigma(8.62022e-04, 9.08156e+05);
1462   }
1463   
1464   if (fArrPidResponseMaster)
1465   fResolutionCorrection=(TF1*)fArrPidResponseMaster->FindObject(Form("TF1_%s_ALL_%s_PASS%d_%s_SIGMA",datatype.Data(),period.Data(),recopass,fBeamType.Data()));
1466   
1467   if (fResolutionCorrection) AliInfo(Form("Setting multiplicity correction function: %s  (MD5(corr function) = %s)",
1468                                           fResolutionCorrection->GetName(), GetChecksum(fResolutionCorrection).Data()));
1469
1470   //read in the voltage map
1471   TVectorF* gsm = 0x0;
1472   if (fOADBvoltageMaps) gsm=dynamic_cast<TVectorF*>(fOADBvoltageMaps->GetObject(fRun));
1473   if (gsm) 
1474   {
1475     fTPCResponse.SetVoltageMap(*gsm);
1476     TString vals;
1477     AliInfo(Form("Reading the voltage map for run %d\n",fRun));
1478     vals="IROC A: "; for (Int_t i=0; i<18; i++){vals+=Form("%.2f ",(*gsm)[i]);}
1479     AliInfo(vals.Data());
1480     vals="IROC C: "; for (Int_t i=18; i<36; i++){vals+=Form("%.2f ",(*gsm)[i]);}
1481     AliInfo(vals.Data());
1482     vals="OROC A: "; for (Int_t i=36; i<54; i++){vals+=Form("%.2f ",(*gsm)[i]);}
1483     AliInfo(vals.Data());
1484     vals="OROC C: "; for (Int_t i=54; i<72; i++){vals+=Form("%.2f ",(*gsm)[i]);}
1485     AliInfo(vals.Data());
1486   }
1487   else AliInfo("no voltage map, ideal default assumed");
1488 }
1489
1490 //______________________________________________________________________________
1491 void AliPIDResponse::SetTRDPidResponseMaster()
1492 {
1493   //
1494   // Load the TRD pid params and references from the OADB
1495   //
1496   if(fTRDPIDResponseObject) return;
1497   AliOADBContainer contParams("contParams"); 
1498
1499   Int_t statusResponse = contParams.InitFromFile(Form("%s/COMMON/PID/data/TRDPIDResponse.root", fOADBPath.Data()), "AliTRDPIDResponseObject");
1500   if(statusResponse){
1501     AliError("Failed initializing PID Response Object from OADB");
1502   } else {
1503     AliInfo(Form("Loading TRD Response from %s/COMMON/PID/data/TRDPIDResponse.root", fOADBPath.Data()));
1504     fTRDPIDResponseObject = dynamic_cast<AliTRDPIDResponseObject *>(contParams.GetObject(fRun));
1505     if(!fTRDPIDResponseObject){
1506       AliError(Form("TRD Response not found in run %d", fRun));
1507     }
1508   }
1509 }
1510
1511 //______________________________________________________________________________
1512 void AliPIDResponse::InitializeTRDResponse(){
1513   //
1514   // Set PID Params and references to the TRD PID response
1515   // 
1516     fTRDResponse.SetPIDResponseObject(fTRDPIDResponseObject);
1517 }
1518
1519 //______________________________________________________________________________
1520 void AliPIDResponse::SetTRDSlices(UInt_t TRDslicesForPID[2],AliTRDPIDResponse::ETRDPIDMethod method) const{
1521
1522     if(fLHCperiod.Contains("LHC10D") || fLHCperiod.Contains("LHC10E")){
1523         // backward compatibility for setting with 8 slices
1524         TRDslicesForPID[0] = 0;
1525         TRDslicesForPID[1] = 7;
1526     }
1527     else{
1528         if(method==AliTRDPIDResponse::kLQ1D){
1529             TRDslicesForPID[0] = 0; // first Slice contains normalized dEdx
1530             TRDslicesForPID[1] = 0;
1531         }
1532         if(method==AliTRDPIDResponse::kLQ2D){
1533             TRDslicesForPID[0] = 1;
1534             TRDslicesForPID[1] = 7;
1535         }
1536     }
1537     AliDebug(1,Form("Slice Range set to %d - %d",TRDslicesForPID[0],TRDslicesForPID[1]));
1538 }
1539
1540 //______________________________________________________________________________
1541 void AliPIDResponse::SetTOFPidResponseMaster()
1542 {
1543   //
1544   // Load the TOF pid params from the OADB
1545   //
1546
1547   if (fTOFPIDParams) delete fTOFPIDParams;
1548   fTOFPIDParams=NULL;
1549
1550   TFile *oadbf = new TFile(Form("%s/COMMON/PID/data/TOFPIDParams.root",fOADBPath.Data()));
1551   if (oadbf && oadbf->IsOpen()) {
1552     AliInfo(Form("Loading TOF Params from %s/COMMON/PID/data/TOFPIDParams.root", fOADBPath.Data()));
1553     AliOADBContainer *oadbc = (AliOADBContainer *)oadbf->Get("TOFoadb");
1554     if (oadbc) fTOFPIDParams = dynamic_cast<AliTOFPIDParams *>(oadbc->GetObject(fRun,"TOFparams"));
1555     oadbf->Close();
1556     delete oadbc;
1557   }
1558   delete oadbf;
1559
1560   if (!fTOFPIDParams) AliFatal("TOFPIDParams could not be retrieved");
1561 }
1562
1563 //______________________________________________________________________________
1564 void AliPIDResponse::InitializeTOFResponse(){
1565   //
1566   // Set PID Params to the TOF PID response
1567   //
1568
1569   AliInfo("TOF PID Params loaded from OADB");
1570   AliInfo(Form("  TOF resolution %5.2f [ps]",fTOFPIDParams->GetTOFresolution()));
1571   AliInfo(Form("  StartTime method %d",fTOFPIDParams->GetStartTimeMethod()));
1572   AliInfo(Form("  TOF res. mom. params: %5.2f %5.2f %5.2f %5.2f",
1573                fTOFPIDParams->GetSigParams(0),fTOFPIDParams->GetSigParams(1),fTOFPIDParams->GetSigParams(2),fTOFPIDParams->GetSigParams(3)));
1574   AliInfo(Form("  Fraction of tracks within gaussian behaviour: %6.4f",fTOFPIDParams->GetTOFtail()));
1575   AliInfo(Form("  MC: Fraction of tracks (percentage) to cut to fit matching in data: %6.2f%%",fTOFPIDParams->GetTOFmatchingLossMC()));
1576   AliInfo(Form("  MC: Fraction of random hits (percentage) to add to fit mismatch in data: %6.2f%%",fTOFPIDParams->GetTOFadditionalMismForMC()));
1577   AliInfo(Form("  Start Time Offset %6.2f ps",fTOFPIDParams->GetTOFtimeOffset()));
1578
1579   for (Int_t i=0;i<4;i++) {
1580     fTOFResponse.SetTrackParameter(i,fTOFPIDParams->GetSigParams(i));
1581   }
1582   fTOFResponse.SetTimeResolution(fTOFPIDParams->GetTOFresolution());
1583
1584   AliInfo("TZERO resolution loaded from ESDrun/AODheader");
1585   Float_t t0Spread[4];
1586   for (Int_t i=0;i<4;i++) t0Spread[i]=fCurrentEvent->GetT0spread(i);
1587   AliInfo(Form("  TZERO spreads from data: (A+C)/2 %f A %f C %f (A'-C')/2: %f",t0Spread[0],t0Spread[1],t0Spread[2],t0Spread[3]));
1588   Float_t a = t0Spread[1]*t0Spread[1]-t0Spread[0]*t0Spread[0]+t0Spread[3]*t0Spread[3];
1589   Float_t c = t0Spread[2]*t0Spread[2]-t0Spread[0]*t0Spread[0]+t0Spread[3]*t0Spread[3];
1590   if ( (t0Spread[0] > 50. && t0Spread[0] < 400.) && (a > 0.) && (c>0.)) {
1591     fResT0AC=t0Spread[3];
1592     fResT0A=TMath::Sqrt(a);
1593     fResT0C=TMath::Sqrt(c);
1594   } else {
1595     AliInfo("  TZERO spreads not present or inconsistent, loading default");
1596     fResT0A=75.;
1597     fResT0C=65.;
1598     fResT0AC=55.;
1599   }
1600   AliInfo(Form("  TZERO resolution set to: T0A: %f [ps] T0C: %f [ps] T0AC %f [ps]",fResT0A,fResT0C,fResT0AC));
1601
1602 }
1603
1604 //______________________________________________________________________________
1605 void AliPIDResponse::SetHMPIDPidResponseMaster()
1606 {
1607   //
1608   // Load the HMPID pid params from the OADB
1609   //
1610
1611   if (fHMPIDPIDParams) delete fHMPIDPIDParams;
1612   fHMPIDPIDParams=NULL;
1613
1614   TFile *oadbf = new TFile(Form("%s/COMMON/PID/data/HMPIDPIDParams.root",fOADBPath.Data()));
1615   if (oadbf && oadbf->IsOpen()) {
1616     AliInfo(Form("Loading HMPID Params from %s/COMMON/PID/data/HMPIDPIDParams.root", fOADBPath.Data()));
1617     AliOADBContainer *oadbc = (AliOADBContainer *)oadbf->Get("HMPoadb");
1618     if (oadbc) fHMPIDPIDParams = dynamic_cast<AliHMPIDPIDParams *>(oadbc->GetObject(fRun,"HMPparams"));
1619     oadbf->Close();
1620     delete oadbc;
1621   }
1622   delete oadbf;
1623
1624   if (!fHMPIDPIDParams) AliFatal("HMPIDPIDParams could not be retrieved");
1625 }
1626
1627 //______________________________________________________________________________
1628 void AliPIDResponse::InitializeHMPIDResponse(){
1629   //
1630   // Set PID Params to the HMPID PID response
1631   //
1632
1633   fHMPIDResponse.SetRefIndexArray(fHMPIDPIDParams->GetHMPIDrefIndex());
1634 }
1635
1636 //______________________________________________________________________________
1637 Bool_t AliPIDResponse::IdentifiedAsElectronTRD(const AliVTrack *vtrack, Double_t efficiencyLevel,Double_t centrality,AliTRDPIDResponse::ETRDPIDMethod PIDmethod) const {
1638   //
1639   // Check whether track is identified as electron under a given electron efficiency hypothesis
1640     //
1641
1642   Double_t probs[AliPID::kSPECIES];
1643   ComputeTRDProbability(vtrack, AliPID::kSPECIES, probs,PIDmethod);
1644
1645   Int_t ntracklets = vtrack->GetTRDntrackletsPID();
1646   // Take mean of the TRD momenta in the given tracklets
1647   Float_t p = 0, trdmomenta[AliVTrack::kTRDnPlanes];
1648   Int_t nmomenta = 0;
1649   for(Int_t iPl=0;iPl<AliVTrack::kTRDnPlanes;iPl++){
1650     if(vtrack->GetTRDmomentum(iPl) > 0.){
1651       trdmomenta[nmomenta++] = vtrack->GetTRDmomentum(iPl); 
1652     }
1653   }
1654   p = TMath::Mean(nmomenta, trdmomenta);
1655
1656   return fTRDResponse.IdentifiedAsElectron(ntracklets, probs, p, efficiencyLevel,centrality,PIDmethod);
1657 }
1658
1659 //______________________________________________________________________________
1660 void AliPIDResponse::SetEMCALPidResponseMaster()
1661 {
1662   //
1663   // Load the EMCAL pid response functions from the OADB
1664   //
1665   TObjArray* fEMCALPIDParamsRun      = NULL;
1666   TObjArray* fEMCALPIDParamsPass     = NULL;
1667
1668   if(fEMCALPIDParams) return;
1669   AliOADBContainer contParams("contParams"); 
1670
1671   Int_t statusPars = contParams.InitFromFile(Form("%s/COMMON/PID/data/EMCALPIDParams.root", fOADBPath.Data()), "AliEMCALPIDParams");
1672   if(statusPars){
1673     AliError("Failed initializing PID Params from OADB");
1674   } 
1675   else {
1676     AliInfo(Form("Loading EMCAL Params from %s/COMMON/PID/data/EMCALPIDParams.root", fOADBPath.Data()));
1677
1678     fEMCALPIDParamsRun = dynamic_cast<TObjArray *>(contParams.GetObject(fRun));
1679     if(fEMCALPIDParamsRun)  fEMCALPIDParamsPass = dynamic_cast<TObjArray *>(fEMCALPIDParamsRun->FindObject(Form("pass%d",fRecoPass)));
1680     if(fEMCALPIDParamsPass) fEMCALPIDParams     = dynamic_cast<TObjArray *>(fEMCALPIDParamsPass->FindObject(Form("EMCALPIDParams_Particles")));
1681
1682     if(!fEMCALPIDParams){
1683       AliInfo(Form("EMCAL Params not found in run %d pass %d", fRun, fRecoPass));
1684       AliInfo("Will take the standard LHC11d instead ...");
1685
1686       fEMCALPIDParamsRun = dynamic_cast<TObjArray *>(contParams.GetObject(156477));
1687       if(fEMCALPIDParamsRun)  fEMCALPIDParamsPass = dynamic_cast<TObjArray *>(fEMCALPIDParamsRun->FindObject(Form("pass%d",1)));
1688       if(fEMCALPIDParamsPass) fEMCALPIDParams     = dynamic_cast<TObjArray *>(fEMCALPIDParamsPass->FindObject(Form("EMCALPIDParams_Particles")));
1689
1690       if(!fEMCALPIDParams){
1691         AliError(Form("DEFAULT EMCAL Params (LHC11d) not found in file %s/COMMON/PID/data/EMCALPIDParams.root", fOADBPath.Data()));     
1692       }
1693     }
1694   }
1695 }
1696
1697 //______________________________________________________________________________
1698 void AliPIDResponse::InitializeEMCALResponse(){
1699   //
1700   // Set PID Params to the EMCAL PID response
1701   // 
1702   fEMCALResponse.SetPIDParams(fEMCALPIDParams);
1703
1704 }
1705
1706 //______________________________________________________________________________
1707 void AliPIDResponse::FillTrackDetectorPID(const AliVTrack *track, EDetector detector) const
1708 {
1709   //
1710   // create detector PID information and setup the transient pointer in the track
1711   //
1712   
1713   // check if detector number is inside accepted range
1714   if (detector == kNdetectors) return;
1715   
1716   // get detector pid
1717   AliDetectorPID *detPID=const_cast<AliDetectorPID*>(track->GetDetectorPID());
1718   if (!detPID) {
1719     detPID=new AliDetectorPID;
1720     (const_cast<AliVTrack*>(track))->SetDetectorPID(detPID);
1721   }
1722   
1723   //check if values exist
1724   if (detPID->HasRawProbability(detector) && detPID->HasNumberOfSigmas(detector)) return;
1725   
1726   //TODO: which particles to include? See also the loops below...
1727   Double_t values[AliPID::kSPECIESC]={0};
1728
1729   //probabilities
1730   EDetPidStatus status=GetComputePIDProbability(detector,track,AliPID::kSPECIESC,values);
1731   detPID->SetRawProbability(detector, values, (Int_t)AliPID::kSPECIESC, status);
1732   
1733   //nsigmas
1734   for (Int_t ipart=0; ipart<AliPID::kSPECIESC; ++ipart)
1735     values[ipart]=GetNumberOfSigmas(detector,track,(AliPID::EParticleType)ipart);
1736   // the pid status is the same for probabilities and nSigmas, so it is
1737   // fine to use the one from the probabilities also here
1738   detPID->SetNumberOfSigmas(detector, values, (Int_t)AliPID::kSPECIESC, status);
1739   
1740 }
1741
1742 //______________________________________________________________________________
1743 void AliPIDResponse::FillTrackDetectorPID()
1744 {
1745   //
1746   // create detector PID information and setup the transient pointer in the track
1747   //
1748
1749   if (!fCurrentEvent) return;
1750   
1751   for (Int_t itrack=0; itrack<fCurrentEvent->GetNumberOfTracks(); ++itrack){
1752     AliVTrack *track=dynamic_cast<AliVTrack*>(fCurrentEvent->GetTrack(itrack));
1753     if (!track) continue;
1754
1755     for (Int_t idet=0; idet<kNdetectors; ++idet){
1756       FillTrackDetectorPID(track, (EDetector)idet);
1757     }
1758   }
1759 }
1760
1761 //______________________________________________________________________________
1762 void AliPIDResponse::SetTOFResponse(AliVEvent *vevent,EStartTimeType_t option){
1763   //
1764   // Set TOF response function
1765   // Input option for event_time used
1766   //
1767
1768     Float_t t0spread = 0.; //vevent->GetEventTimeSpread();
1769     if(t0spread < 10) t0spread = 80;
1770
1771     // T0-FILL and T0-TO offset (because of TOF misallignment
1772     Float_t starttimeoffset = 0;
1773     if(fTOFPIDParams && !(fIsMC)) starttimeoffset=fTOFPIDParams->GetTOFtimeOffset();
1774     if(fTOFPIDParams){
1775       fTOFtail = fTOFPIDParams->GetTOFtail();
1776       GetTOFResponse().SetTOFtail(fTOFtail);
1777     }
1778
1779     // T0 from TOF algorithm
1780     Bool_t flagT0TOF=kFALSE;
1781     Bool_t flagT0T0=kFALSE;
1782     Float_t *startTime = new Float_t[fTOFResponse.GetNmomBins()];
1783     Float_t *startTimeRes = new Float_t[fTOFResponse.GetNmomBins()];
1784     Int_t *startTimeMask = new Int_t[fTOFResponse.GetNmomBins()];
1785
1786     // T0-TOF arrays
1787     Float_t *estimatedT0event = new Float_t[fTOFResponse.GetNmomBins()];
1788     Float_t *estimatedT0resolution = new Float_t[fTOFResponse.GetNmomBins()];
1789     for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){
1790       estimatedT0event[i]=0.0;
1791       estimatedT0resolution[i]=0.0;
1792       startTimeMask[i] = 0;
1793     }
1794
1795     Float_t resT0A=fResT0A;
1796     Float_t resT0C=fResT0C;
1797     Float_t resT0AC=fResT0AC;
1798     if(vevent->GetT0TOF()){ // check if T0 detector information is available
1799         flagT0T0=kTRUE;
1800     }
1801
1802
1803     AliTOFHeader *tofHeader = (AliTOFHeader*)vevent->GetTOFHeader();
1804
1805     if (tofHeader) { // read global info and T0-TOF
1806       fTOFResponse.SetTimeResolution(tofHeader->GetTOFResolution());
1807       t0spread = tofHeader->GetT0spread(); // read t0 sprad
1808       if(t0spread < 10) t0spread = 80;
1809
1810       flagT0TOF=kTRUE;
1811       for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){ // read T0-TOF default value
1812         startTime[i]=tofHeader->GetDefaultEventTimeVal();
1813         startTimeRes[i]=tofHeader->GetDefaultEventTimeRes();
1814         if(startTimeRes[i] < 1.e-5) startTimeRes[i] = t0spread;
1815
1816         if(startTimeRes[i] > t0spread - 10 && TMath::Abs(startTime[i]) < 0.001) startTime[i] = -starttimeoffset; // apply offset for T0-fill
1817       }
1818
1819       TArrayI *ibin=(TArrayI*)tofHeader->GetNvalues();
1820       TArrayF *t0Bin=(TArrayF*)tofHeader->GetEventTimeValues();
1821       TArrayF *t0ResBin=(TArrayF*)tofHeader->GetEventTimeRes();
1822       for(Int_t j=0;j < tofHeader->GetNbins();j++){ // fill T0-TOF in p-bins
1823         Int_t icurrent = (Int_t)ibin->GetAt(j);
1824         startTime[icurrent]=t0Bin->GetAt(j);
1825         startTimeRes[icurrent]=t0ResBin->GetAt(j);
1826         if(startTimeRes[icurrent] < 1.e-5) startTimeRes[icurrent] = t0spread;
1827         if(startTimeRes[icurrent] > t0spread - 10 && TMath::Abs(startTime[icurrent]) < 0.001) startTime[icurrent] = -starttimeoffset; // apply offset for T0-fill
1828       }
1829     }
1830
1831     // for cut of 3 sigma on t0 spread
1832     Float_t t0cut = 3 * t0spread;
1833     if(t0cut < 500) t0cut = 500;
1834
1835     if(option == kFILL_T0){ // T0-FILL is used
1836         for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){
1837           estimatedT0event[i]=0.0-starttimeoffset;
1838           estimatedT0resolution[i]=t0spread;
1839         }
1840         fTOFResponse.SetT0event(estimatedT0event);
1841         fTOFResponse.SetT0resolution(estimatedT0resolution);
1842     }
1843
1844     if(option == kTOF_T0){ // T0-TOF is used when available (T0-FILL otherwise) from ESD
1845         if(flagT0TOF){
1846             fTOFResponse.SetT0event(startTime);
1847             fTOFResponse.SetT0resolution(startTimeRes);
1848             for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){
1849               if(startTimeRes[i]<t0spread) startTimeMask[i]=1;
1850               fTOFResponse.SetT0binMask(i,startTimeMask[i]);
1851             }
1852         }
1853         else{
1854             for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){
1855               estimatedT0event[i]=0.0-starttimeoffset;
1856               estimatedT0resolution[i]=t0spread;
1857               fTOFResponse.SetT0binMask(i,startTimeMask[i]);
1858             }
1859             fTOFResponse.SetT0event(estimatedT0event);
1860             fTOFResponse.SetT0resolution(estimatedT0resolution);
1861         }
1862     }
1863     else if(option == kBest_T0){ // T0-T0 or T0-TOF are used when available (T0-FILL otherwise) from ESD
1864         Float_t t0AC=-10000;
1865         Float_t t0A=-10000;
1866         Float_t t0C=-10000;
1867         if(flagT0T0){
1868             t0A= vevent->GetT0TOF()[1] - starttimeoffset;
1869             t0C= vevent->GetT0TOF()[2] - starttimeoffset;
1870         //      t0AC= vevent->GetT0TOF()[0];
1871             t0AC= t0A/resT0A/resT0A + t0C/resT0C/resT0C;
1872             resT0AC= TMath::Sqrt(1./resT0A/resT0A + 1./resT0C/resT0C);
1873             t0AC /= resT0AC*resT0AC;
1874         }
1875
1876         Float_t t0t0Best = 0;
1877         Float_t t0t0BestRes = 9999;
1878         Int_t t0used=0;
1879         if(TMath::Abs(t0A) < t0cut && TMath::Abs(t0C) < t0cut && TMath::Abs(t0C-t0A) < 500){
1880             t0t0Best = t0AC;
1881             t0t0BestRes = resT0AC;
1882             t0used=6;
1883         }
1884         else if(TMath::Abs(t0C) < t0cut){
1885             t0t0Best = t0C;
1886             t0t0BestRes = resT0C;
1887             t0used=4;
1888         }
1889         else if(TMath::Abs(t0A) < t0cut){
1890             t0t0Best = t0A;
1891             t0t0BestRes = resT0A;
1892             t0used=2;
1893         }
1894
1895         if(flagT0TOF){ // if T0-TOF info is available
1896             for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){
1897                 if(t0t0BestRes < 999){
1898                   if(startTimeRes[i] < t0spread){
1899                     Double_t wtot = 1./startTimeRes[i]/startTimeRes[i] + 1./t0t0BestRes/t0t0BestRes;
1900                     Double_t t0best = startTime[i]/startTimeRes[i]/startTimeRes[i] + t0t0Best/t0t0BestRes/t0t0BestRes;
1901                     estimatedT0event[i]=t0best / wtot;
1902                     estimatedT0resolution[i]=1./TMath::Sqrt(wtot);
1903                     startTimeMask[i] = t0used+1;
1904                   }
1905                   else {
1906                     estimatedT0event[i]=t0t0Best;
1907                     estimatedT0resolution[i]=t0t0BestRes;
1908                     startTimeMask[i] = t0used;
1909                   }
1910                 }
1911                 else{
1912                   estimatedT0event[i]=startTime[i];
1913                   estimatedT0resolution[i]=startTimeRes[i];
1914                   if(startTimeRes[i]<t0spread) startTimeMask[i]=1;
1915                 }
1916                 fTOFResponse.SetT0binMask(i,startTimeMask[i]);
1917             }
1918             fTOFResponse.SetT0event(estimatedT0event);
1919             fTOFResponse.SetT0resolution(estimatedT0resolution);
1920         }
1921         else{ // if no T0-TOF info is available
1922             for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){
1923               fTOFResponse.SetT0binMask(i,t0used);
1924               if(t0t0BestRes < 999){
1925                 estimatedT0event[i]=t0t0Best;
1926                 estimatedT0resolution[i]=t0t0BestRes;
1927               }
1928               else{
1929                 estimatedT0event[i]=0.0-starttimeoffset;
1930                 estimatedT0resolution[i]=t0spread;
1931               }
1932             }
1933             fTOFResponse.SetT0event(estimatedT0event);
1934             fTOFResponse.SetT0resolution(estimatedT0resolution);
1935         }
1936     }
1937
1938     else if(option == kT0_T0){ // T0-T0 is used when available (T0-FILL otherwise)
1939         Float_t t0AC=-10000;
1940         Float_t t0A=-10000;
1941         Float_t t0C=-10000;
1942         if(flagT0T0){
1943             t0A= vevent->GetT0TOF()[1] - starttimeoffset;
1944             t0C= vevent->GetT0TOF()[2] - starttimeoffset;
1945         //      t0AC= vevent->GetT0TOF()[0];
1946             t0AC= t0A/resT0A/resT0A + t0C/resT0C/resT0C;
1947             resT0AC= TMath::Sqrt(1./resT0A/resT0A + 1./resT0C/resT0C);
1948             t0AC /= resT0AC*resT0AC;
1949         }
1950
1951         if(TMath::Abs(t0A) < t0cut && TMath::Abs(t0C) < t0cut && TMath::Abs(t0C-t0A) < 500){
1952             for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){
1953               estimatedT0event[i]=t0AC;
1954               estimatedT0resolution[i]=resT0AC;
1955               fTOFResponse.SetT0binMask(i,6);
1956             }
1957         }
1958         else if(TMath::Abs(t0C) < t0cut){
1959             for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){
1960               estimatedT0event[i]=t0C;
1961               estimatedT0resolution[i]=resT0C;
1962               fTOFResponse.SetT0binMask(i,4);
1963             }
1964         }
1965         else if(TMath::Abs(t0A) < t0cut){
1966             for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){
1967               estimatedT0event[i]=t0A;
1968               estimatedT0resolution[i]=resT0A;
1969               fTOFResponse.SetT0binMask(i,2);
1970             }
1971         }
1972         else{
1973             for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){
1974               estimatedT0event[i]= 0.0 - starttimeoffset;
1975               estimatedT0resolution[i]=t0spread;
1976               fTOFResponse.SetT0binMask(i,0);
1977             }
1978         }
1979         fTOFResponse.SetT0event(estimatedT0event);
1980         fTOFResponse.SetT0resolution(estimatedT0resolution);
1981     }
1982
1983     delete [] startTime;
1984     delete [] startTimeRes;
1985     delete [] startTimeMask;
1986     delete [] estimatedT0event;
1987     delete [] estimatedT0resolution;
1988 }
1989
1990 //______________________________________________________________________________
1991 // private non cached versions of the PID calculation
1992 //
1993
1994
1995 //______________________________________________________________________________
1996 Float_t AliPIDResponse::GetNumberOfSigmas(EDetector detector, const AliVParticle *vtrack, AliPID::EParticleType type) const
1997 {
1998   //
1999   // NumberOfSigmas for 'detCode'
2000   //
2001
2002   const AliVTrack *track=static_cast<const AliVTrack*>(vtrack);
2003   
2004   switch (detector){
2005     case kITS:   return GetNumberOfSigmasITS(track, type);   break;
2006     case kTPC:   return GetNumberOfSigmasTPC(track, type);   break;
2007     case kTOF:   return GetNumberOfSigmasTOF(track, type);   break;
2008     case kHMPID: return GetNumberOfSigmasHMPID(track, type); break;
2009     case kEMCAL: return GetNumberOfSigmasEMCAL(track, type); break;
2010     default: return -999.;
2011   }
2012
2013   return -999.;
2014 }
2015
2016 //______________________________________________________________________________
2017 Float_t AliPIDResponse::GetNumberOfSigmasITS(const AliVParticle *vtrack, AliPID::EParticleType type) const
2018 {
2019   //
2020   // Calculate the number of sigmas in the ITS
2021   //
2022   
2023   AliVTrack *track=(AliVTrack*)vtrack;
2024
2025   const EDetPidStatus pidStatus=GetITSPIDStatus(track);
2026   if (pidStatus!=kDetPidOk) return -999.;
2027
2028   return fITSResponse.GetNumberOfSigmas(track,type);
2029 }
2030
2031 //______________________________________________________________________________
2032 Float_t AliPIDResponse::GetNumberOfSigmasTPC(const AliVParticle *vtrack, AliPID::EParticleType type) const
2033 {
2034   //
2035   // Calculate the number of sigmas in the TPC
2036   //
2037   
2038   AliVTrack *track=(AliVTrack*)vtrack;
2039
2040   const EDetPidStatus pidStatus=GetTPCPIDStatus(track);
2041   if (pidStatus!=kDetPidOk) return -999.;
2042
2043   // the following call is needed in order to fill the transient data member
2044   // fTPCsignalTuned which is used in the TPCPIDResponse to judge
2045   // if using tuned on data
2046   if (fTuneMConData && ((fTuneMConDataMask & kDetTPC) == kDetTPC))
2047     this->GetTPCsignalTunedOnData(track);
2048   
2049   return fTPCResponse.GetNumberOfSigmas(track, type, AliTPCPIDResponse::kdEdxDefault, fUseTPCEtaCorrection, fUseTPCMultiplicityCorrection);
2050 }
2051
2052 //______________________________________________________________________________
2053 Float_t AliPIDResponse::GetNumberOfSigmasTOF(const AliVParticle *vtrack, AliPID::EParticleType type) const
2054 {
2055   //
2056   // Calculate the number of sigmas in the TOF
2057   //
2058   
2059   AliVTrack *track=(AliVTrack*)vtrack;
2060
2061   const EDetPidStatus pidStatus=GetTOFPIDStatus(track);
2062   if (pidStatus!=kDetPidOk) return -999.;
2063   
2064   return GetNumberOfSigmasTOFold(vtrack, type);
2065 }
2066 //______________________________________________________________________________
2067
2068 Float_t AliPIDResponse::GetNumberOfSigmasHMPID(const AliVParticle *vtrack, AliPID::EParticleType type) const
2069 {
2070   //
2071   // Calculate the number of sigmas in the HMPID
2072   //  
2073   AliVTrack *track=(AliVTrack*)vtrack;
2074     
2075   const EDetPidStatus pidStatus=GetHMPIDPIDStatus(track);
2076   if (pidStatus!=kDetPidOk) return -999.; 
2077   
2078   return fHMPIDResponse.GetNumberOfSigmas(track, type);
2079 }
2080
2081 //______________________________________________________________________________
2082 Float_t AliPIDResponse::GetNumberOfSigmasEMCAL(const AliVParticle *vtrack, AliPID::EParticleType type) const
2083 {
2084   //
2085   // Calculate the number of sigmas in the EMCAL
2086   //
2087   
2088   AliVTrack *track=(AliVTrack*)vtrack;
2089
2090   const EDetPidStatus pidStatus=GetEMCALPIDStatus(track);
2091   if (pidStatus!=kDetPidOk) return -999.;
2092
2093   const Int_t nMatchClus = track->GetEMCALcluster();
2094   AliVCluster *matchedClus = (AliVCluster*)fCurrentEvent->GetCaloCluster(nMatchClus);
2095   
2096   const Double_t mom    = track->P();
2097   const Double_t pt     = track->Pt();
2098   const Int_t    charge = track->Charge();
2099   const Double_t fClsE  = matchedClus->E();
2100   const Double_t EovP   = fClsE/mom;
2101   
2102   return fEMCALResponse.GetNumberOfSigmas(pt,EovP,type,charge);
2103 }
2104
2105 //______________________________________________________________________________
2106 AliPIDResponse::EDetPidStatus AliPIDResponse::GetSignalDeltaITS(const AliVParticle *vtrack, AliPID::EParticleType type, Double_t &val, Bool_t ratio/*=kFALSE*/) const
2107 {
2108   //
2109   // Signal minus expected Signal for ITS
2110   //
2111   AliVTrack *track=(AliVTrack*)vtrack;
2112   val=fITSResponse.GetSignalDelta(track,type,ratio);
2113   
2114   return GetITSPIDStatus(track);
2115 }
2116
2117 //______________________________________________________________________________
2118 AliPIDResponse::EDetPidStatus AliPIDResponse::GetSignalDeltaTPC(const AliVParticle *vtrack, AliPID::EParticleType type, Double_t &val, Bool_t ratio/*=kFALSE*/) const
2119 {
2120   //
2121   // Signal minus expected Signal for TPC
2122   //
2123   AliVTrack *track=(AliVTrack*)vtrack;
2124   
2125   // the following call is needed in order to fill the transient data member
2126   // fTPCsignalTuned which is used in the TPCPIDResponse to judge
2127   // if using tuned on data
2128   if (fTuneMConData && ((fTuneMConDataMask & kDetTPC) == kDetTPC))
2129     this->GetTPCsignalTunedOnData(track);
2130   
2131   val=fTPCResponse.GetSignalDelta(track, type, AliTPCPIDResponse::kdEdxDefault, fUseTPCEtaCorrection, fUseTPCMultiplicityCorrection, ratio);
2132   
2133   return GetTPCPIDStatus(track);
2134 }
2135
2136 //______________________________________________________________________________
2137 AliPIDResponse::EDetPidStatus AliPIDResponse::GetSignalDeltaTOF(const AliVParticle *vtrack, AliPID::EParticleType type, Double_t &val, Bool_t ratio/*=kFALSE*/) const
2138 {
2139   //
2140   // Signal minus expected Signal for TOF
2141   //
2142   AliVTrack *track=(AliVTrack*)vtrack;
2143   val=GetSignalDeltaTOFold(track, type, ratio);
2144   
2145   return GetTOFPIDStatus(track);
2146 }
2147
2148 //______________________________________________________________________________
2149 AliPIDResponse::EDetPidStatus AliPIDResponse::GetSignalDeltaHMPID(const AliVParticle *vtrack, AliPID::EParticleType type, Double_t &val, Bool_t ratio/*=kFALSE*/) const
2150 {
2151   //
2152   // Signal minus expected Signal for HMPID
2153   //
2154   AliVTrack *track=(AliVTrack*)vtrack;
2155   val=fHMPIDResponse.GetSignalDelta(track, type, ratio);
2156   
2157   return GetHMPIDPIDStatus(track);
2158 }
2159
2160 //______________________________________________________________________________
2161 AliPIDResponse::EDetPidStatus AliPIDResponse::GetComputePIDProbability  (EDetector detCode,  const AliVTrack *track, Int_t nSpecies, Double_t p[]) const
2162 {
2163   //
2164   // Compute PID response of 'detCode'
2165   //
2166
2167   switch (detCode){
2168     case kITS: return GetComputeITSProbability(track, nSpecies, p); break;
2169     case kTPC: return GetComputeTPCProbability(track, nSpecies, p); break;
2170     case kTRD: return GetComputeTRDProbability(track, nSpecies, p); break;
2171     case kTOF: return GetComputeTOFProbability(track, nSpecies, p); break;
2172     case kPHOS: return GetComputePHOSProbability(track, nSpecies, p); break;
2173     case kEMCAL: return GetComputeEMCALProbability(track, nSpecies, p); break;
2174     case kHMPID: return GetComputeHMPIDProbability(track, nSpecies, p); break;
2175     default: return kDetNoSignal;
2176   }
2177 }
2178
2179 //______________________________________________________________________________
2180 AliPIDResponse::EDetPidStatus AliPIDResponse::GetComputeITSProbability  (const AliVTrack *track, Int_t nSpecies, Double_t p[]) const
2181 {
2182   //
2183   // Compute PID response for the ITS
2184   //
2185   
2186   // set flat distribution (no decision)
2187   for (Int_t j=0; j<nSpecies; j++) p[j]=1./nSpecies;
2188   
2189   const EDetPidStatus pidStatus=GetITSPIDStatus(track);
2190   if (pidStatus!=kDetPidOk) return pidStatus;
2191   
2192   if (track->GetDetectorPID()){
2193     return track->GetDetectorPID()->GetRawProbability(kITS, p, nSpecies);
2194   }
2195   
2196   //check for ITS standalone tracks
2197   Bool_t isSA=kTRUE;
2198   if( track->GetStatus() & AliVTrack::kTPCin ) isSA=kFALSE;
2199
2200   Double_t mom=track->P();
2201   Double_t dedx=track->GetITSsignal();
2202   Double_t momITS=mom;
2203   UChar_t clumap=track->GetITSClusterMap();
2204   Int_t nPointsForPid=0;
2205   for(Int_t i=2; i<6; i++){
2206     if(clumap&(1<<i)) ++nPointsForPid;
2207   }
2208
2209   Bool_t mismatch=kTRUE/*, heavy=kTRUE*/;
2210   for (Int_t j=0; j<nSpecies; j++) {
2211     Double_t mass=AliPID::ParticleMassZ(j);//GeV/c^2
2212     const Double_t chargeFactor = TMath::Power(AliPID::ParticleCharge(j),2.);
2213     Double_t bethe=fITSResponse.Bethe(momITS,mass)*chargeFactor;
2214     //TODO: in case of the electron, use the SA parametrisation,
2215     //      this needs to be changed if ITS provides a parametrisation
2216     //      for electrons also for ITS+TPC tracks
2217     Double_t sigma=fITSResponse.GetResolution(bethe,nPointsForPid,isSA || (j==(Int_t)AliPID::kElectron));
2218     if (TMath::Abs(dedx-bethe) > fRange*sigma) {
2219       p[j]=TMath::Exp(-0.5*fRange*fRange)/sigma;
2220     } else {
2221       p[j]=TMath::Exp(-0.5*(dedx-bethe)*(dedx-bethe)/(sigma*sigma))/sigma;
2222       mismatch=kFALSE;
2223     }
2224   }
2225
2226   if (mismatch){
2227     for (Int_t j=0; j<nSpecies; j++) p[j]=1./nSpecies;
2228   }
2229
2230   return kDetPidOk;
2231 }
2232 //______________________________________________________________________________
2233 AliPIDResponse::EDetPidStatus AliPIDResponse::GetComputeTPCProbability  (const AliVTrack *track, Int_t nSpecies, Double_t p[]) const
2234 {
2235   //
2236   // Compute PID response for the TPC
2237   //
2238   
2239   // set flat distribution (no decision)
2240   for (Int_t j=0; j<nSpecies; j++) p[j]=1./nSpecies;
2241   
2242   const EDetPidStatus pidStatus=GetTPCPIDStatus(track);
2243   if (pidStatus!=kDetPidOk) return pidStatus;
2244   
2245   Double_t dedx=track->GetTPCsignal();
2246   Bool_t mismatch=kTRUE/*, heavy=kTRUE*/;
2247   
2248   if (fTuneMConData && ((fTuneMConDataMask & kDetTPC) == kDetTPC)) dedx = this->GetTPCsignalTunedOnData(track);
2249   
2250   Double_t bethe = 0.;
2251   Double_t sigma = 0.;
2252   
2253   for (Int_t j=0; j<nSpecies; j++) {
2254     AliPID::EParticleType type=AliPID::EParticleType(j);
2255     
2256     bethe=fTPCResponse.GetExpectedSignal(track, type, AliTPCPIDResponse::kdEdxDefault, fUseTPCEtaCorrection, fUseTPCMultiplicityCorrection);
2257     sigma=fTPCResponse.GetExpectedSigma(track, type, AliTPCPIDResponse::kdEdxDefault, fUseTPCEtaCorrection, fUseTPCMultiplicityCorrection);
2258     
2259     if (TMath::Abs(dedx-bethe) > fRange*sigma) {
2260       p[j]=TMath::Exp(-0.5*fRange*fRange)/sigma;
2261     } else {
2262       p[j]=TMath::Exp(-0.5*(dedx-bethe)*(dedx-bethe)/(sigma*sigma))/sigma;
2263       mismatch=kFALSE;
2264     }
2265   }
2266   
2267   if (mismatch){
2268     for (Int_t j=0; j<nSpecies; j++) p[j]=1./nSpecies;
2269   }
2270   
2271   return kDetPidOk;
2272 }
2273 //______________________________________________________________________________
2274 AliPIDResponse::EDetPidStatus AliPIDResponse::GetComputeTOFProbability  (const AliVTrack *track, Int_t nSpecies, Double_t p[]) const
2275 {
2276   //
2277   // Compute PID probabilities for TOF
2278   //
2279
2280   Double_t mismprob = 1E-8;
2281   //fTOFResponse.GetMismatchProbability(track->GetTOFsignal(),track->Eta()) * 0.01; // for future implementation of mismatch (i.e. 1% mismatch that should be extended for PbPb, pPb)
2282
2283   // set flat distribution (no decision)
2284   for (Int_t j=0; j<nSpecies; j++) p[j]=1./nSpecies;
2285   
2286   const EDetPidStatus pidStatus=GetTOFPIDStatus(track);
2287   if (pidStatus!=kDetPidOk) return pidStatus;
2288
2289   const Double_t meanCorrFactor = 0.07/fTOFtail; // Correction factor on the mean because of the tail (should be ~ 0.1 with tail = 1.1)
2290   
2291   for (Int_t j=0; j<nSpecies; j++) {
2292     AliPID::EParticleType type=AliPID::EParticleType(j);
2293     const Double_t nsigmas=GetNumberOfSigmasTOFold(track,type) + meanCorrFactor;
2294     
2295     const Double_t expTime = fTOFResponse.GetExpectedSignal(track,type);
2296     const Double_t sig     = fTOFResponse.GetExpectedSigma(track->P(),expTime,AliPID::ParticleMassZ(type));
2297
2298     if(nsigmas < fTOFtail)
2299       p[j] = TMath::Exp(-0.5*nsigmas*nsigmas)/sig;
2300     else
2301       p[j] = TMath::Exp(-(nsigmas - fTOFtail*0.5)*fTOFtail)/sig;
2302     
2303     p[j] += mismprob;
2304   }
2305   
2306   return kDetPidOk;
2307 }
2308 //______________________________________________________________________________
2309 AliPIDResponse::EDetPidStatus AliPIDResponse::GetComputeTRDProbability  (const AliVTrack *track, Int_t nSpecies, Double_t p[],AliTRDPIDResponse::ETRDPIDMethod PIDmethod/*=AliTRDPIDResponse::kLQ1D*/) const
2310 {
2311   //
2312   // Compute PID probabilities for the TRD
2313   //
2314   
2315   // set flat distribution (no decision)
2316   for (Int_t j=0; j<nSpecies; j++) p[j]=1./nSpecies;
2317   
2318   const EDetPidStatus pidStatus=GetTRDPIDStatus(track);
2319   if (pidStatus!=kDetPidOk) return pidStatus;
2320
2321   UInt_t TRDslicesForPID[2];
2322   SetTRDSlices(TRDslicesForPID,PIDmethod);
2323   
2324   Float_t mom[6]={0.};
2325   Double_t dedx[48]={0.};  // Allocate space for the maximum number of TRD slices
2326   Int_t nslices = TRDslicesForPID[1] - TRDslicesForPID[0] + 1;
2327   AliDebug(1, Form("First Slice: %d, Last Slice: %d, Number of slices: %d",  TRDslicesForPID[0], TRDslicesForPID[1], nslices));
2328   for(UInt_t ilayer = 0; ilayer < 6; ilayer++){
2329     mom[ilayer] = track->GetTRDmomentum(ilayer);
2330     for(UInt_t islice = TRDslicesForPID[0]; islice <= TRDslicesForPID[1]; islice++){
2331       dedx[ilayer*nslices+islice-TRDslicesForPID[0]] = track->GetTRDslice(ilayer, islice);
2332     }
2333   }
2334   
2335   fTRDResponse.GetResponse(nslices, dedx, mom, p,PIDmethod);
2336   return kDetPidOk;
2337 }
2338
2339 //______________________________________________________________________________
2340 AliPIDResponse::EDetPidStatus AliPIDResponse::GetComputeEMCALProbability  (const AliVTrack *track, Int_t nSpecies, Double_t p[]) const
2341 {
2342   //
2343   // Compute PID response for the EMCAL
2344   //
2345   
2346   for (Int_t j=0; j<nSpecies; j++) p[j]=1./nSpecies;
2347
2348   const EDetPidStatus pidStatus=GetEMCALPIDStatus(track);
2349   if (pidStatus!=kDetPidOk) return pidStatus;
2350
2351   const Int_t nMatchClus = track->GetEMCALcluster();
2352   AliVCluster *matchedClus = (AliVCluster*)fCurrentEvent->GetCaloCluster(nMatchClus);
2353   
2354   const Double_t mom    = track->P();
2355   const Double_t pt     = track->Pt();
2356   const Int_t    charge = track->Charge();
2357   const Double_t fClsE  = matchedClus->E();
2358   const Double_t EovP   = fClsE/mom;
2359   
2360   // compute the probabilities
2361   fEMCALResponse.ComputeEMCALProbability(nSpecies,pt,EovP,charge,p);
2362   return kDetPidOk;
2363 }
2364
2365 //______________________________________________________________________________
2366 AliPIDResponse::EDetPidStatus AliPIDResponse::GetComputePHOSProbability (const AliVTrack */*track*/, Int_t nSpecies, Double_t p[]) const
2367 {
2368   //
2369   // Compute PID response for the PHOS
2370   //
2371   
2372   // set flat distribution (no decision)
2373   for (Int_t j=0; j<nSpecies; j++) p[j]=1./nSpecies;
2374   return kDetNoSignal;
2375 }
2376
2377 //______________________________________________________________________________
2378 AliPIDResponse::EDetPidStatus AliPIDResponse::GetComputeHMPIDProbability(const AliVTrack *track, Int_t nSpecies, Double_t p[]) const
2379 {
2380   //
2381   // Compute PID response for the HMPID
2382   //
2383   
2384   // set flat distribution (no decision)
2385   for (Int_t j=0; j<nSpecies; j++) p[j]=1./nSpecies;
2386   
2387   const EDetPidStatus pidStatus=GetHMPIDPIDStatus(track);
2388   if (pidStatus!=kDetPidOk) return pidStatus;
2389   
2390   fHMPIDResponse.GetProbability(track,nSpecies,p);
2391     
2392   return kDetPidOk;
2393 }
2394
2395 //______________________________________________________________________________
2396 AliPIDResponse::EDetPidStatus AliPIDResponse::GetITSPIDStatus(const AliVTrack *track) const
2397 {
2398   // compute ITS pid status
2399
2400   // check status bits
2401   if ((track->GetStatus()&AliVTrack::kITSin)==0 &&
2402     (track->GetStatus()&AliVTrack::kITSout)==0) return kDetNoSignal;
2403
2404   const Float_t dEdx=track->GetITSsignal();
2405   if (dEdx<=0) return kDetNoSignal;
2406   
2407   // requite at least 3 pid clusters
2408   const UChar_t clumap=track->GetITSClusterMap();
2409   Int_t nPointsForPid=0;
2410   for(Int_t i=2; i<6; i++){
2411     if(clumap&(1<<i)) ++nPointsForPid;
2412   }
2413   
2414   if(nPointsForPid<3) { 
2415     return kDetNoSignal;
2416   }
2417   
2418   return kDetPidOk;
2419 }
2420
2421 //______________________________________________________________________________
2422 AliPIDResponse::EDetPidStatus AliPIDResponse:: GetTPCPIDStatus(const AliVTrack *track) const
2423 {
2424   // compute TPC pid status
2425   
2426   // check quality of the track
2427   if ( (track->GetStatus()&AliVTrack::kTPCin )==0 && (track->GetStatus()&AliVTrack::kTPCout)==0 ) return kDetNoSignal;
2428
2429   // check pid values
2430   const Double_t dedx=track->GetTPCsignal();
2431   const UShort_t signalN=track->GetTPCsignalN();
2432   if (signalN<10 || dedx<10) return kDetNoSignal;
2433
2434   if (!(fArrPidResponseMaster && fArrPidResponseMaster->At(AliPID::kPion))) return kDetNoParams;
2435   
2436   return kDetPidOk;
2437 }
2438
2439 //______________________________________________________________________________
2440 AliPIDResponse::EDetPidStatus AliPIDResponse::GetTRDPIDStatus(const AliVTrack *track) const
2441 {
2442   // compute TRD pid status
2443
2444   if((track->GetStatus()&AliVTrack::kTRDout)==0) return kDetNoSignal;
2445   return kDetPidOk;
2446 }
2447
2448 //______________________________________________________________________________
2449 AliPIDResponse::EDetPidStatus AliPIDResponse::GetTOFPIDStatus(const AliVTrack *track) const
2450 {
2451   // compute TOF pid status
2452
2453   if ((track->GetStatus()&AliVTrack::kTOFout)==0) return kDetNoSignal;
2454   if ((track->GetStatus()&AliVTrack::kTIME)==0) return kDetNoSignal;
2455
2456   return kDetPidOk;
2457 }
2458
2459 //______________________________________________________________________________
2460 Float_t AliPIDResponse::GetTOFMismatchProbability(const AliVTrack *track) const
2461 {
2462   // compute mismatch probability cross-checking at 5 sigmas with TPC
2463   // currently just implemented as a 5 sigma compatibility cut
2464
2465   // check pid status
2466   const EDetPidStatus tofStatus=GetTOFPIDStatus(track);
2467   if (tofStatus!=kDetPidOk) return 0.;
2468
2469   //mismatch
2470   const EDetPidStatus tpcStatus=GetTPCPIDStatus(track);
2471   if (tpcStatus!=kDetPidOk) return 0.;
2472   
2473   const Double_t meanCorrFactor = 0.11/fTOFtail; // Correction factor on the mean because of the tail (should be ~ 0.1 with tail = 1.1)
2474   Bool_t mismatch = kTRUE/*, heavy = kTRUE*/;
2475   for (Int_t j=0; j<AliPID::kSPECIESC; j++) {
2476     AliPID::EParticleType type=AliPID::EParticleType(j);
2477     const Double_t nsigmas=GetNumberOfSigmasTOFold(track,type) + meanCorrFactor;
2478     
2479     if (TMath::Abs(nsigmas)<5.){
2480       const Double_t nsigmasTPC=GetNumberOfSigmasTPC(track,type);
2481       if (TMath::Abs(nsigmasTPC)<5.) mismatch=kFALSE;
2482     }
2483   }
2484   
2485   if (mismatch){
2486     return 1.;
2487   }
2488   
2489   return 0.;
2490 }
2491
2492 //______________________________________________________________________________
2493 AliPIDResponse::EDetPidStatus AliPIDResponse:: GetHMPIDPIDStatus(const AliVTrack *track) const
2494 {
2495   // compute HMPID pid status
2496   
2497   Int_t ch = track->GetHMPIDcluIdx()/1000000;
2498   Double_t HMPIDsignal = track->GetHMPIDsignal(); 
2499   
2500   if((track->GetStatus()&AliVTrack::kHMPIDpid)==0 || ch<0 || ch>6 || HMPIDsignal<0) return kDetNoSignal;
2501   
2502   return kDetPidOk;
2503 }
2504
2505 //______________________________________________________________________________
2506 AliPIDResponse::EDetPidStatus AliPIDResponse:: GetPHOSPIDStatus(const AliVTrack */*track*/) const
2507 {
2508   // compute PHOS pid status
2509   return kDetNoSignal;  
2510 }
2511
2512 //______________________________________________________________________________
2513 AliPIDResponse::EDetPidStatus AliPIDResponse:: GetEMCALPIDStatus(const AliVTrack *track) const
2514 {
2515   // compute EMCAL pid status
2516
2517
2518   // Track matching
2519   const Int_t nMatchClus = track->GetEMCALcluster();
2520   if (nMatchClus<0) return kDetNoSignal;
2521
2522   AliVCluster *matchedClus = (AliVCluster*)fCurrentEvent->GetCaloCluster(nMatchClus);
2523
2524   if (!(matchedClus && matchedClus->IsEMCAL())) return kDetNoSignal;
2525
2526   const Int_t charge = track->Charge();
2527   if (TMath::Abs(charge)!=1) return kDetNoSignal;
2528
2529   if (!(fEMCALPIDParams && fEMCALPIDParams->At(AliPID::kElectron))) return kDetNoParams;
2530   
2531   return kDetPidOk;
2532
2533 }
2534
2535 //______________________________________________________________________________
2536 AliPIDResponse::EDetPidStatus AliPIDResponse::GetPIDStatus(EDetector detector, const AliVTrack *track) const
2537 {
2538   //
2539   // check pid status for a track
2540   //
2541
2542   switch (detector){
2543     case kITS:   return GetITSPIDStatus(track);   break;
2544     case kTPC:   return GetTPCPIDStatus(track);   break;
2545     case kTRD:   return GetTRDPIDStatus(track);   break;
2546     case kTOF:   return GetTOFPIDStatus(track);   break;
2547     case kPHOS:  return GetPHOSPIDStatus(track);  break;
2548     case kEMCAL: return GetEMCALPIDStatus(track); break;
2549     case kHMPID: return GetHMPIDPIDStatus(track); break;
2550     default: return kDetNoSignal;
2551   }
2552   return kDetNoSignal;
2553   
2554 }
2555
2556 //______________________________________________________________________________
2557 TString AliPIDResponse::GetChecksum(const TObject* obj) const
2558 {
2559   // Return the checksum for an object obj (tested to work properly at least for histograms and TSplines).
2560   
2561   TString fileName = Form("tempChecksum.C"); // File name must be fixed for data type "TSpline3", since the file name will end up in the file content!
2562   
2563   // For parallel processing, a unique file pathname is required. Uniqueness can be guaranteed by using a unique directory name
2564   UInt_t index = 0;
2565   TString uniquePathName = Form("tempChecksum_%u", index);
2566   
2567   // To get a unique path name, increase the index until no directory
2568   // of such a name exists.
2569   // NOTE: gSystem->AccessPathName(...) returns kTRUE, if the access FAILED!
2570   while (!gSystem->AccessPathName(uniquePathName.Data()))
2571     uniquePathName = Form("tempChecksum_%u", ++index);
2572   
2573   if (gSystem->mkdir(uniquePathName.Data()) < 0) {
2574     AliError("Could not create temporary directory to store temp file for checksum determination!");
2575     return "ERROR";
2576   }
2577   
2578   TString option = "";
2579   
2580   // Save object as a macro, which will be deleted immediately after the checksum has been computed
2581   // (does not work for desired data types if saved as *.root for some reason) - one only wants to compare the content, not
2582   // the modification time etc. ...
2583   if (dynamic_cast<const TH1*>(obj))
2584     option = "colz"; // Histos need this option, since w/o this option, a counter is added to the filename
2585   
2586   
2587   // SaveAs must be called with the fixed fileName only, since the first argument goes into the file content
2588   // for some object types. Thus, change the directory, save the file and then go back
2589   TString oldDir = gSystem->pwd();
2590   gSystem->cd(uniquePathName.Data());
2591   obj->SaveAs(fileName.Data(), option.Data());
2592   gSystem->cd(oldDir.Data());
2593   
2594   // Use the file to calculate the MD5 checksum
2595   TMD5* md5 = TMD5::FileChecksum(Form("%s/%s", uniquePathName.Data(), fileName.Data()));
2596   TString checksum = md5->AsString();
2597   
2598   // Clean up
2599   delete md5;
2600   gSystem->Exec(Form("rm -rf %s", uniquePathName.Data()));
2601   
2602   return checksum;
2603 }