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