]> git.uio.no Git - u/mrichter/AliRoot.git/blob - EMCAL/AliEMCALRecoUtils.cxx
Add protection in method AliEMCALGeometry::GetAbsCellIdFromCellIndexes in case eta...
[u/mrichter/AliRoot.git] / EMCAL / AliEMCALRecoUtils.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: AliEMCALRecoUtils.cxx 33808 2009-07-15 09:48:08Z gconesab $ */
17
18 ///////////////////////////////////////////////////////////////////////////////
19 //
20 // Class AliEMCALRecoUtils
21 // Some utilities to recalculate the cluster position or energy linearity
22 //
23 //
24 // Author:  Gustavo Conesa (LPSC- Grenoble) 
25 //          Track matching part: Rongrong Ma (Yale)
26
27 ///////////////////////////////////////////////////////////////////////////////
28 // --- standard c ---
29
30 // standard C++ includes
31 //#include <Riostream.h>
32
33 // ROOT includes
34 #include <TGeoManager.h>
35 #include <TGeoMatrix.h>
36 #include <TGeoBBox.h>
37 #include <TH2F.h>
38 #include <TArrayI.h>
39 #include <TArrayF.h>
40 #include <TObjArray.h>
41
42 // STEER includes
43 #include "AliVCluster.h"
44 #include "AliVCaloCells.h"
45 #include "AliLog.h"
46 #include "AliPID.h"
47 #include "AliESDEvent.h"
48 #include "AliAODEvent.h"
49 #include "AliESDtrack.h"
50 #include "AliAODTrack.h"
51 #include "AliExternalTrackParam.h"
52 #include "AliESDfriendTrack.h"
53 #include "AliTrackerBase.h"
54
55 // EMCAL includes
56 #include "AliEMCALRecoUtils.h"
57 #include "AliEMCALGeometry.h"
58 #include "AliTrackerBase.h"
59 #include "AliEMCALCalibTimeDepCorrection.h" // Run dependent
60 #include "AliEMCALPIDUtils.h"
61
62
63 ClassImp(AliEMCALRecoUtils)
64   
65 //_____________________________________
66 AliEMCALRecoUtils::AliEMCALRecoUtils():
67   fParticleType(0),                       fPosAlgo(0),                            fW0(0), 
68   fNonLinearityFunction(0),               fNonLinearThreshold(0),
69   fSmearClusterEnergy(kFALSE),            fRandom(),
70   fCellsRecalibrated(kFALSE),             fRecalibration(kFALSE),                 fEMCALRecalibrationFactors(),
71   fTimeRecalibration(kFALSE),             fEMCALTimeRecalibrationFactors(),
72   fUseRunCorrectionFactors(kFALSE),       fRunCorrectionFactorsSet(kFALSE),
73   fRemoveBadChannels(kFALSE),             fRecalDistToBadChannels(kFALSE),        fEMCALBadChannelMap(),
74   fNCellsFromEMCALBorder(0),              fNoEMCALBorderAtEta0(kTRUE),
75   fRejectExoticCluster(kFALSE),           fRejectExoticCells(kFALSE), 
76   fExoticCellFraction(0),                 fExoticCellDiffTime(0),                 fExoticCellMinAmplitude(0),
77   fPIDUtils(),                            fAODFilterMask(0),
78   fMatchedTrackIndex(0x0),                fMatchedClusterIndex(0x0), 
79   fResidualEta(0x0), fResidualPhi(0x0),   fCutEtaPhiSum(kFALSE),                  fCutEtaPhiSeparate(kFALSE), 
80   fCutR(0),                               fCutEta(0),                             fCutPhi(0),
81   fClusterWindow(0),                      fMass(0),                           
82   fStepSurface(0),                        fStepCluster(0),
83   fTrackCutsType(0),                      fCutMinTrackPt(0),                      fCutMinNClusterTPC(0), 
84   fCutMinNClusterITS(0),                  fCutMaxChi2PerClusterTPC(0),            fCutMaxChi2PerClusterITS(0),
85   fCutRequireTPCRefit(kFALSE),            fCutRequireITSRefit(kFALSE),            fCutAcceptKinkDaughters(kFALSE),
86   fCutMaxDCAToVertexXY(0),                fCutMaxDCAToVertexZ(0),                 fCutDCAToVertex2D(kFALSE)
87 {
88 //
89   // Constructor.
90   // Initialize all constant values which have to be used
91   // during Reco algorithm execution
92   //
93   
94   // Init parameters
95   InitParameters();
96   
97   //Track matching
98   fMatchedTrackIndex     = new TArrayI();
99   fMatchedClusterIndex   = new TArrayI();
100   fResidualPhi           = new TArrayF();
101   fResidualEta           = new TArrayF();
102   fPIDUtils              = new AliEMCALPIDUtils();
103
104   InitTrackCuts();
105 }
106
107 //______________________________________________________________________
108 AliEMCALRecoUtils::AliEMCALRecoUtils(const AliEMCALRecoUtils & reco) 
109 : TNamed(reco), 
110   fParticleType(reco.fParticleType),                         fPosAlgo(reco.fPosAlgo),     fW0(reco.fW0),
111   fNonLinearityFunction(reco.fNonLinearityFunction),         fNonLinearThreshold(reco.fNonLinearThreshold),
112   fSmearClusterEnergy(reco.fSmearClusterEnergy),             fRandom(),
113   fCellsRecalibrated(reco.fCellsRecalibrated),
114   fRecalibration(reco.fRecalibration),                       fEMCALRecalibrationFactors(reco.fEMCALRecalibrationFactors),
115   fTimeRecalibration(reco.fTimeRecalibration),               fEMCALTimeRecalibrationFactors(reco.fEMCALTimeRecalibrationFactors),
116   fUseRunCorrectionFactors(reco.fUseRunCorrectionFactors),   fRunCorrectionFactorsSet(reco.fRunCorrectionFactorsSet),
117   fRemoveBadChannels(reco.fRemoveBadChannels),               fRecalDistToBadChannels(reco.fRecalDistToBadChannels),
118   fEMCALBadChannelMap(reco.fEMCALBadChannelMap),
119   fNCellsFromEMCALBorder(reco.fNCellsFromEMCALBorder),       fNoEMCALBorderAtEta0(reco.fNoEMCALBorderAtEta0),
120   fRejectExoticCluster(reco.fRejectExoticCluster),           fRejectExoticCells(reco.fRejectExoticCells), 
121   fExoticCellFraction(reco.fExoticCellFraction),             fExoticCellDiffTime(reco.fExoticCellDiffTime),               
122   fExoticCellMinAmplitude(reco.fExoticCellMinAmplitude),
123   fPIDUtils(reco.fPIDUtils),                                 fAODFilterMask(reco.fAODFilterMask),
124   fMatchedTrackIndex(  reco.fMatchedTrackIndex?  new TArrayI(*reco.fMatchedTrackIndex):0x0),
125   fMatchedClusterIndex(reco.fMatchedClusterIndex?new TArrayI(*reco.fMatchedClusterIndex):0x0),
126   fResidualEta(        reco.fResidualEta?        new TArrayF(*reco.fResidualEta):0x0),
127   fResidualPhi(        reco.fResidualPhi?        new TArrayF(*reco.fResidualPhi):0x0),
128   fCutEtaPhiSum(reco.fCutEtaPhiSum),                         fCutEtaPhiSeparate(reco.fCutEtaPhiSeparate), 
129   fCutR(reco.fCutR),        fCutEta(reco.fCutEta),           fCutPhi(reco.fCutPhi),
130   fClusterWindow(reco.fClusterWindow),
131   fMass(reco.fMass),        fStepSurface(reco.fStepSurface), fStepCluster(reco.fStepCluster),
132   fTrackCutsType(reco.fTrackCutsType),                       fCutMinTrackPt(reco.fCutMinTrackPt), 
133   fCutMinNClusterTPC(reco.fCutMinNClusterTPC),               fCutMinNClusterITS(reco.fCutMinNClusterITS), 
134   fCutMaxChi2PerClusterTPC(reco.fCutMaxChi2PerClusterTPC),   fCutMaxChi2PerClusterITS(reco.fCutMaxChi2PerClusterITS),
135   fCutRequireTPCRefit(reco.fCutRequireTPCRefit),             fCutRequireITSRefit(reco.fCutRequireITSRefit),
136   fCutAcceptKinkDaughters(reco.fCutAcceptKinkDaughters),     fCutMaxDCAToVertexXY(reco.fCutMaxDCAToVertexXY),    
137   fCutMaxDCAToVertexZ(reco.fCutMaxDCAToVertexZ),             fCutDCAToVertex2D(reco.fCutDCAToVertex2D)
138 {
139   //Copy ctor
140   
141   for(Int_t i = 0; i < 15 ; i++) { fMisalRotShift[i]      = reco.fMisalRotShift[i]      ; 
142                                    fMisalTransShift[i]    = reco.fMisalTransShift[i]    ; } 
143   for(Int_t i = 0; i < 7  ; i++) { fNonLinearityParams[i] = reco.fNonLinearityParams[i] ; }
144   for(Int_t i = 0; i < 3  ; i++) { fSmearClusterParam[i]  = reco.fSmearClusterParam[i]  ; }
145
146 }
147
148
149 //______________________________________________________________________
150 AliEMCALRecoUtils & AliEMCALRecoUtils::operator = (const AliEMCALRecoUtils & reco) 
151 {
152   //Assignment operator
153   
154   if(this == &reco)return *this;
155   ((TNamed *)this)->operator=(reco);
156
157   for(Int_t i = 0; i < 15 ; i++) { fMisalTransShift[i]    = reco.fMisalTransShift[i]    ; 
158                                    fMisalRotShift[i]      = reco.fMisalRotShift[i]      ; }
159   for(Int_t i = 0; i < 7  ; i++) { fNonLinearityParams[i] = reco.fNonLinearityParams[i] ; }
160   for(Int_t i = 0; i < 3  ; i++) { fSmearClusterParam[i]  = reco.fSmearClusterParam[i]  ; }   
161   
162   fParticleType              = reco.fParticleType;
163   fPosAlgo                   = reco.fPosAlgo; 
164   fW0                        = reco.fW0;
165   
166   fNonLinearityFunction      = reco.fNonLinearityFunction;
167   fNonLinearThreshold        = reco.fNonLinearThreshold;
168   fSmearClusterEnergy        = reco.fSmearClusterEnergy;
169
170   fCellsRecalibrated         = reco.fCellsRecalibrated;
171   fRecalibration             = reco.fRecalibration;
172   fEMCALRecalibrationFactors = reco.fEMCALRecalibrationFactors;
173
174   fTimeRecalibration             = reco.fTimeRecalibration;
175   fEMCALTimeRecalibrationFactors = reco.fEMCALTimeRecalibrationFactors;
176
177   fUseRunCorrectionFactors   = reco.fUseRunCorrectionFactors;
178   fRunCorrectionFactorsSet   = reco.fRunCorrectionFactorsSet;
179   
180   fRemoveBadChannels         = reco.fRemoveBadChannels;
181   fRecalDistToBadChannels    = reco.fRecalDistToBadChannels;
182   fEMCALBadChannelMap        = reco.fEMCALBadChannelMap;
183   
184   fNCellsFromEMCALBorder     = reco.fNCellsFromEMCALBorder;
185   fNoEMCALBorderAtEta0       = reco.fNoEMCALBorderAtEta0;
186   
187   fRejectExoticCluster       = reco.fRejectExoticCluster;           
188   fRejectExoticCells         = reco.fRejectExoticCells; 
189   fExoticCellFraction        = reco.fExoticCellFraction;
190   fExoticCellDiffTime        = reco.fExoticCellDiffTime;              
191   fExoticCellMinAmplitude    = reco.fExoticCellMinAmplitude;
192   
193   fPIDUtils                  = reco.fPIDUtils;
194
195   fAODFilterMask             = reco.fAODFilterMask;
196   
197   fCutEtaPhiSum              = reco.fCutEtaPhiSum;
198   fCutEtaPhiSeparate         = reco.fCutEtaPhiSeparate;
199   fCutR                      = reco.fCutR;
200   fCutEta                    = reco.fCutEta;
201   fCutPhi                    = reco.fCutPhi;
202   fClusterWindow             = reco.fClusterWindow;
203   fMass                      = reco.fMass;
204   fStepSurface               = reco.fStepSurface;
205   fStepCluster               = reco.fStepCluster;
206
207   fTrackCutsType             = reco.fTrackCutsType;
208   fCutMinTrackPt             = reco.fCutMinTrackPt;
209   fCutMinNClusterTPC         = reco.fCutMinNClusterTPC;
210   fCutMinNClusterITS         = reco.fCutMinNClusterITS; 
211   fCutMaxChi2PerClusterTPC   = reco.fCutMaxChi2PerClusterTPC;
212   fCutMaxChi2PerClusterITS   = reco.fCutMaxChi2PerClusterITS;
213   fCutRequireTPCRefit        = reco.fCutRequireTPCRefit;
214   fCutRequireITSRefit        = reco.fCutRequireITSRefit;
215   fCutAcceptKinkDaughters    = reco.fCutAcceptKinkDaughters;
216   fCutMaxDCAToVertexXY       = reco.fCutMaxDCAToVertexXY;
217   fCutMaxDCAToVertexZ        = reco.fCutMaxDCAToVertexZ;
218   fCutDCAToVertex2D          = reco.fCutDCAToVertex2D;
219   
220   if(reco.fResidualEta)
221   {
222     // assign or copy construct
223     if(fResidualEta)
224     { 
225       *fResidualEta = *reco.fResidualEta;
226     }
227     else 
228     {
229       fResidualEta = new TArrayF(*reco.fResidualEta);
230     }
231   }
232   else
233   {
234     if(fResidualEta)delete fResidualEta;
235     fResidualEta = 0;
236   }
237   
238   if(reco.fResidualPhi)
239   {
240     // assign or copy construct
241     if(fResidualPhi)
242     { 
243       *fResidualPhi = *reco.fResidualPhi;
244     }
245     else 
246     {
247       fResidualPhi = new TArrayF(*reco.fResidualPhi);
248     }
249   }
250   else
251   {
252     if(fResidualPhi)delete fResidualPhi;
253     fResidualPhi = 0;
254   }
255   
256   if(reco.fMatchedTrackIndex)
257   {
258     // assign or copy construct
259     if(fMatchedTrackIndex)
260     { 
261       *fMatchedTrackIndex = *reco.fMatchedTrackIndex;
262     }
263     else 
264     { 
265       fMatchedTrackIndex = new TArrayI(*reco.fMatchedTrackIndex);
266     }
267   }
268   else
269   {
270     if(fMatchedTrackIndex)delete fMatchedTrackIndex;
271     fMatchedTrackIndex = 0;
272   }  
273   
274   if(reco.fMatchedClusterIndex)
275   {
276     // assign or copy construct
277     if(fMatchedClusterIndex)
278     { 
279       *fMatchedClusterIndex = *reco.fMatchedClusterIndex;
280     }
281     else 
282     {
283       fMatchedClusterIndex = new TArrayI(*reco.fMatchedClusterIndex);
284     }
285   }
286   else
287   {
288     if(fMatchedClusterIndex)delete fMatchedClusterIndex;
289     fMatchedClusterIndex = 0;
290   }
291    
292   return *this;
293 }
294
295
296 //_____________________________________
297 AliEMCALRecoUtils::~AliEMCALRecoUtils()
298 {
299   //Destructor.
300         
301   if(fEMCALRecalibrationFactors) 
302   { 
303     fEMCALRecalibrationFactors->Clear();
304     delete fEMCALRecalibrationFactors;
305   }     
306   
307   if(fEMCALTimeRecalibrationFactors) 
308   { 
309     fEMCALTimeRecalibrationFactors->Clear();
310     delete fEMCALTimeRecalibrationFactors;
311   }     
312   
313   if(fEMCALBadChannelMap) 
314   { 
315     fEMCALBadChannelMap->Clear();
316     delete fEMCALBadChannelMap;
317   }
318  
319   delete fMatchedTrackIndex   ; 
320   delete fMatchedClusterIndex ; 
321   delete fResidualEta         ; 
322   delete fResidualPhi         ; 
323   delete fPIDUtils            ;
324
325   InitTrackCuts();
326 }
327
328 //_______________________________________________________________________________
329 Bool_t AliEMCALRecoUtils::AcceptCalibrateCell(const Int_t absID, const Int_t bc,
330                                               Float_t  & amp,    Double_t & time, 
331                                               AliVCaloCells* cells) 
332 {
333   // Reject cell if criteria not passed and calibrate it
334   
335   AliEMCALGeometry* geom = AliEMCALGeometry::GetInstance();
336   
337   if(absID < 0 || absID >= 24*48*geom->GetNumberOfSuperModules()) return kFALSE;
338   
339   Int_t imod = -1, iphi =-1, ieta=-1,iTower = -1, iIphi = -1, iIeta = -1; 
340   
341   if(!geom->GetCellIndex(absID,imod,iTower,iIphi,iIeta)) 
342   {
343     // cell absID does not exist
344     amp=0; time = 1.e9;
345     return kFALSE; 
346   }
347   
348   geom->GetCellPhiEtaIndexInSModule(imod,iTower,iIphi, iIeta,iphi,ieta);        
349
350   // Do not include bad channels found in analysis,
351   if( IsBadChannelsRemovalSwitchedOn() && GetEMCALChannelStatus(imod, ieta, iphi)) 
352   {
353     return kFALSE;
354   }
355   
356   //Recalibrate energy
357   amp  = cells->GetCellAmplitude(absID);
358   if(!fCellsRecalibrated && IsRecalibrationOn())
359     amp *= GetEMCALChannelRecalibrationFactor(imod,ieta,iphi);
360   
361   
362   // Recalibrate time
363   time = cells->GetCellTime(absID);
364   
365   RecalibrateCellTime(absID,bc,time);
366   
367   return kTRUE;
368 }
369
370 //_____________________________________________________________________________
371 Bool_t AliEMCALRecoUtils::CheckCellFiducialRegion(const AliEMCALGeometry* geom, 
372                                                   const AliVCluster* cluster, 
373                                                   AliVCaloCells* cells) 
374 {
375         // Given the list of AbsId of the cluster, get the maximum cell and 
376         // check if there are fNCellsFromBorder from the calorimeter border
377         
378   if(!cluster)
379   {
380     AliInfo("Cluster pointer null!");
381     return kFALSE;
382   }
383   
384   //If the distance to the border is 0 or negative just exit accept all clusters
385         if(cells->GetType()==AliVCaloCells::kEMCALCell && fNCellsFromEMCALBorder <= 0 ) return kTRUE;
386   
387   Int_t absIdMax        = -1, iSM =-1, ieta = -1, iphi = -1;
388   Bool_t shared = kFALSE;
389   GetMaxEnergyCell(geom, cells, cluster, absIdMax,  iSM, ieta, iphi, shared);
390   
391   AliDebug(2,Form("Cluster Max AbsId %d, Cell Energy %2.2f, Cluster Energy %2.2f, Ncells from border %d, EMCAL eta=0 %d\n", 
392                   absIdMax, cells->GetCellAmplitude(absIdMax), cluster->E(), fNCellsFromEMCALBorder, fNoEMCALBorderAtEta0));
393         
394         if(absIdMax==-1) return kFALSE;
395         
396         //Check if the cell is close to the borders:
397         Bool_t okrow = kFALSE;
398         Bool_t okcol = kFALSE;
399   
400   if(iSM < 0 || iphi < 0 || ieta < 0 ) 
401   {
402     AliFatal(Form("Negative value for super module: %d, or cell ieta: %d, or cell iphi: %d, check EMCAL geometry name\n",
403                   iSM,ieta,iphi));
404   }
405   
406   //Check rows/phi
407   if(iSM < 10)
408   {
409     if(iphi >= fNCellsFromEMCALBorder && iphi < 24-fNCellsFromEMCALBorder) okrow =kTRUE; 
410   }
411   else if (iSM >=10 && ( ( geom->GetEMCGeometry()->GetGeoName()).Contains("12SMV1"))) 
412   {
413     if(iphi >= fNCellsFromEMCALBorder && iphi < 8-fNCellsFromEMCALBorder) okrow =kTRUE; //1/3 sm case
414   }
415   else 
416   {
417     if(iphi >= fNCellsFromEMCALBorder && iphi < 12-fNCellsFromEMCALBorder) okrow =kTRUE; // half SM case
418   }
419   
420   //Check columns/eta
421   if(!fNoEMCALBorderAtEta0)
422   {
423     if(ieta  > fNCellsFromEMCALBorder && ieta < 48-fNCellsFromEMCALBorder) okcol =kTRUE; 
424   }
425   else
426   {
427     if(iSM%2==0)
428     {
429       if(ieta >= fNCellsFromEMCALBorder)     okcol = kTRUE;     
430     }
431     else 
432     {
433       if(ieta <  48-fNCellsFromEMCALBorder)  okcol = kTRUE;     
434     }
435   }//eta 0 not checked
436   
437   AliDebug(2,Form("EMCAL Cluster in %d cells fiducial volume: ieta %d, iphi %d, SM %d:  column? %d, row? %d\nq",
438                   fNCellsFromEMCALBorder, ieta, iphi, iSM, okcol, okrow));
439         
440         if (okcol && okrow) 
441   {
442     //printf("Accept\n");
443     return kTRUE;
444   }
445         else  
446   {
447     //printf("Reject\n");
448     AliDebug(2,Form("Reject cluster in border, max cell : ieta %d, iphi %d, SM %d\n",ieta, iphi, iSM));
449     return kFALSE;
450   }
451         
452 }       
453
454
455 //_______________________________________________________________________________
456 Bool_t AliEMCALRecoUtils::ClusterContainsBadChannel(const AliEMCALGeometry* geom, 
457                                                     const UShort_t* cellList, 
458                                                     const Int_t nCells)
459 {
460   // Check that in the cluster cells, there is no bad channel of those stored 
461   // in fEMCALBadChannelMap or fPHOSBadChannelMap
462         
463   if(!fRemoveBadChannels)  return kFALSE;
464   if(!fEMCALBadChannelMap) return kFALSE;
465         
466   Int_t icol = -1;
467   Int_t irow = -1;
468   Int_t imod = -1;
469   for(Int_t iCell = 0; iCell<nCells; iCell++)
470   {
471     //Get the column and row
472     Int_t iTower = -1, iIphi = -1, iIeta = -1; 
473     geom->GetCellIndex(cellList[iCell],imod,iTower,iIphi,iIeta); 
474     if(fEMCALBadChannelMap->GetEntries() <= imod) continue;
475     geom->GetCellPhiEtaIndexInSModule(imod,iTower,iIphi, iIeta,irow,icol);                      
476     if(GetEMCALChannelStatus(imod, icol, irow))
477     {
478       AliDebug(2,Form("Cluster with bad channel: SM %d, col %d, row %d\n",imod, icol, irow));
479       return kTRUE;
480     }
481                 
482   }// cell cluster loop
483         
484   return kFALSE;
485 }
486
487 //_____________________________________________________________________________________________
488 Bool_t AliEMCALRecoUtils::IsExoticCell(const Int_t absID, AliVCaloCells* cells, const Int_t bc)
489 {
490   // Look to cell neighbourhood and reject if it seems exotic
491   // Do before recalibrating the cells
492
493   if(!fRejectExoticCells) return kFALSE;
494   
495   AliEMCALGeometry * geom = AliEMCALGeometry::GetInstance();
496   
497   Int_t imod = -1, iphi =-1, ieta=-1,iTower = -1, iIphi = -1, iIeta = -1; 
498   geom->GetCellIndex(absID,imod,iTower,iIphi,iIeta); 
499   geom->GetCellPhiEtaIndexInSModule(imod,iTower,iIphi, iIeta,iphi,ieta);        
500   
501   //Get close cells index, energy and time, not in corners
502
503   Int_t absID1 = -1;
504   Int_t absID2 = -1;
505   
506   if( iphi < AliEMCALGeoParams::fgkEMCALRows-1) absID1 = geom-> GetAbsCellIdFromCellIndexes(imod, iphi+1, ieta);
507   if( iphi > 0 )                                absID2 = geom-> GetAbsCellIdFromCellIndexes(imod, iphi-1, ieta);
508   
509   // In case of cell in eta = 0 border, depending on SM shift the cross cell index
510
511   Int_t absID3 = -1;
512   Int_t absID4 = -1;
513   
514   
515   if     ( ieta == AliEMCALGeoParams::fgkEMCALCols-1 && !(imod%2) )
516   {
517     absID3 = geom-> GetAbsCellIdFromCellIndexes(imod+1, iphi, 0);
518     absID4 = geom-> GetAbsCellIdFromCellIndexes(imod,   iphi, ieta-1); 
519   }
520   else if( ieta == 0 && imod%2 )
521   {
522     absID3 = geom-> GetAbsCellIdFromCellIndexes(imod,   iphi, ieta+1);
523     absID4 = geom-> GetAbsCellIdFromCellIndexes(imod-1, iphi, AliEMCALGeoParams::fgkEMCALCols-1); 
524   }
525   else
526   {
527     if( ieta < AliEMCALGeoParams::fgkEMCALCols-1 ) 
528       absID3 = geom-> GetAbsCellIdFromCellIndexes(imod, iphi, ieta+1);
529     if( ieta > 0 )                                 
530       absID4 = geom-> GetAbsCellIdFromCellIndexes(imod, iphi, ieta-1); 
531   }
532
533   //printf("IMOD %d, AbsId %d, a %d, b %d, c %d e %d \n",imod,absID,absID1,absID2,absID3,absID4);
534
535   
536   Float_t  ecell  = 0, ecell1  = 0, ecell2  = 0, ecell3  = 0, ecell4  = 0;
537   Double_t tcell  = 0, tcell1  = 0, tcell2  = 0, tcell3  = 0, tcell4  = 0;
538   Bool_t   accept = 0, accept1 = 0, accept2 = 0, accept3 = 0, accept4 = 0;
539   
540   accept  = AcceptCalibrateCell(absID, bc, ecell ,tcell ,cells); 
541     
542   if(!accept) return kTRUE; // reject this cell
543   
544   if(ecell < fExoticCellMinAmplitude) return kFALSE; // do not reject low energy cells
545   
546   accept1 = AcceptCalibrateCell(absID1,bc, ecell1,tcell1,cells); 
547   accept2 = AcceptCalibrateCell(absID2,bc, ecell2,tcell2,cells); 
548   accept3 = AcceptCalibrateCell(absID3,bc, ecell3,tcell3,cells); 
549   accept4 = AcceptCalibrateCell(absID4,bc, ecell4,tcell4,cells); 
550   
551   /*
552     printf("Cell absID %d \n",absID);
553     printf("\t  accept1 %d, accept2 %d, accept3 %d, accept4 %d\n",
554            accept1,accept2,accept3,accept4);
555     printf("\t id %d: id1 %d, id2 %d, id3 %d, id4 %d\n",
556            absID,absID1,absID2,absID3,absID4);
557     printf("\t e %f: e1 %f, e2 %f, e3 %f, e4 %f\n",
558            ecell,ecell1,ecell2,ecell3,ecell4);
559     printf("\t t %f: t1 %f, t2 %f, t3 %f, t4 %f;\n dt1 %f, dt2 %f, dt3 %f, dt4 %f\n",
560            tcell*1.e9,tcell1*1.e9,tcell2*1.e9,tcell3*1.e9,tcell4*1.e9,
561            TMath::Abs(tcell-tcell1)*1.e9, TMath::Abs(tcell-tcell2)*1.e9, TMath::Abs(tcell-tcell3)*1.e9, TMath::Abs(tcell-tcell4)*1.e9);
562   */
563   
564   if(TMath::Abs(tcell-tcell1)*1.e9 > fExoticCellDiffTime) ecell1 = 0 ;
565   if(TMath::Abs(tcell-tcell2)*1.e9 > fExoticCellDiffTime) ecell2 = 0 ;
566   if(TMath::Abs(tcell-tcell3)*1.e9 > fExoticCellDiffTime) ecell3 = 0 ;
567   if(TMath::Abs(tcell-tcell4)*1.e9 > fExoticCellDiffTime) ecell4 = 0 ;
568
569   Float_t eCross = ecell1+ecell2+ecell3+ecell4;
570
571   //printf("\t eCell %f, eCross %f, 1-eCross/eCell %f\n",ecell,eCross,1-eCross/ecell);
572   
573   if(1-eCross/ecell > fExoticCellFraction) 
574   {
575     AliDebug(2,Form("AliEMCALRecoUtils::IsExoticCell() - EXOTIC CELL id %d, eCell %f, eCross %f, 1-eCross/eCell %f\n",
576                     absID,ecell,eCross,1-eCross/ecell));
577     return kTRUE;
578   }
579
580   return kFALSE;
581 }
582
583 //___________________________________________________________________
584 Bool_t AliEMCALRecoUtils::IsExoticCluster(const AliVCluster *cluster, 
585                                           AliVCaloCells *cells, 
586                                           const Int_t bc) 
587 {
588   // Check if the cluster highest energy tower is exotic
589   
590   if(!cluster)
591   {
592     AliInfo("Cluster pointer null!");
593     return kFALSE;
594   }
595   
596   if(!fRejectExoticCluster) return kFALSE;
597   
598   // Get highest energy tower
599   AliEMCALGeometry* geom = AliEMCALGeometry::GetInstance();
600   Int_t iSupMod = -1, absId = -1, ieta = -1, iphi = -1;
601   Bool_t shared = kFALSE;
602   GetMaxEnergyCell(geom, cells, cluster, absId, iSupMod, ieta, iphi, shared);
603   
604   return IsExoticCell(absId,cells,bc);
605   
606 }
607
608 //_______________________________________________________________________
609 Float_t AliEMCALRecoUtils::SmearClusterEnergy(const AliVCluster* cluster) 
610 {
611   //In case of MC analysis, smear energy to match resolution/calibration in real data
612   
613   if(!cluster)
614   {
615     AliInfo("Cluster pointer null!");
616     return 0;
617   }
618   
619   Float_t energy    = cluster->E() ;
620   Float_t rdmEnergy = energy ;
621   if(fSmearClusterEnergy)
622   {
623     rdmEnergy = fRandom.Gaus(energy,fSmearClusterParam[0] * TMath::Sqrt(energy) +
624                                     fSmearClusterParam[1] * energy +
625                                     fSmearClusterParam[2] );
626     AliDebug(2, Form("Energy: original %f, smeared %f\n", energy, rdmEnergy));
627   }
628   
629   return rdmEnergy;
630 }
631
632 //____________________________________________________________________________
633 Float_t AliEMCALRecoUtils::CorrectClusterEnergyLinearity(AliVCluster* cluster)
634 {
635   // Correct cluster energy from non linearity functions
636   
637   if(!cluster)
638   {
639     AliInfo("Cluster pointer null!");
640     return 0;
641   }
642   
643   Float_t energy = cluster->E();
644
645   switch (fNonLinearityFunction) 
646   {
647       
648     case kPi0MC:
649     {
650       //Non-Linearity correction (from MC with function ([0]*exp(-[1]/E))+(([2]/([3]*2.*TMath::Pi())*exp(-(E-[4])^2/(2.*[3]^2)))))
651       //Double_t fNonLinearityParams[0] = 1.014;
652       //Double_t fNonLinearityParams[1] = -0.03329;
653       //Double_t fNonLinearityParams[2] = -0.3853;
654       //Double_t fNonLinearityParams[3] = 0.5423;
655       //Double_t fNonLinearityParams[4] = -0.4335;
656        energy *= (fNonLinearityParams[0]*exp(-fNonLinearityParams[1]/energy))+
657                   ((fNonLinearityParams[2]/(fNonLinearityParams[3]*2.*TMath::Pi())*
658                     exp(-(energy-fNonLinearityParams[4])*(energy-fNonLinearityParams[4])/(2.*fNonLinearityParams[3]*fNonLinearityParams[3]))));
659       break;
660     }
661      
662     case kPi0GammaGamma:
663     {
664       //Non-Linearity correction (from Olga Data with function p0+p1*exp(-p2*E))
665       //Double_t fNonLinearityParams[0] = 1.04;
666       //Double_t fNonLinearityParams[1] = -0.1445;
667       //Double_t fNonLinearityParams[2] = 1.046;
668       energy /= (fNonLinearityParams[0]+fNonLinearityParams[1]*exp(-fNonLinearityParams[2]*energy)); //Olga function
669       break;
670     }
671       
672     case kPi0GammaConversion:
673     {
674       //Non-Linearity correction (Nicolas from Dimitri Data with function C*[1-a*exp(-b*E)])
675       //fNonLinearityParams[0] = 0.139393/0.1349766;
676       //fNonLinearityParams[1] = 0.0566186;
677       //fNonLinearityParams[2] = 0.982133;
678       energy /= fNonLinearityParams[0]*(1-fNonLinearityParams[1]*exp(-fNonLinearityParams[2]*energy));
679       
680       break;
681     }
682       
683     case kBeamTest:
684     {
685       //From beam test, Alexei's results, for different ZS thresholds
686       //                        th=30 MeV; th = 45 MeV; th = 75 MeV
687       //fNonLinearityParams[0] = 1.007;      1.003;      1.002 
688       //fNonLinearityParams[1] = 0.894;      0.719;      0.797 
689       //fNonLinearityParams[2] = 0.246;      0.334;      0.358 
690       //Rescale the param[0] with 1.03
691       energy /= fNonLinearityParams[0]/(1+fNonLinearityParams[1]*exp(-energy/fNonLinearityParams[2]));
692       
693       break;
694     }
695       
696     case kBeamTestCorrected:
697     {
698       //From beam test, corrected for material between beam and EMCAL
699       //fNonLinearityParams[0] =  0.99078
700       //fNonLinearityParams[1] =  0.161499;
701       //fNonLinearityParams[2] =  0.655166; 
702       //fNonLinearityParams[3] =  0.134101;
703       //fNonLinearityParams[4] =  163.282;
704       //fNonLinearityParams[5] =  23.6904;
705       //fNonLinearityParams[6] =  0.978;
706         energy *= fNonLinearityParams[6]/(fNonLinearityParams[0]*(1./(1.+fNonLinearityParams[1]*exp(-energy/fNonLinearityParams[2]))*1./(1.+fNonLinearityParams[3]*exp((energy-fNonLinearityParams[4])/fNonLinearityParams[5]))));
707
708       break;
709     }
710       
711     case kNoCorrection:
712       AliDebug(2,"No correction on the energy\n");
713       break;
714       
715   }
716
717   return energy;
718 }
719
720 //__________________________________________________
721 void AliEMCALRecoUtils::InitNonLinearityParam()
722 {
723   //Initialising Non Linearity Parameters
724         
725   if(fNonLinearityFunction == kPi0MC) 
726   {
727     fNonLinearityParams[0] = 1.014;
728     fNonLinearityParams[1] = -0.03329;
729     fNonLinearityParams[2] = -0.3853;
730     fNonLinearityParams[3] = 0.5423;
731     fNonLinearityParams[4] = -0.4335;
732   }
733   
734   if(fNonLinearityFunction == kPi0GammaGamma) 
735   {
736     fNonLinearityParams[0] = 1.04;
737     fNonLinearityParams[1] = -0.1445;
738     fNonLinearityParams[2] = 1.046;
739   }     
740
741   if(fNonLinearityFunction == kPi0GammaConversion) 
742   {
743     fNonLinearityParams[0] = 0.139393;
744     fNonLinearityParams[1] = 0.0566186;
745     fNonLinearityParams[2] = 0.982133;
746   }     
747
748   if(fNonLinearityFunction == kBeamTest) 
749   {
750     if(fNonLinearThreshold == 30) 
751     {
752       fNonLinearityParams[0] = 1.007; 
753       fNonLinearityParams[1] = 0.894; 
754       fNonLinearityParams[2] = 0.246; 
755     }
756     if(fNonLinearThreshold == 45) 
757     {
758       fNonLinearityParams[0] = 1.003; 
759       fNonLinearityParams[1] = 0.719; 
760       fNonLinearityParams[2] = 0.334; 
761     }
762     if(fNonLinearThreshold == 75) 
763     {
764       fNonLinearityParams[0] = 1.002; 
765       fNonLinearityParams[1] = 0.797; 
766       fNonLinearityParams[2] = 0.358; 
767     }
768   }
769
770   if(fNonLinearityFunction == kBeamTestCorrected) 
771   {
772     fNonLinearityParams[0] =  0.99078;
773     fNonLinearityParams[1] =  0.161499;
774     fNonLinearityParams[2] =  0.655166; 
775     fNonLinearityParams[3] =  0.134101;
776     fNonLinearityParams[4] =  163.282;
777     fNonLinearityParams[5] =  23.6904;
778     fNonLinearityParams[6] =  0.978;
779   }
780 }
781
782 //_________________________________________________________
783 Float_t  AliEMCALRecoUtils::GetDepth(const Float_t energy, 
784                                      const Int_t iParticle, 
785                                      const Int_t iSM) const 
786 {
787   //Calculate shower depth for a given cluster energy and particle type
788
789   // parameters 
790   Float_t x0    = 1.31;
791   Float_t ecr   = 8;
792   Float_t depth = 0;
793   
794   switch ( iParticle )
795   {
796     case kPhoton:
797       depth = x0 * (TMath::Log(energy*1000/ ecr) + 0.5); //Multiply energy by 1000 to transform to MeV
798       break;
799       
800     case kElectron:
801       depth = x0 * (TMath::Log(energy*1000/ ecr) - 0.5); //Multiply energy by 1000 to transform to MeV
802       break;
803       
804     case kHadron:
805       // hadron 
806       // boxes anc. here
807       if(gGeoManager)
808       {
809         gGeoManager->cd("ALIC_1/XEN1_1");
810         TGeoNode        *geoXEn1    = gGeoManager->GetCurrentNode();
811         TGeoNodeMatrix  *geoSM      = dynamic_cast<TGeoNodeMatrix *>(geoXEn1->GetDaughter(iSM));
812         if(geoSM)
813         {
814           TGeoVolume      *geoSMVol   = geoSM->GetVolume(); 
815           TGeoShape       *geoSMShape = geoSMVol->GetShape();
816           TGeoBBox        *geoBox     = dynamic_cast<TGeoBBox *>(geoSMShape);
817           if(geoBox) depth = 0.5 * geoBox->GetDX()*2 ;
818           else AliFatal("Null GEANT box");
819         }
820         else AliFatal("NULL  GEANT node matrix");
821       }
822       else
823       {//electron
824         depth = x0 * (TMath::Log(energy*1000 / ecr)  - 0.5); //Multiply energy by 1000 to transform to MeV
825       }
826         
827       break;
828       
829     default://photon
830       depth = x0 * (TMath::Log(energy*1000 / ecr) + 0.5); //Multiply energy by 1000 to transform to MeV
831   }  
832   
833   return depth;
834 }
835
836 //____________________________________________________________________
837 void AliEMCALRecoUtils::GetMaxEnergyCell(const AliEMCALGeometry *geom, 
838                                          AliVCaloCells* cells, 
839                                          const AliVCluster* clu, 
840                                          Int_t  & absId,  
841                                          Int_t  & iSupMod, 
842                                          Int_t  & ieta, 
843                                          Int_t  & iphi, 
844                                          Bool_t & shared)
845 {
846   //For a given CaloCluster gets the absId of the cell 
847   //with maximum energy deposit.
848   
849   Double_t eMax        = -1.;
850   Double_t eCell       = -1.;
851   Float_t  fraction    = 1.;
852   Float_t  recalFactor = 1.;
853   Int_t    cellAbsId   = -1 ;
854
855   Int_t iTower  = -1;
856   Int_t iIphi   = -1;
857   Int_t iIeta   = -1;
858   Int_t iSupMod0= -1;
859
860   if(!clu)
861   {
862     AliInfo("Cluster pointer null!");
863     absId=-1; iSupMod0=-1, ieta = -1; iphi = -1; shared = -1;
864     return;
865   }
866   
867   for (Int_t iDig=0; iDig< clu->GetNCells(); iDig++) 
868   {
869     cellAbsId = clu->GetCellAbsId(iDig);
870     fraction  = clu->GetCellAmplitudeFraction(iDig);
871     //printf("a Cell %d, id, %d, amp %f, fraction %f\n",iDig,cellAbsId,cells->GetCellAmplitude(cellAbsId),fraction);
872     if(fraction < 1e-4) fraction = 1.; // in case unfolding is off
873     geom->GetCellIndex(cellAbsId,iSupMod,iTower,iIphi,iIeta); 
874     geom->GetCellPhiEtaIndexInSModule(iSupMod,iTower,iIphi, iIeta,iphi,ieta);
875     if     (iDig==0) 
876     {
877       iSupMod0=iSupMod;
878     }
879     else if(iSupMod0!=iSupMod) 
880     {
881       shared = kTRUE;
882       //printf("AliEMCALRecoUtils::GetMaxEnergyCell() - SHARED CLUSTER\n");
883     }
884     if(!fCellsRecalibrated && IsRecalibrationOn()) 
885     {
886       recalFactor = GetEMCALChannelRecalibrationFactor(iSupMod,ieta,iphi);
887     }
888     eCell  = cells->GetCellAmplitude(cellAbsId)*fraction*recalFactor;
889     //printf("b Cell %d, id, %d, amp %f, fraction %f\n",iDig,cellAbsId,eCell,fraction);
890     if(eCell > eMax)  
891     { 
892       eMax  = eCell; 
893       absId = cellAbsId;
894       //printf("\t new max: cell %d, e %f, ecell %f\n",maxId, eMax,eCell);
895     }
896   }// cell loop
897   
898   //Get from the absid the supermodule, tower and eta/phi numbers
899   geom->GetCellIndex(absId,iSupMod,iTower,iIphi,iIeta); 
900   //Gives SuperModule and Tower numbers
901   geom->GetCellPhiEtaIndexInSModule(iSupMod,iTower,
902                                          iIphi, iIeta,iphi,ieta); 
903   //printf("Max id %d, iSM %d, col %d, row %d\n",absId,iSupMod,ieta,iphi);
904   //printf("Max end---\n");
905 }
906
907 //______________________________________
908 void AliEMCALRecoUtils::InitParameters()
909 {
910   // Initialize data members with default values
911   
912   fParticleType = kPhoton;
913   fPosAlgo      = kUnchanged;
914   fW0           = 4.5;
915   
916   fNonLinearityFunction = kNoCorrection;
917   fNonLinearThreshold   = 30;
918   
919   fExoticCellFraction     = 0.97;
920   fExoticCellDiffTime     = 1e6;
921   fExoticCellMinAmplitude = 0.5;
922   
923   fAODFilterMask = 32;
924   
925   fCutEtaPhiSum      = kTRUE;
926   fCutEtaPhiSeparate = kFALSE;
927   
928   fCutR   = 0.05; 
929   fCutEta = 0.025; 
930   fCutPhi = 0.05;
931   
932   fClusterWindow = 100;
933   fMass          = 0.139;
934   
935   fStepSurface   = 20.;                      
936   fStepCluster   = 5.;
937   fTrackCutsType = kLooseCut;
938   
939   fCutMinTrackPt     = 0;
940   fCutMinNClusterTPC = -1;
941   fCutMinNClusterITS = -1;
942   
943   fCutMaxChi2PerClusterTPC  = 1e10;
944   fCutMaxChi2PerClusterITS  = 1e10;
945   
946   fCutRequireTPCRefit     = kFALSE;
947   fCutRequireITSRefit     = kFALSE;
948   fCutAcceptKinkDaughters = kFALSE;
949   
950   fCutMaxDCAToVertexXY = 1e10;             
951   fCutMaxDCAToVertexZ  = 1e10;              
952   fCutDCAToVertex2D    = kFALSE;
953   
954   
955   //Misalignment matrices
956   for(Int_t i = 0; i < 15 ; i++) 
957   {
958     fMisalTransShift[i] = 0.; 
959     fMisalRotShift[i]   = 0.; 
960   }
961   
962   //Non linearity
963   for(Int_t i = 0; i < 7  ; i++) fNonLinearityParams[i] = 0.; 
964   
965   //For kBeamTestCorrected case, but default is no correction
966   fNonLinearityParams[0] =  0.99078;
967   fNonLinearityParams[1] =  0.161499;
968   fNonLinearityParams[2] =  0.655166; 
969   fNonLinearityParams[3] =  0.134101;
970   fNonLinearityParams[4] =  163.282;
971   fNonLinearityParams[5] =  23.6904;
972   fNonLinearityParams[6] =  0.978;
973   
974   //For kPi0GammaGamma case
975   //fNonLinearityParams[0] = 0.1457/0.1349766/1.038;
976   //fNonLinearityParams[1] = -0.02024/0.1349766/1.038;
977   //fNonLinearityParams[2] = 1.046;
978   
979   //Cluster energy smearing
980   fSmearClusterEnergy   = kFALSE;
981   fSmearClusterParam[0] = 0.07; // * sqrt E term
982   fSmearClusterParam[1] = 0.00; // * E term
983   fSmearClusterParam[2] = 0.00; // constant
984 }
985
986 //_____________________________________________________
987 void AliEMCALRecoUtils::InitEMCALRecalibrationFactors()
988 {
989   //Init EMCAL recalibration factors
990   AliDebug(2,"AliCalorimeterUtils::InitEMCALRecalibrationFactors()");
991         //In order to avoid rewriting the same histograms
992   Bool_t oldStatus = TH1::AddDirectoryStatus();
993   TH1::AddDirectory(kFALSE);
994   
995   fEMCALRecalibrationFactors = new TObjArray(12);
996   for (int i = 0; i < 12; i++) 
997     fEMCALRecalibrationFactors->Add(new TH2F(Form("EMCALRecalFactors_SM%d",i),
998                                              Form("EMCALRecalFactors_SM%d",i),  48, 0, 48, 24, 0, 24));
999   //Init the histograms with 1
1000   for (Int_t sm = 0; sm < 12; sm++) 
1001   {
1002     for (Int_t i = 0; i < 48; i++) 
1003     {
1004       for (Int_t j = 0; j < 24; j++) 
1005       {
1006         SetEMCALChannelRecalibrationFactor(sm,i,j,1.);
1007       }
1008     }
1009   }
1010   
1011   fEMCALRecalibrationFactors->SetOwner(kTRUE);
1012   fEMCALRecalibrationFactors->Compress();
1013         
1014   //In order to avoid rewriting the same histograms
1015   TH1::AddDirectory(oldStatus);         
1016 }
1017
1018 //_________________________________________________________
1019 void AliEMCALRecoUtils::InitEMCALTimeRecalibrationFactors()
1020 {
1021   //Init EMCAL recalibration factors
1022   AliDebug(2,"AliCalorimeterUtils::InitEMCALRecalibrationFactors()");
1023   //In order to avoid rewriting the same histograms
1024   Bool_t oldStatus = TH1::AddDirectoryStatus();
1025   TH1::AddDirectory(kFALSE);
1026   
1027   fEMCALTimeRecalibrationFactors = new TObjArray(4);
1028   for (int i = 0; i < 4; i++) 
1029     fEMCALTimeRecalibrationFactors->Add(new TH1F(Form("hAllTimeAvBC%d",i),
1030                                                  Form("hAllTimeAvBC%d",i),  
1031                                                  48*24*12,0.,48*24*12)          );
1032   //Init the histograms with 1
1033   for (Int_t bc = 0; bc < 4; bc++) 
1034   {
1035     for (Int_t i = 0; i < 48*24*12; i++) 
1036       SetEMCALChannelTimeRecalibrationFactor(bc,i,0.);
1037   }
1038   
1039   fEMCALTimeRecalibrationFactors->SetOwner(kTRUE);
1040   fEMCALTimeRecalibrationFactors->Compress();
1041   
1042   //In order to avoid rewriting the same histograms
1043   TH1::AddDirectory(oldStatus);         
1044 }
1045
1046 //____________________________________________________
1047 void AliEMCALRecoUtils::InitEMCALBadChannelStatusMap()
1048 {
1049   //Init EMCAL bad channels map
1050   AliDebug(2,"AliEMCALRecoUtils::InitEMCALBadChannelStatusMap()");
1051   //In order to avoid rewriting the same histograms
1052   Bool_t oldStatus = TH1::AddDirectoryStatus();
1053   TH1::AddDirectory(kFALSE);
1054   
1055   fEMCALBadChannelMap = new TObjArray(12);
1056   //TH2F * hTemp = new  TH2I("EMCALBadChannelMap","EMCAL SuperModule bad channel map", 48, 0, 48, 24, 0, 24);
1057   for (int i = 0; i < 12; i++) 
1058   {
1059     fEMCALBadChannelMap->Add(new TH2I(Form("EMCALBadChannelMap_Mod%d",i),Form("EMCALBadChannelMap_Mod%d",i), 48, 0, 48, 24, 0, 24));
1060   }
1061   
1062   fEMCALBadChannelMap->SetOwner(kTRUE);
1063   fEMCALBadChannelMap->Compress();
1064   
1065   //In order to avoid rewriting the same histograms
1066   TH1::AddDirectory(oldStatus);         
1067 }
1068
1069 //____________________________________________________________________________
1070 void AliEMCALRecoUtils::RecalibrateClusterEnergy(const AliEMCALGeometry* geom, 
1071                                                  AliVCluster * cluster, 
1072                                                  AliVCaloCells * cells, 
1073                                                  const Int_t bc)
1074 {
1075   // Recalibrate the cluster energy and Time, considering the recalibration map 
1076   // and the energy of the cells and time that compose the cluster.
1077   // bc= bunch crossing number returned by esdevent->GetBunchCrossNumber();
1078         
1079   if(!cluster)
1080   {
1081     AliInfo("Cluster pointer null!");
1082     return;
1083   }  
1084   
1085   //Get the cluster number of cells and list of absId, check what kind of cluster do we have.
1086   UShort_t * index    = cluster->GetCellsAbsId() ;
1087   Double_t * fraction = cluster->GetCellsAmplitudeFraction() ;
1088   Int_t ncells = cluster->GetNCells();
1089         
1090   //Initialize some used variables
1091   Float_t energy = 0;
1092   Int_t   absId  =-1;
1093   Int_t   icol   =-1, irow =-1, imod=1;
1094   Float_t factor = 1, frac = 0;
1095   Int_t   absIdMax = -1;
1096   Float_t emax     = 0;
1097   
1098   //Loop on the cells, get the cell amplitude and recalibration factor, multiply and and to the new energy
1099   for(Int_t icell = 0; icell < ncells; icell++)
1100   {
1101     absId = index[icell];
1102     frac =  fraction[icell];
1103     if(frac < 1e-5) frac = 1; //in case of EMCAL, this is set as 0 since unfolding is off
1104     
1105     if(!fCellsRecalibrated && IsRecalibrationOn()) 
1106     {
1107       // Energy  
1108       Int_t iTower = -1, iIphi = -1, iIeta = -1; 
1109       geom->GetCellIndex(absId,imod,iTower,iIphi,iIeta); 
1110       if(fEMCALRecalibrationFactors->GetEntries() <= imod) continue;
1111       geom->GetCellPhiEtaIndexInSModule(imod,iTower,iIphi, iIeta,irow,icol);                    
1112       factor = GetEMCALChannelRecalibrationFactor(imod,icol,irow);
1113       
1114       AliDebug(2,Form("AliEMCALRecoUtils::RecalibrateClusterEnergy - recalibrate cell: module %d, col %d, row %d, cell fraction %f,recalibration factor %f, cell energy %f\n",
1115                       imod,icol,irow,frac,factor,cells->GetCellAmplitude(absId)));
1116       
1117     } 
1118     
1119     energy += cells->GetCellAmplitude(absId)*factor*frac;
1120     
1121     if(emax < cells->GetCellAmplitude(absId)*factor*frac)
1122     {
1123       emax     = cells->GetCellAmplitude(absId)*factor*frac;
1124       absIdMax = absId;
1125     }
1126   }
1127         
1128   AliDebug(2,Form("AliEMCALRecoUtils::RecalibrateClusterEnergy - Energy before %f, after %f \n",cluster->E(),energy));
1129
1130   cluster->SetE(energy);
1131
1132   // Recalculate time of cluster   
1133   Double_t timeorg = cluster->GetTOF();
1134   if(!fCellsRecalibrated && IsTimeRecalibrationOn())
1135   {
1136     Double_t time = timeorg;
1137     RecalibrateCellTime(absIdMax,bc,time);
1138     cluster->SetTOF(time);
1139   } 
1140
1141   AliDebug(2,Form("AliEMCALRecoUtils::RecalibrateClusterEnergy - Time before %f, after %f \n",timeorg,cluster->GetTOF()));
1142
1143 }
1144
1145 //_____________________________________________________________
1146 void AliEMCALRecoUtils::RecalibrateCells(AliVCaloCells * cells,
1147                                          const Int_t bc)
1148 {
1149   // Recalibrate the cells time and energy, considering the recalibration map and the energy 
1150   // of the cells that compose the cluster.
1151   // bc= bunch crossing number returned by esdevent->GetBunchCrossNumber();
1152
1153   if(!IsRecalibrationOn() && !IsTimeRecalibrationOn()) return;
1154   
1155   if(!cells)
1156   {
1157     AliInfo("Cells pointer null!");
1158     return;
1159   }  
1160   
1161   Int_t    absId  =-1;
1162   Bool_t   accept = kFALSE;
1163   Float_t  ecell  = 0;
1164   Double_t tcell  = 0;
1165   
1166   Int_t nEMcell  = cells->GetNumberOfCells() ;  
1167   for (Int_t iCell = 0; iCell < nEMcell; iCell++) 
1168   { 
1169     absId  = cells->GetCellNumber(iCell);
1170     
1171     accept = AcceptCalibrateCell(absId, bc, ecell ,tcell ,cells); 
1172     if(!accept) 
1173     {
1174       ecell = 0;
1175       tcell = 0;
1176     }
1177     
1178     //Set new values
1179     cells->SetCell(iCell,absId,ecell, tcell);
1180   }
1181
1182   fCellsRecalibrated = kTRUE;
1183 }
1184
1185 //_______________________________________________________________________________________________________
1186 void AliEMCALRecoUtils::RecalibrateCellTime(const Int_t absId, const Int_t bc, Double_t & celltime) const
1187 {
1188   // Recalibrate time of cell with absID  considering the recalibration map 
1189   // bc= bunch crossing number returned by esdevent->GetBunchCrossNumber();
1190   
1191   if(!fCellsRecalibrated && IsTimeRecalibrationOn() && bc >= 0)
1192   {
1193     celltime -= GetEMCALChannelTimeRecalibrationFactor(bc%4,absId)*1.e-9;    ;  
1194   }
1195 }
1196   
1197 //______________________________________________________________________________
1198 void AliEMCALRecoUtils::RecalculateClusterPosition(const AliEMCALGeometry *geom, 
1199                                                    AliVCaloCells* cells, 
1200                                                    AliVCluster* clu)
1201 {
1202   //For a given CaloCluster recalculates the position for a given set of misalignment shifts and puts it again in the CaloCluster.
1203   
1204   if(!clu)
1205   {
1206     AliInfo("Cluster pointer null!");
1207     return;
1208   }
1209     
1210   if     (fPosAlgo==kPosTowerGlobal) RecalculateClusterPositionFromTowerGlobal( geom, cells, clu);
1211   else if(fPosAlgo==kPosTowerIndex)  RecalculateClusterPositionFromTowerIndex ( geom, cells, clu);
1212   else   AliDebug(2,"Algorithm to recalculate position not selected, do nothing.");
1213 }  
1214
1215 //_____________________________________________________________________________________________
1216 void AliEMCALRecoUtils::RecalculateClusterPositionFromTowerGlobal(const AliEMCALGeometry *geom, 
1217                                                                   AliVCaloCells* cells, 
1218                                                                   AliVCluster* clu)
1219 {
1220   // For a given CaloCluster recalculates the position for a given set of misalignment shifts and puts it again in the CaloCluster.
1221   // The algorithm is a copy of what is done in AliEMCALRecPoint
1222   
1223   Double_t eCell       = 0.;
1224   Float_t  fraction    = 1.;
1225   Float_t  recalFactor = 1.;
1226   
1227   Int_t    absId   = -1;
1228   Int_t    iTower  = -1, iIphi  = -1, iIeta  = -1;
1229   Int_t    iSupModMax = -1, iSM=-1, iphi   = -1, ieta   = -1;
1230   Float_t  weight = 0.,  totalWeight=0.;
1231   Float_t  newPos[3] = {0,0,0};
1232   Double_t pLocal[3], pGlobal[3];
1233   Bool_t shared = kFALSE;
1234
1235   Float_t  clEnergy = clu->E(); //Energy already recalibrated previously
1236   GetMaxEnergyCell(geom, cells, clu, absId,  iSupModMax, ieta, iphi,shared);
1237   Double_t depth = GetDepth(clEnergy,fParticleType,iSupModMax) ;
1238   
1239   //printf("** Cluster energy %f, ncells %d, depth %f\n",clEnergy,clu->GetNCells(),depth);
1240   
1241   for (Int_t iDig=0; iDig< clu->GetNCells(); iDig++) 
1242   {
1243     absId = clu->GetCellAbsId(iDig);
1244     fraction  = clu->GetCellAmplitudeFraction(iDig);
1245     if(fraction < 1e-4) fraction = 1.; // in case unfolding is off
1246     
1247     if (!fCellsRecalibrated)
1248     {
1249       geom->GetCellIndex(absId,iSM,iTower,iIphi,iIeta); 
1250       geom->GetCellPhiEtaIndexInSModule(iSM,iTower,iIphi, iIeta,iphi,ieta);                     
1251       
1252       if(IsRecalibrationOn()) 
1253       {
1254         recalFactor = GetEMCALChannelRecalibrationFactor(iSM,ieta,iphi);
1255       }
1256     }
1257     
1258     eCell  = cells->GetCellAmplitude(absId)*fraction*recalFactor;
1259     
1260     weight = GetCellWeight(eCell,clEnergy);
1261     totalWeight += weight;
1262     
1263     geom->RelPosCellInSModule(absId,depth,pLocal[0],pLocal[1],pLocal[2]);
1264     //printf("pLocal (%f,%f,%f), SM %d, absId %d\n",pLocal[0],pLocal[1],pLocal[2],iSupModMax,absId);
1265     geom->GetGlobal(pLocal,pGlobal,iSupModMax);
1266     //printf("pLocal (%f,%f,%f)\n",pGlobal[0],pGlobal[1],pGlobal[2]);
1267
1268     for(int i=0; i<3; i++ ) newPos[i] += (weight*pGlobal[i]);
1269   }// cell loop
1270   
1271   if(totalWeight>0)
1272   {
1273     for(int i=0; i<3; i++ )    newPos[i] /= totalWeight;
1274   }
1275     
1276   //Float_t pos[]={0,0,0};
1277   //clu->GetPosition(pos);
1278   //printf("OldPos  : %2.3f,%2.3f,%2.3f\n",pos[0],pos[1],pos[2]);
1279   //printf("NewPos  : %2.3f,%2.3f,%2.3f\n",newPos[0],newPos[1],newPos[2]);
1280   
1281   if(iSupModMax > 1) //sector 1
1282   {
1283     newPos[0] +=fMisalTransShift[3];//-=3.093; 
1284     newPos[1] +=fMisalTransShift[4];//+=6.82;
1285     newPos[2] +=fMisalTransShift[5];//+=1.635;
1286     //printf("   +    : %2.3f,%2.3f,%2.3f\n",fMisalTransShift[3],fMisalTransShift[4],fMisalTransShift[5]);
1287   } else //sector 0
1288   {
1289     newPos[0] +=fMisalTransShift[0];//+=1.134;
1290     newPos[1] +=fMisalTransShift[1];//+=8.2;
1291     newPos[2] +=fMisalTransShift[2];//+=1.197;
1292     //printf("   +    : %2.3f,%2.3f,%2.3f\n",fMisalTransShift[0],fMisalTransShift[1],fMisalTransShift[2]);
1293   }
1294   //printf("NewPos : %2.3f,%2.3f,%2.3f\n",newPos[0],newPos[1],newPos[2]);
1295
1296   clu->SetPosition(newPos);
1297 }  
1298
1299 //____________________________________________________________________________________________
1300 void AliEMCALRecoUtils::RecalculateClusterPositionFromTowerIndex(const AliEMCALGeometry *geom, 
1301                                                                  AliVCaloCells* cells, 
1302                                                                  AliVCluster* clu)
1303 {
1304   // For a given CaloCluster recalculates the position for a given set of misalignment shifts and puts it again in the CaloCluster.
1305   // The algorithm works with the tower indeces, averages the indeces and from them it calculates the global position
1306   
1307   Double_t eCell       = 1.;
1308   Float_t  fraction    = 1.;
1309   Float_t  recalFactor = 1.;
1310   
1311   Int_t absId   = -1;
1312   Int_t iTower  = -1;
1313   Int_t iIphi   = -1, iIeta   = -1;
1314   Int_t iSupMod = -1, iSupModMax = -1;
1315   Int_t iphi = -1, ieta =-1;
1316   Bool_t shared = kFALSE;
1317
1318   Float_t clEnergy = clu->E(); //Energy already recalibrated previously.
1319   GetMaxEnergyCell(geom, cells, clu, absId,  iSupModMax, ieta, iphi,shared);
1320   Float_t  depth = GetDepth(clEnergy,fParticleType,iSupMod) ;
1321
1322   Float_t weight = 0., weightedCol = 0., weightedRow = 0., totalWeight=0.;
1323   Bool_t areInSameSM = kTRUE; //exclude clusters with cells in different SMs for now
1324   Int_t startingSM = -1;
1325   
1326   for (Int_t iDig=0; iDig< clu->GetNCells(); iDig++) 
1327   {
1328     absId = clu->GetCellAbsId(iDig);
1329     fraction  = clu->GetCellAmplitudeFraction(iDig);
1330     if(fraction < 1e-4) fraction = 1.; // in case unfolding is off
1331
1332     if     (iDig==0)  startingSM = iSupMod;
1333     else if(iSupMod != startingSM) areInSameSM = kFALSE;
1334
1335     eCell  = cells->GetCellAmplitude(absId);
1336     
1337     geom->GetCellIndex(absId,iSupMod,iTower,iIphi,iIeta); 
1338     geom->GetCellPhiEtaIndexInSModule(iSupMod,iTower,iIphi, iIeta,iphi,ieta);           
1339     
1340     if (!fCellsRecalibrated)
1341     {
1342       if(IsRecalibrationOn()) 
1343       {
1344         recalFactor = GetEMCALChannelRecalibrationFactor(iSupMod,ieta,iphi);
1345       }
1346     }
1347     
1348     eCell  = cells->GetCellAmplitude(absId)*fraction*recalFactor;
1349     
1350     weight = GetCellWeight(eCell,clEnergy);
1351     if(weight < 0) weight = 0;
1352     totalWeight += weight;
1353     weightedCol += ieta*weight;
1354     weightedRow += iphi*weight;
1355     
1356     //printf("Max cell? cell %d, amplitude org %f, fraction %f, recalibration %f, amplitude new %f \n",cellAbsId, cells->GetCellAmplitude(cellAbsId), fraction, recalFactor, eCell) ;
1357   }// cell loop
1358     
1359   Float_t xyzNew[]={0.,0.,0.};
1360   if(areInSameSM == kTRUE) 
1361   {
1362     //printf("In Same SM\n");
1363     weightedCol = weightedCol/totalWeight;
1364     weightedRow = weightedRow/totalWeight;
1365     geom->RecalculateTowerPosition(weightedRow, weightedCol, iSupModMax, depth, fMisalTransShift, fMisalRotShift, xyzNew); 
1366   } 
1367   else 
1368   {
1369     //printf("In Different SM\n");
1370     geom->RecalculateTowerPosition(iphi,        ieta,        iSupModMax, depth, fMisalTransShift, fMisalRotShift, xyzNew); 
1371   }
1372   
1373   clu->SetPosition(xyzNew);
1374 }
1375
1376 //___________________________________________________________________________________________
1377 void AliEMCALRecoUtils::RecalculateClusterDistanceToBadChannel(const AliEMCALGeometry * geom, 
1378                                                                AliVCaloCells* cells, 
1379                                                                AliVCluster * cluster)
1380 {           
1381   //re-evaluate distance to bad channel with updated bad map
1382   
1383   if(!fRecalDistToBadChannels) return;
1384   
1385   if(!cluster)
1386   {
1387     AliInfo("Cluster pointer null!");
1388     return;
1389   }  
1390   
1391   //Get channels map of the supermodule where the cluster is.
1392   Int_t absIdMax        = -1, iSupMod =-1, icolM = -1, irowM = -1;
1393   Bool_t shared = kFALSE;
1394   GetMaxEnergyCell(geom, cells, cluster, absIdMax,  iSupMod, icolM, irowM, shared);
1395   TH2D* hMap  = (TH2D*)fEMCALBadChannelMap->At(iSupMod);
1396
1397   Int_t dRrow, dRcol;   
1398   Float_t  minDist = 10000.;
1399   Float_t  dist    = 0.;
1400   
1401   //Loop on tower status map 
1402   for(Int_t irow = 0; irow < AliEMCALGeoParams::fgkEMCALRows; irow++)
1403   {
1404     for(Int_t icol = 0; icol < AliEMCALGeoParams::fgkEMCALCols; icol++)
1405     {
1406       //Check if tower is bad.
1407       if(hMap->GetBinContent(icol,irow)==0) continue;
1408       //printf("AliEMCALRecoUtils::RecalculateDistanceToBadChannels() - \n \t Bad channel in SM %d, col %d, row %d, \n \t Cluster max in col %d, row %d\n",
1409       //       iSupMod,icol, irow, icolM,irowM);
1410       
1411       dRrow=TMath::Abs(irowM-irow);
1412       dRcol=TMath::Abs(icolM-icol);
1413       dist=TMath::Sqrt(dRrow*dRrow+dRcol*dRcol);
1414       if(dist < minDist)
1415       {
1416         //printf("MIN DISTANCE TO BAD %2.2f\n",dist);
1417         minDist = dist;
1418       }
1419     }
1420   }
1421   
1422   //In case the cluster is shared by 2 SuperModules, need to check the map of the second Super Module
1423   if (shared) 
1424   {
1425     TH2D* hMap2 = 0;
1426     Int_t iSupMod2 = -1;
1427     
1428     //The only possible combinations are (0,1), (2,3) ... (8,9)
1429     if(iSupMod%2) iSupMod2 = iSupMod-1;
1430     else          iSupMod2 = iSupMod+1;
1431     hMap2  = (TH2D*)fEMCALBadChannelMap->At(iSupMod2);
1432     
1433     //Loop on tower status map of second super module
1434     for(Int_t irow = 0; irow < AliEMCALGeoParams::fgkEMCALRows; irow++)
1435     {
1436       for(Int_t icol = 0; icol < AliEMCALGeoParams::fgkEMCALCols; icol++)
1437       {
1438         //Check if tower is bad.
1439         if(hMap2->GetBinContent(icol,irow)==0) continue;
1440         //printf("AliEMCALRecoUtils::RecalculateDistanceToBadChannels(shared) - \n \t Bad channel in SM %d, col %d, row %d \n \t Cluster max in SM %d, col %d, row %d\n",
1441         //     iSupMod2,icol, irow,iSupMod,icolM,irowM);
1442         dRrow=TMath::Abs(irow-irowM);
1443         
1444         if(iSupMod%2) 
1445         {
1446           dRcol=TMath::Abs(icol-(AliEMCALGeoParams::fgkEMCALCols+icolM));
1447         } else 
1448         {
1449           dRcol=TMath::Abs(AliEMCALGeoParams::fgkEMCALCols+icol-icolM);
1450         }                    
1451         
1452         dist=TMath::Sqrt(dRrow*dRrow+dRcol*dRcol);
1453         if(dist < minDist) minDist = dist;        
1454       }
1455     }
1456   }// shared cluster in 2 SuperModules
1457   
1458   AliDebug(2,Form("Max cluster cell (SM,col,row)=(%d %d %d) - Distance to Bad Channel %2.2f",iSupMod, icolM, irowM, minDist));
1459   cluster->SetDistanceToBadChannel(minDist);
1460 }
1461
1462 //__________________________________________________________________
1463 void AliEMCALRecoUtils::RecalculateClusterPID(AliVCluster * cluster)
1464 {           
1465   //re-evaluate identification parameters with bayesian
1466   
1467   if(!cluster)
1468   {
1469     AliInfo("Cluster pointer null!");
1470     return;
1471   }
1472   
1473   if ( cluster->GetM02() != 0)
1474     fPIDUtils->ComputePID(cluster->E(),cluster->GetM02());
1475   
1476   Float_t pidlist[AliPID::kSPECIESN+1];
1477         for(Int_t i = 0; i < AliPID::kSPECIESN+1; i++) pidlist[i] = fPIDUtils->GetPIDFinal(i);
1478         
1479   cluster->SetPID(pidlist);
1480 }
1481
1482 //___________________________________________________________________________________________________________________
1483 void AliEMCALRecoUtils::RecalculateClusterShowerShapeParameters(const AliEMCALGeometry * geom, 
1484                                                                 AliVCaloCells* cells, 
1485                                                                 AliVCluster * cluster,
1486                                                                 Float_t & l0,   Float_t & l1,   
1487                                                                 Float_t & disp, Float_t & dEta, Float_t & dPhi,
1488                                                                 Float_t & sEta, Float_t & sPhi, Float_t & sEtaPhi)
1489 {
1490   // Calculates new center of gravity in the local EMCAL-module coordinates 
1491   // and tranfers into global ALICE coordinates
1492   // Calculates Dispersion and main axis
1493   
1494   if(!cluster)
1495   {
1496     AliInfo("Cluster pointer null!");
1497     return;
1498   }
1499     
1500   Double_t eCell       = 0.;
1501   Float_t  fraction    = 1.;
1502   Float_t  recalFactor = 1.;
1503
1504   Int_t    iSupMod = -1;
1505   Int_t    iTower  = -1;
1506   Int_t    iIphi   = -1;
1507   Int_t    iIeta   = -1;
1508   Int_t    iphi    = -1;
1509   Int_t    ieta    = -1;
1510   Double_t etai    = -1.;
1511   Double_t phii    = -1.;
1512   
1513   Int_t    nstat   = 0 ;
1514   Float_t  wtot    = 0.;
1515   Double_t w       = 0.;
1516   Double_t etaMean = 0.;
1517   Double_t phiMean = 0.;
1518     
1519   //Loop on cells
1520   for(Int_t iDigit=0; iDigit < cluster->GetNCells(); iDigit++) 
1521   {
1522     //Get from the absid the supermodule, tower and eta/phi numbers
1523     geom->GetCellIndex(cluster->GetCellAbsId(iDigit),iSupMod,iTower,iIphi,iIeta); 
1524     geom->GetCellPhiEtaIndexInSModule(iSupMod,iTower,iIphi,iIeta, iphi,ieta);        
1525     
1526     //Get the cell energy, if recalibration is on, apply factors
1527     fraction  = cluster->GetCellAmplitudeFraction(iDigit);
1528     if(fraction < 1e-4) fraction = 1.; // in case unfolding is off
1529     
1530     if (!fCellsRecalibrated)
1531     {
1532       if(IsRecalibrationOn()) 
1533       {
1534         recalFactor = GetEMCALChannelRecalibrationFactor(iSupMod,ieta,iphi);
1535       }
1536     }
1537     
1538     eCell  = cells->GetCellAmplitude(cluster->GetCellAbsId(iDigit))*fraction*recalFactor;
1539     
1540     if(cluster->E() > 0 && eCell > 0)
1541     {
1542       w  = GetCellWeight(eCell,cluster->E());
1543       
1544       etai=(Double_t)ieta;
1545       phii=(Double_t)iphi;      
1546       
1547       if(w > 0.0) 
1548       {
1549         wtot += w ;
1550         nstat++;                        
1551         //Shower shape
1552         sEta     += w * etai * etai ;
1553         etaMean  += w * etai ;
1554         sPhi     += w * phii * phii ;
1555         phiMean  += w * phii ; 
1556         sEtaPhi  += w * etai * phii ; 
1557       }
1558     } 
1559     else
1560       AliError(Form("Wrong energy %f and/or amplitude %f\n", eCell, cluster->E()));
1561   }//cell loop
1562   
1563   //Normalize to the weight     
1564   if (wtot > 0) 
1565   {
1566     etaMean /= wtot ;
1567     phiMean /= wtot ;
1568   }
1569   else
1570     AliError(Form("Wrong weight %f\n", wtot));
1571   
1572   //Calculate dispersion        
1573   for(Int_t iDigit=0; iDigit < cluster->GetNCells(); iDigit++) 
1574   {
1575     //Get from the absid the supermodule, tower and eta/phi numbers
1576     geom->GetCellIndex(cluster->GetCellAbsId(iDigit),iSupMod,iTower,iIphi,iIeta); 
1577     geom->GetCellPhiEtaIndexInSModule(iSupMod,iTower,iIphi,iIeta, iphi,ieta);
1578     
1579     //Get the cell energy, if recalibration is on, apply factors
1580     fraction  = cluster->GetCellAmplitudeFraction(iDigit);
1581     if(fraction < 1e-4) fraction = 1.; // in case unfolding is off
1582     if (IsRecalibrationOn()) 
1583     {
1584       recalFactor = GetEMCALChannelRecalibrationFactor(iSupMod,ieta,iphi);
1585     }
1586     eCell  = cells->GetCellAmplitude(cluster->GetCellAbsId(iDigit))*fraction*recalFactor;
1587     
1588     if(cluster->E() > 0 && eCell > 0)
1589     {
1590       w  = GetCellWeight(eCell,cluster->E());
1591       
1592       etai=(Double_t)ieta;
1593       phii=(Double_t)iphi;              
1594       if(w > 0.0) 
1595       { 
1596         disp +=  w *((etai-etaMean)*(etai-etaMean)+(phii-phiMean)*(phii-phiMean)); 
1597         dEta +=  w * (etai-etaMean)*(etai-etaMean) ; 
1598         dPhi +=  w * (phii-phiMean)*(phii-phiMean) ; 
1599       }
1600     }
1601     else
1602       AliError(Form("Wrong energy %f and/or amplitude %f\n", eCell, cluster->E()));
1603   }// cell loop
1604   
1605   //Normalize to the weigth and set shower shape parameters
1606   if (wtot > 0 && nstat > 1) 
1607   {
1608     disp    /= wtot ;
1609     dEta    /= wtot ;
1610     dPhi    /= wtot ;
1611     sEta    /= wtot ;
1612     sPhi    /= wtot ;
1613     sEtaPhi /= wtot ;
1614     
1615     sEta    -= etaMean * etaMean ;
1616     sPhi    -= phiMean * phiMean ;
1617     sEtaPhi -= etaMean * phiMean ;
1618     
1619     l0 = (0.5 * (sEta + sPhi) + TMath::Sqrt( 0.25 * (sEta - sPhi) * (sEta - sPhi) + sEtaPhi * sEtaPhi ));
1620     l1 = (0.5 * (sEta + sPhi) - TMath::Sqrt( 0.25 * (sEta - sPhi) * (sEta - sPhi) + sEtaPhi * sEtaPhi ));
1621   }
1622   else
1623   {
1624     l0   = 0. ;
1625     l1   = 0. ;
1626     dEta = 0. ; dPhi = 0. ; disp    = 0. ;
1627     sEta = 0. ; sPhi = 0. ; sEtaPhi = 0. ;
1628   }     
1629   
1630 }
1631
1632 //____________________________________________________________________________________________
1633 void AliEMCALRecoUtils::RecalculateClusterShowerShapeParameters(const AliEMCALGeometry * geom, 
1634                                                                 AliVCaloCells* cells, 
1635                                                                 AliVCluster * cluster)
1636 {
1637   // Calculates new center of gravity in the local EMCAL-module coordinates 
1638   // and tranfers into global ALICE coordinates
1639   // Calculates Dispersion and main axis and puts them into the cluster
1640   
1641   Float_t l0   = 0., l1   = 0.;
1642   Float_t disp = 0., dEta = 0., dPhi    = 0.; 
1643   Float_t sEta = 0., sPhi = 0., sEtaPhi = 0.;
1644   
1645   AliEMCALRecoUtils::RecalculateClusterShowerShapeParameters(geom,cells,cluster,l0,l1,disp,
1646                                                              dEta, dPhi, sEta, sPhi, sEtaPhi);
1647   
1648   cluster->SetM02(l0);
1649   cluster->SetM20(l1);
1650   if(disp > 0. ) cluster->SetDispersion(TMath::Sqrt(disp)) ;
1651   
1652
1653
1654 //____________________________________________________________________________
1655 void AliEMCALRecoUtils::FindMatches(AliVEvent *event,
1656                                     TObjArray * clusterArr,  
1657                                     const AliEMCALGeometry *geom)
1658 {
1659   //This function should be called before the cluster loop
1660   //Before call this function, please recalculate the cluster positions
1661   //Given the input event, loop over all the tracks, select the closest cluster as matched with fCutR
1662   //Store matched cluster indexes and residuals
1663   
1664   fMatchedTrackIndex  ->Reset();
1665   fMatchedClusterIndex->Reset();
1666   fResidualPhi->Reset();
1667   fResidualEta->Reset();
1668   
1669   fMatchedTrackIndex  ->Set(1000);
1670   fMatchedClusterIndex->Set(1000);
1671   fResidualPhi->Set(1000);
1672   fResidualEta->Set(1000);
1673   
1674   AliESDEvent* esdevent = dynamic_cast<AliESDEvent*> (event);
1675   AliAODEvent* aodevent = dynamic_cast<AliAODEvent*> (event);
1676   
1677   // init the magnetic field if not already on
1678   if(!TGeoGlobalMagField::Instance()->GetField())
1679   {
1680     AliInfo("Init the magnetic field\n");
1681     if     (esdevent) 
1682     {
1683       esdevent->InitMagneticField();
1684     }
1685     else if(aodevent)
1686     {
1687       Double_t curSol = 30000*aodevent->GetMagneticField()/5.00668;
1688       Double_t curDip = 6000 *aodevent->GetMuonMagFieldScale();
1689       AliMagF *field  = AliMagF::CreateFieldMap(curSol,curDip);
1690       TGeoGlobalMagField::Instance()->SetField(field);
1691     }
1692     else
1693     {
1694       AliInfo("Mag Field not initialized, null esd/aod evetn pointers");
1695     }
1696     
1697   } // Init mag field
1698   
1699   TObjArray *clusterArray = 0x0;
1700   if(!clusterArr)
1701     {
1702       clusterArray = new TObjArray(event->GetNumberOfCaloClusters());
1703       for(Int_t icl=0; icl<event->GetNumberOfCaloClusters(); icl++)
1704         {
1705           AliVCluster *cluster = (AliVCluster*) event->GetCaloCluster(icl);
1706           if(geom && !IsGoodCluster(cluster,geom,(AliVCaloCells*)event->GetEMCALCells())) continue;
1707           clusterArray->AddAt(cluster,icl);
1708         }
1709     }
1710   
1711   Int_t    matched=0;
1712   Double_t cv[21];
1713   for (Int_t i=0; i<21;i++) cv[i]=0;
1714   for(Int_t itr=0; itr<event->GetNumberOfTracks(); itr++)
1715   {
1716     AliExternalTrackParam *trackParam = 0;
1717     
1718     //If the input event is ESD, the starting point for extrapolation is TPCOut, if available, or TPCInner 
1719     AliESDtrack *esdTrack = 0;
1720     AliAODTrack *aodTrack = 0;
1721     if(esdevent)
1722     {
1723       esdTrack = esdevent->GetTrack(itr);
1724       if(!esdTrack) continue;
1725       if(!IsAccepted(esdTrack)) continue;
1726       if(esdTrack->Pt()<fCutMinTrackPt) continue;
1727       Double_t phi = esdTrack->Phi()*TMath::RadToDeg();
1728       if(TMath::Abs(esdTrack->Eta())>0.8 || phi <= 20 || phi >= 240 ) continue;
1729       trackParam =  const_cast<AliExternalTrackParam*>(esdTrack->GetInnerParam());
1730     }
1731     
1732     //If the input event is AOD, the starting point for extrapolation is at vertex
1733     //AOD tracks are selected according to its filterbit.
1734     else if(aodevent)
1735     {
1736       aodTrack = aodevent->GetTrack(itr);
1737       if(!aodTrack) continue;
1738       if(!aodTrack->TestFilterMask(fAODFilterMask)) continue; //Select AOD tracks that fulfill GetStandardITSTPCTrackCuts2010()
1739       if(aodTrack->Pt()<fCutMinTrackPt) continue;
1740       Double_t phi = aodTrack->Phi()*TMath::RadToDeg();
1741       if(TMath::Abs(aodTrack->Eta())>0.8 || phi <= 20 || phi >= 240 ) continue;
1742       Double_t pos[3],mom[3];
1743       aodTrack->GetXYZ(pos);
1744       aodTrack->GetPxPyPz(mom);
1745       AliDebug(5,Form("aod track: i=%d | pos=(%5.4f,%5.4f,%5.4f) | mom=(%5.4f,%5.4f,%5.4f) | charge=%d\n",itr,pos[0],pos[1],pos[2],mom[0],mom[1],mom[2],aodTrack->Charge()));
1746       trackParam= new AliExternalTrackParam(pos,mom,cv,aodTrack->Charge());
1747     }
1748     
1749     //Return if the input data is not "AOD" or "ESD"
1750     else
1751     {
1752       printf("Wrong input data type! Should be \"AOD\" or \"ESD\"\n");
1753       if(clusterArray)
1754         {
1755           clusterArray->Clear();
1756           delete clusterArray;
1757         }
1758       return;
1759     }
1760     
1761     if(!trackParam) continue;
1762
1763     //Extrapolate the track to EMCal surface
1764     AliExternalTrackParam emcalParam(*trackParam);
1765     Float_t eta, phi;
1766     if(!ExtrapolateTrackToEMCalSurface(&emcalParam, 430., fMass, fStepSurface, eta, phi)) 
1767       {
1768         if(aodevent && trackParam) delete trackParam;
1769         continue;
1770       }
1771
1772 //    if(esdevent)
1773 //      {
1774 //      esdTrack->SetOuterParam(&emcalParam,AliExternalTrackParam::kMultSec);
1775 //      }
1776
1777     if(TMath::Abs(eta)>0.75 || (phi) < 70*TMath::DegToRad() || (phi) > 190*TMath::DegToRad())
1778       {
1779         if(aodevent && trackParam) delete trackParam;
1780         continue;
1781       }
1782
1783
1784     //Find matched clusters
1785     Int_t index = -1;
1786     Float_t dEta = -999, dPhi = -999;
1787     if(!clusterArr)
1788       {
1789         index = FindMatchedClusterInClusterArr(&emcalParam, &emcalParam, clusterArray, dEta, dPhi);  
1790       }
1791     else
1792       {
1793         index = FindMatchedClusterInClusterArr(&emcalParam, &emcalParam, clusterArr, dEta, dPhi);  
1794       }  
1795     
1796     if(index>-1)
1797     {
1798       fMatchedTrackIndex   ->AddAt(itr,matched);
1799       fMatchedClusterIndex ->AddAt(index,matched);
1800       fResidualEta         ->AddAt(dEta,matched);
1801       fResidualPhi         ->AddAt(dPhi,matched);
1802       matched++;
1803     }
1804     if(aodevent && trackParam) delete trackParam;
1805   }//track loop
1806
1807   if(clusterArray)
1808     {
1809       clusterArray->Clear();
1810       delete clusterArray;
1811     }
1812   
1813   AliDebug(2,Form("Number of matched pairs = %d !\n",matched));
1814   
1815   fMatchedTrackIndex   ->Set(matched);
1816   fMatchedClusterIndex ->Set(matched);
1817   fResidualPhi         ->Set(matched);
1818   fResidualEta         ->Set(matched);
1819 }
1820
1821 //________________________________________________________________________________
1822 Int_t AliEMCALRecoUtils::FindMatchedClusterInEvent(const AliESDtrack *track, 
1823                                                    const AliVEvent *event, 
1824                                                    const AliEMCALGeometry *geom, 
1825                                                    Float_t &dEta, Float_t &dPhi)
1826 {
1827   //
1828   // This function returns the index of matched cluster to input track
1829   // Returns -1 if no match is found
1830   Int_t index = -1;
1831   Double_t phiV = track->Phi()*TMath::RadToDeg();
1832   if(TMath::Abs(track->Eta())>0.8 || phiV <= 20 || phiV >= 240 ) return index;
1833   AliExternalTrackParam *trackParam = const_cast<AliExternalTrackParam*>(track->GetInnerParam());
1834   if(!trackParam) return index;
1835   AliExternalTrackParam emcalParam(*trackParam);
1836   Float_t eta, phi;
1837   if(!ExtrapolateTrackToEMCalSurface(&emcalParam, 430., fMass, fStepSurface, eta, phi)) return index;
1838   if(TMath::Abs(eta)>0.75 || (phi) < 70*TMath::DegToRad() || (phi) > 190*TMath::DegToRad()) return index;
1839
1840   TObjArray *clusterArr = new TObjArray(event->GetNumberOfCaloClusters());
1841
1842   for(Int_t icl=0; icl<event->GetNumberOfCaloClusters(); icl++)
1843   {
1844     AliVCluster *cluster = (AliVCluster*) event->GetCaloCluster(icl);
1845     if(geom && !IsGoodCluster(cluster,geom,(AliVCaloCells*)event->GetEMCALCells())) continue;
1846     clusterArr->AddAt(cluster,icl);
1847   }
1848
1849   index = FindMatchedClusterInClusterArr(&emcalParam, &emcalParam, clusterArr, dEta, dPhi);  
1850   clusterArr->Clear();
1851   delete clusterArr;
1852   
1853   return index;
1854 }
1855
1856 //_______________________________________________________________________________________________
1857 Int_t  AliEMCALRecoUtils::FindMatchedClusterInClusterArr(const AliExternalTrackParam *emcalParam, 
1858                                                          AliExternalTrackParam *trkParam, 
1859                                                          const TObjArray * clusterArr, 
1860                                                          Float_t &dEta, Float_t &dPhi)
1861 {
1862   // Find matched cluster in array
1863   
1864   dEta=-999, dPhi=-999;
1865   Float_t dRMax = fCutR, dEtaMax=fCutEta, dPhiMax=fCutPhi;
1866   Int_t index = -1;
1867   Float_t tmpEta=-999, tmpPhi=-999;
1868
1869   Double_t exPos[3] = {0.,0.,0.};
1870   if(!emcalParam->GetXYZ(exPos)) return index;
1871
1872   Float_t clsPos[3] = {0.,0.,0.};
1873   for(Int_t icl=0; icl<clusterArr->GetEntriesFast(); icl++)
1874     {
1875       AliVCluster *cluster = dynamic_cast<AliVCluster*> (clusterArr->At(icl)) ;
1876       if(!cluster || !cluster->IsEMCAL()) continue;
1877       cluster->GetPosition(clsPos);
1878       Double_t dR = TMath::Sqrt(TMath::Power(exPos[0]-clsPos[0],2)+TMath::Power(exPos[1]-clsPos[1],2)+TMath::Power(exPos[2]-clsPos[2],2));
1879       if(dR > fClusterWindow) continue;
1880
1881       AliExternalTrackParam trkPamTmp (*trkParam);//Retrieve the starting point every time before the extrapolation
1882       if(!ExtrapolateTrackToCluster(&trkPamTmp, cluster, fMass, fStepCluster, tmpEta, tmpPhi)) continue;
1883       if(fCutEtaPhiSum)
1884         {
1885           Float_t tmpR=TMath::Sqrt(tmpEta*tmpEta + tmpPhi*tmpPhi);
1886           if(tmpR<dRMax)
1887             {
1888               dRMax=tmpR;
1889               dEtaMax=tmpEta;
1890               dPhiMax=tmpPhi;
1891               index=icl;
1892             }
1893         }
1894       else if(fCutEtaPhiSeparate)
1895         {
1896           if(TMath::Abs(tmpEta)<TMath::Abs(dEtaMax) && TMath::Abs(tmpPhi)<TMath::Abs(dPhiMax))
1897             {
1898               dEtaMax = tmpEta;
1899               dPhiMax = tmpPhi;
1900               index=icl;
1901             }
1902         }
1903       else
1904         {
1905           printf("Error: please specify your cut criteria\n");
1906           printf("To cut on sqrt(dEta^2+dPhi^2), use: SwitchOnCutEtaPhiSum()\n");
1907           printf("To cut on dEta and dPhi separately, use: SwitchOnCutEtaPhiSeparate()\n");
1908           return index;
1909         }
1910     }
1911
1912   dEta=dEtaMax;
1913   dPhi=dPhiMax;
1914
1915   return index;
1916 }
1917
1918 //------------------------------------------------------------------------------------
1919 Bool_t AliEMCALRecoUtils::ExtrapolateTrackToEMCalSurface(AliExternalTrackParam *trkParam, 
1920                                                          const Double_t emcalR,
1921                                                          const Double_t mass, 
1922                                                          const Double_t step, 
1923                                                          Float_t &eta, 
1924                                                          Float_t &phi)
1925 {
1926   //Extrapolate track to EMCAL surface
1927   
1928   eta = -999, phi = -999;
1929   if(!trkParam) return kFALSE;
1930   if(!AliTrackerBase::PropagateTrackToBxByBz(trkParam, emcalR, mass, step, kTRUE, 0.8, -1)) return kFALSE;
1931   Double_t trkPos[3] = {0.,0.,0.};
1932   if(!trkParam->GetXYZ(trkPos)) return kFALSE;
1933   TVector3 trkPosVec(trkPos[0],trkPos[1],trkPos[2]);
1934   eta = trkPosVec.Eta();
1935   phi = trkPosVec.Phi();
1936   if(phi<0)
1937     phi += 2*TMath::Pi();
1938
1939   return kTRUE;
1940 }
1941
1942 //-----------------------------------------------------------------------------------
1943 Bool_t AliEMCALRecoUtils::ExtrapolateTrackToPosition(AliExternalTrackParam *trkParam, 
1944                                                      const Float_t *clsPos, 
1945                                                      Double_t mass, 
1946                                                      Double_t step, 
1947                                                      Float_t &tmpEta, 
1948                                                      Float_t &tmpPhi)
1949 {
1950   //
1951   //Return the residual by extrapolating a track param to a global position
1952   //
1953   tmpEta = -999;
1954   tmpPhi = -999;
1955   if(!trkParam) return kFALSE;
1956   Double_t trkPos[3] = {0.,0.,0.};
1957   TVector3 vec(clsPos[0],clsPos[1],clsPos[2]);
1958   Double_t alpha =  ((int)(vec.Phi()*TMath::RadToDeg()/20)+0.5)*20*TMath::DegToRad();
1959   vec.RotateZ(-alpha); //Rotate the cluster to the local extrapolation coordinate system
1960   if(!AliTrackerBase::PropagateTrackToBxByBz(trkParam, vec.X(), mass, step,kTRUE, 0.8, -1)) return kFALSE;
1961   if(!trkParam->GetXYZ(trkPos)) return kFALSE; //Get the extrapolated global position
1962
1963   TVector3 clsPosVec(clsPos[0],clsPos[1],clsPos[2]);
1964   TVector3 trkPosVec(trkPos[0],trkPos[1],trkPos[2]);
1965
1966   // track cluster matching
1967   tmpPhi = clsPosVec.DeltaPhi(trkPosVec);    // tmpPhi is between -pi and pi
1968   tmpEta = clsPosVec.Eta()-trkPosVec.Eta();
1969
1970   return kTRUE;
1971 }
1972
1973 //----------------------------------------------------------------------------------
1974 Bool_t AliEMCALRecoUtils::ExtrapolateTrackToCluster(AliExternalTrackParam *trkParam, 
1975                                                     const AliVCluster *cluster, 
1976                                                     const Double_t mass, 
1977                                                     const Double_t step, 
1978                                                     Float_t &tmpEta, 
1979                                                     Float_t &tmpPhi)
1980 {
1981   //
1982   //Return the residual by extrapolating a track param to a cluster
1983   //
1984   tmpEta = -999;
1985   tmpPhi = -999;
1986   if(!cluster || !trkParam) return kFALSE;
1987
1988   Float_t clsPos[3] = {0.,0.,0.};
1989   cluster->GetPosition(clsPos);
1990
1991   return ExtrapolateTrackToPosition(trkParam, clsPos, mass, step, tmpEta, tmpPhi);
1992 }
1993
1994 //---------------------------------------------------------------------------------
1995 Bool_t AliEMCALRecoUtils::ExtrapolateTrackToCluster(AliExternalTrackParam *trkParam, 
1996                                                     const AliVCluster *cluster, 
1997                                                     Float_t &tmpEta, 
1998                                                     Float_t &tmpPhi)
1999 {
2000   //
2001   //Return the residual by extrapolating a track param to a clusterfStepCluster
2002   //
2003
2004   return ExtrapolateTrackToCluster(trkParam, cluster, fMass, fStepCluster, tmpEta, tmpPhi);
2005 }
2006
2007 //_______________________________________________________________________
2008 void AliEMCALRecoUtils::GetMatchedResiduals(const Int_t clsIndex, 
2009                                             Float_t &dEta, Float_t &dPhi)
2010 {
2011   //Given a cluster index as in AliESDEvent::GetCaloCluster(clsIndex)
2012   //Get the residuals dEta and dPhi for this cluster to the closest track
2013   //Works with ESDs and AODs
2014
2015   if( FindMatchedPosForCluster(clsIndex) >= 999 )
2016   {
2017     AliDebug(2,"No matched tracks found!\n");
2018     dEta=999.;
2019     dPhi=999.;
2020     return;
2021   }
2022   dEta = fResidualEta->At(FindMatchedPosForCluster(clsIndex));
2023   dPhi = fResidualPhi->At(FindMatchedPosForCluster(clsIndex));
2024 }
2025
2026 //______________________________________________________________________________________________
2027 void AliEMCALRecoUtils::GetMatchedClusterResiduals(Int_t trkIndex, Float_t &dEta, Float_t &dPhi)
2028 {
2029   //Given a track index as in AliESDEvent::GetTrack(trkIndex)
2030   //Get the residuals dEta and dPhi for this track to the closest cluster
2031   //Works with ESDs and AODs
2032
2033   if( FindMatchedPosForTrack(trkIndex) >= 999 )
2034   {
2035     AliDebug(2,"No matched cluster found!\n");
2036     dEta=999.;
2037     dPhi=999.;
2038     return;
2039   }
2040   dEta = fResidualEta->At(FindMatchedPosForTrack(trkIndex));
2041   dPhi = fResidualPhi->At(FindMatchedPosForTrack(trkIndex));
2042 }
2043
2044 //__________________________________________________________
2045 Int_t AliEMCALRecoUtils::GetMatchedTrackIndex(Int_t clsIndex)
2046 {
2047   //Given a cluster index as in AliESDEvent::GetCaloCluster(clsIndex)
2048   //Get the index of matched track to this cluster
2049   //Works with ESDs and AODs
2050   
2051   if(IsClusterMatched(clsIndex))
2052     return fMatchedTrackIndex->At(FindMatchedPosForCluster(clsIndex));
2053   else 
2054     return -1; 
2055 }
2056
2057 //__________________________________________________________
2058 Int_t AliEMCALRecoUtils::GetMatchedClusterIndex(Int_t trkIndex)
2059 {
2060   //Given a track index as in AliESDEvent::GetTrack(trkIndex)
2061   //Get the index of matched cluster to this track
2062   //Works with ESDs and AODs
2063   
2064   if(IsTrackMatched(trkIndex))
2065     return fMatchedClusterIndex->At(FindMatchedPosForTrack(trkIndex));
2066   else 
2067     return -1; 
2068 }
2069
2070 //______________________________________________________________
2071 Bool_t AliEMCALRecoUtils::IsClusterMatched(Int_t clsIndex) const
2072 {
2073   //Given a cluster index as in AliESDEvent::GetCaloCluster(clsIndex)
2074   //Returns if the cluster has a match
2075   if(FindMatchedPosForCluster(clsIndex) < 999) 
2076     return kTRUE;
2077   else
2078     return kFALSE;
2079 }
2080
2081 //____________________________________________________________
2082 Bool_t AliEMCALRecoUtils::IsTrackMatched(Int_t trkIndex) const 
2083 {
2084   //Given a track index as in AliESDEvent::GetTrack(trkIndex)
2085   //Returns if the track has a match
2086   if(FindMatchedPosForTrack(trkIndex) < 999) 
2087     return kTRUE;
2088   else
2089     return kFALSE;
2090 }
2091
2092 //______________________________________________________________________
2093 UInt_t AliEMCALRecoUtils::FindMatchedPosForCluster(Int_t clsIndex) const
2094 {
2095   //Given a cluster index as in AliESDEvent::GetCaloCluster(clsIndex)
2096   //Returns the position of the match in the fMatchedClusterIndex array
2097   Float_t tmpR = fCutR;
2098   UInt_t pos = 999;
2099   
2100   for(Int_t i=0; i<fMatchedClusterIndex->GetSize(); i++) 
2101   {
2102     if(fMatchedClusterIndex->At(i)==clsIndex) 
2103     {
2104       Float_t r = TMath::Sqrt(fResidualEta->At(i)*fResidualEta->At(i) + fResidualPhi->At(i)*fResidualPhi->At(i));
2105       if(r<tmpR) 
2106       {
2107         pos=i;
2108         tmpR=r;
2109         AliDebug(3,Form("Matched cluster index: index: %d, dEta: %2.4f, dPhi: %2.4f.\n",
2110                         fMatchedClusterIndex->At(i),fResidualEta->At(i),fResidualPhi->At(i)));
2111       }
2112     }
2113   }
2114   return pos;
2115 }
2116
2117 //____________________________________________________________________
2118 UInt_t AliEMCALRecoUtils::FindMatchedPosForTrack(Int_t trkIndex) const
2119 {
2120   //Given a track index as in AliESDEvent::GetTrack(trkIndex)
2121   //Returns the position of the match in the fMatchedTrackIndex array
2122   Float_t tmpR = fCutR;
2123   UInt_t pos = 999;
2124   
2125   for(Int_t i=0; i<fMatchedTrackIndex->GetSize(); i++) 
2126   {
2127     if(fMatchedTrackIndex->At(i)==trkIndex) 
2128     {
2129       Float_t r = TMath::Sqrt(fResidualEta->At(i)*fResidualEta->At(i) + fResidualPhi->At(i)*fResidualPhi->At(i));
2130       if(r<tmpR) 
2131       {
2132         pos=i;
2133         tmpR=r;
2134         AliDebug(3,Form("Matched track index: index: %d, dEta: %2.4f, dPhi: %2.4f.\n",
2135                         fMatchedTrackIndex->At(i),fResidualEta->At(i),fResidualPhi->At(i)));
2136       }
2137     }
2138   }
2139   return pos;
2140 }
2141
2142 //__________________________________________________________________________
2143 Bool_t AliEMCALRecoUtils::IsGoodCluster(AliVCluster *cluster, 
2144                                         const AliEMCALGeometry *geom, 
2145                                         AliVCaloCells* cells,const Int_t bc)
2146 {
2147   // check if the cluster survives some quality cut
2148   //
2149   //
2150   Bool_t isGood=kTRUE;
2151
2152   if(!cluster || !cluster->IsEMCAL())              return kFALSE;
2153   
2154   if(ClusterContainsBadChannel(geom,cluster->GetCellsAbsId(),cluster->GetNCells())) return kFALSE;
2155   
2156   if(!CheckCellFiducialRegion(geom,cluster,cells)) return kFALSE;
2157   
2158   if(IsExoticCluster(cluster, cells,bc))           return kFALSE;
2159
2160   return isGood;
2161 }
2162
2163 //__________________________________________________________
2164 Bool_t AliEMCALRecoUtils::IsAccepted(AliESDtrack *esdTrack)
2165 {
2166   // Given a esd track, return whether the track survive all the cuts
2167
2168   // The different quality parameter are first
2169   // retrieved from the track. then it is found out what cuts the
2170   // track did not survive and finally the cuts are imposed.
2171
2172   UInt_t status = esdTrack->GetStatus();
2173
2174   Int_t nClustersITS = esdTrack->GetITSclusters(0);
2175   Int_t nClustersTPC = esdTrack->GetTPCclusters(0);
2176
2177   Float_t chi2PerClusterITS = -1;
2178   Float_t chi2PerClusterTPC = -1;
2179   if (nClustersITS!=0)
2180     chi2PerClusterITS = esdTrack->GetITSchi2()/Float_t(nClustersITS);
2181   if (nClustersTPC!=0) 
2182     chi2PerClusterTPC = esdTrack->GetTPCchi2()/Float_t(nClustersTPC);
2183
2184
2185   //DCA cuts
2186   if(fTrackCutsType==kGlobalCut)
2187     {
2188       Float_t maxDCAToVertexXYPtDep = 0.0182 + 0.0350/TMath::Power(esdTrack->Pt(),1.01); //This expression comes from AliESDtrackCuts::GetStandardITSTPCTrackCuts2010()
2189       //AliDebug(3,Form("Track pT = %f, DCAtoVertexXY = %f",esdTrack->Pt(),MaxDCAToVertexXYPtDep));
2190       SetMaxDCAToVertexXY(maxDCAToVertexXYPtDep); //Set pT dependent DCA cut to vertex in x-y plane
2191     }
2192
2193
2194   Float_t b[2];
2195   Float_t bCov[3];
2196   esdTrack->GetImpactParameters(b,bCov);
2197   if (bCov[0]<=0 || bCov[2]<=0) 
2198   {
2199     AliDebug(1, "Estimated b resolution lower or equal zero!");
2200     bCov[0]=0; bCov[2]=0;
2201   }
2202
2203   Float_t dcaToVertexXY = b[0];
2204   Float_t dcaToVertexZ = b[1];
2205   Float_t dcaToVertex = -1;
2206
2207   if (fCutDCAToVertex2D)
2208     dcaToVertex = TMath::Sqrt(dcaToVertexXY*dcaToVertexXY/fCutMaxDCAToVertexXY/fCutMaxDCAToVertexXY + dcaToVertexZ*dcaToVertexZ/fCutMaxDCAToVertexZ/fCutMaxDCAToVertexZ);
2209   else
2210     dcaToVertex = TMath::Sqrt(dcaToVertexXY*dcaToVertexXY + dcaToVertexZ*dcaToVertexZ);
2211     
2212   // cut the track?
2213   
2214   Bool_t cuts[kNCuts];
2215   for (Int_t i=0; i<kNCuts; i++) cuts[i]=kFALSE;
2216   
2217   // track quality cuts
2218   if (fCutRequireTPCRefit && (status&AliESDtrack::kTPCrefit)==0)
2219     cuts[0]=kTRUE;
2220   if (fCutRequireITSRefit && (status&AliESDtrack::kITSrefit)==0)
2221     cuts[1]=kTRUE;
2222   if (nClustersTPC<fCutMinNClusterTPC)
2223     cuts[2]=kTRUE;
2224   if (nClustersITS<fCutMinNClusterITS) 
2225     cuts[3]=kTRUE;
2226   if (chi2PerClusterTPC>fCutMaxChi2PerClusterTPC) 
2227     cuts[4]=kTRUE; 
2228   if (chi2PerClusterITS>fCutMaxChi2PerClusterITS) 
2229     cuts[5]=kTRUE;  
2230   if (!fCutAcceptKinkDaughters && esdTrack->GetKinkIndex(0)>0)
2231     cuts[6]=kTRUE;
2232   if (fCutDCAToVertex2D && dcaToVertex > 1)
2233     cuts[7] = kTRUE;
2234   if (!fCutDCAToVertex2D && TMath::Abs(dcaToVertexXY) > fCutMaxDCAToVertexXY)
2235     cuts[8] = kTRUE;
2236   if (!fCutDCAToVertex2D && TMath::Abs(dcaToVertexZ) > fCutMaxDCAToVertexZ)
2237     cuts[9] = kTRUE;
2238
2239   if(fTrackCutsType==kGlobalCut)
2240     {
2241       //Require at least one SPD point + anything else in ITS
2242       if( (esdTrack->HasPointOnITSLayer(0) || esdTrack->HasPointOnITSLayer(1)) == kFALSE)
2243         cuts[10] = kTRUE;
2244     }
2245
2246   Bool_t cut=kFALSE;
2247   for (Int_t i=0; i<kNCuts; i++)
2248     if (cuts[i]) { cut = kTRUE ; }
2249
2250     // cut the track
2251   if (cut) 
2252     return kFALSE;
2253   else 
2254     return kTRUE;
2255 }
2256
2257 //_____________________________________
2258 void AliEMCALRecoUtils::InitTrackCuts()
2259 {
2260   //Intilize the track cut criteria
2261   //By default these cuts are set according to AliESDtrackCuts::GetStandardTPCOnlyTrackCuts()
2262   //Also you can customize the cuts using the setters
2263   
2264   switch (fTrackCutsType)
2265   {
2266     case kTPCOnlyCut:
2267     {
2268       AliInfo(Form("Track cuts for matching: GetStandardTPCOnlyTrackCuts()"));
2269       //TPC
2270       SetMinNClustersTPC(70);
2271       SetMaxChi2PerClusterTPC(4);
2272       SetAcceptKinkDaughters(kFALSE);
2273       SetRequireTPCRefit(kFALSE);
2274       
2275       //ITS
2276       SetRequireITSRefit(kFALSE);
2277       SetMaxDCAToVertexZ(3.2);
2278       SetMaxDCAToVertexXY(2.4);
2279       SetDCAToVertex2D(kTRUE);
2280       
2281       break;
2282     }
2283       
2284     case kGlobalCut:
2285     {
2286       AliInfo(Form("Track cuts for matching: GetStandardITSTPCTrackCuts2010(kTURE)"));
2287       //TPC
2288       SetMinNClustersTPC(70);
2289       SetMaxChi2PerClusterTPC(4);
2290       SetAcceptKinkDaughters(kFALSE);
2291       SetRequireTPCRefit(kTRUE);
2292       
2293       //ITS
2294       SetRequireITSRefit(kTRUE);
2295       SetMaxDCAToVertexZ(2);
2296       SetMaxDCAToVertexXY();
2297       SetDCAToVertex2D(kFALSE);
2298       
2299       break;
2300     }
2301       
2302     case kLooseCut:
2303     {
2304       AliInfo(Form("Track cuts for matching: Loose cut w/o DCA cut"));
2305       SetMinNClustersTPC(50);
2306       SetAcceptKinkDaughters(kTRUE);
2307       
2308       break;
2309     }
2310   }
2311 }
2312
2313
2314 //________________________________________________________________________
2315 void AliEMCALRecoUtils::SetClusterMatchedToTrack(const AliVEvent *event)
2316 {
2317   // Checks if tracks are matched to EMC clusters and set the matched EMCAL cluster index to ESD track. 
2318
2319   Int_t nTracks = event->GetNumberOfTracks();
2320   for (Int_t iTrack = 0; iTrack < nTracks; ++iTrack) 
2321   {
2322     AliVTrack* track = dynamic_cast<AliVTrack*>(event->GetTrack(iTrack));
2323     if (!track) 
2324     {
2325       AliWarning(Form("Could not receive track %d", iTrack));
2326       continue;
2327     }
2328     
2329     Int_t matchClusIndex = GetMatchedClusterIndex(iTrack);                 
2330     track->SetEMCALcluster(matchClusIndex); //sets -1 if track not matched within residual
2331     /*the following can be done better if AliVTrack::SetStatus will be there. Patch pending with Andreas/Peter*/
2332     AliESDtrack* esdtrack = dynamic_cast<AliESDtrack*>(track);
2333     if (esdtrack) { 
2334       if(matchClusIndex != -1) 
2335         esdtrack->SetStatus(AliESDtrack::kEMCALmatch);
2336       else
2337         esdtrack->ResetStatus(AliESDtrack::kEMCALmatch);
2338     } else {
2339       AliAODTrack* aodtrack = dynamic_cast<AliAODTrack*>(track);
2340       if(matchClusIndex != -1) 
2341         aodtrack->SetStatus(AliESDtrack::kEMCALmatch);
2342       else
2343         aodtrack->ResetStatus(AliESDtrack::kEMCALmatch);
2344     }
2345
2346   }
2347   AliDebug(2,"Track matched to closest cluster");       
2348 }
2349
2350 //_________________________________________________________________________
2351 void AliEMCALRecoUtils::SetTracksMatchedToCluster(const AliVEvent *event)
2352 {
2353   // Checks if EMC clusters are matched to ESD track.
2354   // Adds track indexes of all the tracks matched to a cluster withing residuals in ESDCalocluster.
2355   
2356   for (Int_t iClus=0; iClus < event->GetNumberOfCaloClusters(); ++iClus) 
2357   {
2358     AliVCluster *cluster = event->GetCaloCluster(iClus);
2359     if (!cluster->IsEMCAL()) 
2360       continue;
2361     
2362     Int_t nTracks = event->GetNumberOfTracks();
2363     TArrayI arrayTrackMatched(nTracks);
2364     
2365     // Get the closest track matched to the cluster
2366     Int_t nMatched = 0;
2367     Int_t matchTrackIndex = GetMatchedTrackIndex(iClus);
2368     if (matchTrackIndex != -1) 
2369     {
2370       arrayTrackMatched[nMatched] = matchTrackIndex;
2371       nMatched++;
2372     }
2373     
2374     // Get all other tracks matched to the cluster
2375     for(Int_t iTrk=0; iTrk<nTracks; ++iTrk) 
2376     {
2377       AliVTrack* track = dynamic_cast<AliVTrack*>(event->GetTrack(iTrk));
2378       if(iTrk == matchTrackIndex) continue;
2379       if(track->GetEMCALcluster() == iClus)
2380       {
2381         arrayTrackMatched[nMatched] = iTrk;
2382         ++nMatched;
2383       }
2384     }
2385     
2386     //printf("Tender::SetTracksMatchedToCluster - cluster E %f, N matches %d, first match %d\n",cluster->E(),nMatched,arrayTrackMatched[0]);
2387     
2388     arrayTrackMatched.Set(nMatched);
2389     AliESDCaloCluster *esdcluster = dynamic_cast<AliESDCaloCluster*>(cluster);
2390     if (esdcluster) 
2391       esdcluster->AddTracksMatched(arrayTrackMatched);
2392     else if (nMatched>0) {
2393       AliAODCaloCluster *aodcluster = dynamic_cast<AliAODCaloCluster*>(cluster);
2394       if (aodcluster)
2395         aodcluster->AddTrackMatched(event->GetTrack(arrayTrackMatched.At(0)));
2396     }
2397     
2398     Float_t eta= -999, phi = -999;
2399     if (matchTrackIndex != -1) 
2400       GetMatchedResiduals(iClus, eta, phi);
2401     cluster->SetTrackDistance(phi, eta);
2402   }
2403   
2404   AliDebug(2,"Cluster matched to tracks");      
2405 }
2406
2407
2408 //___________________________________________________
2409 void AliEMCALRecoUtils::Print(const Option_t *) const 
2410 {
2411   // Print Parameters
2412   
2413   printf("AliEMCALRecoUtils Settings: \n");
2414   printf("Misalignment shifts\n");
2415   for(Int_t i=0; i<5; i++) printf("\t sector %d, traslation (x,y,z)=(%f,%f,%f), rotation (x,y,z)=(%f,%f,%f)\n",i, 
2416                                   fMisalTransShift[i*3],fMisalTransShift[i*3+1],fMisalTransShift[i*3+2],
2417                                   fMisalRotShift[i*3],  fMisalRotShift[i*3+1],  fMisalRotShift[i*3+2]   );
2418   printf("Non linearity function %d, parameters:\n", fNonLinearityFunction);
2419   for(Int_t i=0; i<6; i++) printf("param[%d]=%f\n",i, fNonLinearityParams[i]);
2420   
2421   printf("Position Recalculation option %d, Particle Type %d, fW0 %2.2f, Recalibrate Data %d \n",fPosAlgo,fParticleType,fW0, fRecalibration);
2422
2423   printf("Matching criteria: ");
2424   if(fCutEtaPhiSum)
2425     {
2426       printf("sqrt(dEta^2+dPhi^2)<%4.3f\n",fCutR);
2427     }
2428   else if(fCutEtaPhiSeparate)
2429     {
2430       printf("dEta<%4.3f, dPhi<%4.3f\n",fCutEta,fCutPhi);
2431     }
2432   else
2433     {
2434       printf("Error\n");
2435       printf("please specify your cut criteria\n");
2436       printf("To cut on sqrt(dEta^2+dPhi^2), use: SwitchOnCutEtaPhiSum()\n");
2437       printf("To cut on dEta and dPhi separately, use: SwitchOnCutEtaPhiSeparate()\n");
2438     }
2439
2440   printf("Mass hypothesis = %2.3f [GeV/c^2], extrapolation step to surface = %2.2f[cm], step to cluster = %2.2f[cm]\n",fMass,fStepSurface, fStepCluster);
2441   printf("Cluster selection window: dR < %2.0f\n",fClusterWindow);
2442
2443   printf("Track cuts: \n");
2444   printf("Minimum track pT: %1.2f\n",fCutMinTrackPt);
2445   printf("AOD track selection mask: %d\n",fAODFilterMask);
2446   printf("TPCRefit = %d, ITSRefit = %d\n",fCutRequireTPCRefit,fCutRequireITSRefit);
2447   printf("AcceptKinks = %d\n",fCutAcceptKinkDaughters);
2448   printf("MinNCulsterTPC = %d, MinNClusterITS = %d\n",fCutMinNClusterTPC,fCutMinNClusterITS);
2449   printf("MaxChi2TPC = %2.2f, MaxChi2ITS = %2.2f\n",fCutMaxChi2PerClusterTPC,fCutMaxChi2PerClusterITS);
2450   printf("DCSToVertex2D = %d, MaxDCAToVertexXY = %2.2f, MaxDCAToVertexZ = %2.2f\n",fCutDCAToVertex2D,fCutMaxDCAToVertexXY,fCutMaxDCAToVertexZ);
2451 }
2452
2453 //_________________________________________________________________
2454 void AliEMCALRecoUtils::SetRunDependentCorrections(Int_t runnumber)
2455 {
2456   //Get EMCAL time dependent corrections from file and put them in the recalibration histograms
2457   //Do it only once and only if it is requested
2458   
2459   if(!fUseRunCorrectionFactors) return;
2460   if(fRunCorrectionFactorsSet)  return;
2461   
2462   AliInfo(Form("AliEMCALRecoUtils::GetRunDependentCorrections() - Get Correction Factors for Run number %d\n",runnumber));
2463  
2464   AliEMCALCalibTimeDepCorrection  *corr =  new AliEMCALCalibTimeDepCorrection();
2465   corr->ReadRootInfo(Form("CorrectionFiles/Run%d_Correction.root",runnumber));
2466   
2467   SwitchOnRecalibration();
2468   
2469   AliEMCALGeometry* geom = AliEMCALGeometry::GetInstance();
2470   
2471   for(Int_t ism = 0; ism < geom->GetNumberOfSuperModules(); ism++)
2472   {
2473     for(Int_t icol = 0; icol < 48; icol++)
2474     {
2475       for(Int_t irow = 0; irow < 24; irow++)
2476       {
2477         Float_t orgRecalFactor = GetEMCALChannelRecalibrationFactors(ism)->GetBinContent(icol,irow);
2478         Float_t newRecalFactor = orgRecalFactor*corr->GetCorrection(ism, icol,irow,0);
2479         GetEMCALChannelRecalibrationFactors(ism)->SetBinContent(icol,irow,newRecalFactor);
2480         //printf("ism %d, icol %d, irow %d, corrections : org %f, time dep %f, final %f (org*time %f)\n",ism, icol, irow, 
2481         //        orgRecalFactor, corr->GetCorrection(ism, icol,irow,0),
2482         //       (GetEMCALChannelRecalibrationFactors(ism))->GetBinContent(icol,irow),newRecalFactor);
2483       }
2484     }
2485   }
2486   
2487   fRunCorrectionFactorsSet = kTRUE;
2488   
2489 }