]> git.uio.no Git - u/mrichter/AliRoot.git/blob - EMCAL/AliEMCALUnfolding.cxx
184949778945460f896364838557561a6e41b50f
[u/mrichter/AliRoot.git] / EMCAL / AliEMCALUnfolding.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 //_________________________________________________________________________
17 //  Base class for the cluster unfolding algorithm 
18 //*-- Author: Adam Matyja (SUBATECH)
19 //  Based on unfolding in clusterizerv1 done by Cynthia Hadjidakis
20 //-- Unfolding for eta~0: Cynthia Hadjidakis - still in AliEMCALCLusterizerv1
21 //-- Unfolding extension for whole EMCAL: Adam Matyja (SUBATECH & INP PAN)
22 //
23 //  unfolds the clusters having several local maxima. 
24 //////////////////////////////////////////////////////////////////////////////
25
26 // --- ROOT system ---
27 #include "TClonesArray.h"
28 #include <TMath.h> 
29 #include <TMinuit.h>
30
31 // --- Standard library ---
32 #include <cassert>
33
34 // --- AliRoot header files ---
35 #include "AliEMCALUnfolding.h"
36 #include "AliEMCALGeometry.h"
37 #include "AliRunLoader.h"
38 #include "AliRun.h"
39 #include "AliEMCAL.h"
40 #include "AliEMCALRecParam.h"
41 #include "AliEMCALRecPoint.h"
42 #include "AliEMCALDigit.h"
43 #include "AliEMCALReconstructor.h"
44
45 #include "AliLog.h"
46 #include "AliCDBManager.h"
47 class AliCDBStorage;
48 #include "AliCDBEntry.h"
49
50 Double_t AliEMCALUnfolding::fgSSPars[8]={0.9262,3.365,1.548,0.1625,-0.4195,0.,0.,2.332};
51 Double_t AliEMCALUnfolding::fgPar5[3]={12.31,-0.007381,-0.06936};
52 Double_t AliEMCALUnfolding::fgPar6[3]={0.05452,0.0001228,0.001361};
53
54 ClassImp(AliEMCALUnfolding)
55   
56 //____________________________________________________________________________
57 AliEMCALUnfolding::AliEMCALUnfolding():
58   fNumberOfECAClusters(0),
59   fECALocMaxCut(0),
60   fThreshold(0.01),//10 MeV
61   fRejectBelowThreshold(0),//split
62   fGeom(NULL),
63   fRecPoints(NULL),
64   fDigitsArr(NULL)
65 {
66   // ctor with the indication of the file where header Tree and digits Tree are stored
67   Init() ;
68 }
69
70 //____________________________________________________________________________
71 AliEMCALUnfolding::AliEMCALUnfolding(AliEMCALGeometry* geometry):
72   fNumberOfECAClusters(0),
73   fECALocMaxCut(0),
74   fThreshold(0.01),//10 MeV
75   fRejectBelowThreshold(0),//split
76   fGeom(geometry),
77   fRecPoints(NULL),
78   fDigitsArr(NULL)
79 {
80   // ctor with the indication of the file where header Tree and digits Tree are stored
81   // use this contructor to avoid usage of Init() which uses runloader
82   // change needed by HLT - MP
83   if (!fGeom)
84   {
85     AliFatal("AliEMCALUnfolding: Geometry not initialized.");
86   }
87
88 }
89
90 //____________________________________________________________________________
91 AliEMCALUnfolding::AliEMCALUnfolding(AliEMCALGeometry* geometry,Float_t ECALocMaxCut,Double_t *SSPars,Double_t *Par5,Double_t *Par6):
92   fNumberOfECAClusters(0),
93   fECALocMaxCut(ECALocMaxCut),
94   fThreshold(0.01),//10 MeV
95   fRejectBelowThreshold(0),//split
96   fGeom(geometry),
97   fRecPoints(NULL),
98   fDigitsArr(NULL)
99 {
100   // ctor with the indication of the file where header Tree and digits Tree are stored
101   // use this contructor to avoid usage of Init() which uses runloader
102   // change needed by HLT - MP
103   if (!fGeom)
104   {
105     AliFatal("AliEMCALUnfolding: Geometry not initialized.");
106   }
107   Int_t i=0;
108   for (i = 0; i < 8; i++) fgSSPars[i] = SSPars[i];
109   for (i = 0; i < 3; i++) {
110     fgPar5[i] = Par5[i];
111     fgPar6[i] = Par6[i];
112   }
113
114 }
115
116 //____________________________________________________________________________
117 void AliEMCALUnfolding::Init()
118 {
119   // Make all memory allocations which can not be done in default constructor.
120   // Attach the Clusterizer task to the list of EMCAL tasks
121
122   AliRunLoader *rl = AliRunLoader::Instance();
123   if (rl && rl->GetAliRun()){
124     AliEMCAL* emcal = dynamic_cast<AliEMCAL*>(rl->GetAliRun()->GetDetector("EMCAL"));
125     if(emcal)fGeom = emcal->GetGeometry();
126   }
127   
128   if(!fGeom)
129     fGeom =  AliEMCALGeometry::GetInstance(AliEMCALGeometry::GetDefaultGeometryName());
130   
131   AliDebug(1,Form("geom %p",fGeom));
132   
133   if(!gMinuit) 
134     //    gMinuit = new TMinuit(100) ;//the same is in FindFitV2
135     gMinuit = new TMinuit(30) ;//the same is in FindFitV2
136   
137 }
138
139 //____________________________________________________________________________
140   AliEMCALUnfolding::~AliEMCALUnfolding()
141 {
142   // dtor
143 }
144
145 //____________________________________________________________________________
146 void AliEMCALUnfolding::SetInput(Int_t numberOfECAClusters,TObjArray *recPoints,TClonesArray *digitsArr)
147 {
148   //
149   //Set input for unfolding purposes
150   //
151   SetNumberOfECAClusters(numberOfECAClusters);
152   SetRecPoints(recPoints);
153   SetDigitsArr(digitsArr);
154 }
155
156 //____________________________________________________________________________
157 void AliEMCALUnfolding::MakeUnfolding()
158 {
159   // Unfolds clusters using the shape of an ElectroMagnetic shower
160   // Performs unfolding of all clusters
161   
162   AliDebug(4,Form(" V1: total no of clusters %d from %d digits",fNumberOfECAClusters,fDigitsArr->GetEntriesFast()));
163   if(fNumberOfECAClusters > 0){
164     if (fGeom==0)
165       AliFatal("Did not get geometry from EMCALLoader") ;
166     //Int_t nModulesToUnfold = fGeom->GetNCells();
167     
168     Int_t numberOfClustersToUnfold=fNumberOfECAClusters;
169     //we unfold only clusters present in the array untill now
170     //fNumberOfECAClusters may change due to unfilded clusters
171     //so 0 to numberOfClustersToUnfold-1: clusters before unfolding
172     //numberOfClustersToUnfold to the end: new clusters from unfolding
173     //of course numberOfClustersToUnfold also is decreased but we don't loop over clusters added in UF 
174     Int_t index ;
175     for(index = 0 ; index < numberOfClustersToUnfold ; index++){
176       AliEMCALRecPoint * recPoint = dynamic_cast<AliEMCALRecPoint *>( fRecPoints->At(index) ) ;
177       if(recPoint){
178         Int_t nMultipl = recPoint->GetMultiplicity() ;
179         AliEMCALDigit ** maxAt = new AliEMCALDigit*[nMultipl] ;
180         Float_t * maxAtEnergy = new Float_t[nMultipl] ;
181         Int_t nMax = recPoint->GetNumberOfLocalMax(maxAt, maxAtEnergy,fECALocMaxCut,fDigitsArr) ;
182         if( nMax > 1 ) {     // if cluster is very flat (no pronounced maximum) then nMax = 0
183           AliDebug(4,Form("  *** V1+UNFOLD *** Cluster index before UF %d",fNumberOfECAClusters));
184           if(UnfoldClusterV2(recPoint, nMax, maxAt, maxAtEnergy) ){
185             //if unfolding correct remove old recPoint
186             fRecPoints->Remove(recPoint);
187             fRecPoints->Compress() ;//is it really needed
188             index-- ;
189             fNumberOfECAClusters-- ;
190             numberOfClustersToUnfold--;
191           }
192           AliDebug(4,Form("  Cluster index after UF %d",fNumberOfECAClusters));
193         } else{
194           recPoint->SetNExMax(1) ; //Only one local maximum
195         }
196         
197         delete[] maxAt ;
198         delete[] maxAtEnergy ;
199       } else {
200         //AliError("RecPoint NULL"); //end of check if recPoint exist
201         Error("MakeUnfolding", "RecPoint NULL, index = %d, fNumberOfECAClusters = %d, numberOfClustersToUnfold = %d",index,fNumberOfECAClusters,numberOfClustersToUnfold) ;
202       }
203     } // rec point loop
204   }//end of check fNumberOfECAClusters
205   // End of Unfolding of clusters
206
207   AliDebug(4,Form(" V1+UNFOLD: total no of clusters %d from %d digits",fNumberOfECAClusters,fDigitsArr->GetEntriesFast()));
208 //  for(Int_t i=0;i<fNumberOfECAClusters;i++){
209 //    AliEMCALRecPoint * recPoint = dynamic_cast<AliEMCALRecPoint *>(fRecPoints->At(i));
210 //    Int_t nMultipl = recPoint->GetMultiplicity() ;
211 //    Double_t energy=recPoint->GetEnergy();
212 //    Int_t absIdMaxDigit=recPoint->GetAbsIdMaxDigit();
213 //    Int_t sm=recPoint->GetSuperModuleNumber();
214 //    Double_t pointEne=recPoint->GetPointEnergy();
215 //    Float_t maxEne=recPoint->GetMaximalEnergy();
216 //    Int_t maxEneInd=recPoint->GetMaximalEnergyIndex();
217 //    printf("  cluster %d,ncells %d,ene %f,absIdMaxCell %d,sm %d,pointEne %f,maxEne %f,maxEneInd %d\n",i,nMultipl,energy,absIdMaxDigit,sm,pointEne,maxEne,maxEneInd);
218 //  }
219
220 }
221
222 //____________________________________________________________________________
223 Int_t AliEMCALUnfolding::UnfoldOneCluster(AliEMCALRecPoint * iniTower, 
224                                           Int_t nMax, 
225                                           AliEMCALDigit ** maxAt, 
226                                           Float_t * maxAtEnergy,
227                                           TObjArray *list)
228 {
229   // Input one cluster
230   // Output list of clusters
231   // returns number of clusters
232   // if fit failed or unfolding is not applicable returns 0 and empty list
233   
234   //**************************** part 1 *******************************************
235   // Performs the unfolding of a cluster with nMax overlapping showers 
236   
237   //cout<<"unfolding check here part 1"<<endl;
238   AliDebug(5,Form("  Original cluster E %f, nMax = %d",iniTower->GetEnergy(),nMax ));
239
240   Int_t nPar = 3 * nMax ;
241   Float_t * fitparameters = new Float_t[nPar] ;
242   
243   if (fGeom==0)
244     AliFatal("Did not get geometry from EMCALLoader") ;
245   
246   Bool_t rv = FindFitV2(iniTower, maxAt, maxAtEnergy, nPar, fitparameters) ;
247   if( !rv ) 
248   {
249     // Fit failed, return (and remove cluster? - why? I leave the cluster)
250     iniTower->SetNExMax(-1) ;
251     delete[] fitparameters ;
252     return 0;//changed here
253   }
254   
255   //speed up solution for clusters with 2 maxima where one maximum is below threshold fThreshold
256   if(nMax==2){
257     if(fitparameters[2]<fThreshold || fitparameters[5]<fThreshold){
258       AliDebug(1,"One of fitted energy below threshold");
259       iniTower->SetNExMax(1) ;
260       delete[] fitparameters ;
261       return 0;//changed here
262     }
263   }
264
265   //**************************** part 2 *******************************************
266   // create unfolded rec points and fill them with new energy lists
267   // First calculate energy deposited in each sell in accordance with
268   // fit (without fluctuations): efit[]
269   // and later correct this number in acordance with actual energy
270   // deposition
271   
272   //  cout<<"unfolding check here part 2"<<endl;
273   Int_t nDigits = iniTower->GetMultiplicity() ;
274   Float_t * efit = new Float_t[nDigits] ;//new fitted energy in cells
275   Float_t xpar=0.,zpar=0.,epar=0.  ;//center of gravity in cell units
276   
277   AliEMCALDigit * digit = 0 ;
278   Int_t * digitsList = iniTower->GetDigitsList() ;
279   
280   Int_t iSupMod =  0 ;
281   Int_t iTower  =  0 ;
282   Int_t iIphi   =  0 ;
283   Int_t iIeta   =  0 ;
284   Int_t iphi    =  0 ;//x direction
285   Int_t ieta    =  0 ;//z direstion
286   
287   Int_t iparam = 0 ;
288   Int_t iDigit = 0 ;
289   
290   for(iDigit = 0 ; iDigit < nDigits ; iDigit ++)
291   {
292     digit = dynamic_cast<AliEMCALDigit*>( fDigitsArr->At(digitsList[iDigit] ) ) ;
293     if(digit)
294     {
295       fGeom->GetCellIndex(digit->GetId(),iSupMod,iTower,iIphi,iIeta); 
296       fGeom->GetCellPhiEtaIndexInSModule(iSupMod,iTower,
297                                          iIphi, iIeta,iphi,ieta);
298       EvalParsPhiDependence(digit->GetId(),fGeom);
299       
300       efit[iDigit] = 0.;
301       iparam = 0;
302       while(iparam < nPar )
303       {
304         xpar = fitparameters[iparam] ;
305         zpar = fitparameters[iparam+1] ;
306         epar = fitparameters[iparam+2] ;
307
308         efit[iDigit] += epar * ShowerShapeV2((Float_t)iphi - xpar,(Float_t)ieta - zpar) ;
309         iparam += 3 ;
310       }
311
312     } else AliDebug(1,"Digit NULL part 2!");
313     
314   }//digit loop
315   
316   //**************************** part 3 *******************************************
317   // Now create new RecPoints and fill energy lists with efit corrected to fluctuations
318   // so that energy deposited in each cell is distributed between new clusters proportionally
319   // to its contribution to efit
320   
321   Float_t * energiesList = iniTower->GetEnergiesList() ;
322   Float_t ratio = 0. ;
323   Float_t eDigit = 0. ;
324   Int_t nSplittedClusters=(Int_t)nPar/3;
325   
326   Float_t * correctedEnergyList = new Float_t[nDigits*nSplittedClusters];
327   //above - temporary table with energies after unfolding.
328   //the order is following: 
329   //first cluster <first cell - last cell>, 
330   //second cluster <first cell - last cell>, etc.
331   
332   //**************************** sub-part 3.1 *************************************
333   //If not the energy from a given cell in the cluster is divided in correct proportions 
334   //in accordance to the other clusters and added to them and set to 0.
335   
336   //  cout<<"unfolding check here part 3.1"<<endl;
337
338   iparam = 0 ;
339   while(iparam < nPar )
340   {
341     xpar = fitparameters[iparam] ;
342     zpar = fitparameters[iparam+1] ;
343     epar = fitparameters[iparam+2] ;
344     
345     for(iDigit = 0 ; iDigit < nDigits ; iDigit ++)
346     {
347       digit = dynamic_cast<AliEMCALDigit*>( fDigitsArr->At( digitsList[iDigit] ) ) ;
348       if(digit)
349       {
350         fGeom->GetCellIndex(digit->GetId(),iSupMod,iTower,iIphi,iIeta); 
351         fGeom->GetCellPhiEtaIndexInSModule(iSupMod,iTower,
352                                            iIphi, iIeta,iphi,ieta);
353         
354         EvalParsPhiDependence(digit->GetId(),fGeom);
355        
356         if(efit[iDigit]==0) 
357         {//just for sure
358           correctedEnergyList[iparam/3*nDigits+iDigit] = 0.;//correction here
359           continue;
360         }
361         
362         ratio = epar * ShowerShapeV2((Float_t)iphi - xpar,(Float_t)ieta - zpar) / efit[iDigit] ;
363         eDigit = energiesList[iDigit] * ratio ;
364         
365         //add energy to temporary matrix
366         correctedEnergyList[iparam/3*nDigits+iDigit] = eDigit;
367         
368       } else AliDebug(1,"NULL digit part 3");
369     }//digit loop 
370     iparam += 3 ;
371   }//while
372   
373   //**************************** sub-part 3.2 *************************************
374   //here we check if energy of the cell in the cluster after unfolding is above threshold. 
375   //here we correct energy for each cell and cluster
376   //  cout<<"unfolding check here part 3.2"<<endl;
377
378
379   //here we have 3 possibilities
380   //when after UF cell energy in cluster is below threshold:
381   //1 - keep it associated to cluster - equivalent of threshold=0
382   //2 - default - split (or add) energy of that cell into that cell in the other cluster(s)
383   //3 - reject that cell from cluster - fraction energy in cell=0 - breaks energy conservation
384   //Bool_t rejectBelowThreshold=kTRUE;//default option = 2 - split = kFALSE
385
386   if(fThreshold > 0){//option 2 or 3
387     if(fRejectBelowThreshold){//option 3
388       for(iDigit = 0 ; iDigit < nDigits ; iDigit++){//digit loop
389         for(iparam = 0 ; iparam < nPar ; iparam+=3){//param0 loop = energy loop
390           if(correctedEnergyList[iparam/3*nDigits+iDigit] < fThreshold ) correctedEnergyList[iparam/3*nDigits+iDigit]=0.;
391         }
392       }
393     }else{//option 2
394       Float_t maximumEne=0.;
395       Int_t maximumIndex=0;
396       Bool_t isAnyBelowThreshold=kFALSE;
397       //  Float_t Threshold=0.01;
398       Float_t * energyFraction = new Float_t[nSplittedClusters];
399       Int_t iparam2 = 0 ;
400       for(iDigit = 0 ; iDigit < nDigits ; iDigit++){
401         isAnyBelowThreshold=kFALSE;
402         maximumEne=0.;
403         for(iparam = 0 ; iparam < nPar ; iparam+=3){
404           if(correctedEnergyList[iparam/3*nDigits+iDigit] < fThreshold ) isAnyBelowThreshold = kTRUE;
405           if(correctedEnergyList[iparam/3*nDigits+iDigit] > maximumEne) 
406             {
407               maximumEne = correctedEnergyList[iparam/3*nDigits+iDigit];
408               maximumIndex = iparam;
409             }
410         }//end of loop over clusters after unfolding
411         
412         if(!isAnyBelowThreshold) continue; //no cluster-cell below threshold 
413         
414         if(maximumEne < fThreshold) 
415           {//add all cluster cells and put energy into max index, other set to 0
416             maximumEne=0.;
417             for(iparam = 0 ; iparam < nPar ; iparam+=3)
418               {
419                 maximumEne+=correctedEnergyList[iparam/3*nDigits+iDigit];
420                 correctedEnergyList[iparam/3*nDigits+iDigit]=0;
421               }
422             correctedEnergyList[maximumIndex/3*nDigits+iDigit]=maximumEne;
423             continue;
424           }//end if
425         
426         //divide energy of cell below threshold in the correct proportion and add to other cells
427         maximumEne=0.;//not used any more so use it for the energy sum 
428         for(iparam = 0 ; iparam < nPar ; iparam+=3)
429           {//calculate energy sum
430             if(correctedEnergyList[iparam/3*nDigits+iDigit] < fThreshold) energyFraction[iparam/3]=0;
431             else 
432               {
433                 energyFraction[iparam/3]=1.;
434                 maximumEne+=correctedEnergyList[iparam/3*nDigits+iDigit];
435               }
436           }//end of loop over clusters after unfolding
437         if(maximumEne>0.) {
438           for(iparam = 0 ; iparam < nPar ; iparam+=3){//calculate fraction
439             energyFraction[iparam/3] = energyFraction[iparam/3] * correctedEnergyList[iparam/3*nDigits+iDigit] / maximumEne;
440           }
441           
442           for(iparam = 0 ; iparam < nPar ; iparam+=3)
443             {//add energy from cells below threshold to others
444               if(energyFraction[iparam/3]>0.) continue;
445               else
446                 {
447                   for(iparam2 = 0 ; iparam2 < nPar ; iparam2+=3)
448                     {
449                       correctedEnergyList[iparam2/3*nDigits+iDigit] += (energyFraction[iparam2/3] * 
450                                                                         correctedEnergyList[iparam/3*nDigits+iDigit]) ;
451                     }//inner loop
452                   correctedEnergyList[iparam/3*nDigits+iDigit] = 0.;
453                 }
454             }
455         } else {
456           //digit energy to be set to 0
457           for(iparam = 0 ; iparam < nPar ; iparam+=3)
458             {
459               correctedEnergyList[iparam/3*nDigits+iDigit] = 0.;
460             }
461         }//correction for: is energy>0
462         
463       }//end of loop over digits
464       delete[] energyFraction;
465       
466     }//end of option 2 or 3 
467   } else {//option 1
468     //do nothing
469   }
470
471   
472   //**************************** sub-part 3.3 *************************************
473   //here we add digits to recpoints with corrected energy
474   //  cout<<"unfolding check here part 3.3"<<endl;
475
476   Int_t newClusterIndex=0;
477   iparam = 0 ;
478   while(iparam < nPar )
479   {
480     AliEMCALRecPoint * recPoint = 0 ;
481     
482     if(nSplittedClusters >= list->GetSize())
483       list->Expand(nSplittedClusters);
484     
485     //add recpoint
486     (*list)[newClusterIndex] = new AliEMCALRecPoint("") ;
487     recPoint = dynamic_cast<AliEMCALRecPoint *>( list->At(newClusterIndex) ) ;
488     
489     if(recPoint){//recPoint present -> good
490       recPoint->SetNExMax(nSplittedClusters) ;//can be wrong number, to be corrected in outer method
491       
492       for(iDigit = 0 ; iDigit < nDigits ; iDigit ++) {
493         digit = dynamic_cast<AliEMCALDigit*>( fDigitsArr->At( digitsList[iDigit] ) ) ;
494         if(digit && correctedEnergyList[iparam/3*nDigits+iDigit]>0. ){
495           //if(correctedEnergyList[iparam/3*nDigits+iDigit]<fThreshold) printf("Final E cell %f < %f\n",correctedEnergyList[iparam/3*nDigits+iDigit],fThreshold);
496           recPoint->AddDigit( *digit, correctedEnergyList[iparam/3*nDigits+iDigit], kFALSE ) ; //FIXME, need to study the shared case
497         } else {
498           AliDebug(1,Form("NULL digit part3.3 or NULL energy=%f",correctedEnergyList[iparam/3*nDigits+iDigit]));
499         }
500       }//digit loop
501
502       if(recPoint->GetMultiplicity()==0){//recpoint exists but no digits associated -> remove from list
503         delete (*list)[newClusterIndex];
504         list->RemoveAt(newClusterIndex);
505         nSplittedClusters--;
506         newClusterIndex--;//decrease cluster number
507       }else {//recPoint exists and has digits associated -> very good increase number of clusters 
508         AliDebug(5,Form("cluster %d, digit no %d, energy %f",iparam/3,(recPoint->GetDigitsList())[0],(recPoint->GetEnergiesList())[0]));
509       }
510       
511     } else {//recPoint empty -> remove from list
512       AliError("NULL RecPoint");
513       //protection from recpoint with no digits
514       delete (*list)[newClusterIndex];
515       list->RemoveAt(newClusterIndex);
516       nSplittedClusters--;
517       newClusterIndex--;//decrease cluster number
518     }
519
520     iparam += 3 ;
521     newClusterIndex++;
522   }//while
523   
524   delete[] fitparameters ;
525   delete[] efit ;
526   delete[] correctedEnergyList ;
527
528 //  print 
529   AliDebug(5,Form("  nSplittedClusters %d, fNumberOfECAClusters %d, newClusterIndex %d,list->Entries() %d\n",nSplittedClusters,fNumberOfECAClusters,newClusterIndex,list->GetEntriesFast() ));
530   
531   //  cout<<"end of unfolding check part 3.3"<<endl;
532   return nSplittedClusters;
533 }
534
535 //____________________________________________________________________________
536 Bool_t AliEMCALUnfolding::UnfoldClusterV2(AliEMCALRecPoint * iniTower, 
537                                           Int_t nMax, 
538                                           AliEMCALDigit ** maxAt, 
539                                           Float_t * maxAtEnergy)
540 {
541   // Extended to whole EMCAL 
542   // Performs the unfolding of a cluster with nMax overlapping showers 
543   // Returns true if success (1->several clusters), otherwise false (fit failed)
544
545   TObjArray *list =new TObjArray(2);//temporary object
546   Int_t nUnfoldedClusters=UnfoldOneCluster(iniTower,nMax,maxAt,maxAtEnergy,list);
547
548   // here we write new clusters from list to fRecPoints 
549   AliDebug(5,Form("Number of clusters after unfolding %d",list->GetEntriesFast()));
550   Int_t iDigit=0;
551   AliEMCALDigit * digit = 0 ;
552   for(Int_t i=0;i<list->GetEntriesFast();i++) {
553     AliEMCALRecPoint * recPoint = 0 ;
554     
555     if(fNumberOfECAClusters >= fRecPoints->GetSize())
556       fRecPoints->Expand(2*fNumberOfECAClusters) ;
557     
558     //add recpoint
559     (*fRecPoints)[fNumberOfECAClusters] = new AliEMCALRecPoint("") ;//fNumberOfECAClusters-1 is old cluster before unfolding
560     recPoint = dynamic_cast<AliEMCALRecPoint *>( fRecPoints->At(fNumberOfECAClusters) ) ;
561     if(recPoint){//recPoint present -> good
562       recPoint->SetNExMax(list->GetEntriesFast()) ;
563       Int_t *digitsList = dynamic_cast<AliEMCALRecPoint *>(list->At(i))->GetDigitsList();
564       Float_t *energyList = dynamic_cast<AliEMCALRecPoint *>(list->At(i))->GetEnergiesList();
565
566       AliDebug(5,Form("cluster %d, digit no %d, energy %f\n",i,digitsList[0],energyList[0]));
567
568       for(iDigit = 0 ; iDigit < dynamic_cast<AliEMCALRecPoint *>(list->At(i))->GetMultiplicity(); iDigit ++) {
569         digit = dynamic_cast<AliEMCALDigit*>( fDigitsArr->At( digitsList[iDigit] ) ) ;
570         recPoint->AddDigit( *digit, energyList[iDigit], kFALSE ) ; //FIXME, need to study the shared case
571       }//digit loop
572       fNumberOfECAClusters++ ; 
573     } else {//recPoint empty -> remove from list
574       AliError("NULL RecPoint");
575       delete (*fRecPoints)[fNumberOfECAClusters];
576       fRecPoints->RemoveAt(fNumberOfECAClusters);
577     }
578
579   }//loop over unfolded clusters
580   
581   //print energy of new unfolded clusters
582   AliDebug(5,Form("  nUnfoldedClusters %d, fNumberOfECAClusters %d",nUnfoldedClusters,fNumberOfECAClusters ));
583   for(Int_t inewclus=0; inewclus<nUnfoldedClusters;inewclus++){
584     AliDebug(5,Form("  Unfolded cluster %d E %f",inewclus,dynamic_cast<AliEMCALRecPoint *>(fRecPoints->At(fNumberOfECAClusters-1-inewclus)) ->GetEnergy() ));
585   }
586
587   //clear tables  
588   list->SetOwner(kTRUE);
589   list->Delete();
590   delete list;
591   if(nUnfoldedClusters>1) return kTRUE;
592   return kFALSE;
593 }
594
595
596
597 //____________________________________________________________________________
598 Bool_t AliEMCALUnfolding::UnfoldClusterV2old(AliEMCALRecPoint * iniTower, 
599                                           Int_t nMax, 
600                                           AliEMCALDigit ** maxAt, 
601                                           Float_t * maxAtEnergy)
602 {
603   // Extended to whole EMCAL 
604   // Performs the unfolding of a cluster with nMax overlapping showers 
605   
606   Int_t nPar = 3 * nMax ;
607   Float_t * fitparameters = new Float_t[nPar] ;
608   
609   if (fGeom==0)
610     AliFatal("Did not get geometry from EMCALLoader") ;
611   
612   Bool_t rv = FindFitV2(iniTower, maxAt, maxAtEnergy, nPar, fitparameters) ;
613   if( !rv ) {
614     // Fit failed, return (and remove cluster? - why? I leave the cluster)
615     iniTower->SetNExMax(-1) ;
616     delete[] fitparameters ;
617     return kFALSE;
618   }
619   
620   // create unfolded rec points and fill them with new energy lists
621   // First calculate energy deposited in each sell in accordance with
622   // fit (without fluctuations): efit[]
623   // and later correct this number in acordance with actual energy
624   // deposition
625   
626   Int_t nDigits = iniTower->GetMultiplicity() ;
627   Float_t * efit = new Float_t[nDigits] ;//new fitted energy in cells
628   Float_t xpar=0.,zpar=0.,epar=0.  ;//center of gravity in cell units
629   
630   AliEMCALDigit * digit = 0 ;
631   Int_t * digitsList = iniTower->GetDigitsList() ;
632   
633   Int_t iSupMod =  0 ;
634   Int_t iTower  =  0 ;
635   Int_t iIphi   =  0 ;
636   Int_t iIeta   =  0 ;
637   Int_t iphi    =  0 ;//x direction
638   Int_t ieta    =  0 ;//z direstion
639   
640   Int_t iparam = 0 ;
641   Int_t iDigit = 0 ;
642   
643   for(iDigit = 0 ; iDigit < nDigits ; iDigit ++){
644     digit = dynamic_cast<AliEMCALDigit*>( fDigitsArr->At(digitsList[iDigit] ) ) ;
645     if(digit){
646       fGeom->GetCellIndex(digit->GetId(),iSupMod,iTower,iIphi,iIeta); 
647       fGeom->GetCellPhiEtaIndexInSModule(iSupMod,iTower,
648                                          iIphi, iIeta,iphi,ieta);
649       EvalParsPhiDependence(digit->GetId(),fGeom);
650       
651       efit[iDigit] = 0.;
652       iparam = 0;
653       while(iparam < nPar ){
654         xpar = fitparameters[iparam] ;
655         zpar = fitparameters[iparam+1] ;
656         epar = fitparameters[iparam+2] ;
657         iparam += 3 ;
658         
659         efit[iDigit] += epar * ShowerShapeV2((Float_t)iphi - xpar,(Float_t)ieta - zpar) ;
660       }
661     } else AliError("Digit NULL!");
662     
663   }//digit loop
664   
665   // Now create new RecPoints and fill energy lists with efit corrected to fluctuations
666   // so that energy deposited in each cell is distributed between new clusters proportionally
667   // to its contribution to efit
668   
669   Float_t * energiesList = iniTower->GetEnergiesList() ;
670   Float_t ratio = 0 ;
671   
672   iparam = 0 ;
673   while(iparam < nPar ){
674     xpar = fitparameters[iparam] ;
675     zpar = fitparameters[iparam+1] ;
676     epar = fitparameters[iparam+2] ;
677     iparam += 3 ;
678     
679     AliEMCALRecPoint * recPoint = 0 ;
680     
681     if(fNumberOfECAClusters >= fRecPoints->GetSize())
682       fRecPoints->Expand(2*fNumberOfECAClusters) ;
683     
684     //add recpoint
685     (*fRecPoints)[fNumberOfECAClusters] = new AliEMCALRecPoint("") ;
686     recPoint = dynamic_cast<AliEMCALRecPoint *>( fRecPoints->At(fNumberOfECAClusters) ) ;
687     
688     if(recPoint){
689       
690       fNumberOfECAClusters++ ;
691       recPoint->SetNExMax((Int_t)nPar/3) ;
692       
693       Float_t eDigit = 0. ;
694       for(iDigit = 0 ; iDigit < nDigits ; iDigit ++){
695         digit = dynamic_cast<AliEMCALDigit*>( fDigitsArr->At( digitsList[iDigit] ) ) ;
696         if(digit){
697           fGeom->GetCellIndex(digit->GetId(),iSupMod,iTower,iIphi,iIeta); 
698           fGeom->GetCellPhiEtaIndexInSModule(iSupMod,iTower,
699                                              iIphi, iIeta,iphi,ieta);
700           EvalParsPhiDependence(digit->GetId(),fGeom);
701           if(efit[iDigit]==0) continue;//just for sure
702           ratio = epar * ShowerShapeV2((Float_t)iphi - xpar,(Float_t)ieta - zpar) / efit[iDigit] ;
703           eDigit = energiesList[iDigit] * ratio ;
704           recPoint->AddDigit( *digit, eDigit, kFALSE ) ; //FIXME, need to study the shared case
705         } else AliError("NULL digit");
706       }//digit loop 
707     } else AliError("NULL RecPoint");
708   }//while
709   
710   delete[] fitparameters ;
711   delete[] efit ;
712   
713   return kTRUE;
714 }
715
716
717 //____________________________________________________________________________
718 Bool_t AliEMCALUnfolding::FindFitV2(AliEMCALRecPoint * recPoint, AliEMCALDigit ** maxAt, 
719                                         const Float_t* maxAtEnergy,
720                                         Int_t nPar, Float_t * fitparameters) const
721 {
722   // Calls TMinuit to fit the energy distribution of a cluster with several maxima
723   // The initial values for fitting procedure are set equal to the
724   // positions of local maxima.       
725   // Cluster will be fitted as a superposition of nPar/3
726   // electromagnetic showers
727
728   if (fGeom==0) AliFatal("Did not get geometry from EMCALLoader");
729         
730   if(!gMinuit){
731     //    gMinuit = new TMinuit(100) ;//max 100 parameters
732     if(nPar<30) gMinuit = new TMinuit(30);
733     else gMinuit = new TMinuit(nPar) ;//max nPar parameters
734     //
735   } else {
736     if(gMinuit->fMaxpar < nPar) {
737       delete gMinuit;
738       gMinuit = new TMinuit(nPar);
739     }
740   }
741
742   gMinuit->mncler();                     // Reset Minuit's list of paramters
743   gMinuit->SetPrintLevel(-1) ;           // No Printout
744   gMinuit->SetFCN(AliEMCALUnfolding::UnfoldingChiSquareV2) ;
745   // To set the address of the minimization function
746   TList * toMinuit = new TList();
747   toMinuit->AddAt(recPoint,0) ;
748   toMinuit->AddAt(fDigitsArr,1) ;
749   toMinuit->AddAt(fGeom,2) ;
750
751   gMinuit->SetObjectFit(toMinuit) ;         // To tranfer pointer to UnfoldingChiSquare
752
753   // filling initial values for fit parameters
754   AliEMCALDigit * digit ;
755
756   Int_t ierflg  = 0;
757   Int_t index   = 0 ;
758   Int_t nDigits = (Int_t) nPar / 3 ;
759
760   Int_t iDigit ;
761
762   Int_t iSupMod =  0 ;
763   Int_t iTower  =  0 ;
764   Int_t iIphi   =  0 ;
765   Int_t iIeta   =  0 ;
766   Int_t iphi    =  0 ;//x direction
767   Int_t ieta    =  0 ;//z direstion
768
769   for(iDigit = 0; iDigit < nDigits; iDigit++){
770     digit = maxAt[iDigit];
771     if(digit==0) AliError("energy of digit = 0!");
772     fGeom->GetCellIndex(digit->GetId(),iSupMod,iTower,iIphi,iIeta); 
773     fGeom->GetCellPhiEtaIndexInSModule(iSupMod,iTower,
774                                        iIphi, iIeta,iphi,ieta);
775
776     Float_t energy = maxAtEnergy[iDigit] ;
777
778     //gMinuit->mnparm(index, "x",  iphi, 0.1, 0, 0, ierflg) ;//original
779     gMinuit->mnparm(index, "x",  iphi, 0.05, 0, 0, ierflg) ;
780     index++ ;
781     if(ierflg != 0){
782       Error("FindFit", "EMCAL Unfolding unable to set initial value for fit procedure: x=%d, param.id=%d, nMaxima=%d",iphi,index-1,nPar/3 ) ;
783       toMinuit->Clear();
784       delete toMinuit ;
785       return kFALSE;
786     }
787     //gMinuit->mnparm(index, "z",  ieta, 0.1, 0, 0, ierflg) ;//original
788     gMinuit->mnparm(index, "z",  ieta, 0.05, 0, 0, ierflg) ;
789     index++ ;
790     if(ierflg != 0){
791       Error("FindFit", "EMCAL Unfolding unable to set initial value for fit procedure: z=%d, param.id=%d, nMaxima=%d", ieta, index-1,nPar/3) ;
792       toMinuit->Clear();
793       delete toMinuit ;
794       return kFALSE;
795     }
796     //gMinuit->mnparm(index, "Energy",  energy , 0.05*energy, 0., 4.*energy, ierflg) ;//original
797     gMinuit->mnparm(index, "Energy",  energy , 0.001*energy, 0., 5.*energy, ierflg) ;//was 0.05
798     index++ ;
799     if(ierflg != 0){
800       Error("FindFit", "EMCAL Unfolding unable to set initial value for fit procedure: energy = %f, param.id=%d, nMaxima=%d", energy, index-1, nPar/3) ;
801       toMinuit->Clear();
802       delete toMinuit ;
803       return kFALSE;
804     }
805   }
806
807   Double_t p0 = 0.1 ; // "Tolerance" Evaluation stops when EDM = 0.0001*p0 ; 
808                       // The number of function call slightly depends on it.
809   //  Double_t p1 = 1.0 ;// par to gradient 
810   Double_t p2 = 0.0 ;
811   //  Double_t p3 = 3.0 ;
812   gMinuit->mnexcm("SET STR", &p2, 0, ierflg) ;   // force TMinuit to reduce function calls
813   //  gMinuit->mnexcm("SET GRA", &p1, 1, ierflg) ;   // force TMinuit to use my gradient
814   gMinuit->SetMaxIterations(5);//was 5
815   gMinuit->mnexcm("SET NOW", &p2 , 0, ierflg) ;  // No Warnings
816   //gMinuit->mnexcm("SET PRI", &p3 , 3, ierflg) ;  // printouts
817
818   gMinuit->mnexcm("MIGRAD", &p0, 0, ierflg) ;    // minimize
819   //gMinuit->mnexcm("MINI", &p0, 0, ierflg) ;    // minimize
820   if(ierflg == 4){  // Minimum not found
821     AliDebug(1,"EMCAL Unfolding  Fit not converged, cluster abandoned " ) ;
822     toMinuit->Clear();
823     delete toMinuit ;
824     return kFALSE ;
825   }
826   for(index = 0; index < nPar; index++){
827     Double_t err = 0. ;
828     Double_t val = 0. ;
829     gMinuit->GetParameter(index, val, err) ;    // Returns value and error ofOA parameter index
830     fitparameters[index] = val ;
831   }
832
833   toMinuit->Clear();
834   delete toMinuit ;
835
836   if(gMinuit->fMaxpar>30) delete gMinuit;
837
838   return kTRUE;
839
840 }
841
842 //____________________________________________________________________________
843 Double_t  AliEMCALUnfolding::ShowerShapeV2(Double_t x, Double_t y)
844
845   // extended to whole EMCAL 
846   // Shape of the shower
847   // If you change this function, change also the gradient evaluation in ChiSquare()
848
849   Double_t r = fgSSPars[7]*TMath::Sqrt(x*x+y*y);
850   Double_t rp1  = TMath::Power(r, fgSSPars[1]) ;
851   Double_t rp5  = TMath::Power(r, fgSSPars[5]) ;
852   Double_t shape = fgSSPars[0]*TMath::Exp( -rp1 * (1. / (fgSSPars[2] + fgSSPars[3] * rp1) + fgSSPars[4] / (1 + fgSSPars[6] * rp5) ) ) ;
853   return shape ;
854 }
855
856 //____________________________________________________________________________
857 void AliEMCALUnfolding::UnfoldingChiSquareV2(Int_t & nPar, Double_t * Grad,
858                                              Double_t & fret,
859                                              Double_t * x, Int_t iflag)
860 {
861   // Calculates the Chi square for the cluster unfolding minimization
862   // Number of parameters, Gradient, Chi squared, parameters, what to do
863   
864   TList * toMinuit = dynamic_cast<TList*>( gMinuit->GetObjectFit() ) ;
865   if(toMinuit){
866     AliEMCALRecPoint * recPoint = dynamic_cast<AliEMCALRecPoint*>( toMinuit->At(0) )  ;
867     TClonesArray * digits = dynamic_cast<TClonesArray*>( toMinuit->At(1) )  ;
868     // A bit buggy way to get an access to the geometry
869     // To be revised!
870     AliEMCALGeometry *geom = dynamic_cast<AliEMCALGeometry *>(toMinuit->At(2));
871     
872     if(recPoint && digits && geom){
873       
874       Int_t * digitsList     = recPoint->GetDigitsList() ;
875       
876       Int_t nOdigits = recPoint->GetDigitsMultiplicity() ;
877       
878       Float_t * energiesList = recPoint->GetEnergiesList() ;
879       
880       fret = 0. ;
881       Int_t iparam = 0 ;
882       
883       if(iflag == 2)
884         for(iparam = 0 ; iparam < nPar ; iparam++)
885           Grad[iparam] = 0 ; // Will evaluate gradient
886       
887       Double_t efit = 0. ;
888       
889       AliEMCALDigit * digit ;
890       Int_t iDigit ;
891       
892       Int_t iSupMod =  0 ;
893       Int_t iTower  =  0 ;
894       Int_t iIphi   =  0 ;
895       Int_t iIeta   =  0 ;
896       Int_t iphi    =  0 ;//x direction
897       Int_t ieta    =  0 ;//z direstion
898       
899       
900       for( iDigit = 0 ; iDigit < nOdigits ; iDigit++) {
901         if(energiesList[iDigit]==0) continue;
902         
903         digit = dynamic_cast<AliEMCALDigit*>( digits->At( digitsList[iDigit] ) );
904         
905         if(digit){
906           geom->GetCellIndex(digit->GetId(),iSupMod,iTower,iIphi,iIeta); 
907           geom->GetCellPhiEtaIndexInSModule(iSupMod,iTower,
908                                             iIphi, iIeta,iphi,ieta);
909           EvalParsPhiDependence(digit->GetId(),geom);
910           
911           if(iflag == 2){  // calculate gradient
912             Int_t iParam = 0 ;
913             efit = 0. ;
914             while(iParam < nPar ){
915               Double_t dx = ((Float_t)iphi - x[iParam]) ;
916               iParam++ ;
917               Double_t dz = ((Float_t)ieta - x[iParam]) ;
918               iParam++ ;
919               efit += x[iParam] * ShowerShapeV2(dx,dz) ;
920               iParam++ ;
921             }
922             
923             Double_t sum = 2. * (efit - energiesList[iDigit]) / energiesList[iDigit] ; // Here we assume, that sigma = sqrt(E)
924             iParam = 0 ;
925             while(iParam < nPar ){
926               Double_t xpar = x[iParam] ;
927               Double_t zpar = x[iParam+1] ;
928               Double_t epar = x[iParam+2] ;
929               
930               Double_t dr = fgSSPars[7]*TMath::Sqrt( ((Float_t)iphi - xpar) * ((Float_t)iphi - xpar) + ((Float_t)ieta - zpar) * ((Float_t)ieta - zpar) );
931               Double_t shape = sum * ShowerShapeV2((Float_t)iphi - xpar,(Float_t)ieta - zpar) ;
932               Double_t rp1  = TMath::Power(dr, fgSSPars[1]) ;
933               Double_t rp5  = TMath::Power(dr, fgSSPars[5]) ;
934               
935               Double_t deriv = -2 * TMath::Power(dr,fgSSPars[1]-2.) * fgSSPars[7] * fgSSPars[7] * 
936                 (fgSSPars[1] * ( 1/(fgSSPars[2]+fgSSPars[3]*rp1) + fgSSPars[4]/(1+fgSSPars[6]*rp5) ) - 
937                  (fgSSPars[1]*fgSSPars[3]*rp1/( (fgSSPars[2]+fgSSPars[3]*rp1)*(fgSSPars[2]+fgSSPars[3]*rp1) ) + 
938                   fgSSPars[4]*fgSSPars[5]*fgSSPars[6]*rp5/( (1+fgSSPars[6]*rp5)*(1+fgSSPars[6]*rp5) ) ) );
939               
940               //Double_t deriv =-1.33 * TMath::Power(dr,0.33)*dr * ( 1.57 / ( (1.57 + 0.0860 * r133) * (1.57 + 0.0860 * r133) )
941               //                                                   - 0.55 / (1 + 0.000563 * r669) / ( (1 + 0.000563 * r669) * (1 + 0.000563 * r669) ) ) ;
942               
943               Grad[iParam] += epar * shape * deriv * ((Float_t)iphi - xpar) ;  // Derivative over x
944               iParam++ ;
945               Grad[iParam] += epar * shape * deriv * ((Float_t)ieta - zpar) ;  // Derivative over z
946               iParam++ ;
947               Grad[iParam] += shape ;                                  // Derivative over energy
948               iParam++ ;
949             }
950           }
951           efit = 0;
952           iparam = 0 ;
953           
954           while(iparam < nPar ){
955             Double_t xpar = x[iparam] ;
956             Double_t zpar = x[iparam+1] ;
957             Double_t epar = x[iparam+2] ;
958             iparam += 3 ;
959             efit += epar * ShowerShapeV2((Float_t)iphi - xpar,(Float_t)ieta - zpar) ;
960           }
961           
962           fret += (efit-energiesList[iDigit])*(efit-energiesList[iDigit])/energiesList[iDigit] ;
963           // Here we assume, that sigma = sqrt(E) 
964         } else printf("AliEMCALUnfoding::UnfoldingChiSquareV2 - NULL digit!, nPar %d \n", nPar); // put nPar here to cheat coverity and rule checker
965       } // digit loop
966     } // recpoint, digits and geom not NULL
967   }// List is not NULL
968   
969 }
970
971
972 //____________________________________________________________________________
973 void AliEMCALUnfolding::SetShowerShapeParams(Double_t *pars){
974   for(UInt_t i=0;i<7;++i)
975     fgSSPars[i]=pars[i];
976   if(pars[2]==0. && pars[3]==0.) fgSSPars[2]=1.;//to avoid dividing by 0
977 }
978
979 //____________________________________________________________________________
980 void AliEMCALUnfolding::SetPar5(Double_t *pars){
981   for(UInt_t i=0;i<3;++i)
982     fgPar5[i]=pars[i];
983 }
984
985 //____________________________________________________________________________
986 void AliEMCALUnfolding::SetPar6(Double_t *pars){
987   for(UInt_t i=0;i<3;++i)
988     fgPar6[i]=pars[i];
989 }
990
991 //____________________________________________________________________________
992 void AliEMCALUnfolding::EvalPar5(Double_t phi){
993   //
994   //Evaluate the 5th parameter of the shower shape function
995   //phi in degrees range (-10,10)
996   //
997   //fSSPars[5] = 12.31 - phi*0.007381 - phi*phi*0.06936;
998   fgSSPars[5] = fgPar5[0] + phi * fgPar5[1] + phi*phi * fgPar5[2];
999 }
1000
1001 //____________________________________________________________________________
1002 void AliEMCALUnfolding::EvalPar6(Double_t phi){
1003   //
1004   //Evaluate the 6th parameter of the shower shape function
1005   //phi in degrees range (-10,10)
1006   //
1007   //fSSPars[6] = 0.05452 + phi*0.0001228 + phi*phi*0.001361;
1008   fgSSPars[6] = fgPar6[0] + phi * fgPar6[1] + phi*phi * fgPar6[2];
1009 }
1010
1011 //____________________________________________________________________________
1012 void AliEMCALUnfolding::EvalParsPhiDependence(Int_t absId, const AliEMCALGeometry *geom){
1013   //
1014   // calculate params p5 and p6 depending on the phi angle in global coordinate
1015   // for the cell with given absId index
1016   //
1017   Double_t etaGlob = 0.;//eta in global c.s. - unused
1018   Double_t phiGlob = 0.;//phi in global c.s. in radians
1019   geom->EtaPhiFromIndex(absId, etaGlob, phiGlob);
1020   phiGlob*=180./TMath::Pi();
1021   phiGlob-=90.;
1022   phiGlob-= (Double_t)((Int_t)geom->GetSuperModuleNumber(absId)/2 * 20);
1023
1024   EvalPar5(phiGlob);
1025   EvalPar6(phiGlob);
1026 }
1027