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