]> git.uio.no Git - u/mrichter/AliRoot.git/blob - PWG4/CaloCalib/AliAnalysisTaskEMCALClusterize.cxx
add one more condition on SM4 to reject LED events
[u/mrichter/AliRoot.git] / PWG4 / CaloCalib / AliAnalysisTaskEMCALClusterize.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 /* $Id: $ */
16
17 //_________________________________________________________________________
18 // This analysis provides a new list of clusters to be used in other analysis
19 //
20 // Author: Gustavo Conesa Balbastre,
21 //         Adapted from analysis class from Deepa Thomas
22 //
23 //
24 //_________________________________________________________________________
25
26 // --- Root ---
27 #include "TString.h"
28 #include "TRefArray.h"
29 #include "TClonesArray.h"
30 #include "TTree.h"
31 #include "TGeoManager.h"
32 #include "TROOT.h"
33 #include "TInterpreter.h"
34 #include "TFile.h"
35 //#include "string.h"
36
37 // --- AliRoot Analysis Steering
38 #include "AliAnalysisTask.h"
39 #include "AliAnalysisManager.h"
40 #include "AliESDEvent.h"
41 #include "AliGeomManager.h"
42 #include "AliVCaloCells.h"
43 #include "AliAODCaloCluster.h"
44 #include "AliCDBManager.h"
45 #include "AliCDBStorage.h"
46 #include "AliCDBEntry.h"
47 #include "AliLog.h"
48 #include "AliVEventHandler.h"
49 #include "AliAODInputHandler.h"
50
51 // --- EMCAL
52 #include "AliEMCALRecParam.h"
53 #include "AliEMCALAfterBurnerUF.h"
54 #include "AliEMCALGeometry.h"
55 #include "AliEMCALClusterizerNxN.h"
56 #include "AliEMCALClusterizerv1.h"
57 #include "AliEMCALClusterizerv2.h"
58 #include "AliEMCALRecPoint.h"
59 #include "AliEMCALDigit.h"
60 #include "AliCaloCalibPedestal.h"
61 #include "AliEMCALCalibData.h"
62 #include "AliEMCALRecoUtils.h"
63
64 #include "AliAnalysisTaskEMCALClusterize.h"
65
66 ClassImp(AliAnalysisTaskEMCALClusterize)
67
68 //________________________________________________________________________
69 AliAnalysisTaskEMCALClusterize::AliAnalysisTaskEMCALClusterize(const char *name) 
70   : AliAnalysisTaskSE(name)
71   , fGeom(0),               fGeomName("EMCAL_COMPLETEV1") 
72   , fGeomMatrixSet(kFALSE), fLoadGeomMatrices(kFALSE)
73   , fCalibData(0),          fPedestalData(0)
74   , fOCDBpath("raw://"),    fAccessOCDB(kFALSE)
75   , fDigitsArr(0),          fClusterArr(0),             fCaloClusterArr(0)
76   , fRecParam(0),           fClusterizer(0)
77   , fUnfolder(0),           fJustUnfold(kFALSE) 
78   , fOutputAODBranch(0),    fOutputAODBranchName("newEMCALClusters")
79   , fFillAODFile(kTRUE),    fFillAODHeader(0)
80   , fFillAODCaloCells(0),   fRun(-1)
81   , fRecoUtils(0),          fConfigName("")
82   , fCellLabels(),          fCellSecondLabels(),        fCellTime()
83   , fMaxEvent(1000000000),  fDoTrackMatching(kFALSE)
84   , fSelectCell(kFALSE),    fSelectCellMinE(0.005),     fSelectCellMinFrac(0.001)
85   , fRemoveLEDEvents(kFALSE)
86 {
87   //ctor
88   for(Int_t i = 0; i < 10;    i++)  fGeomMatrix[i] =  0;
89   for(Int_t j = 0; j < 24*48*11; j++)  {
90     fCellLabels[j]       = -1;
91     fCellSecondLabels[j] = -1;
92     fCellTime[j]         =  0.;        
93   }  
94   
95   fDigitsArr       = new TClonesArray("AliEMCALDigit",200);
96   fClusterArr      = new TObjArray(100);
97   fCaloClusterArr  = new TObjArray(1000);
98   fRecParam        = new AliEMCALRecParam;
99   fBranchNames     = "ESD:AliESDHeader.,EMCALCells.";
100   fRecoUtils       = new AliEMCALRecoUtils();
101   
102 }
103
104 //________________________________________________________________________
105 AliAnalysisTaskEMCALClusterize::AliAnalysisTaskEMCALClusterize() 
106   : AliAnalysisTaskSE("DefaultAnalysis_AliAnalysisTaskEMCALClusterize")
107 , fGeom(0),               fGeomName("EMCAL_COMPLETEV1") 
108 , fGeomMatrixSet(kFALSE), fLoadGeomMatrices(kFALSE)
109 , fCalibData(0),          fPedestalData(0)
110 , fOCDBpath("raw://"),    fAccessOCDB(kFALSE)
111 , fDigitsArr(0),          fClusterArr(0),             fCaloClusterArr(0)
112 , fRecParam(0),           fClusterizer(0)
113 , fUnfolder(0),           fJustUnfold(kFALSE) 
114 , fOutputAODBranch(0),    fOutputAODBranchName("newEMCALClusters")
115 , fFillAODFile(kTRUE),    fFillAODHeader(0)
116 , fFillAODCaloCells(0),   fRun(-1)
117 , fRecoUtils(0),          fConfigName("")
118 , fCellLabels(),          fCellSecondLabels(),        fCellTime()
119 , fMaxEvent(1000000000),  fDoTrackMatching(kFALSE)
120 , fSelectCell(kFALSE),    fSelectCellMinE(0.005),     fSelectCellMinFrac(0.001)
121 , fRemoveLEDEvents(kFALSE)
122
123 {
124   // Constructor
125   for(Int_t i = 0; i < 10;    i++)  fGeomMatrix[i] =  0;
126   for(Int_t j = 0; j < 24*48*11; j++)  {
127     fCellLabels[j]       = -1;
128     fCellSecondLabels[j] = -1;
129     fCellTime[j]         =  0.;        
130   }
131   fDigitsArr       = new TClonesArray("AliEMCALDigit",200);
132   fClusterArr      = new TObjArray(100);
133   fCaloClusterArr  = new TObjArray(100);
134   fRecParam        = new AliEMCALRecParam;
135   fBranchNames     = "ESD:AliESDHeader.,EMCALCells.";
136   fRecoUtils       = new AliEMCALRecoUtils();
137 }
138
139
140 //________________________________________________________________________
141 AliAnalysisTaskEMCALClusterize::~AliAnalysisTaskEMCALClusterize()
142 {
143   //dtor 
144   
145   if (fDigitsArr){
146     fDigitsArr->Clear("C");
147     delete fDigitsArr; 
148   }
149   
150   if (fClusterArr){
151     fClusterArr->Delete();
152     delete fClusterArr;
153   }
154   
155   if (fCaloClusterArr){
156     fCaloClusterArr->Delete();
157     delete fCaloClusterArr; 
158   }
159   
160   if(fClusterizer) delete fClusterizer;
161   if(fUnfolder)    delete fUnfolder;   
162   if(fRecoUtils)   delete fRecoUtils;
163   
164 }
165
166 //-------------------------------------------------------------------
167 void AliAnalysisTaskEMCALClusterize::Init()
168 {
169   //Init analysis with configuration macro if available
170   
171   if(gROOT->LoadMacro(fConfigName) >=0){
172     printf("Configure analysis with %s\n",fConfigName.Data());
173     AliAnalysisTaskEMCALClusterize *clus = (AliAnalysisTaskEMCALClusterize*)gInterpreter->ProcessLine("ConfigEMCALClusterize()");
174     fGeomName         = clus->fGeomName; 
175     fLoadGeomMatrices = clus->fLoadGeomMatrices;
176     fOCDBpath         = clus->fOCDBpath;   
177     fAccessOCDB       = clus->fAccessOCDB;
178     fRecParam         = clus->fRecParam;
179     fJustUnfold       = clus->fJustUnfold;
180     fFillAODFile      = clus->fFillAODFile;
181     fRecoUtils        = clus->fRecoUtils; 
182     fConfigName       = clus->fConfigName;
183     fMaxEvent         = clus->fMaxEvent;
184     fDoTrackMatching  = clus->fDoTrackMatching;
185     fOutputAODBranchName = clus->fOutputAODBranchName;
186     for(Int_t i = 0; i < 10; i++) fGeomMatrix[i] = clus->fGeomMatrix[i] ;
187     
188   }
189   
190 }  
191
192 //-------------------------------------------------------------------
193 void AliAnalysisTaskEMCALClusterize::UserCreateOutputObjects()
194 {
195   // Init geometry, create list of output clusters
196   
197   fGeom =  AliEMCALGeometry::GetInstance(fGeomName) ;   
198   if(fOutputAODBranchName.Length()!=0){
199     fOutputAODBranch = new TClonesArray("AliAODCaloCluster", 0);
200     fOutputAODBranch->SetName(fOutputAODBranchName);
201     AddAODBranch("TClonesArray", &fOutputAODBranch);
202   }
203   else {
204     AliFatal("fOutputAODBranchName not set\n");
205   }
206 }
207
208 //________________________________________________________________________
209 void AliAnalysisTaskEMCALClusterize::FillAODCaloCells() {
210   // Put calo cells in standard branch  
211   AliVEvent * event = InputEvent();
212   AliVCaloCells &eventEMcells = *(event->GetEMCALCells());
213   Int_t nEMcell = eventEMcells.GetNumberOfCells() ;
214   
215   AliAODCaloCells &aodEMcells = *(AODEvent()->GetEMCALCells());
216   aodEMcells.CreateContainer(nEMcell);
217   aodEMcells.SetType(AliVCaloCells::kEMCALCell);
218   Double_t calibFactor = 1.;   
219   for (Int_t iCell = 0; iCell < nEMcell; iCell++) { 
220     Int_t imod = -1, iphi =-1, ieta=-1,iTower = -1, iIphi = -1, iIeta = -1; 
221     fGeom->GetCellIndex(eventEMcells.GetCellNumber(iCell),imod,iTower,iIphi,iIeta); 
222     fGeom->GetCellPhiEtaIndexInSModule(imod,iTower,iIphi, iIeta,iphi,ieta);     
223     
224     if(fRecoUtils->IsRecalibrationOn()){ 
225       calibFactor = fRecoUtils->GetEMCALChannelRecalibrationFactor(imod,ieta,iphi);
226     }
227     
228     if(!fRecoUtils->GetEMCALChannelStatus(imod, ieta, iphi)){ //Channel is not declared as bad
229       aodEMcells.SetCell(iCell,eventEMcells.GetCellNumber(iCell),eventEMcells.GetAmplitude(iCell)*calibFactor);
230     }
231     else {
232       aodEMcells.SetCell(iCell,eventEMcells.GetCellNumber(iCell),0);
233     }
234   }
235   aodEMcells.Sort();
236   
237 }
238
239 //________________________________________________________________________
240 void AliAnalysisTaskEMCALClusterize::FillAODHeader() {
241   //Put event header information in standard AOD branch
242   
243   AliVEvent* event      = InputEvent();
244   AliESDEvent* esdevent = dynamic_cast<AliESDEvent*> (event);
245   AliAODEvent* aodevent = dynamic_cast<AliAODEvent*> (event);
246   
247   Double_t pos[3]   ;
248   Double_t covVtx[6];
249   for (Int_t i = 0; i < 6; i++)  covVtx[i] = 0.;
250   
251   AliAODHeader* header = AODEvent()->GetHeader();
252   header->SetRunNumber(event->GetRunNumber());
253   
254   if(esdevent){
255     TTree* tree = fInputHandler->GetTree();
256     if (tree) {
257       TFile* file = tree->GetCurrentFile();
258       if (file) header->SetESDFileName(file->GetName());
259     }
260   }
261   else if (aodevent) header->SetESDFileName(aodevent->GetHeader()->GetESDFileName());
262   
263   header->SetBunchCrossNumber(event->GetBunchCrossNumber());
264   header->SetOrbitNumber(event->GetOrbitNumber());
265   header->SetPeriodNumber(event->GetPeriodNumber());
266   header->SetEventType(event->GetEventType());
267   
268   //Centrality
269   if(event->GetCentrality()){
270     header->SetCentrality(new AliCentrality(*(event->GetCentrality())));
271   }
272   else{
273     header->SetCentrality(0);
274   }
275   
276   //Trigger  
277   header->SetOfflineTrigger(fInputHandler->IsEventSelected()); // propagate the decision of the physics selection
278   if      (esdevent) header->SetFiredTriggerClasses(esdevent->GetFiredTriggerClasses());
279   else if (aodevent) header->SetFiredTriggerClasses(aodevent->GetFiredTriggerClasses());
280   header->SetTriggerMask(event->GetTriggerMask()); 
281   header->SetTriggerCluster(event->GetTriggerCluster());
282   if(esdevent){
283     header->SetL0TriggerInputs(esdevent->GetHeader()->GetL0TriggerInputs());    
284     header->SetL1TriggerInputs(esdevent->GetHeader()->GetL1TriggerInputs());    
285     header->SetL2TriggerInputs(esdevent->GetHeader()->GetL2TriggerInputs());    
286   }
287   else if (aodevent){
288     header->SetL0TriggerInputs(aodevent->GetHeader()->GetL0TriggerInputs());    
289     header->SetL1TriggerInputs(aodevent->GetHeader()->GetL1TriggerInputs());    
290     header->SetL2TriggerInputs(aodevent->GetHeader()->GetL2TriggerInputs());    
291   }
292   
293   header->SetMagneticField(event->GetMagneticField());
294   //header->SetMuonMagFieldScale(esdevent->GetCurrentDip()/6000.); 
295   
296   header->SetZDCN1Energy(event->GetZDCN1Energy());
297   header->SetZDCP1Energy(event->GetZDCP1Energy());
298   header->SetZDCN2Energy(event->GetZDCN2Energy());
299   header->SetZDCP2Energy(event->GetZDCP2Energy());
300   header->SetZDCEMEnergy(event->GetZDCEMEnergy(0),event->GetZDCEMEnergy(1));
301   
302   Float_t diamxy[2]={event->GetDiamondX(),event->GetDiamondY()};
303   Float_t diamcov[3];
304   event->GetDiamondCovXY(diamcov);
305   header->SetDiamond(diamxy,diamcov);
306   if      (esdevent) header->SetDiamondZ(esdevent->GetDiamondZ(),esdevent->GetSigma2DiamondZ());
307   else if (aodevent) header->SetDiamondZ(aodevent->GetDiamondZ(),aodevent->GetSigma2DiamondZ());
308   
309   //
310   //
311   Int_t nVertices = 1 ;/* = prim. vtx*/;
312   Int_t nCaloClus = event->GetNumberOfCaloClusters();
313   
314   AODEvent()->ResetStd(0, nVertices, 0, 0, 0, nCaloClus, 0, 0);
315   
316   // Access to the AOD container of vertices
317   TClonesArray &vertices = *(AODEvent()->GetVertices());
318   Int_t jVertices=0;
319   
320   // Add primary vertex. The primary tracks will be defined
321   // after the loops on the composite objects (V0, cascades, kinks)
322   event->GetPrimaryVertex()->GetXYZ(pos);
323   Float_t chi = 0;
324   if      (esdevent){
325     esdevent->GetPrimaryVertex()->GetCovMatrix(covVtx);
326     chi = esdevent->GetPrimaryVertex()->GetChi2toNDF();
327   }
328   else if (aodevent){
329     aodevent->GetPrimaryVertex()->GetCovMatrix(covVtx);
330     chi = aodevent->GetPrimaryVertex()->GetChi2perNDF();//Different from ESD?
331   }
332   
333   AliAODVertex * primary = new(vertices[jVertices++])
334   AliAODVertex(pos, covVtx, chi, NULL, -1, AliAODVertex::kPrimary);
335   primary->SetName(event->GetPrimaryVertex()->GetName());
336   primary->SetTitle(event->GetPrimaryVertex()->GetTitle());
337   
338 }
339
340 //________________________________________________________________________
341 void AliAnalysisTaskEMCALClusterize::UserExec(Option_t *) 
342 {
343   // Main loop
344   // Called for each event
345   
346   AliAODInputHandler* aodIH = dynamic_cast<AliAODInputHandler*>((AliAnalysisManager::GetAnalysisManager())->GetInputEventHandler());
347   Int_t eventN = Entry();
348   if(aodIH) eventN = aodIH->GetReadEntry(); 
349   
350   if (eventN > fMaxEvent) return;
351   //printf("Clusterizer --- Event %d-- \n",eventN);
352   
353   //Remove the contents of output list set in the previous event 
354   fOutputAODBranch->Clear("C");
355   
356   //Magic line to write events to AOD file
357   AliAnalysisManager::GetAnalysisManager()->GetOutputEventHandler()->SetFillAOD(fFillAODFile);
358   LoadBranches();
359   
360   //Init pointers, clusterizer, ocdb
361   if(fAccessOCDB) AccessOCDB();
362   InitClusterization();
363   
364   //Get the event
365   AliVEvent   * event    = 0;
366   AliESDEvent * esdevent = 0;
367   
368   //Fill output event with header
369   
370   //Check if input event are embedded events
371   //If so, take output event
372   if (aodIH && aodIH->GetMergeEvents()) {
373     //printf("AliAnalysisTaskEMCALClusterize::UserExec() - Use embedded events\n");
374     event  = AODEvent();
375     
376     if(!aodIH->GetMergeEMCALCells()) 
377       AliFatal("Events merged but not EMCAL cells, check analysis settings!");
378     
379     //    printf("InputEvent  N Clusters %d, N Cells %d\n",InputEvent()->GetNumberOfCaloClusters(),
380     //           InputEvent()->GetEMCALCells()->GetNumberOfCells());
381     //    printf("MergedEvent  N Clusters %d, N Cells %d\n",aodIH->GetEventToMerge()->GetNumberOfCaloClusters(),
382     //           aodIH->GetEventToMerge()->GetEMCALCells()->GetNumberOfCells());
383     //    for (Int_t icl=0; icl < aodIH->GetEventToMerge()->GetNumberOfCaloClusters(); icl++) {
384     //        AliAODCaloCluster *sigCluster = aodIH->GetEventToMerge()->GetCaloCluster(icl);
385     //        if(sigCluster->IsEMCAL()) printf("Signal cluster: i %d, E  %f\n",icl,sigCluster->E());
386     //    }
387     //    printf("OutputEvent N Clusters %d, N Cells %d\n", AODEvent()->GetNumberOfCaloClusters(),
388     //           AODEvent()->GetEMCALCells()->GetNumberOfCells());
389     
390   }
391   else {
392     event =  InputEvent();
393     esdevent = dynamic_cast<AliESDEvent*>(InputEvent());
394     if(fFillAODCaloCells) FillAODCaloCells();   
395     if(fFillAODHeader)    FillAODHeader();
396   }
397   
398   if (!event) {
399     Error("UserExec","Event not available");
400     return;
401   }
402   
403   //-------------------------------------------------------------------------------------
404   // Reject event if large clusters with large energy
405   // Use only for LHC11a data for the moment, and if input is clusterizer V1 or V1+unfolding
406   // If clusterzer NxN or V2 it does not help
407   //-------------------------------------------------------------------------------------
408   if(fRemoveLEDEvents){
409     for (Int_t i = 0; i < InputEvent()->GetNumberOfCaloClusters(); i++)
410     {
411       AliVCluster *clus = InputEvent()->GetCaloCluster(i);
412       if(clus->IsEMCAL()){    
413         
414         if ((clus->E() > 500 && clus->GetNCells() > 200 ) || clus->GetNCells() > 200) {
415           Int_t absID = clus->GetCellsAbsId()[0];
416           Int_t sm = fGeom->GetSuperModuleNumber(absID);
417           printf("AliAnalysisTaskEMCALClusterize - reject event with cluster : E %f, ncells %d, absId(0) %d, SM %d\n",clus->E(),  clus->GetNCells(),absID, sm);
418           
419           return;
420         }
421       }
422     }
423     
424     // Count number of cells with energy larger than 0.1 in SM3, cut on this number
425     Int_t ncellsSM3 = 0;
426     Int_t ncellsSM4 = 0;
427     for(Int_t icell = 0; icell < event->GetEMCALCells()->GetNumberOfCells(); icell++){
428       if(event->GetEMCALCells()->GetAmplitude(icell) > 0.1 && event->GetEMCALCells()->GetCellNumber(icell)/(24*48)==3) ncellsSM3++;
429       if(event->GetEMCALCells()->GetAmplitude(icell) > 0.1 && event->GetEMCALCells()->GetCellNumber(icell)/(24*48)==4) ncellsSM4++;
430     }
431     
432     TString triggerclasses = "";
433     if(esdevent) triggerclasses = esdevent             ->GetFiredTriggerClasses();
434     else         triggerclasses = ((AliAODEvent*)event)->GetFiredTriggerClasses();
435     
436     Int_t ncellcut = 21;
437     if(triggerclasses.Contains("EMC")) ncellcut = 35;
438     
439     if( ncellsSM3 >= ncellcut || ncellsSM4 >= 100 ){
440       printf("AliAnalysisTaskEMCALClusterize - reject event with cluster  - reject event with ncells in SM3 %d and SM4 %d\n",ncellsSM3, ncellsSM4);
441       return;
442     }
443     
444   }// Remove LED events
445   
446   //-------------------------------------------------------------------------------------
447   //Set the geometry matrix, for the first event, skip the rest
448   //-------------------------------------------------------------------------------------
449   if(!fGeomMatrixSet){
450     if(fLoadGeomMatrices){
451       for(Int_t mod=0; mod < (fGeom->GetEMCGeometry())->GetNumberOfSuperModules(); mod++){
452         if(fGeomMatrix[mod]){
453           if(DebugLevel() > 1) 
454             fGeomMatrix[mod]->Print();
455           fGeom->SetMisalMatrix(fGeomMatrix[mod],mod) ;  
456         }
457         fGeomMatrixSet=kTRUE;
458       }//SM loop
459     }//Load matrices
460     else if(!gGeoManager){
461       Info("UserExec","Get geo matrices from data");
462       //Still not implemented in AOD, just a workaround to be able to work at least with ESDs   
463       if(!strcmp(event->GetName(),"AliAODEvent")) {
464         if(DebugLevel() > 1) 
465           Warning("UserExec","Use ideal geometry, values geometry matrix not kept in AODs.");
466       }//AOD
467       else {    
468         if(DebugLevel() > 1) 
469           Info("UserExec","AliAnalysisTaskEMCALClusterize Load Misaligned matrices.");
470         AliESDEvent* esd = dynamic_cast<AliESDEvent*>(event) ;
471         if(!esd) {
472           Error("UserExec","This event does not contain ESDs?");
473           return;
474         }
475         for(Int_t mod=0; mod < (fGeom->GetEMCGeometry())->GetNumberOfSuperModules(); mod++){
476           if(DebugLevel() > 1) 
477             esd->GetEMCALMatrix(mod)->Print();
478           if(esd->GetEMCALMatrix(mod)) fGeom->SetMisalMatrix(esd->GetEMCALMatrix(mod),mod) ;
479         } 
480         fGeomMatrixSet=kTRUE;
481       }//ESD
482     }//Load matrices from Data 
483     
484     //Recover time dependent corrections, put then in recalibration histograms. Do it once
485     fRecoUtils->SetRunDependentCorrections(InputEvent()->GetRunNumber());
486     
487   }//first event
488   
489   //Get the list of cells needed for unfolding and reclustering
490   AliVCaloCells *cells   = event->GetEMCALCells();
491   Int_t    nClustersOrg  = 0;
492   Double_t cellAmplitude = 0;
493   Double_t cellTime      = 0;
494   Short_t  cellNumber    = 0;
495   
496   //-------------------------------------------
497   //---------Unfolding clusters----------------
498   //-------------------------------------------
499   if (fJustUnfold) {
500     
501     //Fill the array with the EMCAL clusters, copy them
502     for (Int_t i = 0; i < event->GetNumberOfCaloClusters(); i++)
503     {
504       AliVCluster *clus = event->GetCaloCluster(i);
505       if(clus->IsEMCAL()){        
506         
507         //recalibrate/remove bad channels/etc if requested
508         if(fRecoUtils->ClusterContainsBadChannel(fGeom,clus->GetCellsAbsId(), clus->GetNCells())){
509           continue;
510         } 
511         
512         if(fRecoUtils->IsRecalibrationOn()){
513           
514           //Calibrate cluster
515           //printf("Energy before %f ",clus->E());
516           fRecoUtils->RecalibrateClusterEnergy(fGeom, clus, cells);
517           //printf("; after %f\n",clus->E());
518           
519           //CalibrateCells
520           for (Int_t icell = 0; icell < cells->GetNumberOfCells(); icell++)
521           {
522             if (cells->GetCell(icell, cellNumber, cellAmplitude, cellTime) != kTRUE)
523               break;
524             
525             
526             Int_t imod = -1, iphi =-1, ieta=-1,iTower = -1, iIphi = -1, iIeta = -1; 
527             fGeom->GetCellIndex(cellNumber,imod,iTower,iIphi,iIeta); 
528             fGeom->GetCellPhiEtaIndexInSModule(imod,iTower,iIphi, iIeta,iphi,ieta);     
529             
530             //Do not include bad channels found in analysis?
531             if( fRecoUtils->IsBadChannelsRemovalSwitchedOn() && 
532                 fRecoUtils->GetEMCALChannelStatus(imod, ieta, iphi)){
533               fCellLabels[cellNumber]      =-1; //reset the entry in the array for next event
534               fCellSecondLabels[cellNumber]=-1; //reset the entry in the array for next event
535               fCellTime[cellNumber]        = 0.;        
536               continue;
537             }
538             
539             cells->SetCell(icell, cellNumber, cellAmplitude*fRecoUtils->GetEMCALChannelRecalibrationFactor(imod,ieta,iphi),cellTime);
540             
541           }// cells loop            
542         }// recalibrate
543         
544         //Cast to ESD or AOD, needed to create the cluster array
545         AliESDCaloCluster * esdCluster = dynamic_cast<AliESDCaloCluster*> (clus);
546         AliAODCaloCluster * aodCluster = dynamic_cast<AliAODCaloCluster*> (clus);
547         if     (esdCluster){
548           fCaloClusterArr->Add( new AliESDCaloCluster(*esdCluster) );   
549         }//ESD
550         else if(aodCluster){
551           fCaloClusterArr->Add( new AliAODCaloCluster(*aodCluster) );   
552         }//AOD
553         else 
554           Warning("UserExec()"," - Wrong CaloCluster type?");
555         nClustersOrg++;
556       }
557     }
558     
559     //Do the unfolding
560     fUnfolder->UnfoldClusters(fCaloClusterArr, cells);
561     
562     //CLEAN-UP
563     fUnfolder->Clear();
564     
565   } // just unfold ESD/AOD cluster
566   
567   //-------------------------------------------
568   //---------- Recluster cells ----------------
569   //-------------------------------------------
570   
571   else{
572     //-------------------------------------------------------------------------------------
573     //Transform CaloCells into Digits
574     //-------------------------------------------------------------------------------------
575     
576     //In case of MC, first loop on the clusters and fill MC label to array
577     //.....................................................................
578     
579     //    for(Int_t j = 0; j < 24*48*11; j++)  {
580     //      if(fCellLabels[j]      !=-1) printf("Not well initialized cell %d, label1 %d\n",j,fCellLabels[j]      ) ;
581     //      if(fCellSecondLabels[j]!=-1) printf("Not well initialized cell %d, label2 %d\n",j,fCellSecondLabels[j]) ;
582     //    }
583     
584     Int_t nClusters = event->GetNumberOfCaloClusters();
585     if(aodIH && aodIH->GetEventToMerge())  //Embedding
586       nClusters = aodIH->GetEventToMerge()->GetNumberOfCaloClusters(); //Get clusters directly from embedded signal
587     for (Int_t i = 0; i < nClusters; i++)
588     {
589       AliVCluster *clus = 0;
590       if(aodIH && aodIH->GetEventToMerge()) //Embedding
591         clus = aodIH->GetEventToMerge()->GetCaloCluster(i); //Get clusters directly from embedded signal
592       else      
593         clus = event->GetCaloCluster(i);
594       
595       if(!clus) {
596         printf("AliEMCALReclusterize::UserExec() - No Clusters\n");
597         return;
598       }
599       
600       if(clus->IsEMCAL()){   
601         //printf("Cluster Signal %d, energy %f\n",clus->GetID(),clus->E());
602         Int_t label = clus->GetLabel();
603         Int_t label2 = -1 ;
604         if (clus->GetNLabels()>=2) label2 = clus->GetLabelAt(1) ;
605         UShort_t * index    = clus->GetCellsAbsId() ;
606         for(Int_t icell=0; icell < clus->GetNCells(); icell++ ){
607           fCellLabels[index[icell]]       = label;
608           fCellSecondLabels[index[icell]] = label2;
609           //printf("Clusterizer in : TOF %g\n",clus->GetTOF()*1.e9);
610
611           fCellTime[icell]                = clus->GetTOF();        
612
613           //printf("1) absID %d, label[0] %d label[1] %d\n",index[icell], fCellLabels[index[icell]],fCellSecondLabels[index[icell]]);
614         }
615         nClustersOrg++;
616       }
617     } 
618     
619     // Create digits 
620     //.................
621     Int_t    idigit =  0;
622     Int_t    id     = -1;
623     Float_t  amp    = -1; 
624     Double_t time   = -1; 
625     
626     TTree *digitsTree = new TTree("digitstree","digitstree");
627     digitsTree->Branch("EMCAL","TClonesArray", &fDigitsArr, 32000);
628     
629     Int_t bc = InputEvent()->GetBunchCrossNumber();
630     
631     for (Int_t icell = 0; icell < cells->GetNumberOfCells(); icell++)
632     {
633       if (cells->GetCell(icell, cellNumber, cellAmplitude, cellTime) != kTRUE)
634         break;
635       
636       time = cellTime;
637       amp  = cellAmplitude;
638       id   = cellNumber;
639       
640       Int_t imod = -1, iphi =-1, ieta=-1,iTower = -1, iIphi = -1, iIeta = -1; 
641       fGeom->GetCellIndex(id,imod,iTower,iIphi,iIeta); 
642       fGeom->GetCellPhiEtaIndexInSModule(imod,iTower,iIphi, iIeta,iphi,ieta);   
643       
644       //Do not include bad channels found in analysis?
645       if( fRecoUtils->IsBadChannelsRemovalSwitchedOn() && 
646          fRecoUtils->GetEMCALChannelStatus(imod, ieta, iphi)){
647         fCellLabels[id]      =-1; //reset the entry in the array for next event
648         fCellSecondLabels[id]=-1; //reset the entry in the array for next event
649         fCellTime[id]        = 0.;        
650         //printf("Remove channel %d\n",id);
651         continue;
652       }
653       
654       //Recalibrate?
655       if(fRecoUtils->IsRecalibrationOn()){ 
656         //printf("CalibFactor %f times %f for id %d\n",fRecoUtils->GetEMCALChannelRecalibrationFactor(imod,ieta,iphi),amp,id);
657         amp *=fRecoUtils->GetEMCALChannelRecalibrationFactor(imod,ieta,iphi);
658       }
659             
660       // In case of AOD analysis cell time is 0, approximate replacing by time of the cluster the digit belongs.
661       if (time*1e9 < 1.) time = fCellTime[id];
662       
663       // Recalibrate time
664       fRecoUtils->RecalibrateCellTime(id,bc,time);
665       
666 //      printf("Clusterizer: Id %d, Time org %e, Time new %e; Amp org %f, Amp new %f\n",
667 //             id, cells->GetTime(icell),time, cells->GetAmplitude(icell),amp);
668
669       
670       //Create the digit, put a fake primary deposited energy to trick the clusterizer when checking the most likely primary
671       new((*fDigitsArr)[idigit]) AliEMCALDigit( fCellLabels[id], fCellLabels[id],id, amp, time,AliEMCALDigit::kHG,idigit, 0, 0, 1); 
672       //if(fCellLabels[id]>=0)printf("2) Digit cell %d, label %d\n",id,fCellLabels[id]) ;
673       //else                  printf("2) Digit cell %d, no label, amp %f \n",id,amp) ;
674       fCellLabels[id]      =-1; //reset the entry in the array for next event
675       
676       //printf("Digit: Id %d, amp %f, time %e, index %d\n",id, amp,time,idigit);
677       idigit++;
678     }
679     
680     //Fill the tree with digits
681     digitsTree->Fill();
682     
683     //-------------------------------------------------------------------------------------
684     //Do the clusterization
685     //-------------------------------------------------------------------------------------        
686     TTree *clustersTree = new TTree("clustertree","clustertree");
687     
688     fClusterizer->SetInput(digitsTree);
689     fClusterizer->SetOutput(clustersTree);
690     fClusterizer->Digits2Clusters("");
691     
692     //-------------------------------------------------------------------------------------
693     //Transform the recpoints into AliVClusters
694     //-------------------------------------------------------------------------------------
695     
696     clustersTree->SetBranchStatus("*",0); //disable all branches
697     clustersTree->SetBranchStatus("EMCALECARP",1); //Enable only the branch we need
698     
699     TBranch *branch = clustersTree->GetBranch("EMCALECARP");
700     branch->SetAddress(&fClusterArr);
701     branch->GetEntry(0);
702     
703     RecPoints2Clusters(fDigitsArr, fClusterArr, fCaloClusterArr);
704     
705     if(!fCaloClusterArr){ 
706       printf("AliAnalisysTaskEMCALClusterize::UserExec() - No array with CaloClusters, input RecPoints entries %d\n",fClusterArr->GetEntriesFast());
707       return;    
708     }
709     
710     if( DebugLevel() > 0 && fCaloClusterArr->GetEntriesFast() != fClusterArr->GetEntriesFast()){
711       printf("AliAnalisysTaskEMCALClusterize::UserExec() - Some RecRoints not transformed into CaloClusters (clusterizer %d, unfold %d): Input entries %d - Output entries %d - %d (not fast)\n",
712              fRecParam->GetClusterizerFlag(),fRecParam->GetUnfold(),
713              fClusterArr->GetEntriesFast(), fCaloClusterArr->GetEntriesFast(), fCaloClusterArr->GetEntries());
714     }
715     
716     //Reset the array with second labels for this event
717     memset(fCellSecondLabels, -1, sizeof(fCellSecondLabels));
718     
719     //---CLEAN UP-----
720     fClusterizer->Clear();
721     fDigitsArr  ->Clear("C");
722     fClusterArr ->Delete(); // Do not Clear(), it leaks, why?
723     
724     clustersTree->Delete("all");
725     digitsTree  ->Delete("all");
726   }
727   
728   //Recalculate track-matching for the new clusters, only with ESDs
729   if(fDoTrackMatching) fRecoUtils->FindMatches(event,fCaloClusterArr,fGeom);
730   
731   
732   //-------------------------------------------------------------------------------------
733   //Put the new clusters in the AOD list
734   //-------------------------------------------------------------------------------------
735   
736   Int_t kNumberOfCaloClusters   = fCaloClusterArr->GetEntriesFast();
737   //printf("New clusters %d, Org clusters %d\n",kNumberOfCaloClusters, nClustersOrg);
738   for(Int_t i = 0; i < kNumberOfCaloClusters; i++){
739     AliAODCaloCluster *newCluster = (AliAODCaloCluster *) fCaloClusterArr->At(i);
740     //if(Entry()==0) Info("UserExec","newCluster E %f\n", newCluster->E());
741     
742     //Add matched track
743     if(fDoTrackMatching){
744       Int_t trackIndex = fRecoUtils->GetMatchedTrackIndex(i);
745       if(trackIndex >= 0){
746         newCluster->AddTrackMatched(event->GetTrack(trackIndex));
747         if(DebugLevel() > 1) 
748           Info("UserExec","Matched Track index %d to new cluster %d \n",trackIndex,i);
749       }
750     }
751     
752     //In case of new bad channels, recalculate distance to bad channels
753     if(fRecoUtils->IsBadChannelsRemovalSwitchedOn()){
754       //printf("DistToBad before %f ",newCluster->GetDistanceToBadChannel());
755       fRecoUtils->RecalculateClusterDistanceToBadChannel(fGeom, event->GetEMCALCells(), newCluster);
756       //printf("; after %f \n",newCluster->GetDistanceToBadChannel());
757     }
758     
759     //    if(newCluster->GetNLabels()>0){
760     //      printf("3) MC: N labels %d, label %d ; ", newCluster->GetNLabels(), newCluster->GetLabel() );
761     //      UShort_t * newindex    = newCluster->GetCellsAbsId() ;
762     //      for(Int_t icell=0; icell < newCluster->GetNCells(); icell++ ){
763     //       printf("\t absID %d\n",newindex[icell]);
764     //     }
765     //    }
766     
767     //    printf("Cluster %d, energy %f\n",newCluster->GetID(),newCluster->E());
768     //    printf("labels: ");
769     //    for(UInt_t ilab = 0; ilab < newCluster->GetNLabels(); ilab++)
770     //      printf("Label[%d]: %d ",ilab, newCluster->GetLabelAt(ilab)); 
771     //     printf("\n ");
772     
773     newCluster->SetID(i);
774     new((*fOutputAODBranch)[i])  AliAODCaloCluster(*newCluster);
775   }
776   
777   //if(fOutputAODBranchName.Length()!=0)
778   fOutputAODBranch->Expand(kNumberOfCaloClusters); // resize TObjArray to 'remove' slots
779   
780   //---CLEAN UP-----
781   fCaloClusterArr->Delete(); // Do not Clear(), it leaks, why?
782 }      
783
784 //_____________________________________________________________________
785 Bool_t AliAnalysisTaskEMCALClusterize::AccessOCDB()
786 {
787   //Access to OCDB stuff
788   
789   AliVEvent * event = InputEvent();
790   if (!event)
791   {
792     Warning("AccessOCDB","Event not available!!!");
793     return kFALSE;
794   }
795   
796   if (event->GetRunNumber()==fRun)
797     return kTRUE;
798   fRun = event->GetRunNumber();
799   
800   if(DebugLevel() > 1 )
801     Info("AccessODCD()"," Begin");
802   
803   //fGeom = AliEMCALGeometry::GetInstance(fGeomName);
804   
805   AliCDBManager *cdb = AliCDBManager::Instance();
806   
807   
808   if (fOCDBpath.Length()){
809     cdb->SetDefaultStorage(fOCDBpath.Data());
810     Info("AccessOCDB","Default storage %s",fOCDBpath.Data());
811   }
812   
813   cdb->SetRun(event->GetRunNumber());
814   
815   //
816   // EMCAL from RAW OCDB
817   if (fOCDBpath.Contains("alien:"))
818   {
819     cdb->SetSpecificStorage("EMCAL/Calib/Data","alien://Folder=/alice/data/2010/OCDB");
820     cdb->SetSpecificStorage("EMCAL/Calib/Pedestals","alien://Folder=/alice/data/2010/OCDB");
821   }
822   
823   TString path = cdb->GetDefaultStorage()->GetBaseFolder();
824   
825   // init parameters:
826   
827   //Get calibration parameters  
828   if(!fCalibData)
829   {
830     AliCDBEntry *entry = (AliCDBEntry*) 
831     AliCDBManager::Instance()->Get("EMCAL/Calib/Data");
832     
833     if (entry) fCalibData =  (AliEMCALCalibData*) entry->GetObject();
834   }
835   
836   if(!fCalibData)
837     AliFatal("Calibration parameters not found in CDB!");
838   
839   //Get calibration parameters  
840   if(!fPedestalData)
841   {
842     AliCDBEntry *entry = (AliCDBEntry*) 
843     AliCDBManager::Instance()->Get("EMCAL/Calib/Pedestals");
844     
845     if (entry) fPedestalData =  (AliCaloCalibPedestal*) entry->GetObject();
846   }
847   
848   if(!fPedestalData)
849     AliFatal("Dead map not found in CDB!");
850   
851   return kTRUE;
852 }
853
854 //________________________________________________________________________________________
855 void AliAnalysisTaskEMCALClusterize::InitClusterization()
856 {
857   //Select clusterization/unfolding algorithm and set all the needed parameters
858   
859   if (fJustUnfold){
860     // init the unfolding afterburner 
861     delete fUnfolder;
862     fUnfolder =  new AliEMCALAfterBurnerUF(fRecParam->GetW0(),fRecParam->GetLocMaxCut());
863     return;
864   }
865   
866   //First init the clusterizer
867   delete fClusterizer;
868   if     (fRecParam->GetClusterizerFlag() == AliEMCALRecParam::kClusterizerv1)
869     fClusterizer = new AliEMCALClusterizerv1 (fGeom, fCalibData, fPedestalData);
870   else if(fRecParam->GetClusterizerFlag() == AliEMCALRecParam::kClusterizerv2) 
871     fClusterizer = new AliEMCALClusterizerv2(fGeom, fCalibData, fPedestalData);
872   else if(fRecParam->GetClusterizerFlag() == AliEMCALRecParam::kClusterizerNxN){ 
873     fClusterizer = new AliEMCALClusterizerNxN(fGeom, fCalibData, fPedestalData);
874     fClusterizer->SetNRowDiff(fRecParam->GetNRowDiff());
875     fClusterizer->SetNColDiff(fRecParam->GetNColDiff());
876   } else {
877     AliFatal(Form("Clusterizer < %d > not available", fRecParam->GetClusterizerFlag()));
878   }
879   
880   //Now set the parameters
881   fClusterizer->SetECAClusteringThreshold( fRecParam->GetClusteringThreshold() );
882   fClusterizer->SetECALogWeight          ( fRecParam->GetW0()                  );
883   fClusterizer->SetMinECut               ( fRecParam->GetMinECut()             );    
884   fClusterizer->SetUnfolding             ( fRecParam->GetUnfold()              );
885   fClusterizer->SetECALocalMaxCut        ( fRecParam->GetLocMaxCut()           );
886   fClusterizer->SetTimeCut               ( fRecParam->GetTimeCut()             );
887   fClusterizer->SetTimeMin               ( fRecParam->GetTimeMin()             );
888   fClusterizer->SetTimeMax               ( fRecParam->GetTimeMax()             );
889   fClusterizer->SetInputCalibrated       ( kTRUE                               );
890   fClusterizer->SetJustClusters          ( kTRUE                               );  
891   //In case of unfolding after clusterization is requested, set the corresponding parameters
892   if(fRecParam->GetUnfold()){
893     Int_t i=0;
894     for (i = 0; i < 8; i++) {
895       fClusterizer->SetSSPars(i, fRecParam->GetSSPars(i));
896     }//end of loop over parameters
897     for (i = 0; i < 3; i++) {
898       fClusterizer->SetPar5  (i, fRecParam->GetPar5(i));
899       fClusterizer->SetPar6  (i, fRecParam->GetPar6(i));
900     }//end of loop over parameters
901     
902     fClusterizer->InitClusterUnfolding();
903
904   }// to unfold
905 }
906
907 //________________________________________________________________________________________
908 void AliAnalysisTaskEMCALClusterize::RecPoints2Clusters(TClonesArray *digitsArr, TObjArray *recPoints, TObjArray *clusArray)
909 {
910   // Restore clusters from recPoints
911   // Cluster energy, global position, cells and their amplitude fractions are restored
912   Int_t j = 0;
913   for(Int_t i = 0; i < recPoints->GetEntriesFast(); i++)
914   {
915     AliEMCALRecPoint *recPoint = (AliEMCALRecPoint*) recPoints->At(i);
916     
917     const Int_t ncells = recPoint->GetMultiplicity();
918     Int_t ncellsTrue = 0;
919     
920     if(recPoint->GetEnergy() < fRecParam->GetClusteringThreshold()) continue;
921     
922     // cells and their amplitude fractions
923     UShort_t   absIds[ncells];  
924     Double32_t ratios[ncells];
925     
926     //For later check embedding
927     AliAODInputHandler* aodIH = dynamic_cast<AliAODInputHandler*>((AliAnalysisManager::GetAnalysisManager())->GetInputEventHandler());
928     
929     Float_t clusterE = 0; 
930     for (Int_t c = 0; c < ncells; c++) {
931       AliEMCALDigit *digit = (AliEMCALDigit*) digitsArr->At(recPoint->GetDigitsList()[c]);
932       
933       absIds[ncellsTrue] = digit->GetId();
934       ratios[ncellsTrue] = recPoint->GetEnergiesList()[c]/digit->GetAmplitude();
935             
936       // In case of unfolding, remove digits with unfolded energy too low      
937       if(fSelectCell){
938         if     (recPoint->GetEnergiesList()[c] < fSelectCellMinE || ratios[ncellsTrue] < fSelectCellMinFrac)  {
939           
940           if(DebugLevel() > 1)  {
941             printf("AliAnalysisTaskEMCALClusterize::RecPoints2Clusters() - Too small energy in cell of cluster: cluster cell %f, digit %f\n",
942                    recPoint->GetEnergiesList()[c],digit->GetAmplitude());
943           }
944           
945           continue;
946           
947         } // if cuts
948       }// Select cells
949             
950       //Recalculate cluster energy and number of cluster cells in case any of the cells was rejected
951       ncellsTrue++;
952       clusterE  +=recPoint->GetEnergiesList()[c];
953       
954       // In case of embedding, fill ratio with amount of signal, 
955       if (aodIH && aodIH->GetMergeEvents()) {
956        
957         //AliVCaloCells* inEMCALCells = InputEvent()->GetEMCALCells();
958         AliVCaloCells* meEMCALCells = aodIH->GetEventToMerge()->GetEMCALCells();
959         AliVCaloCells* ouEMCALCells = AODEvent()->GetEMCALCells();
960         
961         Float_t sigAmplitude = meEMCALCells->GetCellAmplitude(absIds[ncellsTrue]);
962         //Float_t bkgAmplitude = inEMCALCells->GetCellAmplitude(absIds[ncellsTrue]);
963         Float_t sumAmplitude = ouEMCALCells->GetCellAmplitude(absIds[ncellsTrue]);
964         //printf("\t AbsID %d, amplitude : bkg %f, sigAmplitude %f, summed %f - %f\n",absIds[ncellsTrue], bkgAmplitude, sigAmplitude, sumAmplitude, digit->GetAmplitude());
965         
966         if(sumAmplitude > 0) ratios[ncellsTrue] = sigAmplitude/sumAmplitude;
967         //printf("\t \t ratio %f\n",ratios[ncellsTrue]);
968         
969       }//Embedding
970       
971     }// cluster cell loop
972     
973     if (ncellsTrue < 1) {
974       if (DebugLevel() > 1) 
975         printf("AliAnalysisTaskEMCALClusterize::RecPoints2Clusters() - Skipping cluster with no cells avobe threshold E = %f, ncells %d\n",
976                recPoint->GetEnergy(), ncells);
977       continue;
978     }
979     
980     //if(ncellsTrue != ncells) printf("Old E %f, ncells %d; New E %f, ncells %d\n",recPoint->GetEnergy(),ncells,clusterE,ncellsTrue);
981     
982     if(clusterE <  fRecParam->GetClusteringThreshold()) {
983       if (DebugLevel()>1)
984         printf("AliAnalysisTaskEMCALClusterize::RecPoints2Clusters() - Remove cluster with energy below seed threshold %f\n",clusterE);
985       continue;
986     }
987     
988     TVector3 gpos;
989     Float_t g[3];
990     
991     // calculate new cluster position
992     recPoint->EvalGlobalPosition(fRecParam->GetW0(), digitsArr);
993     recPoint->GetGlobalPosition(gpos);
994     gpos.GetXYZ(g);
995     
996     // create a new cluster
997     //AliAODCaloCluster *clus = new AliAODCaloCluster();
998     (*clusArray)[j] = new AliAODCaloCluster() ;
999     AliAODCaloCluster *clus = dynamic_cast<AliAODCaloCluster *>( clusArray->At(j) ) ;
1000     j++;
1001     clus->SetType(AliVCluster::kEMCALClusterv1);
1002     clus->SetE(clusterE);//recPoint->GetEnergy());
1003     clus->SetPosition(g);
1004     clus->SetNCells(ncellsTrue);
1005     clus->SetCellsAbsId(absIds);
1006     clus->SetCellsAmplitudeFraction(ratios);
1007     clus->SetChi2(-1); //not yet implemented
1008     clus->SetTOF(recPoint->GetTime()) ; //time-of-flight
1009     clus->SetNExMax(recPoint->GetNExMax()); //number of local maxima
1010     clus->SetDistanceToBadChannel(recPoint->GetDistanceToBadTower()); 
1011
1012     if(ncells == ncellsTrue){
1013       Float_t elipAxis[2];
1014       recPoint->GetElipsAxis(elipAxis);
1015       clus->SetM02(elipAxis[0]*elipAxis[0]) ;
1016       clus->SetM20(elipAxis[1]*elipAxis[1]) ;
1017       clus->SetDispersion(recPoint->GetDispersion());
1018     }
1019     else if(fSelectCell){
1020       // In case some cells rejected, in unfolding case, recalculate
1021       // shower shape parameters and position
1022       AliVCaloCells* cells = 0x0; 
1023       if (aodIH && aodIH->GetMergeEvents()) cells = AODEvent()  ->GetEMCALCells();
1024       else                                  cells = InputEvent()->GetEMCALCells();
1025       fRecoUtils->RecalculateClusterShowerShapeParameters(fGeom,cells,clus);
1026       fRecoUtils->RecalculateClusterPID(clus);
1027       fRecoUtils->RecalculateClusterPosition(fGeom,cells,clus); 
1028       
1029 //      Float_t elipAxis[2];
1030 //      recPoint->GetElipsAxis(elipAxis);
1031 //      if(ncellsTrue > 2)
1032 //      printf("SS, old: l0 %f, l1 %f, D %f; New l0 %f, l1 %f, D %f\n",
1033 //             elipAxis[0]*elipAxis[0],elipAxis[1]*elipAxis[1], recPoint->GetDispersion(),
1034 //             clus->GetM02(),clus->GetM20(),clus->GetDispersion());
1035     }
1036     
1037     //MC
1038     Int_t  parentMult  = 0;
1039     Int_t *parentList = recPoint->GetParents(parentMult);
1040     clus->SetLabel(parentList, parentMult); 
1041     
1042     //    if(parentMult)printf("RecToESD: Labels %d",parentMult);
1043     //    for (Int_t iii = 0; iii < parentMult; iii++) {
1044     //      printf("\t label %d\n",parentList[iii]);
1045     //    }
1046     
1047     //Write the second major contributor to each MC cluster.
1048     Int_t iNewLabel ;
1049     for ( Int_t iLoopCell = 0 ; iLoopCell < clus->GetNCells() ; iLoopCell++ ){
1050       
1051       Int_t idCell = clus->GetCellAbsId(iLoopCell) ;
1052       if(idCell>=0){
1053         iNewLabel = 1 ; //iNewLabel makes sure we  don't write twice the same label.
1054         for ( UInt_t iLoopLabels = 0 ; iLoopLabels < clus->GetNLabels() ; iLoopLabels++ )
1055         {
1056           if ( fCellSecondLabels[idCell] == -1 )  iNewLabel = 0;  // -1 is never a good second label.
1057           if ( fCellSecondLabels[idCell] == clus->GetLabelAt(iLoopLabels) )  iNewLabel = 0;
1058         }
1059         if (iNewLabel == 1) 
1060         {
1061           //Int_t * newLabelArray = (Int_t*)malloc((clus->GetNLabels()+1)*sizeof(Int_t)) ;
1062           Int_t * newLabelArray = new Int_t[clus->GetNLabels()+1] ;
1063           for ( UInt_t iLoopNewLabels = 0 ; iLoopNewLabels < clus->GetNLabels() ; iLoopNewLabels++ ){
1064             newLabelArray[iLoopNewLabels] = clus->GetLabelAt(iLoopNewLabels) ;
1065           }
1066           
1067           newLabelArray[clus->GetNLabels()] = fCellSecondLabels[idCell] ;
1068           //if(fCellSecondLabels[idCell]>-1)printf("\t new label %d\n",fCellSecondLabels[idCell]);
1069           clus->SetLabel(newLabelArray,clus->GetNLabels()+1) ;
1070           delete [] newLabelArray;
1071         }
1072       }//positive cell number
1073     }
1074     
1075   } // recPoints loop
1076     
1077 }