]> git.uio.no Git - u/mrichter/AliRoot.git/blob - TRD/AliTRDdigitizer.cxx
Code for simulation, sdigitization and digitization moved from macros to compiled...
[u/mrichter/AliRoot.git] / TRD / AliTRDdigitizer.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 //  Creates and handles digits from TRD hits                                 //
21 //  Author: C. Blume (C.Blume@gsi.de)                                        //
22 //                                                                           //
23 //  The following effects are included:                                      //
24 //      - Diffusion                                                          //
25 //      - ExB effects                                                        //
26 //      - Gas gain including fluctuations                                    //
27 //      - Pad-response (simple Gaussian approximation)                       //
28 //      - Time-response                                                      //
29 //      - Electronics noise                                                  //
30 //      - Electronics gain                                                   //
31 //      - Digitization                                                       //
32 //      - ADC threshold                                                      //
33 //  The corresponding parameter can be adjusted via the various              //
34 //  Set-functions. If these parameters are not explicitly set, default       //
35 //  values are used (see Init-function).                                     //
36 //  As an example on how to use this class to produce digits from hits       //
37 //  have a look at the macro hits2digits.C                                   //
38 //  The production of summable digits is demonstrated in hits2sdigits.C      //
39 //  and the subsequent conversion of the s-digits into normal digits is      //
40 //  explained in sdigits2digits.C.                                           //
41 //                                                                           //
42 ///////////////////////////////////////////////////////////////////////////////
43
44 #include <stdlib.h>
45
46 #include <TMath.h>
47 #include <TVector.h>
48 #include <TRandom.h>
49 #include <TROOT.h>
50 #include <TTree.h>
51 #include <TFile.h>
52 #include <TF1.h>
53 #include <TList.h>
54 #include <TTask.h>
55
56 #include "AliRun.h"
57 #include "AliRunLoader.h"
58 #include "AliLoader.h"
59 #include "AliConfig.h"
60 #include "AliMagF.h"
61 #include "AliRunDigitizer.h"
62 #include "AliRunLoader.h"
63 #include "AliLoader.h"
64
65 #include "AliTRD.h"
66 #include "AliTRDhit.h"
67 #include "AliTRDdigitizer.h"
68 #include "AliTRDdataArrayI.h"
69 #include "AliTRDdataArrayF.h"
70 #include "AliTRDsegmentArray.h"
71 #include "AliTRDdigitsManager.h"
72 #include "AliTRDgeometry.h"
73 #include "AliTRDparameter.h"
74
75 ClassImp(AliTRDdigitizer)
76
77 //_____________________________________________________________________________
78 AliTRDdigitizer::AliTRDdigitizer()
79 {
80   //
81   // AliTRDdigitizer default constructor
82   //
83
84   fRunLoader          = 0;
85   fDigitsManager      = 0;
86   fSDigitsManager     = 0;
87   fSDigitsManagerList = 0;
88   fTRD                = 0;
89   fGeo                = 0;
90   fPar                = 0;
91   fEvent              = 0;
92   fMasks              = 0;
93   fCompress           = kTRUE;
94   fDebug              = 0;
95   fSDigits            = kFALSE;
96   fSDigitsScale       = 0.0;
97   fMergeSignalOnly    = kFALSE;
98   fSimpleSim          = kFALSE;
99   fSimpleDet          = 0;
100  
101 }
102
103 //_____________________________________________________________________________
104 AliTRDdigitizer::AliTRDdigitizer(const Text_t *name, const Text_t *title)
105                 :AliDigitizer(name,title)
106 {
107   //
108   // AliTRDdigitizer constructor
109   //
110
111   fRunLoader          = 0;
112
113   //NewIO: These data members probably are not needed anymore
114   fDigitsManager      = 0;
115   fSDigitsManager     = 0;
116   fSDigitsManagerList = 0;
117   fTRD                = 0;
118   fGeo                = 0;
119   fPar                = 0;
120   //End NewIO comment
121   fEvent              = 0;
122   fMasks              = 0;
123   fCompress           = kTRUE;
124   fDebug              = 0;
125   fSDigits            = kFALSE;
126   fSDigitsScale       = 100.; // For the summable digits
127   fMergeSignalOnly    = kFALSE;
128   fSimpleSim          = kFALSE;
129   fSimpleDet          = 0;
130  
131
132 }
133
134 //_____________________________________________________________________________
135 AliTRDdigitizer::AliTRDdigitizer(AliRunDigitizer *manager
136                                 , const Text_t *name, const Text_t *title)
137                 :AliDigitizer(manager,name,title)
138 {
139   //
140   // AliTRDdigitizer constructor
141   //
142
143   fRunLoader          = 0;
144   fDigitsManager      = 0;
145   fSDigitsManager     = 0;
146   fSDigitsManagerList = 0;
147   fTRD                = 0;
148   fGeo                = 0;
149   fPar                = 0;
150   fEvent              = 0;
151   fMasks              = 0;
152   fCompress           = kTRUE;
153   fDebug              = 0;
154   fSDigits            = kFALSE;
155   fSDigitsScale       = 100.; // For the summable digits
156   fMergeSignalOnly    = kFALSE;
157   fSimpleSim          = kFALSE;
158   fSimpleDet          = 0;
159  
160
161 }
162
163 //_____________________________________________________________________________
164 AliTRDdigitizer::AliTRDdigitizer(AliRunDigitizer *manager)
165                 :AliDigitizer(manager,"AliTRDdigitizer","TRD digitizer")
166 {
167   //
168   // AliTRDdigitizer constructor
169   //
170
171
172   fRunLoader          = 0;
173   fDigitsManager      = 0;
174   fSDigitsManager     = 0;
175   fSDigitsManagerList = 0;
176   fTRD                = 0;
177   fGeo                = 0;
178   fPar                = 0;
179   fEvent              = 0;
180   fMasks              = 0;
181   fCompress           = kTRUE;
182   fDebug              = 0;
183   fSDigits            = kFALSE;
184   fSDigitsScale       = 100.;  // For the summable digits
185   fMergeSignalOnly    = kFALSE;
186   fSimpleSim          = kFALSE;
187   fSimpleDet          = 0;
188
189
190 }
191
192 //_____________________________________________________________________________
193 AliTRDdigitizer::AliTRDdigitizer(const AliTRDdigitizer &d):AliDigitizer(d)
194 {
195   //
196   // AliTRDdigitizer copy constructor
197   //
198
199   ((AliTRDdigitizer &) d).Copy(*this);
200
201 }
202
203 //_____________________________________________________________________________
204 AliTRDdigitizer::~AliTRDdigitizer()
205 {
206   //
207   // AliTRDdigitizer destructor
208   //
209
210
211   if (fDigitsManager) {
212     delete fDigitsManager;
213     fDigitsManager = 0;
214   }
215
216   if (fSDigitsManager) {
217     delete fSDigitsManager;
218     fSDigitsManager = 0;
219   }
220
221   if (fSDigitsManagerList) {
222     delete fSDigitsManagerList;
223     fSDigitsManagerList = 0;
224   }
225
226   if (fMasks) {
227     delete [] fMasks;
228     fMasks = 0;
229   }
230
231 }
232
233 //_____________________________________________________________________________
234 AliTRDdigitizer &AliTRDdigitizer::operator=(const AliTRDdigitizer &d)
235 {
236   //
237   // Assignment operator
238   //
239
240   if (this != &d) ((AliTRDdigitizer &) d).Copy(*this);
241   return *this;
242
243 }
244
245 //_____________________________________________________________________________
246 void AliTRDdigitizer::Copy(TObject &d)
247 {
248   //
249   // Copy function
250   //
251
252   ((AliTRDdigitizer &) d).fRunLoader          = 0;
253   ((AliTRDdigitizer &) d).fDigitsManager      = 0;
254   ((AliTRDdigitizer &) d).fSDigitsManager     = 0;
255   ((AliTRDdigitizer &) d).fSDigitsManagerList = 0;
256   ((AliTRDdigitizer &) d).fTRD                = 0;
257   ((AliTRDdigitizer &) d).fGeo                = 0;
258   ((AliTRDdigitizer &) d).fPar                = 0;
259   ((AliTRDdigitizer &) d).fEvent              = 0;
260   ((AliTRDdigitizer &) d).fMasks              = 0;
261   ((AliTRDdigitizer &) d).fCompress           = fCompress;
262   ((AliTRDdigitizer &) d).fDebug              = fDebug  ;
263   ((AliTRDdigitizer &) d).fSDigits            = fSDigits;
264   ((AliTRDdigitizer &) d).fSDigitsScale       = fSDigitsScale;
265   ((AliTRDdigitizer &) d).fMergeSignalOnly    = fMergeSignalOnly;
266   ((AliTRDdigitizer &) d).fSimpleSim          = fSimpleSim;
267   ((AliTRDdigitizer &) d).fSimpleDet          = fSimpleDet;
268                                        
269 }
270
271 //_____________________________________________________________________________
272 void AliTRDdigitizer::Exec(Option_t* option)
273 {
274   //
275   // Executes the merging
276   //
277
278   Int_t iInput;
279
280   AliTRDdigitsManager *sdigitsManager;
281
282   TString optionString = option;
283   if (optionString.Contains("deb")) {
284     fDebug = 1;
285     if (optionString.Contains("2")) {
286       fDebug = 2;
287     }
288     printf("<AliTRDdigitizer::Exec> ");
289     printf("Called with debug option %d\n",fDebug);
290   }
291
292   // The AliRoot file is already connected by the manager
293   AliRunLoader* inrl;
294   
295   if (gAlice) 
296    {
297     if (fDebug > 0) {
298       printf("<AliTRDdigitizer::Exec> ");
299       printf("AliRun object found on file.\n");
300     }
301    }
302   else {
303     inrl = AliRunLoader::GetRunLoader(fManager->GetInputFolderName(0));
304     inrl->LoadgAlice();
305     gAlice = inrl->GetAliRun();
306     if (!gAlice)
307      {
308        printf("<AliTRDdigitizer::Exec> ");
309        printf("Could not find AliRun object.\n");
310        return;
311      }
312   }
313                                                                            
314   Int_t nInput = fManager->GetNinputs();
315   fMasks = new Int_t[nInput];
316   for (iInput = 0; iInput < nInput; iInput++) {
317     fMasks[iInput] = fManager->GetMask(iInput);
318   }
319
320   // Initialization
321   InitDetector();
322
323   for (iInput = 0; iInput < nInput; iInput++) {
324
325     if (fDebug > 0) {
326       printf("<AliTRDdigitizer::Exec> ");
327       printf("Add input stream %d\n",iInput);
328     }
329
330     // check if the input tree exists
331     inrl = AliRunLoader::GetRunLoader(fManager->GetInputFolderName(iInput));
332     AliLoader* gime = inrl->GetLoader("TRDLoader");
333
334     TTree * treees =  gime->TreeS();
335     if (treees == 0x0) 
336      {
337       if (gime->LoadSDigits())
338        {
339          Error("Exec","Error Occured while loading S. Digits for input %d.",iInput);
340          return;
341        }
342       treees =  gime->TreeS();
343      }
344     
345     if (treees == 0x0) {
346       printf("<AliTRDdigitizer::Exec> ");
347       printf("Input stream %d does not exist\n",iInput);
348       return;
349     } 
350
351     // Read the s-digits via digits manager
352     sdigitsManager = new AliTRDdigitsManager();
353     sdigitsManager->SetDebug(fDebug);
354     sdigitsManager->SetSDigits(kTRUE);
355     
356     AliRunLoader* rl = AliRunLoader::GetRunLoader(fManager->GetInputFolderName(iInput));
357     AliLoader* gimme = rl->GetLoader("TRDLoader");
358     if (!gimme->TreeS()) gimme->LoadSDigits();
359     sdigitsManager->ReadDigits(gimme->TreeS());
360
361     // Add the s-digits to the input list 
362     AddSDigitsManager(sdigitsManager);
363
364   }
365
366   // Convert the s-digits to normal digits
367   if (fDebug > 0) {
368     printf("<AliTRDdigitizer::Exec> ");
369     printf("Do the conversion\n");
370   }
371   SDigits2Digits();
372
373   // Store the digits
374   if (fDebug > 0) {
375     printf("<AliTRDdigitizer::Exec> ");
376     printf("Write the digits\n");
377   }
378   
379   AliRunLoader* orl = AliRunLoader::GetRunLoader(fManager->GetOutputFolderName());
380   AliLoader* ogime = orl->GetLoader("TRDLoader");
381
382   fDigitsManager->MakeBranch(ogime->TreeD());
383
384   fDigitsManager->WriteDigits();
385
386   if (fDebug > 0) {
387     printf("<AliTRDdigitizer::Exec> ");
388     printf("Done\n");
389   }
390
391   DeleteSDigitsManager();
392
393 }
394
395 //_____________________________________________________________________________
396 Bool_t AliTRDdigitizer::Open(const Char_t *file, Int_t nEvent)
397 {
398   //
399   // Opens a ROOT-file with TRD-hits and reads in the hit-tree
400   //
401
402   // Connect the AliRoot file containing Geometry, Kine, and Hits
403   
404   fRunLoader = AliRunLoader::Open(file,AliConfig::fgkDefaultEventFolderName);
405   
406   if (!fRunLoader)
407    {
408      Error("Open","Can not open session for file %s.",file);
409      return kFALSE;
410    }
411    
412   fRunLoader->LoadgAlice();
413   gAlice = fRunLoader->GetAliRun();
414   
415   if (gAlice) {
416     if (fDebug > 0) {
417       printf("<AliTRDdigitizer::Open> ");
418       printf("AliRun object found on file.\n");
419     }
420   }
421   else {
422     printf("<AliTRDdigitizer::Open> ");
423     printf("Could not find AliRun object.\n");
424     return kFALSE;
425   }
426
427   fEvent = nEvent;
428
429   // Import the Trees for the event nEvent in the file
430   fRunLoader->GetEvent(fEvent);
431   
432   AliLoader* loader = fRunLoader->GetLoader("TRDLoader");
433   if (!loader)
434    {
435      Error("Open","Can not get TRD loader from Run Loader");
436      return kFALSE;
437    }
438   
439   if (InitDetector()) {
440     TTree* tree = 0;
441     if (fSDigits)
442      { 
443      //if we produce SDigits
444        tree = loader->TreeS();
445        if (!tree)
446         {
447          loader->MakeTree("S");
448          tree = loader->TreeS();
449         }
450      }
451     else
452      {//if we produce Digits
453        tree = loader->TreeD();
454        if (!tree)
455         {
456          loader->MakeTree("D");
457          tree = loader->TreeD();
458         }
459      }
460     return MakeBranch(tree);
461   }
462   else {
463     return kFALSE;
464   }
465
466 }
467
468 //_____________________________________________________________________________
469 Bool_t AliTRDdigitizer::InitDetector()
470 {
471   //
472   // Sets the pointer to the TRD detector and the geometry
473   //
474
475   // Get the pointer to the detector class and check for version 1
476   fTRD = (AliTRD *) gAlice->GetDetector("TRD");
477   if (!fTRD) {
478     printf("<AliTRDdigitizer::InitDetector> ");
479     printf("No TRD module found\n");
480     exit(1);
481   }
482   if (fTRD->IsVersion() != 1) {
483     printf("<AliTRDdigitizer::InitDetector> ");
484     printf("TRD must be version 1 (slow simulator).\n");
485     exit(1);
486   }
487
488   // Get the geometry
489   fGeo = fTRD->GetGeometry();
490   if (fDebug > 0) {
491     printf("<AliTRDdigitizer::InitDetector> ");
492     printf("Geometry version %d\n",fGeo->IsVersion());
493   }
494
495   // Create a digits manager
496   fDigitsManager = new AliTRDdigitsManager();
497   fDigitsManager->SetSDigits(fSDigits);
498   fDigitsManager->CreateArrays();
499   fDigitsManager->SetEvent(fEvent);
500   fDigitsManager->SetDebug(fDebug);
501
502   // The list for the input s-digits manager to be merged
503   fSDigitsManagerList = new TList();
504
505   return kTRUE;
506
507 }
508
509 //_____________________________________________________________________________
510 Bool_t AliTRDdigitizer::MakeBranch(TTree* tree) const
511 {
512   // 
513   // Create the branches for the digits array
514   //
515
516   return fDigitsManager->MakeBranch(tree);
517
518 }
519
520 //_____________________________________________________________________________
521 Bool_t AliTRDdigitizer::MakeDigits()
522 {
523   //
524   // Creates digits.
525   //
526
527   ///////////////////////////////////////////////////////////////
528   // Parameter 
529   ///////////////////////////////////////////////////////////////
530
531   // Converts number of electrons to fC
532   const Double_t kEl2fC  = 1.602E-19 * 1.0E15; 
533
534   ///////////////////////////////////////////////////////////////
535
536   // Number of pads included in the pad response
537   const Int_t kNpad  = 3;
538
539   // Number of track dictionary arrays
540   const Int_t kNDict = AliTRDdigitsManager::kNDict;
541
542   // Half the width of the amplification region
543   const Float_t kAmWidth = AliTRDgeometry::AmThick() / 2.;
544
545   Int_t   iRow, iCol, iTime, iPad;
546   Int_t   iDict  = 0;
547   Int_t   nBytes = 0;
548
549   Int_t   totalSizeDigits = 0;
550   Int_t   totalSizeDict0  = 0;
551   Int_t   totalSizeDict1  = 0;
552   Int_t   totalSizeDict2  = 0;
553
554   Int_t   timeTRDbeg = 0;
555   Int_t   timeTRDend = 1;
556
557   Float_t pos[3];
558   Float_t rot[3];
559   Float_t xyz[3];
560   Float_t padSignal[kNpad];
561   Float_t signalOld[kNpad];
562
563   AliTRDdataArrayF *signals = 0;
564   AliTRDdataArrayI *digits  = 0;
565   AliTRDdataArrayI *dictionary[kNDict];
566
567   // Create a default parameter class if none is defined
568   if (!fPar) {
569     fPar = new AliTRDparameter("TRDparameter","Standard TRD parameter");
570     if (fDebug > 0) {
571       printf("<AliTRDdigitizer::MakeDigits> ");
572       printf("Create the default parameter object\n");
573     }
574   }
575
576   // Create a container for the amplitudes
577   AliTRDsegmentArray *signalsArray 
578                      = new AliTRDsegmentArray("AliTRDdataArrayF"
579                                              ,AliTRDgeometry::Ndet());
580
581   if (fPar->TRFOn()) {
582     timeTRDbeg = ((Int_t) (-fPar->GetTRFlo() / fPar->GetTimeBinSize())) - 1;
583     timeTRDend = ((Int_t) ( fPar->GetTRFhi() / fPar->GetTimeBinSize())) - 1;
584     if (fDebug > 0) {
585       printf("<AliTRDdigitizer::MakeDigits> ");
586       printf("Sample the TRF between -%d and %d\n",timeTRDbeg,timeTRDend);
587     }
588   }
589
590   Float_t elAttachProp = fPar->GetElAttachProp() / 100.; 
591
592   if (!fGeo) {
593     printf("<AliTRDdigitizer::MakeDigits> ");
594     printf("No geometry defined\n");
595     return kFALSE;
596   }
597
598   if (fDebug > 0) {
599     printf("<AliTRDdigitizer::MakeDigits> ");
600     printf("Start creating digits.\n");
601   }
602
603   AliLoader* gimme = fRunLoader->GetLoader("TRDLoader");
604   if (!gimme->TreeH()) gimme->LoadHits();
605   TTree* hitTree = gimme->TreeH();
606   if (hitTree == 0x0)
607     {
608       Error("MakeDigits","Can not get TreeH");
609       return kFALSE;
610     }
611   fTRD->SetTreeAddress();
612   
613   // Get the number of entries in the hit tree
614   // (Number of primary particles creating a hit somewhere)
615   Int_t nTrack = 1;
616   if (!fSimpleSim) {
617     nTrack = (Int_t) hitTree->GetEntries();
618     if (fDebug > 0) {
619       printf("<AliTRDdigitizer::MakeDigits> ");
620       printf("Found %d primary particles\n",nTrack);
621     } 
622   }
623
624   Int_t detectorOld = -1;
625   Int_t countHits   =  0; 
626
627   // Loop through all entries in the tree
628   for (Int_t iTrack = 0; iTrack < nTrack; iTrack++) {
629
630     if (!fSimpleSim) {   
631       gAlice->ResetHits();
632       nBytes += hitTree->GetEvent(iTrack);
633     }
634
635     // Loop through the TRD hits
636     Int_t iHit = 0;
637     AliTRDhit *hit = (AliTRDhit *) fTRD->FirstHit(-1);
638     while (hit) {
639  
640       countHits++;
641       iHit++;
642
643               pos[0]      = hit->X();
644               pos[1]      = hit->Y();
645               pos[2]      = hit->Z();
646       Float_t q           = hit->GetCharge();
647       Int_t   track       = hit->Track();
648       Int_t   detector    = hit->GetDetector();
649       Int_t   plane       = fGeo->GetPlane(detector);
650       Int_t   sector      = fGeo->GetSector(detector);
651       Int_t   chamber     = fGeo->GetChamber(detector);
652       Int_t   nRowMax     = fPar->GetRowMax(plane,chamber,sector);
653       Int_t   nColMax     = fPar->GetColMax(plane);
654       Int_t   nTimeMax    = fPar->GetTimeMax();
655       Int_t   nTimeBefore = fPar->GetTimeBefore();
656       Int_t   nTimeAfter  = fPar->GetTimeAfter();
657       Int_t   nTimeTotal  = fPar->GetTimeTotal();
658       Float_t row0        = fPar->GetRow0(plane,chamber,sector);
659       Float_t col0        = fPar->GetCol0(plane);
660       Float_t time0       = fPar->GetTime0(plane);
661       Float_t rowPadSize  = fPar->GetRowPadSize(plane,chamber,sector);
662       Float_t colPadSize  = fPar->GetColPadSize(plane);
663       Float_t timeBinSize = fPar->GetTimeBinSize();
664       Float_t divideRow   = 1.0 / rowPadSize;
665       Float_t divideCol   = 1.0 / colPadSize;
666       Float_t divideTime  = 1.0 / timeBinSize;
667
668       if (fDebug > 1) {
669         printf("Analyze hit no. %d ",iHit);
670         printf("-----------------------------------------------------------\n");
671         hit->Dump();
672         printf("plane = %d, sector = %d, chamber = %d\n"
673               ,plane,sector,chamber);
674         printf("nRowMax = %d, nColMax = %d, nTimeMax = %d\n" 
675               ,nRowMax,nColMax,nTimeMax);
676         printf("nTimeBefore = %d, nTimeAfter = %d, nTimeTotal = %d\n"
677               ,nTimeBefore,nTimeAfter,nTimeTotal);
678         printf("row0 = %f, col0 = %f, time0 = %f\n"
679               ,row0,col0,time0);
680         printf("rowPadSize = %f, colPadSize = %f, timeBinSize = %f\n"
681                ,rowPadSize,colPadSize,timeBinSize); 
682       }
683        
684       // Don't analyze test hits and switched off detectors
685       if ((CheckDetector(plane,chamber,sector)) &&
686           (((Int_t) q) != 0)) {
687
688         if (detector != detectorOld) {
689
690           if (fDebug > 1) {
691             printf("<AliTRDdigitizer::MakeDigits> ");
692             printf("Get new container. New det = %d, Old det = %d\n"
693                   ,detector,detectorOld);
694           }
695           // Compress the old one if enabled
696           if ((fCompress) && (detectorOld > -1)) {
697             if (fDebug > 1) {
698               printf("<AliTRDdigitizer::MakeDigits> ");
699               printf("Compress the old container ...");
700             }
701             signals->Compress(1,0);
702             for (iDict = 0; iDict < kNDict; iDict++) {
703               dictionary[iDict]->Compress(1,0);
704             }
705             if (fDebug > 1) printf("done\n");
706           }
707           // Get the new container
708           signals = (AliTRDdataArrayF *) signalsArray->At(detector);
709           if (signals->GetNtime() == 0) {
710             // Allocate a new one if not yet existing
711             if (fDebug > 1) {
712               printf("<AliTRDdigitizer::MakeDigits> ");
713               printf("Allocate a new container ... ");
714             }
715             signals->Allocate(nRowMax,nColMax,nTimeTotal);
716           }
717           else if (fSimpleSim) {
718             // Clear an old one for the simple simulation
719             if (fDebug > 1) {
720               printf("<AliTRDdigitizer::MakeDigits> ");
721               printf("Clear a old container ... ");
722             }
723             signals->Clear();
724           }
725           else {
726             // Expand an existing one
727             if (fCompress) {
728               if (fDebug > 1) {
729                 printf("<AliTRDdigitizer::MakeDigits> ");
730                 printf("Expand an existing container ... ");
731               }
732               signals->Expand();
733             }
734           }
735           // The same for the dictionary
736           if (!fSimpleSim) {       
737             for (iDict = 0; iDict < kNDict; iDict++) {       
738               dictionary[iDict] = fDigitsManager->GetDictionary(detector,iDict);
739               if (dictionary[iDict]->GetNtime() == 0) {
740                 dictionary[iDict]->Allocate(nRowMax,nColMax,nTimeTotal);
741               }
742               else {
743                 if (fCompress) dictionary[iDict]->Expand();
744               }
745             }
746           }      
747           if (fDebug > 1) printf("done\n");
748           detectorOld = detector;
749         }
750
751         // Rotate the sectors on top of each other
752         if (fSimpleSim) {
753           rot[0] = pos[0];
754           rot[1] = pos[1];
755           rot[2] = pos[2];
756         }
757         else {
758           fGeo->Rotate(detector,pos,rot);
759         }
760
761         // The driftlength. It is negative if the hit is in the 
762         // amplification region.
763         Float_t driftlength = time0 - rot[0];
764
765         // Take also the drift in the amplification region into account
766         // The drift length is at the moment still the same, regardless of
767         // the position relativ to the wire. This non-isochronity needs still
768         // to be implemented.
769         Float_t driftlengthL = TMath::Abs(driftlength + kAmWidth);
770         if (fPar->ExBOn()) driftlengthL /= TMath::Sqrt(fPar->GetLorentzFactor());
771
772         // Loop over all electrons of this hit
773         // TR photons produce hits with negative charge
774         Int_t nEl = ((Int_t) TMath::Abs(q));
775         for (Int_t iEl = 0; iEl < nEl; iEl++) {
776
777           xyz[0] = rot[0];
778           xyz[1] = rot[1];
779           xyz[2] = rot[2];
780
781           // Electron attachment
782           if (fPar->ElAttachOn()) {
783             if (gRandom->Rndm() < (driftlengthL * elAttachProp)) 
784               continue;
785           }
786
787           // Apply the diffusion smearing
788           if (fPar->DiffusionOn()) {
789             if (!(fPar->Diffusion(driftlengthL,xyz))) continue;
790           }
791
792           // Apply E x B effects (depends on drift direction)
793           if (fPar->ExBOn()) { 
794             if (!(fPar->ExB(driftlength+kAmWidth,xyz))) continue;   
795           }
796
797           // The electron position after diffusion and ExB in pad coordinates 
798           // The pad row (z-direction)
799           Float_t rowDist   = xyz[2] - row0;
800           Int_t   rowE      = ((Int_t) (rowDist * divideRow));
801           if ((rowE < 0) || (rowE >= nRowMax)) continue;   
802           Float_t rowOffset = ((((Float_t) rowE) + 0.5) * rowPadSize) - rowDist;
803
804           // The pad column (rphi-direction)
805           Float_t col0tilt  = fPar->Col0Tilted(col0,rowOffset,plane);
806           Float_t colDist   = xyz[1] - col0tilt;
807           Int_t   colE      = ((Int_t) (colDist * divideCol));
808           if ((colE < 0) || (colE >= nColMax)) continue;   
809           Float_t colOffset = ((((Float_t) colE) + 0.5) * colPadSize) - colDist;    
810
811           // The time bin (negative for hits in the amplification region)
812           // In the amplification region the electrons drift from both sides
813           // to the middle (anode wire plane)
814           Float_t timeDist   = time0 - xyz[0];
815           Float_t timeOffset = 0;
816           Int_t   timeE      = 0;
817           if (timeDist > 0) {
818             // The time bin
819             timeE      = ((Int_t) (timeDist * divideTime));
820             // The distance of the position to the middle of the timebin
821             timeOffset = ((((Float_t) timeE) + 0.5) * timeBinSize) - timeDist;
822           }
823           else {
824             // Difference between half of the amplification gap width and
825             // the distance to the anode wire
826             Float_t anodeDist = kAmWidth - TMath::Abs(timeDist + kAmWidth);
827             // The time bin
828             timeE      = -1 * (((Int_t ) (anodeDist * divideTime)) + 1);
829             // The distance of the position to the middle of the timebin
830             timeOffset = ((((Float_t) timeE) + 0.5) * timeBinSize) + anodeDist;
831           }
832  
833           // Apply the gas gain including fluctuations
834           Float_t ggRndm = 0.0;
835           do {
836             ggRndm = gRandom->Rndm();
837           } while (ggRndm <= 0);
838           Int_t signal = (Int_t) (-fPar->GetGasGain() * TMath::Log(ggRndm));
839
840           // Apply the pad response 
841           if (fPar->PRFOn()) {
842             // The distance of the electron to the center of the pad 
843             // in units of pad width
844             Float_t dist = - colOffset * divideCol;
845             if (!(fPar->PadResponse(signal,dist,plane,padSignal))) continue;
846           }
847           else {
848             padSignal[0] = 0.0;
849             padSignal[1] = signal;
850             padSignal[2] = 0.0;
851           }
852
853           // Sample the time response inside the drift region
854           // + additional time bins before and after.
855           // The sampling is done always in the middle of the time bin
856           for (Int_t iTimeBin = TMath::Max(timeE-timeTRDbeg,        -nTimeBefore) 
857                     ;iTimeBin < TMath::Min(timeE+timeTRDend,nTimeMax+nTimeAfter ) 
858                     ;iTimeBin++) {
859
860             // Apply the time response
861             Float_t timeResponse = 1.0;
862             Float_t crossTalk    = 0.0;
863             Float_t time         = (iTimeBin - timeE) * timeBinSize + timeOffset;
864             if (fPar->TRFOn()) {
865               timeResponse = fPar->TimeResponse(time);
866             }
867             if (fPar->CTOn()) {
868               crossTalk    = fPar->CrossTalk(time);
869             }
870
871             signalOld[0] = 0.0;
872             signalOld[1] = 0.0;
873             signalOld[2] = 0.0;
874
875             for (iPad = 0; iPad < kNpad; iPad++) {
876
877               Int_t colPos = colE + iPad - 1;
878               if (colPos <        0) continue;
879               if (colPos >= nColMax) break;
880
881               // Add the signals
882               // Note: The time bin number is shifted by nTimeBefore to avoid negative
883               // time bins. This has to be subtracted later.
884               Int_t iCurrentTimeBin = iTimeBin + nTimeBefore;
885               signalOld[iPad]  = signals->GetDataUnchecked(rowE,colPos,iCurrentTimeBin);
886               if( colPos != colE ) {
887                 signalOld[iPad] += padSignal[iPad] * (timeResponse + crossTalk);
888               } 
889               else {
890                 signalOld[iPad] += padSignal[iPad] * timeResponse;
891               }
892               signals->SetDataUnchecked(rowE,colPos,iCurrentTimeBin,signalOld[iPad]);
893
894               // Store the track index in the dictionary
895               // Note: We store index+1 in order to allow the array to be compressed
896               if ((signalOld[iPad] > 0) && (!fSimpleSim)) { 
897                 for (iDict = 0; iDict < kNDict; iDict++) {
898                   Int_t oldTrack = dictionary[iDict]->GetDataUnchecked(rowE
899                                                                       ,colPos
900                                                                       ,iCurrentTimeBin);
901                   if (oldTrack == track+1) break;
902                   if (oldTrack ==       0) {
903                     dictionary[iDict]->SetDataUnchecked(rowE,colPos,iCurrentTimeBin,track+1);
904                     break;
905                   }
906                 }
907               }
908
909             } // Loop: pads
910
911           } // Loop: time bins
912
913         } // Loop: electrons of a single hit
914
915       } // If: detector and test hit
916
917       hit = (AliTRDhit *) fTRD->NextHit();   
918
919     } // Loop: hits of one primary track
920
921   } // Loop: primary tracks
922
923   if (fDebug > 0) {
924     printf("<AliTRDdigitizer::MakeDigits> ");
925     printf("Finished analyzing %d hits\n",countHits);
926   }
927
928   // The coupling factor
929   Float_t coupling = fPar->GetPadCoupling() 
930                    * fPar->GetTimeCoupling();
931
932   // The conversion factor
933   Float_t convert  = kEl2fC
934                    * fPar->GetChipGain();
935
936   // Loop through all chambers to finalize the digits
937   Int_t iDetBeg = 0;
938   Int_t iDetEnd = AliTRDgeometry::Ndet();
939   if (fSimpleSim) {
940     iDetBeg = fSimpleDet;
941     iDetEnd = iDetBeg + 1;
942   }
943   for (Int_t iDet = iDetBeg; iDet < iDetEnd; iDet++) {
944
945     Int_t plane       = fGeo->GetPlane(iDet);
946     Int_t sector      = fGeo->GetSector(iDet);
947     Int_t chamber     = fGeo->GetChamber(iDet);
948     Int_t nRowMax     = fPar->GetRowMax(plane,chamber,sector);
949     Int_t nColMax     = fPar->GetColMax(plane);
950     Int_t nTimeMax    = fPar->GetTimeMax();
951     Int_t nTimeTotal  = fPar->GetTimeTotal();
952
953     Double_t *inADC  = new Double_t[nTimeTotal];
954     Double_t *outADC = new Double_t[nTimeTotal];
955
956     if (fDebug > 0) {
957       printf("<AliTRDdigitizer::MakeDigits> ");
958       printf("Digitization for chamber %d\n",iDet);
959     }
960
961     // Add a container for the digits of this detector
962     digits = fDigitsManager->GetDigits(iDet);        
963     // Allocate memory space for the digits buffer
964     if (digits->GetNtime() == 0) {
965       digits->Allocate(nRowMax,nColMax,nTimeTotal);
966     }
967     else if (fSimpleSim) {
968       digits->Clear();
969     }
970  
971     // Get the signal container
972     signals = (AliTRDdataArrayF *) signalsArray->At(iDet);
973     if (signals->GetNtime() == 0) {
974       // Create missing containers
975       signals->Allocate(nRowMax,nColMax,nTimeTotal);      
976     }
977     else {
978       // Expand the container if neccessary
979       if (fCompress) signals->Expand();
980     }
981     // Create the missing dictionary containers
982     if (!fSimpleSim) {    
983       for (iDict = 0; iDict < kNDict; iDict++) {       
984         dictionary[iDict] = fDigitsManager->GetDictionary(iDet,iDict);
985         if (dictionary[iDict]->GetNtime() == 0) {
986           dictionary[iDict]->Allocate(nRowMax,nColMax,nTimeTotal);
987         }
988       } 
989     }
990
991     Int_t nDigits = 0;
992
993     // Don't create noise in detectors that are switched off
994     if (CheckDetector(plane,chamber,sector)) {
995
996       // Create the digits for this chamber
997       for (iRow  = 0; iRow  <  nRowMax;   iRow++ ) {
998         for (iCol  = 0; iCol  <  nColMax;   iCol++ ) {
999
1000           // Create summable digits
1001           if (fSDigits) {
1002
1003             for (iTime = 0; iTime < nTimeTotal; iTime++) {         
1004               Float_t signalAmp = signals->GetDataUnchecked(iRow,iCol,iTime);
1005               signalAmp *= fSDigitsScale;
1006               signalAmp  = TMath::Min(signalAmp,(Float_t) 1.0e9);
1007               Int_t adc  = (Int_t) signalAmp;
1008               if (adc > 0) nDigits++;
1009               digits->SetDataUnchecked(iRow,iCol,iTime,adc);
1010             }
1011
1012           }
1013           // Create normal digits
1014           else {
1015
1016             for (iTime = 0; iTime < nTimeTotal; iTime++) {         
1017               Float_t signalAmp = signals->GetDataUnchecked(iRow,iCol,iTime);
1018               // Pad and time coupling
1019               signalAmp *= coupling;
1020               // Add the noise, starting from minus ADC baseline in electrons
1021               Double_t baselineEl = fPar->GetADCbaseline() * (fPar->GetADCinRange()
1022                                                            / fPar->GetADCoutRange()) 
1023                                                            / convert;
1024               signalAmp  = TMath::Max((Double_t) gRandom->Gaus(signalAmp,fPar->GetNoise())
1025                                      ,-baselineEl);
1026               // Convert to mV
1027               signalAmp *= convert;
1028               // Add ADC baseline in mV
1029               signalAmp += fPar->GetADCbaseline() * (fPar->GetADCinRange()
1030                                                    / fPar->GetADCoutRange());
1031               // Convert to ADC counts. Set the overflow-bit fADCoutRange if the 
1032               // signal is larger than fADCinRange
1033               Int_t adc  = 0;
1034               if (signalAmp >= fPar->GetADCinRange()) {
1035                 adc = ((Int_t) fPar->GetADCoutRange());
1036               }
1037               else {
1038                 adc = ((Int_t) (signalAmp * (fPar->GetADCoutRange() 
1039                                            / fPar->GetADCinRange())));
1040               }
1041               inADC[iTime]  = adc;
1042               outADC[iTime] = adc;
1043             }
1044
1045             // Apply the tail cancelation via the digital filter
1046             if (fPar->TCOn()) {
1047               DeConvExp(inADC,outADC,nTimeTotal,fPar->GetTCnexp());
1048             }
1049
1050             for (iTime = 0; iTime < nTimeTotal; iTime++) {   
1051               // Store the amplitude of the digit if above threshold
1052               if (outADC[iTime] > fPar->GetADCthreshold()) {
1053                 if (fDebug > 2) {
1054                   printf("  iRow = %d, iCol = %d, iTime = %d, adc = %f\n"
1055                         ,iRow,iCol,iTime,outADC[iTime]);
1056                 }
1057                 nDigits++;
1058                 digits->SetDataUnchecked(iRow,iCol,iTime,((Int_t) outADC[iTime]));
1059               }
1060             }
1061
1062           }
1063
1064         }
1065       }
1066
1067     }
1068
1069     // Compress the arrays
1070     if (!fSimpleSim) {  
1071       digits->Compress(1,0);
1072       for (iDict = 0; iDict < kNDict; iDict++) {
1073         dictionary[iDict]->Compress(1,0);
1074       }
1075
1076       totalSizeDigits += digits->GetSize();
1077       totalSizeDict0  += dictionary[0]->GetSize();
1078       totalSizeDict1  += dictionary[1]->GetSize();
1079       totalSizeDict2  += dictionary[2]->GetSize();
1080
1081       Float_t nPixel = nRowMax * nColMax * nTimeMax;
1082       if (fDebug > 0) {
1083         printf("<AliTRDdigitizer::MakeDigits> ");
1084         printf("Found %d digits in detector %d (%3.0f).\n"
1085               ,nDigits,iDet
1086               ,100.0 * ((Float_t) nDigits) / nPixel);
1087       } 
1088
1089       if (fCompress) signals->Compress(1,0);
1090
1091     }
1092
1093     delete [] inADC;
1094     delete [] outADC;
1095
1096   }
1097
1098   if (signalsArray) {
1099     delete signalsArray;
1100     signalsArray = 0;
1101   }
1102
1103   if (fDebug > 0) {
1104     printf("<AliTRDdigitizer::MakeDigits> ");
1105     printf("Total number of analyzed hits = %d\n",countHits);
1106     if (!fSimpleSim) {    
1107       printf("<AliTRDdigitizer::MakeDigits> ");
1108       printf("Total digits data size = %d, %d, %d, %d\n",totalSizeDigits
1109                                                         ,totalSizeDict0
1110                                                         ,totalSizeDict1
1111                                                         ,totalSizeDict2);        
1112     }
1113   }
1114
1115   return kTRUE;
1116
1117 }
1118
1119 //_____________________________________________________________________________
1120 void AliTRDdigitizer::AddSDigitsManager(AliTRDdigitsManager *man)
1121 {
1122   //
1123   // Add a digits manager for s-digits to the input list.
1124   //
1125
1126   fSDigitsManagerList->Add(man);
1127
1128 }
1129
1130 //_____________________________________________________________________________
1131 void AliTRDdigitizer::DeleteSDigitsManager()
1132 {
1133   //
1134   // Removes digits manager from the input list.
1135   //
1136
1137   fSDigitsManagerList->Delete();
1138
1139 }
1140
1141 //_____________________________________________________________________________
1142 Bool_t AliTRDdigitizer::ConvertSDigits()
1143 {
1144   //
1145   // Converts s-digits to normal digits
1146   //
1147
1148   // Number of track dictionary arrays
1149   const Int_t    kNDict = AliTRDdigitsManager::kNDict;
1150
1151   // Converts number of electrons to fC
1152   const Double_t kEl2fC = 1.602E-19 * 1.0E15; 
1153
1154   Int_t iDict = 0;
1155   Int_t iRow;
1156   Int_t iCol;
1157   Int_t iTime;
1158
1159   if (!fPar) {    
1160     fPar = new AliTRDparameter("TRDparameter","Standard parameter");
1161     if (fDebug > 0) {
1162       printf("<AliTRDdigitizer::ConvertSDigits> ");
1163       printf("Create the default parameter object\n");
1164     }
1165   }
1166
1167   Double_t sDigitsScale = 1.0 / GetSDigitsScale();
1168   Double_t noise        = fPar->GetNoise();
1169   Double_t padCoupling  = fPar->GetPadCoupling();
1170   Double_t timeCoupling = fPar->GetTimeCoupling();
1171   Double_t chipGain     = fPar->GetChipGain();
1172   Double_t coupling     = padCoupling * timeCoupling;
1173   Double_t convert      = kEl2fC * chipGain;
1174   Double_t adcInRange   = fPar->GetADCinRange();
1175   Double_t adcOutRange  = fPar->GetADCoutRange();
1176   Int_t    adcThreshold = fPar->GetADCthreshold();
1177   Int_t    adcBaseline  = fPar->GetADCbaseline();   
1178
1179   AliTRDdataArrayI *digitsIn;
1180   AliTRDdataArrayI *digitsOut;
1181   AliTRDdataArrayI *dictionaryIn[kNDict];
1182   AliTRDdataArrayI *dictionaryOut[kNDict];
1183
1184   // Loop through the detectors
1185   for (Int_t iDet = 0; iDet < AliTRDgeometry::Ndet(); iDet++) {
1186
1187     if (fDebug > 0) {
1188       printf("<AliTRDdigitizer::ConvertSDigits> ");
1189       printf("Convert detector %d to digits.\n",iDet);
1190     }
1191
1192     Int_t plane      = fGeo->GetPlane(iDet);
1193     Int_t sector     = fGeo->GetSector(iDet);
1194     Int_t chamber    = fGeo->GetChamber(iDet);
1195     Int_t nRowMax    = fPar->GetRowMax(plane,chamber,sector);
1196     Int_t nColMax    = fPar->GetColMax(plane);
1197     Int_t nTimeTotal = fPar->GetTimeTotal();
1198
1199     Double_t *inADC  = new Double_t[nTimeTotal];
1200     Double_t *outADC = new Double_t[nTimeTotal];
1201
1202     digitsIn  = fSDigitsManager->GetDigits(iDet);
1203     digitsIn->Expand();
1204     digitsOut = fDigitsManager->GetDigits(iDet);
1205     digitsOut->Allocate(nRowMax,nColMax,nTimeTotal);
1206     for (iDict = 0; iDict < kNDict; iDict++) {
1207       dictionaryIn[iDict]  = fSDigitsManager->GetDictionary(iDet,iDict);
1208       dictionaryIn[iDict]->Expand();
1209       dictionaryOut[iDict] = fDigitsManager->GetDictionary(iDet,iDict);
1210       dictionaryOut[iDict]->Allocate(nRowMax,nColMax,nTimeTotal);
1211     }
1212
1213     for (iRow  = 0; iRow  <  nRowMax;   iRow++ ) {
1214       for (iCol  = 0; iCol  <  nColMax;   iCol++ ) {
1215
1216         for (iTime = 0; iTime < nTimeTotal; iTime++) {         
1217           Double_t signal = (Double_t) digitsIn->GetDataUnchecked(iRow,iCol,iTime);
1218           signal *= sDigitsScale;
1219           // Pad and time coupling
1220           signal *= coupling;
1221           // Add the noise, starting from minus ADC baseline in electrons
1222           Double_t baselineEl = adcBaseline * (adcInRange / adcOutRange) / convert;
1223           signal  = TMath::Max((Double_t) gRandom->Gaus(signal,noise),-baselineEl);
1224           // Convert to mV
1225           signal *= convert;
1226           // add ADC baseline in mV
1227           signal += adcBaseline * (adcInRange / adcOutRange);
1228           // Convert to ADC counts. Set the overflow-bit adcOutRange if the 
1229           // signal is larger than adcInRange
1230           Int_t adc  = 0;
1231           if (signal >= adcInRange) {
1232             adc = ((Int_t) adcOutRange);
1233           }
1234           else {
1235             adc = ((Int_t) (signal * (adcOutRange / adcInRange)));
1236           }
1237           inADC[iTime]  = adc;
1238           outADC[iTime] = adc;
1239         }
1240
1241         // Apply the tail cancelation via the digital filter
1242         if (fPar->TCOn()) {
1243           DeConvExp(inADC,outADC,nTimeTotal,fPar->GetTCnexp());
1244         }
1245
1246         for (iTime = 0; iTime < nTimeTotal; iTime++) {   
1247           // Store the amplitude of the digit if above threshold
1248           if (outADC[iTime] > adcThreshold) {
1249             digitsOut->SetDataUnchecked(iRow,iCol,iTime,((Int_t) outADC[iTime]));
1250             // Copy the dictionary
1251             for (iDict = 0; iDict < kNDict; iDict++) { 
1252               Int_t track = dictionaryIn[iDict]->GetDataUnchecked(iRow,iCol,iTime);
1253               dictionaryOut[iDict]->SetDataUnchecked(iRow,iCol,iTime,track);
1254             }
1255           }
1256         }
1257
1258       }
1259     }
1260
1261     if (fCompress) {
1262       digitsIn->Compress(1,0);
1263       digitsOut->Compress(1,0);
1264       for (iDict = 0; iDict < kNDict; iDict++) {
1265         dictionaryIn[iDict]->Compress(1,0);
1266         dictionaryOut[iDict]->Compress(1,0);
1267       }
1268     }
1269
1270     delete [] inADC;
1271     delete [] outADC;
1272
1273   }    
1274
1275   return kTRUE;
1276
1277 }
1278
1279 //_____________________________________________________________________________
1280 Bool_t AliTRDdigitizer::MergeSDigits()
1281 {
1282   //
1283   // Merges the input s-digits:
1284   //   - The amplitude of the different inputs are summed up.
1285   //   - Of the track IDs from the input dictionaries only one is
1286   //     kept for each input. This works for maximal 3 different merged inputs.
1287   //
1288
1289   // Number of track dictionary arrays
1290   const Int_t kNDict = AliTRDdigitsManager::kNDict;
1291
1292   if (!fPar) {
1293     fPar = new AliTRDparameter("TRDparameter","Standard parameter");
1294     if (fDebug > 0) {
1295       printf("<AliTRDdigitizer::MergeSDigits> ");
1296       printf("Create the default parameter object\n");
1297     }
1298   }
1299
1300   Int_t iDict = 0;
1301   Int_t jDict = 0;
1302
1303   AliTRDdataArrayI *digitsA;
1304   AliTRDdataArrayI *digitsB;
1305   AliTRDdataArrayI *dictionaryA[kNDict];
1306   AliTRDdataArrayI *dictionaryB[kNDict];
1307
1308   // Get the first s-digits
1309   fSDigitsManager = (AliTRDdigitsManager *) fSDigitsManagerList->First();
1310   if (!fSDigitsManager) return kFALSE;
1311
1312   // Loop through the other sets of s-digits
1313   AliTRDdigitsManager *mergeSDigitsManager;
1314   mergeSDigitsManager = (AliTRDdigitsManager *) 
1315                         fSDigitsManagerList->After(fSDigitsManager);
1316
1317   if (fDebug > 0) {
1318     if (mergeSDigitsManager) {
1319       printf("<AliTRDdigitizer::MergeSDigits> ");
1320       printf("Merge %d input files.\n",fSDigitsManagerList->GetSize());
1321     }
1322     else {
1323       printf("<AliTRDdigitizer::MergeSDigits> ");
1324       printf("Only one input file.\n");
1325     }
1326   }
1327
1328   Int_t iMerge = 0;
1329   while (mergeSDigitsManager) {
1330
1331     iMerge++;
1332
1333     // Loop through the detectors
1334     for (Int_t iDet = 0; iDet < AliTRDgeometry::Ndet(); iDet++) {
1335
1336       Int_t plane      = fGeo->GetPlane(iDet);
1337       Int_t sector     = fGeo->GetSector(iDet);
1338       Int_t chamber    = fGeo->GetChamber(iDet);
1339       Int_t nRowMax    = fPar->GetRowMax(plane,chamber,sector);
1340       Int_t nColMax    = fPar->GetColMax(plane);
1341       Int_t nTimeTotal = fPar->GetTimeTotal();
1342
1343       // Loop through the pixels of one detector and add the signals
1344       digitsA = fSDigitsManager->GetDigits(iDet);
1345       digitsB = mergeSDigitsManager->GetDigits(iDet);
1346       digitsA->Expand();
1347       digitsB->Expand();
1348       for (iDict = 0; iDict < kNDict; iDict++) {
1349         dictionaryA[iDict] = fSDigitsManager->GetDictionary(iDet,iDict);
1350         dictionaryB[iDict] = mergeSDigitsManager->GetDictionary(iDet,iDict);
1351         dictionaryA[iDict]->Expand();
1352         dictionaryB[iDict]->Expand();
1353       }
1354
1355       // Merge only detectors that contain a signal
1356       Bool_t doMerge = kTRUE;
1357       if (fMergeSignalOnly) {
1358         if (digitsA->GetOverThreshold(0) == 0) {
1359           doMerge = kFALSE;
1360         }
1361       }
1362
1363       if (doMerge) {
1364
1365         if (fDebug > 0) {
1366           printf("<AliTRDdigitizer::MergeSDigits> ");
1367           printf("Merge detector %d of input no.%d\n",iDet,iMerge+1);
1368         }
1369
1370         for (Int_t iRow  = 0; iRow  <  nRowMax;   iRow++ ) {
1371           for (Int_t iCol  = 0; iCol  <  nColMax;   iCol++ ) {
1372             for (Int_t iTime = 0; iTime < nTimeTotal; iTime++) {         
1373
1374               // Add the amplitudes of the summable digits 
1375               Int_t ampA = digitsA->GetDataUnchecked(iRow,iCol,iTime);
1376               Int_t ampB = digitsB->GetDataUnchecked(iRow,iCol,iTime);
1377               ampA += ampB;
1378               digitsA->SetDataUnchecked(iRow,iCol,iTime,ampA);
1379
1380              // Add the mask to the track id if defined.
1381               for (iDict = 0; iDict < kNDict; iDict++) {
1382                 Int_t trackB = dictionaryB[iDict]->GetDataUnchecked(iRow,iCol,iTime);
1383                 if ((fMasks) && (trackB > 0)) {
1384                   for (jDict = 0; jDict < kNDict; jDict++) { 
1385                     Int_t trackA = dictionaryA[iDict]->GetDataUnchecked(iRow,iCol,iTime);
1386                     if (trackA == 0) {
1387                       trackA = trackB + fMasks[iMerge];
1388                       dictionaryA[iDict]->SetDataUnchecked(iRow,iCol,iTime,trackA);
1389                     }
1390                   }
1391                 }
1392               }
1393
1394             }
1395           }
1396         }
1397
1398       }
1399
1400       if (fCompress) {
1401         digitsA->Compress(1,0);
1402         digitsB->Compress(1,0);
1403         for (iDict = 0; iDict < kNDict; iDict++) {
1404           dictionaryA[iDict]->Compress(1,0);
1405           dictionaryB[iDict]->Compress(1,0);
1406         }
1407       }
1408
1409     }    
1410
1411     // The next set of s-digits
1412     mergeSDigitsManager = (AliTRDdigitsManager *) 
1413                           fSDigitsManagerList->After(mergeSDigitsManager);
1414
1415   }
1416
1417   return kTRUE;
1418
1419 }
1420
1421 //_____________________________________________________________________________
1422 Bool_t AliTRDdigitizer::SDigits2Digits()
1423 {
1424   //
1425   // Merges the input s-digits and converts them to normal digits
1426   //
1427
1428   if (!MergeSDigits()) return kFALSE;
1429
1430   return ConvertSDigits();
1431
1432 }
1433
1434 //_____________________________________________________________________________
1435 Bool_t AliTRDdigitizer::CheckDetector(Int_t plane, Int_t chamber, Int_t sector)
1436 {
1437   //
1438   // Checks whether a detector is enabled
1439   //
1440
1441   if (fSimpleSim) return kTRUE; 
1442
1443   if ((fTRD->GetSensChamber() >=       0) &&
1444       (fTRD->GetSensChamber() != chamber)) return kFALSE;
1445   if ((fTRD->GetSensPlane()   >=       0) &&
1446       (fTRD->GetSensPlane()   !=   plane)) return kFALSE;
1447   if ( fTRD->GetSensSector()  >=       0) {
1448     Int_t sens1 = fTRD->GetSensSector();
1449     Int_t sens2 = sens1 + fTRD->GetSensSectorRange();
1450     sens2 -= ((Int_t) (sens2 / AliTRDgeometry::Nsect())) 
1451            * AliTRDgeometry::Nsect();
1452     if (sens1 < sens2) {
1453       if ((sector < sens1) || (sector >= sens2)) return kFALSE;
1454     }
1455     else {
1456       if ((sector < sens1) && (sector >= sens2)) return kFALSE;
1457     }
1458   }
1459
1460   return kTRUE;
1461
1462 }
1463
1464 //_____________________________________________________________________________
1465 Bool_t AliTRDdigitizer::WriteDigits() const
1466 {
1467   //
1468   // Writes out the TRD-digits and the dictionaries
1469   //
1470
1471   // Store the digits and the dictionary in the tree
1472   return fDigitsManager->WriteDigits();
1473
1474 }
1475
1476 //_____________________________________________________________________________
1477 void AliTRDdigitizer::DeConvExp(Double_t *source, Double_t *target
1478                               , Int_t n, Int_t nexp) 
1479 {
1480   //
1481   // Does the deconvolution by the digital filter.
1482   //
1483   // Author:        Marcus Gutfleisch, KIP Heidelberg
1484   // Optimized for: New TRF from Venelin Angelov, simulated with CADENCE
1485   //                Pad-ground capacitance = 25 pF
1486   //                Pad-pad cross talk capacitance = 6 pF
1487   //                For 10 MHz digitization, corresponding to 20 time bins
1488   //                in the drift region
1489   //
1490
1491   Double_t rates[2];
1492   Double_t coefficients[2];
1493
1494   /* initialize (coefficient = alpha, rates = lambda) */
1495   
1496   if( nexp == 1 ) {
1497     rates[0] = 0.466998;
1498     /* no rescaling */
1499     coefficients[0] = 1.0;
1500   }
1501   if( nexp == 2 ) {
1502     rates[0] = 0.8988162;
1503     coefficients[0] = 0.11392069;
1504     rates[1] = 0.3745688;
1505     coefficients[1] = 0.8860793;
1506     /* no rescaling */
1507     Float_t sumc = coefficients[0]+coefficients[1];
1508     coefficients[0] /= sumc;
1509     coefficients[1] /= sumc;
1510   }
1511       
1512   Int_t i, k;
1513   Double_t reminder[2];
1514   Double_t correction, result;
1515
1516   /* attention: computation order is important */
1517   correction=0.0;
1518   for ( k = 0; k < nexp; k++ ) reminder[k]=0.0;
1519     
1520   for ( i = 0; i < n; i++ ) {
1521     result = ( source[i] - correction );    /* no rescaling */
1522     target[i] = result;
1523     
1524     for ( k = 0; k < nexp; k++ ) reminder[k] = rates[k] 
1525                              * ( reminder[k] + coefficients[k] * result);
1526       
1527     correction=0.0;
1528     for ( k = 0; k < nexp; k++ ) correction += reminder[k];
1529   }
1530   
1531 }
1532
1533 //_____________________________________________________________________________
1534 void AliTRDdigitizer::InitOutput(Int_t iEvent)
1535 {
1536   //
1537   // Initializes the output branches
1538   //
1539
1540   fEvent = iEvent;
1541    
1542   if (!fRunLoader)
1543    {
1544      Error("InitOutput","Run Loader is NULL");
1545      return;  
1546    }
1547   AliLoader* loader = fRunLoader->GetLoader("TRDLoader");
1548   if (!loader)
1549    {
1550      Error("Open","Can not get TRD loader from Run Loader");
1551      return;
1552    }
1553
1554   TTree* tree = 0;
1555   
1556   if (fSDigits)
1557    { 
1558    //if we produce SDigits
1559     tree = loader->TreeS();
1560     if (!tree)
1561      {
1562       loader->MakeTree("S");
1563       tree = loader->TreeS();
1564      }
1565    }
1566   else
1567    {//if we produce Digits
1568      tree = loader->TreeD();
1569      if (!tree)
1570       {
1571        loader->MakeTree("D");
1572        tree = loader->TreeD();
1573       }
1574    }
1575   fDigitsManager->SetEvent(iEvent);
1576   fDigitsManager->MakeBranch(tree);
1577
1578 }