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