]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - MUON/AliMUONDigitizerV3.cxx
Being more realistic with gain calibration (Laurent)
[u/mrichter/AliRoot.git] / MUON / AliMUONDigitizerV3.cxx
index c54f44bb0f7fdb8f3eca75946d2515c51b72c136..d391b4002abb38edf2e1e0fc4a21b7b7748fd36c 100644 (file)
 
 #include "AliMUONDigitizerV3.h"
 
+#include "AliCDBManager.h"
+#include "AliLog.h"
 #include "AliMUON.h"
 #include "AliMUONCalibrationData.h"
 #include "AliMUONConstants.h"
-#include "AliMUONData.h"
-#include "AliMUONDataIterator.h"
 #include "AliMUONDigit.h"
-#include "AliMUONSegmentation.h"
+#include "AliMUONLogger.h"
 #include "AliMUONTriggerEfficiencyCells.h"
 #include "AliMUONTriggerElectronics.h"
+#include "AliMUONTriggerStoreV1.h"
 #include "AliMUONVCalibParam.h"
-
+#include "AliMUONVDigitStore.h"
+#include "AliMpCathodType.h"
+#include "AliMpConstants.h"
 #include "AliMpDEIterator.h"
 #include "AliMpDEManager.h"
+#include "AliMpDEManager.h"
 #include "AliMpIntPair.h"
 #include "AliMpPad.h"
-#include "AliMpStationType.h"
 #include "AliMpSegmentation.h"
+#include "AliMpStationType.h"
 #include "AliMpVSegmentation.h"
-#include "AliMpDEManager.h"
-#include "AliMpCathodType.h"
-
 #include "AliRun.h"
 #include "AliRunDigitizer.h"
 #include "AliRunLoader.h"
-#include "AliLog.h"
-
 #include <Riostream.h>
 #include <TF1.h>
+#include <TFile.h>
 #include <TMath.h>
 #include <TRandom.h>
 #include <TString.h>
+#include <TSystem.h>
+
+#include "AliMUONGeometryTransformer.h" //ADDED for trigger noise
 ///
 /// \class AliMUONDigitizerV3
 /// The digitizer is performing the transformation to go from SDigits (digits
@@ -63,6 +66,7 @@
 /// (for performance reason mainly, and because anyway we know we have to do it
 /// here, at the digitization level).
 ///
+/// \author Laurent Aphecetche
 
 namespace
 {
@@ -70,6 +74,12 @@ namespace
   {
     return static_cast<AliMUON*>(gAlice->GetModule("MUON"));
   }
+
+  //ADDED for trigger noise
+  const AliMUONGeometryTransformer* GetTransformer()
+  {
+      return muon()->GetGeometryTransformer();
+  }
 }
 
 const Double_t AliMUONDigitizerV3::fgkNSigmas=3;
@@ -80,25 +90,27 @@ ClassImp(AliMUONDigitizerV3)
 
 //_____________________________________________________________________________
 AliMUONDigitizerV3::AliMUONDigitizerV3(AliRunDigitizer* manager, 
-                                       Bool_t generateNoisyDigits)
+                                       Int_t generateNoisyDigits)
 : AliDigitizer(manager),
 fIsInitialized(kFALSE),
-fOutputData(0x0),
 fCalibrationData(0x0),
 fTriggerProcessor(0x0),
 fTriggerEfficiency(0x0),
-fFindDigitIndexTimer(),
 fGenerateNoisyDigitsTimer(),
 fExecTimer(),
 fNoiseFunction(0x0),
-fGenerateNoisyDigits(generateNoisyDigits)
+fNoiseFunctionTrig(0x0),
+  fGenerateNoisyDigits(generateNoisyDigits),
+  fLogger(new AliMUONLogger(1000)),
+fTriggerStore(new AliMUONTriggerStoreV1),
+fDigitStore(0x0),
+fOutputDigitStore(0x0)
 {
   /// Ctor.
 
   AliDebug(1,Form("AliRunDigitizer=%p",fManager));
   fGenerateNoisyDigitsTimer.Start(kTRUE); fGenerateNoisyDigitsTimer.Stop();
   fExecTimer.Start(kTRUE); fExecTimer.Stop();
-  fFindDigitIndexTimer.Start(kTRUE); fFindDigitIndexTimer.Stop();
 }
 
 //_____________________________________________________________________________
@@ -108,13 +120,14 @@ AliMUONDigitizerV3::~AliMUONDigitizerV3()
 
   AliDebug(1,"dtor");
 
-  delete fOutputData;
   delete fCalibrationData;
   delete fTriggerProcessor;
   delete fNoiseFunction;
+  delete fNoiseFunctionTrig;
+  delete fTriggerStore;
+  delete fDigitStore;
+  delete fOutputDigitStore;
   
