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