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