-  AliDebug(1, Form("Execution time for FindDigitIndex() : R:%.2fs C:%.2fs",
-               fFindDigitIndexTimer.RealTime(),fFindDigitIndexTimer.CpuTime()));
   if ( fGenerateNoisyDigits )
   {
     AliDebug(1, Form("Execution time for GenerateNoisyDigits() : R:%.2fs C:%.2fs",
@@ -123,29 +136,37 @@ AliMUONDigitizerV3::~AliMUONDigitizerV3()
   }
   AliDebug(1, Form("Execution time for Exec() : R:%.2fs C:%.2fs",
                fExecTimer.RealTime(),fExecTimer.CpuTime()));
+  AliInfo("Summary of messages");
+  fLogger->Print();
   
+  delete fLogger;
 }
 
 //_____________________________________________________________________________
 void 
-AliMUONDigitizerV3::ApplyResponseToTrackerDigit(AliMUONDigit& digit, Bool_t addNoise)
+AliMUONDigitizerV3::ApplyResponseToTrackerDigit(AliMUONVDigit& digit, Bool_t addNoise)
 {
   /// For tracking digits, starting from an ideal digit's charge, we :
   ///
   /// - add some noise (thus leading to a realistic charge), if requested to do so
-  /// - divide by a gain (thus decalibrating the digit)
+  /// - "divide" by a gain (thus decalibrating the digit)
   /// - add a pedestal (thus decalibrating the digit)
   /// - sets the signal to zero if below 3*sigma of the noise
 
   static const Int_t kMaxADC = (1<<12)-1; // We code the charge on a 12 bits ADC.
-
-  Float_t signal = digit.Signal();
-
+  
+  Float_t charge = digit.Charge();
+  
+  // We set the charge to 0, as the only relevant piece of information
+  // after Digitization is the ADC value.  
+  digit.SetCharge(0);
+  
   if ( !addNoise )
-    {
-      digit.SetADC(TMath::Nint(signal));
-      return;
-    }
+  {
+    digit.SetADC(TMath::Min(kMaxADC,TMath::Nint(charge)));
+    return;
+  }
   
   Int_t detElemId = digit.DetElemId();
   
@@ -154,65 +175,88 @@ AliMUONDigitizerV3::ApplyResponseToTrackerDigit(AliMUONDigit& digit, Bool_t addN
   
   AliMUONVCalibParam* pedestal = fCalibrationData->Pedestals(detElemId,manuId);
   if (!pedestal)
-    {
-      AliFatal(Form("Could not get pedestal for DE=%d manuId=%d",
-                   detElemId,manuId));    
-    }
+  {
+    fLogger->Log(Form("%s:%d:Could not get pedestal for DE=%4d manuId=%4d. Disabling.",
+                      __FILE__,__LINE__,
+                      detElemId,manuId));
+    digit.SetADC(0);
+    return;    
+  }
   Float_t pedestalMean = pedestal->ValueAsFloat(manuChannel,0);
   Float_t pedestalSigma = pedestal->ValueAsFloat(manuChannel,1);
   
   AliMUONVCalibParam* gain = fCalibrationData->Gains(detElemId,manuId);
   if (!gain)
-    {
-      AliFatal(Form("Could not get gain for DE=%d manuId=%d",
-                   detElemId,manuId));    
-    }    
-  Float_t gainMean = gain->ValueAsFloat(manuChannel,0);
+  {
+    fLogger->Log(Form("%s:%d:Could not get gain for DE=%4d manuId=%4d. Disabling.",
+                      __FILE__,__LINE__,
+                      detElemId,manuId));
+    digit.SetADC(0);
+    return;        
+  }    
 
-  Float_t adcNoise = gRandom->Gaus(0.0,pedestalSigma);
-     
-  Int_t adc;
+  Float_t a0 = gain->ValueAsFloat(manuChannel,0);
+  Float_t a1 = gain->ValueAsFloat(manuChannel,1);
 
-  if ( gainMean < 1E-6 )
-    {
-      AliError(Form("Got a too small gain %e for DE=%d manuId=%d manuChannel=%d. "
-                   "Setting signal to 0.",
-                   gainMean,detElemId,manuId,manuChannel));
-      adc = 0;
-    }
-  else
+  Int_t thres = gain->ValueAsInt(manuChannel,2);
+  Float_t chargeThres = a0*thres;
+  
+  Float_t padc(0); // (adc - ped) value
+  
+  if ( charge <= chargeThres || TMath::Abs(a1) < 1E-12 ) 
+  {
+    // linear part only
+    
+    if ( TMath::Abs(a0) > 1E-12 ) 
     {
-      adc = TMath::Nint( signal / gainMean + pedestalMean + adcNoise);///
-      
-      if ( adc <= pedestalMean + fgkNSigmas*pedestalSigma ) 
-       {
-         adc = 0;
-       }
+      padc = charge/a0;    
     }
+  }
+  else // charge > chargeThres && a1 not zero
+  {
+    // parabolic part
+    padc = TMath::Sqrt((chargeThres-charge)/a1) + thres;
+  }
+
+  Float_t adcNoise = gRandom->Gaus(0.0,pedestalSigma);
+  Int_t adc(0);
+  
+  if ( padc > 0 ) 
+  {
+    adc = TMath::Nint(padc + pedestalMean + adcNoise);
+  }
   
   // be sure we stick to 12 bits.
   if ( adc > kMaxADC )
-    {
-      adc = kMaxADC;
-    }
+  {
+    adc = kMaxADC;
+  }
   
-  digit.SetPhysicsSignal(TMath::Nint(signal));
-  digit.SetSignal(adc);
+  AliDebug(3,Form("DE %4d Manu %4d Ch %2d Charge %e A0 %e A1 %e Thres %d padc %e ADC %4d",
+                  detElemId,manuId,manuChannel,charge,
+                  gain->ValueAsFloat(manuChannel,0),
+                  gain->ValueAsFloat(manuChannel,1),
+                  gain->ValueAsInt(manuChannel,2),
+                  padc,
+                  adc));
+                  
   digit.SetADC(adc);
 }
 
 //_____________________________________________________________________________
 void 
-AliMUONDigitizerV3::ApplyResponseToTriggerDigit(AliMUONDigit& digit,
-                                                AliMUONData* data)
+AliMUONDigitizerV3::ApplyResponseToTriggerDigit(const AliMUONVDigitStore& digitStore,
+                                                AliMUONVDigit& digit)
 {
   /// \todo add comment
 
   if ( !fTriggerEfficiency ) return;
 
-  AliMUONDigit* correspondingDigit = FindCorrespondingDigit(digit,data);
+  if (digit.IsEfficiencyApplied()) return;
 
-  if(!correspondingDigit)return;//reject bad correspondences
+  AliMUONVDigit* correspondingDigit = FindCorrespondingDigit(digitStore,digit);
+
+  if (!correspondingDigit) return; //reject bad correspondences
 
   Int_t detElemId = digit.DetElemId();
 
@@ -230,121 +274,65 @@ AliMUONDigitizerV3::ApplyResponseToTriggerDigit(AliMUONDigit& digit,
   };
 
   Int_t p0(1);
-  if (digit.Cathode()==0)p0=0;
+  if (digit.Cathode()==0) p0=0;
 
   AliMpIntPair location = pad[p0].GetLocation(0);
   Int_t nboard = location.GetFirst();
 
   Bool_t isTrig[2];
 
-  fTriggerEfficiency->IsTriggered(detElemId, nboard-1
+  fTriggerEfficiency->IsTriggered(detElemId, nboard, 
                                   isTrig[0], isTrig[1]);
+  digit.EfficiencyApplied(kTRUE);
+  correspondingDigit->EfficiencyApplied(kTRUE);
 
   if (!isTrig[digit.Cathode()])
   {
-         digit.SetSignal(0);
+         digit.SetCharge(0);
   }
   
   if ( &digit != correspondingDigit )
   {
          if (!isTrig[correspondingDigit->Cathode()])
     {
-      correspondingDigit->SetSignal(0);
+      correspondingDigit->SetCharge(0);
          }
   }
 }
 
 //_____________________________________________________________________________
 void
-AliMUONDigitizerV3::ApplyResponse()
+AliMUONDigitizerV3::ApplyResponse(const AliMUONVDigitStore& store,
+                                  AliMUONVDigitStore& filteredStore)
 {
   /// Loop over all chamber digits, and apply the response to them
   /// Note that this method may remove digits.
 
+  filteredStore.Clear();
+  
   const Bool_t kAddNoise = kTRUE;
   
-  for ( Int_t ich = 0; ich < AliMUONConstants::NCh(); ++ich )
+  TIter next(store.CreateIterator());
+  AliMUONVDigit* digit;
+  
+  while ( ( digit = static_cast<AliMUONVDigit*>(next()) ) )
   {
-    TClonesArray* digits = fOutputData->Digits(ich);
-    Int_t n = digits->GetEntriesFast();
-    Bool_t trackingChamber = ( ich < AliMUONConstants::NTrackingCh() );
-    for ( Int_t i = 0; i < n; ++i )
+    AliMp::StationType stationType = AliMpDEManager::GetStationType(digit->DetElemId());
+    
+    if ( stationType != AliMp::kStationTrigger )
     {
-      AliMUONDigit* d = static_cast<AliMUONDigit*>(digits->UncheckedAt(i));
-      if ( trackingChamber )
-      {
-        ApplyResponseToTrackerDigit(*d,kAddNoise);
-      }
-      else
-      {
-        ApplyResponseToTriggerDigit(*d,fOutputData);
-      }
-      if ( d->Signal() <= 0 )
-      {
-        digits->RemoveAt(i);
-      }
+      ApplyResponseToTrackerDigit(*digit,kAddNoise);
     }
-    digits->Compress();
-  }    
-  
-// The version below, using iterator, does not yet work (as the iterator
-// assumes it is reading digits from the tree, while in this case it's
-// writing...)
-//
-//  AliMUONDigit* digit(0x0);
-//
-//  // First loop on tracker digits
-//  AliMUONDataIterator tracker(fOutputData,"D",AliMUONDataIterator::kTrackingChambers);
-//  
-//  while ( ( digit = static_cast<AliMUONDigit*>(tracker.Next()) ) )
-//  {
-//    ApplyResponseToTrackerDigit(*digit);
-//    if ( digit->Signal() <= 0 )
-//    {
-//      tracker.Remove();
-//    }    
-//    
-//  }
-//
-//  // Then loop on trigger digits
-//  AliMUONDataIterator trigger(fOutputData,"D",AliMUONDataIterator::kTriggerChambers);
-//  
-//  while ( ( digit = static_cast<AliMUONDigit*>(trigger.Next()) ) )
-//  {
-//    ApplyResponseToTriggerDigit(*digit,fOutputData);
-//    if ( digit->Signal() <= 0 )
-//    {
-//      trigger.Remove();
-//    }    
-//  }
-}
-
-//_____________________________________________________________________________
-void
-AliMUONDigitizerV3::AddOrUpdateDigit(TClonesArray& array, 
-                                     const AliMUONDigit& digit)
-{
-  /// Add or update a digit, depending on whether there's already a digit
-  /// for the corresponding channel.
-
-  Int_t ix = FindDigitIndex(array,digit);
-  
-  if (ix>=0)
-  {
-    AliMUONDigit* d = static_cast<AliMUONDigit*>(array.UncheckedAt(ix));
-    Bool_t ok = MergeDigits(digit,*d);
-    if (!ok)
+    else
     {
-      AliError("Digits are not mergeable !");
+      ApplyResponseToTriggerDigit(store,*digit);
+    }
+    if ( digit->ADC() > 0  || digit->Charge() > 0 )
+    {
+      filteredStore.Add(*digit,AliMUONVDigitStore::kIgnore);
     }
   }
-  else
-  {
-    ix = array.GetLast() + 1;
-    new(array[ix]) AliMUONDigit(digit);
-  }
-  
-}
+}    
 
 //_____________________________________________________________________________
 void
@@ -374,33 +362,42 @@ AliMUONDigitizerV3::Exec(Option_t*)
 
   Int_t nInputFiles = fManager->GetNinputs();
   
-  if ( fOutputData->TreeD() == 0x0 )
+  AliLoader* outputLoader = GetLoader(fManager->GetOutputFolderName());
+  
+  outputLoader->MakeDigitsContainer();
+  
+  TTree* oTreeD = outputLoader->TreeD();
+  
+  if (!oTreeD) 
   {
-    AliDebug(1,"Calling MakeDigitsContainer");
-    fOutputData->GetLoader()->MakeDigitsContainer();
+    AliFatal("Cannot create output TreeD");
   }
-  fOutputData->MakeBranch("D,GLT");
-  fOutputData->SetTreeAddress("D,GLT");
-  
+
   // Loop over all the input files, and merge the sdigits found in those
   // files.
+  
   for ( Int_t iFile = 0; iFile < nInputFiles; ++iFile )
   {    
-    AliMUONData* inputData = GetDataAccess(fManager->GetInputFolderName(iFile));
-    if (!inputData)
+    AliLoader* inputLoader = GetLoader(fManager->GetInputFolderName(iFile));
+
+    inputLoader->LoadSDigits("READ");
+
+    TTree* iTreeS = inputLoader->TreeS();
+    if (!iTreeS)
     {
       AliFatal(Form("Could not get access to input file #%d",iFile));
     }
+    
+    AliMUONVDigitStore* inputStore = AliMUONVDigitStore::Create(*iTreeS);
+    inputStore->Connect(*iTreeS);
+    
+    iTreeS->GetEvent(0);
+    
+    MergeWithSDigits(fDigitStore,*inputStore,fManager->GetMask(iFile));
 
-    inputData->GetLoader()->LoadSDigits("READ");
-    inputData->SetTreeAddress("S");
-    inputData->GetSDigits();
-
-    MergeWithSDigits(*fOutputData,*inputData,fManager->GetMask(iFile));
+    inputLoader->UnloadSDigits();
     
-    inputData->ResetSDigits();
-    inputData->GetLoader()->UnloadSDigits();
-    delete inputData;
+    delete inputStore;
   }
   
   // At this point, we do have digit arrays (one per chamber) which contains 
@@ -408,105 +405,82 @@ AliMUONDigitizerV3::Exec(Option_t*)
   // We now massage them to apply the detector response, i.e. this
   // is here that we do the "digitization" work.
   
-  ApplyResponse();
+  if (!fOutputDigitStore)
+  {
+    fOutputDigitStore = fDigitStore->Create();
+  }
+  
+  if ( fGenerateNoisyDigits>=2 )
+  {
+    // Generate noise-only digits for trigger.
+    GenerateNoisyDigitsForTrigger(*fDigitStore);
+  }
+
+  ApplyResponse(*fDigitStore,*fOutputDigitStore);
   
   if ( fGenerateNoisyDigits )
   {
     // Generate noise-only digits for tracker.
-    GenerateNoisyDigits();
+    GenerateNoisyDigits(*fOutputDigitStore);
   }
   
   // We generate the global and local trigger decisions.
-  fTriggerProcessor->ExecuteTask();
+  fTriggerProcessor->Digits2Trigger(*fOutputDigitStore,*fTriggerStore);
+
+  // Prepare output tree
+  Bool_t okD = fOutputDigitStore->Connect(*oTreeD,kFALSE);
+  Bool_t okT = fTriggerStore->Connect(*oTreeD,kFALSE);
+  if (!okD || !okT)
+  {
+    AliError(Form("Could not make branch : Digit %d Trigger %d",okD,okT));
+    return;
+  }
   
   // Fill the output treeD
-  fOutputData->Fill("D,GLT");
+  oTreeD->Fill();
   
   // Write to the output tree(D).
   // Please note that as GlobalTrigger, LocalTrigger and Digits are in the same
   // tree (=TreeD) in different branches, this WriteDigits in fact writes all of 
   // the 3 branches.
-  fOutputData->GetLoader()->WriteDigits("OVERWRITE");
+  outputLoader->WriteDigits("OVERWRITE");  
   
-  // Finally, we clean up after ourselves.
-  fOutputData->ResetDigits();
-  fOutputData->ResetTrigger();
-  fOutputData->GetLoader()->UnloadDigits();
+  outputLoader->UnloadDigits();
   
+  // Finally, we clean up after ourselves.
+  fTriggerStore->Clear();
+  fDigitStore->Clear();
+  fOutputDigitStore->Clear();
   fExecTimer.Stop();
 }
 
 //_____________________________________________________________________________
-AliMUONDigit* 
-AliMUONDigitizerV3::FindCorrespondingDigit(AliMUONDigit& digit,
-                                           AliMUONData* data) const
+AliMUONVDigit* 
+AliMUONDigitizerV3::FindCorrespondingDigit(const AliMUONVDigitStore& digitStore,
+                                           AliMUONVDigit& digit) const
 {                                                
-  /// \todo add comment
+  /// Find, if it exists, the digit corresponding to digit.Hit(), in the 
+  /// other cathode
 
-  AliMUONDataIterator it(data,"D",AliMUONDataIterator::kTriggerChambers);
-  AliMUONDigit* cd;
-
-  for(;;){
-      cd = static_cast<AliMUONDigit*>(it.Next());
-      if(!cd)continue;
-      if (cd->DetElemId() == digit.DetElemId() &&
-         cd->PadX() == digit.PadX() &&
-         cd->PadY() == digit.PadY() && 
-         cd->Cathode() == digit.Cathode()){
-         break;
-      }
-  }
-  //The corresponding digit is searched only forward in the AliMUONData.
-  //In this way when the first digit of the couple is given, the second digit is found and the efficiency is applied to both. 
-  //Afterwards, when the second digit of the couple is given the first one is not found and hence efficiency is not applied again
+  TIter next(digitStore.CreateIterator());
+  AliMUONVDigit* d;
   
-  while ( ( cd = static_cast<AliMUONDigit*>(it.Next()) ) )
+  while ( ( d = static_cast<AliMUONVDigit*>(next()) ) )
   {
-    if(!cd)continue;//avoid problems when 1 digit is removed
-    if ( cd->DetElemId() == digit.DetElemId() &&
-         cd->Hit() == digit.Hit() &&
-         cd->Cathode() != digit.Cathode() )
+    if ( d->DetElemId() == digit.DetElemId() &&
+         d->Hit() == digit.Hit() &&
+         d->Cathode() != digit.Cathode() )
     {
-      return cd;
-    }
-  }
+      return d;
+    }      
+  }    
   return 0x0;
 }
 
 
