]> git.uio.no Git - u/mrichter/AliRoot.git/blob - EMCAL/AliEMCALClusterizerv1.cxx
1) New library EMCALUtils with geometry and PID utils for the analysis: New classes...
[u/mrichter/AliRoot.git] / EMCAL / AliEMCALClusterizerv1.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$ */
17
18 //-- Author: Yves Schutz (SUBATECH)  & Dmitri Peressounko (SUBATECH & Kurchatov Institute)
19 //  August 2002 Yves Schutz: clone PHOS as closely as possible and intoduction
20 //                           of new  IO (à la PHOS)
21 //  Mar 2007, Aleksei Pavlinov - new algoritmh of pseudo clusters
22 //////////////////////////////////////////////////////////////////////////////
23 //  Clusterization class. Performs clusterization (collects neighbouring active cells) and 
24 //  unfolds the clusters having several local maxima.  
25 //  Results are stored in TreeR#, branches EMCALTowerRP (EMC recPoints),
26 //  EMCALPreShoRP (CPV RecPoints) and AliEMCALClusterizer (Clusterizer with all 
27 //  parameters including input digits branch title, thresholds etc.)
28 //  This TTask is normally called from Reconstructioner, but can as well be used in 
29 //  standalone mode.
30 // Use Case:
31 //  root [0] AliEMCALClusterizerv1 * cl = new AliEMCALClusterizerv1("galice.root")  
32 //  Warning in <TDatabasePDG::TDatabasePDG>: object already instantiated
33 //               //reads gAlice from header file "..."                      
34 //  root [1] cl->ExecuteTask()  
35 //               //finds RecPoints in all events stored in galice.root
36 //  root [2] cl->SetDigitsBranch("digits2") 
37 //               //sets another title for Digitis (input) branch
38 //  root [3] cl->SetRecPointsBranch("recp2")  
39 //               //sets another title four output branches
40 //  root [4] cl->SetTowerLocalMaxCut(0.03)  
41 //               //set clusterization parameters
42 //  root [5] cl->ExecuteTask("deb all time")  
43 //               //once more finds RecPoints options are 
44 //               // deb - print number of found rec points
45 //               // deb all - print number of found RecPoints and some their characteristics 
46 //               // time - print benchmarking results
47
48 // --- ROOT system ---
49 #include <cassert>
50
51 class TROOT;
52 #include <TH1.h>
53 #include <TFile.h> 
54 class TFolder;
55 #include <TMath.h> 
56 #include <TMinuit.h>
57 #include <TTree.h> 
58 class TSystem; 
59 #include <TBenchmark.h>
60 #include <TBrowser.h>
61 #include <TROOT.h>
62
63 // --- Standard library ---
64
65
66 // --- AliRoot header files ---
67 #include "AliRunLoader.h"
68 #include "AliRun.h"
69 #include "AliESD.h"
70 #include "AliEMCALClusterizerv1.h"
71 #include "AliEMCALRecPoint.h"
72 #include "AliEMCALDigit.h"
73 #include "AliEMCALDigitizer.h"
74 #include "AliEMCAL.h"
75 #include "AliEMCALGeometry.h"
76 #include "AliEMCALRecParam.h"
77 #include "AliEMCALReconstructor.h"
78 #include "AliCDBManager.h"
79
80 class AliCDBStorage;
81 #include "AliCDBEntry.h"
82
83 ClassImp(AliEMCALClusterizerv1)
84
85 //____________________________________________________________________________
86 AliEMCALClusterizerv1::AliEMCALClusterizerv1()
87   : AliEMCALClusterizer(),
88     fGeom(0),
89     fDefaultInit(kFALSE),
90     fToUnfold(kFALSE),
91     fNumberOfECAClusters(0),fCalibData(0),
92     fADCchannelECA(0.),fADCpedestalECA(0.),fECAClusteringThreshold(0.),fECALocMaxCut(0.),
93     fECAW0(0.),fTimeCut(0.),fMinECut(0.)
94 {
95   // ctor with the indication of the file where header Tree and digits Tree are stored
96   
97   Init() ;
98 }
99
100 //____________________________________________________________________________
101 AliEMCALClusterizerv1::AliEMCALClusterizerv1(AliEMCALGeometry* geometry)
102   : AliEMCALClusterizer(),
103     fGeom(geometry),
104     fDefaultInit(kFALSE),
105     fToUnfold(kFALSE),
106     fNumberOfECAClusters(0),fCalibData(0),
107     fADCchannelECA(0.),fADCpedestalECA(0.),fECAClusteringThreshold(0.),fECALocMaxCut(0.),
108     fECAW0(0.),fTimeCut(0.),fMinECut(0.)
109 {
110   // ctor with the indication of the file where header Tree and digits Tree are stored
111   // use this contructor to avoid usage of Init() which uses runloader
112   // change needed by HLT - MP
113
114   // Note for the future: the use on runloader should be avoided or optional at least
115   // another way is to make Init virtual and protected at least such that the deriving classes can overload
116   // Init() ;
117   //
118
119   if (!fGeom)
120     {
121       AliFatal("Geometry not initialized.");
122     }
123
124   if(!gMinuit)
125     gMinuit = new TMinuit(100) ;
126
127 }
128
129 //____________________________________________________________________________
130 AliEMCALClusterizerv1::AliEMCALClusterizerv1(AliEMCALGeometry* geometry, AliEMCALCalibData * calib)
131 : AliEMCALClusterizer(),
132 fGeom(geometry),
133 fDefaultInit(kFALSE),
134 fToUnfold(kFALSE),
135 fNumberOfECAClusters(0),fCalibData(calib),
136 fADCchannelECA(0.),fADCpedestalECA(0.),fECAClusteringThreshold(0.),fECALocMaxCut(0.),
137 fECAW0(0.),fTimeCut(0.),fMinECut(0.)
138 {
139         // ctor, geometry and calibration are initialized elsewhere.
140         
141         if (!fGeom)
142                 AliFatal("Geometry not initialized.");
143                 
144         if(!gMinuit)
145                 gMinuit = new TMinuit(100) ;
146         
147 }
148
149
150 //____________________________________________________________________________
151   AliEMCALClusterizerv1::~AliEMCALClusterizerv1()
152 {
153   // dtor
154 }
155
156 //____________________________________________________________________________
157 Float_t  AliEMCALClusterizerv1::Calibrate(Int_t amp, Int_t AbsId) 
158 {
159  
160   // Convert digitized amplitude into energy.
161   // Calibration parameters are taken from calibration data base for raw data,
162   // or from digitizer parameters for simulated data.
163
164   if(fCalibData){
165     
166     if (fGeom==0)
167       AliFatal("Did not get geometry from EMCALLoader") ;
168     
169     Int_t iSupMod = -1;
170     Int_t nModule  = -1;
171     Int_t nIphi   = -1;
172     Int_t nIeta   = -1;
173     Int_t iphi    = -1;
174     Int_t ieta    = -1;
175     
176     Bool_t bCell = fGeom->GetCellIndex(AbsId, iSupMod, nModule, nIphi, nIeta) ;
177     if(!bCell) {
178       fGeom->PrintGeometry();
179       Error("Calibrate()"," Wrong cell id number : %i", AbsId);
180       assert(0);
181     }
182
183     fGeom->GetCellPhiEtaIndexInSModule(iSupMod,nModule,nIphi, nIeta,iphi,ieta);
184
185     fADCchannelECA  = fCalibData->GetADCchannel (iSupMod,ieta,iphi);
186     fADCpedestalECA = fCalibData->GetADCpedestal(iSupMod,ieta,iphi);
187   
188    return -fADCpedestalECA + amp * fADCchannelECA ;        
189  
190   }
191   else //Return energy with default parameters if calibration is not available
192     return -fADCpedestalECA + amp * fADCchannelECA ; 
193   
194 }
195
196 //____________________________________________________________________________
197 void AliEMCALClusterizerv1::Digits2Clusters(Option_t * option)
198 {
199   // Steering method to perform clusterization for the current event 
200   // in AliEMCALLoader
201
202   if(strstr(option,"tim"))
203     gBenchmark->Start("EMCALClusterizer"); 
204   
205   if(strstr(option,"print"))
206     Print("") ; 
207  
208   //Get calibration parameters from file or digitizer default values.
209   GetCalibrationParameters() ;
210
211
212   fNumberOfECAClusters = 0;
213
214   MakeClusters() ;  //only the real clusters
215
216   if(fToUnfold)
217     MakeUnfolding() ;
218
219   Int_t index ;
220
221   //Evaluate position, dispersion and other RecPoint properties for EC section                      
222   for(index = 0; index < fRecPoints->GetEntries(); index++) {
223       dynamic_cast<AliEMCALRecPoint *>(fRecPoints->At(index))->EvalAll(fECAW0,fDigitsArr) ;
224   }
225
226   fRecPoints->Sort() ;
227
228   for(index = 0; index < fRecPoints->GetEntries(); index++) {
229     (dynamic_cast<AliEMCALRecPoint *>(fRecPoints->At(index)))->SetIndexInList(index) ;
230     (dynamic_cast<AliEMCALRecPoint *>(fRecPoints->At(index)))->Print();
231   }
232
233   fTreeR->Fill();
234   
235   if(strstr(option,"deb") || strstr(option,"all"))  
236     PrintRecPoints(option) ;
237
238   AliDebug(1,Form("EMCAL Clusterizer found %d Rec Points",fRecPoints->GetEntriesFast()));
239
240   if(strstr(option,"tim")){
241     gBenchmark->Stop("EMCALClusterizer");
242     printf("Exec took %f seconds for Clusterizing", 
243            gBenchmark->GetCpuTime("EMCALClusterizer"));
244   }    
245 }
246
247 //____________________________________________________________________________
248 Bool_t AliEMCALClusterizerv1::FindFit(AliEMCALRecPoint * RecPoint, AliEMCALDigit ** maxAt, 
249                                       Float_t* maxAtEnergy,
250                                       Int_t nPar, Float_t * fitparameters) const
251 {
252   // Calls TMinuit to fit the energy distribution of a cluster with several maxima
253   // The initial values for fitting procedure are set equal to the
254   // positions of local maxima.       
255   // Cluster will be fitted as a superposition of nPar/3
256   // electromagnetic showers
257
258   if (fGeom==0) AliFatal("Did not get geometry from EMCALLoader");
259
260   gMinuit->mncler();                     // Reset Minuit's list of paramters
261   gMinuit->SetPrintLevel(-1) ;           // No Printout
262   gMinuit->SetFCN(AliEMCALClusterizerv1::UnfoldingChiSquare) ;
263   // To set the address of the minimization function
264   TList * toMinuit = new TList();
265   toMinuit->AddAt(RecPoint,0) ;
266   toMinuit->AddAt(fDigitsArr,1) ;
267   toMinuit->AddAt(fGeom,2) ;
268
269   gMinuit->SetObjectFit(toMinuit) ;         // To tranfer pointer to UnfoldingChiSquare
270
271   // filling initial values for fit parameters
272   AliEMCALDigit * digit ;
273
274   Int_t ierflg  = 0;
275   Int_t index   = 0 ;
276   Int_t nDigits = (Int_t) nPar / 3 ;
277
278   Int_t iDigit ;
279
280   for(iDigit = 0; iDigit < nDigits; iDigit++){
281     digit = maxAt[iDigit];
282     Double_t x = 0.;
283     Double_t y = 0.;
284     Double_t z = 0.;
285
286     fGeom->RelPosCellInSModule(digit->GetId(), y, x, z);
287
288     Float_t energy = maxAtEnergy[iDigit] ;
289
290     gMinuit->mnparm(index, "x",  x, 0.1, 0, 0, ierflg) ;
291     index++ ;
292     if(ierflg != 0){
293       Error("FindFit", "EMCAL Unfolding  Unable to set initial value for fit procedure : x = %f", x ) ;
294       return kFALSE;
295     }
296     gMinuit->mnparm(index, "z",  z, 0.1, 0, 0, ierflg) ;
297     index++ ;
298     if(ierflg != 0){
299       Error("FindFit", "EMCAL Unfolding  Unable to set initial value for fit procedure : z = %f", z) ;
300       return kFALSE;
301     }
302     gMinuit->mnparm(index, "Energy",  energy , 0.05*energy, 0., 4.*energy, ierflg) ;
303     index++ ;
304     if(ierflg != 0){
305       Error("FindFit", "EMCAL Unfolding  Unable to set initial value for fit procedure : energy = %f", energy) ;
306       return kFALSE;
307     }
308   }
309
310   Double_t p0 = 0.1 ; // "Tolerance" Evaluation stops when EDM = 0.0001*p0 ; 
311                       // The number of function call slightly depends on it.
312   //Double_t p1 = 1.0 ;
313   Double_t p2 = 0.0 ;
314
315   gMinuit->mnexcm("SET STR", &p2, 0, ierflg) ;   // force TMinuit to reduce function calls
316   //  gMinuit->mnexcm("SET GRA", &p1, 1, ierflg) ;   // force TMinuit to use my gradient
317   gMinuit->SetMaxIterations(5);
318   gMinuit->mnexcm("SET NOW", &p2 , 0, ierflg) ;  // No Warnings
319   gMinuit->mnexcm("MIGRAD", &p0, 0, ierflg) ;    // minimize
320
321   if(ierflg == 4){  // Minimum not found
322     Error("FindFit", "EMCAL Unfolding  Fit not converged, cluster abandoned " ) ;
323     return kFALSE ;
324   }
325   for(index = 0; index < nPar; index++){
326     Double_t err ;
327     Double_t val ;
328     gMinuit->GetParameter(index, val, err) ;    // Returns value and error of parameter index
329     fitparameters[index] = val ;
330   }
331
332   delete toMinuit ;
333   return kTRUE;
334
335 }
336
337 //____________________________________________________________________________
338 void AliEMCALClusterizerv1::GetCalibrationParameters() 
339 {
340   // Set calibration parameters:
341   // if calibration database exists, they are read from database,
342   // otherwise, they are taken from digitizer.
343   //
344   // It is a user responsilibity to open CDB before reconstruction, 
345   // for example: 
346   // AliCDBStorage* storage = AliCDBManager::Instance()->GetStorage("local://CalibDB");
347
348   //Check if calibration is stored in data base
349
350   if(!fCalibData)
351     {
352       AliCDBEntry *entry = (AliCDBEntry*) 
353         AliCDBManager::Instance()->Get("EMCAL/Calib/Data");
354       if (entry) fCalibData =  (AliEMCALCalibData*) entry->GetObject();
355     }
356   
357   if(!fCalibData)
358     AliFatal("Calibration parameters not found in CDB!");
359  
360 }
361
362 //____________________________________________________________________________
363 void AliEMCALClusterizerv1::Init()
364 {
365   // Make all memory allocations which can not be done in default constructor.
366   // Attach the Clusterizer task to the list of EMCAL tasks
367   
368   AliRunLoader *rl = AliRunLoader::Instance();
369   if (rl->GetAliRun() && rl->GetAliRun()->GetDetector("EMCAL"))
370     fGeom = dynamic_cast<AliEMCAL*>(rl->GetAliRun()->GetDetector("EMCAL"))->GetGeometry();
371   else 
372     fGeom =  AliEMCALGeometry::GetInstance(AliEMCALGeometry::GetDefaultGeometryName());
373
374   AliDebug(1,Form("geom 0x%x",fGeom));
375
376   if(!gMinuit) 
377     gMinuit = new TMinuit(100) ;
378
379 }
380
381 //____________________________________________________________________________
382 void AliEMCALClusterizerv1::InitParameters()
383
384   // Initializes the parameters for the Clusterizer
385   fNumberOfECAClusters = 0;
386   fTimeCut = 300e-9 ; // 300 ns time cut (to be tuned) 
387
388   fCalibData               = 0 ;
389
390   const AliEMCALRecParam* recParam = AliEMCALReconstructor::GetRecParam();
391   if(!recParam) {
392     AliFatal("Reconstruction parameters for EMCAL not set!");
393   } else {
394     fECAClusteringThreshold = recParam->GetClusteringThreshold();
395     fECAW0                  = recParam->GetW0();
396     fMinECut                = recParam->GetMinECut();    
397     fToUnfold               = recParam->GetUnfold();
398     if(fToUnfold) AliWarning("Cluster Unfolding ON. Implementing only for eta=0 case!!!"); 
399     fECALocMaxCut           = recParam->GetLocMaxCut();
400     
401     AliDebug(1,Form("Reconstruction parameters: fECAClusteringThreshold=%.3f, fECAW=%.3f, fMinECut=%.3f, fToUnfold=%d, fECALocMaxCut=%.3f",
402                     fECAClusteringThreshold,fECAW0,fMinECut,fToUnfold,fECALocMaxCut));
403   }
404
405 }
406
407 //____________________________________________________________________________
408 Int_t AliEMCALClusterizerv1::AreNeighbours(AliEMCALDigit * d1, AliEMCALDigit * d2) const
409 {
410   // Gives the neighbourness of two digits = 0 are not neighbour ; continue searching 
411   //                                       = 1 are neighbour
412   //                                       = 2 is in different SM; continue searching 
413   // neighbours are defined as digits having at least a common vertex 
414   // The order of d1 and d2 is important: first (d1) should be a digit already in a cluster 
415   //                                      which is compared to a digit (d2)  not yet in a cluster  
416
417   static Int_t rv; 
418   static Int_t nSupMod1=0, nModule1=0, nIphi1=0, nIeta1=0, iphi1=0, ieta1=0;
419   static Int_t nSupMod2=0, nModule2=0, nIphi2=0, nIeta2=0, iphi2=0, ieta2=0;
420   static Int_t rowdiff, coldiff;
421   rv = 0 ; 
422
423   fGeom->GetCellIndex(d1->GetId(), nSupMod1,nModule1,nIphi1,nIeta1);
424   fGeom->GetCellIndex(d2->GetId(), nSupMod2,nModule2,nIphi2,nIeta2);
425   if(nSupMod1 != nSupMod2) return 2; // different SM
426
427   fGeom->GetCellPhiEtaIndexInSModule(nSupMod1,nModule1,nIphi1,nIeta1, iphi1,ieta1);
428   fGeom->GetCellPhiEtaIndexInSModule(nSupMod2,nModule2,nIphi2,nIeta2, iphi2,ieta2);
429
430   rowdiff = TMath::Abs(iphi1 - iphi2);  
431   coldiff = TMath::Abs(ieta1 - ieta2) ;  
432   
433   // neighbours with at least commom side; May 11, 2007
434   if ((coldiff==0 && abs(rowdiff)==1) || (rowdiff==0 && abs(coldiff)==1)) rv = 1;  
435  
436   if (gDebug == 2 && rv==1) 
437   printf("AreNeighbours: neighbours=%d, id1=%d, relid1=%d,%d \n id2=%d, relid2=%d,%d \n", 
438          rv, d1->GetId(), iphi1,ieta1, d2->GetId(), iphi2,ieta2);   
439   
440   return rv ; 
441 }
442
443 //____________________________________________________________________________
444 void AliEMCALClusterizerv1::MakeClusters()
445 {
446   // Steering method to construct the clusters stored in a list of Reconstructed Points
447   // A cluster is defined as a list of neighbour digits
448   // Mar 03, 2007 by PAI
449
450   if (fGeom==0) AliFatal("Did not get geometry from EMCALLoader");
451
452   fRecPoints->Clear();
453
454   // Set up TObjArray with pointers to digits to work on 
455   TObjArray *digitsC = new TObjArray();
456   TIter nextdigit(fDigitsArr);
457   AliEMCALDigit *digit;
458   while ( (digit = dynamic_cast<AliEMCALDigit*>(nextdigit())) ) {
459     digitsC->AddLast(digit);
460   }
461
462   double e = 0.0, ehs = 0.0;
463   TIter nextdigitC(digitsC);
464
465   while ( (digit = dynamic_cast<AliEMCALDigit *>(nextdigitC())) ) { // clean up digits
466     e = Calibrate(digit->GetAmp(), digit->GetId());
467     if ( e < fMinECut || digit->GetTimeR() > fTimeCut ) 
468       digitsC->Remove(digit);
469     else    
470       ehs += e;
471   } 
472   AliDebug(1,Form("MakeClusters: Number of digits %d  -> (e %f), ehs %d\n",
473                   fDigitsArr->GetEntries(),fMinECut,ehs));
474
475   nextdigitC.Reset();
476
477   while ( (digit = dynamic_cast<AliEMCALDigit *>(nextdigitC())) ) { // scan over the list of digitsC
478     TArrayI clusterECAdigitslist(fDigitsArr->GetEntries());
479
480     if(fGeom->CheckAbsCellId(digit->GetId()) && (Calibrate(digit->GetAmp(), digit->GetId()) > fECAClusteringThreshold  ) ){
481       // start a new Tower RecPoint
482       if(fNumberOfECAClusters >= fRecPoints->GetSize()) fRecPoints->Expand(2*fNumberOfECAClusters+1) ;
483
484       AliEMCALRecPoint *recPoint = new  AliEMCALRecPoint("") ; 
485       fRecPoints->AddAt(recPoint, fNumberOfECAClusters) ;
486       recPoint = dynamic_cast<AliEMCALRecPoint *>(fRecPoints->At(fNumberOfECAClusters)) ; 
487       fNumberOfECAClusters++ ; 
488
489       recPoint->SetClusterType(AliESDCaloCluster::kEMCALClusterv1);
490
491       recPoint->AddDigit(*digit, Calibrate(digit->GetAmp(), digit->GetId())) ; 
492       TObjArray clusterDigits;
493       clusterDigits.AddLast(digit);     
494       digitsC->Remove(digit) ; 
495
496       AliDebug(1,Form("MakeClusters: OK id = %d, ene = %f , cell.th. = %f \n", digit->GetId(),
497       Calibrate(digit->GetAmp(),digit->GetId()), fECAClusteringThreshold));  
498       
499       // Grow cluster by finding neighbours
500       TIter nextClusterDigit(&clusterDigits);
501       while ( (digit = dynamic_cast<AliEMCALDigit*>(nextClusterDigit())) ) { // scan over digits in cluster 
502         TIter nextdigitN(digitsC); 
503         AliEMCALDigit *digitN = 0; // digi neighbor
504         while ( (digitN = (AliEMCALDigit *)nextdigitN()) ) { // scan over all digits to look for neighbours
505           if (AreNeighbours(digit, digitN)==1) {      // call (digit,digitN) in THAT oder !!!!! 
506             recPoint->AddDigit(*digitN, Calibrate(digitN->GetAmp(),digitN->GetId()) ) ;
507             clusterDigits.AddLast(digitN) ; 
508             digitsC->Remove(digitN) ; 
509           } // if(ineb==1)
510         } // scan over digits
511       } // scan over digits already in cluster
512       if(recPoint)
513         AliDebug(2,Form("MakeClusters: %d digitd, energy %f \n", clusterDigits.GetEntries(), recPoint->GetEnergy())); 
514     } // If seed found
515   } // while digit 
516
517   delete digitsC ;
518   
519   AliDebug(1,Form("total no of clusters %d from %d digits",fNumberOfECAClusters,fDigitsArr->GetEntriesFast())); 
520 }
521
522 //____________________________________________________________________________
523 void AliEMCALClusterizerv1::MakeUnfolding()
524 {
525   // Unfolds clusters using the shape of an ElectroMagnetic shower
526   // Performs unfolding of all clusters
527
528   if(fNumberOfECAClusters > 0){
529     if (fGeom==0)
530       AliFatal("Did not get geometry from EMCALLoader") ;
531     Int_t nModulesToUnfold = fGeom->GetNCells();
532
533     Int_t numberofNotUnfolded = fNumberOfECAClusters ;
534     Int_t index ;
535     for(index = 0 ; index < numberofNotUnfolded ; index++){
536
537       AliEMCALRecPoint * RecPoint = dynamic_cast<AliEMCALRecPoint *>( fRecPoints->At(index) ) ;
538
539       TVector3 gpos;
540       Int_t absId;
541       RecPoint->GetGlobalPosition(gpos);
542       fGeom->GetAbsCellIdFromEtaPhi(gpos.Eta(),gpos.Phi(),absId);
543       if(absId > nModulesToUnfold)
544         break ;
545
546       Int_t nMultipl = RecPoint->GetMultiplicity() ;
547       AliEMCALDigit ** maxAt = new AliEMCALDigit*[nMultipl] ;
548       Float_t * maxAtEnergy = new Float_t[nMultipl] ;
549       Int_t nMax = RecPoint->GetNumberOfLocalMax(maxAt, maxAtEnergy,fECALocMaxCut,fDigitsArr) ;
550
551       if( nMax > 1 ) {     // if cluster is very flat (no pronounced maximum) then nMax = 0
552         UnfoldCluster(RecPoint, nMax, maxAt, maxAtEnergy) ;
553         fRecPoints->Remove(RecPoint);
554         fRecPoints->Compress() ;
555         index-- ;
556         fNumberOfECAClusters-- ;
557         numberofNotUnfolded-- ;
558       }
559       else{
560         RecPoint->SetNExMax(1) ; //Only one local maximum
561       }
562
563       delete[] maxAt ;
564       delete[] maxAtEnergy ;
565     }
566   }
567   // End of Unfolding of clusters
568 }
569
570 //____________________________________________________________________________
571 Double_t  AliEMCALClusterizerv1::ShowerShape(Double_t x, Double_t y)
572
573   // Shape of the shower
574   // If you change this function, change also the gradient evaluation in ChiSquare()
575
576   Double_t r = sqrt(x*x+y*y);
577   Double_t r133  = TMath::Power(r, 1.33) ;
578   Double_t r669  = TMath::Power(r, 6.69) ;
579   Double_t shape = TMath::Exp( -r133 * (1. / (1.57 + 0.0860 * r133) - 0.55 / (1 + 0.000563 * r669) ) ) ;
580   return shape ;
581 }
582
583 //____________________________________________________________________________
584 void  AliEMCALClusterizerv1::UnfoldCluster(AliEMCALRecPoint * iniTower, 
585                                            Int_t nMax, 
586                                            AliEMCALDigit ** maxAt, 
587                                            Float_t * maxAtEnergy)
588 {
589   // Performs the unfolding of a cluster with nMax overlapping showers 
590   Int_t nPar = 3 * nMax ;
591   Float_t * fitparameters = new Float_t[nPar] ;
592
593   if (fGeom==0)
594     AliFatal("Did not get geometry from EMCALLoader") ;
595
596   Bool_t rv = FindFit(iniTower, maxAt, maxAtEnergy, nPar, fitparameters) ;
597   if( !rv ) {
598     // Fit failed, return and remove cluster
599     iniTower->SetNExMax(-1) ;
600     delete[] fitparameters ;
601     return ;
602   }
603
604   // create unfolded rec points and fill them with new energy lists
605   // First calculate energy deposited in each sell in accordance with
606   // fit (without fluctuations): efit[]
607   // and later correct this number in acordance with actual energy
608   // deposition
609
610   Int_t nDigits = iniTower->GetMultiplicity() ;
611   Float_t * efit = new Float_t[nDigits] ;
612   Double_t xDigit=0.,yDigit=0.,zDigit=0. ;
613   Float_t xpar=0.,zpar=0.,epar=0.  ;
614
615   AliEMCALDigit * digit = 0 ;
616   Int_t * Digits = iniTower->GetDigitsList() ;
617
618   Int_t iparam ;
619   Int_t iDigit ;
620   for(iDigit = 0 ; iDigit < nDigits ; iDigit ++){
621     digit = dynamic_cast<AliEMCALDigit*>( fDigitsArr->At(Digits[iDigit] ) ) ;
622     fGeom->RelPosCellInSModule(digit->GetId(), yDigit, xDigit, zDigit);
623     efit[iDigit] = 0;
624
625     iparam = 0 ;
626     while(iparam < nPar ){
627       xpar = fitparameters[iparam] ;
628       zpar = fitparameters[iparam+1] ;
629       epar = fitparameters[iparam+2] ;
630       iparam += 3 ;
631       efit[iDigit] += epar * ShowerShape(xDigit - xpar,zDigit - zpar) ;
632     }
633   }
634
635
636   // Now create new RecPoints and fill energy lists with efit corrected to fluctuations
637   // so that energy deposited in each cell is distributed between new clusters proportionally
638   // to its contribution to efit
639
640   Float_t * Energies = iniTower->GetEnergiesList() ;
641   Float_t ratio ;
642
643   iparam = 0 ;
644   while(iparam < nPar ){
645     xpar = fitparameters[iparam] ;
646     zpar = fitparameters[iparam+1] ;
647     epar = fitparameters[iparam+2] ;
648     iparam += 3 ;
649
650     AliEMCALRecPoint * RecPoint = 0 ;
651
652     if(fNumberOfECAClusters >= fRecPoints->GetSize())
653       fRecPoints->Expand(2*fNumberOfECAClusters) ;
654
655     (*fRecPoints)[fNumberOfECAClusters] = new AliEMCALRecPoint("") ;
656     RecPoint = dynamic_cast<AliEMCALRecPoint *>( fRecPoints->At(fNumberOfECAClusters) ) ;
657     fNumberOfECAClusters++ ;
658     RecPoint->SetNExMax((Int_t)nPar/3) ;
659
660     Float_t eDigit ;
661     for(iDigit = 0 ; iDigit < nDigits ; iDigit ++){
662       digit = dynamic_cast<AliEMCALDigit*>( fDigitsArr->At( Digits[iDigit] ) ) ;
663       fGeom->RelPosCellInSModule(digit->GetId(), yDigit, xDigit, zDigit);
664
665       ratio = epar * ShowerShape(xDigit - xpar,zDigit - zpar) / efit[iDigit] ;
666       eDigit = Energies[iDigit] * ratio ;
667       RecPoint->AddDigit( *digit, eDigit ) ;
668     }
669   }
670
671   delete[] fitparameters ;
672   delete[] efit ;
673
674 }
675
676 //_____________________________________________________________________________
677 void AliEMCALClusterizerv1::UnfoldingChiSquare(Int_t & nPar, Double_t * Grad,
678                                                Double_t & fret,
679                                                Double_t * x, Int_t iflag)
680 {
681   // Calculates the Chi square for the cluster unfolding minimization
682   // Number of parameters, Gradient, Chi squared, parameters, what to do
683
684   TList * toMinuit = dynamic_cast<TList*>( gMinuit->GetObjectFit() ) ;
685
686   AliEMCALRecPoint * RecPoint = dynamic_cast<AliEMCALRecPoint*>( toMinuit->At(0) )  ;
687   TClonesArray * digits = dynamic_cast<TClonesArray*>( toMinuit->At(1) )  ;
688   // A bit buggy way to get an access to the geometry
689   // To be revised!
690   AliEMCALGeometry *geom = dynamic_cast<AliEMCALGeometry *>(toMinuit->At(2));
691
692   Int_t * Digits     = RecPoint->GetDigitsList() ;
693
694   Int_t nOdigits = RecPoint->GetDigitsMultiplicity() ;
695
696   Float_t * Energies = RecPoint->GetEnergiesList() ;
697
698   fret = 0. ;
699   Int_t iparam ;
700
701   if(iflag == 2)
702     for(iparam = 0 ; iparam < nPar ; iparam++)
703       Grad[iparam] = 0 ; // Will evaluate gradient
704
705   Double_t efit ;
706
707   AliEMCALDigit * digit ;
708   Int_t iDigit ;
709
710   for( iDigit = 0 ; iDigit < nOdigits ; iDigit++) {
711
712     digit = dynamic_cast<AliEMCALDigit*>( digits->At( Digits[iDigit] ) );
713
714     Double_t xDigit=0 ;
715     Double_t zDigit=0 ;
716     Double_t yDigit=0 ;//not used yet, assumed to be 0
717
718     geom->RelPosCellInSModule(digit->GetId(), yDigit, xDigit, zDigit);
719
720     if(iflag == 2){  // calculate gradient
721       Int_t iParam = 0 ;
722       efit = 0 ;
723       while(iParam < nPar ){
724         Double_t dx = (xDigit - x[iParam]) ;
725         iParam++ ;
726         Double_t dz = (zDigit - x[iParam]) ;
727         iParam++ ;
728         efit += x[iParam] * ShowerShape(dx,dz) ;
729         iParam++ ;
730       }
731       Double_t sum = 2. * (efit - Energies[iDigit]) / Energies[iDigit] ; // Here we assume, that sigma = sqrt(E)
732       iParam = 0 ;
733       while(iParam < nPar ){
734         Double_t xpar = x[iParam] ;
735         Double_t zpar = x[iParam+1] ;
736         Double_t epar = x[iParam+2] ;
737         Double_t dr = TMath::Sqrt( (xDigit - xpar) * (xDigit - xpar) + (zDigit - zpar) * (zDigit - zpar) );
738         Double_t shape = sum * ShowerShape(xDigit - xpar,zDigit - zpar) ;
739         Double_t r133 =  TMath::Power(dr, 1.33);
740         Double_t r669 = TMath::Power(dr,6.69);
741         Double_t deriv =-1.33 * TMath::Power(dr,0.33)*dr * ( 1.57 / ( (1.57 + 0.0860 * r133) * (1.57 + 0.0860 * r133) )
742                                                              - 0.55 / (1 + 0.000563 * r669) / ( (1 + 0.000563 * r669) * (1 + 0.000563 * r669) ) ) ;
743
744         Grad[iParam] += epar * shape * deriv * (xpar - xDigit) ;  // Derivative over x
745         iParam++ ;
746         Grad[iParam] += epar * shape * deriv * (zpar - zDigit) ;  // Derivative over z
747         iParam++ ;
748         Grad[iParam] += shape ;                                  // Derivative over energy
749         iParam++ ;
750       }
751     }
752     efit = 0;
753     iparam = 0 ;
754
755
756     while(iparam < nPar ){
757       Double_t xpar = x[iparam] ;
758       Double_t zpar = x[iparam+1] ;
759       Double_t epar = x[iparam+2] ;
760       iparam += 3 ;
761       efit += epar * ShowerShape(xDigit - xpar,zDigit - zpar) ;
762     }
763
764     fret += (efit-Energies[iDigit])*(efit-Energies[iDigit])/Energies[iDigit] ;
765     // Here we assume, that sigma = sqrt(E) 
766   }
767 }
768 //____________________________________________________________________________
769 void AliEMCALClusterizerv1::Print(Option_t * /*option*/)const
770 {
771   // Print clusterizer parameters
772
773   TString message("\n") ; 
774   
775   if( strcmp(GetName(), "") !=0 ){
776     
777     // Print parameters
778  
779     TString taskName(Version()) ;
780     
781     printf("--------------- "); 
782     printf(taskName.Data()) ; 
783     printf(" "); 
784     printf("Clusterizing digits: "); 
785     printf("\n                       ECA Local Maximum cut    = %f", fECALocMaxCut); 
786     printf("\n                       ECA Logarithmic weight   = %f", fECAW0); 
787     if(fToUnfold)
788       printf("\nUnfolding on\n");
789     else
790       printf("\nUnfolding off\n");
791     
792     printf("------------------------------------------------------------------"); 
793   }
794   else
795     printf("AliEMCALClusterizerv1 not initialized ") ;
796 }
797
798 //____________________________________________________________________________
799 void AliEMCALClusterizerv1::PrintRecPoints(Option_t * option)
800 {
801   // Prints list of RecPoints produced at the current pass of AliEMCALClusterizer
802   if(strstr(option,"deb")) {
803     printf("PrintRecPoints: Clusterization result:") ; 
804   
805     printf("           Found %d ECA Rec Points\n ", 
806          fRecPoints->GetEntriesFast()) ; 
807   }
808
809   if(strstr(option,"all")) {
810     if(strstr(option,"deb")) {
811       printf("\n-----------------------------------------------------------------------\n") ;
812       printf("Clusters in ECAL section\n") ;
813       printf("Index    Ene(GeV) Multi Module     GX    GY   GZ  lX    lY   lZ   Dispersion Lambda 1   Lambda 2  # of prim  Primaries list\n") ;
814     }
815    Int_t index =0;
816
817     for (index = 0 ; index < fRecPoints->GetEntries() ; index++) {
818       AliEMCALRecPoint * rp = dynamic_cast<AliEMCALRecPoint * >(fRecPoints->At(index)) ; 
819       TVector3  globalpos;  
820       //rp->GetGlobalPosition(globalpos);
821       TVector3  localpos;  
822       rp->GetLocalPosition(localpos);
823       Float_t lambda[2]; 
824       rp->GetElipsAxis(lambda);
825       Int_t * primaries; 
826       Int_t nprimaries;
827       primaries = rp->GetPrimaries(nprimaries);
828       if(strstr(option,"deb")) 
829       printf("\n%6d  %8.4f  %3d     %4.1f    %4.1f %4.1f  %4.1f %4.1f %4.1f    %4.1f   %4f  %4f    %2d     : ", 
830              rp->GetIndexInList(), rp->GetEnergy(), rp->GetMultiplicity(),
831              globalpos.X(), globalpos.Y(), globalpos.Z(), localpos.X(), localpos.Y(), localpos.Z(), 
832              rp->GetDispersion(), lambda[0], lambda[1], nprimaries) ; 
833       if(strstr(option,"deb")){ 
834         for (Int_t iprimary=0; iprimary<nprimaries; iprimary++) {
835           printf("%d ", primaries[iprimary] ) ; 
836         }
837       }
838     }
839
840     if(strstr(option,"deb"))
841     printf("\n-----------------------------------------------------------------------\n");
842   }
843 }
844
845 //___________________________________________________________________
846 void  AliEMCALClusterizerv1::PrintRecoInfo()
847 {
848   printf(" AliEMCALClusterizerv1::PrintRecoInfo() : version %s \n", Version() );
849
850 }