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