]> git.uio.no Git - u/mrichter/AliRoot.git/blob - EMCAL/AliEMCALReconstructor.cxx
Move data member fFixTau from AliCaloRawAnalyzerFitter to the mother class
[u/mrichter/AliRoot.git] / EMCAL / AliEMCALReconstructor.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 //_________________________________________________________________________
19 //--
20 //-- Yves Schutz (SUBATECH) 
21 // Reconstruction class. Redesigned from the old AliReconstructionner class and 
22 // derived from STEER/AliReconstructor. 
23 // 
24
25
26 // --- ROOT system ---
27 #include <TClonesArray.h>
28 #include "TGeoManager.h"
29 #include "TGeoMatrix.h"
30
31 // --- Standard library ---
32
33 // --- AliRoot header files ---
34 #include "AliEMCALReconstructor.h"
35
36 #include "AliCodeTimer.h"
37 #include "AliCaloCalibPedestal.h"
38 #include "AliEMCALCalibData.h"
39 #include "AliESDEvent.h"
40 #include "AliESDCaloCluster.h"
41 #include "AliESDCaloCells.h"
42 #include "AliESDtrack.h"
43 #include "AliEMCALLoader.h"
44 #include "AliEMCALRawUtils.h"
45 #include "AliEMCALDigit.h"
46 #include "AliEMCALClusterizerv1.h"
47 #include "AliEMCALClusterizerv2.h"
48 #include "AliEMCALClusterizerNxN.h"
49 #include "AliEMCALRecPoint.h"
50 #include "AliEMCALPID.h"
51 #include "AliEMCALRecoUtils.h"
52 #include "AliRawReader.h"
53 #include "AliCDBEntry.h"
54 #include "AliCDBManager.h"
55 #include "AliEMCALGeometry.h"
56 #include "AliEMCAL.h"
57 #include "AliESDVZERO.h"
58 #include "AliCDBManager.h"
59 #include "AliRunLoader.h"
60 #include "AliRun.h"
61 #include "AliEMCALTriggerData.h"
62 #include "AliEMCALTriggerElectronics.h"
63 #include "AliEMCALTriggerDCSConfigDB.h"
64 #include "AliEMCALTriggerDCSConfig.h"
65 #include "AliEMCALTriggerData.h"
66 #include "AliEMCALTriggerRawDigit.h"
67 #include "AliEMCALTriggerPatch.h"
68 #include "AliEMCALTriggerTypes.h"
69
70 ClassImp(AliEMCALReconstructor) 
71   
72 const AliEMCALRecParam*     AliEMCALReconstructor::fgkRecParam        = 0;   // EMCAL rec. parameters
73 AliEMCALRawUtils*           AliEMCALReconstructor::fgRawUtils         = 0;   // EMCAL raw utilities class
74 AliEMCALClusterizer*        AliEMCALReconstructor::fgClusterizer      = 0;   // EMCAL clusterizer class
75 TClonesArray*               AliEMCALReconstructor::fgDigitsArr        = 0;   // list of digits, to be used multiple times
76 TObjArray*                  AliEMCALReconstructor::fgClustersArr      = 0;   // list of clusters, to be used multiple times
77 TClonesArray*               AliEMCALReconstructor::fgTriggerDigits    = 0;   // list of trigger digits, to be used multiple times
78 AliEMCALTriggerElectronics* AliEMCALReconstructor::fgTriggerProcessor = 0x0;
79 //____________________________________________________________________________
80 AliEMCALReconstructor::AliEMCALReconstructor() 
81   : fGeom(0),fCalibData(0),fPedestalData(0),fTriggerData(0x0), fMatches(0x0)
82 {
83   // ctor
84
85   // AliDebug(2, "Mark.");  
86
87   fgRawUtils = new AliEMCALRawUtils;
88   
89   //To make sure we match with the geometry in a simulation file,
90   //let's try to get it first.  If not, take the default geometry
91   AliRunLoader *rl = AliRunLoader::Instance();
92   if (rl->GetAliRun()){
93     AliEMCAL * emcal = dynamic_cast<AliEMCAL*>(rl->GetAliRun()->GetDetector("EMCAL"));
94     if(emcal) fGeom = emcal->GetGeometry();
95   }
96   
97   if(!fGeom) {
98     AliInfo(Form("Using default geometry in reconstruction"));
99     fGeom =  AliEMCALGeometry::GetInstance(AliEMCALGeometry::GetDefaultGeometryName());
100   }
101   
102   //Get calibration parameters  
103   if(!fCalibData)
104     {
105       AliCDBEntry *entry = (AliCDBEntry*) 
106       AliCDBManager::Instance()->Get("EMCAL/Calib/Data");
107       if (entry) fCalibData =  (AliEMCALCalibData*) entry->GetObject();
108     }
109   
110   if(!fCalibData)
111     AliFatal("Calibration parameters not found in CDB!");
112   
113   //Get calibration parameters  
114   if(!fPedestalData)
115     {
116       AliCDBEntry *entry = (AliCDBEntry*) 
117       AliCDBManager::Instance()->Get("EMCAL/Calib/Pedestals");
118       if (entry) fPedestalData =  (AliCaloCalibPedestal*) entry->GetObject();
119     }
120   
121   if(!fPedestalData)
122     AliFatal("Dead map not found in CDB!");
123   
124   if(!fGeom) AliFatal(Form("Could not get geometry!"));
125   
126   AliEMCALTriggerDCSConfigDB* dcsConfigDB = AliEMCALTriggerDCSConfigDB::Instance();
127   
128   const AliEMCALTriggerDCSConfig* dcsConfig = dcsConfigDB->GetTriggerDCSConfig();
129   
130   if (!dcsConfig) AliFatal("No Trigger DCS Configuration from OCDB!");
131   fgTriggerProcessor = new AliEMCALTriggerElectronics( dcsConfig );
132   
133   fTriggerData = new AliEMCALTriggerData();
134   
135   //Init temporary list of digits
136   fgDigitsArr     = new TClonesArray("AliEMCALDigit",1000);
137   fgClustersArr   = new TObjArray(1000);
138
139   const int kNTRU = fGeom->GetNTotalTRU();
140   fgTriggerDigits = new TClonesArray("AliEMCALTriggerRawDigit", kNTRU * 96);    
141         
142   //Track matching
143   fMatches = new TList();
144   fMatches->SetOwner(kTRUE);
145
146
147 //____________________________________________________________________________
148 AliEMCALReconstructor::~AliEMCALReconstructor()
149 {
150   // dtor
151
152   //AliDebug(2, "Mark.");
153
154   if(fGeom)              delete fGeom;
155   
156   //No need to delete, recovered from OCDB
157   //if(fCalibData)         delete fCalibData;
158   //if(fPedestalData)      delete fPedestalData;
159   
160   if(fgDigitsArr){
161     fgDigitsArr->Clear("C");
162     delete fgDigitsArr; 
163   }
164   
165   if(fgClustersArr){
166     fgClustersArr->Clear();
167     delete fgClustersArr; 
168   }
169   
170   if(fgTriggerDigits){
171     fgTriggerDigits->Clear();
172     delete fgTriggerDigits; 
173   }
174   
175   if(fgRawUtils)         delete fgRawUtils;
176   if(fgClusterizer)      delete fgClusterizer;
177   if(fgTriggerProcessor) delete fgTriggerProcessor;
178   
179   if(fMatches) { fMatches->Delete(); delete fMatches; fMatches = 0;}
180   
181   AliCodeTimer::Instance()->Print();
182
183
184 //____________________________________________________________________________                                  
185 void AliEMCALReconstructor::InitClusterizer() const
186 {
187   //Init the clusterizer with geometry and calibration pointers, avoid doing it twice.                          
188   Int_t clusterizerType = -1;
189   Int_t eventType = -1;
190   if(GetRecParam()) {
191     clusterizerType = GetRecParam()->GetClusterizerFlag();
192     eventType       = GetRecParam()->GetEventSpecie();
193   }
194   else{
195     AliCDBEntry *entry = (AliCDBEntry*)
196       AliCDBManager::Instance()->Get("EMCAL/Calib/RecoParam");
197     //Get The reco param for the default event specie                                                           
198     if (entry) {
199       AliEMCALRecParam *recParam  = (AliEMCALRecParam*)((TObjArray *) entry->GetObject())->At(0);
200       if(recParam) clusterizerType = recParam->GetClusterizerFlag(); 
201     }
202   }
203   
204   //Check if clusterizer previously set corresponds to what is needed for this event type                       
205   if(fgClusterizer){
206     if(eventType!=AliRecoParam::kCalib){
207       //printf("ReCreate clusterizer? Clusterizer set <%d>, Clusterizer in use <%s>\n",
208       //     clusterizerType, fgClusterizer->Version());
209       
210       if     (clusterizerType == AliEMCALRecParam::kClusterizerv1  && !strcmp(fgClusterizer->Version(),"clu-v1"))  return;
211       
212       else if(clusterizerType == AliEMCALRecParam::kClusterizerNxN && !strcmp(fgClusterizer->Version(),"clu-NxN")) return;
213       
214       else if(clusterizerType == AliEMCALRecParam::kClusterizerv2  && !strcmp(fgClusterizer->Version(),"clu-v2"))  return;
215       
216       //Need to create new clusterizer, the one set previously is not the correct one     
217       delete fgClusterizer;
218     }
219     else return;
220   }
221   
222   if      (clusterizerType  == AliEMCALRecParam::kClusterizerv1)
223     {
224       fgClusterizer = new AliEMCALClusterizerv1 (fGeom, fCalibData,fPedestalData);
225     }
226   else if (clusterizerType  == AliEMCALRecParam::kClusterizerNxN)
227     {
228       fgClusterizer = new AliEMCALClusterizerNxN(fGeom, fCalibData,fPedestalData);
229     }
230   else if (clusterizerType  == AliEMCALRecParam::kClusterizerv2)
231   {
232     fgClusterizer = new AliEMCALClusterizerv2   (fGeom, fCalibData,fPedestalData);
233   }
234   else 
235   {
236     AliFatal(Form("Unknown clusterizer %d ", clusterizerType));
237   }
238 }
239
240 //____________________________________________________________________________
241 void AliEMCALReconstructor::Reconstruct(TTree* digitsTree, TTree* clustersTree) const
242 {
243   // method called by AliReconstruction; 
244   // Only the clusterization is performed,; the rest of the reconstruction is done in FillESD because the track
245   // segment maker needs access to the AliESD object to retrieve the tracks reconstructed by 
246   // the global tracking.
247   // Works on the current event.
248   
249   AliCodeTimerAuto("",0)
250     
251   //Get input digits and put them in fgDigitsArr, clear the list before 
252   ReadDigitsArrayFromTree(digitsTree);
253   
254   InitClusterizer();
255   
256   fgClusterizer->InitParameters();
257   fgClusterizer->SetOutput(clustersTree);
258   
259   //Skip clusterization of LED events
260   if (GetRecParam()->GetEventSpecie()!=AliRecoParam::kCalib){
261     
262     if(fgDigitsArr && fgDigitsArr->GetEntries()) {
263       
264       fgClusterizer->SetInput(digitsTree);
265       
266       //fgClusterizer->Digits2Clusters("deb all") ; //For debugging
267       fgClusterizer->Digits2Clusters("");
268       
269       fgClusterizer->Clear();
270       
271     }//digits array exists and has somethind
272   }//not a LED event
273   
274   clustersTree->Fill(); 
275
276   // Deleting the recpoints at the end of the reconstruction call
277   fgClusterizer->DeleteRecPoints();
278 }
279
280 //____________________________________________________________________________
281 void AliEMCALReconstructor::ConvertDigits(AliRawReader* rawReader, TTree* digitsTree) const
282   
283 {
284   // Conversion from raw data to
285   // EMCAL digits.
286   // Works on a single-event basis
287   
288   rawReader->Reset() ; 
289   
290   fTriggerData->SetMode(1);     
291   
292   if(fgDigitsArr) fgDigitsArr->Clear("C");
293   
294   const int kNTRU = fGeom->GetNTotalTRU();
295   TClonesArray *digitsTrg = new TClonesArray("AliEMCALTriggerRawDigit", kNTRU * 96);
296   
297   Int_t bufsize = 32000;
298   digitsTree->Branch("EMCAL", &fgDigitsArr, bufsize);
299   digitsTree->Branch("EMTRG", &digitsTrg, bufsize);
300   
301   //Skip calibration events do the rest
302   Bool_t doFit = kTRUE;
303   if ( !(GetRecParam()->FitLEDEvents()) && GetRecParam()->GetEventSpecie()==AliRecoParam::kCalib) doFit = kFALSE;
304   if (doFit){
305     //must be done here because, in constructor, option is not yet known
306     fgRawUtils->SetOption(GetOption());
307     
308     //  fgRawUtils->SetRawFormatHighLowGainFactor(GetRecParam()->GetHighLowGainFactor());
309     
310     //   fgRawUtils->SetRawFormatOrder(GetRecParam()->GetOrderParameter());
311     //    fgRawUtils->SetRawFormatTau(GetRecParam()->GetTau());
312     fgRawUtils->SetNoiseThreshold(GetRecParam()->GetNoiseThreshold());
313     fgRawUtils->SetNPedSamples(GetRecParam()->GetNPedSamples());
314     fgRawUtils->SetRemoveBadChannels(GetRecParam()->GetRemoveBadChannels());
315     if (!fgRawUtils->GetFittingAlgorithm()) fgRawUtils->SetFittingAlgorithm(GetRecParam()->GetFittingAlgorithm());
316     fgRawUtils->SetFALTROUsage(GetRecParam()->UseFALTRO());
317     //  fgRawUtils->SetFALTROUsage(0);
318  
319     //fgRawUtils->SetTimeMin(GetRecParam()->GetTimeMin());
320     //fgRawUtils->SetTimeMax(GetRecParam()->GetTimeMax());
321     
322     //  fgRawUtils->SetTimeMin(-99999 );
323     //  fgRawUtils->SetTimeMax( 99999 );
324     
325     fgRawUtils->Raw2Digits(rawReader,fgDigitsArr,fPedestalData,digitsTrg,fTriggerData);
326     
327   }//skip calibration event
328   else{
329     AliDebug(1," Calibration Event, skip!");
330   }
331   
332   digitsTree->Fill();
333   digitsTrg->Delete();
334   delete digitsTrg;
335   
336 }
337
338
339 //____________________________________________________________________________
340 void AliEMCALReconstructor::FillESD(TTree* digitsTree, TTree* clustersTree, 
341                                     AliESDEvent* esd) const
342 {
343   // Called by AliReconstruct after Reconstruct() and global tracking and vertexing 
344   // and V0 
345   // Works on the current event
346   // printf(" ## AliEMCALReconstructor::FillESD() is started ### \n ");
347   //return;
348   
349   //########################################
350   // Trigger
351   //########################################
352   
353   static int saveOnce = 0;
354   
355   Int_t v0M[2] = {0, 0};
356   
357   AliESDVZERO* esdV0 = esd->GetVZEROData();
358   
359   if (esdV0) 
360     {
361                 v0M[0] = esdV0->GetTriggerChargeC();
362                 v0M[1] = esdV0->GetTriggerChargeA();
363     }
364   else
365     {
366       AliWarning("No V0 ESD! Run trigger processor w/ null V0 charges");
367     }
368   
369   if (fgTriggerDigits && fgTriggerDigits->GetEntriesFast()) fgTriggerDigits->Delete();
370   
371   TBranch *branchtrg = digitsTree->GetBranch("EMTRG");
372   
373   if (!branchtrg) 
374     { 
375       AliError("Can't get the branch with the EMCAL trigger digits!");
376       return;
377     }
378   
379   branchtrg->SetAddress(&fgTriggerDigits);
380   branchtrg->GetEntry(0);
381   
382   // Note: fgTriggerProcessor reset done at the end of this method
383   fgTriggerProcessor->Digits2Trigger(fgTriggerDigits, v0M, fTriggerData);
384   
385   // Fill ESD
386   AliESDCaloTrigger* trgESD = esd->GetCaloTrigger("EMCAL");
387   
388   if (trgESD)
389     {
390       trgESD->Allocate(fgTriggerDigits->GetEntriesFast());
391       
392       for (Int_t i = 0; i < fgTriggerDigits->GetEntriesFast(); i++)
393         {         
394           AliEMCALTriggerRawDigit* rdig = (AliEMCALTriggerRawDigit*)fgTriggerDigits->At(i);
395           if (AliDebugLevel() > 999) rdig->Print("");
396                 
397           Int_t px, py;
398           if (fGeom->GetPositionInEMCALFromAbsFastORIndex(rdig->GetId(), px, py))
399             {
400               Int_t a = -1, t = -1, times[10]; 
401               
402               rdig->GetMaximum(a, t);
403               rdig->GetL0Times(times);
404                         
405               trgESD->Add(px, py, a, t, times, rdig->GetNL0Times(), rdig->GetL1TimeSum(), rdig->GetTriggerBits());
406             }
407         }
408       
409                 for (int i = 0; i < 2; i++) {
410                         trgESD->SetL1Threshold(2 * i    , fTriggerData->GetL1JetThreshold(  i));
411                         trgESD->SetL1Threshold(2 * i + 1, fTriggerData->GetL1GammaThreshold(i));
412                 }
413       
414       Int_t v0[2];
415       fTriggerData->GetL1V0(v0);
416       
417       trgESD->SetL1V0(v0);      
418       trgESD->SetL1FrameMask(fTriggerData->GetL1FrameMask());            
419       
420       if (!saveOnce && fTriggerData->GetL1DataDecoded()) 
421         {
422           int type[15] = {0};
423           fTriggerData->GetL1TriggerType(type);
424           
425           esd->SetCaloTriggerType(type);
426           
427           saveOnce = 1;
428         }
429     }
430   
431   // Resetting
432   fTriggerData->Reset();
433   
434   //########################################
435   //##############Fill CaloCells###############
436   //########################################
437   
438   //Get input digits and put them in fgDigitsArr, clear the list before 
439   ReadDigitsArrayFromTree(digitsTree);
440   
441   Int_t nDigits = fgDigitsArr->GetEntries(), idignew = 0 ;
442   AliDebug(1,Form("%d digits",nDigits));
443   
444   AliESDCaloCells &emcCells = *(esd->GetEMCALCells());
445   emcCells.CreateContainer(nDigits);
446   emcCells.SetType(AliVCaloCells::kEMCALCell);
447   
448   Float_t energy = 0;
449   Float_t time   = 0;
450   for (Int_t idig = 0 ; idig < nDigits ; idig++) 
451   {
452     const AliEMCALDigit * dig = (const AliEMCALDigit*)fgDigitsArr->At(idig);
453     time   = dig->GetTime();      // Time already calibrated in clusterizer
454     energy = dig->GetAmplitude(); // energy calibrated in clusterizer
455     
456     if(energy > 0 )
457     {
458       fgClusterizer->Calibrate(energy,time,dig->GetId()); //Digits already calibrated in clusterizers
459       
460       if(energy > 0) //Digits tagged as bad (dead, hot, not alive) are set to 0 in calibrate, remove them
461       { 
462         // Only for MC
463         // Get the label of the primary particle that generated the cell
464         // Assign the particle that deposited more energy
465         Int_t   nprimaries = dig->GetNprimary() ;
466         Int_t   digLabel   =-1 ;
467         Float_t edep       =-1.;
468         if ( nprimaries > 0 )
469         {
470           Int_t jndex ;
471           for ( jndex = 0 ; jndex < nprimaries ; jndex++ ) { // all primaries in digit
472  
473             if(edep < dig->GetDEParent(jndex+1))
474             {
475               digLabel = dig->GetIparent (jndex+1);
476               edep     = dig->GetDEParent(jndex+1);
477             }
478                    
479           } // all primaries in digit      
480         } // select primary label
481         
482         Bool_t highGain = kFALSE;
483         if( dig->GetType() == AliEMCALDigit::kHG ) highGain = kTRUE;
484         
485         emcCells.SetCell(idignew,dig->GetId(),energy, time,digLabel,0.,highGain);
486         idignew++;
487       }
488     }
489   }
490   
491   emcCells.SetNumberOfCells(idignew);
492   emcCells.Sort();
493   
494   //------------------------------------------------------------
495   //-----------------CLUSTERS-----------------------------
496   //------------------------------------------------------------
497   clustersTree->SetBranchStatus("*",0); //disable all branches
498   clustersTree->SetBranchStatus("EMCALECARP",1); //Enable only the branch we need
499   if(fgClustersArr) fgClustersArr->Clear();
500   TBranch *branch = clustersTree->GetBranch("EMCALECARP");
501   branch->SetAddress(&fgClustersArr);
502   branch->GetEntry(0);
503   //clustersTree->GetEvent(0);
504   
505   Int_t nClusters = fgClustersArr->GetEntries(),  nClustersNew=0;
506   AliDebug(1,Form("%d clusters",nClusters));
507
508   
509   //########################################
510   //##############Fill CaloClusters#############
511   //########################################
512   for (Int_t iClust = 0 ; iClust < nClusters ; iClust++) {
513     const AliEMCALRecPoint * clust = (const AliEMCALRecPoint*)fgClustersArr->At(iClust);
514     if(!clust) continue;
515     //if(clust->GetClusterType()== AliVCluster::kEMCALClusterv1) nRP++; else nPC++;
516     // clust->Print(); //For debugging
517     // Get information from EMCAL reconstruction points
518     Float_t xyz[3];
519     TVector3 gpos;
520     clust->GetGlobalPosition(gpos);
521     for (Int_t ixyz=0; ixyz<3; ixyz++)
522       xyz[ixyz] = gpos[ixyz];
523     Float_t elipAxis[2];
524     clust->GetElipsAxis(elipAxis);
525     //Create digits lists
526     Int_t cellMult = clust->GetMultiplicity();
527     //TArrayS digiList(digitMult);
528     Float_t *amplFloat = clust->GetEnergiesList();
529     Int_t   *digitInts = clust->GetAbsId();
530     TArrayS absIdList(cellMult);
531     TArrayD fracList(cellMult);
532     
533     Int_t newCellMult = 0;
534     for (Int_t iCell=0; iCell<cellMult; iCell++) {
535       if (amplFloat[iCell] > 0) {
536         absIdList[newCellMult] = (UShort_t)(digitInts[iCell]);
537         //Calculate Fraction
538         if(emcCells.GetCellAmplitude(digitInts[iCell])>0 && GetRecParam()->GetUnfold()){
539           fracList[newCellMult] = amplFloat[iCell]/(emcCells.GetCellAmplitude(digitInts[iCell]));//get cell calibration value 
540           
541         }
542         else{
543           fracList[newCellMult] = 0; 
544         }
545         newCellMult++;
546       }
547     }
548     
549     absIdList.Set(newCellMult);
550     fracList.Set(newCellMult);
551     
552     if(newCellMult > 0) { // accept cluster if it has some digit
553       nClustersNew++;
554       //Primaries
555       Int_t  parentMult  = 0;
556       Int_t *parentList =  clust->GetParents(parentMult);
557       // fills the ESDCaloCluster
558       AliESDCaloCluster * ec = new AliESDCaloCluster() ;
559       ec->SetType(AliVCluster::kEMCALClusterv1);
560       ec->SetPosition(xyz);
561       ec->SetE(clust->GetEnergy());
562       
563       //Distance to the nearest bad crystal
564       ec->SetDistanceToBadChannel(clust->GetDistanceToBadTower()); 
565       
566       ec->SetNCells(newCellMult);
567       //Change type of list from short to ushort
568       UShort_t *newAbsIdList  = new UShort_t[newCellMult];
569       Double_t *newFracList   = new Double_t[newCellMult];
570       for(Int_t i = 0; i < newCellMult ; i++) {
571         newAbsIdList[i]=absIdList[i];
572         newFracList[i] =fracList[i];
573       }
574       ec->SetCellsAbsId(newAbsIdList);
575       ec->SetCellsAmplitudeFraction(newFracList);
576       ec->SetDispersion(clust->GetDispersion());
577       ec->SetChi2(-1); //not yet implemented
578       ec->SetM02(elipAxis[0]*elipAxis[0]) ;
579       ec->SetM20(elipAxis[1]*elipAxis[1]) ;
580       ec->SetTOF(clust->GetTime()) ; //time-of-fligh
581       ec->SetNExMax(clust->GetNExMax());          //number of local maxima
582   
583       
584       TArrayI arrayParents(parentMult,parentList);
585       ec->AddLabels(arrayParents);
586       //
587       //Track matching
588       //
589       fMatches->Clear();
590       Int_t nTracks = esd->GetNumberOfTracks();
591       for (Int_t itrack = 0; itrack < nTracks; itrack++)
592         {
593           AliESDtrack * track = esd->GetTrack(itrack) ; // retrieve track
594           if(track->GetEMCALcluster()==iClust)
595             {
596               Float_t dEta=-999, dPhi=-999;
597               Bool_t isMatch =  CalculateResidual(track, ec, dEta, dPhi);
598               if(!isMatch) 
599                 {
600                   // AliDebug(10, "Not good");
601                   continue;
602                 }
603               AliEMCALMatch *match = new AliEMCALMatch();
604               match->SetIndexT(itrack);
605               match->SetDistance(TMath::Sqrt(dEta*dEta+dPhi*dPhi));
606               match->SetdEta(dEta);
607               match->SetdPhi(dPhi);
608               fMatches->Add(match);
609             }
610         } 
611       fMatches->Sort(kSortAscending); //Sort matched tracks from closest to furthest
612       Int_t nMatch = fMatches->GetEntries();
613       TArrayI arrayTrackMatched(nMatch);
614       for(Int_t imatch=0; imatch<nMatch; imatch++)
615         {
616           AliEMCALMatch *match = (AliEMCALMatch*)fMatches->At(imatch);
617           arrayTrackMatched[imatch] = match->GetIndexT();
618           if(imatch==0)
619             {
620               ec->SetTrackDistance(match->GetdPhi(), match->GetdEta());
621             }
622         }
623       ec->AddTracksMatched(arrayTrackMatched);
624     
625       //add the cluster to the esd object
626       esd->AddCaloCluster(ec);
627
628       delete ec;
629       delete [] newAbsIdList ;
630       delete [] newFracList ;
631     }
632   } // cycle on clusters
633
634   //
635   //Reset the index of matched cluster for tracks
636   //to the one in CaloCluster array
637   Int_t ncls = esd->GetNumberOfCaloClusters();
638   for(Int_t icl=0; icl<ncls; icl++)
639     {
640       AliESDCaloCluster *cluster = esd->GetCaloCluster(icl);
641       if(!cluster || !cluster->IsEMCAL()) continue;
642       TArrayI *trackIndex = cluster->GetTracksMatched();
643       for(Int_t itr=0; itr<trackIndex->GetSize(); itr++)
644         {
645           AliESDtrack *track = esd->GetTrack(trackIndex->At(itr));
646           track->SetEMCALcluster(cluster->GetID());
647         }
648     }
649   
650   
651   //Fill ESDCaloCluster with PID weights
652   AliEMCALPID *pid = new AliEMCALPID;
653   //pid->SetPrintInfo(kTRUE);
654   pid->SetReconstructor(kTRUE);
655   pid->RunPID(esd);
656   delete pid;
657   
658   //Store EMCAL misalignment matrixes
659   FillMisalMatrixes(esd) ;
660   
661 }
662
663 //==================================================================================
664 void AliEMCALReconstructor::FillMisalMatrixes(AliESDEvent* esd)const{
665   //Store EMCAL matrixes in ESD Header
666   
667   //Check, if matrixes was already stored
668   for(Int_t sm = 0 ; sm < fGeom->GetNumberOfSuperModules(); sm++){
669     if(esd->GetEMCALMatrix(sm)!=0)
670       return ;
671   }
672   
673   //Create and store matrixes
674   if(!gGeoManager){
675     AliError("Can not store misal. matrixes: no gGeoManager! \n") ;
676     return ;
677   }
678   //Note, that owner of copied marixes will be header
679   const Int_t bufsize = 255;
680   char path[bufsize] ;
681   TGeoHMatrix * m = 0x0;
682   Int_t tmpType = -1;
683   Int_t SMOrder = 0;
684   TString SMName;
685   for(Int_t sm = 0; sm < fGeom->GetNumberOfSuperModules(); sm++){
686     if(fGeom->GetSMType(sm) == AliEMCALGeometry::kEMCAL_Standard )      SMName = "SMOD";
687     else if(fGeom->GetSMType(sm) == AliEMCALGeometry::kEMCAL_Half )     SMName = "SM10";
688     else if(fGeom->GetSMType(sm) == AliEMCALGeometry::kEMCAL_3rd )      SMName = "SM3rd";
689     else if( fGeom->GetSMType(sm) == AliEMCALGeometry::kDCAL_Standard ) SMName = "DCSM";
690     else if( fGeom->GetSMType(sm) == AliEMCALGeometry::kDCAL_Ext )      SMName = "DCEXT";
691     else AliError("Unkown SM Type!!");
692
693     if(fGeom->GetSMType(sm) == tmpType) {
694       SMOrder++;
695     } else {
696       tmpType = fGeom->GetSMType(sm);
697       SMOrder = 1;
698     }
699     snprintf(path,bufsize,"/ALIC_1/XEN1_1/%s_%d", SMName.Data(), SMOrder) ;
700
701     if (gGeoManager->CheckPath(path)){
702       gGeoManager->cd(path);
703       m = gGeoManager->GetCurrentMatrix() ;
704       //                        printf("================================================= \n");
705       //                        printf("AliEMCALReconstructor::FixMisalMatrixes(), sm %d, \n",sm);
706       //                        m->Print("");
707       esd->SetEMCALMatrix(new TGeoHMatrix(*m),sm) ;
708       //                        printf("================================================= \n");
709     }
710     else{
711       esd->SetEMCALMatrix(NULL,sm) ;
712     }
713   }
714 }
715
716 //__________________________________________________________________________
717 void AliEMCALReconstructor::ReadDigitsArrayFromTree(TTree *digitsTree) const
718 {
719   // Read the digits from the input tree
720   // See AliEMCALClusterizer::SetInput(TTree *digitsTree);    
721   
722   // Clear previous digits in the list
723   if(fgDigitsArr){ 
724     fgDigitsArr->Clear("C");
725   }
726   else{
727     // It should not happen, but just in case ...
728     fgDigitsArr = new TClonesArray("AliEMCALDigit",100); 
729   }
730   
731   // Read the digits from the input tree
732   TBranch *branch = digitsTree->GetBranch("EMCAL");
733   if (!branch) { 
734     AliError("can't get the branch with the EMCAL digits !");
735     return;
736   }  
737   
738   branch->SetAddress(&fgDigitsArr);
739   branch->GetEntry(0);
740 }
741
742 //==================================================================================
743 Bool_t AliEMCALReconstructor::CalculateResidual(AliESDtrack *track, AliESDCaloCluster *cluster, Float_t &dEta, Float_t &dPhi)const
744 {
745   //
746   // calculate the residual between track and cluster
747   //
748
749   // If the esdFriend is available, use the TPCOuter point as the starting point of extrapolation
750   // Otherwise use the TPCInner point
751
752   dEta = -999, dPhi = -999;
753   Bool_t ITSTrackSA = 0;
754
755   AliExternalTrackParam *trkParam = 0;
756   
757   const AliESDfriendTrack*  friendTrack = track->GetFriendTrack();
758   if(friendTrack && friendTrack->GetTPCOut())
759     trkParam = const_cast<AliExternalTrackParam*>(friendTrack->GetTPCOut());
760   else if(track->GetInnerParam())
761     trkParam = const_cast<AliExternalTrackParam*>(track->GetInnerParam());
762   else{
763     trkParam = new AliExternalTrackParam(*track); //If there is ITSSa track 
764     ITSTrackSA = 1;     
765   }
766   if(!trkParam) return kFALSE;
767   
768   AliExternalTrackParam trkParamTmp (*trkParam);
769   if(!AliEMCALRecoUtils::ExtrapolateTrackToCluster(&trkParamTmp, cluster, track->GetMass(kTRUE), GetRecParam()->GetExtrapolateStep(), dEta, dPhi)){
770         if(ITSTrackSA) delete trkParam;
771         return kFALSE;
772   }
773
774   if(ITSTrackSA) delete trkParam;
775   return kTRUE;
776 }
777
778 //
779 //==================================================================================
780 //
781 AliEMCALReconstructor::AliEMCALMatch::AliEMCALMatch() 
782   : TObject(),  
783     fIndexT(-1), 
784     fDistance(-999.),
785     fdEta(-999.),
786     fdPhi(-999.)
787 {
788   //default constructor
789
790 }
791
792 //
793 //==================================================================================
794 //
795 AliEMCALReconstructor::AliEMCALMatch::AliEMCALMatch(const AliEMCALMatch& copy)
796   : TObject(),
797     fIndexT(copy.fIndexT),
798     fDistance(copy.fDistance),
799     fdEta(copy.fdEta),
800     fdPhi(copy.fdPhi)
801 {
802   //copy ctor
803 }
804 //_____________________________________________________________________
805 AliEMCALReconstructor::AliEMCALMatch& AliEMCALReconstructor::AliEMCALMatch::AliEMCALMatch::operator = (const AliEMCALMatch &source)
806 { // assignment operator; use copy ctor
807   if (&source == this) return *this;
808
809   new (this) AliEMCALMatch(source);
810   return *this;
811 }
812 //
813 //==================================================================================
814 //
815 Int_t AliEMCALReconstructor::AliEMCALMatch::Compare(const TObject *obj) const 
816 {
817   //
818   // Compare wrt the residual
819   //
820         
821   AliEMCALReconstructor::AliEMCALMatch *that = (AliEMCALReconstructor::AliEMCALMatch*)obj;
822         
823   Double_t thisDist = fDistance;//fDistance;
824   Double_t thatDist = that->fDistance;//that->GetDistance();
825         
826   if (thisDist > thatDist) return 1;
827   else if (thisDist < thatDist) return -1;
828   return 0;
829 }