]> git.uio.no Git - u/mrichter/AliRoot.git/blob - STEER/STEERBase/AliPIDResponse.cxx
- fast TRD PID implementation with muon constraints (Daniel Lohner)
[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     // old function for compatibility
1648     Int_t ntracklets=0;
1649     return IdentifiedAsElectronTRD(vtrack,ntracklets,efficiencyLevel,centrality,PIDmethod);
1650 }
1651
1652 //______________________________________________________________________________
1653 Bool_t AliPIDResponse::IdentifiedAsElectronTRD(const AliVTrack *vtrack, Int_t &ntracklets,Double_t efficiencyLevel,Double_t centrality,AliTRDPIDResponse::ETRDPIDMethod PIDmethod) const {
1654   //
1655   // Check whether track is identified as electron under a given electron efficiency hypothesis
1656     //
1657     // ntracklets is the number of tracklets that has been used to calculate the PID signal
1658
1659   Double_t probs[AliPID::kSPECIES];
1660
1661   ntracklets =CalculateTRDResponse(vtrack,probs,PIDmethod);
1662
1663   // Take mean of the TRD momenta in the given tracklets
1664   Float_t p = 0, trdmomenta[AliVTrack::kTRDnPlanes];
1665   Int_t nmomenta = 0;
1666   for(Int_t iPl=0;iPl<AliVTrack::kTRDnPlanes;iPl++){
1667     if(vtrack->GetTRDmomentum(iPl) > 0.){
1668       trdmomenta[nmomenta++] = vtrack->GetTRDmomentum(iPl); 
1669     }
1670   }
1671   p = TMath::Mean(nmomenta, trdmomenta);
1672
1673   return fTRDResponse.IdentifiedAsElectron(ntracklets, probs, p, efficiencyLevel,centrality,PIDmethod);
1674 }
1675
1676 //______________________________________________________________________________
1677 void AliPIDResponse::SetEMCALPidResponseMaster()
1678 {
1679   //
1680   // Load the EMCAL pid response functions from the OADB
1681   //
1682   TObjArray* fEMCALPIDParamsRun      = NULL;
1683   TObjArray* fEMCALPIDParamsPass     = NULL;
1684
1685   if(fEMCALPIDParams) return;
1686   AliOADBContainer contParams("contParams"); 
1687
1688   Int_t statusPars = contParams.InitFromFile(Form("%s/COMMON/PID/data/EMCALPIDParams.root", fOADBPath.Data()), "AliEMCALPIDParams");
1689   if(statusPars){
1690     AliError("Failed initializing PID Params from OADB");
1691   } 
1692   else {
1693     AliInfo(Form("Loading EMCAL Params from %s/COMMON/PID/data/EMCALPIDParams.root", fOADBPath.Data()));
1694
1695     fEMCALPIDParamsRun = dynamic_cast<TObjArray *>(contParams.GetObject(fRun));
1696     if(fEMCALPIDParamsRun)  fEMCALPIDParamsPass = dynamic_cast<TObjArray *>(fEMCALPIDParamsRun->FindObject(Form("pass%d",fRecoPass)));
1697     if(fEMCALPIDParamsPass) fEMCALPIDParams     = dynamic_cast<TObjArray *>(fEMCALPIDParamsPass->FindObject(Form("EMCALPIDParams_Particles")));
1698
1699     if(!fEMCALPIDParams){
1700       AliInfo(Form("EMCAL Params not found in run %d pass %d", fRun, fRecoPass));
1701       AliInfo("Will take the standard LHC11d instead ...");
1702
1703       fEMCALPIDParamsRun = dynamic_cast<TObjArray *>(contParams.GetObject(156477));
1704       if(fEMCALPIDParamsRun)  fEMCALPIDParamsPass = dynamic_cast<TObjArray *>(fEMCALPIDParamsRun->FindObject(Form("pass%d",1)));
1705       if(fEMCALPIDParamsPass) fEMCALPIDParams     = dynamic_cast<TObjArray *>(fEMCALPIDParamsPass->FindObject(Form("EMCALPIDParams_Particles")));
1706
1707       if(!fEMCALPIDParams){
1708         AliError(Form("DEFAULT EMCAL Params (LHC11d) not found in file %s/COMMON/PID/data/EMCALPIDParams.root", fOADBPath.Data()));     
1709       }
1710     }
1711   }
1712 }
1713
1714 //______________________________________________________________________________
1715 void AliPIDResponse::InitializeEMCALResponse(){
1716   //
1717   // Set PID Params to the EMCAL PID response
1718   // 
1719   fEMCALResponse.SetPIDParams(fEMCALPIDParams);
1720
1721 }
1722
1723 //______________________________________________________________________________
1724 void AliPIDResponse::FillTrackDetectorPID(const AliVTrack *track, EDetector detector) const
1725 {
1726   //
1727   // create detector PID information and setup the transient pointer in the track
1728   //
1729   
1730   // check if detector number is inside accepted range
1731   if (detector == kNdetectors) return;
1732   
1733   // get detector pid
1734   AliDetectorPID *detPID=const_cast<AliDetectorPID*>(track->GetDetectorPID());
1735   if (!detPID) {
1736     detPID=new AliDetectorPID;
1737     (const_cast<AliVTrack*>(track))->SetDetectorPID(detPID);
1738   }
1739   
1740   //check if values exist
1741   if (detPID->HasRawProbability(detector) && detPID->HasNumberOfSigmas(detector)) return;
1742   
1743   //TODO: which particles to include? See also the loops below...
1744   Double_t values[AliPID::kSPECIESC]={0};
1745
1746   //probabilities
1747   EDetPidStatus status=GetComputePIDProbability(detector,track,AliPID::kSPECIESC,values);
1748   detPID->SetRawProbability(detector, values, (Int_t)AliPID::kSPECIESC, status);
1749   
1750   //nsigmas
1751   for (Int_t ipart=0; ipart<AliPID::kSPECIESC; ++ipart)
1752     values[ipart]=GetNumberOfSigmas(detector,track,(AliPID::EParticleType)ipart);
1753   // the pid status is the same for probabilities and nSigmas, so it is
1754   // fine to use the one from the probabilities also here
1755   detPID->SetNumberOfSigmas(detector, values, (Int_t)AliPID::kSPECIESC, status);
1756   
1757 }
1758
1759 //______________________________________________________________________________
1760 void AliPIDResponse::FillTrackDetectorPID()
1761 {
1762   //
1763   // create detector PID information and setup the transient pointer in the track
1764   //
1765
1766   if (!fCurrentEvent) return;
1767   
1768   for (Int_t itrack=0; itrack<fCurrentEvent->GetNumberOfTracks(); ++itrack){
1769     AliVTrack *track=dynamic_cast<AliVTrack*>(fCurrentEvent->GetTrack(itrack));
1770     if (!track) continue;
1771
1772     for (Int_t idet=0; idet<kNdetectors; ++idet){
1773       FillTrackDetectorPID(track, (EDetector)idet);
1774     }
1775   }
1776 }
1777
1778 //______________________________________________________________________________
1779 void AliPIDResponse::SetTOFResponse(AliVEvent *vevent,EStartTimeType_t option){
1780   //
1781   // Set TOF response function
1782   // Input option for event_time used
1783   //
1784
1785     Float_t t0spread = 0.; //vevent->GetEventTimeSpread();
1786     if(t0spread < 10) t0spread = 80;
1787
1788     // T0-FILL and T0-TO offset (because of TOF misallignment
1789     Float_t starttimeoffset = 0;
1790     if(fTOFPIDParams && !(fIsMC)) starttimeoffset=fTOFPIDParams->GetTOFtimeOffset();
1791     if(fTOFPIDParams){
1792       fTOFtail = fTOFPIDParams->GetTOFtail();
1793       GetTOFResponse().SetTOFtail(fTOFtail);
1794     }
1795
1796     // T0 from TOF algorithm
1797     Bool_t flagT0TOF=kFALSE;
1798     Bool_t flagT0T0=kFALSE;
1799     Float_t *startTime = new Float_t[fTOFResponse.GetNmomBins()];
1800     Float_t *startTimeRes = new Float_t[fTOFResponse.GetNmomBins()];
1801     Int_t *startTimeMask = new Int_t[fTOFResponse.GetNmomBins()];
1802
1803     // T0-TOF arrays
1804     Float_t *estimatedT0event = new Float_t[fTOFResponse.GetNmomBins()];
1805     Float_t *estimatedT0resolution = new Float_t[fTOFResponse.GetNmomBins()];
1806     for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){
1807       estimatedT0event[i]=0.0;
1808       estimatedT0resolution[i]=0.0;
1809       startTimeMask[i] = 0;
1810     }
1811
1812     Float_t resT0A=fResT0A;
1813     Float_t resT0C=fResT0C;
1814     Float_t resT0AC=fResT0AC;
1815     if(vevent->GetT0TOF()){ // check if T0 detector information is available
1816         flagT0T0=kTRUE;
1817     }
1818
1819
1820     AliTOFHeader *tofHeader = (AliTOFHeader*)vevent->GetTOFHeader();
1821
1822     if (tofHeader) { // read global info and T0-TOF
1823       fTOFResponse.SetTimeResolution(tofHeader->GetTOFResolution());
1824       t0spread = tofHeader->GetT0spread(); // read t0 sprad
1825       if(t0spread < 10) t0spread = 80;
1826
1827       flagT0TOF=kTRUE;
1828       for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){ // read T0-TOF default value
1829         startTime[i]=tofHeader->GetDefaultEventTimeVal();
1830         startTimeRes[i]=tofHeader->GetDefaultEventTimeRes();
1831         if(startTimeRes[i] < 1.e-5) startTimeRes[i] = t0spread;
1832
1833         if(startTimeRes[i] > t0spread - 10 && TMath::Abs(startTime[i]) < 0.001) startTime[i] = -starttimeoffset; // apply offset for T0-fill
1834       }
1835
1836       TArrayI *ibin=(TArrayI*)tofHeader->GetNvalues();
1837       TArrayF *t0Bin=(TArrayF*)tofHeader->GetEventTimeValues();
1838       TArrayF *t0ResBin=(TArrayF*)tofHeader->GetEventTimeRes();
1839       for(Int_t j=0;j < tofHeader->GetNbins();j++){ // fill T0-TOF in p-bins
1840         Int_t icurrent = (Int_t)ibin->GetAt(j);
1841         startTime[icurrent]=t0Bin->GetAt(j);
1842         startTimeRes[icurrent]=t0ResBin->GetAt(j);
1843         if(startTimeRes[icurrent] < 1.e-5) startTimeRes[icurrent] = t0spread;
1844         if(startTimeRes[icurrent] > t0spread - 10 && TMath::Abs(startTime[icurrent]) < 0.001) startTime[icurrent] = -starttimeoffset; // apply offset for T0-fill
1845       }
1846     }
1847
1848     // for cut of 3 sigma on t0 spread
1849     Float_t t0cut = 3 * t0spread;
1850     if(t0cut < 500) t0cut = 500;
1851
1852     if(option == kFILL_T0){ // T0-FILL is used
1853         for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){
1854           estimatedT0event[i]=0.0-starttimeoffset;
1855           estimatedT0resolution[i]=t0spread;
1856         }
1857         fTOFResponse.SetT0event(estimatedT0event);
1858         fTOFResponse.SetT0resolution(estimatedT0resolution);
1859     }
1860
1861     if(option == kTOF_T0){ // T0-TOF is used when available (T0-FILL otherwise) from ESD
1862         if(flagT0TOF){
1863             fTOFResponse.SetT0event(startTime);
1864             fTOFResponse.SetT0resolution(startTimeRes);
1865             for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){
1866               if(startTimeRes[i]<t0spread) startTimeMask[i]=1;
1867               fTOFResponse.SetT0binMask(i,startTimeMask[i]);
1868             }
1869         }
1870         else{
1871             for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){
1872               estimatedT0event[i]=0.0-starttimeoffset;
1873               estimatedT0resolution[i]=t0spread;
1874               fTOFResponse.SetT0binMask(i,startTimeMask[i]);
1875             }
1876             fTOFResponse.SetT0event(estimatedT0event);
1877             fTOFResponse.SetT0resolution(estimatedT0resolution);
1878         }
1879     }
1880     else if(option == kBest_T0){ // T0-T0 or T0-TOF are used when available (T0-FILL otherwise) from ESD
1881         Float_t t0AC=-10000;
1882         Float_t t0A=-10000;
1883         Float_t t0C=-10000;
1884         if(flagT0T0){
1885             t0A= vevent->GetT0TOF()[1] - starttimeoffset;
1886             t0C= vevent->GetT0TOF()[2] - starttimeoffset;
1887         //      t0AC= vevent->GetT0TOF()[0];
1888             t0AC= t0A/resT0A/resT0A + t0C/resT0C/resT0C;
1889             resT0AC= TMath::Sqrt(1./resT0A/resT0A + 1./resT0C/resT0C);
1890             t0AC /= resT0AC*resT0AC;
1891         }
1892
1893         Float_t t0t0Best = 0;
1894         Float_t t0t0BestRes = 9999;
1895         Int_t t0used=0;
1896         if(TMath::Abs(t0A) < t0cut && TMath::Abs(t0C) < t0cut && TMath::Abs(t0C-t0A) < 500){
1897             t0t0Best = t0AC;
1898             t0t0BestRes = resT0AC;
1899             t0used=6;
1900         }
1901         else if(TMath::Abs(t0C) < t0cut){
1902             t0t0Best = t0C;
1903             t0t0BestRes = resT0C;
1904             t0used=4;
1905         }
1906         else if(TMath::Abs(t0A) < t0cut){
1907             t0t0Best = t0A;
1908             t0t0BestRes = resT0A;
1909             t0used=2;
1910         }
1911
1912         if(flagT0TOF){ // if T0-TOF info is available
1913             for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){
1914                 if(t0t0BestRes < 999){
1915                   if(startTimeRes[i] < t0spread){
1916                     Double_t wtot = 1./startTimeRes[i]/startTimeRes[i] + 1./t0t0BestRes/t0t0BestRes;
1917                     Double_t t0best = startTime[i]/startTimeRes[i]/startTimeRes[i] + t0t0Best/t0t0BestRes/t0t0BestRes;
1918                     estimatedT0event[i]=t0best / wtot;
1919                     estimatedT0resolution[i]=1./TMath::Sqrt(wtot);
1920                     startTimeMask[i] = t0used+1;
1921                   }
1922                   else {
1923                     estimatedT0event[i]=t0t0Best;
1924                     estimatedT0resolution[i]=t0t0BestRes;
1925                     startTimeMask[i] = t0used;
1926                   }
1927                 }
1928                 else{
1929                   estimatedT0event[i]=startTime[i];
1930                   estimatedT0resolution[i]=startTimeRes[i];
1931                   if(startTimeRes[i]<t0spread) startTimeMask[i]=1;
1932                 }
1933                 fTOFResponse.SetT0binMask(i,startTimeMask[i]);
1934             }
1935             fTOFResponse.SetT0event(estimatedT0event);
1936             fTOFResponse.SetT0resolution(estimatedT0resolution);
1937         }
1938         else{ // if no T0-TOF info is available
1939             for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){
1940               fTOFResponse.SetT0binMask(i,t0used);
1941               if(t0t0BestRes < 999){
1942                 estimatedT0event[i]=t0t0Best;
1943                 estimatedT0resolution[i]=t0t0BestRes;
1944               }
1945               else{
1946                 estimatedT0event[i]=0.0-starttimeoffset;
1947                 estimatedT0resolution[i]=t0spread;
1948               }
1949             }
1950             fTOFResponse.SetT0event(estimatedT0event);
1951             fTOFResponse.SetT0resolution(estimatedT0resolution);
1952         }
1953     }
1954
1955     else if(option == kT0_T0){ // T0-T0 is used when available (T0-FILL otherwise)
1956         Float_t t0AC=-10000;
1957         Float_t t0A=-10000;
1958         Float_t t0C=-10000;
1959         if(flagT0T0){
1960             t0A= vevent->GetT0TOF()[1] - starttimeoffset;
1961             t0C= vevent->GetT0TOF()[2] - starttimeoffset;
1962         //      t0AC= vevent->GetT0TOF()[0];
1963             t0AC= t0A/resT0A/resT0A + t0C/resT0C/resT0C;
1964             resT0AC= TMath::Sqrt(1./resT0A/resT0A + 1./resT0C/resT0C);
1965             t0AC /= resT0AC*resT0AC;
1966         }
1967
1968         if(TMath::Abs(t0A) < t0cut && TMath::Abs(t0C) < t0cut && TMath::Abs(t0C-t0A) < 500){
1969             for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){
1970               estimatedT0event[i]=t0AC;
1971               estimatedT0resolution[i]=resT0AC;
1972               fTOFResponse.SetT0binMask(i,6);
1973             }
1974         }
1975         else if(TMath::Abs(t0C) < t0cut){
1976             for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){
1977               estimatedT0event[i]=t0C;
1978               estimatedT0resolution[i]=resT0C;
1979               fTOFResponse.SetT0binMask(i,4);
1980             }
1981         }
1982         else if(TMath::Abs(t0A) < t0cut){
1983             for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){
1984               estimatedT0event[i]=t0A;
1985               estimatedT0resolution[i]=resT0A;
1986               fTOFResponse.SetT0binMask(i,2);
1987             }
1988         }
1989         else{
1990             for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){
1991               estimatedT0event[i]= 0.0 - starttimeoffset;
1992               estimatedT0resolution[i]=t0spread;
1993               fTOFResponse.SetT0binMask(i,0);
1994             }
1995         }
1996         fTOFResponse.SetT0event(estimatedT0event);
1997         fTOFResponse.SetT0resolution(estimatedT0resolution);
1998     }
1999
2000     delete [] startTime;
2001     delete [] startTimeRes;
2002     delete [] startTimeMask;
2003     delete [] estimatedT0event;
2004     delete [] estimatedT0resolution;
2005 }
2006
2007 //______________________________________________________________________________
2008 // private non cached versions of the PID calculation
2009 //
2010
2011
2012 //______________________________________________________________________________
2013 Float_t AliPIDResponse::GetNumberOfSigmas(EDetector detector, const AliVParticle *vtrack, AliPID::EParticleType type) const
2014 {
2015   //
2016   // NumberOfSigmas for 'detCode'
2017   //
2018
2019   const AliVTrack *track=static_cast<const AliVTrack*>(vtrack);
2020   
2021   switch (detector){
2022     case kITS:   return GetNumberOfSigmasITS(track, type);   break;
2023     case kTPC:   return GetNumberOfSigmasTPC(track, type);   break;
2024     case kTOF:   return GetNumberOfSigmasTOF(track, type);   break;
2025     case kHMPID: return GetNumberOfSigmasHMPID(track, type); break;
2026     case kEMCAL: return GetNumberOfSigmasEMCAL(track, type); break;
2027     default: return -999.;
2028   }
2029
2030   return -999.;
2031 }
2032
2033 //______________________________________________________________________________
2034 Float_t AliPIDResponse::GetNumberOfSigmasITS(const AliVParticle *vtrack, AliPID::EParticleType type) const
2035 {
2036   //
2037   // Calculate the number of sigmas in the ITS
2038   //
2039   
2040   AliVTrack *track=(AliVTrack*)vtrack;
2041
2042   const EDetPidStatus pidStatus=GetITSPIDStatus(track);
2043   if (pidStatus!=kDetPidOk) return -999.;
2044
2045   return fITSResponse.GetNumberOfSigmas(track,type);
2046 }
2047
2048 //______________________________________________________________________________
2049 Float_t AliPIDResponse::GetNumberOfSigmasTPC(const AliVParticle *vtrack, AliPID::EParticleType type) const
2050 {
2051   //
2052   // Calculate the number of sigmas in the TPC
2053   //
2054   
2055   AliVTrack *track=(AliVTrack*)vtrack;
2056
2057   const EDetPidStatus pidStatus=GetTPCPIDStatus(track);
2058   if (pidStatus!=kDetPidOk) return -999.;
2059
2060   // the following call is needed in order to fill the transient data member
2061   // fTPCsignalTuned which is used in the TPCPIDResponse to judge
2062   // if using tuned on data
2063   if (fTuneMConData && ((fTuneMConDataMask & kDetTPC) == kDetTPC))
2064     this->GetTPCsignalTunedOnData(track);
2065   
2066   return fTPCResponse.GetNumberOfSigmas(track, type, AliTPCPIDResponse::kdEdxDefault, fUseTPCEtaCorrection, fUseTPCMultiplicityCorrection);
2067 }
2068
2069 //______________________________________________________________________________
2070 Float_t AliPIDResponse::GetNumberOfSigmasTOF(const AliVParticle *vtrack, AliPID::EParticleType type) const
2071 {
2072   //
2073   // Calculate the number of sigmas in the TOF
2074   //
2075   
2076   AliVTrack *track=(AliVTrack*)vtrack;
2077
2078   const EDetPidStatus pidStatus=GetTOFPIDStatus(track);
2079   if (pidStatus!=kDetPidOk) return -999.;
2080   
2081   return GetNumberOfSigmasTOFold(vtrack, type);
2082 }
2083 //______________________________________________________________________________
2084
2085 Float_t AliPIDResponse::GetNumberOfSigmasHMPID(const AliVParticle *vtrack, AliPID::EParticleType type) const
2086 {
2087   //
2088   // Calculate the number of sigmas in the HMPID
2089   //  
2090   AliVTrack *track=(AliVTrack*)vtrack;
2091     
2092   const EDetPidStatus pidStatus=GetHMPIDPIDStatus(track);
2093   if (pidStatus!=kDetPidOk) return -999.; 
2094   
2095   return fHMPIDResponse.GetNumberOfSigmas(track, type);
2096 }
2097
2098 //______________________________________________________________________________
2099 Float_t AliPIDResponse::GetNumberOfSigmasEMCAL(const AliVParticle *vtrack, AliPID::EParticleType type) const
2100 {
2101   //
2102   // Calculate the number of sigmas in the EMCAL
2103   //
2104   
2105   AliVTrack *track=(AliVTrack*)vtrack;
2106
2107   const EDetPidStatus pidStatus=GetEMCALPIDStatus(track);
2108   if (pidStatus!=kDetPidOk) return -999.;
2109
2110   const Int_t nMatchClus = track->GetEMCALcluster();
2111   AliVCluster *matchedClus = (AliVCluster*)fCurrentEvent->GetCaloCluster(nMatchClus);
2112   
2113   const Double_t mom    = track->P();
2114   const Double_t pt     = track->Pt();
2115   const Int_t    charge = track->Charge();
2116   const Double_t fClsE  = matchedClus->E();
2117   const Double_t EovP   = fClsE/mom;
2118   
2119   return fEMCALResponse.GetNumberOfSigmas(pt,EovP,type,charge);
2120 }
2121
2122 //______________________________________________________________________________
2123 AliPIDResponse::EDetPidStatus AliPIDResponse::GetSignalDeltaITS(const AliVParticle *vtrack, AliPID::EParticleType type, Double_t &val, Bool_t ratio/*=kFALSE*/) const
2124 {
2125   //
2126   // Signal minus expected Signal for ITS
2127   //
2128   AliVTrack *track=(AliVTrack*)vtrack;
2129   val=fITSResponse.GetSignalDelta(track,type,ratio);
2130   
2131   return GetITSPIDStatus(track);
2132 }
2133
2134 //______________________________________________________________________________
2135 AliPIDResponse::EDetPidStatus AliPIDResponse::GetSignalDeltaTPC(const AliVParticle *vtrack, AliPID::EParticleType type, Double_t &val, Bool_t ratio/*=kFALSE*/) const
2136 {
2137   //
2138   // Signal minus expected Signal for TPC
2139   //
2140   AliVTrack *track=(AliVTrack*)vtrack;
2141   
2142   // the following call is needed in order to fill the transient data member
2143   // fTPCsignalTuned which is used in the TPCPIDResponse to judge
2144   // if using tuned on data
2145   if (fTuneMConData && ((fTuneMConDataMask & kDetTPC) == kDetTPC))
2146     this->GetTPCsignalTunedOnData(track);
2147   
2148   val=fTPCResponse.GetSignalDelta(track, type, AliTPCPIDResponse::kdEdxDefault, fUseTPCEtaCorrection, fUseTPCMultiplicityCorrection, ratio);
2149   
2150   return GetTPCPIDStatus(track);
2151 }
2152
2153 //______________________________________________________________________________
2154 AliPIDResponse::EDetPidStatus AliPIDResponse::GetSignalDeltaTOF(const AliVParticle *vtrack, AliPID::EParticleType type, Double_t &val, Bool_t ratio/*=kFALSE*/) const
2155 {
2156   //
2157   // Signal minus expected Signal for TOF
2158   //
2159   AliVTrack *track=(AliVTrack*)vtrack;
2160   val=GetSignalDeltaTOFold(track, type, ratio);
2161   
2162   return GetTOFPIDStatus(track);
2163 }
2164
2165 //______________________________________________________________________________
2166 AliPIDResponse::EDetPidStatus AliPIDResponse::GetSignalDeltaHMPID(const AliVParticle *vtrack, AliPID::EParticleType type, Double_t &val, Bool_t ratio/*=kFALSE*/) const
2167 {
2168   //
2169   // Signal minus expected Signal for HMPID
2170   //
2171   AliVTrack *track=(AliVTrack*)vtrack;
2172   val=fHMPIDResponse.GetSignalDelta(track, type, ratio);
2173   
2174   return GetHMPIDPIDStatus(track);
2175 }
2176
2177 //______________________________________________________________________________
2178 AliPIDResponse::EDetPidStatus AliPIDResponse::GetComputePIDProbability  (EDetector detCode,  const AliVTrack *track, Int_t nSpecies, Double_t p[]) const
2179 {
2180   //
2181   // Compute PID response of 'detCode'
2182   //
2183
2184   switch (detCode){
2185     case kITS: return GetComputeITSProbability(track, nSpecies, p); break;
2186     case kTPC: return GetComputeTPCProbability(track, nSpecies, p); break;
2187     case kTRD: return GetComputeTRDProbability(track, nSpecies, p); break;
2188     case kTOF: return GetComputeTOFProbability(track, nSpecies, p); break;
2189     case kPHOS: return GetComputePHOSProbability(track, nSpecies, p); break;
2190     case kEMCAL: return GetComputeEMCALProbability(track, nSpecies, p); break;
2191     case kHMPID: return GetComputeHMPIDProbability(track, nSpecies, p); break;
2192     default: return kDetNoSignal;
2193   }
2194 }
2195
2196 //______________________________________________________________________________
2197 AliPIDResponse::EDetPidStatus AliPIDResponse::GetComputeITSProbability  (const AliVTrack *track, Int_t nSpecies, Double_t p[]) const
2198 {
2199   //
2200   // Compute PID response for the ITS
2201   //
2202   
2203   // set flat distribution (no decision)
2204   for (Int_t j=0; j<nSpecies; j++) p[j]=1./nSpecies;
2205   
2206   const EDetPidStatus pidStatus=GetITSPIDStatus(track);
2207   if (pidStatus!=kDetPidOk) return pidStatus;
2208   
2209   if (track->GetDetectorPID()){
2210     return track->GetDetectorPID()->GetRawProbability(kITS, p, nSpecies);
2211   }
2212   
2213   //check for ITS standalone tracks
2214   Bool_t isSA=kTRUE;
2215   if( track->GetStatus() & AliVTrack::kTPCin ) isSA=kFALSE;
2216
2217   Double_t mom=track->P();
2218   Double_t dedx=track->GetITSsignal();
2219   Double_t momITS=mom;
2220   UChar_t clumap=track->GetITSClusterMap();
2221   Int_t nPointsForPid=0;
2222   for(Int_t i=2; i<6; i++){
2223     if(clumap&(1<<i)) ++nPointsForPid;
2224   }
2225
2226   Bool_t mismatch=kTRUE/*, heavy=kTRUE*/;
2227   for (Int_t j=0; j<nSpecies; j++) {
2228     Double_t mass=AliPID::ParticleMassZ(j);//GeV/c^2
2229     const Double_t chargeFactor = TMath::Power(AliPID::ParticleCharge(j),2.);
2230     Double_t bethe=fITSResponse.Bethe(momITS,mass)*chargeFactor;
2231     //TODO: in case of the electron, use the SA parametrisation,
2232     //      this needs to be changed if ITS provides a parametrisation
2233     //      for electrons also for ITS+TPC tracks
2234     Double_t sigma=fITSResponse.GetResolution(bethe,nPointsForPid,isSA || (j==(Int_t)AliPID::kElectron));
2235     if (TMath::Abs(dedx-bethe) > fRange*sigma) {
2236       p[j]=TMath::Exp(-0.5*fRange*fRange)/sigma;
2237     } else {
2238       p[j]=TMath::Exp(-0.5*(dedx-bethe)*(dedx-bethe)/(sigma*sigma))/sigma;
2239       mismatch=kFALSE;
2240     }
2241   }
2242
2243   if (mismatch){
2244     for (Int_t j=0; j<nSpecies; j++) p[j]=1./nSpecies;
2245   }
2246
2247   return kDetPidOk;
2248 }
2249 //______________________________________________________________________________
2250 AliPIDResponse::EDetPidStatus AliPIDResponse::GetComputeTPCProbability  (const AliVTrack *track, Int_t nSpecies, Double_t p[]) const
2251 {
2252   //
2253   // Compute PID response for the TPC
2254   //
2255   
2256   // set flat distribution (no decision)
2257   for (Int_t j=0; j<nSpecies; j++) p[j]=1./nSpecies;
2258   
2259   const EDetPidStatus pidStatus=GetTPCPIDStatus(track);
2260   if (pidStatus!=kDetPidOk) return pidStatus;
2261   
2262   Double_t dedx=track->GetTPCsignal();
2263   Bool_t mismatch=kTRUE/*, heavy=kTRUE*/;
2264   
2265   if (fTuneMConData && ((fTuneMConDataMask & kDetTPC) == kDetTPC)) dedx = this->GetTPCsignalTunedOnData(track);
2266   
2267   Double_t bethe = 0.;
2268   Double_t sigma = 0.;
2269   
2270   for (Int_t j=0; j<nSpecies; j++) {
2271     AliPID::EParticleType type=AliPID::EParticleType(j);
2272     
2273     bethe=fTPCResponse.GetExpectedSignal(track, type, AliTPCPIDResponse::kdEdxDefault, fUseTPCEtaCorrection, fUseTPCMultiplicityCorrection);
2274     sigma=fTPCResponse.GetExpectedSigma(track, type, AliTPCPIDResponse::kdEdxDefault, fUseTPCEtaCorrection, fUseTPCMultiplicityCorrection);
2275     
2276     if (TMath::Abs(dedx-bethe) > fRange*sigma) {
2277       p[j]=TMath::Exp(-0.5*fRange*fRange)/sigma;
2278     } else {
2279       p[j]=TMath::Exp(-0.5*(dedx-bethe)*(dedx-bethe)/(sigma*sigma))/sigma;
2280       mismatch=kFALSE;
2281     }
2282   }
2283   
2284   if (mismatch){
2285     for (Int_t j=0; j<nSpecies; j++) p[j]=1./nSpecies;
2286   }
2287   
2288   return kDetPidOk;
2289 }
2290 //______________________________________________________________________________
2291 AliPIDResponse::EDetPidStatus AliPIDResponse::GetComputeTOFProbability  (const AliVTrack *track, Int_t nSpecies, Double_t p[]) const
2292 {
2293   //
2294   // Compute PID probabilities for TOF
2295   //
2296
2297   fgTOFmismatchProb = 1E-8;
2298
2299   // centrality --> fCurrCentrality
2300   // Beam type --> fBeamTypeNum
2301   // 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
2302   // isMC --> fIsMC
2303
2304   Int_t nTOFcluster = 0;
2305   if(track->GetTOFHeader() && track->GetTOFHeader()->GetTriggerMask()){ // N TOF clusters available
2306     nTOFcluster = track->GetTOFHeader()->GetNumberOfTOFclusters();
2307     if(fIsMC) nTOFcluster *= 1.5; // +50% in MC
2308   }
2309   else{
2310     switch(fBeamTypeNum){
2311     case kPP: // pp 7 TeV
2312       nTOFcluster = 50;
2313       break;
2314     case kPPB: // pPb 5.05 ATeV
2315       nTOFcluster = 50 + (100-fCurrCentrality)*50;
2316       break;
2317     case kPBPB: // PbPb 2.76 ATeV
2318       nTOFcluster = 50 + (100-fCurrCentrality)*150;
2319       break;
2320     }
2321   }
2322
2323   //fTOFResponse.GetMismatchProbability(track->GetTOFsignal(),track->Eta()) * 0.01; // for future implementation of mismatch (i.e. 1% mismatch that should be extended for PbPb, pPb)
2324
2325   // set flat distribution (no decision)
2326   for (Int_t j=0; j<nSpecies; j++) p[j]=1./nSpecies;
2327   
2328   const EDetPidStatus pidStatus=GetTOFPIDStatus(track);
2329   if (pidStatus!=kDetPidOk) return pidStatus;
2330
2331   const Double_t meanCorrFactor = 0.07/fTOFtail; // Correction factor on the mean because of the tail (should be ~ 0.1 with tail = 1.1)
2332   
2333   for (Int_t j=0; j<nSpecies; j++) {
2334     AliPID::EParticleType type=AliPID::EParticleType(j);
2335     const Double_t nsigmas=GetNumberOfSigmasTOFold(track,type) + meanCorrFactor;
2336     
2337     const Double_t expTime = fTOFResponse.GetExpectedSignal(track,type);
2338     const Double_t sig     = fTOFResponse.GetExpectedSigma(track->P(),expTime,AliPID::ParticleMassZ(type));
2339
2340     if(nsigmas < fTOFtail)
2341       p[j] = TMath::Exp(-0.5*nsigmas*nsigmas)/sig;
2342     else
2343       p[j] = TMath::Exp(-(nsigmas - fTOFtail*0.5)*fTOFtail)/sig;
2344     
2345     p[j] += fgTOFmismatchProb;
2346   }
2347   
2348   return kDetPidOk;
2349 }
2350
2351 Int_t AliPIDResponse::CalculateTRDResponse(const AliVTrack *track,Double_t p[],AliTRDPIDResponse::ETRDPIDMethod PIDmethod) const
2352 {
2353     // new function for backward compatibility
2354     // returns number of tracklets PID
2355
2356     UInt_t TRDslicesForPID[2];
2357     SetTRDSlices(TRDslicesForPID,PIDmethod);
2358
2359     Float_t mom[6]={0.};
2360     Double_t dedx[48]={0.};  // Allocate space for the maximum number of TRD slices
2361     Int_t nslices = TRDslicesForPID[1] - TRDslicesForPID[0] + 1;
2362     AliDebug(1, Form("First Slice: %d, Last Slice: %d, Number of slices: %d",  TRDslicesForPID[0], TRDslicesForPID[1], nslices));
2363     for(UInt_t ilayer = 0; ilayer < 6; ilayer++){
2364         mom[ilayer] = track->GetTRDmomentum(ilayer);
2365         for(UInt_t islice = TRDslicesForPID[0]; islice <= TRDslicesForPID[1]; islice++){
2366             dedx[ilayer*nslices+islice-TRDslicesForPID[0]] = track->GetTRDslice(ilayer, islice);
2367         }
2368     }
2369
2370     return fTRDResponse.GetResponse(nslices, dedx, mom, p,PIDmethod);
2371
2372 }
2373 //______________________________________________________________________________
2374 AliPIDResponse::EDetPidStatus AliPIDResponse::GetComputeTRDProbability  (const AliVTrack *track, Int_t nSpecies, Double_t p[],AliTRDPIDResponse::ETRDPIDMethod PIDmethod) const
2375 {
2376   //
2377   // Compute PID probabilities for the TRD
2378   //
2379   
2380   // set flat distribution (no decision)
2381   for (Int_t j=0; j<nSpecies; j++) p[j]=1./nSpecies;
2382   
2383   const EDetPidStatus pidStatus=GetTRDPIDStatus(track);
2384   if (pidStatus!=kDetPidOk) return pidStatus;
2385
2386   CalculateTRDResponse(track,p,PIDmethod);
2387
2388   return kDetPidOk;
2389 }
2390
2391 //______________________________________________________________________________
2392 AliPIDResponse::EDetPidStatus AliPIDResponse::GetComputeEMCALProbability  (const AliVTrack *track, Int_t nSpecies, Double_t p[]) const
2393 {
2394   //
2395   // Compute PID response for the EMCAL
2396   //
2397   
2398   for (Int_t j=0; j<nSpecies; j++) p[j]=1./nSpecies;
2399
2400   const EDetPidStatus pidStatus=GetEMCALPIDStatus(track);
2401   if (pidStatus!=kDetPidOk) return pidStatus;
2402
2403   const Int_t nMatchClus = track->GetEMCALcluster();
2404   AliVCluster *matchedClus = (AliVCluster*)fCurrentEvent->GetCaloCluster(nMatchClus);
2405   
2406   const Double_t mom    = track->P();
2407   const Double_t pt     = track->Pt();
2408   const Int_t    charge = track->Charge();
2409   const Double_t fClsE  = matchedClus->E();
2410   const Double_t EovP   = fClsE/mom;
2411   
2412   // compute the probabilities
2413   fEMCALResponse.ComputeEMCALProbability(nSpecies,pt,EovP,charge,p);
2414   return kDetPidOk;
2415 }
2416
2417 //______________________________________________________________________________
2418 AliPIDResponse::EDetPidStatus AliPIDResponse::GetComputePHOSProbability (const AliVTrack */*track*/, Int_t nSpecies, Double_t p[]) const
2419 {
2420   //
2421   // Compute PID response for the PHOS
2422   //
2423   
2424   // set flat distribution (no decision)
2425   for (Int_t j=0; j<nSpecies; j++) p[j]=1./nSpecies;
2426   return kDetNoSignal;
2427 }
2428
2429 //______________________________________________________________________________
2430 AliPIDResponse::EDetPidStatus AliPIDResponse::GetComputeHMPIDProbability(const AliVTrack *track, Int_t nSpecies, Double_t p[]) const
2431 {
2432   //
2433   // Compute PID response for the HMPID
2434   //
2435   
2436   // set flat distribution (no decision)
2437   for (Int_t j=0; j<nSpecies; j++) p[j]=1./nSpecies;
2438   
2439   const EDetPidStatus pidStatus=GetHMPIDPIDStatus(track);
2440   if (pidStatus!=kDetPidOk) return pidStatus;
2441   
2442   fHMPIDResponse.GetProbability(track,nSpecies,p);
2443     
2444   return kDetPidOk;
2445 }
2446
2447 //______________________________________________________________________________
2448 AliPIDResponse::EDetPidStatus AliPIDResponse::GetITSPIDStatus(const AliVTrack *track) const
2449 {
2450   // compute ITS pid status
2451
2452   // check status bits
2453   if ((track->GetStatus()&AliVTrack::kITSin)==0 &&
2454     (track->GetStatus()&AliVTrack::kITSout)==0) return kDetNoSignal;
2455
2456   const Float_t dEdx=track->GetITSsignal();
2457   if (dEdx<=0) return kDetNoSignal;
2458   
2459   // requite at least 3 pid clusters
2460   const UChar_t clumap=track->GetITSClusterMap();
2461   Int_t nPointsForPid=0;
2462   for(Int_t i=2; i<6; i++){
2463     if(clumap&(1<<i)) ++nPointsForPid;
2464   }
2465   
2466   if(nPointsForPid<3) { 
2467     return kDetNoSignal;
2468   }
2469   
2470   return kDetPidOk;
2471 }
2472
2473 //______________________________________________________________________________
2474 AliPIDResponse::EDetPidStatus AliPIDResponse:: GetTPCPIDStatus(const AliVTrack *track) const
2475 {
2476   // compute TPC pid status
2477   
2478   // check quality of the track
2479   if ( (track->GetStatus()&AliVTrack::kTPCin )==0 && (track->GetStatus()&AliVTrack::kTPCout)==0 ) return kDetNoSignal;
2480
2481   // check pid values
2482   const Double_t dedx=track->GetTPCsignal();
2483   const UShort_t signalN=track->GetTPCsignalN();
2484   if (signalN<10 || dedx<10) return kDetNoSignal;
2485
2486   if (!(fArrPidResponseMaster && fArrPidResponseMaster->At(AliPID::kPion))) return kDetNoParams;
2487   
2488   return kDetPidOk;
2489 }
2490
2491 //______________________________________________________________________________
2492 AliPIDResponse::EDetPidStatus AliPIDResponse::GetTRDPIDStatus(const AliVTrack *track) const
2493 {
2494   // compute TRD pid status
2495
2496   if((track->GetStatus()&AliVTrack::kTRDout)==0) return kDetNoSignal;
2497   return kDetPidOk;
2498 }
2499
2500 //______________________________________________________________________________
2501 AliPIDResponse::EDetPidStatus AliPIDResponse::GetTOFPIDStatus(const AliVTrack *track) const
2502 {
2503   // compute TOF pid status
2504
2505   if ((track->GetStatus()&AliVTrack::kTOFout)==0) return kDetNoSignal;
2506   if ((track->GetStatus()&AliVTrack::kTIME)==0) return kDetNoSignal;
2507
2508   return kDetPidOk;
2509 }
2510
2511 //______________________________________________________________________________
2512 Float_t AliPIDResponse::GetTOFMismatchProbability(const AliVTrack *track) const
2513 {
2514   // compute mismatch probability cross-checking at 5 sigmas with TPC
2515   // currently just implemented as a 5 sigma compatibility cut
2516
2517   if(!track) return fgTOFmismatchProb;
2518
2519   // check pid status
2520   const EDetPidStatus tofStatus=GetTOFPIDStatus(track);
2521   if (tofStatus!=kDetPidOk) return 0.;
2522
2523   //mismatch
2524   const EDetPidStatus tpcStatus=GetTPCPIDStatus(track);
2525   if (tpcStatus!=kDetPidOk) return 0.;
2526   
2527   const Double_t meanCorrFactor = 0.11/fTOFtail; // Correction factor on the mean because of the tail (should be ~ 0.1 with tail = 1.1)
2528   Bool_t mismatch = kTRUE/*, heavy = kTRUE*/;
2529   for (Int_t j=0; j<AliPID::kSPECIESC; j++) {
2530     AliPID::EParticleType type=AliPID::EParticleType(j);
2531     const Double_t nsigmas=GetNumberOfSigmasTOFold(track,type) + meanCorrFactor;
2532     
2533     if (TMath::Abs(nsigmas)<5.){
2534       const Double_t nsigmasTPC=GetNumberOfSigmasTPC(track,type);
2535       if (TMath::Abs(nsigmasTPC)<5.) mismatch=kFALSE;
2536     }
2537   }
2538   
2539   if (mismatch){
2540     return 1.;
2541   }
2542   
2543   return 0.;
2544 }
2545
2546 //______________________________________________________________________________
2547 AliPIDResponse::EDetPidStatus AliPIDResponse:: GetHMPIDPIDStatus(const AliVTrack *track) const
2548 {
2549   // compute HMPID pid status
2550   
2551   Int_t ch = track->GetHMPIDcluIdx()/1000000;
2552   Double_t HMPIDsignal = track->GetHMPIDsignal(); 
2553   
2554   if((track->GetStatus()&AliVTrack::kHMPIDpid)==0 || ch<0 || ch>6 || HMPIDsignal<0) return kDetNoSignal;
2555   
2556   return kDetPidOk;
2557 }
2558
2559 //______________________________________________________________________________
2560 AliPIDResponse::EDetPidStatus AliPIDResponse:: GetPHOSPIDStatus(const AliVTrack */*track*/) const
2561 {
2562   // compute PHOS pid status
2563   return kDetNoSignal;  
2564 }
2565
2566 //______________________________________________________________________________
2567 AliPIDResponse::EDetPidStatus AliPIDResponse:: GetEMCALPIDStatus(const AliVTrack *track) const
2568 {
2569   // compute EMCAL pid status
2570
2571
2572   // Track matching
2573   const Int_t nMatchClus = track->GetEMCALcluster();
2574   if (nMatchClus<0) return kDetNoSignal;
2575
2576   AliVCluster *matchedClus = (AliVCluster*)fCurrentEvent->GetCaloCluster(nMatchClus);
2577
2578   if (!(matchedClus && matchedClus->IsEMCAL())) return kDetNoSignal;
2579
2580   const Int_t charge = track->Charge();
2581   if (TMath::Abs(charge)!=1) return kDetNoSignal;
2582
2583   if (!(fEMCALPIDParams && fEMCALPIDParams->At(AliPID::kElectron))) return kDetNoParams;
2584   
2585   return kDetPidOk;
2586
2587 }
2588
2589 //______________________________________________________________________________
2590 AliPIDResponse::EDetPidStatus AliPIDResponse::GetPIDStatus(EDetector detector, const AliVTrack *track) const
2591 {
2592   //
2593   // check pid status for a track
2594   //
2595
2596   switch (detector){
2597     case kITS:   return GetITSPIDStatus(track);   break;
2598     case kTPC:   return GetTPCPIDStatus(track);   break;
2599     case kTRD:   return GetTRDPIDStatus(track);   break;
2600     case kTOF:   return GetTOFPIDStatus(track);   break;
2601     case kPHOS:  return GetPHOSPIDStatus(track);  break;
2602     case kEMCAL: return GetEMCALPIDStatus(track); break;
2603     case kHMPID: return GetHMPIDPIDStatus(track); break;
2604     default: return kDetNoSignal;
2605   }
2606   return kDetNoSignal;
2607   
2608 }
2609
2610 //______________________________________________________________________________
2611 TString AliPIDResponse::GetChecksum(const TObject* obj) const
2612 {
2613   // Return the checksum for an object obj (tested to work properly at least for histograms and TSplines).
2614   
2615   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!
2616   
2617   // For parallel processing, a unique file pathname is required. Uniqueness can be guaranteed by using a unique directory name
2618   UInt_t index = 0;
2619   TString uniquePathName = Form("tempChecksum_%u", index);
2620   
2621   // To get a unique path name, increase the index until no directory
2622   // of such a name exists.
2623   // NOTE: gSystem->AccessPathName(...) returns kTRUE, if the access FAILED!
2624   while (!gSystem->AccessPathName(uniquePathName.Data()))
2625     uniquePathName = Form("tempChecksum_%u", ++index);
2626   
2627   if (gSystem->mkdir(uniquePathName.Data()) < 0) {
2628     AliError("Could not create temporary directory to store temp file for checksum determination!");
2629     return "ERROR";
2630   }
2631   
2632   TString option = "";
2633   
2634   // Save object as a macro, which will be deleted immediately after the checksum has been computed
2635   // (does not work for desired data types if saved as *.root for some reason) - one only wants to compare the content, not
2636   // the modification time etc. ...
2637   if (dynamic_cast<const TH1*>(obj))
2638     option = "colz"; // Histos need this option, since w/o this option, a counter is added to the filename
2639   
2640   
2641   // SaveAs must be called with the fixed fileName only, since the first argument goes into the file content
2642   // for some object types. Thus, change the directory, save the file and then go back
2643   TString oldDir = gSystem->pwd();
2644   gSystem->cd(uniquePathName.Data());
2645   obj->SaveAs(fileName.Data(), option.Data());
2646   gSystem->cd(oldDir.Data());
2647   
2648   // Use the file to calculate the MD5 checksum
2649   TMD5* md5 = TMD5::FileChecksum(Form("%s/%s", uniquePathName.Data(), fileName.Data()));
2650   TString checksum = md5->AsString();
2651   
2652   // Clean up
2653   delete md5;
2654   gSystem->Exec(Form("rm -rf %s", uniquePathName.Data()));
2655   
2656   return checksum;
2657 }