-//_____________________________________________________________________________
-Int_t
-AliMUONDigitizerV3::FindDigitIndex(TClonesArray& array, 
-                                   const AliMUONDigit& digit) const
-{
-  /// Return the index of digit within array, if that digit is there, 
-  /// otherwise returns -1
-  ///
-  /// \todo FIXME: this is of course not the best implementation you can think of.
-  /// Reconsider the use of hit/digit map... ? (but be sure it's needed!)
-  
-  fFindDigitIndexTimer.Start(kFALSE);
-  
-  Int_t n = array.GetEntriesFast();
-  for ( Int_t i = 0; i < n; ++i )
-  {
-    AliMUONDigit* d = static_cast<AliMUONDigit*>(array.UncheckedAt(i));
-    if ( d->DetElemId() == digit.DetElemId() &&
-         d->PadX() == digit.PadX() &&
-         d->PadY() == digit.PadY() && 
-         d->Cathode() == digit.Cathode() )
-    {
-      fFindDigitIndexTimer.Stop();
-      return i;
-    }
-  }
-  fFindDigitIndexTimer.Stop();
-  return -1;
-}
-
 //_____________________________________________________________________________
 void
-AliMUONDigitizerV3::GenerateNoisyDigits()
+AliMUONDigitizerV3::GenerateNoisyDigits(AliMUONVDigitStore& digitStore)
 {
   /// According to a given probability, generate digits that
   /// have a signal above the noise cut (ped+n*sigma_ped), i.e. digits
@@ -532,7 +506,7 @@ AliMUONDigitizerV3::GenerateNoisyDigits()
     {
       for ( Int_t cathode = 0; cathode < 2; ++cathode )
       {
-        GenerateNoisyDigitsForOneCathode(it.CurrentDEId(),cathode);
+        GenerateNoisyDigitsForOneCathode(digitStore,it.CurrentDEId(),cathode);
       }
       it.Next();
     }
@@ -543,14 +517,12 @@ AliMUONDigitizerV3::GenerateNoisyDigits()
  
 //_____________________________________________________________________________
 void
-AliMUONDigitizerV3::GenerateNoisyDigitsForOneCathode(Int_t detElemId, Int_t cathode)
+AliMUONDigitizerV3::GenerateNoisyDigitsForOneCathode(AliMUONVDigitStore& digitStore,
+                                                     Int_t detElemId, Int_t cathode)
 {
   /// Generate noise-only digits for one cathode of one detection element.
   /// Called by GenerateNoisyDigits()
   
-  Int_t chamberId = AliMpDEManager::GetChamberId(detElemId);
-  TClonesArray* digits = fOutputData->Digits(chamberId);
-  
   const AliMpVSegmentation* seg 
     = AliMpSegmentation::Instance()->GetMpSegmentation(detElemId,AliMp::GetCathodType(cathode));
   Int_t nofPads = seg->NofPads();
@@ -569,80 +541,184 @@ AliMUONDigitizerV3::GenerateNoisyDigitsForOneCathode(Int_t detElemId, Int_t cath
   
   AliDebug(3,Form("DE %d cath %d nofNoisyPads %d",detElemId,cathode,nofNoisyPads));
   
-  for ( Int_t i = 0; i < nofNoisyPads; ++i )
+  for ( Int_t i = 0; i < nofNoisyPads; ++i ) 
   {
     Int_t ix(-1);
     Int_t iy(-1);
+    AliMpPad pad;
+    
     do {
       ix = gRandom->Integer(maxIx+1);
       iy = gRandom->Integer(maxIy+1);
-    } while ( !seg->HasPad(AliMpIntPair(ix,iy)) );
-    AliMUONDigit d;
-    d.SetDetElemId(detElemId);
-    d.SetCathode(cathode);
-    d.SetPadX(ix);
-    d.SetPadY(iy);
-    if ( FindDigitIndex(*digits,d) >= 0 )
+      pad = seg->PadByIndices(AliMpIntPair(ix,iy),kFALSE);
+    } while ( !pad.IsValid() );
+
+    Int_t manuId = pad.GetLocation().GetFirst();
+    Int_t manuChannel = pad.GetLocation().GetSecond();    
+
+    AliMUONVCalibParam* pedestals = fCalibrationData->Pedestals(detElemId,manuId);
+    
+    if (!pedestals) 
     {
-      // this digit is already there, and not noise-only, we simply skip it
+      // no pedestal available for this channel, simply give up
       continue;
     }
-    AliMpPad pad = seg->PadByIndices(AliMpIntPair(ix,iy));
-    Int_t manuId = pad.GetLocation().GetFirst();
-    Int_t manuChannel = pad.GetLocation().GetSecond();
     
-    d.SetElectronics(manuId,manuChannel);
+    AliMUONVDigit* d = digitStore.CreateDigit(detElemId,manuId,manuChannel,cathode);
     
-    AliMUONVCalibParam* pedestals = fCalibrationData->Pedestals(detElemId,manuId);
+    d->SetPadXY(ix,iy);
     
     Float_t pedestalMean = pedestals->ValueAsFloat(manuChannel,0);
     Float_t pedestalSigma = pedestals->ValueAsFloat(manuChannel,1);
     
     Double_t ped = fNoiseFunction->GetRandom()*pedestalSigma;
 
-    d.SetSignal(TMath::Nint(ped+pedestalMean+0.5));
-    d.SetPhysicsSignal(0);
-    d.NoiseOnly(kTRUE);
-    AliDebug(3,Form("Adding a pure noise digit :"));
-    StdoutToAliDebug(3,cout << "Before Response: " << endl; 
-                     d.Print(););
-    ApplyResponseToTrackerDigit(d,kFALSE);
-    if ( d.Signal() > 0 )
+    d->SetCharge(TMath::Nint(ped+pedestalMean+0.5));
+    d->NoiseOnly(kTRUE);
+    ApplyResponseToTrackerDigit(*d,kFALSE);
+    if ( d->ADC() > 0 )
     {
-      AddOrUpdateDigit(*digits,d);
+      Bool_t ok = digitStore.Add(*d,AliMUONVDigitStore::kDeny);
+      // this can happen (that we randomly chose a digit that is
+      // already there). We simply ignore this, but log the occurence
+      // to cross-check that it's not too frequent.
+      if (!ok)
+      {
+        fLogger->Log("Collision while adding noiseOnly digit");
+      }
+      else
+      {
+        fLogger->Log("Added noiseOnly digit");
+      }
     }
     else
     {
       AliError("Pure noise below threshold. This should not happen. Not adding "
                "this digit.");
     }
-    StdoutToAliDebug(3,cout << "After Response: " << endl; 
-                     d.Print(););
+    delete d;
   }
 }
 
+
 //_____________________________________________________________________________
-AliMUONData* 
-AliMUONDigitizerV3::GetDataAccess(const TString& folderName)
+void
+AliMUONDigitizerV3::GenerateNoisyDigitsForTrigger(AliMUONVDigitStore& digitStore)
 {
-  /// Create an AliMUONData to deal with data found in folderName.
+  /// Generate noise-only digits for one cathode of one detection element.
+  /// Called by GenerateNoisyDigits()
 
-  AliDebug(1,Form("Getting access to folder %s",folderName.Data()));
-  AliRunLoader* runLoader = AliRunLoader::GetRunLoader(folderName);
-  if (!runLoader)
+  if ( !fNoiseFunctionTrig )
   {
-    AliError(Form("Could not get RunLoader from folder %s",folderName.Data()));
-    return 0x0;
+    fNoiseFunctionTrig = new TF1("AliMUONDigitizerV3::fNoiseFunctionTrig","landau",
+                                50.,270.);
+    
+    fNoiseFunctionTrig->SetParameters(3.91070e+02, 9.85026, 9.35881e-02);
   }
-  AliLoader* loader = static_cast<AliLoader*>(runLoader->GetLoader("MUONLoader"));
+
+  AliMpPad pad[2];
+  AliMUONVDigit *d[2]={0x0};
+
+  for ( Int_t chamberId = AliMUONConstants::NTrackingCh(); chamberId < AliMUONConstants::NCh(); ++chamberId )
+  {
+  
+    Int_t nofNoisyPads = 50;
+
+    Float_t r=-1, fi = 0., gx, gy, x, y, z, xg01, yg01, zg, xg02, yg02;
+    AliMpDEIterator it;
+  
+    AliDebug(3,Form("Chamber %d nofNoisyPads %d",chamberId,nofNoisyPads));
+
+    for ( Int_t i = 0; i < nofNoisyPads; ++i )
+    {
+      //printf("Generating noise %i\n",i);
+       Int_t ix(-1);
+       Int_t iy(-1);
+       Bool_t isOk = kFALSE;
+       Int_t detElemId = -1;
+       do {
+         //r = gRandom->Landau(9.85026, 9.35881e-02);
+           r = fNoiseFunctionTrig->GetRandom();
+           fi = 2. * TMath::Pi() * gRandom->Rndm();
+           //printf("r = %f\tfi = %f\n", r, fi);
+           gx = r * TMath::Cos(fi);
+           gy = r * TMath::Sin(fi);
+
+           for ( it.First(chamberId); ! it.IsDone(); it.Next() ){
+               Int_t currDetElemId = it.CurrentDEId();
+               const AliMpVSegmentation* seg
+                   = AliMpSegmentation::Instance()->GetMpSegmentation(currDetElemId,AliMp::GetCathodType(0));
+               if (!seg) continue;
+               Float_t deltax = seg->Dimensions().X();
+               Float_t deltay = seg->Dimensions().Y();
+               GetTransformer()->Local2Global(currDetElemId, -deltax, -deltay, 0, xg01, yg01, zg);
+               GetTransformer()->Local2Global(currDetElemId,  deltax,  deltay, 0, xg02, yg02, zg);
+               Float_t xg1 = xg01, xg2 = xg02, yg1 = yg01, yg2 = yg02;
+               if(xg01>xg02){
+                   xg1 = xg02;
+                   xg2 = xg01;
+               }
+               if(yg01>yg02){
+                   yg1 = yg02;
+                   yg2 = yg01;
+               }
+               if(gx>=xg1 && gx<=xg2 && gy>=yg1 && gy<=yg2){
+                   detElemId = currDetElemId;
+                   GetTransformer()->Global2Local(detElemId, gx, gy, 0, x, y, z);
+                   pad[0] = seg->PadByPosition(TVector2(x,y),kFALSE);
+                   if(!pad[0].IsValid()) continue;
+                   isOk = kTRUE;
+                   break;
+               }
+           } // loop on slats
+       } while ( !isOk );
+
+       const AliMpVSegmentation* seg1
+           = AliMpSegmentation::Instance()->GetMpSegmentation(detElemId,AliMp::GetCathodType(1));
+       pad[1] = seg1->PadByPosition(TVector2(x,y),kFALSE);
+
+       for ( Int_t cathode = 0; cathode < 2; ++cathode ){
+         Int_t manuId = pad[cathode].GetLocation(0).GetFirst();
+         Int_t manuChannel = pad[cathode].GetLocation(0).GetSecond();    
+         d[cathode] = digitStore.CreateDigit(detElemId,manuId,manuChannel,cathode);
+         ix = pad[cathode].GetIndices().GetFirst();
+         iy = pad[cathode].GetIndices().GetSecond();
+         d[cathode]->SetPadXY(ix,iy);
+         //d[cathode].SetSignal(1);
+         //d[cathode].SetPhysicsSignal(0);
+         d[cathode]->SetCharge(1);
+         d[cathode]->NoiseOnly(kTRUE);
+         AliDebug(3,Form("Adding a pure noise digit :"));
+
+         Bool_t ok = digitStore.Add(*d[cathode],AliMUONVDigitStore::kDeny);
+         if (!ok)
+         {
+             fLogger->Log("Collision while adding TriggerNoise digit");
+         }
+         else
+         {
+             fLogger->Log("Added triggerNoise digit");
+         }
+       } //loop on cathodes
+    } // loop on noisy pads
+  } // loop on chambers
+}
+
+
+//_____________________________________________________________________________
+AliLoader*
+AliMUONDigitizerV3::GetLoader(const TString& folderName)
+{
+  /// Get a MUON loader
+
+  AliDebug(2,Form("Getting access to folder %s",folderName.Data()));
+  AliLoader* loader = AliRunLoader::GetDetectorLoader("MUON",folderName.Data());
   if (!loader)
   {
     AliError(Form("Could not get MuonLoader from folder %s",folderName.Data()));
     return 0x0;
   }
-  AliMUONData* data = new AliMUONData(loader,"MUON","MUONDataForDigitOutput");
-  AliDebug(1,Form("AliMUONData=%p loader=%p",data,loader));
-  return data;
+  return loader;
 }
 
 //_____________________________________________________________________________
@@ -650,11 +726,10 @@ Bool_t
 AliMUONDigitizerV3::Init()
 {
   /// Initialization of the TTask :
-  /// a) set the outputData pointer
-  /// b) create the calibrationData, according to run number
-  /// c) create the trigger processing task
+  /// a) create the calibrationData, according to run number
+  /// b) create the trigger processing task
 
-  AliDebug(1,"");
+  AliDebug(2,"");
   
   if ( fIsInitialized )
   {
@@ -668,21 +743,18 @@ AliMUONDigitizerV3::Init()
     return kFALSE;
   }
   
-  fOutputData = GetDataAccess(fManager->GetOutputFolderName());
-  if (!fOutputData)
-  {
-    AliError("Can not perform digitization. I'm sorry");
-    return kFALSE;
-  }
-  AliDebug(1,Form("fOutputData=%p",fOutputData));
-  
-  AliRunLoader* runLoader = fOutputData->GetLoader()->GetRunLoader();
-  AliRun* galice = runLoader->GetAliRun();  
-  Int_t runnumber = galice->GetRunNumber();
+  Int_t runnumber = AliCDBManager::Instance()->GetRun();
   
   fCalibrationData = new AliMUONCalibrationData(runnumber);
-  
-  fTriggerProcessor = new AliMUONTriggerElectronics(fOutputData,fCalibrationData);
+  if ( !fCalibrationData->Pedestals() )
+  {
+    AliFatal("Could not access pedestals from OCDB !");
+  }
+  if ( !fCalibrationData->Gains() )
+  {
+    AliFatal("Could not access gains from OCDB !");
+  }
+  fTriggerProcessor = new AliMUONTriggerElectronics(fCalibrationData);
   
   if ( muon()->GetTriggerEffCells() )
   {
@@ -693,85 +765,42 @@ AliMUONDigitizerV3::Init()
     }
     else
     {
-      AliError("I was requested to apply trigger efficiency, but I could "
+      AliFatal("I was requested to apply trigger efficiency, but I could "
                "not get it !");
     }
   }
   
-  if ( fGenerateNoisyDigits )
-  {
-    AliDebug(1, "Will generate noise-only digits for tracker");
-  }
-  
-  fIsInitialized = kTRUE;
-  return kTRUE;
-}
-
-//_____________________________________________________________________________
-Bool_t
-AliMUONDigitizerV3::MergeDigits(const AliMUONDigit& src, 
-                                AliMUONDigit& srcAndDest)
-{
-  /// Merge 2 digits (src and srcAndDest) into srcAndDest.
+  AliDebug(1, Form("Will %s generate noise-only digits for tracker",
+                     (fGenerateNoisyDigits ? "":"NOT")));
 
-  AliDebug(1,"Merging the following digits:");
-  StdoutToAliDebug(1,src.Print("tracks"););
-  StdoutToAliDebug(1,srcAndDest.Print("tracks"););
-  
-  Bool_t check = ( src.DetElemId() == srcAndDest.DetElemId() &&
-                   src.PadX() == srcAndDest.PadX() &&
-                   src.PadY() == srcAndDest.PadY() &&
-                   src.Cathode() == srcAndDest.Cathode() );
-  if (!check)
-  {
-    return kFALSE;
-  }
-  
-  srcAndDest.AddSignal(src.Signal());
-  srcAndDest.AddPhysicsSignal(src.Physics());
-  for ( Int_t i = 0; i < src.Ntracks(); ++i )
-  {
-    srcAndDest.AddTrack(src.Track(i),src.TrackCharge(i));
-  }
-  StdoutToAliDebug(1,cout << "result:"; srcAndDest.Print("tracks"););
+  fIsInitialized = kTRUE;
   return kTRUE;
 }
 
 //_____________________________________________________________________________
 void 
-AliMUONDigitizerV3::MergeWithSDigits(AliMUONData& outputData, 
-                                     const AliMUONData& inputData, Int_t mask)
+AliMUONDigitizerV3::MergeWithSDigits(AliMUONVDigitStore*& outputStore,
+                                     const AliMUONVDigitStore& input,
+                                     Int_t mask)
 {
   /// Merge the sdigits in inputData with the digits already present in outputData
-
-  AliDebug(1,"");
   
-       for ( Int_t ich = 0; ich < AliMUONConstants::NCh(); ++ich )
-       {
-    TClonesArray* iDigits = inputData.SDigits(ich); 
-    TClonesArray* oDigits = outputData.Digits(ich);
-    if (!iDigits)
+  if ( !outputStore ) outputStore = input.Create();
+  
+  TIter next(input.CreateIterator());
+  AliMUONVDigit* sdigit;
+  
+  while ( ( sdigit = static_cast<AliMUONVDigit*>(next()) ) )
+  {
+    // Update the track references using the mask.
+    // FIXME: this is dirty, for backward compatibility only.
+    // Should re-design all this way of keeping track of MC information...
+    if ( mask ) sdigit->PatchTracks(mask);
+    // Then add or update the digit to the output.
+    AliMUONVDigit* added = outputStore->Add(*sdigit,AliMUONVDigitStore::kMerge);
+    if (!added)
     {
-      AliError(Form("Could not get sdigits for ich=%d",ich));
-      return;
+      AliError("Could not add digit in merge mode");
     }
-    Int_t nSDigits = iDigits->GetEntriesFast();
-    for ( Int_t k = 0; k < nSDigits; ++k )
-               {
-                       AliMUONDigit* sdigit = static_cast<AliMUONDigit*>(iDigits->UncheckedAt(k));
-      if (!sdigit)
-      {
-        AliError(Form("Could not get sdigit for ich=%d and k=%d",ich,k));
-      }
-      else
-      {
-        // Update the track references using the mask.
-        // FIXME: this is dirty, for backward compatibility only.
-        // Should re-design all this way of keeping track of MC information...
-        if ( mask ) sdigit->PatchTracks(mask);
-        // Then add or update the digit to the output.
-        AddOrUpdateDigit(*oDigits,*sdigit);
-      }
-    }   
   }
 }