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