]> git.uio.no Git - u/mrichter/AliRoot.git/blob - EMCAL/AliEMCALDigitizer.cxx
corrected some things that gave compiler warnings; minor cleanup
[u/mrichter/AliRoot.git] / EMCAL / AliEMCALDigitizer.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 //////////////////////////////////////////////////////////////////////////////
21 // Class performs digitization of Summable digits 
22 //  
23 // In addition it performs mixing of summable digits from different events.
24 //
25 // For each event two branches are created in TreeD:
26 //   "EMCAL" - list of digits
27 //   "AliEMCALDigitizer" - AliEMCALDigitizer with all parameters used in digitization
28 //
29 // Note, that one cset title for new digits branch, and repeat digitization with
30 // another set of parameters.
31 //
32 // Examples of use:
33 // root[0] AliEMCALDigitizer * d = new AliEMCALDigitizer() ;
34 // root[1] d->ExecuteTask()             
35 // Warning in <TDatabasePDG::TDatabasePDG>: object already instantiated
36 //                       //Digitizes SDigitis in all events found in file galice.root 
37 //
38 // root[2] AliEMCALDigitizer * d1 = new AliEMCALDigitizer("galice1.root") ;  
39 //                       // Will read sdigits from galice1.root
40 // root[3] d1->MixWith("galice2.root")       
41 // Warning in <TDatabasePDG::TDatabasePDG>: object already instantiated
42 //                       // Reads another portion of sdigits from galice2.root
43 // root[3] d1->MixWith("galice3.root")       
44 //                       // Reads another portion of sdigits from galice3.root
45 // root[4] d->ExecuteTask("deb timing")    
46 //                       // Reads SDigits from files galice1.root, galice2.root ....
47 //                       // mixes them and stores produced Digits in file galice1.root          
48 //                       // deb - prints number of produced digits
49 //                       // deb all - prints list of produced digits
50 //                       // timing  - prints time used for digitization
51 ////////////////////////////////////////////////////////////////////////////////////
52 //
53 //*-- Author: Sahal Yacoob (LBL)
54 // based on : AliEMCALDigitizer
55 // Modif: 
56 //  August 2002 Yves Schutz: clone PHOS as closely as possible and intoduction
57 //                           of new  IO (à la PHOS)
58 //  November 2003 Aleksei Pavlinov : adopted for Shish-Kebab geometry 
59 //_________________________________________________________________________________
60
61 // --- ROOT system ---
62 #include "TROOT.h"
63 #include "TTree.h"
64 #include "TSystem.h"
65 #include "TBenchmark.h"
66 #include "TList.h"
67 #include "TH1.h"
68 #include "TBrowser.h"
69 #include "TObjectTable.h"
70
71 // --- AliRoot header files ---
72 #include "AliRun.h"
73 #include "AliRunDigitizer.h"
74 #include "AliRunLoader.h"
75 #include "AliEMCALDigit.h"
76 #include "AliEMCAL.h"
77 #include "AliEMCALLoader.h"
78 #include "AliEMCALDigitizer.h"
79 #include "AliEMCALSDigitizer.h"
80 #include "AliEMCALGeometry.h"
81 #include "AliEMCALTick.h"
82 #include "AliEMCALHistoUtilities.h"
83
84 ClassImp(AliEMCALDigitizer)
85
86
87 //____________________________________________________________________________ 
88   AliEMCALDigitizer::AliEMCALDigitizer():AliDigitizer("",""),
89                                        fInput(0),
90                                        fInputFileNames(0x0),
91                                        fEventNames(0x0)
92 {
93   // ctor
94   InitParameters() ; 
95   fDefaultInit = kTRUE ; 
96   fManager = 0 ;                     // We work in the standalong mode
97   fEventFolderName = "" ; 
98 }
99
100 //____________________________________________________________________________ 
101 AliEMCALDigitizer::AliEMCALDigitizer(TString alirunFileName, TString eventFolderName):
102   AliDigitizer("EMCAL"+AliConfig::Instance()->GetDigitizerTaskName(), alirunFileName),
103   fInputFileNames(0), fEventNames(0), fEventFolderName(eventFolderName)
104 {
105   // ctor
106
107   InitParameters() ; 
108   Init() ;
109   fDefaultInit = kFALSE ; 
110   fManager = 0 ;                     // We work in the standalong mode
111 }
112
113 //____________________________________________________________________________ 
114 AliEMCALDigitizer::AliEMCALDigitizer(const AliEMCALDigitizer & d) : AliDigitizer(d)
115 {
116   // copyy ctor 
117
118   SetName(d.GetName()) ; 
119   SetTitle(d.GetTitle()) ; 
120   fDigitThreshold = d.fDigitThreshold ; 
121   fMeanPhotonElectron = d.fMeanPhotonElectron ; 
122   fPedestal           = d.fPedestal ; 
123   fSlope              = d.fSlope ; 
124   fPinNoise           = d.fPinNoise ; 
125   fTimeResolution     = d.fTimeResolution ; 
126   fTimeThreshold      = d.fTimeThreshold ; 
127   fTimeSignalLength   = d.fTimeSignalLength ; 
128   fADCchannelEC       = d.fADCchannelEC ; 
129   fADCpedestalEC      = d.fADCpedestalEC ; 
130   fNADCEC             = d.fNADCEC ;
131   fEventFolderName    = d.fEventFolderName;
132  }
133
134 //____________________________________________________________________________ 
135 AliEMCALDigitizer::AliEMCALDigitizer(AliRunDigitizer * rd):
136  AliDigitizer(rd,"EMCAL"+AliConfig::Instance()->GetDigitizerTaskName()),
137  fEventFolderName(0)
138 {
139   // ctor Init() is called by RunDigitizer
140   fManager = rd ; 
141   fEventFolderName = fManager->GetInputFolderName(0) ;
142   SetTitle(dynamic_cast<AliStream*>(fManager->GetInputStream(0))->GetFileName(0));
143   InitParameters() ; 
144   fDefaultInit = kFALSE ; 
145 }
146
147 //____________________________________________________________________________ 
148   AliEMCALDigitizer::~AliEMCALDigitizer()
149 {
150   if (AliRunLoader::GetRunLoader()) {
151     AliLoader *emcalLoader=0;
152     if ((emcalLoader = AliRunLoader::GetRunLoader()->GetDetectorLoader("EMCAL")))
153       emcalLoader->CleanDigitizer();
154   }
155   else
156     AliDebug(1," no runloader present");
157   delete [] fInputFileNames ; 
158   delete [] fEventNames ; 
159
160   if(fHists) delete fHists;
161 }
162
163 //____________________________________________________________________________
164 void AliEMCALDigitizer::Digitize(Int_t event) 
165
166
167   // Makes the digitization of the collected summable digits
168   // for this it first creates the array of all EMCAL modules
169   // filled with noise (different for EMC, CPV and PPSD) and
170   // after that adds contributions from SDigits. This design 
171   // helps to avoid scanning over the list of digits to add 
172   // contribution of any new SDigit.
173   static int isTrd1Geom = -1; // -1 - mean undefined 
174   static int nEMC=0; //max number of digits possible
175
176   AliRunLoader *rl = AliRunLoader::GetRunLoader();
177   AliEMCALLoader *emcalLoader = dynamic_cast<AliEMCALLoader*>(rl->GetDetectorLoader("EMCAL"));
178   Int_t ReadEvent = event ; 
179   // fManager is data member from AliDigitizer
180   if (fManager) 
181     ReadEvent = dynamic_cast<AliStream*>(fManager->GetInputStream(0))->GetCurrentEventNumber() ; 
182   AliDebug(1,Form("Adding event %d from input stream 0 %s %s", 
183                   ReadEvent, GetTitle(), fEventFolderName.Data())) ; 
184   rl->GetEvent(ReadEvent);
185
186   TClonesArray * digits = emcalLoader->Digits() ; 
187   digits->Clear() ;
188
189   // Load Geometry
190   // const AliEMCALGeometry *geom = AliEMCALGeometry::GetInstance();
191   rl->LoadgAlice(); 
192   AliRun * gAlice = rl->GetAliRun(); 
193   AliEMCAL * emcal  = (AliEMCAL*)gAlice->GetDetector("EMCAL");
194   AliEMCALGeometry * geom = emcal->GetGeometry();
195
196   if(isTrd1Geom < 0) { 
197     TString ng(geom->GetName());
198     isTrd1Geom = 0;
199     if(ng.Contains("SHISH") &&  ng.Contains("TRD1")) isTrd1Geom = 1;
200
201     if(isTrd1Geom == 0) nEMC = geom->GetNPhi()*geom->GetNZ();
202     else                nEMC = geom->GetNCells();
203     AliDebug(1,Form("nEMC %i (number cells in EMCAL) | %s | isTrd1Geom %i\n", nEMC, geom->GetName(), isTrd1Geom));
204   }
205   Int_t absID ;
206
207   digits->Expand(nEMC) ;
208
209   // get first the sdigitizer from the tasks list (must have same name as the digitizer)
210   if ( !emcalLoader->SDigitizer() ) 
211     emcalLoader->LoadSDigitizer();
212   AliEMCALSDigitizer * sDigitizer = dynamic_cast<AliEMCALSDigitizer*>(emcalLoader->SDigitizer()); 
213   
214   if ( !sDigitizer )
215     Fatal("Digitize", "SDigitizer with name %s %s not found", fEventFolderName.Data(), GetTitle() ) ; 
216
217   //take all the inputs to add together and load the SDigits
218   TObjArray * sdigArray = new TObjArray(fInput) ;
219   sdigArray->AddAt(emcalLoader->SDigits(), 0) ;
220   Int_t i ;
221
222   for(i = 1 ; i < fInput ; i++){
223     TString tempo(fEventNames[i]) ; 
224     tempo += i ;
225     rl = AliRunLoader::Open(fInputFileNames[i], tempo) ; 
226     if (fManager) 
227       ReadEvent = dynamic_cast<AliStream*>(fManager->GetInputStream(i))->GetCurrentEventNumber() ; 
228     Info("Digitize", "Adding event %d from input stream %d %s %s", ReadEvent, i, fInputFileNames[i].Data(), tempo.Data()) ; 
229     rl->LoadSDigits();
230     rl->GetEvent(ReadEvent);
231     sdigArray->AddAt(emcalLoader->SDigits(), i) ;
232   }
233   
234   //Find the first tower with signal
235   Int_t nextSig = nEMC + 1 ; 
236   TClonesArray * sdigits ;  
237   for(i = 0 ; i < fInput ; i++){
238     sdigits = dynamic_cast<TClonesArray *>(sdigArray->At(i)) ;
239     if ( !sdigits->GetEntriesFast() )
240       continue ; 
241     Int_t curNext = dynamic_cast<AliEMCALDigit *>(sdigits->At(0))->GetId() ;
242      if(curNext < nextSig) 
243        nextSig = curNext ;
244      AliDebug(1,Form("input %i : #sdigits %i \n",
245                      i, sdigits->GetEntriesFast()));
246   }
247   AliDebug(1,Form("FIRST tower with signal %i \n", nextSig));
248
249   TArrayI index(fInput) ;
250   index.Reset() ;  //Set all indexes to zero
251
252   AliEMCALDigit * digit ;
253   AliEMCALDigit * curSDigit ;
254
255   TClonesArray * ticks = new TClonesArray("AliEMCALTick",1000) ;
256
257   //Put Noise contribution
258   for(absID = 1; absID <= nEMC; absID++){
259     Float_t amp = 0 ;
260     // amplitude set to zero, noise will be added later
261     new((*digits)[absID-1]) AliEMCALDigit( -1, -1, absID, 0, TimeOfNoise() ) ;
262     //look if we have to add signal?
263     digit = dynamic_cast<AliEMCALDigit *>(digits->At(absID-1)) ;
264     
265     if(absID==nextSig){
266       //Add SDigits from all inputs    
267       ticks->Clear() ;
268       Int_t contrib = 0 ;
269       Float_t a = digit->GetAmp() ;
270       Float_t b = TMath::Abs( a /fTimeSignalLength) ;
271       //Mark the beginning of the signal
272       new((*ticks)[contrib++]) AliEMCALTick(digit->GetTime(),0, b);  
273       //Mark the end of the signal     
274       new((*ticks)[contrib++]) AliEMCALTick(digit->GetTime()+fTimeSignalLength, -a, -b);
275       
276       // loop over input
277       for(i = 0; i< fInput ; i++){  //loop over (possible) merge sources
278         if(dynamic_cast<TClonesArray *>(sdigArray->At(i))->GetEntriesFast() > index[i] )
279           curSDigit = dynamic_cast<AliEMCALDigit*>(dynamic_cast<TClonesArray *>(sdigArray->At(i))->At(index[i])) ;      
280         else
281           curSDigit = 0 ;
282         //May be several digits will contribute from the same input
283         while(curSDigit && (curSDigit->GetId() == absID)){         
284           //Shift primary to separate primaries belonging different inputs
285           Int_t primaryoffset ;
286           if(fManager)
287             primaryoffset = fManager->GetMask(i) ; 
288           else
289             primaryoffset = i ;
290           curSDigit->ShiftPrimary(primaryoffset) ;
291           
292           a = curSDigit->GetAmp() ;
293           b = a /fTimeSignalLength ;
294           new((*ticks)[contrib++]) AliEMCALTick(curSDigit->GetTime(),0, b);  
295           new((*ticks)[contrib++]) AliEMCALTick(curSDigit->GetTime()+fTimeSignalLength, -a, -b); 
296
297           *digit = *digit + *curSDigit ;  //add energies
298
299           index[i]++ ;
300           if( dynamic_cast<TClonesArray *>(sdigArray->At(i))->GetEntriesFast() > index[i] )
301             curSDigit = dynamic_cast<AliEMCALDigit*>(dynamic_cast<TClonesArray *>(sdigArray->At(i))->At(index[i])) ;
302           else
303             curSDigit = 0 ;
304         }
305       }
306       // add fluctuations for photo-electron creation
307       amp = sDigitizer->Calibrate(digit->GetAmp()) ; // GeV
308       amp *= static_cast<Float_t>(gRandom->Poisson(fMeanPhotonElectron)) / static_cast<Float_t>(fMeanPhotonElectron) ;
309   
310       //calculate and set time
311       Float_t time = FrontEdgeTime(ticks) ;
312       digit->SetTime(time) ;
313
314       //Find next signal module
315       nextSig = nEMC + 1 ;
316       for(i = 0 ; i < fInput ; i++){
317         sdigits = dynamic_cast<TClonesArray *>(sdigArray->At(i)) ;
318         Int_t curNext = nextSig ;
319         if(sdigits->GetEntriesFast() > index[i] ){
320           curNext = dynamic_cast<AliEMCALDigit *>(sdigits->At(index[i]))->GetId() ;       
321         }
322         if(curNext < nextSig) nextSig = curNext ;
323       }
324     }
325     // add the noise now
326     amp += TMath::Abs(gRandom->Gaus(0., fPinNoise)) ;
327     digit->SetAmp(sDigitizer->Digitize(amp)) ;  
328     AliDebug(10,Form(" absID %5i amp %f nextSig %5i\n",
329                      absID, amp, nextSig));
330   } // for(absID = 1; absID <= nEMC; absID++)
331   
332   ticks->Delete() ;
333   delete ticks ;
334
335   delete sdigArray ; //We should not delete its contents
336
337   //remove digits below thresholds
338   for(i = 0 ; i < nEMC ; i++){
339     digit = dynamic_cast<AliEMCALDigit*>( digits->At(i) ) ;
340     Float_t threshold = fDigitThreshold ; 
341     if(sDigitizer->Calibrate( digit->GetAmp() ) < threshold)
342       digits->RemoveAt(i) ;
343     else 
344       digit->SetTime(gRandom->Gaus(digit->GetTime(),fTimeResolution) ) ;
345   }
346   
347   digits->Compress() ;  
348   
349   Int_t ndigits = digits->GetEntriesFast() ; 
350   digits->Expand(ndigits) ;
351   
352   //Set indexes in list of digits and fill hists.
353   AliEMCALHistoUtilities::FillH1(fHists, 0, Double_t(ndigits));
354   Float_t energy=0., esum=0.;
355   for (i = 0 ; i < ndigits ; i++) { 
356     digit = dynamic_cast<AliEMCALDigit *>( digits->At(i) ) ; 
357     digit->SetIndexInList(i) ; 
358     energy = sDigitizer->Calibrate(digit->GetAmp()) ;
359     esum += energy;
360     digit->SetAmp(DigitizeEnergy(energy, digit->GetId()) ) ; // for what ??
361     AliEMCALHistoUtilities::FillH1(fHists, 2, double(digit->GetAmp()));
362     AliEMCALHistoUtilities::FillH1(fHists, 3, double(energy));
363     AliEMCALHistoUtilities::FillH1(fHists, 4, double(digit->GetId()));
364   }
365   AliEMCALHistoUtilities::FillH1(fHists, 1, esum);
366 }
367
368 // //_____________________________________________________________________
369 Int_t AliEMCALDigitizer::DigitizeEnergy(Float_t energy, Int_t AbsId)
370
371   // Returns digitized value of the energy in a cell absId
372   // Loader
373   AliRunLoader *rl = AliRunLoader::GetRunLoader();
374   AliEMCALLoader *emcalLoader = dynamic_cast<AliEMCALLoader*>
375     (rl->GetDetectorLoader("EMCAL"));
376   
377   // Load EMCAL Geometry
378   rl->LoadgAlice(); 
379   AliRun * gAlice = rl->GetAliRun(); 
380   AliEMCAL * emcal  = (AliEMCAL*)gAlice->GetDetector("EMCAL");
381   AliEMCALGeometry * geom = emcal->GetGeometry();
382
383   if (geom==0)
384     AliFatal("Did not get geometry from EMCALLoader") ;
385
386   Int_t iSupMod = -1;
387   Int_t nTower  = -1;
388   Int_t nIphi   = -1;
389   Int_t nIeta   = -1;
390   Int_t iphi    = -1;
391   Int_t ieta    = -1;
392   Int_t channel = -999; 
393
394   Bool_t bCell = geom->GetCellIndex(AbsId, iSupMod, nTower, nIphi, nIeta) ;
395   if(!bCell)
396     Error("DigitizeEnergy","Wrong cell id number") ;
397   geom->GetCellPhiEtaIndexInSModule(iSupMod,nTower,nIphi, nIeta,iphi,ieta);
398   
399   if(emcalLoader->CalibData()) {
400     fADCpedestalEC = emcalLoader->CalibData()
401       ->GetADCpedestal(iSupMod,ieta,iphi);
402     fADCchannelEC = emcalLoader->CalibData()
403       ->GetADCchannel(iSupMod,ieta,iphi);
404   }
405   
406   channel = static_cast<Int_t> (TMath::Ceil( (energy + fADCpedestalEC)/fADCchannelEC ))  ;
407   
408   if(channel > fNADCEC ) 
409     channel =  fNADCEC ; 
410   return channel ;
411   
412 }
413
414 //____________________________________________________________________________
415 void AliEMCALDigitizer::Exec(Option_t *option) 
416
417   // Steering method to process digitization for events
418   // in the range from fFirstEvent to fLastEvent.
419   // This range is optionally set by SetEventRange().
420   // if fLastEvent=-1, then process events until the end.
421   // by default fLastEvent = fFirstEvent (process only one event)
422
423   if (!fInit) { // to prevent overwrite existing file
424     Error( "Exec", "Give a version name different from %s", fEventFolderName.Data() ) ;
425     return ;
426   } 
427
428   if (strstr(option,"print")) {
429     Print();
430     return ; 
431   }
432   
433   if(strstr(option,"tim"))
434     gBenchmark->Start("EMCALDigitizer");
435
436   AliRunLoader *rl = AliRunLoader::GetRunLoader();
437   AliEMCALLoader *emcalLoader = dynamic_cast<AliEMCALLoader*>(rl->GetDetectorLoader("EMCAL"));
438
439   // Post Digitizer to the white board
440   emcalLoader->PostDigitizer(this) ;
441   
442   if (fLastEvent == -1) 
443     fLastEvent = rl->GetNumberOfEvents() - 1 ;
444   else if (fManager) 
445     fLastEvent = fFirstEvent ; // what is this ??
446
447   Int_t nEvents   = fLastEvent - fFirstEvent + 1;
448   Int_t ievent;
449
450   rl->LoadSDigits("EMCAL");
451   for (ievent = fFirstEvent; ievent <= fLastEvent; ievent++) {
452     
453     rl->GetEvent(ievent);
454
455     Digitize(ievent) ; //Add prepared SDigits to digits and add the noise
456
457     WriteDigits() ;
458
459     if(strstr(option,"deb"))
460       PrintDigits(option);
461     if(strstr(option,"table")) gObjectTable->Print();
462
463     //increment the total number of Digits per run 
464     fDigitsInRun += emcalLoader->Digits()->GetEntriesFast() ;  
465   }
466   
467   emcalLoader->CleanDigitizer() ;
468
469   if(strstr(option,"tim")){
470     gBenchmark->Stop("EMCALDigitizer");
471     printf("Exec: took %f seconds for Digitizing %f seconds per event", 
472          gBenchmark->GetCpuTime("EMCALDigitizer"), gBenchmark->GetCpuTime("EMCALDigitizer")/nEvents ) ;
473   } 
474 }
475
476 //____________________________________________________________________________ 
477 Float_t AliEMCALDigitizer::FrontEdgeTime(TClonesArray * ticks) 
478
479   //  Returns the shortest time among all time ticks
480
481   ticks->Sort() ; //Sort in accordance with times of ticks
482   TIter it(ticks) ;
483   AliEMCALTick * ctick = (AliEMCALTick *) it.Next() ;
484   Float_t time = ctick->CrossingTime(fTimeThreshold) ;    
485   
486   AliEMCALTick * t ;  
487   while((t=(AliEMCALTick*) it.Next())){
488     if(t->GetTime() < time)  //This tick starts before crossing
489       *ctick+=*t ;
490     else
491       return time ;
492     
493     time = ctick->CrossingTime(fTimeThreshold) ;    
494   }
495   return time ;
496 }
497
498 //____________________________________________________________________________ 
499 Bool_t AliEMCALDigitizer::Init()
500 {
501   // Makes all memory allocations
502   fInit = kTRUE ; 
503   AliEMCALLoader *emcalLoader = dynamic_cast<AliEMCALLoader*>(AliRunLoader::GetRunLoader()->GetDetectorLoader("EMCAL"));
504
505   if ( emcalLoader == 0 ) {
506     Fatal("Init", "Could not obtain the AliEMCALLoader");  
507     return kFALSE;
508   } 
509
510   fFirstEvent = 0 ; 
511   fLastEvent = fFirstEvent ; 
512   
513   if(fManager)
514     fInput = fManager->GetNinputs() ; 
515   else 
516     fInput           = 1 ;
517
518   fInputFileNames  = new TString[fInput] ; 
519   fEventNames      = new TString[fInput] ; 
520   fInputFileNames[0] = GetTitle() ; 
521   fEventNames[0]     = fEventFolderName.Data() ; 
522   Int_t index ; 
523   for (index = 1 ; index < fInput ; index++) {
524     fInputFileNames[index] = dynamic_cast<AliStream*>(fManager->GetInputStream(index))->GetFileName(0); 
525     TString tempo = fManager->GetInputFolderName(index) ;
526     fEventNames[index] = tempo.Remove(tempo.Length()-1) ; // strip of the stream number added bt fManager 
527   }
528   
529   //to prevent cleaning of this object while GetEvent is called
530   emcalLoader->GetDigitsDataLoader()->GetBaseTaskLoader()->SetDoNotReload(kTRUE);
531
532   Print();
533   
534   return fInit ;    
535 }
536
537 //____________________________________________________________________________ 
538 void AliEMCALDigitizer::InitParameters()
539 { // Tune parameters - 24-nov-04
540
541   fMeanPhotonElectron = 3300 ; // electrons per GeV 
542   fPinNoise           = 0.004; 
543   if (fPinNoise == 0. ) 
544     Warning("InitParameters", "No noise added\n") ; 
545   fDigitThreshold     = fPinNoise * 3; // 3 * sigma
546   fTimeResolution     = 0.3e-9 ; // 300 psc
547   fTimeSignalLength   = 1.0e-9 ;
548
549   fADCchannelEC    = 0.00305; // 200./65536 - width of one ADC channel in GeV
550   fADCpedestalEC   = 0.009 ;  // GeV
551   fNADCEC          = (Int_t) TMath::Power(2,16) ;  // number of channels in Tower ADC - 65536
552
553   fTimeThreshold      = 0.001*10000000 ; // Means 1 MeV in terms of SDigits amplitude ??
554   // hists. for control; no hists on default
555   fControlHists = 0;
556   fHists        = 0;
557 }
558
559 //__________________________________________________________________
560 void AliEMCALDigitizer::MixWith(TString alirunFileName, TString eventFolderName)
561 {
562   // Allows to produce digits by superimposing background and signal event.
563   // It is assumed, that headers file with SIGNAL events is opened in 
564   // the constructor. 
565   // Sets the BACKGROUND event, with which the SIGNAL event is to be mixed 
566   // Thus we avoid writing (changing) huge and expensive 
567   // backgound files: all output will be writen into SIGNAL, i.e. 
568   // opened in constructor file. 
569   //
570   // One can open as many files to mix with as one needs.
571   // However only Sdigits with the same name (i.e. constructed with the same SDigitizer)
572   // can be mixed.
573
574   if( strcmp(GetName(), "") == 0 )
575     Init() ;
576   
577   if(fManager){
578     Error("MixWith", "Cannot use this method under AliRunDigitizer") ;
579     return ;
580   } 
581   // looking for file which contains AliRun
582   if (gSystem->AccessPathName(alirunFileName)) {// file does not exist
583     Error("MixWith", "File %s does not exist!", alirunFileName.Data()) ;
584     return ; 
585   }
586   // looking for the file which contains SDigits
587   AliEMCALLoader *emcalLoader = dynamic_cast<AliEMCALLoader*>(AliRunLoader::GetRunLoader()->GetDetectorLoader("EMCAL"));
588   TString fileName( emcalLoader->GetSDigitsFileName() ) ; 
589     if ( eventFolderName != AliConfig::GetDefaultEventFolderName()) // only if not the default folder name 
590       fileName = fileName.ReplaceAll(".root", "") + "_" + eventFolderName + ".root" ;
591     if ( (gSystem->AccessPathName(fileName)) ) { 
592       Error("MixWith", "The file %s does not exist!", fileName.Data()) ;
593       return ;
594     }
595     // need to increase the arrays
596     TString tempo = fInputFileNames[fInput-1] ; 
597     delete [] fInputFileNames ; 
598     fInputFileNames = new TString[fInput+1] ; 
599     fInputFileNames[fInput-1] = tempo ; 
600  
601     tempo = fEventNames[fInput-1] ; 
602     delete [] fEventNames ; 
603     fEventNames = new TString[fInput+1] ; 
604     fEventNames[fInput-1] = tempo ; 
605
606     fInputFileNames[fInput] = alirunFileName ; 
607     fEventNames[fInput]     = eventFolderName ;
608     fInput++ ;
609 }  
610
611 void AliEMCALDigitizer::Print1(Option_t * option)
612 { // 19-nov-04 - just for convinience
613   Print(); 
614   PrintDigits(option);
615 }
616
617 //__________________________________________________________________
618 void AliEMCALDigitizer::Print(Option_t*)const 
619 {
620   // Print Digitizer's parameters
621   printf("Print: \n------------------- %s -------------", GetName() ) ; 
622   if( strcmp(fEventFolderName.Data(), "") != 0 ){
623     printf(" Writing Digits to branch with title  %s\n", fEventFolderName.Data()) ;
624     
625     Int_t nStreams ; 
626     if (fManager) 
627       nStreams =  GetNInputStreams() ;
628     else 
629       nStreams = fInput ; 
630     
631     Int_t index = 0 ;  
632
633     AliRunLoader *rl=0;
634
635     for (index = 0 ; index < nStreams ; index++) {  
636       TString tempo(fEventNames[index]) ; 
637       tempo += index ;
638       if ((rl = AliRunLoader::GetRunLoader(tempo)) == 0)
639         rl = AliRunLoader::Open(fInputFileNames[index], tempo) ; 
640       AliEMCALLoader *emcalLoader = dynamic_cast<AliEMCALLoader*>(rl->GetDetectorLoader("EMCAL"));
641       TString fileName( emcalLoader->GetSDigitsFileName() ) ; 
642       if ( fEventNames[index] != AliConfig::GetDefaultEventFolderName()) // only if not the default folder name 
643         fileName = fileName.ReplaceAll(".root", "") + "_" + fEventNames[index]  + ".root" ;
644       printf ("Adding SDigits from %s %s\n", fInputFileNames[index].Data(), fileName.Data()) ; 
645     }
646
647     AliEMCALLoader *emcalLoader = dynamic_cast<AliEMCALLoader*>(AliRunLoader::GetRunLoader()->GetDetectorLoader("EMCAL"));
648
649     printf("\nWriting digits to %s", emcalLoader->GetDigitsFileName().Data()) ;
650     
651     printf("\nWith following parameters:\n") ;
652     
653     printf("    Electronics noise in EMC (fPinNoise) = %f\n", fPinNoise) ;
654     printf("    Threshold  in EMC  (fDigitThreshold) = %f\n", fDigitThreshold)  ;
655     printf("---------------------------------------------------\n")  ;
656   }
657   else
658     printf("Print: AliEMCALDigitizer not initialized") ; 
659 }
660
661 //__________________________________________________________________
662 void AliEMCALDigitizer::PrintDigits(Option_t * option){
663   AliEMCALLoader *emcalLoader = dynamic_cast<AliEMCALLoader*>(AliRunLoader::GetRunLoader()->GetDetectorLoader("EMCAL"));
664   TClonesArray * digits  = emcalLoader->Digits() ;
665   TClonesArray * sdigits = emcalLoader->SDigits() ;
666   
667   printf("\n #Digits: %d : sdigits %d ", digits->GetEntriesFast(), sdigits->GetEntriesFast()) ; 
668   printf("\n event %d", emcalLoader->GetRunLoader()->GetEventNumber());
669   
670   if(strstr(option,"all")){  
671     //loop over digits
672     AliEMCALDigit * digit;
673     printf("\nEMC digits (with primaries):\n")  ;
674     printf("\n   Id  Amplitude    Time          Index Nprim: Primaries list \n") ;    
675     Int_t index ;
676     for (index = 0 ; index < digits->GetEntries() ; index++) {
677       digit = dynamic_cast<AliEMCALDigit *>(digits->At(index)) ;
678       printf("\n%6d  %8d    %6.5e %4d      %2d : ",
679               digit->GetId(), digit->GetAmp(), digit->GetTime(), digit->GetIndexInList(), digit->GetNprimary()) ;  
680       Int_t iprimary;
681       for (iprimary=0; iprimary<digit->GetNprimary(); iprimary++) {
682         printf("%d ",digit->GetPrimary(iprimary+1) ) ; 
683       }
684     }   
685   }
686   printf("\n");
687 }
688
689 //__________________________________________________________________
690 Float_t AliEMCALDigitizer::TimeOfNoise(void)
691 {  
692   // Calculates the time signal generated by noise
693   //PH  Info("TimeOfNoise", "Change me") ; 
694   return gRandom->Rndm() * 1.28E-5;
695 }
696
697 //__________________________________________________________________
698 void AliEMCALDigitizer::Unload() 
699 {  
700   // Unloads the SDigits and Digits
701   AliRunLoader *rl=0;
702     
703   Int_t i ; 
704   for(i = 1 ; i < fInput ; i++){
705     TString tempo(fEventNames[i]) ; 
706     tempo += i;
707     if ((rl = AliRunLoader::GetRunLoader(tempo))) 
708       rl->GetDetectorLoader("EMCAL")->UnloadSDigits() ; 
709   }
710   AliEMCALLoader *emcalLoader = dynamic_cast<AliEMCALLoader*>(AliRunLoader::GetRunLoader()->GetDetectorLoader("EMCAL"));
711   emcalLoader->UnloadDigits() ; 
712 }
713
714 //_________________________________________________________________________________________
715 void AliEMCALDigitizer::WriteDigits()
716 {
717
718   // Makes TreeD in the output file. 
719   // Check if branch already exists: 
720   //   if yes, exit without writing: ROOT TTree does not support overwriting/updating of 
721   //      already existing branches. 
722   //   else creates branch with Digits, named "EMCAL", title "...",
723   //      and branch "AliEMCALDigitizer", with the same title to keep all the parameters
724   //      and names of files, from which digits are made.
725
726   AliEMCALLoader *emcalLoader = dynamic_cast<AliEMCALLoader*>(AliRunLoader::GetRunLoader()->GetDetectorLoader("EMCAL"));
727
728   const TClonesArray * digits = emcalLoader->Digits() ; 
729   TTree * treeD = emcalLoader->TreeD(); 
730   if ( !treeD ) {
731     emcalLoader->MakeDigitsContainer();
732     treeD = emcalLoader->TreeD(); 
733   }
734
735   // -- create Digits branch
736   Int_t bufferSize = 32000 ;    
737   TBranch * digitsBranch = 0;
738   if ((digitsBranch = treeD->GetBranch("EMCAL")))
739     digitsBranch->SetAddress(&digits);
740   else
741     treeD->Branch("EMCAL","TClonesArray",&digits,bufferSize);
742   //digitsBranch->SetTitle(fEventFolderName);
743   treeD->Fill() ;
744   
745   emcalLoader->WriteDigits("OVERWRITE");
746   emcalLoader->WriteDigitizer("OVERWRITE");
747
748   Unload() ; 
749
750 }
751
752 void AliEMCALDigitizer::Browse(TBrowser* b)
753 {
754   if(fHists) b->Add(fHists);
755   TTask::Browse(b);
756 }
757
758 TList *AliEMCALDigitizer::BookControlHists(int var)
759 { // 22-nov-04
760   Info("BookControlHists"," started ");
761   gROOT->cd();
762   const AliEMCALGeometry *geom = AliEMCALGeometry::GetInstance();
763   if(var>=1){
764     new TH1F("hDigiN",  "#EMCAL digits with fAmp > fDigitThreshold", 
765     fNADCEC+1, -0.5, Double_t(fNADCEC));
766     new TH1F("HDigiSumEnergy","Sum.EMCAL energy from digi", 1000, 0.0, 200.);
767     new TH1F("hDigiAmp",  "EMCAL digital amplitude", fNADCEC+1, -0.5, Double_t(fNADCEC));
768     new TH1F("hDigiEnergy","EMCAL cell energy", 2000, 0.0, 200.);
769     new TH1F("hDigiAbsId","EMCAL absId cells with fAmp > fDigitThreshold ",
770     geom->GetNCells(), 0.5, Double_t(geom->GetNCells())+0.5);
771   }
772
773   fHists = AliEMCALHistoUtilities::MoveHistsToList("EmcalDigiControlHists", kFALSE);
774   fHists = 0; //huh? JLK 03-Mar-2006
775   return fHists;
776 }
777
778 void AliEMCALDigitizer::SaveHists(const char* name, Bool_t kSingleKey, const char* opt)
779 {
780   AliEMCALHistoUtilities::SaveListOfHists(fHists, name, kSingleKey, opt); 
781 }