]> git.uio.no Git - u/mrichter/AliRoot.git/blob - TRD/AliTRDrawData.cxx
New raw data simulation by WooJin
[u/mrichter/AliRoot.git] / TRD / AliTRDrawData.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 //  TRD raw data conversion class                                            //
21 //                                                                           //
22 ///////////////////////////////////////////////////////////////////////////////
23
24 #include <TMath.h>
25 #include "TClass.h"
26
27 #include "AliDAQ.h"
28 #include "AliRawDataHeaderSim.h"
29 #include "AliRawReader.h"
30 #include "AliLog.h"
31 #include "AliFstream.h"
32
33 #include "AliTRDrawData.h"
34 #include "AliTRDdigitsManager.h"
35 #include "AliTRDgeometry.h"
36 #include "AliTRDdataArrayI.h"
37 #include "AliTRDdataArrayS.h"
38 #include "AliTRDrawStreamBase.h"
39 #include "AliTRDrawOldStream.h"
40 #include "AliTRDRawStreamV2.h"
41 #include "AliTRDcalibDB.h"
42 #include "AliTRDSignalIndex.h"
43 #include "AliTRDfeeParam.h"
44 #include "AliTRDmcmSim.h"
45
46 ClassImp(AliTRDrawData)
47
48 Int_t AliTRDrawData::fgRawFormatVersion = AliTRDrawData::kRawOldFormat;
49
50 //_____________________________________________________________________________
51 AliTRDrawData::AliTRDrawData()
52   :TObject()
53   ,fGeo(NULL)
54   ,fFee(NULL)
55   ,fNumberOfDDLs(0)
56 {
57   //
58   // Default constructor
59   //
60
61   fFee = AliTRDfeeParam::Instance();
62   fNumberOfDDLs = AliDAQ::NumberOfDdls("TRD");
63
64 }
65
66 //_____________________________________________________________________________
67 AliTRDrawData::AliTRDrawData(const AliTRDrawData &r)
68   :TObject(r)
69   ,fGeo(NULL)
70   ,fFee(NULL)
71   ,fNumberOfDDLs(0)
72 {
73   //
74   // Copy constructor
75   //
76
77   fFee = AliTRDfeeParam::Instance();
78   fNumberOfDDLs = AliDAQ::NumberOfDdls("TRD");
79
80 }
81
82 //_____________________________________________________________________________
83 AliTRDrawData::~AliTRDrawData()
84 {
85   //
86   // Destructor
87   //
88
89 }
90
91 //_____________________________________________________________________________
92 Bool_t AliTRDrawData::Digits2Raw(TTree *digitsTree, TTree *tracks )
93 {
94   //
95   // Initialize necessary parameters and call one
96   // of the raw data simulator selected by SetRawVersion.
97   //
98   // Currently tracklet output is not spported yet and it
99   // will be supported in higher version simulator.
100   //
101
102   AliTRDdigitsManager* digitsManager = new AliTRDdigitsManager();
103
104   if (!digitsManager->ReadDigits(digitsTree)) {
105     delete digitsManager;
106     return kFALSE;
107   }
108
109   if (tracks != NULL) {
110     delete digitsManager;
111     AliError("Tracklet input is not supported yet.");
112     return kFALSE;
113   }
114
115   fGeo = new AliTRDgeometry();
116
117   if (!AliTRDcalibDB::Instance()) {
118     AliError("Could not get calibration object");
119     delete fGeo;
120     delete digitsManager;
121     return kFALSE;
122   }
123
124   Int_t retval = kTRUE;
125   Int_t rv     = fFee->GetRAWversion();
126
127   // Call appropriate Raw Simulator
128   if ( rv > 0 && rv <= 3 ) retval = Digits2Raw(digitsManager); 
129   else {
130     retval = kFALSE;
131     AliWarning(Form("Unsupported raw version (%d).", rv));
132   }
133
134   // Cleanup
135   delete fGeo;
136   delete digitsManager;
137
138   return retval;
139
140 }
141
142 //_____________________________________________________________________________
143 Bool_t AliTRDrawData::Digits2Raw(AliTRDdigitsManager *digitsManager)
144 {
145   //
146   // Raw data simulator for all versions > 0. This is prepared for real data.
147   // This version simulate only raw data with ADC data and not with tracklet.
148   //
149
150   const Int_t kMaxHcWords = (fGeo->TBmax()/3)
151                           * fGeo->ADCmax()
152                           * fGeo->MCMmax()
153                           * fGeo->ROBmaxC1()/2 
154                           + 100 + 20;
155
156   // Buffer to temporary store half chamber data
157   UInt_t     *hcBuffer    = new UInt_t[kMaxHcWords];
158   
159   Bool_t newEvent = kFALSE;  // only for correct readout tree
160
161   // sect is same as iDDL, so I use only sect here.
162   for (Int_t sect = 0; sect < fGeo->Nsector(); sect++) { 
163
164     char name[1024];
165     sprintf(name,"TRD_%d.ddl",sect + AliTRDrawOldStream::kDDLOffset);
166
167     AliFstream* of = new AliFstream(name);
168
169     // Write a dummy data header
170     AliRawDataHeaderSim  header;  // the event header
171     UInt_t hpos = of->Tellp();
172     of->WriteBuffer((char *) (& header), sizeof(header));
173
174     // Reset payload byte size (payload does not include header).
175     Int_t npayloadbyte = 0;
176
177     
178         if ( fgRawFormatVersion == 0 ){
179     // GTU common data header (5x4 bytes per super module, shows link mask)
180     for( Int_t stack = 0; stack < fGeo->Nstack(); stack++ ) {
181       UInt_t gtuCdh = (UInt_t)(0xe << 28);
182       for( Int_t layer = 0; layer < fGeo->Nlayer(); layer++) {
183         Int_t iDet = fGeo->GetDetector(layer, stack, sect);
184         
185         // If chamber status is ok, we assume that the optical link is also OK.
186         // This is shown in the GTU link mask.
187         if ( AliTRDcalibDB::Instance()->GetChamberStatus(iDet) )
188           gtuCdh = gtuCdh | (3 << (2*layer));
189       }
190       of->WriteBuffer((char *) (& gtuCdh), sizeof(gtuCdh));
191       npayloadbyte += 4;
192     }
193         }
194
195     // Prepare chamber data
196     for( Int_t stack = 0; stack < fGeo->Nstack(); stack++) {
197       for( Int_t layer = 0; layer < fGeo->Nlayer(); layer++) {
198
199         Int_t iDet = fGeo->GetDetector(layer,stack,sect);
200         if (iDet == 0) newEvent = kTRUE; // it is expected that each event has at least one tracklet; this is only needed for correct readout tree
201         // Get the digits array
202         AliTRDdataArrayS *digits = (AliTRDdataArrayS *) digitsManager->GetDigits(iDet);
203         if (digits->HasData() ) {  // second part is new!! and is for indicating a new event
204
205           digits->Expand();
206
207           Int_t hcwords = 0;
208           Int_t rv = fFee->GetRAWversion();
209
210
211         if ( fgRawFormatVersion == 0 ){
212       // Process A side of the chamber
213           if ( rv >= 1 && rv <= 2 ) {
214             hcwords = ProduceHcDataV1andV2(digits,0,iDet,hcBuffer,kMaxHcWords);
215           }
216           if ( rv == 3 ) { 
217    
218               hcwords = ProduceHcDataV3     (digits,0,iDet,hcBuffer,kMaxHcWords,newEvent);
219               //hcwords = ProduceHcDataV3     (digits,0,iDet,hcBuffer,kMaxHcWords);
220             if(newEvent == kTRUE) newEvent = kFALSE;
221           }
222
223           of->WriteBuffer((char *) hcBuffer, hcwords*4);
224           npayloadbyte += hcwords*4;
225
226       // Process B side of the chamber
227           if ( rv >= 1 && rv <= 2 ) {
228             hcwords = ProduceHcDataV1andV2(digits,1,iDet,hcBuffer,kMaxHcWords);
229           }
230           if ( rv >= 3 ) {
231            
232               hcwords = ProduceHcDataV3     (digits,1,iDet,hcBuffer,kMaxHcWords,newEvent);
233               //hcwords = ProduceHcDataV3     (digits,1,iDet,hcBuffer,kMaxHcWords);
234           }
235
236           of->WriteBuffer((char *) hcBuffer, hcwords*4);
237           npayloadbyte += hcwords*4;
238
239         } else { // real data format
240                 // Process A side of the chamber
241                 hcwords = ProduceHcData(digits,0,iDet,hcBuffer,kMaxHcWords,newEvent);
242                 if(newEvent == kTRUE) newEvent = kFALSE;
243         of->WriteBuffer((char *) hcBuffer, hcwords*4);
244         npayloadbyte += hcwords*4;
245                 //for ( Int_t i=0; i<hcwords; i++ ) AliInfo(Form("Buf : %X",hcBuffer[i]));
246
247                 // Process B side of the chamber
248                 hcwords = ProduceHcData(digits,1,iDet,hcBuffer,kMaxHcWords,newEvent);
249         of->WriteBuffer((char *) hcBuffer, hcwords*4);
250         npayloadbyte += hcwords*4;
251         }
252
253         }
254
255       }
256     }
257
258     // Complete header
259     header.fSize = UInt_t(of->Tellp()) - hpos;
260     header.SetAttribute(0);  // Valid data
261     of->Seekp(hpos);         // Rewind to header position
262     of->WriteBuffer((char *) (& header), sizeof(header));
263     delete of;
264   }
265
266   delete [] hcBuffer;
267
268   return kTRUE;
269
270 }
271
272 //_____________________________________________________________________________
273 void AliTRDrawData::ProduceSMIndexData(UInt_t *buf, Int_t& nw){
274         // 
275         // This function generates 
276         //       1) SM index words : ssssssss ssssssss vvvv rrrr r d t mmmmm
277         //          - s : size of SM header (number of header, default = 0x0001)
278         //          - v : SM header version (default = 0xa)
279         //          - r : reserved for future use (default = 00000)
280         //          - d : track data enabled bit (default = 0)
281         //          - t : tracklet data enabled bit (default = 1)
282         //          - m : stack mask (each bit corresponds a stack, default = 11111)
283         //
284         //       2) SM header : rrr c vvvv vvvvvvvv vvvv rrrr bbbbbbbb
285         //          - r : reserved for future use (default = 000)
286         //          - c : clean check out flag (default = 1)
287         //          - v : hardware design revision (default = 0x0404)
288         //          - r : reserved for future use (default = 0x0)
289         //          - b : physical board ID (default = 0x71)
290         //
291         //       3) stack index words : ssssssss ssssssss vvvv mmmm mmmmmmmm
292         //          - s : size of stack header (number of header, (default = 0x0007)
293         //          - v : header version (default = 0xa)
294         //          - m : link mask (default = 0xfff)
295         //
296         //       4) stack header : vvvvvvvv vvvvvvvv bbbbbbbb rrrr rrr c
297         //          - v : hardware design revision (default = 0x0404)
298         //          - b : physical board ID (default = 0x5b)
299         //          - r : reserved for future use (default = 0000 000)
300         //          - c : clean checkout flag (default = 1)
301         //      
302         //       and 6 dummy words(0x00000000)
303         //
304         
305         buf[nw++] = 0x0001a03f; // SM index words
306         buf[nw++] = 0x10404071; // SM header
307
308         for (Int_t istack=0; istack<5; istack++){
309                 buf[nw++] = 0x0007afff; // stack index words
310                 buf[nw++] = 0x04045b01; // stack header
311                 for (Int_t i=0;i<6;i++) buf[nw++] = 0x00000000; // 6 dummy words
312         } // loop over 5 stacks
313
314 }
315
316 //_____________________________________________________________________________
317 Int_t AliTRDrawData::ProduceHcData(AliTRDdataArrayS *digits, Int_t side, Int_t det, UInt_t *buf, Int_t maxSize, Bool_t newEvent = kFALSE){
318         //
319         // This function can be used for both ZS and NZS data
320         //
321
322         Int_t           nw = 0;                       // Number of written    words
323         Int_t           of = 0;                       // Number of overflowed words
324         Int_t        layer = fGeo->GetLayer( det );   // Layer
325         Int_t        stack = fGeo->GetStack( det );   // Stack
326         Int_t         sect = fGeo->GetSector( det );  // Sector (=iDDL)
327         Int_t         nRow = fGeo->GetRowMax( layer, stack, sect );
328         Int_t         nCol = fGeo->GetColMax( layer );
329         const Int_t kNTBin = AliTRDcalibDB::Instance()->GetNumberOfTimeBins();
330         Int_t       kCtype = 0;                       // Chamber type (0:C0, 1:C1)
331
332         Bool_t tracklet_on = fFee->GetTracklet();     // **new**   
333
334         // Check the nCol and nRow.
335         if ((nCol == 144) && (nRow == 16 || nRow == 12)) {
336         kCtype = (nRow-12) / 4;
337         } else {
338         AliError(Form("This type of chamber is not supported (nRow=%d, nCol=%d).",nRow,nCol));
339         return 0;
340         }
341
342         AliDebug(1,Form("Producing raw data for sect=%d layer=%d stack=%d side=%d",sect,layer,stack,side));
343
344         AliTRDmcmSim** mcm = new AliTRDmcmSim*[(kCtype + 3)*(fGeo->MCMmax())];
345
346         if (newEvent) ProduceSMIndexData(buf, nw);              // SM index words , Stack index words
347
348         if (!tracklet_on) WriteIntermediateWordsV2(buf,nw,of,maxSize,det,side); // no tracklet or NZS
349  
350         
351         // scanning direction such, that tracklet-words are sorted in ascending z and then in ascending y order
352         // ROB numbering on chamber and MCM numbering on ROB increase with decreasing z and increasing y
353         for (Int_t iRobRow =  (kCtype + 3)-1; iRobRow >= 0; iRobRow-- ) {
354         Int_t iRob = iRobRow * 2 + side;
355         // MCM on one ROB
356         for (Int_t iMcmRB = 0; iMcmRB < fGeo->MCMmax(); iMcmRB++ ) {
357                 Int_t iMcm = 16 - 4*(iMcmRB/4 + 1) + (iMcmRB%4);
358                 Int_t entry = iRobRow*(fGeo->MCMmax()) + iMcm;
359         
360                 mcm[entry] = new AliTRDmcmSim();
361                 mcm[entry]->Init( det, iRob, iMcm , newEvent);
362                 //mcm[entry]->Init( det, iRob, iMcm);
363                 if (newEvent == kTRUE) newEvent = kFALSE; // only one mcm is concerned with new event
364                 Int_t padrow = mcm[entry]->GetRow();
365
366                 // Copy ADC data to MCM simulator
367                 for (Int_t iAdc = 0; iAdc < 21; iAdc++ ) {
368                     Int_t padcol = mcm[entry]->GetCol( iAdc );
369                     if ((padcol >=    0) && (padcol <  nCol)) {
370                                 for (Int_t iT = 0; iT < kNTBin; iT++) { 
371                                         mcm[entry]->SetData( iAdc, iT, digits->GetDataUnchecked( padrow, padcol, iT) );
372                                 } 
373                     } 
374                 else {  // this means it is out of chamber, and masked ADC
375                                 mcm[entry]->SetDataPedestal( iAdc );
376                         }
377                 }
378
379                 // Simulate process in MCM
380                 mcm[entry]->Filter();     // Apply filter
381                 mcm[entry]->ZSMapping();  // Calculate zero suppression mapping
382
383                 if (tracklet_on) {
384                     mcm[entry]->Tracklet(); 
385                     Int_t tempNw =  mcm[entry]->ProduceTrackletStream( &buf[nw], maxSize - nw );
386                     //Int_t tempNw = 0;
387                     if( tempNw < 0 ) {
388                                 of += tempNw;
389                                 nw += maxSize - nw;
390                                 AliError(Form("Buffer overflow detected. Please increase the buffer size and recompile."));
391                     } else {
392                                 nw += tempNw;
393                     }
394                 } else { // no tracklets: write raw-data already in this loop 
395                     // Write MCM data to buffer
396                     Int_t tempNw =  mcm[entry]->ProduceRawStreamV2( &buf[nw], maxSize - nw );
397                     if( tempNw < 0 ) {
398                                 of += tempNw;
399                                 nw += maxSize - nw;
400                                 AliError(Form("Buffer overflow detected. Please increase the buffer size and recompile."));
401                     } else {
402                                 nw += tempNw;
403                     }
404                     
405                     delete mcm[entry];
406                 }
407
408                 //mcm->DumpData( "trdmcmdata.txt", "RFZS" ); // debugging purpose
409         }
410         }
411
412         // if tracklets are switched on, raw-data can be written only after all tracklets
413         if (tracklet_on) {
414         WriteIntermediateWordsV2(buf,nw,of,maxSize,det,side); 
415   
416         // Scan for ROB and MCM
417         for (Int_t iRobRow =  (kCtype + 3)-1; iRobRow >= 0; iRobRow-- ) {
418                 //Int_t iRob = iRobRow * 2 + side;
419                 // MCM on one ROB
420                         for (Int_t iMcmRB = 0; iMcmRB < fGeo->MCMmax(); iMcmRB++ ) {
421                         Int_t iMcm = 16 - 4*(iMcmRB/4 + 1) + (iMcmRB%4);
422               
423                         Int_t entry = iRobRow*(fGeo->MCMmax()) + iMcm; 
424                       
425                         // Write MCM data to buffer
426                         Int_t tempNw =  mcm[entry]->ProduceRawStreamV2( &buf[nw], maxSize - nw );
427                         if( tempNw < 0 ) {
428                                         of += tempNw;
429                                         nw += maxSize - nw;
430                                         AliError(Form("Buffer overflow detected. Please increase the buffer size and recompile."));
431                         } else {
432                                         nw += tempNw;
433                         }
434               
435                       delete mcm[entry];
436           
437                         }       
438         }
439         }
440
441         delete [] mcm;
442   
443         // Write end of raw data marker
444         if (nw < maxSize) {
445         buf[nw++] = kEndofrawdatamarker; 
446         } else {
447         of++;
448         }
449         
450         if (of != 0) {
451         AliError("Buffer overflow. Data is truncated. Please increase buffer size and recompile.");
452         }
453
454         return nw;
455 }
456
457
458 //_____________________________________________________________________________
459 Int_t AliTRDrawData::ProduceHcDataV1andV2(AliTRDdataArrayS *digits, Int_t side
460                                         , Int_t det, UInt_t *buf, Int_t maxSize)
461 {
462   //
463   // This function simulates: 1) SM-I commissiong data Oct. 06 (Raw Version == 1).
464   //                          2) Full Raw Production Version   (Raw Version == 2)
465   //
466   // Produce half chamber data (= an ORI data) for the given chamber (det) and side (side)
467   // where
468   //
469   //   side=0 means A side with ROB positions 0, 2, 4, 6.
470   //   side=1 means B side with ROB positions 1, 3, 5, 7.
471   //
472   // Chamber type (C0 orC1) is determined by "det" automatically.
473   // Appropriate size of buffer (*buf) must be prepared prior to calling this function.
474   // Pointer to the buffer and its size must be given to "buf" and "maxSize".
475   // Return value is the number of valid data filled in the buffer in unit of 32 bits
476   // UInt_t words.
477   // If buffer size if too small, the data is truncated with the buffer size however
478   // the function will finish without crash (this behaviour is similar to the MCM).
479   //
480
481   Int_t           nw = 0;                       // Number of written    words
482   Int_t           of = 0;                       // Number of overflowed words
483   Int_t        layer = fGeo->GetLayer( det );   // Layer
484   Int_t        stack = fGeo->GetStack( det );   // Stack
485   Int_t         sect = fGeo->GetSector( det );  // Sector (=iDDL)
486   Int_t         nRow = fGeo->GetRowMax( layer, stack, sect );
487   Int_t         nCol = fGeo->GetColMax( layer );
488   const Int_t kNTBin = AliTRDcalibDB::Instance()->GetNumberOfTimeBins();
489   Int_t       kCtype = 0;                       // Chamber type (0:C0, 1:C1)
490   Int_t          iEv = 0xA;                     // Event ID. Now fixed to 10, how do I get event id?
491   UInt_t           x = 0;                       // General used number
492   Int_t           rv = fFee->GetRAWversion();
493
494   // Check the nCol and nRow.
495   if ((nCol == 144) && 
496       (nRow == 16 || nRow == 12)) {
497     kCtype = (nRow-12) / 4;
498   } 
499   else {
500     AliError(Form("This type of chamber is not supported (nRow=%d, nCol=%d)."
501                  ,nRow,nCol));
502     return 0;
503   }
504
505   AliDebug(1,Form("Producing raw data for sect=%d layer=%d stack=%d side=%d"
506                  ,sect,layer,stack,side));
507
508   // Tracklet should be processed here but not implemented yet
509
510   // Write end of tracklet marker
511   if (nw < maxSize) {
512     buf[nw++] = kEndoftrackletmarker;
513   } 
514   else {
515     of++;
516   }
517
518   // Half Chamber header
519   if      ( rv == 1 ) {
520     // Now it is the same version as used in SM-I commissioning.
521     Int_t  dcs = det+100;      // DCS Serial (in simulation, it is meaningless
522     x = (dcs<<20) | (sect<<15) | (layer<<12) | (stack<<9) | (side<<8) | 1;
523     if (nw < maxSize) {
524       buf[nw++] = x; 
525     }
526     else {
527       of++;
528     }
529   } 
530   else if ( rv == 2 ) {
531     // h[0] (there are 3 HC header)
532     Int_t minorv = 0;      // The minor version number
533     Int_t add    = 2;      // The number of additional header words to follow
534     x = (1<<31) | (rv<<24) | (minorv<<17) | (add<<14) | (sect<<9) | (layer<<6) | (stack<<3) | (side<<2) | 1;
535     if (nw < maxSize) {
536       buf[nw++] = x; 
537     }
538     else {
539       of++;
540     }
541     // h[1]
542     Int_t bcCtr   = 99; // bunch crossing counter. Here it is set to 99 always for no reason
543     Int_t ptCtr   = 15; // pretrigger counter. Here it is set to 15 always for no reason
544     Int_t ptPhase = 11; // pretrigger phase. Here it is set to 11 always for no reason
545     x = (bcCtr<<16) | (ptCtr<<12) | (ptPhase<<8) | ((kNTBin-1)<<2) | 1;
546     if (nw < maxSize) {
547       buf[nw++] = x; 
548     }
549     else {
550       of++;
551     }
552     // h[2]
553     Int_t pedSetup       = 1;    // Pedestal filter setup (0:1). Here it is always 1 for no reason
554     Int_t gainSetup      = 1;    // Gain filter setup (0:1). Here it is always 1 for no reason
555     Int_t tailSetup      = 1;    // Tail filter setup (0:1). Here it is always 1 for no reason
556     Int_t xtSetup        = 0;    // Cross talk filter setup (0:1). Here it is always 0 for no reason
557     Int_t nonlinSetup    = 0;    // Nonlinearity filter setup (0:1). Here it is always 0 for no reason
558     Int_t bypassSetup    = 0;    // Filter bypass (for raw data) setup (0:1). Here it is always 0 for no reason
559     Int_t commonAdditive = 10;   // Digital filter common additive (0:63). Here it is always 10 for no reason
560     x = (pedSetup<<31) | (gainSetup<<30) | (tailSetup<<29) | (xtSetup<<28) | (nonlinSetup<<27)
561       | (bypassSetup<<26) | (commonAdditive<<20) | 1;
562     if (nw < maxSize) {
563       buf[nw++] = x; 
564     }
565     else {
566       of++;
567     }
568   }
569
570   // Scan for ROB and MCM
571   for (Int_t iRobRow = 0; iRobRow < (kCtype + 3); iRobRow++ ) {
572     Int_t iRob = iRobRow * 2 + side;
573     for (Int_t iMcm = 0; iMcm < fGeo->MCMmax(); iMcm++ ) {
574       Int_t padrow = iRobRow * 4 + iMcm / 4;
575
576       // MCM header
577       x = ((iRob * fGeo->MCMmax() + iMcm) << 24) | ((iEv % 0x100000) << 4) | 0xC;
578       if (nw < maxSize) {
579         buf[nw++] = x; 
580       }
581       else {
582         of++;
583       }
584
585       // ADC data
586       for (Int_t iAdc = 0; iAdc < 21; iAdc++ ) {
587         Int_t padcol = fFee->GetPadColFromADC(iRob, iMcm, iAdc);
588         UInt_t aa = !(iAdc & 1) + 2;
589         UInt_t *a = new UInt_t[kNTBin+2];
590         // 3 timebins are packed into one 32 bits word
591         for (Int_t iT = 0; iT < kNTBin; iT+=3) { 
592           if ((padcol >=    0) && (padcol <  nCol)) {
593             a[iT  ] = ((iT    ) < kNTBin ) ? digits->GetDataUnchecked(padrow,padcol,iT    ) : 0;
594             a[iT+1] = ((iT + 1) < kNTBin ) ? digits->GetDataUnchecked(padrow,padcol,iT + 1) : 0;
595             a[iT+2] = ((iT + 2) < kNTBin ) ? digits->GetDataUnchecked(padrow,padcol,iT + 2) : 0; 
596           } 
597           else {
598             a[iT] = a[iT+1] = a[iT+2] = 0; // This happenes at the edge of chamber (should be pedestal! How?)
599           }
600           x = (a[iT+2] << 22) | (a[iT+1] << 12) | (a[iT] << 2) | aa;
601           if (nw < maxSize) {
602             buf[nw++] = x; 
603           }
604           else {
605             of++;
606           }
607         }
608         // Diagnostics
609         Float_t avg = 0;
610         Float_t rms = 0;
611         for (Int_t iT = 0; iT < kNTBin; iT++) {
612           avg += (Float_t) (a[iT]);
613         }
614         avg /= (Float_t) kNTBin;
615         for (Int_t iT = 0; iT < kNTBin; iT++) {
616           rms += ((Float_t) (a[iT]) - avg) * ((Float_t) (a[iT]) - avg);
617         }
618         rms = TMath::Sqrt(rms / (Float_t) kNTBin);
619         if (rms > 1.7) {
620           AliDebug(2,Form("Large RMS (>1.7)  (ROB,MCM,ADC)=(%02d,%02d,%02d), avg=%03.1f, rms=%03.1f"
621                           ,iRob,iMcm,iAdc,avg,rms));
622         }
623         delete [] a;
624       }
625     }
626   }
627
628   // Write end of raw data marker
629   if (nw < maxSize) {
630     buf[nw++] = kEndofrawdatamarker; 
631   }
632   else {
633     of++;
634   }
635   if (of != 0) {
636     AliWarning("Buffer overflow. Data is truncated. Please increase buffer size and recompile.");
637   }
638
639   return nw;
640
641 }
642
643 //_____________________________________________________________________________
644
645 //Int_t AliTRDrawData::ProduceHcDataV3(AliTRDdataArrayS *digits, Int_t side , Int_t det, UInt_t *buf, Int_t maxSize)
646 Int_t AliTRDrawData::ProduceHcDataV3(AliTRDdataArrayS *digits, Int_t side , Int_t det, UInt_t *buf, Int_t maxSize, Bool_t newEvent = kFALSE)
647 {
648   //
649   // This function simulates: Raw Version == 3 (Zero Suppression Prototype)
650   //
651
652   Int_t           nw = 0;                       // Number of written    words
653   Int_t           of = 0;                       // Number of overflowed words
654   Int_t        layer = fGeo->GetLayer( det );   // Layer
655   Int_t        stack = fGeo->GetStack( det );   // Stack
656   Int_t         sect = fGeo->GetSector( det );  // Sector (=iDDL)
657   Int_t         nRow = fGeo->GetRowMax( layer, stack, sect );
658   Int_t         nCol = fGeo->GetColMax( layer );
659   const Int_t kNTBin = AliTRDcalibDB::Instance()->GetNumberOfTimeBins();
660   Int_t       kCtype = 0;                       // Chamber type (0:C0, 1:C1)
661   //Int_t          iEv = 0xA;                     // Event ID. Now fixed to 10, how do I get event id?
662
663  
664
665   Bool_t tracklet_on = fFee->GetTracklet();     // **new**
666
667   // Check the nCol and nRow.
668   if ((nCol == 144) && 
669       (nRow == 16 || nRow == 12)) {
670     kCtype = (nRow-12) / 4;
671   } 
672   else {
673     AliError(Form("This type of chamber is not supported (nRow=%d, nCol=%d)."
674                  ,nRow,nCol));
675     return 0;
676   }
677
678   AliDebug(1,Form("Producing raw data for sect=%d layer=%d stack=%d side=%d"
679                  ,sect,layer,stack,side));
680
681   AliTRDmcmSim** mcm = new AliTRDmcmSim*[(kCtype + 3)*(fGeo->MCMmax())];
682
683   // in case no tracklet-words are processed: write the tracklet-endmarker as well as all additional words immediately and write 
684   // raw-data in one go; if tracklet-processing is enabled, first all tracklet-words of a half-chamber have to be processed before the
685   // additional words (tracklet-endmarker,headers,...)are written. Raw-data is written in a second loop;
686   
687   if (!tracklet_on) {
688       WriteIntermediateWords(buf,nw,of,maxSize,det,side); 
689   }
690   
691   // Scan for ROB and MCM
692   // scanning direction such, that tracklet-words are sorted in ascending z and then in ascending y order
693   // ROB numbering on chamber and MCM numbering on ROB increase with decreasing z and increasing y
694   for (Int_t iRobRow =  (kCtype + 3)-1; iRobRow >= 0; iRobRow-- ) {
695     Int_t iRob = iRobRow * 2 + side;
696     // MCM on one ROB
697     for (Int_t iMcmRB = 0; iMcmRB < fGeo->MCMmax(); iMcmRB++ ) {
698         Int_t iMcm = 16 - 4*(iMcmRB/4 + 1) + (iMcmRB%4);
699         Int_t entry = iRobRow*(fGeo->MCMmax()) + iMcm;
700         
701         mcm[entry] = new AliTRDmcmSim();
702         mcm[entry]->Init( det, iRob, iMcm , newEvent);
703         //mcm[entry]->Init( det, iRob, iMcm);
704         if (newEvent == kTRUE) newEvent = kFALSE; // only one mcm is concerned with new event
705         Int_t padrow = mcm[entry]->GetRow();
706
707         // Copy ADC data to MCM simulator
708         for (Int_t iAdc = 0; iAdc < 21; iAdc++ ) {
709             Int_t padcol = mcm[entry]->GetCol( iAdc );
710             if ((padcol >=    0) && (padcol <  nCol)) {
711                 for (Int_t iT = 0; iT < kNTBin; iT++) { 
712                     mcm[entry]->SetData( iAdc, iT, digits->GetDataUnchecked( padrow, padcol, iT) );
713                 } 
714             } 
715             else {  // this means it is out of chamber, and masked ADC
716                 mcm[entry]->SetDataPedestal( iAdc );
717             }
718         }
719
720         // Simulate process in MCM
721         mcm[entry]->Filter();     // Apply filter
722         mcm[entry]->ZSMapping();  // Calculate zero suppression mapping
723
724         if (tracklet_on) {
725             mcm[entry]->Tracklet(); 
726             Int_t tempNw =  mcm[entry]->ProduceTrackletStream( &buf[nw], maxSize - nw );
727             //Int_t tempNw = 0;
728             if( tempNw < 0 ) {
729                 of += tempNw;
730                 nw += maxSize - nw;
731                 AliError(Form("Buffer overflow detected. Please increase the buffer size and recompile."));
732             } else {
733                 nw += tempNw;
734             }
735         }
736         // no tracklets: write raw-data already in this loop
737         else {
738              // Write MCM data to buffer
739             Int_t tempNw =  mcm[entry]->ProduceRawStream( &buf[nw], maxSize - nw );
740             if( tempNw < 0 ) {
741                 of += tempNw;
742                 nw += maxSize - nw;
743                 AliError(Form("Buffer overflow detected. Please increase the buffer size and recompile."));
744             } else {
745                 nw += tempNw;
746             }
747             
748             delete mcm[entry];
749         }
750             
751         
752
753
754         //mcm->DumpData( "trdmcmdata.txt", "RFZS" ); // debugging purpose
755     }
756   }
757
758   // if tracklets are switched on, raw-data can be written only after all tracklets
759   if (tracklet_on) {
760       WriteIntermediateWords(buf,nw,of,maxSize,det,side); 
761   
762   
763       // Scan for ROB and MCM
764       for (Int_t iRobRow =  (kCtype + 3)-1; iRobRow >= 0; iRobRow-- ) {
765           //Int_t iRob = iRobRow * 2 + side;
766           // MCM on one ROB
767           for (Int_t iMcmRB = 0; iMcmRB < fGeo->MCMmax(); iMcmRB++ ) {
768               Int_t iMcm = 16 - 4*(iMcmRB/4 + 1) + (iMcmRB%4);
769               
770               Int_t entry = iRobRow*(fGeo->MCMmax()) + iMcm; 
771               
772               // Write MCM data to buffer
773               Int_t tempNw =  mcm[entry]->ProduceRawStream( &buf[nw], maxSize - nw );
774               if( tempNw < 0 ) {
775                   of += tempNw;
776                   nw += maxSize - nw;
777                   AliError(Form("Buffer overflow detected. Please increase the buffer size and recompile."));
778               } else {
779                   nw += tempNw;
780               }
781               
782               delete mcm[entry];
783           
784           }
785       }
786   }
787
788   delete [] mcm;
789   
790   // Write end of raw data marker
791   if (nw < maxSize) {
792     buf[nw++] = kEndofrawdatamarker; 
793   }
794   else {
795     of++;
796   }
797   if (of != 0) {
798     AliError("Buffer overflow. Data is truncated. Please increase buffer size and recompile.");
799   }
800
801
802   return nw;
803
804 }
805
806 //_____________________________________________________________________________
807 AliTRDdigitsManager *AliTRDrawData::Raw2Digits(AliRawReader *rawReader)
808 {
809   //
810   // Vx of the raw data reading
811   //
812
813   AliTRDdataArrayS *digits = 0;
814   AliTRDdataArrayI *track0 = 0;
815   AliTRDdataArrayI *track1 = 0;
816   AliTRDdataArrayI *track2 = 0; 
817
818   //AliTRDSignalIndex *indexes = 0;
819   // Create the digits manager
820   AliTRDdigitsManager* digitsManager = new AliTRDdigitsManager();
821   digitsManager->CreateArrays();
822
823   //AliTRDrawOldStream input(rawReader);
824   //   AliTRDRawStreamV2 input(rawReader);
825   //   input.SetRawVersion( fFee->GetRAWversion() );
826   //   input.Init();
827
828   AliTRDrawStreamBase *pinput = AliTRDrawStreamBase::GetRawStream(rawReader);
829   AliTRDrawStreamBase &input = *pinput;
830   input.SetRawVersion( fFee->GetRAWversion() ); //<= ADDED by MinJung
831
832   AliInfo(Form("Stream version: %s", input.IsA()->GetName()));
833
834   // Loop through the digits
835   Int_t det    = 0;
836
837   while (det >= 0)
838     {
839       det = input.NextChamber(digitsManager);
840       if (det >= 0)
841         {
842           // get...
843           digits = (AliTRDdataArrayS *) digitsManager->GetDigits(det);
844           track0 = (AliTRDdataArrayI *) digitsManager->GetDictionary(det,0);
845           track1 = (AliTRDdataArrayI *) digitsManager->GetDictionary(det,1);
846           track2 = (AliTRDdataArrayI *) digitsManager->GetDictionary(det,2);
847           // and compress
848           if (digits) digits->Compress(1,0);
849           if (track0) track0->Compress(1,0);
850           if (track1) track1->Compress(1,0);
851           if (track2) track2->Compress(1,0);
852         }
853     }
854
855   delete pinput;
856   pinput = NULL;
857
858   return digitsManager;
859 }
860
861
862 //_____________________________________________________________________________
863 void AliTRDrawData::WriteIntermediateWords(UInt_t* buf, Int_t& nw, Int_t& of, const Int_t& maxSize, const Int_t& det, const Int_t& side) {
864     
865     Int_t        layer = fGeo->GetLayer( det );   // Layer
866     Int_t        stack = fGeo->GetStack( det );   // Stack
867     Int_t         sect = fGeo->GetSector( det );  // Sector (=iDDL)
868     Int_t           rv = fFee->GetRAWversion();
869     const Int_t kNTBin = AliTRDcalibDB::Instance()->GetNumberOfTimeBins();
870     UInt_t           x = 0;
871
872     // Write end of tracklet marker
873     if (nw < maxSize) {
874         buf[nw++] = kEndoftrackletmarker;
875     } 
876     else {
877         of++;
878     }
879     
880   // Half Chamber header
881   // h[0] (there are 3 HC header)
882     Int_t minorv = 0;    // The minor version number
883     Int_t add    = 2;    // The number of additional header words to follow
884     x = (1<<31) | (rv<<24) | (minorv<<17) | (add<<14) | (sect<<9) | (layer<<6) | (stack<<3) | (side<<2) | 1;
885     if (nw < maxSize) {
886         buf[nw++] = x; 
887     }
888     else {
889         of++;
890     }
891     // h[1]
892     Int_t bcCtr   = 99; // bunch crossing counter. Here it is set to 99 always for no reason
893     Int_t ptCtr   = 15; // pretrigger counter. Here it is set to 15 always for no reason
894     Int_t ptPhase = 11; // pretrigger phase. Here it is set to 11 always for no reason
895     x = (bcCtr<<16) | (ptCtr<<12) | (ptPhase<<8) | ((kNTBin-1)<<2) | 1;
896     if (nw < maxSize) {
897         buf[nw++] = x; 
898     }
899     else {
900         of++;
901     }
902     // h[2]
903     Int_t pedSetup       = 1;  // Pedestal filter setup (0:1). Here it is always 1 for no reason
904     Int_t gainSetup      = 1;  // Gain filter setup (0:1). Here it is always 1 for no reason
905     Int_t tailSetup      = 1;  // Tail filter setup (0:1). Here it is always 1 for no reason
906     Int_t xtSetup        = 0;  // Cross talk filter setup (0:1). Here it is always 0 for no reason
907     Int_t nonlinSetup    = 0;  // Nonlinearity filter setup (0:1). Here it is always 0 for no reason
908     Int_t bypassSetup    = 0;  // Filter bypass (for raw data) setup (0:1). Here it is always 0 for no reason
909     Int_t commonAdditive = 10; // Digital filter common additive (0:63). Here it is always 10 for no reason
910     x = (pedSetup<<31) | (gainSetup<<30) | (tailSetup<<29) | (xtSetup<<28) | (nonlinSetup<<27)
911         | (bypassSetup<<26) | (commonAdditive<<20) | 1;
912     if (nw < maxSize) {
913         buf[nw++] = x; 
914     }
915     else {
916         of++;
917     } 
918 }
919
920 //_____________________________________________________________________________
921 void AliTRDrawData::WriteIntermediateWordsV2(UInt_t* buf, Int_t& nw, Int_t& of, const Int_t& maxSize, const Int_t& det, const Int_t& side) {
922     
923     Int_t        layer = fGeo->GetLayer( det );   // Layer
924     Int_t        stack = fGeo->GetStack( det );   // Stack
925     Int_t         sect = fGeo->GetSector( det );  // Sector (=iDDL)
926     Int_t           rv = fFee->GetRAWversion();
927     const Int_t kNTBin = AliTRDcalibDB::Instance()->GetNumberOfTimeBins();
928         Bool_t tracklet_on = fFee->GetTracklet();
929     UInt_t           x = 0;
930
931     // Write end of tracklet marker
932     if (nw < maxSize) buf[nw++] = fgkEndOfTrackletMarker; else of++;
933    
934         // Half Chamber header
935         // h[0] (there are 2 HC headers) xmmm mmmm nnnn nnnq qqss sssp ppcc ci01
936         //      , where  x : Raw version speacial number (=1)
937         //                   m : Raw version major number (test pattern, ZS, disable tracklet, 0, options)
938         //                   n : Raw version minor number
939         //                   q : number of addtional header words (default = 1)
940         //                   s : SM sector number (ALICE numbering)
941         //                   p : plane(layer) number
942         //                       c : chamber(stack) number
943         //                       i : side number (0:A, 1:B)
944         Int_t majorv = 0;       // The major version number 
945     Int_t minorv = 0;   // The minor version number
946     Int_t add    = 1;   // The number of additional header words to follow : now 1, previous 2
947         Int_t TP         = 0;   // test pattern (default=0)
948         Int_t ZS         = (rv==3) ? 1 : 0;                     // zero suppression
949         Int_t DT         = (tracklet_on) ? 0 : 1;       // disable tracklet 
950
951         majorv = (TP<<6) | (ZS<<5) | (DT<<4) | 1;       // major version
952
953     x = (1<<31) | (majorv<<24) | (minorv<<17) | (add<<14) | (sect<<9) | (layer<<6) | (stack<<3) | (side<<2) | 1;
954     if (nw < maxSize) buf[nw++] = x; else of++;
955    
956     // h[1]             tttt ttbb bbbb bbbb bbbb bbpp pphh hh01
957         // , where  t : number of time bins
958         //          b : bunch crossing number
959         //          p : pretrigger counter
960         //          h : pretrigger phase
961     Int_t bcCtr   = 99; // bunch crossing counter. Here it is set to 99 always for no reason
962     Int_t ptCtr   = 15; // pretrigger counter. Here it is set to 15 always for no reason
963     Int_t ptPhase = 11; // pretrigger phase. Here it is set to 11 always for no reason
964     //x = (bcCtr<<16) | (ptCtr<<12) | (ptPhase<<8) | ((kNTBin-1)<<2) | 1;       // old format
965     x = ((kNTBin-1)<<26) | (bcCtr<<10) | (ptCtr<<6) | (ptPhase<<2) | 1;
966     if (nw < maxSize) buf[nw++] = x; else of++;
967   
968 }
969
970 //_____________________________________________________________________________
971 AliTRDdigitsManager *AliTRDrawData::Raw2DigitsOLD(AliRawReader *rawReader)
972 {
973   //
974   // Vx of the raw data reading
975   //
976
977   AliTRDdataArrayS *digits = 0;
978   AliTRDdataArrayI *track0 = 0;
979   AliTRDdataArrayI *track1 = 0;
980   AliTRDdataArrayI *track2 = 0; 
981
982   AliTRDSignalIndex *indexes = 0;
983   // Create the digits manager
984   AliTRDdigitsManager* digitsManager = new AliTRDdigitsManager();
985   digitsManager->CreateArrays();
986
987   //AliTRDrawOldStream input(rawReader);
988   AliTRDRawStreamV2 input(rawReader);
989   input.SetRawVersion( fFee->GetRAWversion() );
990   input.Init();
991
992   AliInfo(Form("Stream version: %s", input.IsA()->GetName()));
993
994   // Loop through the digits
995   Int_t lastdet = -1;
996   Int_t det    = 0;
997   Int_t it = 0;
998   while (input.Next()) {
999
1000       det    = input.GetDet();
1001
1002       if (det != lastdet) { // If new detector found
1003         
1004           lastdet = det;
1005
1006           if (digits) digits->Compress(1,0);
1007           if (track0) track0->Compress(1,0);
1008           if (track1) track1->Compress(1,0);
1009           if (track2) track2->Compress(1,0);
1010         
1011           // Add a container for the digits of this detector
1012           digits = (AliTRDdataArrayS *) digitsManager->GetDigits(det);
1013           track0 = (AliTRDdataArrayI *) digitsManager->GetDictionary(det,0);
1014           track1 = (AliTRDdataArrayI *) digitsManager->GetDictionary(det,1);
1015           track2 = (AliTRDdataArrayI *) digitsManager->GetDictionary(det,2);
1016
1017           // Allocate memory space for the digits buffer
1018           if (digits->GetNtime() == 0) 
1019             {
1020               digits->Allocate(input.GetMaxRow(),input.GetMaxCol(), input.GetNumberOfTimeBins());
1021               track0->Allocate(input.GetMaxRow(),input.GetMaxCol(), input.GetNumberOfTimeBins());
1022               track1->Allocate(input.GetMaxRow(),input.GetMaxCol(), input.GetNumberOfTimeBins());
1023               track2->Allocate(input.GetMaxRow(),input.GetMaxCol(), input.GetNumberOfTimeBins());
1024             }
1025
1026           indexes = digitsManager->GetIndexes(det);
1027           indexes->SetSM(input.GetSM());
1028           indexes->SetStack(input.GetStack());
1029           indexes->SetLayer(input.GetLayer());
1030           indexes->SetDetNumber(det);
1031           if (indexes->IsAllocated() == kFALSE)
1032             indexes->Allocate(input.GetMaxRow(), input.GetMaxCol(), input.GetNumberOfTimeBins());
1033         }
1034     
1035       // 3 timebin data are stored per word
1036       for (it = 0; it < 3; it++)
1037         {
1038           if ( input.GetTimeBin() + it < input.GetNumberOfTimeBins() )
1039             {
1040               if (input.GetSignals()[it] > 0)
1041                 {
1042                   digits->SetDataUnchecked(input.GetRow(), input.GetCol(),
1043                                            input.GetTimeBin() + it, input.GetSignals()[it]);
1044
1045                   indexes->AddIndexTBin(input.GetRow(), input.GetCol(),
1046                                         input.GetTimeBin() + it);
1047                   track0->SetDataUnchecked(input.GetRow(), input.GetCol(),
1048                                            input.GetTimeBin() + it, 0);
1049                   track1->SetDataUnchecked(input.GetRow(), input.GetCol(),
1050                                            input.GetTimeBin() + it, 0);
1051                   track2->SetDataUnchecked(input.GetRow(), input.GetCol(),
1052                                            input.GetTimeBin() + it, 0);
1053                 }
1054             }
1055         }
1056   }
1057
1058   if (digits) digits->Compress(1,0);
1059   if (track0) track0->Compress(1,0);
1060   if (track1) track1->Compress(1,0);
1061   if (track2) track2->Compress(1,0);
1062
1063   return digitsManager;
1064
1065 }