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