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