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