]> git.uio.no Git - u/mrichter/AliRoot.git/blob - MUON/AliMUONDigitizerV3.cxx
Coding conventions (Ivana)
[u/mrichter/AliRoot.git] / MUON / AliMUONDigitizerV3.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 #include "AliMUONDigitizerV3.h"
19
20 #include "AliLog.h"
21 #include "AliMUON.h"
22 #include "AliMUONCalibrationData.h"
23 #include "AliMUONConstants.h"
24 #include "AliMUONData.h"
25 #include "AliMUONDataIterator.h"
26 #include "AliMUONDigit.h"
27 #include "AliMUONSegmentation.h"
28 #include "AliMUONTriggerDecisionV1.h"
29 #include "AliMUONTriggerEfficiencyCells.h"
30 #include "AliMUONTriggerElectronics.h"
31 #include "AliMUONVCalibParam.h"
32 #include "AliMpDEIterator.h"
33 #include "AliMpDEManager.h"
34 #include "AliMpIntPair.h"
35 #include "AliMpPad.h"
36 #include "AliMpStationType.h"
37 #include "AliMpVSegmentation.h"
38 #include "AliRun.h"
39 #include "AliRunDigitizer.h"
40 #include "AliRunLoader.h"
41 #include "Riostream.h"
42 #include "TF1.h"
43 #include "TRandom.h"
44 #include "TString.h"
45
46 ///
47 /// The digitizer is performing the transformation to go from SDigits (digits
48 /// w/o any electronic noise) to Digits (w/ electronic noise, and decalibration)
49 /// 
50 /// The decalibration is performed by doing the reverse operation of the
51 /// calibration, that is we do (Signal+pedestal)/gain -> ADC
52 ///
53 /// Note also that the digitizer takes care of merging sdigits that belongs
54 /// to the same pad, either because we're merging several input sdigit files
55 /// or with a single file because the sdigitizer does not merge sdigits itself
56 /// (for performance reason mainly, and because anyway we know we have to do it
57 /// here, at the digitization level).
58 ///
59
60 namespace
61 {
62   AliMUON* muon()
63   {
64     return static_cast<AliMUON*>(gAlice->GetModule("MUON"));
65   }
66
67   AliMUONSegmentation* Segmentation()
68   {
69     static AliMUONSegmentation* segmentation = muon()->GetSegmentation();
70     return segmentation;
71   }
72 }
73
74 const Double_t AliMUONDigitizerV3::fgkNSigmas=3;
75
76 ClassImp(AliMUONDigitizerV3)
77
78 //_____________________________________________________________________________
79 AliMUONDigitizerV3::AliMUONDigitizerV3(AliRunDigitizer* manager, 
80                                        ETriggerCodeVersion triggerCodeVersion,
81                                        Bool_t useTriggerEfficiency,
82                                        Bool_t generateNoisyDigits)
83 : AliDigitizer(manager),
84 fIsInitialized(kFALSE),
85 fOutputData(0x0),
86 fCalibrationData(0x0),
87 fTriggerProcessor(0x0),
88 fTriggerCodeVersion(triggerCodeVersion),
89 fUseTriggerEfficiency(useTriggerEfficiency),
90 fTriggerEfficiency(0x0),
91 fNoiseFunction(0x0),
92 fGenerateNoisyDigits(generateNoisyDigits)
93 {
94   //
95   // Ctor.
96   //
97   AliDebug(1,Form("AliRunDigitizer=%p",fManager));
98   fGenerateNoisyDigitsTimer.Start(kTRUE); fGenerateNoisyDigitsTimer.Stop();
99   fExecTimer.Start(kTRUE); fExecTimer.Stop();
100   fFindDigitIndexTimer.Start(kTRUE); fFindDigitIndexTimer.Stop();
101 }
102
103 //______________________________________________________________________________
104 AliMUONDigitizerV3::AliMUONDigitizerV3(const AliMUONDigitizerV3& right) 
105   : AliDigitizer(right) 
106 {  
107 /// Protected copy constructor (not implemented)
108
109   AliFatal("Copy constructor not provided.");
110 }
111
112 //_____________________________________________________________________________
113 AliMUONDigitizerV3::~AliMUONDigitizerV3()
114 {
115   //
116   // Dtor. Note we're the owner of some pointers.
117   // 
118   AliDebug(1,"dtor");
119
120   delete fOutputData;
121   delete fCalibrationData;
122   delete fTriggerProcessor;
123   delete fNoiseFunction;
124   
125   AliInfo(Form("Execution time for FindDigitIndex() : R:%.2fs C:%.2fs",
126                fFindDigitIndexTimer.RealTime(),fFindDigitIndexTimer.CpuTime()));
127   if ( fGenerateNoisyDigits )
128   {
129     AliInfo(Form("Execution time for GenerateNoisyDigits() : R:%.2fs C:%.2fs",
130                  fGenerateNoisyDigitsTimer.RealTime(),
131                  fGenerateNoisyDigitsTimer.CpuTime()));
132   }
133   AliInfo(Form("Execution time for Exec() : R:%.2fs C:%.2fs",
134                fExecTimer.RealTime(),fExecTimer.CpuTime()));
135   
136 }
137
138 //______________________________________________________________________________
139 AliMUONDigitizerV3& 
140 AliMUONDigitizerV3::operator=(const AliMUONDigitizerV3& right)
141 {
142 /// Protected assignement operator (not implemented)
143
144   // check assignement to self
145   if (this == &right) return *this;
146
147   AliFatal("Assignement operator not provided.");
148     
149   return *this;  
150 }    
151
152 //_____________________________________________________________________________
153 void 
154 AliMUONDigitizerV3::ApplyResponseToTrackerDigit(AliMUONDigit& digit, Bool_t addNoise)
155 {
156   // For tracking digits, starting from an ideal digit's charge, we :
157   //
158   // - add some noise (thus leading to a realistic charge), if requested to do so
159   // - divide by a gain (thus decalibrating the digit)
160   // - add a pedestal (thus decalibrating the digit)
161   // - sets the signal to zero if below 3*sigma of the noise
162   //
163
164   static const Int_t kMaxADC = (1<<12)-1; // We code the charge on a 12 bits ADC.
165
166   Float_t signal = digit.Signal();
167
168   if ( !addNoise )
169     {
170       digit.SetADC(TMath::Nint(signal));
171       return;
172     }
173   
174   Int_t detElemId = digit.DetElemId();
175   
176   Int_t manuId = digit.ManuId();
177   Int_t manuChannel = digit.ManuChannel();
178   
179   AliMUONVCalibParam* pedestal = fCalibrationData->Pedestals(detElemId,manuId);
180   if (!pedestal)
181     {
182       AliFatal(Form("Could not get pedestal for DE=%d manuId=%d",
183                     detElemId,manuId));    
184     }
185   Float_t pedestalMean = pedestal->ValueAsFloat(manuChannel,0);
186   Float_t pedestalSigma = pedestal->ValueAsFloat(manuChannel,1);
187   
188   AliMUONVCalibParam* gain = fCalibrationData->Gains(detElemId,manuId);
189   if (!gain)
190     {
191       AliFatal(Form("Could not get gain for DE=%d manuId=%d",
192                     detElemId,manuId));    
193     }    
194   Float_t gainMean = gain->ValueAsFloat(manuChannel,0);
195
196   Float_t adcNoise = gRandom->Gaus(0.0,pedestalSigma);
197      
198   Int_t adc;
199
200   if ( gainMean < 1E-6 )
201     {
202       AliError(Form("Got a too small gain %e for DE=%d manuId=%d manuChannel=%d. "
203                     "Setting signal to 0.",
204                     gainMean,detElemId,manuId,manuChannel));
205       adc = 0;
206     }
207   else
208     {
209       adc = TMath::Nint( signal / gainMean + pedestalMean + adcNoise);///
210       
211       if ( adc <= pedestalMean + fgkNSigmas*pedestalSigma ) 
212         {
213           adc = 0;
214         }
215     }
216   
217   // be sure we stick to 12 bits.
218   if ( adc > kMaxADC )
219     {
220       adc = kMaxADC;
221     }
222   
223   digit.SetPhysicsSignal(TMath::Nint(signal));
224   digit.SetSignal(adc);
225   digit.SetADC(adc);
226 }
227
228 //_____________________________________________________________________________
229 void 
230 AliMUONDigitizerV3::ApplyResponseToTriggerDigit(AliMUONDigit& digit,
231                                                 AliMUONData* data)
232 {
233   if ( !fTriggerEfficiency ) return;
234
235   AliMUONDigit* correspondingDigit = FindCorrespondingDigit(digit,data);
236
237   if(!correspondingDigit)return;//reject bad correspondences
238
239   Int_t detElemId = digit.DetElemId();
240   
241   const AliMpVSegmentation* segment[2] = 
242   {
243     Segmentation()->GetMpSegmentation(detElemId,digit.Cathode()), 
244     Segmentation()->GetMpSegmentation(detElemId,correspondingDigit->Cathode())
245   };
246
247   AliMpPad pad[2] = 
248   {
249     segment[0]->PadByIndices(AliMpIntPair(digit.PadX(),digit.PadY()),kTRUE), 
250     segment[1]->PadByIndices(AliMpIntPair(correspondingDigit->PadX(),correspondingDigit->PadY()),kTRUE)
251   };
252
253   Int_t ix(0);
254   Int_t iy(1);
255
256   if (digit.Cathode()==0)
257   {
258           ix=1;
259           iy=0;
260   }
261   
262   Float_t x = pad[ix].Position().X();
263   Float_t y = pad[iy].Position().Y();
264   if ( x==-1 && y==-1 )
265   {
266           x=-9999.;
267           y=-9999.;
268     AliError(Form("Got an unknown position for a digit in DE %d at (ix,iy)=(%d,%d)",
269              detElemId,pad[ix].GetIndices().GetFirst(),pad[iy].GetIndices().GetSecond()));
270   }
271   Float_t x0 = segment[0]->Dimensions().X();
272   Float_t y0 = segment[1]->Dimensions().Y();
273   TVector2 newCoord = fTriggerEfficiency->ChangeReferenceFrame(x, y, x0, y0);
274   
275   Bool_t isTrig[2];
276   fTriggerEfficiency->IsTriggered(detElemId, newCoord.Px(), newCoord.Py(), 
277                                   isTrig[0], isTrig[1]);
278   
279   if (!isTrig[digit.Cathode()])
280   {
281           digit.SetSignal(0);
282   }
283   
284   if ( &digit != correspondingDigit )
285   {
286           if (!isTrig[correspondingDigit->Cathode()])
287     {
288       correspondingDigit->SetSignal(0);
289           }
290   }
291 }
292
293 //_____________________________________________________________________________
294 void
295 AliMUONDigitizerV3::ApplyResponse()
296 {
297   //
298   // Loop over all chamber digits, and apply the response to them
299   // Note that this method may remove digits.
300   //
301   const Bool_t kAddNoise = kTRUE;
302   
303   for ( Int_t ich = 0; ich < AliMUONConstants::NCh(); ++ich )
304   {
305     TClonesArray* digits = fOutputData->Digits(ich);
306     Int_t n = digits->GetEntriesFast();
307     Bool_t trackingChamber = ( ich < AliMUONConstants::NTrackingCh() );
308     for ( Int_t i = 0; i < n; ++i )
309     {
310       AliMUONDigit* d = static_cast<AliMUONDigit*>(digits->UncheckedAt(i));
311       if ( trackingChamber )
312       {
313         ApplyResponseToTrackerDigit(*d,kAddNoise);
314       }
315       else
316       {
317         ApplyResponseToTriggerDigit(*d,fOutputData);
318       }
319       if ( d->Signal() <= 0 )
320       {
321         digits->RemoveAt(i);
322       }
323     }
324     digits->Compress();
325   }    
326   
327 // The version below, using iterator, does not yet work (as the iterator
328 // assumes it is reading digits from the tree, while in this case it's
329 // writing...)
330 //
331 //  AliMUONDigit* digit(0x0);
332 //
333 //  // First loop on tracker digits
334 //  AliMUONDataIterator tracker(fOutputData,"D",AliMUONDataIterator::kTrackingChambers);
335 //  
336 //  while ( ( digit = static_cast<AliMUONDigit*>(tracker.Next()) ) )
337 //  {
338 //    ApplyResponseToTrackerDigit(*digit);
339 //    if ( digit->Signal() <= 0 )
340 //    {
341 //      tracker.Remove();
342 //    }    
343 //    
344 //  }
345 //
346 //  // Then loop on trigger digits
347 //  AliMUONDataIterator trigger(fOutputData,"D",AliMUONDataIterator::kTriggerChambers);
348 //  
349 //  while ( ( digit = static_cast<AliMUONDigit*>(trigger.Next()) ) )
350 //  {
351 //    ApplyResponseToTriggerDigit(*digit,fOutputData);
352 //    if ( digit->Signal() <= 0 )
353 //    {
354 //      trigger.Remove();
355 //    }    
356 //  }
357 }
358
359 //_____________________________________________________________________________
360 void
361 AliMUONDigitizerV3::AddOrUpdateDigit(TClonesArray& array, 
362                                      const AliMUONDigit& digit)
363 {
364   //
365   // Add or update a digit, depending on whether there's already a digit
366   // for the corresponding channel.
367   //
368   Int_t ix = FindDigitIndex(array,digit);
369   
370   if (ix>=0)
371   {
372     AliMUONDigit* d = static_cast<AliMUONDigit*>(array.UncheckedAt(ix));
373     Bool_t ok = MergeDigits(digit,*d);
374     if (!ok)
375     {
376       AliError("Digits are not mergeable !");
377     }
378   }
379   else
380   {
381     ix = array.GetLast() + 1;
382     new(array[ix]) AliMUONDigit(digit);
383   }
384   
385 }
386
387 //_____________________________________________________________________________
388 void
389 AliMUONDigitizerV3::Exec(Option_t*)
390 {
391   //
392   // Main method.
393   // We first loop over input files, and merge the sdigits we found there.
394   // Second, we digitize all the resulting sdigits
395   // Then we generate noise-only digits (for tracker only)
396   // And we finally generate the trigger outputs.
397   //
398     
399   AliDebug(1, "Running digitizer.");
400   
401   if ( fManager->GetNinputs() == 0 )
402   {
403     AliWarning("No input set. Nothing to do.");
404     return;
405   }
406   
407   if ( !fIsInitialized )
408   {
409     AliError("Not initialized. Cannot perform the work. Sorry");
410     return;
411   }
412   
413   fExecTimer.Start(kFALSE);
414
415   Int_t nInputFiles = fManager->GetNinputs();
416   
417   if ( fOutputData->TreeD() == 0x0 )
418   {
419     AliDebug(1,"Calling MakeDigitsContainer");
420     fOutputData->GetLoader()->MakeDigitsContainer();
421   }
422   fOutputData->MakeBranch("D,GLT");
423   fOutputData->SetTreeAddress("D,GLT");
424   
425   // Loop over all the input files, and merge the sdigits found in those
426   // files.
427   for ( Int_t iFile = 0; iFile < nInputFiles; ++iFile )
428   {    
429     AliMUONData* inputData = GetDataAccess(fManager->GetInputFolderName(iFile));
430     if (!inputData)
431     {
432       AliFatal(Form("Could not get access to input file #%d",iFile));
433     }
434
435     inputData->GetLoader()->LoadSDigits("READ");
436     inputData->SetTreeAddress("S");
437     inputData->GetSDigits();
438
439     MergeWithSDigits(*fOutputData,*inputData,fManager->GetMask(iFile));
440     
441     inputData->ResetSDigits();
442     inputData->GetLoader()->UnloadSDigits();
443     delete inputData;
444   }
445   
446   // At this point, we do have digit arrays (one per chamber) which contains 
447   // the merging of all the sdigits of the input file(s).
448   // We now massage them to apply the detector response, i.e. this
449   // is here that we do the "digitization" work.
450   
451   ApplyResponse();
452   
453   if ( fGenerateNoisyDigits )
454   {
455     // Generate noise-only digits for tracker.
456     GenerateNoisyDigits();
457   }
458   
459   // We generate the global and local trigger decisions.
460   fTriggerProcessor->ExecuteTask();
461   
462   // Fill the output treeD
463   fOutputData->Fill("D,GLT");
464   
465   // Write to the output tree(D).
466   // Please note that as GlobalTrigger, LocalTrigger and Digits are in the same
467   // tree (=TreeD) in different branches, this WriteDigits in fact writes all of 
468   // the 3 branches.
469   fOutputData->GetLoader()->WriteDigits("OVERWRITE");
470   
471   // Finally, we clean up after ourselves.
472   fOutputData->ResetDigits();
473   fOutputData->ResetTrigger();
474   fOutputData->GetLoader()->UnloadDigits();
475   
476   fExecTimer.Stop();
477 }
478
479 //_____________________________________________________________________________
480 AliMUONDigit* 
481 AliMUONDigitizerV3::FindCorrespondingDigit(AliMUONDigit& digit,
482                                            AliMUONData* data)
483 {                                                
484   AliMUONDataIterator it(data,"D",AliMUONDataIterator::kTriggerChambers);
485   AliMUONDigit* cd;
486
487   for(;;){
488       cd = static_cast<AliMUONDigit*>(it.Next());
489       if(!cd)continue;
490       if (cd->DetElemId() == digit.DetElemId() &&
491           cd->PadX() == digit.PadX() &&
492           cd->PadY() == digit.PadY() && 
493           cd->Cathode() == digit.Cathode()){
494           break;
495       }
496   }
497   //The corresponding digit is searched only forward in the AliMUONData.
498   //In this way when the first digit of the couple is given, the second digit is found and the efficiency is applied to both. 
499   //Afterwards, when the second digit of the couple is given the first one is not found and hence efficiency is not applied again
500   
501   while ( ( cd = static_cast<AliMUONDigit*>(it.Next()) ) )
502   {
503     if(!cd)continue;//avoid problems when 1 digit is removed
504     if ( cd->DetElemId() == digit.DetElemId() &&
505          cd->Hit() == digit.Hit() &&
506          cd->Cathode() != digit.Cathode() )
507     {
508       return cd;
509     }
510   }
511   return 0x0;
512 }
513
514
515 //_____________________________________________________________________________
516 Int_t
517 AliMUONDigitizerV3::FindDigitIndex(TClonesArray& array, 
518                                    const AliMUONDigit& digit) const
519 {
520   // 
521   // Return the index of digit within array, if that digit is there, 
522   // otherwise returns -1
523   //
524   // FIXME: this is of course not the best implementation you can think of.
525   // Reconsider the use of hit/digit map... ? (but be sure it's needed!)
526   //
527   
528   fFindDigitIndexTimer.Start(kFALSE);
529   
530   Int_t n = array.GetEntriesFast();
531   for ( Int_t i = 0; i < n; ++i )
532   {
533     AliMUONDigit* d = static_cast<AliMUONDigit*>(array.UncheckedAt(i));
534     if ( d->DetElemId() == digit.DetElemId() &&
535          d->PadX() == digit.PadX() &&
536          d->PadY() == digit.PadY() && 
537          d->Cathode() == digit.Cathode() )
538     {
539       fFindDigitIndexTimer.Stop();
540       return i;
541     }
542   }
543   fFindDigitIndexTimer.Stop();
544   return -1;
545 }
546
547 //_____________________________________________________________________________
548 void
549 AliMUONDigitizerV3::GenerateNoisyDigits()
550 {
551   //
552   // According to a given probability, generate digits that
553   // have a signal above the noise cut (ped+n*sigma_ped), i.e. digits
554   // that are "only noise".
555   //
556   
557   if ( !fNoiseFunction )
558   {
559     fNoiseFunction = new TF1("AliMUONDigitizerV3::fNoiseFunction","gaus",
560                              fgkNSigmas,fgkNSigmas*10);
561     
562     fNoiseFunction->SetParameters(1,0,1);
563   }
564   
565   fGenerateNoisyDigitsTimer.Start(kFALSE);
566   
567   for ( Int_t i = 0; i < AliMUONConstants::NTrackingCh(); ++i )
568   {
569     AliMpDEIterator it;
570   
571     it.First(i);
572   
573     while ( !it.IsDone() )
574     {
575       for ( Int_t cathode = 0; cathode < 2; ++cathode )
576       {
577         GenerateNoisyDigitsForOneCathode(it.CurrentDE(),cathode);
578       }
579       it.Next();
580     }
581   }
582   
583   fGenerateNoisyDigitsTimer.Stop();
584 }
585  
586 //_____________________________________________________________________________
587 void
588 AliMUONDigitizerV3::GenerateNoisyDigitsForOneCathode(Int_t detElemId, Int_t cathode)
589 {
590   //
591   // Generate noise-only digits for one cathode of one detection element.
592   // Called by GenerateNoisyDigits()
593   //
594   
595   TClonesArray* digits = fOutputData->Digits(detElemId/100-1);
596   
597   const AliMpVSegmentation* seg = Segmentation()->GetMpSegmentation(detElemId,cathode);
598   Int_t nofPads = seg->NofPads();
599   
600   Int_t maxIx = seg->MaxPadIndexX();
601   Int_t maxIy = seg->MaxPadIndexY();
602   
603   static const Double_t kProbToBeOutsideNsigmas = 1 - TMath::Erf(fgkNSigmas/TMath::Sqrt(2.0));
604   
605   Int_t nofNoisyPads = TMath::Nint(kProbToBeOutsideNsigmas*nofPads);
606   if ( !nofNoisyPads ) return;
607   
608   nofNoisyPads = 
609     TMath::Nint(gRandom->Gaus(nofNoisyPads,
610                               nofNoisyPads/TMath::Sqrt(nofNoisyPads)));
611   
612   AliDebug(3,Form("DE %d cath %d nofNoisyPads %d",detElemId,cathode,nofNoisyPads));
613   
614   for ( Int_t i = 0; i < nofNoisyPads; ++i )
615   {
616     Int_t ix(-1);
617     Int_t iy(-1);
618     do {
619       ix = gRandom->Integer(maxIx+1);
620       iy = gRandom->Integer(maxIy+1);
621     } while ( !seg->HasPad(AliMpIntPair(ix,iy)) );
622     AliMUONDigit d;
623     d.SetDetElemId(detElemId);
624     d.SetCathode(cathode);
625     d.SetPadX(ix);
626     d.SetPadY(iy);
627     if ( FindDigitIndex(*digits,d) >= 0 )
628     {
629       // this digit is already there, and not noise-only, we simply skip it
630       continue;
631     }
632     AliMpPad pad = seg->PadByIndices(AliMpIntPair(ix,iy));
633     Int_t manuId = pad.GetLocation().GetFirst();
634     Int_t manuChannel = pad.GetLocation().GetSecond();
635     
636     d.SetElectronics(manuId,manuChannel);
637     
638     AliMUONVCalibParam* pedestals = fCalibrationData->Pedestals(detElemId,manuId);
639     
640     Float_t pedestalMean = pedestals->ValueAsFloat(manuChannel,0);
641     Float_t pedestalSigma = pedestals->ValueAsFloat(manuChannel,1);
642     
643     Double_t ped = fNoiseFunction->GetRandom()*pedestalSigma;
644
645     d.SetSignal(TMath::Nint(ped+pedestalMean+0.5));
646     d.SetPhysicsSignal(0);
647     d.NoiseOnly(kTRUE);
648     AliDebug(3,Form("Adding a pure noise digit :"));
649     StdoutToAliDebug(3,cout << "Before Response: " << endl; 
650                      d.Print(););
651     ApplyResponseToTrackerDigit(d,kFALSE);
652     if ( d.Signal() > 0 )
653     {
654       AddOrUpdateDigit(*digits,d);
655     }
656     else
657     {
658       AliError("Pure noise below threshold. This should not happen. Not adding "
659                "this digit.");
660     }
661     StdoutToAliDebug(3,cout << "After Response: " << endl; 
662                      d.Print(););
663   }
664 }
665
666 //_____________________________________________________________________________
667 AliMUONData* 
668 AliMUONDigitizerV3::GetDataAccess(const TString& folderName)
669 {
670   //
671   // Create an AliMUONData to deal with data found in folderName.
672   //
673   AliDebug(1,Form("Getting access to folder %s",folderName.Data()));
674   AliRunLoader* runLoader = AliRunLoader::GetRunLoader(folderName);
675   if (!runLoader)
676   {
677     AliError(Form("Could not get RunLoader from folder %s",folderName.Data()));
678     return 0x0;
679   }
680   AliLoader* loader = static_cast<AliLoader*>(runLoader->GetLoader("MUONLoader"));
681   if (!loader)
682   {
683     AliError(Form("Could not get MuonLoader from folder %s",folderName.Data()));
684     return 0x0;
685   }
686   AliMUONData* data = new AliMUONData(loader,"MUON","MUONDataForDigitOutput");
687   AliDebug(1,Form("AliMUONData=%p loader=%p",data,loader));
688   return data;
689 }
690
691 //_____________________________________________________________________________
692 Bool_t
693 AliMUONDigitizerV3::Init()
694 {
695   //
696   // Initialization of the TTask :
697   // a) set the outputData pointer
698   // b) create the calibrationData, according to run number
699   // c) create the trigger processing task
700   //
701   AliDebug(1,"");
702   
703   if ( fIsInitialized )
704   {
705     AliError("Object already initialized.");
706     return kFALSE;
707   }
708   
709   if (!fManager)
710   {
711     AliError("fManager is null !");
712     return kFALSE;
713   }
714   
715   fOutputData = GetDataAccess(fManager->GetOutputFolderName());
716   if (!fOutputData)
717   {
718     AliError("Can not perform digitization. I'm sorry");
719     return kFALSE;
720   }
721   AliDebug(1,Form("fOutputData=%p",fOutputData));
722   
723   AliRunLoader* runLoader = fOutputData->GetLoader()->GetRunLoader();
724   AliRun* galice = runLoader->GetAliRun();  
725   Int_t runnumber = galice->GetRunNumber();
726   
727   fCalibrationData = new AliMUONCalibrationData(runnumber);
728   
729   switch (fTriggerCodeVersion)
730   {
731     case kTriggerDecision:
732       fTriggerProcessor = new AliMUONTriggerDecisionV1(fOutputData);
733       break;
734     case kTriggerElectronics:
735       fTriggerProcessor = new AliMUONTriggerElectronics(fOutputData,fCalibrationData);
736       break;
737     default:
738       AliFatal("Unknown trigger processor type");
739       break;
740   }
741   AliDebug(1,Form("Using the following trigger code %s - %s",
742                   fTriggerProcessor->GetName(),fTriggerProcessor->GetTitle()));
743   
744   if ( fUseTriggerEfficiency )
745   {
746     fTriggerEfficiency = fCalibrationData->TriggerEfficiency();
747     if ( fTriggerEfficiency )
748     {
749       AliInfo("Will apply trigger efficiency");
750     }
751     else
752     {
753       AliError("I was requested to apply trigger efficiency, but I could "
754                "not get it !");
755     }
756   }
757   
758   if ( fGenerateNoisyDigits )
759   {
760     AliInfo("Will generate noise-only digits for tracker");
761   }
762   
763   fIsInitialized = kTRUE;
764   return kTRUE;
765 }
766
767 //_____________________________________________________________________________
768 Bool_t
769 AliMUONDigitizerV3::MergeDigits(const AliMUONDigit& src, 
770                                 AliMUONDigit& srcAndDest)
771 {
772   //
773   // Merge 2 digits (src and srcAndDest) into srcAndDest.
774   //
775   AliDebug(1,"Merging the following digits:");
776   StdoutToAliDebug(1,src.Print("tracks"););
777   StdoutToAliDebug(1,srcAndDest.Print("tracks"););
778   
779   Bool_t check = ( src.DetElemId() == srcAndDest.DetElemId() &&
780                    src.PadX() == srcAndDest.PadX() &&
781                    src.PadY() == srcAndDest.PadY() &&
782                    src.Cathode() == srcAndDest.Cathode() );
783   if (!check)
784   {
785     return kFALSE;
786   }
787   
788   srcAndDest.AddSignal(src.Signal());
789   srcAndDest.AddPhysicsSignal(src.Physics());
790   for ( Int_t i = 0; i < src.Ntracks(); ++i )
791   {
792     srcAndDest.AddTrack(src.Track(i),src.TrackCharge(i));
793   }
794   StdoutToAliDebug(1,cout << "result:"; srcAndDest.Print("tracks"););
795   return kTRUE;
796 }
797
798 //_____________________________________________________________________________
799 void 
800 AliMUONDigitizerV3::MergeWithSDigits(AliMUONData& outputData, 
801                                      const AliMUONData& inputData, Int_t mask)
802 {
803   //
804   // Merge the sdigits in inputData with the digits already present in outputData
805   //
806   AliDebug(1,"");
807   
808         for ( Int_t ich = 0; ich < AliMUONConstants::NCh(); ++ich )
809         {
810     TClonesArray* iDigits = inputData.SDigits(ich); 
811     TClonesArray* oDigits = outputData.Digits(ich);
812     if (!iDigits)
813     {
814       AliError(Form("Could not get sdigits for ich=%d",ich));
815       return;
816     }
817     Int_t nSDigits = iDigits->GetEntriesFast();
818     for ( Int_t k = 0; k < nSDigits; ++k )
819                 {
820                         AliMUONDigit* sdigit = static_cast<AliMUONDigit*>(iDigits->UncheckedAt(k));
821       if (!sdigit)
822       {
823         AliError(Form("Could not get sdigit for ich=%d and k=%d",ich,k));
824       }
825       else
826       {
827         // Update the track references using the mask.
828         // FIXME: this is dirty, for backward compatibility only.
829         // Should re-design all this way of keeping track of MC information...
830         if ( mask ) sdigit->PatchTracks(mask);
831         // Then add or update the digit to the output.
832         AddOrUpdateDigit(*oDigits,*sdigit);
833       }
834                 }   
835   }
836 }