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