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