]> git.uio.no Git - u/mrichter/AliRoot.git/blob - TRD/AliTRDdigitizer.cxx
Revision of AliTRDmcmSim + coding rule violations
[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 //                                                                        //
22 //  Authors: C. Blume (blume@ikf.uni-frankfurt.de)                        //
23 //           C. Lippmann                                                  //
24 //           B. Vulpescu                                                  //
25 //                                                                        //
26 //  The following effects are included:                                   //
27 //      - Diffusion                                                       //
28 //      - ExB effects                                                     //
29 //      - Gas gain including fluctuations                                 //
30 //      - Pad-response (simple Gaussian approximation)                    //
31 //      - Time-response                                                   //
32 //      - Electronics noise                                               //
33 //      - Electronics gain                                                //
34 //      - Digitization                                                    //
35 //      - Zero suppression                                                //
36 //                                                                        //
37 ////////////////////////////////////////////////////////////////////////////
38
39 #include <TF1.h>
40 #include <TFile.h>
41 #include <TGeoGlobalMagField.h>
42 #include <TGeoManager.h>
43 #include <TList.h>
44 #include <TMath.h>
45 #include <TROOT.h>
46 #include <TRandom.h>
47 #include <TTask.h>
48 #include <TTree.h>
49 #include <TVector.h>
50
51 #include "AliRun.h"
52 #include "AliMC.h"
53 #include "AliRunLoader.h"
54 #include "AliLoader.h"
55 #include "AliConfig.h"
56 #include "AliMagF.h"
57 #include "AliRunDigitizer.h"
58 #include "AliRunLoader.h"
59 #include "AliLoader.h"
60 #include "AliLog.h"
61 #include "AliTRD.h"
62 #include "AliTRDhit.h"
63 #include "AliTRDdigitizer.h"
64
65 #include "AliTRDarrayDictionary.h"
66 #include "AliTRDarrayADC.h"
67 #include "AliTRDarraySignal.h"
68 #include "AliTRDdigitsManager.h"
69 #include "AliTRDgeometry.h"
70 #include "AliTRDpadPlane.h"
71 #include "AliTRDcalibDB.h"
72 #include "AliTRDSimParam.h"
73 #include "AliTRDCommonParam.h"
74 #include "AliTRDfeeParam.h"
75 #include "AliTRDmcmSim.h"
76 #include "Cal/AliTRDCalROC.h"
77 #include "Cal/AliTRDCalDet.h"
78
79 ClassImp(AliTRDdigitizer)
80
81 //_____________________________________________________________________________
82 AliTRDdigitizer::AliTRDdigitizer()
83   :AliDigitizer()
84   ,fRunLoader(0)
85   ,fDigitsManager(0)
86   ,fSDigitsManager(0)
87   ,fSDigitsManagerList(0)
88   ,fTRD(0)
89   ,fGeo(0)
90   ,fEvent(0)
91   ,fMasks(0)
92   ,fCompress(kTRUE)
93   ,fSDigits(kFALSE)
94   ,fMergeSignalOnly(kFALSE)
95 {
96   //
97   // AliTRDdigitizer default constructor
98   //
99   
100   Init();
101
102 }
103
104 //_____________________________________________________________________________
105 AliTRDdigitizer::AliTRDdigitizer(const Text_t *name, const Text_t *title)              
106   :AliDigitizer(name,title)
107   ,fRunLoader(0)
108   ,fDigitsManager(0)
109   ,fSDigitsManager(0)
110   ,fSDigitsManagerList(0)
111   ,fTRD(0)
112   ,fGeo(0)
113   ,fEvent(0)
114   ,fMasks(0)
115   ,fCompress(kTRUE)
116   ,fSDigits(kFALSE)
117   ,fMergeSignalOnly(kFALSE)
118 {
119   //
120   // AliTRDdigitizer constructor
121   //
122
123   Init();
124
125 }
126
127 //_____________________________________________________________________________
128 AliTRDdigitizer::AliTRDdigitizer(AliRunDigitizer *manager
129                                , const Text_t *name, const Text_t *title)
130   :AliDigitizer(manager,name,title)
131   ,fRunLoader(0)
132   ,fDigitsManager(0)
133   ,fSDigitsManager(0)
134   ,fSDigitsManagerList(0)
135   ,fTRD(0)
136   ,fGeo(0)
137   ,fEvent(0)
138   ,fMasks(0)
139   ,fCompress(kTRUE)
140   ,fSDigits(kFALSE)
141   ,fMergeSignalOnly(kFALSE)
142 {
143   //
144   // AliTRDdigitizer constructor
145   //
146
147   Init();
148
149 }
150
151 //_____________________________________________________________________________
152 AliTRDdigitizer::AliTRDdigitizer(AliRunDigitizer *manager)
153   :AliDigitizer(manager,"AliTRDdigitizer","TRD digitizer")
154   ,fRunLoader(0)
155   ,fDigitsManager(0)
156   ,fSDigitsManager(0)
157   ,fSDigitsManagerList(0)
158   ,fTRD(0)
159   ,fGeo(0)
160   ,fEvent(0)
161   ,fMasks(0)
162   ,fCompress(kTRUE)
163   ,fSDigits(kFALSE)
164   ,fMergeSignalOnly(kFALSE)
165 {
166   //
167   // AliTRDdigitizer constructor
168   //
169
170   Init();
171
172 }
173
174 //_____________________________________________________________________________
175 Bool_t AliTRDdigitizer::Init()
176 {
177   //
178   // Initialize the digitizer with default values
179   //
180
181   fRunLoader          = 0;
182   fDigitsManager      = 0;
183   fSDigitsManager     = 0;
184   fSDigitsManagerList = 0;
185   fTRD                = 0;
186   fGeo                = 0;
187
188   fEvent              = 0;
189   fMasks              = 0;
190   fCompress           = kTRUE;
191   fSDigits            = kFALSE;
192   fMergeSignalOnly    = kFALSE;
193   
194   return AliDigitizer::Init();
195
196 }
197
198 //_____________________________________________________________________________
199 AliTRDdigitizer::AliTRDdigitizer(const AliTRDdigitizer &d)
200   :AliDigitizer(d)
201   ,fRunLoader(0)
202   ,fDigitsManager(0)
203   ,fSDigitsManager(0)
204   ,fSDigitsManagerList(0)
205   ,fTRD(0)
206   ,fGeo(0)
207   ,fEvent(0)
208   ,fMasks(0)
209   ,fCompress(d.fCompress)
210   ,fSDigits(d.fSDigits)
211   ,fMergeSignalOnly(d.fMergeSignalOnly)
212 {
213   //
214   // AliTRDdigitizer copy constructor
215   //
216
217 }
218
219 //_____________________________________________________________________________
220 AliTRDdigitizer::~AliTRDdigitizer()
221 {
222   //
223   // AliTRDdigitizer destructor
224   //
225
226   if (fDigitsManager) {
227     delete fDigitsManager;
228     fDigitsManager      = 0;
229   }
230
231   if (fDigitsManager) {              //typo? fSDigitsManager?
232     delete fSDigitsManager;
233     fSDigitsManager     = 0;
234   }
235
236   if (fSDigitsManagerList) {
237     fSDigitsManagerList->Delete();
238     delete fSDigitsManagerList;
239     fSDigitsManagerList = 0;
240   }
241
242   if (fMasks) {
243     delete [] fMasks;
244     fMasks       = 0;
245   }
246
247   if (fGeo) {
248     delete fGeo;
249     fGeo = 0;
250   }
251
252 }
253
254 //_____________________________________________________________________________
255 AliTRDdigitizer &AliTRDdigitizer::operator=(const AliTRDdigitizer &d)
256 {
257   //
258   // Assignment operator
259   //
260
261   if (this != &d) {
262     ((AliTRDdigitizer &) d).Copy(*this);
263   }
264
265   return *this;
266
267 }
268
269 //_____________________________________________________________________________
270 void AliTRDdigitizer::Copy(TObject &d) const
271 {
272   //
273   // Copy function
274   //
275
276   ((AliTRDdigitizer &) d).fRunLoader          = 0;
277   ((AliTRDdigitizer &) d).fDigitsManager      = 0;
278   ((AliTRDdigitizer &) d).fSDigitsManager     = 0;
279   ((AliTRDdigitizer &) d).fSDigitsManagerList = 0;
280   ((AliTRDdigitizer &) d).fTRD                = 0;
281   ((AliTRDdigitizer &) d).fGeo                = 0;
282   ((AliTRDdigitizer &) d).fEvent              = 0;
283   ((AliTRDdigitizer &) d).fMasks              = 0;
284   ((AliTRDdigitizer &) d).fCompress           = fCompress;
285   ((AliTRDdigitizer &) d).fSDigits            = fSDigits;
286   ((AliTRDdigitizer &) d).fMergeSignalOnly    = fMergeSignalOnly;
287                                        
288   AliTRDdigitizer& target = (AliTRDdigitizer &) d;
289
290 }
291
292 //_____________________________________________________________________________
293 void AliTRDdigitizer::Exec(Option_t *option)
294 {
295   //
296   // Executes the merging
297   //
298
299   Int_t iInput;
300
301   AliTRDdigitsManager *sdigitsManager;
302
303   TString optionString = option;
304   if (optionString.Contains("deb")) {
305     AliLog::SetClassDebugLevel("AliTRDdigitizer",1);
306     AliInfo("Called with debug option");
307   }
308
309   // The AliRoot file is already connected by the manager
310   AliRunLoader *inrl = 0x0;
311   
312   if (gAlice) {
313     AliDebug(1,"AliRun object found on file.");
314   }
315   else {
316     inrl = AliRunLoader::GetRunLoader(fManager->GetInputFolderName(0));
317     inrl->LoadgAlice();
318     gAlice = inrl->GetAliRun();
319     if (!gAlice) {
320       AliError("Could not find AliRun object.")
321       return;
322     }
323   }
324                                                                            
325   Int_t nInput = fManager->GetNinputs();
326   fMasks       = new Int_t[nInput];
327   for (iInput = 0; iInput < nInput; iInput++) {
328     fMasks[iInput] = fManager->GetMask(iInput);
329   }
330
331   //
332   // Initialization
333   //
334
335   AliRunLoader *orl = AliRunLoader::GetRunLoader(fManager->GetOutputFolderName());
336
337   if (InitDetector()) {
338
339     AliLoader *ogime = orl->GetLoader("TRDLoader");
340
341     TTree *tree = 0;
342     if (fSDigits) { 
343       // If we produce SDigits
344       tree = ogime->TreeS();
345       if (!tree) {
346         ogime->MakeTree("S");
347         tree = ogime->TreeS();
348       }
349     }
350     else {
351       // If we produce Digits
352       tree = ogime->TreeD();
353       if (!tree) {
354         ogime->MakeTree("D");
355         tree = ogime->TreeD();
356       }
357     }
358
359     MakeBranch(tree);
360
361   }
362  
363   for (iInput = 0; iInput < nInput; iInput++) {
364
365     AliDebug(1,Form("Add input stream %d",iInput));
366
367     // Check if the input tree exists
368     inrl = AliRunLoader::GetRunLoader(fManager->GetInputFolderName(iInput));
369     AliLoader *gime = inrl->GetLoader("TRDLoader");
370
371     TTree *treees = gime->TreeS();
372     if (treees == 0x0) {
373       if (gime->LoadSDigits()) {
374         AliError(Form("Error Occured while loading S. Digits for input %d.",iInput));
375         return;
376       }
377       treees = gime->TreeS();
378     }
379     
380     if (treees == 0x0) {
381       AliError(Form("Input stream %d does not exist",iInput));
382       return;
383     } 
384
385     // Read the s-digits via digits manager
386     sdigitsManager = new AliTRDdigitsManager();
387     sdigitsManager->SetSDigits(kTRUE);
388     
389     AliRunLoader *rl = AliRunLoader::GetRunLoader(fManager->GetInputFolderName(iInput));
390     AliLoader *gimme = rl->GetLoader("TRDLoader");
391     if (!gimme->TreeS()) 
392       {
393         gimme->LoadSDigits();
394       }
395
396     sdigitsManager->ReadDigits(gimme->TreeS());
397    
398     // Add the s-digits to the input list 
399     AddSDigitsManager(sdigitsManager);
400
401   }
402
403   // Convert the s-digits to normal digits
404   AliDebug(1,"Do the conversion");
405   SDigits2Digits();
406
407   // Store the digits
408   AliDebug(1,"Write the digits");
409   fDigitsManager->WriteDigits();
410
411   // Write parameters
412   orl->CdGAFile();
413
414   // Clean up
415   DeleteSDigitsManager();
416
417   AliDebug(1,"Done");
418
419 }
420
421 //_____________________________________________________________________________
422 Bool_t AliTRDdigitizer::Open(const Char_t *file, Int_t nEvent)
423 {
424   //
425   // Opens a ROOT-file with TRD-hits and reads in the hit-tree
426   //
427   // Connect the AliRoot file containing Geometry, Kine, and Hits
428   //  
429
430   TString evfoldname = AliConfig::GetDefaultEventFolderName();
431
432   fRunLoader = AliRunLoader::GetRunLoader(evfoldname);
433   if (!fRunLoader) {
434     fRunLoader = AliRunLoader::Open(file,evfoldname,"UPDATE");
435   }  
436   if (!fRunLoader) {
437     AliError(Form("Can not open session for file %s.",file));
438     return kFALSE;
439   }
440    
441   if (!fRunLoader->GetAliRun()) {
442     fRunLoader->LoadgAlice();
443   }
444   gAlice = fRunLoader->GetAliRun();
445   
446   if (gAlice) {
447     AliDebug(1,"AliRun object found on file.");
448   }
449   else {
450     AliError("Could not find AliRun object.");
451     return kFALSE;
452   }
453
454   fEvent = nEvent;
455
456   AliLoader *loader = fRunLoader->GetLoader("TRDLoader");
457   if (!loader) {
458     AliError("Can not get TRD loader from Run Loader");
459     return kFALSE;
460   }
461   
462   if (InitDetector()) {
463     TTree *tree = 0;
464     if (fSDigits) { 
465       // If we produce SDigits
466       tree = loader->TreeS();
467       if (!tree) {
468         loader->MakeTree("S");
469         tree = loader->TreeS();
470       }
471     }
472     else {
473       // If we produce Digits
474       tree = loader->TreeD();
475       if (!tree) {
476         loader->MakeTree("D");
477         tree = loader->TreeD();
478       }
479     }
480     return MakeBranch(tree);
481   }
482   else {
483     return kFALSE;
484   }
485
486 }
487
488 //_____________________________________________________________________________
489 Bool_t AliTRDdigitizer::Open(AliRunLoader *runLoader, Int_t nEvent)
490 {
491   //
492   // Opens a ROOT-file with TRD-hits and reads in the hit-tree
493   //
494   // Connect the AliRoot file containing Geometry, Kine, and Hits
495   //  
496
497   fRunLoader = runLoader;
498   if (!fRunLoader) {
499     AliError("RunLoader does not exist");
500     return kFALSE;
501   }
502    
503   if (!fRunLoader->GetAliRun()) {
504     fRunLoader->LoadgAlice();
505   }
506   gAlice = fRunLoader->GetAliRun();
507   
508   if (gAlice) {
509     AliDebug(1,"AliRun object found on file.");
510   }
511   else {
512     AliError("Could not find AliRun object.");
513     return kFALSE;
514   }
515
516   fEvent = nEvent;
517
518   AliLoader *loader = fRunLoader->GetLoader("TRDLoader");
519   if (!loader) {
520     AliError("Can not get TRD loader from Run Loader");
521     return kFALSE;
522   }
523   
524   if (InitDetector()) {
525     TTree *tree = 0;
526     if (fSDigits) { 
527       // If we produce SDigits
528       tree = loader->TreeS();
529       if (!tree) {
530         loader->MakeTree("S");
531         tree = loader->TreeS();
532       }
533     }
534     else {
535       // If we produce Digits
536       tree = loader->TreeD();
537       if (!tree) {
538         loader->MakeTree("D");
539         tree = loader->TreeD();
540       }
541     }
542     return MakeBranch(tree);
543   }
544   else {
545     return kFALSE;
546   }
547
548 }
549
550 //_____________________________________________________________________________
551 Bool_t AliTRDdigitizer::InitDetector()
552 {
553   //
554   // Sets the pointer to the TRD detector and the geometry
555   //
556
557   // Get the pointer to the detector class and check for version 1
558   fTRD = (AliTRD *) gAlice->GetDetector("TRD");
559   if (!fTRD) {
560     AliFatal("No TRD module found");
561     exit(1);
562   }
563   if (fTRD->IsVersion() != 1) {
564     AliFatal("TRD must be version 1 (slow simulator)");
565     exit(1);
566   }
567
568   // Get the geometry
569   fGeo = new AliTRDgeometry();
570
571   // Create a digits manager
572   if (fDigitsManager) {
573     delete fDigitsManager;
574   }
575   fDigitsManager = new AliTRDdigitsManager();
576   fDigitsManager->SetSDigits(fSDigits);
577   fDigitsManager->CreateArrays();
578   fDigitsManager->SetEvent(fEvent);
579
580   // The list for the input s-digits manager to be merged
581   if (fSDigitsManagerList) {
582     fSDigitsManagerList->Delete();
583   } 
584   else {
585     fSDigitsManagerList = new TList();
586   }
587
588   return kTRUE;
589
590 }
591 //_____________________________________________________________________________
592 Bool_t AliTRDdigitizer::MakeBranch(TTree *tree) const
593 {
594   // 
595   // Create the branches for the digits array
596   //
597
598   return fDigitsManager->MakeBranch(tree);
599
600 }
601
602 //_____________________________________________________________________________
603 void AliTRDdigitizer::AddSDigitsManager(AliTRDdigitsManager *man)
604 {
605   //
606   // Add a digits manager for s-digits to the input list.
607   //
608
609   fSDigitsManagerList->Add(man);
610
611 }
612
613 //_____________________________________________________________________________
614 void AliTRDdigitizer::DeleteSDigitsManager()
615 {
616   //
617   // Removes digits manager from the input list.
618   //
619
620   fSDigitsManagerList->Delete();
621
622 }
623
624 //_____________________________________________________________________________
625 Bool_t AliTRDdigitizer::MakeDigits()
626 {
627   //
628   // Creates digits.
629   //
630
631   AliDebug(1,"Start creating digits");
632
633   if (!fGeo) {
634     AliError("No geometry defined");
635     return kFALSE;
636   }
637
638   AliTRDcalibDB *calibration = AliTRDcalibDB::Instance();
639   if (!calibration) {
640     AliFatal("Could not get calibration object");
641     return kFALSE;
642   }
643
644   const Int_t kNdet  = AliTRDgeometry::Ndet();
645
646   Float_t **hits = new Float_t*[kNdet];
647   Int_t    *nhit = new Int_t[kNdet];
648
649   AliTRDarraySignal *signals = 0x0;
650  
651   // Sort all hits according to detector number
652   if (!SortHits(hits,nhit)) {
653     AliError("Sorting hits failed");
654     return kFALSE;
655   }
656
657   // Loop through all detectors
658   for (Int_t det = 0; det < kNdet; det++) {
659
660     // Detectors that are switched off, not installed, etc.
661     if (( calibration->IsChamberInstalled(det)) &&
662         (!calibration->IsChamberMasked(det))    &&
663         ( fGeo->ChamberInGeometry(det))         &&
664         (nhit[det] > 0)) {
665
666       signals = new AliTRDarraySignal();
667           
668       // Convert the hits of the current detector to detector signals
669       if (!ConvertHits(det,hits[det],nhit[det],signals)) {
670         AliError(Form("Conversion of hits failed for detector=%d",det));
671         return kFALSE;
672       }
673       // Convert the detector signals to digits or s-digits
674       if (!ConvertSignals(det,signals)) {
675         AliError(Form("Conversion of signals failed for detector=%d",det));
676         return kFALSE;
677       }
678
679       // Delete the signals array
680       delete signals;
681       signals = 0x0;
682
683     } // if: detector status
684
685     delete [] hits[det];
686
687   } // for: detector
688
689   delete [] hits;
690   delete [] nhit;
691
692   return kTRUE;
693
694 }
695
696 //_____________________________________________________________________________
697 Bool_t AliTRDdigitizer::SortHits(Float_t **hits, Int_t *nhit)
698 {
699   //
700   // Read all the hits and sorts them according to detector number
701   // in the output array <hits>.
702   //
703
704   AliDebug(1,"Start sorting hits");
705
706   const Int_t kNdet = AliTRDgeometry::Ndet();
707   // Size of the hit vector
708   const Int_t kNhit = 6;
709
710   Float_t *xyz      = 0;
711   Int_t    nhitTrk  = 0;
712
713   Int_t   *lhit     = new Int_t[kNdet];
714
715   for (Int_t det = 0; det < kNdet; det++) {
716     lhit[det] = 0;
717     nhit[det] = 0;
718     hits[det] = 0;
719   }
720
721   AliLoader *gimme = fRunLoader->GetLoader("TRDLoader");
722   if (!gimme->TreeH()) {
723     gimme->LoadHits();
724   }
725   TTree *hitTree = gimme->TreeH();
726   if (hitTree == 0x0) {
727     AliError("Can not get TreeH");
728     return kFALSE;
729   }
730   fTRD->SetTreeAddress();
731
732   // Get the number of entries in the hit tree
733   // (Number of primary particles creating a hit somewhere)
734   Int_t nTrk = (Int_t) hitTree->GetEntries();
735   AliDebug(1,Form("Found %d tracks",nTrk));
736
737   // Loop through all the tracks in the tree
738   for (Int_t iTrk = 0; iTrk < nTrk; iTrk++) {
739
740     gAlice->GetMCApp()->ResetHits();
741     hitTree->GetEvent(iTrk);
742
743     if (!fTRD->Hits()) {
744       AliError(Form("No hits array for track = %d",iTrk));
745       continue;
746     }
747
748     // Number of hits for this track
749     nhitTrk = fTRD->Hits()->GetEntriesFast();
750
751     Int_t hitCnt = 0;
752     // Loop through the TRD hits
753     AliTRDhit *hit = (AliTRDhit *) fTRD->FirstHit(-1);
754     while (hit) {
755
756       hitCnt++;
757
758       // Don't analyze test hits
759       if (((Int_t) hit->GetCharge()) != 0) {
760
761         Int_t   trk  = hit->Track();
762         Int_t   det  = hit->GetDetector();
763         Int_t   q    = hit->GetCharge();
764         Float_t x    = hit->X();
765         Float_t y    = hit->Y();
766         Float_t z    = hit->Z();
767         Float_t time = hit->GetTime();
768
769         if (nhit[det] == lhit[det]) {
770           // Inititialization of new detector
771           xyz        = new Float_t[kNhit*(nhitTrk+lhit[det])];
772           if (hits[det]) {
773             memcpy(xyz,hits[det],sizeof(Float_t)*kNhit*lhit[det]);
774             delete [] hits[det];
775           }
776           lhit[det] += nhitTrk;
777           hits[det]  = xyz;
778         }
779         else {
780           xyz        = hits[det];
781         }
782         xyz[nhit[det]*kNhit+0] = x;
783         xyz[nhit[det]*kNhit+1] = y;
784         xyz[nhit[det]*kNhit+2] = z;
785         xyz[nhit[det]*kNhit+3] = q;
786         xyz[nhit[det]*kNhit+4] = trk;
787         xyz[nhit[det]*kNhit+5] = time;
788         nhit[det]++;
789
790       } // if: charge != 0
791
792       hit = (AliTRDhit *) fTRD->NextHit();   
793
794     } // for: hits of one track
795
796   } // for: tracks
797
798   delete [] lhit;
799
800   return kTRUE;
801
802 }
803
804 //_____________________________________________________________________________
805 Bool_t AliTRDdigitizer::ConvertHits(Int_t det, Float_t *hits, Int_t nhit
806                                   , AliTRDarraySignal *signals)
807 {
808   //
809   // Converts the detectorwise sorted hits to detector signals
810   //
811
812   AliDebug(1,Form("Start converting hits for detector=%d (nhits=%d)",det,nhit));
813
814   // Number of pads included in the pad response
815   const Int_t kNpad      = 3;
816   // Number of track dictionary arrays
817   const Int_t kNdict     = AliTRDdigitsManager::kNDict;
818   // Size of the hit vector
819   const Int_t kNhit      = 6;
820
821   // Width of the amplification region
822   const Float_t kAmWidth = AliTRDgeometry::AmThick();
823   // Width of the drift region
824   const Float_t kDrWidth = AliTRDgeometry::DrThick();
825   // Drift + amplification region 
826   const Float_t kDrMin   =          - 0.5 * kAmWidth;
827   const Float_t kDrMax   = kDrWidth + 0.5 * kAmWidth;
828   
829   Int_t    iPad          = 0;
830   Int_t    dict          = 0;
831   Int_t    timeBinTRFend = 1;
832
833   Double_t pos[3];
834   Double_t loc[3];
835   Double_t padSignal[kNpad];
836   Double_t signalOld[kNpad];
837
838   AliTRDarrayDictionary *dictionary[kNdict];
839
840   AliTRDSimParam    *simParam    = AliTRDSimParam::Instance();
841   AliTRDCommonParam *commonParam = AliTRDCommonParam::Instance();
842   AliTRDcalibDB     *calibration = AliTRDcalibDB::Instance();
843
844   if (!commonParam) {
845     AliFatal("Could not get common parameterss");
846     return kFALSE;
847   }
848   if (!simParam) {
849     AliFatal("Could not get simulation parameters");
850     return kFALSE;
851   }  
852   if (!calibration) {
853     AliFatal("Could not get calibration object");  
854     return kFALSE;
855   }
856
857   // Get the detector wise calibration objects
858   AliTRDCalROC       *calVdriftROC      = 0;
859   Float_t             calVdriftDetValue = 0.0;
860   const AliTRDCalDet *calVdriftDet      = calibration->GetVdriftDet();  
861   AliTRDCalROC       *calT0ROC          = 0;
862   Float_t             calT0DetValue     = 0.0;
863   const AliTRDCalDet *calT0Det          = calibration->GetT0Det();  
864
865   if (simParam->TRFOn()) {
866     timeBinTRFend = ((Int_t) (simParam->GetTRFhi() 
867                   * commonParam->GetSamplingFrequency())) - 1;
868   }
869
870   Int_t   nTimeTotal   = calibration->GetNumberOfTimeBins();
871   Float_t samplingRate = commonParam->GetSamplingFrequency();
872   Float_t elAttachProp = simParam->GetElAttachProp() / 100.0; 
873
874   AliTRDpadPlane *padPlane = fGeo->GetPadPlane(det);
875   Int_t   layer   = fGeo->GetLayer(det);         //update
876   Float_t row0    = padPlane->GetRow0ROC();
877   Int_t   nRowMax = padPlane->GetNrows();
878   Int_t   nColMax = padPlane->GetNcols();
879
880   // Create a new array for the signals
881   signals->Allocate(nRowMax,nColMax,nTimeTotal);
882
883   // Create a new array for the dictionary
884   for (dict = 0; dict < kNdict; dict++) {       
885     dictionary[dict] = (AliTRDarrayDictionary *) fDigitsManager->GetDictionary(det,dict);
886     dictionary[dict]->Allocate(nRowMax,nColMax,nTimeTotal);
887   }      
888
889   // Loop through the hits in this detector
890   for (Int_t hit = 0; hit < nhit; hit++) {
891
892     pos[0]          = hits[hit*kNhit+0];
893     pos[1]          = hits[hit*kNhit+1];
894     pos[2]          = hits[hit*kNhit+2];
895     Float_t q       = hits[hit*kNhit+3];
896     Float_t hittime = hits[hit*kNhit+5];
897     Int_t   track   = ((Int_t) hits[hit*kNhit+4]);
898
899     Int_t   inDrift = 1;
900
901     // Find the current volume with the geo manager
902     gGeoManager->SetCurrentPoint(pos);
903     gGeoManager->FindNode();      
904     if (strstr(gGeoManager->GetPath(),"/UK")) {
905       inDrift = 0;
906     }
907
908     // Get the calibration objects
909     calVdriftROC      = calibration->GetVdriftROC(det);
910     calVdriftDetValue = calVdriftDet->GetValue(det);
911     calT0ROC          = calibration->GetT0ROC(det);
912     calT0DetValue     = calT0Det->GetValue(det);
913
914     // Go to the local coordinate system:
915     // loc[0] - col  direction in amplification or driftvolume
916     // loc[1] - row  direction in amplification or driftvolume
917     // loc[2] - time direction in amplification or driftvolume
918     gGeoManager->MasterToLocal(pos,loc);
919     if (inDrift) {
920       // Relative to middle of amplification region
921       loc[2] = loc[2] - kDrWidth/2.0 - kAmWidth/2.0;
922     } 
923
924     // The driftlength [cm] (w/o diffusion yet !).
925     // It is negative if the hit is between pad plane and anode wires.
926     Double_t driftlength = -1.0 * loc[2];
927
928     // Stupid patch to take care of TR photons that are absorbed
929     // outside the chamber volume. A real fix would actually need
930     // a more clever implementation of the TR hit generation
931     if (q < 0.0) {
932       if ((loc[1] < padPlane->GetRowEndROC()) ||
933           (loc[1] > padPlane->GetRow0ROC())) {
934         continue;
935       }
936       if ((driftlength < kDrMin) ||
937           (driftlength > kDrMax)) {
938         continue;
939       }
940     }
941
942     // Get row and col of unsmeared electron to retrieve drift velocity
943     // The pad row (z-direction)
944     Int_t    rowE         = padPlane->GetPadRowNumberROC(loc[1]);
945     if (rowE < 0) {
946       continue;
947     }
948     Double_t rowOffset    = padPlane->GetPadRowOffsetROC(rowE,loc[1]);
949     // The pad column (rphi-direction)
950     Double_t offsetTilt   = padPlane->GetTiltOffset(rowOffset);
951     Int_t    colE         = padPlane->GetPadColNumber(loc[0]+offsetTilt);
952     if (colE < 0) {
953       continue;   
954     }
955     Double_t colOffset    = 0.0;
956
957     // Normalized drift length
958     Float_t  driftvelocity  = calVdriftDetValue * calVdriftROC->GetValue(colE,rowE);
959     Double_t absdriftlength = TMath::Abs(driftlength);
960     if (commonParam->ExBOn()) {
961       absdriftlength /= TMath::Sqrt(GetLorentzFactor(driftvelocity));
962     }
963
964     // Loop over all electrons of this hit
965     // TR photons produce hits with negative charge
966     Int_t nEl = ((Int_t) TMath::Abs(q));
967     for (Int_t iEl = 0; iEl < nEl; iEl++) {
968
969       // Now the real local coordinate system of the ROC
970       // column direction: locC
971       // row direction:    locR 
972       // time direction:   locT
973       // locR and locC are identical to the coordinates of the corresponding
974       // volumina of the drift or amplification region.
975       // locT is defined relative to the wire plane (i.e. middle of amplification
976       // region), meaning locT = 0, and is negative for hits coming from the
977       // drift region. 
978       Double_t locC = loc[0];
979       Double_t locR = loc[1];
980       Double_t locT = loc[2];
981
982       // Electron attachment
983       if (simParam->ElAttachOn()) {
984         if (gRandom->Rndm() < (absdriftlength * elAttachProp)) {
985           continue;
986         }
987       }
988           
989       // Apply the diffusion smearing
990       if (simParam->DiffusionOn()) {
991         if (!(Diffusion(driftvelocity,absdriftlength,locR,locC,locT))) {
992           continue;
993         }
994       }
995
996       // Apply E x B effects (depends on drift direction)
997       if (commonParam->ExBOn()) { 
998         if (!(ExB(driftvelocity,driftlength,locC))) {
999           continue;
1000         }
1001       }
1002
1003       // The electron position after diffusion and ExB in pad coordinates.
1004       // The pad row (z-direction)
1005       rowE       = padPlane->GetPadRowNumberROC(locR);
1006       if (rowE < 0) continue;
1007       rowOffset  = padPlane->GetPadRowOffsetROC(rowE,locR);
1008
1009       // The pad column (rphi-direction)
1010       offsetTilt = padPlane->GetTiltOffset(rowOffset);
1011       colE       = padPlane->GetPadColNumber(locC+offsetTilt);
1012       if (colE < 0) continue;         
1013       colOffset  = padPlane->GetPadColOffset(colE,locC+offsetTilt);
1014           
1015       // Also re-retrieve drift velocity because col and row may have changed
1016       driftvelocity = calVdriftDetValue * calVdriftROC->GetValue(colE,rowE);
1017       Float_t t0    = calT0DetValue     + calT0ROC->GetValue(colE,rowE);
1018
1019       // Convert the position to drift time [mus], using either constant drift velocity or
1020       // time structure of drift cells (non-isochronity, GARFIELD calculation).
1021       // Also add absolute time of hits to take pile-up events into account properly
1022       Double_t drifttime;
1023       if (simParam->TimeStructOn()) {
1024         // Get z-position with respect to anode wire
1025         Double_t zz  =  row0 - locR + padPlane->GetAnodeWireOffset();
1026         zz -= ((Int_t)(2 * zz)) / 2.0;
1027         if (zz > 0.25) {
1028           zz  = 0.5 - zz;
1029         }
1030         // Use drift time map (GARFIELD)
1031         drifttime = commonParam->TimeStruct(driftvelocity,0.5*kAmWidth-1.0*locT,zz)
1032                   + hittime;
1033       } 
1034       else {
1035         // Use constant drift velocity
1036         drifttime = TMath::Abs(locT) / driftvelocity
1037                   + hittime;
1038       }
1039
1040       // Apply the gas gain including fluctuations
1041       Double_t ggRndm = 0.0;
1042       do {
1043         ggRndm = gRandom->Rndm();
1044       } while (ggRndm <= 0);
1045       Double_t signal = -(simParam->GetGasGain()) * TMath::Log(ggRndm);
1046
1047       // Apply the pad response 
1048       if (simParam->PRFOn()) {
1049         // The distance of the electron to the center of the pad 
1050         // in units of pad width
1051         Double_t dist = (colOffset - 0.5*padPlane->GetColSize(colE))
1052                       / padPlane->GetColSize(colE);
1053         // This is a fixed parametrization, i.e. not dependent on
1054         // calibration values !
1055         if (!(calibration->PadResponse(signal,dist,layer,padSignal))) continue;
1056       }
1057       else {
1058         padSignal[0] = 0.0;
1059         padSignal[1] = signal;
1060         padSignal[2] = 0.0;
1061       }
1062
1063       // The time bin (always positive), with t0 distortion
1064       Double_t timeBinIdeal = drifttime * samplingRate + t0;
1065       // Protection 
1066       if (TMath::Abs(timeBinIdeal) > 2*nTimeTotal) {
1067         timeBinIdeal = 2 * nTimeTotal;
1068       }
1069       Int_t    timeBinTruncated = ((Int_t) timeBinIdeal);
1070       // The distance of the position to the middle of the timebin
1071       Double_t timeOffset       = ((Float_t) timeBinTruncated 
1072                                 + 0.5 - timeBinIdeal) / samplingRate;
1073           
1074       // Sample the time response inside the drift region
1075       // + additional time bins before and after.
1076       // The sampling is done always in the middle of the time bin
1077       for (Int_t iTimeBin = TMath::Max(timeBinTruncated,0)
1078           ;iTimeBin < TMath::Min(timeBinTruncated+timeBinTRFend,nTimeTotal)
1079           ;iTimeBin++) {
1080
1081         // Apply the time response
1082         Double_t timeResponse = 1.0;
1083         Double_t crossTalk    = 0.0;
1084         Double_t time         = (iTimeBin - timeBinTruncated) / samplingRate + timeOffset;
1085
1086         if (simParam->TRFOn()) {
1087           timeResponse = simParam->TimeResponse(time);
1088         }
1089         if (simParam->CTOn()) {
1090           crossTalk    = simParam->CrossTalk(time);
1091         }
1092
1093         signalOld[0] = 0.0;
1094         signalOld[1] = 0.0;
1095         signalOld[2] = 0.0;
1096
1097         for (iPad = 0; iPad < kNpad; iPad++) {
1098
1099           Int_t colPos = colE + iPad - 1;
1100           if (colPos <        0) continue;
1101           if (colPos >= nColMax) break;
1102
1103           // Add the signals
1104           signalOld[iPad] = signals->GetData(rowE,colPos,iTimeBin);
1105
1106           if (colPos != colE) {
1107             // Cross talk added to non-central pads
1108             signalOld[iPad] += padSignal[iPad] 
1109                              * (timeResponse + crossTalk);
1110           } 
1111           else {
1112             // W/o cross talk at central pad
1113             signalOld[iPad] += padSignal[iPad] 
1114                              * timeResponse;
1115           }
1116
1117           signals->SetData(rowE,colPos,iTimeBin,signalOld[iPad]);
1118
1119           // Store the track index in the dictionary
1120           // Note: We store index+1 in order to allow the array to be compressed
1121           // Note2: Taking out the +1 in track
1122           if (signalOld[iPad] > 0.0) { 
1123             for (dict = 0; dict < kNdict; dict++) {
1124               Int_t oldTrack = dictionary[dict]->GetData(rowE,colPos,iTimeBin); 
1125               if (oldTrack == track) break;
1126               if (oldTrack ==  -1 ) {
1127                 dictionary[dict]->SetData(rowE,colPos,iTimeBin,track);
1128                 break;
1129               }
1130             }
1131           }
1132
1133         } // Loop: pads
1134
1135       } // Loop: time bins
1136
1137     } // Loop: electrons of a single hit
1138
1139   } // Loop: hits
1140
1141   AliDebug(2,Form("Finished analyzing %d hits",nhit));
1142
1143   return kTRUE;
1144
1145 }
1146
1147 //_____________________________________________________________________________
1148 Bool_t AliTRDdigitizer::ConvertSignals(Int_t det, AliTRDarraySignal *signals)
1149 {
1150   //
1151   // Convert signals to digits
1152   //
1153
1154   AliDebug(1,Form("Start converting the signals for detector %d",det));
1155
1156   if (fSDigits) {
1157     // Convert the signal array to s-digits
1158     if (!Signal2SDigits(det,signals)) {
1159       return kFALSE;
1160     }
1161   }
1162   else {
1163     // Convert the signal array to digits
1164     if (!Signal2ADC(det,signals)) {
1165       return kFALSE;
1166     }
1167   }
1168
1169   // Compress the arrays
1170   CompressOutputArrays(det);   
1171
1172   return kTRUE;
1173
1174 }
1175
1176 //_____________________________________________________________________________
1177 Bool_t AliTRDdigitizer::Signal2ADC(Int_t det, AliTRDarraySignal *signals)
1178 {
1179   //
1180   // Converts the sampled electron signals to ADC values for a given chamber
1181   //
1182
1183   AliDebug(1,Form("Start converting signals to ADC values for detector=%d",det));
1184
1185   AliTRDcalibDB     *calibration = AliTRDcalibDB::Instance();
1186   if (!calibration) {
1187     AliFatal("Could not get calibration object");
1188     return kFALSE;
1189   }
1190
1191   AliTRDSimParam    *simParam    = AliTRDSimParam::Instance();
1192   if (!simParam) {
1193     AliFatal("Could not get simulation parameters");
1194     return kFALSE;
1195   }  
1196
1197   // Converts number of electrons to fC
1198   const Double_t kEl2fC = 1.602e-19 * 1.0e15; 
1199
1200   // Coupling factor
1201   Double_t coupling     = simParam->GetPadCoupling() 
1202                         * simParam->GetTimeCoupling();
1203   // Electronics conversion factor
1204   Double_t convert      = kEl2fC 
1205                         * simParam->GetChipGain();
1206   // ADC conversion factor
1207   Double_t adcConvert   = simParam->GetADCoutRange()
1208                         / simParam->GetADCinRange();
1209   // The electronics baseline in mV
1210   Double_t baseline     = simParam->GetADCbaseline() 
1211                         / adcConvert;
1212   // The electronics baseline in electrons
1213   Double_t baselineEl   = baseline
1214                         / convert;
1215
1216   Int_t row  = 0;
1217   Int_t col  = 0;
1218   Int_t time = 0;
1219
1220   Int_t nRowMax    = fGeo->GetPadPlane(det)->GetNrows();
1221   Int_t nColMax    = fGeo->GetPadPlane(det)->GetNcols();
1222   Int_t nTimeTotal = calibration->GetNumberOfTimeBins();
1223
1224   // The gainfactor calibration objects
1225   const AliTRDCalDet *calGainFactorDet      = calibration->GetGainFactorDet();  
1226   AliTRDCalROC       *calGainFactorROC      = 0;
1227   Float_t             calGainFactorDetValue = 0.0;
1228
1229   AliTRDarrayADC     *digits = 0x0;
1230
1231   if (!signals) {
1232     AliError(Form("Signals array for detector %d does not exist\n",det));
1233     return kFALSE;
1234   }
1235   if (signals->HasData()) {
1236     // Expand the container if neccessary
1237     signals->Expand();   
1238   }
1239   else {
1240     // Create missing containers
1241     signals->Allocate(nRowMax,nColMax,nTimeTotal);      
1242   }
1243
1244   // Get the container for the digits of this detector
1245   if (fDigitsManager->HasSDigits()) {
1246     AliError("Digits manager has s-digits");
1247     return kFALSE;
1248   }
1249
1250   digits = (AliTRDarrayADC *) fDigitsManager->GetDigits(det);
1251   // Allocate memory space for the digits buffer
1252   if (!digits->HasData()) {
1253     digits->Allocate(nRowMax,nColMax,nTimeTotal);
1254   }
1255
1256   // Get the calibration objects
1257   calGainFactorROC      = calibration->GetGainFactorROC(det);
1258   calGainFactorDetValue = calGainFactorDet->GetValue(det);
1259
1260   // Create the digits for this chamber
1261   for (row  = 0; row  <  nRowMax; row++ ) {
1262     for (col  = 0; col  <  nColMax; col++ ) {
1263
1264       // Check whether pad is masked
1265       // Bridged pads are not considered yet!!!
1266       if (calibration->IsPadMasked(det,col,row)) {
1267         continue;
1268       }
1269
1270       // The gain factors
1271       Float_t padgain = calGainFactorDetValue 
1272                       * calGainFactorROC->GetValue(col,row);
1273       if (padgain <= 0) {
1274         AliError(Form("Not a valid gain %f, %d %d %d",padgain,det,col,row));
1275       }
1276
1277       for (time = 0; time < nTimeTotal; time++) {
1278
1279         // Get the signal amplitude
1280         Float_t signalAmp = signals->GetData(row,col,time);
1281         // Pad and time coupling
1282         signalAmp *= coupling;
1283         // Gain factors
1284         signalAmp *= padgain;
1285
1286         // Add the noise, starting from minus ADC baseline in electrons
1287         signalAmp  = TMath::Max((Double_t) gRandom->Gaus(signalAmp,simParam->GetNoise())
1288                                ,-baselineEl);
1289
1290         // Convert to mV
1291         signalAmp *= convert;
1292         // Add ADC baseline in mV
1293         signalAmp += baseline;
1294
1295         // Convert to ADC counts. Set the overflow-bit fADCoutRange if the
1296         // signal is larger than fADCinRange
1297         Short_t adc  = 0;
1298         if (signalAmp >= simParam->GetADCinRange()) {
1299           adc = ((Short_t) simParam->GetADCoutRange());
1300         }
1301         else {
1302           adc = TMath::Nint(signalAmp * adcConvert);
1303         }
1304
1305         // Saving all digits
1306         digits->SetData(row,col,time,adc);
1307
1308       } // for: time
1309
1310     } // for: col
1311   } // for: row
1312
1313   // Run the digital processing in the MCM
1314   RunDigitalProcessing(digits, det);
1315
1316   return kTRUE;
1317
1318 }
1319
1320 //_____________________________________________________________________________
1321 Bool_t AliTRDdigitizer::Signal2SDigits(Int_t det, AliTRDarraySignal *signals)
1322 {
1323   //
1324   // Converts the sampled electron signals to s-digits
1325   //
1326
1327   AliDebug(1,Form("Start converting signals to s-digits for detector=%d",det));
1328
1329   AliTRDcalibDB     *calibration = AliTRDcalibDB::Instance();
1330   if (!calibration) {
1331     AliFatal("Could not get calibration object");
1332     return kFALSE;
1333   }
1334
1335   Int_t row  = 0;
1336   Int_t col  = 0;
1337   Int_t time = 0;
1338
1339   Int_t nRowMax    = fGeo->GetPadPlane(det)->GetNrows();
1340   Int_t nColMax    = fGeo->GetPadPlane(det)->GetNcols();
1341   Int_t nTimeTotal = calibration->GetNumberOfTimeBins();
1342
1343   // Get the container for the digits of this detector
1344
1345   if (!fDigitsManager->HasSDigits()) {
1346     AliError("Digits manager has no s-digits");
1347     return kFALSE;
1348   }
1349
1350   AliTRDarraySignal *digits = (AliTRDarraySignal *) fDigitsManager->GetSDigits(det);
1351   // Allocate memory space for the digits buffer
1352   if (!digits->HasData()) {
1353     digits->Allocate(nRowMax,nColMax,nTimeTotal);
1354   }
1355
1356   // Create the sdigits for this chamber
1357   for (row  = 0; row  <  nRowMax; row++ ) {
1358     for (col  = 0; col  <  nColMax; col++ ) {
1359       for (time = 0; time < nTimeTotal; time++) {         
1360         digits->SetData(row,col,time,signals->GetData(row,col,time));
1361       } // for: time
1362     } // for: col
1363   } // for: row
1364   
1365   return kTRUE;
1366
1367 }
1368
1369 //_____________________________________________________________________________
1370 Bool_t AliTRDdigitizer::SDigits2Digits()
1371 {
1372   //
1373   // Merges the input s-digits and converts them to normal digits
1374   //
1375
1376   if (!MergeSDigits()) {
1377     return kFALSE;
1378   }
1379
1380   return ConvertSDigits();
1381
1382 }
1383
1384 //_____________________________________________________________________________
1385 Bool_t AliTRDdigitizer::MergeSDigits()
1386 {
1387   //
1388   // Merges the input s-digits:
1389   //   - The amplitude of the different inputs are summed up.
1390   //   - Of the track IDs from the input dictionaries only one is
1391   //     kept for each input. This works for maximal 3 different merged inputs.
1392   //
1393
1394   // Number of track dictionary arrays
1395   const Int_t kNDict = AliTRDdigitsManager::kNDict;
1396
1397   AliTRDSimParam    *simParam    = AliTRDSimParam::Instance();
1398   if (!simParam) {
1399     AliFatal("Could not get simulation parameters");
1400     return kFALSE;
1401   }
1402   
1403   AliTRDcalibDB     *calibration = AliTRDcalibDB::Instance();
1404   if (!calibration) {
1405     AliFatal("Could not get calibration object");
1406     return kFALSE;
1407   }
1408   
1409   Int_t iDict = 0;
1410   Int_t jDict = 0;
1411
1412   AliTRDarraySignal     *digitsA;
1413   AliTRDarraySignal     *digitsB;
1414   AliTRDarrayDictionary *dictionaryA[kNDict];
1415   AliTRDarrayDictionary *dictionaryB[kNDict];
1416
1417   AliTRDdigitsManager   *mergeSDigitsManager = 0x0;
1418   // Get the first s-digits
1419   fSDigitsManager = (AliTRDdigitsManager *) fSDigitsManagerList->First();
1420   if (!fSDigitsManager) { 
1421     AliError("No SDigits manager");
1422     return kFALSE;
1423   }
1424
1425   // Loop through the other sets of s-digits
1426   mergeSDigitsManager = (AliTRDdigitsManager *) fSDigitsManagerList->After(fSDigitsManager);
1427
1428   if (mergeSDigitsManager) {
1429     AliDebug(1,Form("Merge %d input files.",fSDigitsManagerList->GetSize()));
1430   }
1431   else {
1432     AliDebug(1,"Only one input file.");
1433   }
1434   
1435   Int_t nTimeTotal = calibration->GetNumberOfTimeBins();  
1436   Int_t iMerge = 0;
1437
1438   while (mergeSDigitsManager) {
1439
1440     iMerge++;
1441       
1442     // Loop through the detectors
1443     for (Int_t iDet = 0; iDet < AliTRDgeometry::Ndet(); iDet++) {
1444
1445       Int_t nRowMax = fGeo->GetPadPlane(iDet)->GetNrows();
1446       Int_t nColMax = fGeo->GetPadPlane(iDet)->GetNcols();
1447           
1448       // Loop through the pixels of one detector and add the signals
1449       digitsA = (AliTRDarraySignal *) fSDigitsManager->GetSDigits(iDet);    
1450       digitsB = (AliTRDarraySignal *) mergeSDigitsManager->GetSDigits(iDet); 
1451       digitsA->Expand();  
1452       if (!digitsA->HasData()) continue;
1453       digitsB->Expand();    
1454       if (!digitsB->HasData()) continue;
1455           
1456       for (iDict = 0; iDict < kNDict; iDict++) {
1457         dictionaryA[iDict] = (AliTRDarrayDictionary *) fSDigitsManager->GetDictionary(iDet,iDict);
1458         dictionaryB[iDict] = (AliTRDarrayDictionary *) mergeSDigitsManager->GetDictionary(iDet,iDict);
1459         dictionaryA[iDict]->Expand();  
1460         dictionaryB[iDict]->Expand();
1461       }
1462
1463       // Merge only detectors that contain a signal
1464       Bool_t doMerge = kTRUE;
1465       if (fMergeSignalOnly) {
1466         if (digitsA->GetOverThreshold(0) == 0) {                             
1467           doMerge = kFALSE;
1468         }
1469       }
1470           
1471       if (doMerge) {
1472               
1473         AliDebug(1,Form("Merge detector %d of input no.%d",iDet,iMerge+1));
1474               
1475         for (Int_t iRow  = 0; iRow  <  nRowMax;   iRow++ ) {
1476           for (Int_t iCol  = 0; iCol  <  nColMax;   iCol++ ) {
1477             for (Int_t iTime = 0; iTime < nTimeTotal; iTime++) {
1478                 
1479               // Add the amplitudes of the summable digits 
1480               Float_t ampA = digitsA->GetData(iRow,iCol,iTime);
1481               Float_t ampB = digitsB->GetData(iRow,iCol,iTime);
1482               ampA += ampB;
1483               digitsA->SetData(iRow,iCol,iTime,ampA);
1484
1485               // Add the mask to the track id if defined.
1486               for (iDict = 0; iDict < kNDict; iDict++) {
1487                 Int_t trackB = dictionaryB[iDict]->GetData(iRow,iCol,iTime);
1488                 if ((fMasks) && (trackB > 0))  {
1489                   for (jDict = 0; jDict < kNDict; jDict++) { 
1490                     Int_t trackA = dictionaryA[iDict]->GetData(iRow,iCol,iTime); 
1491                     if (trackA == 0) {
1492                       trackA = trackB + fMasks[iMerge];
1493                       dictionaryA[iDict]->SetData(iRow,iCol,iTime,trackA);  
1494                     } // if:  track A == 0
1495                   } // for: jDict
1496                 } // if:  fMasks and trackB > 0
1497               } // for: iDict
1498
1499             } // for: iTime
1500           } // for: iCol
1501         } // for: iRow
1502
1503       } // if:  doMerge
1504
1505       mergeSDigitsManager->RemoveDigits(iDet);
1506       mergeSDigitsManager->RemoveDictionaries(iDet);
1507   
1508       if (fCompress) {
1509         digitsA->Compress(0); 
1510         for (iDict = 0; iDict < kNDict; iDict++) {                                     
1511           dictionaryA[iDict]->Compress();
1512         }
1513       }
1514       
1515     } // for: detectors    
1516       
1517     // The next set of s-digits
1518     mergeSDigitsManager = (AliTRDdigitsManager *) fSDigitsManagerList->After(mergeSDigitsManager);
1519     
1520   } // while: mergeDigitsManagers
1521   
1522   return kTRUE;
1523
1524 }
1525
1526 //_____________________________________________________________________________
1527 Bool_t AliTRDdigitizer::ConvertSDigits()
1528 {
1529   //
1530   // Converts s-digits to normal digits
1531   //
1532
1533   AliTRDarraySignal *digitsIn = 0x0;
1534
1535   if (!fSDigitsManager->HasSDigits()) {
1536     AliError("No s-digits in digits manager");
1537     return kFALSE;
1538   }
1539
1540   // Loop through the detectors
1541   for (Int_t det = 0; det < AliTRDgeometry::Ndet(); det++) {
1542
1543     // Get the merged s-digits (signals)
1544     digitsIn = (AliTRDarraySignal *) fSDigitsManager->GetSDigits(det);
1545     if (!digitsIn->HasData()) {
1546       AliDebug(2,Form("No digits for det=%d",det));
1547       continue;
1548     }
1549     
1550     // Convert the merged sdigits to digits
1551     if (!Signal2ADC(det,digitsIn)) {
1552       continue;
1553     }
1554
1555     // Copy the dictionary information to the output array
1556     if (!CopyDictionary(det)) {
1557       continue;
1558     }
1559
1560     // Delete 
1561     fSDigitsManager->RemoveDigits(det);
1562     fSDigitsManager->RemoveDictionaries(det);
1563
1564     // Compress the arrays
1565     CompressOutputArrays(det);
1566
1567   } // for: detector numbers
1568
1569
1570   return kTRUE;
1571
1572 }
1573
1574 //_____________________________________________________________________________
1575 Bool_t AliTRDdigitizer::CopyDictionary(Int_t det)
1576 {
1577   //
1578   // Copies the dictionary information from the s-digits arrays
1579   // to the output arrays
1580   //
1581
1582   AliTRDcalibDB     *calibration = AliTRDcalibDB::Instance();
1583   if (!calibration) {
1584     AliFatal("Could not get calibration object");
1585     return kFALSE;
1586   }
1587
1588   AliDebug(1,Form("Start copying dictionaries for detector=%d",det));
1589
1590   const Int_t kNDict = AliTRDdigitsManager::kNDict;
1591   AliTRDarrayDictionary *dictionaryIn[kNDict];
1592   AliTRDarrayDictionary *dictionaryOut[kNDict];
1593
1594   Int_t nRowMax    = fGeo->GetPadPlane(det)->GetNrows();
1595   Int_t nColMax    = fGeo->GetPadPlane(det)->GetNcols();
1596   Int_t nTimeTotal = calibration->GetNumberOfTimeBins();
1597
1598   Int_t row  = 0;
1599   Int_t col  = 0;
1600   Int_t time = 0;
1601   Int_t dict = 0;
1602
1603   for (dict = 0; dict < kNDict; dict++) {
1604
1605     dictionaryIn[dict]  = (AliTRDarrayDictionary *) fSDigitsManager->GetDictionary(det,dict);
1606     dictionaryIn[dict]->Expand();
1607     dictionaryOut[dict] = (AliTRDarrayDictionary *) fDigitsManager->GetDictionary(det,dict);
1608     dictionaryOut[dict]->Allocate(nRowMax,nColMax,nTimeTotal);
1609
1610     for (row = 0; row < nRowMax; row++) {
1611       for (col = 0; col < nColMax; col++) {
1612         for (time = 0; time < nTimeTotal; time++) {
1613           Int_t track = dictionaryIn[dict]->GetData(row,col,time);
1614           dictionaryOut[dict]->SetData(row,col,time,track);
1615         } // for: time
1616       } // for: col
1617     } // for: row
1618     
1619   } // for: dictionaries
1620   
1621   return kTRUE;
1622
1623 }
1624
1625 //_____________________________________________________________________________
1626 void AliTRDdigitizer::CompressOutputArrays(Int_t det)
1627 {
1628   //
1629   // Compress the output arrays
1630   //
1631
1632   const Int_t kNDict = AliTRDdigitsManager::kNDict;
1633   AliTRDarrayDictionary *dictionary = 0x0;
1634
1635   if (fCompress) {
1636
1637     if (!fSDigits) {
1638       AliTRDarrayADC *digits = 0x0;  
1639       digits = (AliTRDarrayADC *) fDigitsManager->GetDigits(det);
1640       digits->Compress();
1641     }
1642
1643     if (fSDigits) {
1644       AliTRDarraySignal *digits = 0x0; 
1645       digits = (AliTRDarraySignal *) fDigitsManager->GetSDigits(det);
1646       digits->Compress(0);
1647     }
1648
1649     for (Int_t dict = 0; dict < kNDict; dict++) {
1650       dictionary = (AliTRDarrayDictionary *) fDigitsManager->GetDictionary(det,dict);
1651       dictionary->Compress();
1652     }
1653
1654   }
1655
1656 }
1657
1658 //_____________________________________________________________________________
1659 Bool_t AliTRDdigitizer::WriteDigits() const
1660 {
1661   //
1662   // Writes out the TRD-digits and the dictionaries
1663   //
1664
1665   // Write parameters
1666   fRunLoader->CdGAFile();
1667
1668   // Store the digits and the dictionary in the tree
1669   return fDigitsManager->WriteDigits();
1670
1671 }
1672
1673 //_____________________________________________________________________________
1674 void AliTRDdigitizer::InitOutput(Int_t iEvent)
1675 {
1676   //
1677   // Initializes the output branches
1678   //
1679
1680   fEvent = iEvent;
1681    
1682   if (!fRunLoader) {
1683     AliError("Run Loader is NULL");
1684     return;  
1685   }
1686
1687   AliLoader *loader = fRunLoader->GetLoader("TRDLoader");
1688   if (!loader) {
1689     AliError("Can not get TRD loader from Run Loader");
1690     return;
1691   }
1692
1693   TTree *tree = 0;
1694   
1695   if (fSDigits) { 
1696     // If we produce SDigits
1697     tree = loader->TreeS();
1698     if (!tree) {
1699       loader->MakeTree("S");
1700       tree = loader->TreeS();
1701     }
1702   }
1703   else {
1704     // If we produce Digits
1705     tree = loader->TreeD();
1706     if (!tree) {
1707       loader->MakeTree("D");
1708       tree = loader->TreeD();
1709     }
1710   }
1711   fDigitsManager->SetEvent(iEvent);
1712   fDigitsManager->MakeBranch(tree);
1713
1714 }
1715   
1716 //_____________________________________________________________________________
1717 Int_t AliTRDdigitizer::Diffusion(Float_t vdrift, Double_t absdriftlength
1718                                , Double_t &lRow, Double_t &lCol, Double_t &lTime)
1719 {
1720   //
1721   // Applies the diffusion smearing to the position of a single electron.
1722   // Depends on absolute drift length.
1723   //
1724   
1725   Float_t diffL = 0.0;
1726   Float_t diffT = 0.0;
1727
1728   if (AliTRDCommonParam::Instance()->GetDiffCoeff(diffL,diffT,vdrift)) {
1729
1730     Float_t driftSqrt = TMath::Sqrt(absdriftlength);
1731     Float_t sigmaT    = driftSqrt * diffT;
1732     Float_t sigmaL    = driftSqrt * diffL;
1733     lRow  = gRandom->Gaus(lRow ,sigmaT);
1734     lCol  = gRandom->Gaus(lCol ,sigmaT * GetLorentzFactor(vdrift));
1735     lTime = gRandom->Gaus(lTime,sigmaL * GetLorentzFactor(vdrift));
1736
1737     return 1;
1738
1739   }
1740   else {
1741
1742     return 0;
1743
1744   }
1745
1746 }
1747
1748 //_____________________________________________________________________________
1749 Float_t AliTRDdigitizer::GetLorentzFactor(Float_t vd)
1750 {
1751   //
1752   // Returns the Lorentz factor
1753   //
1754
1755   Double_t omegaTau      = AliTRDCommonParam::Instance()->GetOmegaTau(vd);
1756   Double_t lorentzFactor = 1.0;
1757   if (AliTRDCommonParam::Instance()->ExBOn()) {
1758     lorentzFactor = 1.0 / (1.0 + omegaTau*omegaTau);
1759   }
1760
1761   return lorentzFactor;
1762
1763 }
1764   
1765 //_____________________________________________________________________________
1766 Int_t AliTRDdigitizer::ExB(Float_t vdrift, Double_t driftlength, Double_t &lCol)
1767 {
1768   //
1769   // Applies E x B effects to the position of a single electron.
1770   // Depends on signed drift length.
1771   //
1772
1773   lCol = lCol 
1774        + AliTRDCommonParam::Instance()->GetOmegaTau(vdrift) 
1775        * driftlength;
1776
1777   return 1;
1778
1779 }
1780
1781 //_____________________________________________________________________________
1782 void AliTRDdigitizer::RunDigitalProcessing(AliTRDarrayADC *digits, Int_t det)
1783 {
1784   //
1785   // Run the digital processing in the TRAP
1786   //
1787
1788   AliTRDfeeParam *feeParam = AliTRDfeeParam::Instance();
1789
1790   //Create and initialize the mcm object 
1791   AliTRDmcmSim* mcmfast = new AliTRDmcmSim(); 
1792
1793   //Call the methods in the mcm class using the temporary array as input  
1794   for(Int_t rob = 0; rob < digits->GetNrow() / 4; rob++)
1795   {
1796     for(Int_t mcm = 0; mcm < 16; mcm++)
1797     {
1798       mcmfast->Init(det, rob, mcm); 
1799       mcmfast->SetData(digits);
1800       mcmfast->Filter();
1801       if (feeParam->GetTracklet())
1802         mcmfast->Tracklet();
1803       mcmfast->ZSMapping();
1804       mcmfast->WriteData(digits);
1805     }
1806   }
1807
1808   delete mcmfast;
1809 }