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