]> git.uio.no Git - u/mrichter/AliRoot.git/blob - STEER/STEERBase/AliPIDResponse.cxx
o add tan(theat) at the TPC entrance to AODs (+ getters in VTrack ESDtrack AODtrack)
[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(0.9),
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(0.9),
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=0.9;
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   Bool_t hasProdInfo=(fCurrentFile.BeginsWith("LHC"));
648   
649   TPRegexp reg(".*(LHC1[1-3][a-z]+[0-9]+[a-z_]*)/.*");
650   if (hasProdInfo) reg=TPRegexp("LHC1[1-2][a-z]+[0-9]+[a-z_]*");
651   TPRegexp reg12a17("LHC1[2-3][a-z]");
652
653   //find the period by run number (UGLY, but not stored in ESD and AOD... )
654   if (fRun>=114737&&fRun<=117223)      { fLHCperiod="LHC10B"; fMCperiodTPC="LHC10D1";  }
655   else if (fRun>=118503&&fRun<=121040) { fLHCperiod="LHC10C"; fMCperiodTPC="LHC10D1";  }
656   else if (fRun>=122195&&fRun<=126437) { fLHCperiod="LHC10D"; fMCperiodTPC="LHC10F6A"; }
657   else if (fRun>=127710&&fRun<=130850) { fLHCperiod="LHC10E"; fMCperiodTPC="LHC10F6A"; }
658   else if (fRun>=133004&&fRun<=135029) { fLHCperiod="LHC10F"; fMCperiodTPC="LHC10F6A"; }
659   else if (fRun>=135654&&fRun<=136377) { fLHCperiod="LHC10G"; fMCperiodTPC="LHC10F6A"; }
660   else if (fRun>=136851&&fRun<=139846) {
661     fLHCperiod="LHC10H";
662     fMCperiodTPC="LHC10H8";
663     if (reg.MatchB(fCurrentFile)) fMCperiodTPC="LHC11A10";
664     // exception for 13d2 and later
665     if (fCurrentAliRootRev >= 62714) fMCperiodTPC="LHC13D2";
666     fBeamType="PBPB";
667   }
668   else if (fRun>=139847&&fRun<=146974) { fLHCperiod="LHC11A"; fMCperiodTPC="LHC10F6A"; }
669   //TODO: periods 11B (146975-150721), 11C (150722-155837) are not yet treated assume 11d for the moment
670   else if (fRun>=146975&&fRun<=155837) { fLHCperiod="LHC11D"; fMCperiodTPC="LHC10F6A"; }
671   else if (fRun>=155838&&fRun<=159649) { fLHCperiod="LHC11D"; fMCperiodTPC="LHC10F6A"; }
672   // also for 11e (159650-162750),f(162751-165771) use 11d
673   else if (fRun>=159650&&fRun<=162750) { fLHCperiod="LHC11D"; fMCperiodTPC="LHC10F6A"; }
674   else if (fRun>=162751&&fRun<=165771) { fLHCperiod="LHC11D"; fMCperiodTPC="LHC10F6A"; }
675   
676   else if (fRun>=165772 && fRun<=170718) {
677     fLHCperiod="LHC11H";
678     fMCperiodTPC="LHC11A10";
679     fBeamType="PBPB";
680     if (reg12a17.MatchB(fCurrentFile)) fMCperiodTPC="LHC12A17";
681   }
682   if (fRun>=170719 && fRun<=177311) { fLHCperiod="LHC12A"; fBeamType="PP"; /*fMCperiodTPC="";*/ }
683   // for the moment use LHC12b parameters up to LHC12e
684   if (fRun>=177312 /*&& fRun<=179356*/) { fLHCperiod="LHC12B"; fBeamType="PP"; /*fMCperiodTPC="";*/ }
685 //   if (fRun>=179357 && fRun<=183173) { fLHCperiod="LHC12C"; fBeamType="PP"; /*fMCperiodTPC="";*/ }
686 //   if (fRun>=183174 && fRun<=186345) { fLHCperiod="LHC12D"; fBeamType="PP"; /*fMCperiodTPC="";*/ }
687 //   if (fRun>=186346 && fRun<=186635) { fLHCperiod="LHC12E"; fBeamType="PP"; /*fMCperiodTPC="";*/ }
688
689 //   if (fRun>=186636 && fRun<=188166) { fLHCperiod="LHC12F"; fBeamType="PP"; /*fMCperiodTPC="";*/ }
690 //   if (fRun >= 188167 && fRun <= 188355 ) { fLHCperiod="LHC12G"; fBeamType="PP"; /*fMCperiodTPC="";*/ }
691 //   if (fRun >= 188356 && fRun <= 188503 ) { fLHCperiod="LHC12G"; fBeamType="PPB"; /*fMCperiodTPC="";*/ }
692 // for the moment use 12g parametrisation for all full gain runs (LHC12f+)
693   if (fRun >= 186636 && fRun < 194480) { fLHCperiod="LHC12G"; fBeamType="PPB"; fMCperiodTPC="LHC12G"; }
694
695   // New parametrisation for 2013 pPb runs
696   if (fRun >= 194480) { 
697     fLHCperiod="LHC13B"; 
698     fBeamType="PPB";
699     fMCperiodTPC="LHC12G";
700   
701     if (fCurrentAliRootRev >= 61605)
702       fMCperiodTPC="LHC13B2_FIX";
703     if (fCurrentAliRootRev >= 62714)
704       fMCperiodTPC="LHC13B2_FIXn1";
705   }
706
707   //exception new pp MC productions from 2011
708   if (fBeamType=="PP" && reg.MatchB(fCurrentFile)) { fMCperiodTPC="LHC11B2"; fBeamType="PP"; }
709   // exception for 11f1
710   if (fCurrentFile.Contains("LHC11f1")) fMCperiodTPC="LHC11F1";
711   // exception for 12f1a, 12f1b and 12i3
712   if (fCurrentFile.Contains("LHC12f1") || fCurrentFile.Contains("LHC12i3")) fMCperiodTPC="LHC12F1";
713   // exception for 12c4
714   if (fCurrentFile.Contains("LHC12c4")) fMCperiodTPC="LHC12C4";
715 }
716
717 //______________________________________________________________________________
718 void AliPIDResponse::SetITSParametrisation()
719 {
720   //
721   // Set the ITS parametrisation
722   //
723 }
724
725  
726 //______________________________________________________________________________
727 void AliPIDResponse::AddPointToHyperplane(TH2D* h, TLinearFitter* linExtrapolation, Int_t binX, Int_t binY)
728 {
729   if (h->GetBinContent(binX, binY) <= 1e-4)
730     return; // Reject bins without content (within some numerical precision) or with strange content
731     
732   Double_t coord[2] = {0, 0};
733   coord[0] = h->GetXaxis()->GetBinCenter(binX);
734   coord[1] = h->GetYaxis()->GetBinCenter(binY);
735   Double_t binError = h->GetBinError(binX, binY);
736   if (binError <= 0) {
737     binError = 1000; // Should not happen because bins without content are rejected for the map (TH2D* h)
738     printf("ERROR: This should never happen: Trying to add bin in addPointToHyperplane with error not set....\n");
739   }
740   linExtrapolation->AddPoint(coord, h->GetBinContent(binX, binY, binError));
741 }
742
743
744 //______________________________________________________________________________
745 TH2D* AliPIDResponse::RefineHistoViaLinearInterpolation(TH2D* h, Double_t refineFactorX, Double_t refineFactorY)
746 {
747   if (!h)
748     return 0x0;
749   
750   // Interpolate to finer map
751   TLinearFitter* linExtrapolation = new TLinearFitter(2, "hyp2", "");
752   
753   Double_t upperMapBoundY = h->GetYaxis()->GetBinUpEdge(h->GetYaxis()->GetNbins());
754   Double_t lowerMapBoundY = h->GetYaxis()->GetBinLowEdge(1);
755   Int_t nBinsX = 30;
756   // 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,
757   // scale the number of bins correspondingly
758   Int_t nBinsY = TMath::Nint((upperMapBoundY - lowerMapBoundY) / (0.02 - 0.0016) * 40);
759   Int_t nBinsXrefined = nBinsX * refineFactorX;
760   Int_t nBinsYrefined = nBinsY * refineFactorY; 
761   
762   TH2D* hRefined = new TH2D(Form("%s_refined", h->GetName()),  Form("%s (refined)", h->GetTitle()),
763                             nBinsXrefined, h->GetXaxis()->GetBinLowEdge(1), h->GetXaxis()->GetBinUpEdge(h->GetXaxis()->GetNbins()),
764                             nBinsYrefined, lowerMapBoundY, upperMapBoundY);
765   
766   for (Int_t binX = 1; binX <= nBinsXrefined; binX++)  {
767     for (Int_t binY = 1; binY <= nBinsYrefined; binY++)  {
768       
769       hRefined->SetBinContent(binX, binY, 1); // Default value is 1
770       
771       Double_t centerX = hRefined->GetXaxis()->GetBinCenter(binX);
772       Double_t centerY = hRefined->GetYaxis()->GetBinCenter(binY);
773       
774       /*OLD
775       linExtrapolation->ClearPoints();
776       
777       // For interpolation: Just take the corresponding bin from the old histo.
778       // For extrapolation: take the last available bin from the old histo.
779       // If the boundaries are to be skipped, also skip the corresponding bins
780       Int_t oldBinX = h->GetXaxis()->FindBin(centerX);
781       if (oldBinX < 1)  
782         oldBinX = 1;
783       if (oldBinX > nBinsX)
784         oldBinX = nBinsX;
785       
786       Int_t oldBinY = h->GetYaxis()->FindBin(centerY);
787       if (oldBinY < 1)  
788         oldBinY = 1;
789       if (oldBinY > nBinsY)
790         oldBinY = nBinsY;
791       
792       // Neighbours left column
793       if (oldBinX >= 2) {
794         if (oldBinY >= 2) {
795           AddPointToHyperplane(h, linExtrapolation, oldBinX - 1, oldBinY - 1);
796         }
797         
798         AddPointToHyperplane(h, linExtrapolation, oldBinX - 1, oldBinY);
799         
800         if (oldBinY < nBinsY) {
801           AddPointToHyperplane(h, linExtrapolation, oldBinX - 1, oldBinY + 1);
802         }
803       }
804       
805       // Neighbours (and point itself) same column
806       if (oldBinY >= 2) {
807         AddPointToHyperplane(h, linExtrapolation, oldBinX, oldBinY - 1);
808       }
809         
810       AddPointToHyperplane(h, linExtrapolation, oldBinX, oldBinY);
811         
812       if (oldBinY < nBinsY) {
813         AddPointToHyperplane(h, linExtrapolation, oldBinX, oldBinY + 1);
814       }
815       
816       // Neighbours right column
817       if (oldBinX < nBinsX) {
818         if (oldBinY >= 2) {
819           AddPointToHyperplane(h, linExtrapolation, oldBinX + 1, oldBinY - 1);
820         }
821         
822         AddPointToHyperplane(h, linExtrapolation, oldBinX + 1, oldBinY);
823         
824         if (oldBinY < nBinsY) {
825           AddPointToHyperplane(h, linExtrapolation, oldBinX + 1, oldBinY + 1);
826         }
827       }
828       
829       
830       // Fit 2D-hyperplane
831       if (linExtrapolation->GetNpoints() <= 0)
832         continue;
833         
834       if (linExtrapolation->Eval() != 0)// EvalRobust -> Takes much, much, [...], much more time (~hours instead of seconds)
835         continue;
836       
837       // Fill the bin of the refined histogram with the extrapolated value
838       Double_t interpolatedValue = linExtrapolation->GetParameter(0) + linExtrapolation->GetParameter(1) * centerX
839                                  + linExtrapolation->GetParameter(2) * centerY;
840       */
841       Double_t interpolatedValue = h->Interpolate(centerX, centerY) ;
842       hRefined->SetBinContent(binX, binY, interpolatedValue);      
843     }
844   } 
845   
846   
847   // Problem: Interpolation does not work before/beyond center of first/last bin (as the name suggests).
848   // Therefore, for each row in dEdx: Take last bin from old map and interpolate values from center and edge.
849   // Assume line through these points and extropolate to last bin of refined map
850   const Double_t firstOldXbinUpEdge = h->GetXaxis()->GetBinUpEdge(1);
851   const Double_t firstOldXbinCenter = h->GetXaxis()->GetBinCenter(1);
852   
853   const Double_t oldXbinHalfWidth = firstOldXbinUpEdge - firstOldXbinCenter;
854   
855   const Double_t lastOldXbinLowEdge = h->GetXaxis()->GetBinLowEdge(h->GetNbinsX());
856   const Double_t lastOldXbinCenter = h->GetXaxis()->GetBinCenter(h->GetNbinsX());
857   
858   for (Int_t binY = 1; binY <= nBinsYrefined; binY++)  {
859     Double_t centerY = hRefined->GetYaxis()->GetBinCenter(binY);
860     
861     const Double_t interpolatedCenterFirstXbin = h->Interpolate(firstOldXbinCenter, centerY);
862     const Double_t interpolatedUpEdgeFirstXbin = h->Interpolate(firstOldXbinUpEdge, centerY);
863     
864     const Double_t extrapolationSlopeFirstXbin = (interpolatedUpEdgeFirstXbin - interpolatedCenterFirstXbin) / oldXbinHalfWidth;
865     const Double_t extrapolationOffsetFirstXbin = interpolatedCenterFirstXbin;
866     
867     
868     const Double_t interpolatedCenterLastXbin = h->Interpolate(lastOldXbinCenter, centerY);
869     const Double_t interpolatedLowEdgeLastXbin = h->Interpolate(lastOldXbinLowEdge, centerY);
870     
871     const Double_t extrapolationSlopeLastXbin = (interpolatedCenterLastXbin - interpolatedLowEdgeLastXbin) / oldXbinHalfWidth;
872     const Double_t extrapolationOffsetLastXbin = interpolatedCenterLastXbin;
873
874     for (Int_t binX = 1; binX <= nBinsXrefined; binX++)  {
875       Double_t centerX = hRefined->GetXaxis()->GetBinCenter(binX);
876      
877       if (centerX < firstOldXbinCenter) {
878         Double_t extrapolatedValue = extrapolationOffsetFirstXbin + (centerX - firstOldXbinCenter) * extrapolationSlopeFirstXbin;
879         hRefined->SetBinContent(binX, binY, extrapolatedValue);      
880       }
881       else if (centerX <= lastOldXbinCenter) {
882         continue;
883       }
884       else {
885         Double_t extrapolatedValue = extrapolationOffsetLastXbin + (centerX - lastOldXbinCenter) * extrapolationSlopeLastXbin;
886         hRefined->SetBinContent(binX, binY, extrapolatedValue);     
887       }
888     }
889   } 
890   
891   delete linExtrapolation;
892   
893   return hRefined;
894 }
895
896 //______________________________________________________________________________
897 void AliPIDResponse::SetTPCEtaMaps(Double_t refineFactorMapX, Double_t refineFactorMapY,
898                                    Double_t refineFactorSigmaMapX, Double_t refineFactorSigmaMapY)
899 {
900   //
901   // Load the TPC eta correction maps from the OADB
902   //
903   
904   if (fUseTPCEtaCorrection == kFALSE) {
905     // Disable eta correction via setting no maps
906     if (!fTPCResponse.SetEtaCorrMap(0x0))
907       AliInfo("Request to disable TPC eta correction -> Eta correction has been disabled"); 
908     else
909       AliError("Request to disable TPC eta correction -> Some error occured when unloading the correction maps");
910     
911     if (!fTPCResponse.SetSigmaParams(0x0, 0))
912       AliInfo("Request to disable TPC eta correction -> Using old parametrisation for sigma"); 
913     else
914       AliError("Request to disable TPC eta correction -> Some error occured when unloading the sigma maps");
915     
916     return;
917   }
918   
919   TString dataType = "DATA";
920   TString period = fLHCperiod.IsNull() ? "No period information" : fLHCperiod;
921   
922   if (fIsMC)  {
923     if (!(fTuneMConData && ((fTuneMConDataMask & kDetTPC) == kDetTPC))) {
924       period=fMCperiodTPC;
925       dataType="MC";
926     }
927     fRecoPass = 1;
928     
929     if (!(fTuneMConData && ((fTuneMConDataMask & kDetTPC) == kDetTPC)) && fMCperiodTPC.IsNull()) {
930       AliFatal("MC detected, but no MC period set -> Not changing eta maps!");
931       return;
932     }
933   }
934
935   Int_t recopass = fRecoPass;
936   if (fTuneMConData && ((fTuneMConDataMask & kDetTPC) == kDetTPC) )
937     recopass = fRecoPassUser;
938   
939   TString defaultObj = Form("Default_%s_pass%d", dataType.Data(), recopass);
940   
941   AliInfo(Form("Current period and reco pass: %s.pass%d", period.Data(), recopass));
942   
943   // Invalidate old maps
944   fTPCResponse.SetEtaCorrMap(0x0);
945   fTPCResponse.SetSigmaParams(0x0, 0);
946   
947   // Load the eta correction maps
948   AliOADBContainer etaMapsCont(Form("TPCetaMaps_%s_pass%d", dataType.Data(), recopass)); 
949   
950   Int_t statusCont = etaMapsCont.InitFromFile(Form("%s/COMMON/PID/data/TPCetaMaps.root", fOADBPath.Data()),
951                                               Form("TPCetaMaps_%s_pass%d", dataType.Data(), recopass));
952   if (statusCont) {
953     AliError("Failed initializing TPC eta correction maps from OADB -> Disabled eta correction");
954     fUseTPCEtaCorrection = kFALSE;
955   }
956   else {
957     AliInfo(Form("Loading TPC eta correction map from %s/COMMON/PID/data/TPCetaMaps.root", fOADBPath.Data()));
958     
959     TH2D* etaMap = 0x0;
960     
961     if (fIsMC && !(fTuneMConData && ((fTuneMConDataMask & kDetTPC) == kDetTPC))) {
962       TString searchMap = Form("TPCetaMaps_%s_%s_pass%d", dataType.Data(), period.Data(), recopass);
963       etaMap = dynamic_cast<TH2D *>(etaMapsCont.GetDefaultObject(searchMap.Data()));
964       if (!etaMap) {
965         // Try default object
966         etaMap = dynamic_cast<TH2D *>(etaMapsCont.GetDefaultObject(defaultObj.Data()));
967       }
968     }
969     else {
970       etaMap = dynamic_cast<TH2D *>(etaMapsCont.GetObject(fRun, defaultObj.Data()));
971     }
972     
973         
974     if (!etaMap) {
975       AliError(Form("TPC eta correction map not found for run %d and also no default map found -> Disabled eta correction!!!", fRun));
976       fUseTPCEtaCorrection = kFALSE;
977     }
978     else {
979       TH2D* etaMapRefined = RefineHistoViaLinearInterpolation(etaMap, refineFactorMapX, refineFactorMapY);
980       
981       if (etaMapRefined) {
982         if (!fTPCResponse.SetEtaCorrMap(etaMapRefined)) {
983           AliError(Form("Failed to set TPC eta correction map for run %d -> Disabled eta correction!!!", fRun));
984           fTPCResponse.SetEtaCorrMap(0x0);
985           fUseTPCEtaCorrection = kFALSE;
986         }
987         else {
988           AliInfo(Form("Loaded TPC eta correction map (refine factors %.2f/%.2f) from %s/COMMON/PID/data/TPCetaMaps.root: %s", 
989                        refineFactorMapX, refineFactorMapY, fOADBPath.Data(), fTPCResponse.GetEtaCorrMap()->GetTitle()));
990         }
991         
992         delete etaMapRefined;
993       }
994       else {
995         AliError(Form("Failed to set TPC eta correction map for run %d (map was loaded, but couldn't be refined) -> Disabled eta correction!!!", fRun));
996         fUseTPCEtaCorrection = kFALSE;
997       }
998     }
999   }
1000   
1001   // If there was some problem loading the eta maps, it makes no sense to load the sigma maps (that require eta corrected data)
1002   if (fUseTPCEtaCorrection == kFALSE) {
1003     AliError("Failed to load TPC eta correction map required by sigma maps -> Using old parametrisation for sigma"); 
1004     return;
1005   }
1006   
1007   // Load the sigma parametrisation (1/dEdx vs tanTheta_local (~eta))
1008   AliOADBContainer etaSigmaMapsCont(Form("TPCetaSigmaMaps_%s_pass%d", dataType.Data(), recopass)); 
1009   
1010   statusCont = etaSigmaMapsCont.InitFromFile(Form("%s/COMMON/PID/data/TPCetaMaps.root", fOADBPath.Data()),
1011                                              Form("TPCetaSigmaMaps_%s_pass%d", dataType.Data(), recopass));
1012   if (statusCont) {
1013     AliError("Failed initializing TPC eta sigma maps from OADB -> Using old sigma parametrisation");
1014   }
1015   else {
1016     AliInfo(Form("Loading TPC eta sigma map from %s/COMMON/PID/data/TPCetaMaps.root", fOADBPath.Data()));
1017     
1018     TObjArray* etaSigmaPars = 0x0;
1019     
1020     if (fIsMC && !(fTuneMConData && ((fTuneMConDataMask & kDetTPC) == kDetTPC))) {
1021       TString searchMap = Form("TPCetaSigmaMaps_%s_%s_pass%d", dataType.Data(), period.Data(), recopass);
1022       etaSigmaPars = dynamic_cast<TObjArray *>(etaSigmaMapsCont.GetDefaultObject(searchMap.Data()));
1023       if (!etaSigmaPars) {
1024         // Try default object
1025         etaSigmaPars = dynamic_cast<TObjArray *>(etaSigmaMapsCont.GetDefaultObject(defaultObj.Data()));
1026       }
1027     }
1028     else {
1029       etaSigmaPars = dynamic_cast<TObjArray *>(etaSigmaMapsCont.GetObject(fRun, defaultObj.Data()));
1030     }
1031     
1032     if (!etaSigmaPars) {
1033       AliError(Form("TPC eta sigma parametrisation not found for run %d -> Using old sigma parametrisation!!!", fRun));
1034     }
1035     else {
1036       TH2D* etaSigmaPar1Map = dynamic_cast<TH2D *>(etaSigmaPars->FindObject("sigmaPar1Map"));
1037       TNamed* sigmaPar0Info = dynamic_cast<TNamed *>(etaSigmaPars->FindObject("sigmaPar0"));
1038       Double_t sigmaPar0 = 0.0;
1039       
1040       if (sigmaPar0Info) {
1041         TString sigmaPar0String = sigmaPar0Info->GetTitle();
1042         sigmaPar0 = sigmaPar0String.Atof();
1043       }
1044       else {
1045         // Something is weired because the object for parameter 0 could not be loaded -> New sigma parametrisation can not be used!
1046         etaSigmaPar1Map = 0x0;
1047       }
1048       
1049       TH2D* etaSigmaPar1MapRefined = RefineHistoViaLinearInterpolation(etaSigmaPar1Map, refineFactorSigmaMapX, refineFactorSigmaMapY);
1050       
1051       
1052       if (etaSigmaPar1MapRefined) {
1053         if (!fTPCResponse.SetSigmaParams(etaSigmaPar1MapRefined, sigmaPar0)) {
1054           AliError(Form("Failed to set TPC eta sigma map for run %d -> Using old sigma parametrisation!!!", fRun));
1055           fTPCResponse.SetSigmaParams(0x0, 0);
1056         }
1057         else {
1058           AliInfo(Form("Loaded TPC sigma correction map (refine factors %.2f/%.2f) from %s/COMMON/PID/data/TPCetaMaps.root: %s", 
1059                        refineFactorSigmaMapX, refineFactorSigmaMapY, fOADBPath.Data(), fTPCResponse.GetSigmaPar1Map()->GetTitle()));
1060         }
1061         
1062         delete etaSigmaPar1MapRefined;
1063       }
1064       else {
1065         AliError(Form("Failed to set TPC eta sigma map for run %d (map was loaded, but couldn't be refined) -> Using old sigma parametrisation!!!",
1066                       fRun));
1067       }
1068     }
1069   }
1070 }
1071
1072 //______________________________________________________________________________
1073 void AliPIDResponse::SetTPCPidResponseMaster()
1074 {
1075   //
1076   // Load the TPC pid response functions from the OADB
1077   // Load the TPC voltage maps from OADB
1078   //
1079   //don't load twice for the moment
1080    if (fArrPidResponseMaster) return;
1081  
1082
1083   //reset the PID response functions
1084   delete fArrPidResponseMaster;
1085   fArrPidResponseMaster=NULL;
1086   
1087   TString fileName(Form("%s/COMMON/PID/data/TPCPIDResponse.root", fOADBPath.Data()));
1088   TFile *f=NULL;
1089   if (!fCustomTPCpidResponse.IsNull()) fileName=fCustomTPCpidResponse;
1090   
1091   TString fileNamePIDresponse(Form("%s/COMMON/PID/data/TPCPIDResponse.root", fOADBPath.Data()));
1092   f=TFile::Open(fileNamePIDresponse.Data());
1093   if (f && f->IsOpen() && !f->IsZombie()){
1094     fArrPidResponseMaster=dynamic_cast<TObjArray*>(f->Get("TPCPIDResponse"));
1095   }
1096   delete f;
1097
1098   TString fileNameVoltageMaps(Form("%s/COMMON/PID/data/TPCvoltageSettings.root", fOADBPath.Data()));
1099   f=TFile::Open(fileNameVoltageMaps.Data());
1100   if (f && f->IsOpen() && !f->IsZombie()){
1101     fOADBvoltageMaps=dynamic_cast<AliOADBContainer*>(f->Get("TPCvoltageSettings"));
1102   }
1103   delete f;
1104   
1105   if (!fArrPidResponseMaster){
1106     AliFatal(Form("Could not retrieve the TPC pid response from: %s",fileNamePIDresponse.Data()));
1107     return;
1108   }
1109   fArrPidResponseMaster->SetOwner();
1110
1111   if (!fOADBvoltageMaps)
1112   {
1113     AliFatal(Form("Could not retrieve the TPC voltage maps from: %s",fileNameVoltageMaps.Data()));
1114   }
1115   fArrPidResponseMaster->SetOwner();
1116 }
1117
1118 //______________________________________________________________________________
1119 void AliPIDResponse::SetTPCParametrisation()
1120 {
1121   //
1122   // Change BB parametrisation for current run
1123   //
1124   
1125   //
1126   //reset old splines
1127   //
1128   fTPCResponse.ResetSplines();
1129   
1130   if (fLHCperiod.IsNull()) {
1131     AliError("No period set, not changing parametrisation");
1132     return;
1133   }
1134   
1135   //
1136   // Set default parametrisations for data and MC
1137   //
1138   
1139   //data type
1140   TString datatype="DATA";
1141   //in case of mc fRecoPass is per default 1
1142   if (fIsMC) {
1143       if(!(fTuneMConData && ((fTuneMConDataMask & kDetTPC) == kDetTPC))) datatype="MC";
1144       fRecoPass=1;
1145   }
1146
1147   // period
1148   TString period=fLHCperiod;
1149   if (fIsMC && !(fTuneMConData && ((fTuneMConDataMask & kDetTPC) == kDetTPC))) period=fMCperiodTPC;
1150
1151   Int_t recopass = fRecoPass;
1152   if(fTuneMConData && ((fTuneMConDataMask & kDetTPC) == kDetTPC)) recopass = fRecoPassUser;
1153     
1154   AliInfo(Form("Searching splines for: %s %s PASS%d %s",datatype.Data(),period.Data(),recopass,fBeamType.Data()));
1155   Bool_t found=kFALSE;
1156   //
1157   //set the new PID splines
1158   //
1159   if (fArrPidResponseMaster){
1160     //for MC don't use period information
1161     //if (fIsMC) period="[A-Z0-9]*";
1162     //for MC use MC period information
1163     //pattern for the default entry (valid for all particles)
1164     TPRegexp reg(Form("TSPLINE3_%s_([A-Z]*)_%s_PASS%d_%s_MEAN(_*)([A-Z1-9]*)",datatype.Data(),period.Data(),recopass,fBeamType.Data()));
1165
1166     //find particle id and gain scenario
1167     for (Int_t igainScenario=0; igainScenario<AliTPCPIDResponse::fgkNumberOfGainScenarios; igainScenario++)
1168     {
1169       TObject *grAll=NULL;
1170       TString gainScenario = AliTPCPIDResponse::GainScenarioName(igainScenario);
1171       gainScenario.ToUpper();
1172       //loop over entries and filter them
1173       for (Int_t iresp=0; iresp<fArrPidResponseMaster->GetEntriesFast();++iresp)
1174       {
1175         TObject *responseFunction=fArrPidResponseMaster->At(iresp);
1176         if (responseFunction==NULL) continue;
1177         TString responseName=responseFunction->GetName();
1178          
1179         if (!reg.MatchB(responseName)) continue;
1180
1181         TObjArray *arr=reg.MatchS(responseName); if (!arr) continue;
1182         TObject* tmp=NULL;
1183         tmp=arr->At(1); if (!tmp) continue;
1184         TString particleName=tmp->GetName();
1185         tmp=arr->At(3); if (!tmp) continue;
1186         TString gainScenarioName=tmp->GetName();
1187         delete arr;
1188         if (particleName.IsNull()) continue;
1189         if (!grAll && particleName=="ALL" && gainScenarioName==gainScenario) grAll=responseFunction;
1190         else 
1191         {
1192           for (Int_t ispec=0; ispec<(AliTPCPIDResponse::fgkNumberOfParticleSpecies); ++ispec)
1193           {
1194             TString particle=AliPID::ParticleName(ispec);
1195             particle.ToUpper();
1196             //std::cout<<responseName<<" "<<particle<<" "<<particleName<<" "<<gainScenario<<" "<<gainScenarioName<<std::endl;
1197             if ( particle == particleName && gainScenario == gainScenarioName )
1198             {
1199               fTPCResponse.SetResponseFunction( responseFunction,
1200                                                 (AliPID::EParticleType)ispec,
1201                                                 (AliTPCPIDResponse::ETPCgainScenario)igainScenario );
1202               fTPCResponse.SetUseDatabase(kTRUE);
1203               AliInfo(Form("Adding graph: %d %d - %s",ispec,igainScenario,responseFunction->GetName()));
1204               found=kTRUE;
1205               break;
1206             }
1207           }
1208         }
1209       }
1210       
1211       // Retrieve responsefunction for pions - will (if available) be used for muons if there are no dedicated muon splines.
1212       // For light nuclei, try to set the proton spline, if no dedicated splines are available.
1213       // In both cases: Use default splines, if no dedicated splines and no pion/proton splines are available.
1214       TObject* responseFunctionPion = fTPCResponse.GetResponseFunction( (AliPID::EParticleType)AliPID::kPion,                             
1215                                                                         (AliTPCPIDResponse::ETPCgainScenario)igainScenario);
1216       TObject* responseFunctionProton = fTPCResponse.GetResponseFunction( (AliPID::EParticleType)AliPID::kProton,                             
1217                                                                           (AliTPCPIDResponse::ETPCgainScenario)igainScenario);
1218       
1219       for (Int_t ispec=0; ispec<(AliTPCPIDResponse::fgkNumberOfParticleSpecies); ++ispec)
1220       {
1221         if (!fTPCResponse.GetResponseFunction( (AliPID::EParticleType)ispec,
1222           (AliTPCPIDResponse::ETPCgainScenario)igainScenario))
1223         {
1224           if (ispec == AliPID::kMuon) { // Muons
1225             if (responseFunctionPion) {
1226               fTPCResponse.SetResponseFunction( responseFunctionPion,
1227                                                 (AliPID::EParticleType)ispec,
1228                                                 (AliTPCPIDResponse::ETPCgainScenario)igainScenario );
1229               fTPCResponse.SetUseDatabase(kTRUE);
1230               AliInfo(Form("Adding graph: %d %d - %s",ispec,igainScenario,responseFunctionPion->GetName()));
1231               found=kTRUE;  
1232             }
1233             else if (grAll) {
1234               fTPCResponse.SetResponseFunction( grAll,
1235                                                 (AliPID::EParticleType)ispec,
1236                                                 (AliTPCPIDResponse::ETPCgainScenario)igainScenario );
1237               fTPCResponse.SetUseDatabase(kTRUE);
1238               AliInfo(Form("Adding graph: %d %d - %s",ispec,igainScenario,grAll->GetName()));
1239               found=kTRUE;
1240             }
1241             //else
1242             //  AliError(Form("No splines found for muons (also no pion splines and no default splines) for gain scenario %d!", igainScenario));
1243           }
1244           else if (ispec >= AliPID::kSPECIES) { // Light nuclei
1245             if (responseFunctionProton) {
1246               fTPCResponse.SetResponseFunction( responseFunctionProton,
1247                                                 (AliPID::EParticleType)ispec,
1248                                                 (AliTPCPIDResponse::ETPCgainScenario)igainScenario );
1249               fTPCResponse.SetUseDatabase(kTRUE);
1250               AliInfo(Form("Adding graph: %d %d - %s",ispec,igainScenario,responseFunctionProton->GetName()));
1251               found=kTRUE;  
1252             }
1253             else if (grAll) {
1254               fTPCResponse.SetResponseFunction( grAll,
1255                                                 (AliPID::EParticleType)ispec,
1256                                                 (AliTPCPIDResponse::ETPCgainScenario)igainScenario );
1257               fTPCResponse.SetUseDatabase(kTRUE);
1258               AliInfo(Form("Adding graph: %d %d - %s",ispec,igainScenario,grAll->GetName()));
1259               found=kTRUE;
1260             }
1261             //else
1262             //  AliError(Form("No splines found for species %d (also no proton splines and no default splines) for gain scenario %d!",
1263             //                ispec, igainScenario));
1264           }
1265         }
1266       }
1267     }
1268   }
1269   else AliInfo("no fArrPidResponseMaster");
1270
1271   if (!found){
1272     AliError(Form("No splines found for: %s %s PASS%d %s",datatype.Data(),period.Data(),recopass,fBeamType.Data()));
1273   }
1274
1275
1276   //
1277   // Setup multiplicity correction
1278   //
1279   if (fUseTPCMultiplicityCorrection && !(fBeamType.CompareTo("PP") == 0)) {
1280     AliInfo("Multiplicity correction enabled!");
1281     
1282     //TODO After testing, load parameters from outside       
1283     /*TODO now correction for MC
1284     if (period.Contains("LHC11A10"))  {//LHC11A10A
1285       AliInfo("Using multiplicity correction parameters for 11a10!");
1286       fTPCResponse.SetParameterMultiplicityCorrection(0, 6.90133e-06);
1287       fTPCResponse.SetParameterMultiplicityCorrection(1, -1.22123e-03);
1288       fTPCResponse.SetParameterMultiplicityCorrection(2, 1.80220e-02);
1289       fTPCResponse.SetParameterMultiplicityCorrection(3, 0.1);
1290       fTPCResponse.SetParameterMultiplicityCorrection(4, 6.45306e-03);
1291       
1292       fTPCResponse.SetParameterMultiplicityCorrectionTanTheta(0, -2.85505e-07);
1293       fTPCResponse.SetParameterMultiplicityCorrectionTanTheta(1, -1.31911e-06);
1294       fTPCResponse.SetParameterMultiplicityCorrectionTanTheta(2, -0.5);
1295
1296       fTPCResponse.SetParameterMultiplicitySigmaCorrection(0, -4.29665e-05);
1297       fTPCResponse.SetParameterMultiplicitySigmaCorrection(1, 1.37023e-02);
1298       fTPCResponse.SetParameterMultiplicitySigmaCorrection(2, -6.36337e-01);
1299       fTPCResponse.SetParameterMultiplicitySigmaCorrection(3, 1.13479e-02);
1300     }
1301     else*/ if (period.Contains("LHC13B") || period.Contains("LHC13C") || period.Contains("LHC13D") || period.Contains("LHC13E") || 
1302              period.Contains("LHC13F"))  {// 2013 pPb data taking
1303       AliInfo("Using multiplicity correction parameters for 13b.pass2!");
1304       
1305       fTPCResponse.SetParameterMultiplicityCorrection(0, -5.906e-06);
1306       fTPCResponse.SetParameterMultiplicityCorrection(1, -5.064e-04);
1307       fTPCResponse.SetParameterMultiplicityCorrection(2, -3.521e-02);
1308       fTPCResponse.SetParameterMultiplicityCorrection(3, 2.469e-02);
1309       fTPCResponse.SetParameterMultiplicityCorrection(4, 0);
1310       
1311       fTPCResponse.SetParameterMultiplicityCorrectionTanTheta(0, -5.32e-06);
1312       fTPCResponse.SetParameterMultiplicityCorrectionTanTheta(1, 1.177e-05);
1313       fTPCResponse.SetParameterMultiplicityCorrectionTanTheta(2, -0.5);
1314       
1315       fTPCResponse.SetParameterMultiplicitySigmaCorrection(0, 0.);
1316       fTPCResponse.SetParameterMultiplicitySigmaCorrection(1, 0.);
1317       fTPCResponse.SetParameterMultiplicitySigmaCorrection(2, 0.);
1318       fTPCResponse.SetParameterMultiplicitySigmaCorrection(3, 0.);
1319       
1320       /* Not too bad, but far from perfect in the details
1321       fTPCResponse.SetParameterMultiplicityCorrection(0, -6.27187e-06);
1322       fTPCResponse.SetParameterMultiplicityCorrection(1, -4.60649e-04);
1323       fTPCResponse.SetParameterMultiplicityCorrection(2, -4.26450e-02);
1324       fTPCResponse.SetParameterMultiplicityCorrection(3, 2.40590e-02);
1325       fTPCResponse.SetParameterMultiplicityCorrection(4, 0);
1326       
1327       fTPCResponse.SetParameterMultiplicityCorrectionTanTheta(0, -5.338e-06);
1328       fTPCResponse.SetParameterMultiplicityCorrectionTanTheta(1, 1.220e-05);
1329       fTPCResponse.SetParameterMultiplicityCorrectionTanTheta(2, -0.5);
1330       
1331       fTPCResponse.SetParameterMultiplicitySigmaCorrection(0, 7.89237e-05);
1332       fTPCResponse.SetParameterMultiplicitySigmaCorrection(1, -1.30662e-02);
1333       fTPCResponse.SetParameterMultiplicitySigmaCorrection(2, 8.91548e-01);
1334       fTPCResponse.SetParameterMultiplicitySigmaCorrection(3, 1.47931e-02);
1335       */
1336     }
1337     else if (period.Contains("LHC10H") && recopass == 2) {    
1338       AliInfo("Using multiplicity correction parameters for 10h.pass2!");
1339       fTPCResponse.SetParameterMultiplicityCorrection(0, 3.21636e-07);
1340       fTPCResponse.SetParameterMultiplicityCorrection(1, -6.65876e-04);
1341       fTPCResponse.SetParameterMultiplicityCorrection(2, 1.28786e-03);
1342       fTPCResponse.SetParameterMultiplicityCorrection(3, 1.47677e-02);
1343       fTPCResponse.SetParameterMultiplicityCorrection(4, 0);
1344       
1345       fTPCResponse.SetParameterMultiplicityCorrectionTanTheta(0, 7.23591e-08);
1346       fTPCResponse.SetParameterMultiplicityCorrectionTanTheta(1, 2.7469e-06);
1347       fTPCResponse.SetParameterMultiplicityCorrectionTanTheta(2, -0.5);
1348       
1349       fTPCResponse.SetParameterMultiplicitySigmaCorrection(0, -1.22590e-05);
1350       fTPCResponse.SetParameterMultiplicitySigmaCorrection(1, 6.88888e-03);
1351       fTPCResponse.SetParameterMultiplicitySigmaCorrection(2, -3.20788e-01);
1352       fTPCResponse.SetParameterMultiplicitySigmaCorrection(3, 1.07345e-02);
1353     }
1354     else {
1355       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));
1356       fUseTPCMultiplicityCorrection = kFALSE;
1357       fTPCResponse.ResetMultiplicityCorrectionFunctions();
1358     }
1359   }
1360   else {
1361     // Just set parameters such that overall correction factor is 1, i.e. no correction.
1362     // This is just a reasonable choice for the parameters for safety reasons. Disabling
1363     // the multiplicity correction will anyhow skip the calculation of the corresponding
1364     // correction factor inside THIS class. Nevertheless, experts can access the TPCPIDResponse
1365     // directly and use it for calculations - which should still give valid results, even if
1366     // the multiplicity correction is explicitely enabled in such expert calls.
1367     
1368     AliInfo(Form("Multiplicity correction %sdisabled (%s)!", fUseTPCMultiplicityCorrection ? "automatically " : "",
1369                  fUseTPCMultiplicityCorrection ? "pp collisions" : "requested by user"));
1370     
1371     fUseTPCMultiplicityCorrection = kFALSE;
1372     fTPCResponse.ResetMultiplicityCorrectionFunctions();
1373   }
1374   
1375   /*
1376   //TODO NOW start
1377   for (Int_t i = 0; i <= 4 + 1; i++) {
1378     printf("parMultCorr: %d, %e\n", i, fTPCResponse.GetMultiplicityCorrectionFunction()->GetParameter(i));
1379   }
1380   for (Int_t j = 0; j <= 2 + 1; j++) {
1381     printf("parMultCorrTanTheta: %d, %e\n", j, fTPCResponse.GetMultiplicityCorrectionFunctionTanTheta()->GetParameter(j));
1382   }
1383   for (Int_t j = 0; j <= 3 + 1; j++) {
1384     printf("parMultSigmaCorr: %d, %e\n", j, fTPCResponse.GetMultiplicitySigmaCorrectionFunction()->GetParameter(j));
1385   }
1386   
1387   //TODO NOW end
1388   */
1389   
1390   //
1391   // Setup old resolution parametrisation
1392   //
1393   
1394   //default
1395   fTPCResponse.SetSigma(3.79301e-03, 2.21280e+04);
1396   
1397   if (fRun>=122195){
1398     fTPCResponse.SetSigma(2.30176e-02, 5.60422e+02);
1399   }
1400
1401   if (fRun>=186636){
1402 //   if (fRun>=188356){
1403     fTPCResponse.SetSigma(8.62022e-04, 9.08156e+05);
1404   }
1405   
1406   if (fArrPidResponseMaster)
1407   fResolutionCorrection=(TF1*)fArrPidResponseMaster->FindObject(Form("TF1_%s_ALL_%s_PASS%d_%s_SIGMA",datatype.Data(),period.Data(),recopass,fBeamType.Data()));
1408   
1409   if (fResolutionCorrection) AliInfo(Form("Setting multiplicity correction function: %s",fResolutionCorrection->GetName()));
1410
1411   //read in the voltage map
1412   TVectorF* gsm = 0x0;
1413   if (fOADBvoltageMaps) gsm=dynamic_cast<TVectorF*>(fOADBvoltageMaps->GetObject(fRun));
1414   if (gsm) 
1415   {
1416     fTPCResponse.SetVoltageMap(*gsm);
1417     TString vals;
1418     AliInfo(Form("Reading the voltage map for run %d\n",fRun));
1419     vals="IROC A: "; for (Int_t i=0; i<18; i++){vals+=Form("%.2f ",(*gsm)[i]);}
1420     AliInfo(vals.Data());
1421     vals="IROC C: "; for (Int_t i=18; i<36; i++){vals+=Form("%.2f ",(*gsm)[i]);}
1422     AliInfo(vals.Data());
1423     vals="OROC A: "; for (Int_t i=36; i<54; i++){vals+=Form("%.2f ",(*gsm)[i]);}
1424     AliInfo(vals.Data());
1425     vals="OROC C: "; for (Int_t i=54; i<72; i++){vals+=Form("%.2f ",(*gsm)[i]);}
1426     AliInfo(vals.Data());
1427   }
1428   else AliInfo("no voltage map, ideal default assumed");
1429 }
1430
1431 //______________________________________________________________________________
1432 void AliPIDResponse::SetTRDPidResponseMaster()
1433 {
1434   //
1435   // Load the TRD pid params and references from the OADB
1436   //
1437   if(fTRDPIDResponseObject) return;
1438   AliOADBContainer contParams("contParams"); 
1439
1440   Int_t statusResponse = contParams.InitFromFile(Form("%s/COMMON/PID/data/TRDPIDResponse.root", fOADBPath.Data()), "AliTRDPIDResponseObject");
1441   if(statusResponse){
1442     AliError("Failed initializing PID Response Object from OADB");
1443   } else {
1444     AliInfo(Form("Loading TRD Response from %s/COMMON/PID/data/TRDPIDResponse.root", fOADBPath.Data()));
1445     fTRDPIDResponseObject = dynamic_cast<AliTRDPIDResponseObject *>(contParams.GetObject(fRun));
1446     if(!fTRDPIDResponseObject){
1447       AliError(Form("TRD Response not found in run %d", fRun));
1448     }
1449   }
1450 }
1451
1452 //______________________________________________________________________________
1453 void AliPIDResponse::InitializeTRDResponse(){
1454   //
1455   // Set PID Params and references to the TRD PID response
1456   // 
1457     fTRDResponse.SetPIDResponseObject(fTRDPIDResponseObject);
1458 }
1459
1460 //______________________________________________________________________________
1461 void AliPIDResponse::SetTRDSlices(UInt_t TRDslicesForPID[2],AliTRDPIDResponse::ETRDPIDMethod method) const{
1462
1463     if(fLHCperiod.Contains("LHC10D") || fLHCperiod.Contains("LHC10E")){
1464         // backward compatibility for setting with 8 slices
1465         TRDslicesForPID[0] = 0;
1466         TRDslicesForPID[1] = 7;
1467     }
1468     else{
1469         if(method==AliTRDPIDResponse::kLQ1D){
1470             TRDslicesForPID[0] = 0; // first Slice contains normalized dEdx
1471             TRDslicesForPID[1] = 0;
1472         }
1473         if(method==AliTRDPIDResponse::kLQ2D){
1474             TRDslicesForPID[0] = 1;
1475             TRDslicesForPID[1] = 7;
1476         }
1477     }
1478     AliDebug(1,Form("Slice Range set to %d - %d",TRDslicesForPID[0],TRDslicesForPID[1]));
1479 }
1480
1481 //______________________________________________________________________________
1482 void AliPIDResponse::SetTOFPidResponseMaster()
1483 {
1484   //
1485   // Load the TOF pid params from the OADB
1486   //
1487
1488   if (fTOFPIDParams) delete fTOFPIDParams;
1489   fTOFPIDParams=NULL;
1490
1491   TFile *oadbf = new TFile(Form("%s/COMMON/PID/data/TOFPIDParams.root",fOADBPath.Data()));
1492   if (oadbf && oadbf->IsOpen()) {
1493     AliInfo(Form("Loading TOF Params from %s/COMMON/PID/data/TOFPIDParams.root", fOADBPath.Data()));
1494     AliOADBContainer *oadbc = (AliOADBContainer *)oadbf->Get("TOFoadb");
1495     if (oadbc) fTOFPIDParams = dynamic_cast<AliTOFPIDParams *>(oadbc->GetObject(fRun,"TOFparams"));
1496     oadbf->Close();
1497     delete oadbc;
1498   }
1499   delete oadbf;
1500
1501   if (!fTOFPIDParams) AliFatal("TOFPIDParams could not be retrieved");
1502 }
1503
1504 //______________________________________________________________________________
1505 void AliPIDResponse::InitializeTOFResponse(){
1506   //
1507   // Set PID Params to the TOF PID response
1508   //
1509
1510   AliInfo("TOF PID Params loaded from OADB");
1511   AliInfo(Form("  TOF resolution %5.2f [ps]",fTOFPIDParams->GetTOFresolution()));
1512   AliInfo(Form("  StartTime method %d",fTOFPIDParams->GetStartTimeMethod()));
1513   AliInfo(Form("  TOF res. mom. params: %5.2f %5.2f %5.2f %5.2f",
1514                fTOFPIDParams->GetSigParams(0),fTOFPIDParams->GetSigParams(1),fTOFPIDParams->GetSigParams(2),fTOFPIDParams->GetSigParams(3)));
1515   
1516   for (Int_t i=0;i<4;i++) {
1517     fTOFResponse.SetTrackParameter(i,fTOFPIDParams->GetSigParams(i));
1518   }
1519   fTOFResponse.SetTimeResolution(fTOFPIDParams->GetTOFresolution());
1520
1521   AliInfo("TZERO resolution loaded from ESDrun/AODheader");
1522   Float_t t0Spread[4];
1523   for (Int_t i=0;i<4;i++) t0Spread[i]=fCurrentEvent->GetT0spread(i);
1524   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]));
1525   Float_t a = t0Spread[1]*t0Spread[1]-t0Spread[0]*t0Spread[0]+t0Spread[3]*t0Spread[3];
1526   Float_t c = t0Spread[2]*t0Spread[2]-t0Spread[0]*t0Spread[0]+t0Spread[3]*t0Spread[3];
1527   if ( (t0Spread[0] > 50. && t0Spread[0] < 400.) && (a > 0.) && (c>0.)) {
1528     fResT0AC=t0Spread[3];
1529     fResT0A=TMath::Sqrt(a);
1530     fResT0C=TMath::Sqrt(c);
1531   } else {
1532     AliInfo("  TZERO spreads not present or inconsistent, loading default");
1533     fResT0A=75.;
1534     fResT0C=65.;
1535     fResT0AC=55.;
1536   }
1537   AliInfo(Form("  TZERO resolution set to: T0A: %f [ps] T0C: %f [ps] T0AC %f [ps]",fResT0A,fResT0C,fResT0AC));
1538
1539 }
1540
1541 //______________________________________________________________________________
1542 void AliPIDResponse::SetHMPIDPidResponseMaster()
1543 {
1544   //
1545   // Load the HMPID pid params from the OADB
1546   //
1547
1548   if (fHMPIDPIDParams) delete fHMPIDPIDParams;
1549   fHMPIDPIDParams=NULL;
1550
1551   TFile *oadbf = new TFile(Form("%s/COMMON/PID/data/HMPIDPIDParams.root",fOADBPath.Data()));
1552   if (oadbf && oadbf->IsOpen()) {
1553     AliInfo(Form("Loading HMPID Params from %s/COMMON/PID/data/HMPIDPIDParams.root", fOADBPath.Data()));
1554     AliOADBContainer *oadbc = (AliOADBContainer *)oadbf->Get("HMPoadb");
1555     if (oadbc) fHMPIDPIDParams = dynamic_cast<AliHMPIDPIDParams *>(oadbc->GetObject(fRun,"HMPparams"));
1556     oadbf->Close();
1557     delete oadbc;
1558   }
1559   delete oadbf;
1560
1561   if (!fHMPIDPIDParams) AliFatal("HMPIDPIDParams could not be retrieved");
1562 }
1563
1564 //______________________________________________________________________________
1565 void AliPIDResponse::InitializeHMPIDResponse(){
1566   //
1567   // Set PID Params to the HMPID PID response
1568   //
1569
1570   fHMPIDResponse.SetRefIndexArray(fHMPIDPIDParams->GetHMPIDrefIndex());
1571 }
1572
1573 //______________________________________________________________________________
1574 Bool_t AliPIDResponse::IdentifiedAsElectronTRD(const AliVTrack *vtrack, Double_t efficiencyLevel,Double_t centrality,AliTRDPIDResponse::ETRDPIDMethod PIDmethod) const {
1575   //
1576   // Check whether track is identified as electron under a given electron efficiency hypothesis
1577     //
1578
1579   Double_t probs[AliPID::kSPECIES];
1580   ComputeTRDProbability(vtrack, AliPID::kSPECIES, probs,PIDmethod);
1581
1582   Int_t ntracklets = vtrack->GetTRDntrackletsPID();
1583   // Take mean of the TRD momenta in the given tracklets
1584   Float_t p = 0, trdmomenta[AliVTrack::kTRDnPlanes];
1585   Int_t nmomenta = 0;
1586   for(Int_t iPl=0;iPl<AliVTrack::kTRDnPlanes;iPl++){
1587     if(vtrack->GetTRDmomentum(iPl) > 0.){
1588       trdmomenta[nmomenta++] = vtrack->GetTRDmomentum(iPl); 
1589     }
1590   }
1591   p = TMath::Mean(nmomenta, trdmomenta);
1592
1593   return fTRDResponse.IdentifiedAsElectron(ntracklets, probs, p, efficiencyLevel,centrality,PIDmethod);
1594 }
1595
1596 //______________________________________________________________________________
1597 void AliPIDResponse::SetEMCALPidResponseMaster()
1598 {
1599   //
1600   // Load the EMCAL pid response functions from the OADB
1601   //
1602   TObjArray* fEMCALPIDParamsRun      = NULL;
1603   TObjArray* fEMCALPIDParamsPass     = NULL;
1604
1605   if(fEMCALPIDParams) return;
1606   AliOADBContainer contParams("contParams"); 
1607
1608   Int_t statusPars = contParams.InitFromFile(Form("%s/COMMON/PID/data/EMCALPIDParams.root", fOADBPath.Data()), "AliEMCALPIDParams");
1609   if(statusPars){
1610     AliError("Failed initializing PID Params from OADB");
1611   } 
1612   else {
1613     AliInfo(Form("Loading EMCAL Params from %s/COMMON/PID/data/EMCALPIDParams.root", fOADBPath.Data()));
1614
1615     fEMCALPIDParamsRun = dynamic_cast<TObjArray *>(contParams.GetObject(fRun));
1616     if(fEMCALPIDParamsRun)  fEMCALPIDParamsPass = dynamic_cast<TObjArray *>(fEMCALPIDParamsRun->FindObject(Form("pass%d",fRecoPass)));
1617     if(fEMCALPIDParamsPass) fEMCALPIDParams     = dynamic_cast<TObjArray *>(fEMCALPIDParamsPass->FindObject(Form("EMCALPIDParams_Particles")));
1618
1619     if(!fEMCALPIDParams){
1620       AliInfo(Form("EMCAL Params not found in run %d pass %d", fRun, fRecoPass));
1621       AliInfo("Will take the standard LHC11d instead ...");
1622
1623       fEMCALPIDParamsRun = dynamic_cast<TObjArray *>(contParams.GetObject(156477));
1624       if(fEMCALPIDParamsRun)  fEMCALPIDParamsPass = dynamic_cast<TObjArray *>(fEMCALPIDParamsRun->FindObject(Form("pass%d",1)));
1625       if(fEMCALPIDParamsPass) fEMCALPIDParams     = dynamic_cast<TObjArray *>(fEMCALPIDParamsPass->FindObject(Form("EMCALPIDParams_Particles")));
1626
1627       if(!fEMCALPIDParams){
1628         AliError(Form("DEFAULT EMCAL Params (LHC11d) not found in file %s/COMMON/PID/data/EMCALPIDParams.root", fOADBPath.Data()));     
1629       }
1630     }
1631   }
1632 }
1633
1634 //______________________________________________________________________________
1635 void AliPIDResponse::InitializeEMCALResponse(){
1636   //
1637   // Set PID Params to the EMCAL PID response
1638   // 
1639   fEMCALResponse.SetPIDParams(fEMCALPIDParams);
1640
1641 }
1642
1643 //______________________________________________________________________________
1644 void AliPIDResponse::FillTrackDetectorPID(const AliVTrack *track, EDetector detector) const
1645 {
1646   //
1647   // create detector PID information and setup the transient pointer in the track
1648   //
1649   
1650   // check if detector number is inside accepted range
1651   if (detector == kNdetectors) return;
1652   
1653   // get detector pid
1654   AliDetectorPID *detPID=const_cast<AliDetectorPID*>(track->GetDetectorPID());
1655   if (!detPID) {
1656     detPID=new AliDetectorPID;
1657     (const_cast<AliVTrack*>(track))->SetDetectorPID(detPID);
1658   }
1659   
1660   //check if values exist
1661   if (detPID->HasRawProbability(detector) && detPID->HasNumberOfSigmas(detector)) return;
1662   
1663   //TODO: which particles to include? See also the loops below...
1664   Double_t values[AliPID::kSPECIESC]={0};
1665
1666   //probabilities
1667   EDetPidStatus status=GetComputePIDProbability(detector,track,AliPID::kSPECIESC,values);
1668   detPID->SetRawProbability(detector, values, (Int_t)AliPID::kSPECIESC, status);
1669   
1670   //nsigmas
1671   for (Int_t ipart=0; ipart<AliPID::kSPECIESC; ++ipart)
1672     values[ipart]=GetNumberOfSigmas(detector,track,(AliPID::EParticleType)ipart);
1673   // the pid status is the same for probabilities and nSigmas, so it is
1674   // fine to use the one from the probabilities also here
1675   detPID->SetNumberOfSigmas(detector, values, (Int_t)AliPID::kSPECIESC, status);
1676   
1677 }
1678
1679 //______________________________________________________________________________
1680 void AliPIDResponse::FillTrackDetectorPID()
1681 {
1682   //
1683   // create detector PID information and setup the transient pointer in the track
1684   //
1685
1686   if (!fCurrentEvent) return;
1687   
1688   for (Int_t itrack=0; itrack<fCurrentEvent->GetNumberOfTracks(); ++itrack){
1689     AliVTrack *track=dynamic_cast<AliVTrack*>(fCurrentEvent->GetTrack(itrack));
1690     if (!track) continue;
1691
1692     for (Int_t idet=0; idet<kNdetectors; ++idet){
1693       FillTrackDetectorPID(track, (EDetector)idet);
1694     }
1695   }
1696 }
1697
1698 //______________________________________________________________________________
1699 void AliPIDResponse::SetTOFResponse(AliVEvent *vevent,EStartTimeType_t option){
1700   //
1701   // Set TOF response function
1702   // Input option for event_time used
1703   //
1704   
1705     Float_t t0spread = 0.; //vevent->GetEventTimeSpread();
1706     if(t0spread < 10) t0spread = 80;
1707
1708     // T0 from TOF algorithm
1709
1710     Bool_t flagT0TOF=kFALSE;
1711     Bool_t flagT0T0=kFALSE;
1712     Float_t *startTime = new Float_t[fTOFResponse.GetNmomBins()];
1713     Float_t *startTimeRes = new Float_t[fTOFResponse.GetNmomBins()];
1714     Int_t *startTimeMask = new Int_t[fTOFResponse.GetNmomBins()];
1715
1716     // T0-TOF arrays
1717     Float_t *estimatedT0event = new Float_t[fTOFResponse.GetNmomBins()];
1718     Float_t *estimatedT0resolution = new Float_t[fTOFResponse.GetNmomBins()];
1719     for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){
1720       estimatedT0event[i]=0.0;
1721       estimatedT0resolution[i]=0.0;
1722       startTimeMask[i] = 0;
1723     }
1724
1725     Float_t resT0A=fResT0A;
1726     Float_t resT0C=fResT0C;
1727     Float_t resT0AC=fResT0AC;
1728     if(vevent->GetT0TOF()){ // check if T0 detector information is available
1729         flagT0T0=kTRUE;
1730     }
1731
1732
1733     AliTOFHeader *tofHeader = (AliTOFHeader*)vevent->GetTOFHeader();
1734
1735     if (tofHeader) { // read global info and T0-TOF
1736       fTOFResponse.SetTimeResolution(tofHeader->GetTOFResolution());
1737       t0spread = tofHeader->GetT0spread(); // read t0 sprad
1738       if(t0spread < 10) t0spread = 80;
1739
1740       flagT0TOF=kTRUE;
1741       for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){ // read T0-TOF default value
1742         startTime[i]=tofHeader->GetDefaultEventTimeVal();
1743         startTimeRes[i]=tofHeader->GetDefaultEventTimeRes();
1744         if(startTimeRes[i] < 1.e-5) startTimeRes[i] = t0spread;
1745       }
1746
1747       TArrayI *ibin=(TArrayI*)tofHeader->GetNvalues();
1748       TArrayF *t0Bin=(TArrayF*)tofHeader->GetEventTimeValues();
1749       TArrayF *t0ResBin=(TArrayF*)tofHeader->GetEventTimeRes();
1750       for(Int_t j=0;j < tofHeader->GetNbins();j++){ // fill T0-TOF in p-bins
1751         Int_t icurrent = (Int_t)ibin->GetAt(j);
1752         startTime[icurrent]=t0Bin->GetAt(j);
1753         startTimeRes[icurrent]=t0ResBin->GetAt(j);
1754         if(startTimeRes[icurrent] < 1.e-5) startTimeRes[icurrent] = t0spread;
1755       }
1756     }
1757
1758     // for cut of 3 sigma on t0 spread
1759     Float_t t0cut = 3 * t0spread;
1760     if(t0cut < 500) t0cut = 500;
1761
1762     if(option == kFILL_T0){ // T0-FILL is used
1763         for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){
1764           estimatedT0event[i]=0.0;
1765           estimatedT0resolution[i]=t0spread;
1766         }
1767         fTOFResponse.SetT0event(estimatedT0event);
1768         fTOFResponse.SetT0resolution(estimatedT0resolution);
1769     }
1770
1771     if(option == kTOF_T0){ // T0-TOF is used when available (T0-FILL otherwise) from ESD
1772         if(flagT0TOF){
1773             fTOFResponse.SetT0event(startTime);
1774             fTOFResponse.SetT0resolution(startTimeRes);
1775             for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){
1776               if(startTimeRes[i]<t0spread) startTimeMask[i]=1;
1777               fTOFResponse.SetT0binMask(i,startTimeMask[i]);
1778             }
1779         }
1780         else{
1781             for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){
1782               estimatedT0event[i]=0.0;
1783               estimatedT0resolution[i]=t0spread;
1784               fTOFResponse.SetT0binMask(i,startTimeMask[i]);
1785             }
1786             fTOFResponse.SetT0event(estimatedT0event);
1787             fTOFResponse.SetT0resolution(estimatedT0resolution);
1788         }
1789     }
1790     else if(option == kBest_T0){ // T0-T0 or T0-TOF are used when available (T0-FILL otherwise) from ESD
1791         Float_t t0AC=-10000;
1792         Float_t t0A=-10000;
1793         Float_t t0C=-10000;
1794         if(flagT0T0){
1795             t0A= vevent->GetT0TOF()[1];
1796             t0C= vevent->GetT0TOF()[2];
1797         //      t0AC= vevent->GetT0TOF()[0];
1798         t0AC= t0A/resT0A/resT0A + t0C/resT0C/resT0C;
1799         resT0AC= TMath::Sqrt(1./resT0A/resT0A + 1./resT0C/resT0C);
1800         t0AC /= resT0AC*resT0AC;
1801         }
1802
1803         Float_t t0t0Best = 0;
1804         Float_t t0t0BestRes = 9999;
1805         Int_t t0used=0;
1806         if(TMath::Abs(t0A) < t0cut && TMath::Abs(t0C) < t0cut && TMath::Abs(t0C-t0A) < 500){
1807             t0t0Best = t0AC;
1808             t0t0BestRes = resT0AC;
1809             t0used=6;
1810         }
1811         else if(TMath::Abs(t0C) < t0cut){
1812             t0t0Best = t0C;
1813             t0t0BestRes = resT0C;
1814             t0used=4;
1815         }
1816         else if(TMath::Abs(t0A) < t0cut){
1817             t0t0Best = t0A;
1818             t0t0BestRes = resT0A;
1819             t0used=2;
1820         }
1821
1822         if(flagT0TOF){ // if T0-TOF info is available
1823             for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){
1824                 if(t0t0BestRes < 999){
1825                   if(startTimeRes[i] < t0spread){
1826                     Double_t wtot = 1./startTimeRes[i]/startTimeRes[i] + 1./t0t0BestRes/t0t0BestRes;
1827                     Double_t t0best = startTime[i]/startTimeRes[i]/startTimeRes[i] + t0t0Best/t0t0BestRes/t0t0BestRes;
1828                     estimatedT0event[i]=t0best / wtot;
1829                     estimatedT0resolution[i]=1./TMath::Sqrt(wtot);
1830                     startTimeMask[i] = t0used+1;
1831                   }
1832                   else {
1833                     estimatedT0event[i]=t0t0Best;
1834                     estimatedT0resolution[i]=t0t0BestRes;
1835                     startTimeMask[i] = t0used;
1836                   }
1837                 }
1838                 else{
1839                   estimatedT0event[i]=startTime[i];
1840                   estimatedT0resolution[i]=startTimeRes[i];
1841                   if(startTimeRes[i]<t0spread) startTimeMask[i]=1;
1842                 }
1843                 fTOFResponse.SetT0binMask(i,startTimeMask[i]);
1844             }
1845             fTOFResponse.SetT0event(estimatedT0event);
1846             fTOFResponse.SetT0resolution(estimatedT0resolution);
1847         }
1848         else{ // if no T0-TOF info is available
1849             for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){
1850               fTOFResponse.SetT0binMask(i,t0used);
1851               if(t0t0BestRes < 999){
1852                 estimatedT0event[i]=t0t0Best;
1853                 estimatedT0resolution[i]=t0t0BestRes;
1854               }
1855               else{
1856                 estimatedT0event[i]=0.0;
1857                 estimatedT0resolution[i]=t0spread;
1858               }
1859             }
1860             fTOFResponse.SetT0event(estimatedT0event);
1861             fTOFResponse.SetT0resolution(estimatedT0resolution);
1862         }
1863     }
1864
1865     else if(option == kT0_T0){ // T0-T0 is used when available (T0-FILL otherwise)
1866         Float_t t0AC=-10000;
1867         Float_t t0A=-10000;
1868         Float_t t0C=-10000;
1869         if(flagT0T0){
1870             t0A= vevent->GetT0TOF()[1];
1871             t0C= vevent->GetT0TOF()[2];
1872         //      t0AC= vevent->GetT0TOF()[0];
1873         t0AC= t0A/resT0A/resT0A + t0C/resT0C/resT0C;
1874         resT0AC= TMath::Sqrt(1./resT0A/resT0A + 1./resT0C/resT0C);
1875         t0AC /= resT0AC*resT0AC;
1876         }
1877
1878         if(TMath::Abs(t0A) < t0cut && TMath::Abs(t0C) < t0cut && TMath::Abs(t0C-t0A) < 500){
1879             for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){
1880               estimatedT0event[i]=t0AC;
1881               estimatedT0resolution[i]=resT0AC;
1882               fTOFResponse.SetT0binMask(i,6);
1883             }
1884         }
1885         else if(TMath::Abs(t0C) < t0cut){
1886             for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){
1887               estimatedT0event[i]=t0C;
1888               estimatedT0resolution[i]=resT0C;
1889               fTOFResponse.SetT0binMask(i,4);
1890             }
1891         }
1892         else if(TMath::Abs(t0A) < t0cut){
1893             for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){
1894               estimatedT0event[i]=t0A;
1895               estimatedT0resolution[i]=resT0A;
1896               fTOFResponse.SetT0binMask(i,2);
1897             }
1898         }
1899         else{
1900             for(Int_t i=0;i<fTOFResponse.GetNmomBins();i++){
1901               estimatedT0event[i]=0.0;
1902               estimatedT0resolution[i]=t0spread;
1903               fTOFResponse.SetT0binMask(i,0);
1904             }
1905         }
1906         fTOFResponse.SetT0event(estimatedT0event);
1907         fTOFResponse.SetT0resolution(estimatedT0resolution);
1908     }
1909     delete [] startTime;
1910     delete [] startTimeRes;
1911     delete [] startTimeMask;
1912     delete [] estimatedT0event;
1913     delete [] estimatedT0resolution;
1914 }
1915
1916 //______________________________________________________________________________
1917 // private non cached versions of the PID calculation
1918 //
1919
1920
1921 //______________________________________________________________________________
1922 Float_t AliPIDResponse::GetNumberOfSigmas(EDetector detector, const AliVParticle *vtrack, AliPID::EParticleType type) const
1923 {
1924   //
1925   // NumberOfSigmas for 'detCode'
1926   //
1927
1928   const AliVTrack *track=static_cast<const AliVTrack*>(vtrack);
1929   
1930   switch (detector){
1931     case kITS:   return GetNumberOfSigmasITS(track, type);   break;
1932     case kTPC:   return GetNumberOfSigmasTPC(track, type);   break;
1933     case kTOF:   return GetNumberOfSigmasTOF(track, type);   break;
1934     case kHMPID: return GetNumberOfSigmasHMPID(track, type); break;
1935     case kEMCAL: return GetNumberOfSigmasEMCAL(track, type); break;
1936     default: return -999.;
1937   }
1938
1939   return -999.;
1940 }
1941
1942 //______________________________________________________________________________
1943 Float_t AliPIDResponse::GetNumberOfSigmasITS(const AliVParticle *vtrack, AliPID::EParticleType type) const
1944 {
1945   //
1946   // Calculate the number of sigmas in the ITS
1947   //
1948   
1949   AliVTrack *track=(AliVTrack*)vtrack;
1950
1951   const EDetPidStatus pidStatus=GetITSPIDStatus(track);
1952   if (pidStatus!=kDetPidOk) return -999.;
1953
1954   return fITSResponse.GetNumberOfSigmas(track,type);
1955 }
1956
1957 //______________________________________________________________________________
1958 Float_t AliPIDResponse::GetNumberOfSigmasTPC(const AliVParticle *vtrack, AliPID::EParticleType type) const
1959 {
1960   //
1961   // Calculate the number of sigmas in the TPC
1962   //
1963   
1964   AliVTrack *track=(AliVTrack*)vtrack;
1965
1966   const EDetPidStatus pidStatus=GetTPCPIDStatus(track);
1967   if (pidStatus!=kDetPidOk) return -999.;
1968
1969   // the following call is needed in order to fill the transient data member
1970   // fTPCsignalTuned which is used in the TPCPIDResponse to judge
1971   // if using tuned on data
1972   if (fTuneMConData && ((fTuneMConDataMask & kDetTPC) == kDetTPC))
1973     this->GetTPCsignalTunedOnData(track);
1974   
1975   return fTPCResponse.GetNumberOfSigmas(track, type, AliTPCPIDResponse::kdEdxDefault, fUseTPCEtaCorrection, fUseTPCMultiplicityCorrection);
1976 }
1977
1978 //______________________________________________________________________________
1979 Float_t AliPIDResponse::GetNumberOfSigmasTOF(const AliVParticle *vtrack, AliPID::EParticleType type) const
1980 {
1981   //
1982   // Calculate the number of sigmas in the TOF
1983   //
1984   
1985   AliVTrack *track=(AliVTrack*)vtrack;
1986
1987   const EDetPidStatus pidStatus=GetTOFPIDStatus(track);
1988   if (pidStatus!=kDetPidOk) return -999.;
1989   
1990   return GetNumberOfSigmasTOFold(vtrack, type);
1991 }
1992 //______________________________________________________________________________
1993
1994 Float_t AliPIDResponse::GetNumberOfSigmasHMPID(const AliVParticle *vtrack, AliPID::EParticleType type) const
1995 {
1996   //
1997   // Calculate the number of sigmas in the HMPID
1998   //  
1999   AliVTrack *track=(AliVTrack*)vtrack;
2000     
2001   const EDetPidStatus pidStatus=GetHMPIDPIDStatus(track);
2002   if (pidStatus!=kDetPidOk) return -999.; 
2003   
2004   return fHMPIDResponse.GetNumberOfSigmas(track, type);
2005 }
2006
2007 //______________________________________________________________________________
2008 Float_t AliPIDResponse::GetNumberOfSigmasEMCAL(const AliVParticle *vtrack, AliPID::EParticleType type) const
2009 {
2010   //
2011   // Calculate the number of sigmas in the EMCAL
2012   //
2013   
2014   AliVTrack *track=(AliVTrack*)vtrack;
2015
2016   const EDetPidStatus pidStatus=GetEMCALPIDStatus(track);
2017   if (pidStatus!=kDetPidOk) return -999.;
2018
2019   const Int_t nMatchClus = track->GetEMCALcluster();
2020   AliVCluster *matchedClus = (AliVCluster*)fCurrentEvent->GetCaloCluster(nMatchClus);
2021   
2022   const Double_t mom    = track->P();
2023   const Double_t pt     = track->Pt();
2024   const Int_t    charge = track->Charge();
2025   const Double_t fClsE  = matchedClus->E();
2026   const Double_t EovP   = fClsE/mom;
2027   
2028   return fEMCALResponse.GetNumberOfSigmas(pt,EovP,type,charge);
2029 }
2030
2031 //______________________________________________________________________________
2032 AliPIDResponse::EDetPidStatus AliPIDResponse::GetSignalDeltaITS(const AliVParticle *vtrack, AliPID::EParticleType type, Double_t &val, Bool_t ratio/*=kFALSE*/) const
2033 {
2034   //
2035   // Signal minus expected Signal for ITS
2036   //
2037   AliVTrack *track=(AliVTrack*)vtrack;
2038   val=fITSResponse.GetSignalDelta(track,type,ratio);
2039   
2040   return GetITSPIDStatus(track);
2041 }
2042
2043 //______________________________________________________________________________
2044 AliPIDResponse::EDetPidStatus AliPIDResponse::GetSignalDeltaTPC(const AliVParticle *vtrack, AliPID::EParticleType type, Double_t &val, Bool_t ratio/*=kFALSE*/) const
2045 {
2046   //
2047   // Signal minus expected Signal for TPC
2048   //
2049   AliVTrack *track=(AliVTrack*)vtrack;
2050   
2051   // the following call is needed in order to fill the transient data member
2052   // fTPCsignalTuned which is used in the TPCPIDResponse to judge
2053   // if using tuned on data
2054   if (fTuneMConData && ((fTuneMConDataMask & kDetTPC) == kDetTPC))
2055     this->GetTPCsignalTunedOnData(track);
2056   
2057   val=fTPCResponse.GetSignalDelta(track, type, AliTPCPIDResponse::kdEdxDefault, fUseTPCEtaCorrection, fUseTPCMultiplicityCorrection, ratio);
2058   
2059   return GetTPCPIDStatus(track);
2060 }
2061
2062 //______________________________________________________________________________
2063 AliPIDResponse::EDetPidStatus AliPIDResponse::GetSignalDeltaTOF(const AliVParticle *vtrack, AliPID::EParticleType type, Double_t &val, Bool_t ratio/*=kFALSE*/) const
2064 {
2065   //
2066   // Signal minus expected Signal for TOF
2067   //
2068   AliVTrack *track=(AliVTrack*)vtrack;
2069   val=GetSignalDeltaTOFold(track, type, ratio);
2070   
2071   return GetTOFPIDStatus(track);
2072 }
2073
2074 //______________________________________________________________________________
2075 AliPIDResponse::EDetPidStatus AliPIDResponse::GetSignalDeltaHMPID(const AliVParticle *vtrack, AliPID::EParticleType type, Double_t &val, Bool_t ratio/*=kFALSE*/) const
2076 {
2077   //
2078   // Signal minus expected Signal for HMPID
2079   //
2080   AliVTrack *track=(AliVTrack*)vtrack;
2081   val=fHMPIDResponse.GetSignalDelta(track, type, ratio);
2082   
2083   return GetHMPIDPIDStatus(track);
2084 }
2085
2086 //______________________________________________________________________________
2087 AliPIDResponse::EDetPidStatus AliPIDResponse::GetComputePIDProbability  (EDetector detCode,  const AliVTrack *track, Int_t nSpecies, Double_t p[]) const
2088 {
2089   //
2090   // Compute PID response of 'detCode'
2091   //
2092
2093   switch (detCode){
2094     case kITS: return GetComputeITSProbability(track, nSpecies, p); break;
2095     case kTPC: return GetComputeTPCProbability(track, nSpecies, p); break;
2096     case kTRD: return GetComputeTRDProbability(track, nSpecies, p); break;
2097     case kTOF: return GetComputeTOFProbability(track, nSpecies, p); break;
2098     case kPHOS: return GetComputePHOSProbability(track, nSpecies, p); break;
2099     case kEMCAL: return GetComputeEMCALProbability(track, nSpecies, p); break;
2100     case kHMPID: return GetComputeHMPIDProbability(track, nSpecies, p); break;
2101     default: return kDetNoSignal;
2102   }
2103 }
2104
2105 //______________________________________________________________________________
2106 AliPIDResponse::EDetPidStatus AliPIDResponse::GetComputeITSProbability  (const AliVTrack *track, Int_t nSpecies, Double_t p[]) const
2107 {
2108   //
2109   // Compute PID response for the ITS
2110   //
2111   
2112   // set flat distribution (no decision)
2113   for (Int_t j=0; j<nSpecies; j++) p[j]=1./nSpecies;
2114   
2115   const EDetPidStatus pidStatus=GetITSPIDStatus(track);
2116   if (pidStatus!=kDetPidOk) return pidStatus;
2117   
2118   if (track->GetDetectorPID()){
2119     return track->GetDetectorPID()->GetRawProbability(kITS, p, nSpecies);
2120   }
2121   
2122   //check for ITS standalone tracks
2123   Bool_t isSA=kTRUE;
2124   if( track->GetStatus() & AliVTrack::kTPCin ) isSA=kFALSE;
2125
2126   Double_t mom=track->P();
2127   Double_t dedx=track->GetITSsignal();
2128   Double_t momITS=mom;
2129   UChar_t clumap=track->GetITSClusterMap();
2130   Int_t nPointsForPid=0;
2131   for(Int_t i=2; i<6; i++){
2132     if(clumap&(1<<i)) ++nPointsForPid;
2133   }
2134
2135   Bool_t mismatch=kTRUE/*, heavy=kTRUE*/;
2136   for (Int_t j=0; j<nSpecies; j++) {
2137     Double_t mass=AliPID::ParticleMassZ(j);//GeV/c^2
2138     const Double_t chargeFactor = TMath::Power(AliPID::ParticleCharge(j),2.);
2139     Double_t bethe=fITSResponse.Bethe(momITS,mass)*chargeFactor;
2140     //TODO: in case of the electron, use the SA parametrisation,
2141     //      this needs to be changed if ITS provides a parametrisation
2142     //      for electrons also for ITS+TPC tracks
2143     Double_t sigma=fITSResponse.GetResolution(bethe,nPointsForPid,isSA || (j==(Int_t)AliPID::kElectron));
2144     if (TMath::Abs(dedx-bethe) > fRange*sigma) {
2145       p[j]=TMath::Exp(-0.5*fRange*fRange)/sigma;
2146     } else {
2147       p[j]=TMath::Exp(-0.5*(dedx-bethe)*(dedx-bethe)/(sigma*sigma))/sigma;
2148       mismatch=kFALSE;
2149     }
2150   }
2151
2152   if (mismatch){
2153     for (Int_t j=0; j<nSpecies; j++) p[j]=1./nSpecies;
2154   }
2155
2156   return kDetPidOk;
2157 }
2158 //______________________________________________________________________________
2159 AliPIDResponse::EDetPidStatus AliPIDResponse::GetComputeTPCProbability  (const AliVTrack *track, Int_t nSpecies, Double_t p[]) const
2160 {
2161   //
2162   // Compute PID response for the TPC
2163   //
2164   
2165   // set flat distribution (no decision)
2166   for (Int_t j=0; j<nSpecies; j++) p[j]=1./nSpecies;
2167   
2168   const EDetPidStatus pidStatus=GetTPCPIDStatus(track);
2169   if (pidStatus!=kDetPidOk) return pidStatus;
2170   
2171   Double_t dedx=track->GetTPCsignal();
2172   Bool_t mismatch=kTRUE/*, heavy=kTRUE*/;
2173   
2174   if (fTuneMConData && ((fTuneMConDataMask & kDetTPC) == kDetTPC)) dedx = this->GetTPCsignalTunedOnData(track);
2175   
2176   Double_t bethe = 0.;
2177   Double_t sigma = 0.;
2178   
2179   for (Int_t j=0; j<nSpecies; j++) {
2180     AliPID::EParticleType type=AliPID::EParticleType(j);
2181     
2182     bethe=fTPCResponse.GetExpectedSignal(track, type, AliTPCPIDResponse::kdEdxDefault, fUseTPCEtaCorrection, fUseTPCMultiplicityCorrection);
2183     sigma=fTPCResponse.GetExpectedSigma(track, type, AliTPCPIDResponse::kdEdxDefault, fUseTPCEtaCorrection, fUseTPCMultiplicityCorrection);
2184     
2185     if (TMath::Abs(dedx-bethe) > fRange*sigma) {
2186       p[j]=TMath::Exp(-0.5*fRange*fRange)/sigma;
2187     } else {
2188       p[j]=TMath::Exp(-0.5*(dedx-bethe)*(dedx-bethe)/(sigma*sigma))/sigma;
2189       mismatch=kFALSE;
2190     }
2191   }
2192   
2193   if (mismatch){
2194     for (Int_t j=0; j<nSpecies; j++) p[j]=1./nSpecies;
2195   }
2196   
2197   return kDetPidOk;
2198 }
2199 //______________________________________________________________________________
2200 AliPIDResponse::EDetPidStatus AliPIDResponse::GetComputeTOFProbability  (const AliVTrack *track, Int_t nSpecies, Double_t p[]) const
2201 {
2202   //
2203   // Compute PID probabilities for TOF
2204   //
2205   
2206   // set flat distribution (no decision)
2207   for (Int_t j=0; j<nSpecies; j++) p[j]=1./nSpecies;
2208   
2209   const EDetPidStatus pidStatus=GetTOFPIDStatus(track);
2210   if (pidStatus!=kDetPidOk) return pidStatus;
2211
2212   const Double_t meanCorrFactor = 0.07/fTOFtail; // Correction factor on the mean because of the tail (should be ~ 0.1 with tail = 1.1)
2213   
2214   for (Int_t j=0; j<nSpecies; j++) {
2215     AliPID::EParticleType type=AliPID::EParticleType(j);
2216     const Double_t nsigmas=GetNumberOfSigmasTOFold(track,type) + meanCorrFactor;
2217     
2218     const Double_t expTime = fTOFResponse.GetExpectedSignal(track,type);
2219     const Double_t sig     = fTOFResponse.GetExpectedSigma(track->P(),expTime,AliPID::ParticleMassZ(type));
2220     if (TMath::Abs(nsigmas) > (fRange+2)) {
2221       if(nsigmas < fTOFtail)
2222         p[j] = TMath::Exp(-0.5*(fRange+2)*(fRange+2))/sig;
2223       else
2224         p[j] = TMath::Exp(-(fRange+2 - fTOFtail*0.5)*fTOFtail)/sig;
2225     } else{
2226       if(nsigmas < fTOFtail)
2227         p[j] = TMath::Exp(-0.5*nsigmas*nsigmas)/sig;
2228       else
2229         p[j] = TMath::Exp(-(nsigmas - fTOFtail*0.5)*fTOFtail)/sig;
2230     }    
2231   }
2232   
2233   return kDetPidOk;
2234 }
2235 //______________________________________________________________________________
2236 AliPIDResponse::EDetPidStatus AliPIDResponse::GetComputeTRDProbability  (const AliVTrack *track, Int_t nSpecies, Double_t p[],AliTRDPIDResponse::ETRDPIDMethod PIDmethod/*=AliTRDPIDResponse::kLQ1D*/) const
2237 {
2238   //
2239   // Compute PID probabilities for the TRD
2240   //
2241   
2242   // set flat distribution (no decision)
2243   for (Int_t j=0; j<nSpecies; j++) p[j]=1./nSpecies;
2244   
2245   const EDetPidStatus pidStatus=GetTRDPIDStatus(track);
2246   if (pidStatus!=kDetPidOk) return pidStatus;
2247
2248   UInt_t TRDslicesForPID[2];
2249   SetTRDSlices(TRDslicesForPID,PIDmethod);
2250   
2251   Float_t mom[6]={0.};
2252   Double_t dedx[48]={0.};  // Allocate space for the maximum number of TRD slices
2253   Int_t nslices = TRDslicesForPID[1] - TRDslicesForPID[0] + 1;
2254   AliDebug(1, Form("First Slice: %d, Last Slice: %d, Number of slices: %d",  TRDslicesForPID[0], TRDslicesForPID[1], nslices));
2255   for(UInt_t ilayer = 0; ilayer < 6; ilayer++){
2256     mom[ilayer] = track->GetTRDmomentum(ilayer);
2257     for(UInt_t islice = TRDslicesForPID[0]; islice <= TRDslicesForPID[1]; islice++){
2258       dedx[ilayer*nslices+islice-TRDslicesForPID[0]] = track->GetTRDslice(ilayer, islice);
2259     }
2260   }
2261   
2262   fTRDResponse.GetResponse(nslices, dedx, mom, p,PIDmethod);
2263   return kDetPidOk;
2264 }
2265
2266 //______________________________________________________________________________
2267 AliPIDResponse::EDetPidStatus AliPIDResponse::GetComputeEMCALProbability  (const AliVTrack *track, Int_t nSpecies, Double_t p[]) const
2268 {
2269   //
2270   // Compute PID response for the EMCAL
2271   //
2272   
2273   for (Int_t j=0; j<nSpecies; j++) p[j]=1./nSpecies;
2274
2275   const EDetPidStatus pidStatus=GetEMCALPIDStatus(track);
2276   if (pidStatus!=kDetPidOk) return pidStatus;
2277
2278   const Int_t nMatchClus = track->GetEMCALcluster();
2279   AliVCluster *matchedClus = (AliVCluster*)fCurrentEvent->GetCaloCluster(nMatchClus);
2280   
2281   const Double_t mom    = track->P();
2282   const Double_t pt     = track->Pt();
2283   const Int_t    charge = track->Charge();
2284   const Double_t fClsE  = matchedClus->E();
2285   const Double_t EovP   = fClsE/mom;
2286   
2287   // compute the probabilities
2288   fEMCALResponse.ComputeEMCALProbability(nSpecies,pt,EovP,charge,p);
2289   return kDetPidOk;
2290 }
2291
2292 //______________________________________________________________________________
2293 AliPIDResponse::EDetPidStatus AliPIDResponse::GetComputePHOSProbability (const AliVTrack */*track*/, Int_t nSpecies, Double_t p[]) const
2294 {
2295   //
2296   // Compute PID response for the PHOS
2297   //
2298   
2299   // set flat distribution (no decision)
2300   for (Int_t j=0; j<nSpecies; j++) p[j]=1./nSpecies;
2301   return kDetNoSignal;
2302 }
2303
2304 //______________________________________________________________________________
2305 AliPIDResponse::EDetPidStatus AliPIDResponse::GetComputeHMPIDProbability(const AliVTrack *track, Int_t nSpecies, Double_t p[]) const
2306 {
2307   //
2308   // Compute PID response for the HMPID
2309   //
2310   
2311   // set flat distribution (no decision)
2312   for (Int_t j=0; j<nSpecies; j++) p[j]=1./nSpecies;
2313   
2314   const EDetPidStatus pidStatus=GetHMPIDPIDStatus(track);
2315   if (pidStatus!=kDetPidOk) return pidStatus;
2316   
2317   fHMPIDResponse.GetProbability(track,nSpecies,p);
2318     
2319   return kDetPidOk;
2320 }
2321
2322 //______________________________________________________________________________
2323 AliPIDResponse::EDetPidStatus AliPIDResponse::GetITSPIDStatus(const AliVTrack *track) const
2324 {
2325   // compute ITS pid status
2326
2327   // check status bits
2328   if ((track->GetStatus()&AliVTrack::kITSin)==0 &&
2329     (track->GetStatus()&AliVTrack::kITSout)==0) return kDetNoSignal;
2330
2331   const Float_t dEdx=track->GetITSsignal();
2332   if (dEdx<=0) return kDetNoSignal;
2333   
2334   // requite at least 3 pid clusters
2335   const UChar_t clumap=track->GetITSClusterMap();
2336   Int_t nPointsForPid=0;
2337   for(Int_t i=2; i<6; i++){
2338     if(clumap&(1<<i)) ++nPointsForPid;
2339   }
2340   
2341   if(nPointsForPid<3) { 
2342     return kDetNoSignal;
2343   }
2344   
2345   return kDetPidOk;
2346 }
2347
2348 //______________________________________________________________________________
2349 AliPIDResponse::EDetPidStatus AliPIDResponse:: GetTPCPIDStatus(const AliVTrack *track) const
2350 {
2351   // compute TPC pid status
2352   
2353   // check quality of the track
2354   if ( (track->GetStatus()&AliVTrack::kTPCin )==0 && (track->GetStatus()&AliVTrack::kTPCout)==0 ) return kDetNoSignal;
2355
2356   // check pid values
2357   const Double_t dedx=track->GetTPCsignal();
2358   const UShort_t signalN=track->GetTPCsignalN();
2359   if (signalN<10 || dedx<10) return kDetNoSignal;
2360
2361   if (!(fArrPidResponseMaster && fArrPidResponseMaster->At(AliPID::kPion))) return kDetNoParams;
2362   
2363   return kDetPidOk;
2364 }
2365
2366 //______________________________________________________________________________
2367 AliPIDResponse::EDetPidStatus AliPIDResponse::GetTRDPIDStatus(const AliVTrack *track) const
2368 {
2369   // compute TRD pid status
2370
2371   if((track->GetStatus()&AliVTrack::kTRDout)==0) return kDetNoSignal;
2372   return kDetPidOk;
2373 }
2374
2375 //______________________________________________________________________________
2376 AliPIDResponse::EDetPidStatus AliPIDResponse::GetTOFPIDStatus(const AliVTrack *track) const
2377 {
2378   // compute TOF pid status
2379
2380   if ((track->GetStatus()&AliVTrack::kTOFout)==0) return kDetNoSignal;
2381   if ((track->GetStatus()&AliVTrack::kTIME)==0) return kDetNoSignal;
2382
2383   return kDetPidOk;
2384 }
2385
2386 //______________________________________________________________________________
2387 Float_t AliPIDResponse::GetTOFMismatchProbability(const AliVTrack *track) const
2388 {
2389   // compute mismatch probability cross-checking at 5 sigmas with TPC
2390   // currently just implemented as a 5 sigma compatibility cut
2391
2392   // check pid status
2393   const EDetPidStatus tofStatus=GetTOFPIDStatus(track);
2394   if (tofStatus!=kDetPidOk) return 0.;
2395
2396   //mismatch
2397   const EDetPidStatus tpcStatus=GetTPCPIDStatus(track);
2398   if (tpcStatus!=kDetPidOk) return 0.;
2399   
2400   const Double_t meanCorrFactor = 0.11/fTOFtail; // Correction factor on the mean because of the tail (should be ~ 0.1 with tail = 1.1)
2401   Bool_t mismatch = kTRUE/*, heavy = kTRUE*/;
2402   for (Int_t j=0; j<AliPID::kSPECIESC; j++) {
2403     AliPID::EParticleType type=AliPID::EParticleType(j);
2404     const Double_t nsigmas=GetNumberOfSigmasTOFold(track,type) + meanCorrFactor;
2405     
2406     if (TMath::Abs(nsigmas)<5.){
2407       const Double_t nsigmasTPC=GetNumberOfSigmasTPC(track,type);
2408       if (TMath::Abs(nsigmasTPC)<5.) mismatch=kFALSE;
2409     }
2410   }
2411   
2412   if (mismatch){
2413     return 1.;
2414   }
2415   
2416   return 0.;
2417 }
2418
2419 //______________________________________________________________________________
2420 AliPIDResponse::EDetPidStatus AliPIDResponse:: GetHMPIDPIDStatus(const AliVTrack *track) const
2421 {
2422   // compute HMPID pid status
2423   
2424   Int_t ch = track->GetHMPIDcluIdx()/1000000;
2425   Double_t HMPIDsignal = track->GetHMPIDsignal(); 
2426   
2427   if((track->GetStatus()&AliVTrack::kHMPIDpid)==0 || ch<0 || ch>6 || HMPIDsignal<0) return kDetNoSignal;
2428   
2429   return kDetPidOk;
2430 }
2431
2432 //______________________________________________________________________________
2433 AliPIDResponse::EDetPidStatus AliPIDResponse:: GetPHOSPIDStatus(const AliVTrack */*track*/) const
2434 {
2435   // compute PHOS pid status
2436   return kDetNoSignal;  
2437 }
2438
2439 //______________________________________________________________________________
2440 AliPIDResponse::EDetPidStatus AliPIDResponse:: GetEMCALPIDStatus(const AliVTrack *track) const
2441 {
2442   // compute EMCAL pid status
2443
2444
2445   // Track matching
2446   const Int_t nMatchClus = track->GetEMCALcluster();
2447   if (nMatchClus<0) return kDetNoSignal;
2448
2449   AliVCluster *matchedClus = (AliVCluster*)fCurrentEvent->GetCaloCluster(nMatchClus);
2450
2451   if (!(matchedClus && matchedClus->IsEMCAL())) return kDetNoSignal;
2452
2453   const Int_t charge = track->Charge();
2454   if (TMath::Abs(charge)!=1) return kDetNoSignal;
2455
2456   if (!(fEMCALPIDParams && fEMCALPIDParams->At(AliPID::kElectron))) return kDetNoParams;
2457   
2458   return kDetPidOk;
2459
2460 }
2461
2462 //______________________________________________________________________________
2463 AliPIDResponse::EDetPidStatus AliPIDResponse::GetPIDStatus(EDetector detector, const AliVTrack *track) const
2464 {
2465   //
2466   // check pid status for a track
2467   //
2468
2469   switch (detector){
2470     case kITS:   return GetITSPIDStatus(track);   break;
2471     case kTPC:   return GetTPCPIDStatus(track);   break;
2472     case kTRD:   return GetTRDPIDStatus(track);   break;
2473     case kTOF:   return GetTOFPIDStatus(track);   break;
2474     case kPHOS:  return GetPHOSPIDStatus(track);  break;
2475     case kEMCAL: return GetEMCALPIDStatus(track); break;
2476     case kHMPID: return GetHMPIDPIDStatus(track); break;
2477     default: return kDetNoSignal;
2478   }
2479   return kDetNoSignal;
2480   
2481 }