]> git.uio.no Git - u/mrichter/AliRoot.git/blob - ITS/AliITSHandleDaSSD.cxx
add ITS to TRD prolongation monitoring
[u/mrichter/AliRoot.git] / ITS / AliITSHandleDaSSD.cxx
1 /**************************************************************************
2  * Copyright(c) 2007-2009, 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 /// This class provides ITS SSD data handling
21 /// used by DA. 
22 //  Author: Oleksandr Borysov
23 //  Date: 18/07/2008
24 ///////////////////////////////////////////////////////////////////////////////
25
26 #include <cstring>
27 #include <fstream>
28 #include <new>
29 #include <Riostream.h> 
30 #include "AliITSHandleDaSSD.h"
31 //#include <math.h>
32 #include <limits.h>
33 #include "event.h"
34 #include "TFile.h"
35 #include "TString.h"
36 #include "TMath.h"
37 #include "AliLog.h"
38 #include "AliITSNoiseSSDv2.h"
39 #include "AliITSPedestalSSDv2.h"
40 #include "AliITSBadChannelsSSDv2.h"
41 #include "AliITSRawStreamSSD.h"
42 #include "AliRawReaderDate.h"
43 #include "AliITSRawStreamSSD.h"
44 #include "AliITSChannelDaSSD.h"
45
46
47 ClassImp(AliITSHandleDaSSD)
48
49 using namespace std;
50
51
52 const Int_t    AliITSHandleDaSSD::fgkNumberOfSSDModules = 1698;       // Number of SSD modules in ITS
53 const Int_t    AliITSHandleDaSSD::fgkNumberOfSSDModulesPerDdl = 108;  // Number of SSD modules in DDL
54 const Int_t    AliITSHandleDaSSD::fgkNumberOfSSDModulesPerSlot = 12;  // Number of SSD modules in Slot
55 const Short_t  AliITSHandleDaSSD::fgkMinSSDModuleId = 500;            // Initial SSD modules number
56 const Int_t    AliITSHandleDaSSD::fgkNumberOfSSDSlotsPerDDL = 9;      // Number of SSD slots per DDL
57 const Int_t    AliITSHandleDaSSD::fgkNumberOfSSDDDLs = 16;            // Number of SSD modules in Slot
58 const Float_t  AliITSHandleDaSSD::fgkPedestalThresholdFactor = 3.0;   // Defalt value for fPedestalThresholdFactor 
59 const Float_t  AliITSHandleDaSSD::fgkCmThresholdFactor = 3.0;         // Defalt value for fCmThresholdFactor
60
61 const UInt_t   AliITSHandleDaSSD::fgkZsBitMask      = 0x0000003F;     // Bit mask for FEROM ZS
62 const UInt_t   AliITSHandleDaSSD::fgkOffSetBitMask  = 0x000003FF;     // Bit mask for FEROM Offset correction
63 const UInt_t   AliITSHandleDaSSD::fgkBadChannelMask = 0x00000001;     // Mask to suppress the channel from the bad channel list
64 const Int_t    AliITSHandleDaSSD::fgkAdcPerDBlock   = 6;              // FEROM configuration file constant
65
66 //______________________________________________________________________________
67 AliITSHandleDaSSD::AliITSHandleDaSSD() :
68   fRawDataFileName(NULL),
69   fNumberOfModules(0),
70   fModules(NULL),
71   fModIndProcessed(0),
72   fModIndRead(0),
73   fModIndex(NULL),
74   fEqIndex(0),
75   fNumberOfEvents(0),
76   fBadChannelsList(NULL),
77   fDDLModuleMap(NULL),
78   fALaddersOff(0),
79   fCLaddersOff(0),
80   fLdcId(0),
81   fRunId(0),
82   fPedestalThresholdFactor(fgkPedestalThresholdFactor),
83   fCmThresholdFactor(fgkCmThresholdFactor),
84   fZsDefault(-1),
85   fOffsetDefault(INT_MAX),
86   fZsMinimum(2),
87   fMergeBCLists(1),
88   fZsFactor(3.0)
89 {
90 // Default constructor
91 }
92
93
94 //______________________________________________________________________________
95 AliITSHandleDaSSD::AliITSHandleDaSSD(Char_t *rdfname) :
96   fRawDataFileName(NULL),
97   fNumberOfModules(0),
98   fModules(NULL),
99   fModIndProcessed(0),
100   fModIndRead(0),
101   fModIndex(NULL),
102   fEqIndex(0),
103   fNumberOfEvents(0),
104   fBadChannelsList(NULL),
105   fDDLModuleMap(NULL),
106   fALaddersOff(0),
107   fCLaddersOff(0),
108   fLdcId(0),
109   fRunId(0),
110   fPedestalThresholdFactor(fgkPedestalThresholdFactor) ,
111   fCmThresholdFactor(fgkCmThresholdFactor),
112   fZsDefault(-1),
113   fOffsetDefault(INT_MAX),
114   fZsMinimum(2),
115   fMergeBCLists(1),
116   fZsFactor(3.0)
117 {
118   if (!Init(rdfname)) AliError("AliITSHandleDaSSD::AliITSHandleDaSSD() initialization error!");
119 }
120
121
122 //______________________________________________________________________________
123 AliITSHandleDaSSD::AliITSHandleDaSSD(const AliITSHandleDaSSD& ssdadldc) :
124   TObject(ssdadldc),
125   fRawDataFileName(ssdadldc.fRawDataFileName),
126   fNumberOfModules(ssdadldc.fNumberOfModules),
127   fModules(NULL),
128   fModIndProcessed(ssdadldc.fModIndProcessed),
129   fModIndRead(ssdadldc.fModIndRead),
130   fModIndex(NULL),
131   fEqIndex(0),
132   fNumberOfEvents(ssdadldc.fNumberOfEvents),
133   fBadChannelsList(NULL),
134   fDDLModuleMap(NULL),
135   fALaddersOff(ssdadldc.fALaddersOff),
136   fCLaddersOff(ssdadldc.fCLaddersOff),
137   fLdcId(ssdadldc.fLdcId),
138   fRunId(ssdadldc.fRunId),
139   fPedestalThresholdFactor(ssdadldc.fPedestalThresholdFactor),
140   fCmThresholdFactor(ssdadldc.fCmThresholdFactor),
141   fZsDefault(ssdadldc.fZsDefault),
142   fOffsetDefault(ssdadldc.fOffsetDefault),
143   fZsMinimum(ssdadldc.fZsMinimum),
144   fMergeBCLists(ssdadldc.fMergeBCLists),
145   fZsFactor(ssdadldc.fZsFactor)
146 {
147   // copy constructor
148   if ((ssdadldc.fNumberOfModules > 0) && (ssdadldc.fModules)) {
149     fModules = new (nothrow) AliITSModuleDaSSD* [ssdadldc.fNumberOfModules];
150     if (fModules) {
151       for (Int_t modind = 0; modind < ssdadldc.fNumberOfModules; modind++) {
152         if (ssdadldc.fModules[modind]) {
153           fModules[modind] = new AliITSModuleDaSSD(*(ssdadldc.fModules[modind]));
154           if (!fModules[modind]) { 
155             AliError("AliITSHandleDaSSD: Error copy constructor");
156             for (Int_t i = (modind - 1); i >= 0; i--) delete fModules[modind];
157             delete [] fModules;
158             fModules = NULL;
159             break;
160           }
161         } else fModules[modind] = NULL; 
162       }   
163     } else {
164       AliError(Form("AliITSHandleDaSSD: Error allocating memory for %i AliITSModulesDaSSD* objects!", ssdadldc.fNumberOfModules));
165       fNumberOfModules = 0;
166       fModules = NULL;
167     }
168   }
169   if (ssdadldc.fBadChannelsList) AliWarning("fBadChannelsList is not copied by copy constructor, use other methods to init it!");
170   if (ssdadldc.fDDLModuleMap) AliWarning("fDDLModuleMap is not copied by copy constructor, use other methods to init it!");
171 }
172
173
174 //______________________________________________________________________________
175 AliITSHandleDaSSD& AliITSHandleDaSSD::operator = (const AliITSHandleDaSSD& ssdadldc)
176 {
177 // assignment operator
178   if (this == &ssdadldc)  return *this;
179   TObject::operator=(ssdadldc);
180   if (fModules) {
181     for (Int_t i = 0; i < fNumberOfModules; i++) if (fModules[i]) delete fModules[i];
182     delete [] fModules; 
183     fModules = NULL;
184   }
185   if (fModIndex) { delete [] fModIndex; fModIndex = NULL; }
186   if ((ssdadldc.fNumberOfModules > 0) && (ssdadldc.fModules)) {
187     fModules = new (nothrow) AliITSModuleDaSSD* [ssdadldc.fNumberOfModules];
188     if (fModules) {
189       for (Int_t modind = 0; modind < ssdadldc.fNumberOfModules; modind++) {
190         if (ssdadldc.fModules[modind]) {
191               fModules[modind] = new AliITSModuleDaSSD(*(ssdadldc.fModules[modind]));
192           if (!fModules[modind]) { 
193                 AliError("AliITSHandleDaSSD: Error assignment operator");
194             for (Int_t i = (modind - 1); i >= 0; i--) delete fModules[modind];
195             delete [] fModules;
196             fModules = NULL;
197             break;
198           }
199         } else fModules[modind] = NULL; 
200       }   
201     } else {
202       AliError(Form("AliITSHandleDaSSD: Error allocating memory for %i AliITSModulesDaSSD* objects!", ssdadldc.fNumberOfModules));
203       fNumberOfModules = 0;
204       fModules = NULL;
205     }
206   }
207   if (ssdadldc.fRawDataFileName) {
208     fRawDataFileName = new (nothrow) Char_t[strlen(ssdadldc.fRawDataFileName)+1];
209     if (fRawDataFileName) strncpy(fRawDataFileName, ssdadldc.fRawDataFileName, strlen(ssdadldc.fRawDataFileName)+1);
210   } else fRawDataFileName = ssdadldc.fRawDataFileName;
211   fModIndProcessed = ssdadldc.fModIndProcessed;
212   fModIndRead = ssdadldc.fModIndRead;
213
214   if (ssdadldc.fModIndex) {
215     fModIndex = new (nothrow) Int_t [ssdadldc.fNumberOfModules];
216     if (fModIndex) memcpy(fModIndex, ssdadldc.fModIndex, ssdadldc.fNumberOfModules*sizeof(Int_t));
217   } else fModIndex = ssdadldc.fModIndex;
218
219   fEqIndex = ssdadldc.fEqIndex;
220   fNumberOfEvents = ssdadldc.fNumberOfEvents;
221   fLdcId = ssdadldc.fLdcId;
222   fRunId = ssdadldc.fRunId;
223   fPedestalThresholdFactor = ssdadldc.fPedestalThresholdFactor;
224   fCmThresholdFactor = ssdadldc.fCmThresholdFactor;
225   fZsDefault = ssdadldc.fZsDefault;
226   fOffsetDefault = ssdadldc.fOffsetDefault;
227   fZsMinimum = ssdadldc.fZsMinimum;
228   fMergeBCLists = ssdadldc.fMergeBCLists;
229   fZsFactor = ssdadldc.fZsFactor;
230   fALaddersOff = ssdadldc.fALaddersOff;
231   fCLaddersOff = ssdadldc.fCLaddersOff;
232   if (fBadChannelsList) delete fBadChannelsList;
233   fBadChannelsList = new AliITSBadChannelsSSDv2(*ssdadldc.fBadChannelsList);
234   if (fDDLModuleMap) delete [] fDDLModuleMap; 
235   if (ssdadldc.fDDLModuleMap) {
236     fDDLModuleMap = new (nothrow) Int_t [fgkNumberOfSSDDDLs * fgkNumberOfSSDModulesPerDdl];
237     if (fDDLModuleMap) memcpy(fDDLModuleMap, ssdadldc.fDDLModuleMap, fgkNumberOfSSDDDLs * fgkNumberOfSSDModulesPerDdl * sizeof(Int_t)); 
238   } else fDDLModuleMap = 0;
239
240   if (ssdadldc.fBadChannelsList) AliWarning("fBadChannelsList is not copied by assignment operator, use other methods to init it!");
241   if (ssdadldc.fDDLModuleMap) AliWarning("fDDLModuleMap is not copied by assignment operator, use other methods to init it!");
242   return *this;
243 }
244
245
246 //______________________________________________________________________________
247 AliITSHandleDaSSD::~AliITSHandleDaSSD()
248 {
249 // Default destructor 
250   if (fModules) 
251   {
252     for (Int_t i = 0; i < fNumberOfModules; i++)
253     { 
254       if (fModules[i]) delete fModules[i];
255     }
256     delete [] fModules;
257   }
258   if (fModIndex) delete [] fModIndex;
259   if (fBadChannelsList)  delete fBadChannelsList;
260   if (fDDLModuleMap) delete [] fDDLModuleMap;
261 }
262
263
264
265 //______________________________________________________________________________
266 void AliITSHandleDaSSD::Reset()
267 {
268 // Delete array of AliITSModuleDaSSD* objects. 
269   if (fModules) {
270     for (Int_t i = 0; i < fNumberOfModules; i++) if (fModules[i]) delete fModules[i];
271     delete [] fModules;
272     fModules = NULL;
273   }
274   if (fModIndex) { delete [] fModIndex; fModIndex = NULL; }
275 /*
276   if (fBadChannelsList) {
277     delete fBadChannelsList;
278     fBadChannelsList = NULL; 
279   }    
280   if (fDDLModuleMap) { delete [] fDDLModuleMap; fDDLModuleMap = NULL; }
281 */
282   fALaddersOff.Set(0);
283   fCLaddersOff.Set(0);
284   fRawDataFileName = NULL;
285   fModIndProcessed = fModIndRead = 0;
286   fNumberOfEvents = 0;
287   fLdcId = fRunId = 0;
288   fPedestalThresholdFactor = fgkPedestalThresholdFactor;
289   fCmThresholdFactor = fgkCmThresholdFactor;
290 }
291
292
293
294 //______________________________________________________________________________
295 Bool_t AliITSHandleDaSSD::Init(Char_t *rdfname)
296 {
297 // Read raw data file and set initial and configuration parameters
298   Long_t physeventind = 0, strn = 0, nofstripsev, nofstrips = 0;
299   Int_t  nofeqipmentev, nofeqipment = 0, eqn = 0; 
300   AliRawReaderDate  *rawreaderdate = NULL;
301   UChar_t *data = NULL;
302   Long_t datasize = 0, eqbelsize = 1;
303
304   rawreaderdate = new AliRawReaderDate(rdfname, 0);
305   if (!(rawreaderdate->GetAttributes() || rawreaderdate->GetEventId())) {
306     AliError(Form("AliITSHandleDaSSD: Error reading raw data file %s by RawReaderDate", rdfname));
307     MakeZombie();
308     return kFALSE;
309   }
310   if (rawreaderdate->NextEvent()) {
311     fRunId = rawreaderdate->GetRunNumber(); 
312     rawreaderdate->RewindEvents();
313   } else { MakeZombie(); return kFALSE; }
314   if (fModules) Reset();
315   //rawreaderdate->SelectEvents(-1);
316   rawreaderdate->Select("ITSSSD");  
317   nofstrips = 0;
318   while (rawreaderdate->NextEvent()) {
319     if ((rawreaderdate->GetType() != PHYSICS_EVENT) && (rawreaderdate->GetType() != CALIBRATION_EVENT)) continue;
320     nofstripsev = 0;
321     nofeqipmentev = 0;
322     while (rawreaderdate->ReadNextData(data)) {
323       fLdcId = rawreaderdate->GetLDCId();
324       nofeqipmentev += 1;
325       datasize = rawreaderdate->GetDataSize();
326       eqbelsize = rawreaderdate->GetEquipmentElementSize();
327       if ( datasize % eqbelsize ) {
328         AliError(Form("AliITSHandleDaSSD: Error Init(%s): event data size %ld is not an integer of equipment data size %ld", 
329                                     rdfname, datasize, eqbelsize));
330         MakeZombie();
331             return kFALSE;
332       }
333       nofstripsev += (Int_t) (datasize / eqbelsize);
334     }
335     if (physeventind++) {
336       if (nofstrips != nofstripsev) AliWarning(Form("AliITSHandleDaSSD: number of strips varies from event to event, ev = %ld, %ld", 
337                                                      physeventind, nofstripsev));
338       if (nofeqipment != nofeqipmentev) AliWarning("AliITSHandleDaSSD: number of DDLs varies from event to event");
339     }
340     nofstrips = nofstripsev;
341     nofeqipment = nofeqipmentev;
342     if (strn < nofstrips)  strn = nofstrips;
343     if (eqn < nofeqipment) eqn = nofeqipment;
344   }
345   delete rawreaderdate;
346   if ((physeventind > 0) && (strn > 0))
347   {
348     fNumberOfEvents = physeventind;
349     fRawDataFileName = rdfname;
350     fEqIndex.Set(eqn);
351     fEqIndex.Reset(-1);
352     fModIndex = new (nothrow) Int_t [fgkNumberOfSSDModulesPerDdl * eqn];
353     if (fModIndex) 
354       for (Int_t i = 0; i < fgkNumberOfSSDModulesPerDdl * eqn; i++) fModIndex[i] = -1; 
355     else AliWarning(Form("AliITSHandleDaSSD: Error Init(%s): Index array for %i modules was not created", 
356                                      rdfname, fgkNumberOfSSDModulesPerDdl * eqn));
357     if (SetNumberOfModules(fgkNumberOfSSDModulesPerDdl * eqn)) {
358       TString str = TString::Format("Max number of equipment: %d, max number of channels: %ld\n", eqn, strn);
359       DumpInitData(str.Data());
360       return kTRUE;
361     }  
362   }
363   MakeZombie();
364   return kFALSE;
365 }
366
367
368
369 //______________________________________________________________________________
370 AliITSModuleDaSSD* AliITSHandleDaSSD::GetModule (const UChar_t ddlID, const UChar_t ad, const UChar_t adc) const
371 {
372 // Retrieve AliITSModuleDaSSD object from the array
373    if (!fModules) return NULL;
374    for (Int_t i = 0; i < fNumberOfModules; i++) {
375      if (fModules[i]) {
376        if (    (fModules[i]->GetDdlId() == ddlID)
377             && (fModules[i]->GetAD() == ad)
378             && (fModules[i]->GetADC() == adc))
379             return fModules[i];
380      }      
381    }
382    return NULL;
383 }
384
385
386 Int_t AliITSHandleDaSSD::GetModuleIndex (const UChar_t ddlID, const UChar_t ad, const UChar_t adc) const
387 {
388 // Retrieve the position of AliITSModuleDaSSD object in the array
389    if (!fModules) return -1;
390    for (Int_t i = 0; i < fNumberOfModules; i++) {
391      if (fModules[i]) {
392        if (    (fModules[i]->GetDdlId() == ddlID)
393             && (fModules[i]->GetAD() == ad)
394             && (fModules[i]->GetADC() == adc))
395             return i;
396      }      
397    }
398    return -1;
399 }
400
401
402
403 //______________________________________________________________________________
404 AliITSChannelDaSSD* AliITSHandleDaSSD::GetStrip (const UChar_t ddlID, const UChar_t ad, const UChar_t adc, const UShort_t stripID) const
405 {
406 // Retrieve AliITSChannalDaSSD object from the array
407   for (Int_t modind = 0; modind < fNumberOfModules; modind++) {
408     if (    (fModules[modind]->GetDdlId() == ddlID)
409          && (fModules[modind]->GetAD() == ad)
410          && (fModules[modind]->GetADC() == adc)  ) 
411         {
412        return fModules[modind]->GetStrip(stripID);
413     }
414   }
415   AliError(Form("AliITSHandleDaSSD: Error GetStrip (%i, %i, %i, %i), strip not found, returns NULL!",
416                 ddlID, ad, adc, stripID));
417   return NULL;
418 }
419
420
421
422 //______________________________________________________________________________
423 Bool_t AliITSHandleDaSSD::SetModule(AliITSModuleDaSSD *const module, const Int_t index)
424
425 // Assign array element with AliITSModuleDaSSD object
426    if ((index < fNumberOfModules) && (index >= 0)) 
427      { 
428         if (fModules[index]) delete fModules[index];
429         fModules[index] = module;
430         return kTRUE;
431       }
432    else return kFALSE;                         
433 }
434
435
436
437 //______________________________________________________________________________
438 Bool_t AliITSHandleDaSSD::SetNumberOfModules (const Int_t numberofmodules)
439 {
440 // Allocates memory for AliITSModuleDaSSD objects
441   if (numberofmodules > fgkNumberOfSSDModules)
442     AliWarning(Form("AliITSHandleDaSSD: the number of modules %i you use exceeds the maximum %i for ALICE ITS SSD", 
443                      numberofmodules, fgkNumberOfSSDModules));
444   if (fModules) {
445     for (Int_t i = 0; i < fNumberOfModules; i++) if (fModules[i]) delete fModules[i];
446     delete [] fModules; 
447     fModules = NULL;
448   }
449   fModules = new (nothrow) AliITSModuleDaSSD* [numberofmodules];
450   if (fModules) {
451     fNumberOfModules = numberofmodules;
452     memset(fModules, 0, sizeof(AliITSModuleDaSSD*) * numberofmodules);
453     return kTRUE;
454   } else {
455      AliError(Form("AliITSHandleDaSSD: Error allocating memory for %i AliITSModulesDaSSD* objects!", numberofmodules));
456      fNumberOfModules = 0;
457      fModules = NULL;
458   }
459   return kFALSE;
460 }
461
462
463
464 //______________________________________________________________________________
465 Bool_t AliITSHandleDaSSD::ReadStaticBadChannelsMap(const Char_t *filename)
466 {
467 // Reads Static Bad Channels Map from the file
468   TFile *bcfile;
469   if (!filename) {
470     AliWarning("No file name is specified for Static Bad Channels Map!");
471     return kFALSE;
472   } 
473   bcfile = new TFile(filename, "READ");
474   if (bcfile->IsZombie()) {
475     AliWarning(Form("Error reading file %s with Static Bad Channels Map!", filename));
476     return kFALSE;
477   }
478   bcfile->GetObject("AliITSBadChannelsSSDv2;1", fBadChannelsList);
479   if (!fBadChannelsList) {
480     AliWarning("Error fBadChannelsList == NULL!");
481     bcfile->Close();
482     delete bcfile;
483     return kFALSE;
484   }
485   bcfile->Close();
486   delete bcfile;
487   return kTRUE;
488 }
489
490
491
492 Bool_t AliITSHandleDaSSD::ReadDDLModuleMap(const Char_t *filename)
493 {
494 // Reads the SSD DDL Map from the file
495   ifstream             ddlmfile;
496   AliRawReaderDate    *rwr = NULL;
497   AliITSRawStreamSSD  *rsm = NULL;
498   void                *event = NULL;
499   if (fDDLModuleMap) { delete [] fDDLModuleMap; fDDLModuleMap = NULL;}
500   fDDLModuleMap = new (nothrow) Int_t [fgkNumberOfSSDDDLs * fgkNumberOfSSDModulesPerDdl];
501   if (!fDDLModuleMap) {
502     AliWarning("Error allocation memory for DDL Map!");
503     return kFALSE;
504   }    
505   if (!filename) {
506     AliWarning("No file name is specified for SSD DDL Map, using the one from AliITSRawStreamSSD!");
507     rwr = new AliRawReaderDate(event);
508     rsm = new AliITSRawStreamSSD(rwr);
509     rsm->Setv11HybridDDLMapping();
510     for (Int_t ddli = 0; ddli < fgkNumberOfSSDDDLs; ddli++)
511       for (Int_t mi = 0; mi < fgkNumberOfSSDModulesPerDdl; mi++)
512         fDDLModuleMap[(ddli * fgkNumberOfSSDModulesPerDdl + mi)] = rsm->GetModuleNumber(ddli, mi);
513     if (rsm) delete rsm;
514     if (rwr) delete rwr;        
515     return kTRUE;
516   } 
517   ddlmfile.open(filename, ios::in);
518   if (!ddlmfile.is_open()) {
519     AliWarning(Form("Error reading file %s with SSD DDL Map!", filename));
520     if (fDDLModuleMap) { delete [] fDDLModuleMap; fDDLModuleMap = NULL;}
521     return kFALSE;
522   }
523   Int_t ind = 0;
524   while((!ddlmfile.eof()) && (ind < (fgkNumberOfSSDDDLs * fgkNumberOfSSDModulesPerDdl))) {
525     ddlmfile >> fDDLModuleMap[ind++];
526     if (ddlmfile.fail()) AliError(Form("Error extracting number from the DDL map file %s, ind: %d ", filename, ind));
527   }
528   if (ind != (fgkNumberOfSSDDDLs * fgkNumberOfSSDModulesPerDdl))
529     AliWarning(Form("Only %i (< %i) entries were read from DDL Map!", ind, (fgkNumberOfSSDDDLs * fgkNumberOfSSDModulesPerDdl)));
530   ddlmfile.close();
531   return kTRUE;
532 }
533
534
535
536 //______________________________________________________________________________
537 Int_t AliITSHandleDaSSD::ReadCalibrationDataFile (char* fileName, const Long_t eventsnumber)
538 {
539 // Reads raw data from file
540   if (!Init(fileName)){
541     AliError("AliITSHandleDaSSD: Error ReadCalibrationDataFile");
542     return kFALSE;
543   }
544   fNumberOfEvents = eventsnumber;
545   return ReadModuleRawData (fNumberOfModules);  
546 }
547
548
549
550 //______________________________________________________________________________
551 Int_t AliITSHandleDaSSD::ReadModuleRawData (const Int_t modulesnumber)
552 {
553 // Reads raw data from file
554   AliRawReader        *rawreaderdate = NULL;
555   AliITSRawStreamSSD  *stream = NULL;
556   AliITSModuleDaSSD   *module;
557   AliITSChannelDaSSD  *strip;
558   Long_t            eventind = 0;
559   Int_t             nofeqipment, eqind;
560   Short_t           equipid, prequipid;
561   Short_t           modind;
562   if (!(rawreaderdate = new AliRawReaderDate(fRawDataFileName, 0))) return 0;
563   if (!fModules) {
564     AliError("AliITSHandleDaSSD: Error ReadModuleRawData: no structure was allocated for data");
565     return 0;
566   }
567   if (!fDDLModuleMap) if (!ReadDDLModuleMap()) AliWarning("DDL map is not defined, ModuleID will be set to 0!");
568   stream = new AliITSRawStreamSSD(rawreaderdate);
569   stream->Setv11HybridDDLMapping();
570   //rawreaderdate->SelectEvents(-1);
571   rawreaderdate->Select("ITSSSD");  
572   modind = 0;
573   nofeqipment = 0;
574   while (rawreaderdate->NextEvent()) {
575     if ((rawreaderdate->GetType() != PHYSICS_EVENT) && (rawreaderdate->GetType() != CALIBRATION_EVENT)) continue;
576     prequipid = -1;
577     eqind = -1;
578     while (stream->Next()) {
579       equipid = rawreaderdate->GetEquipmentId(); 
580       if ((equipid != prequipid)) {
581         if ((eqind = GetEqIndex(equipid)) < 0) { fEqIndex.AddAt(equipid, nofeqipment); eqind = nofeqipment++; }
582         prequipid = equipid;
583       }
584       Int_t     equiptype  = rawreaderdate->GetEquipmentType();
585       UChar_t   ddlID      = (UChar_t)rawreaderdate->GetDDLID();
586       UChar_t   ad      = stream->GetAD();
587       UChar_t   adc     = stream->GetADC();
588       UShort_t  stripID = stream->GetSideFlag() ? AliITSChannelDaSSD::GetMaxStripIdConst() - stream->GetStrip() : stream->GetStrip();
589       Short_t   signal  = stream->GetSignal();
590
591       Int_t indpos = (eqind * fgkNumberOfSSDModulesPerDdl)
592                    + ((ad - 1) * fgkNumberOfSSDModulesPerSlot) + (adc < 6 ? adc : (adc - 2));
593       Int_t modpos = fModIndex[indpos];
594       if (((modpos > 0) && (modpos < fModIndRead)) || ((modpos < 0) && (modind == modulesnumber))) continue;
595       if ((modpos < 0) && (modind < modulesnumber)) {
596         module = new AliITSModuleDaSSD(AliITSModuleDaSSD::GetStripsPerModuleConst());
597         Int_t mddli;
598         if (fDDLModuleMap) mddli = RetrieveModuleId(ddlID, ad, adc);
599         else  mddli = 0;
600         if (!module->SetModuleIdData (ddlID, ad, adc, mddli)) return 0;
601         module->SetModuleRorcId (equipid, equiptype);
602         modpos = fModIndRead + modind;
603         modind += 1;
604         fModules[modpos] = module;
605         fModIndex[indpos] = modpos;
606       } 
607       if (stripID < AliITSModuleDaSSD::GetStripsPerModuleConst()) {
608         if (!(strip = fModules[modpos]->GetStrip(stripID))) {
609           strip = new AliITSChannelDaSSD(stripID, fNumberOfEvents);
610           fModules[modpos]->SetStrip(strip, stripID);
611         }
612         strip->SetSignal(eventind, signal);
613           } else  {
614         if (!(fModules[modpos]->GetCMFerom())) {
615           fModules[modpos]->AllocateCMFeromArray();
616           fModules[modpos]->SetCMFeromEventsNumber(fNumberOfEvents);
617                 }
618             fModules[modpos]->SetCMFerom(signal, (stripID - AliITSModuleDaSSD::GetStripsPerModuleConst()), eventind);
619           }
620     }
621     if (++eventind > fNumberOfEvents) break;
622   }
623   delete stream;
624   delete rawreaderdate;
625   if (modind) cout << "The memory was allocated for " <<  modind << " modules." << endl;
626   fModIndRead += modind;
627   if (modind < modulesnumber) RelocateModules();
628   return modind;
629 }
630
631
632
633 //______________________________________________________________________________
634 Bool_t AliITSHandleDaSSD::RelocateModules()
635 {
636 // Relocate memory for AliITSModuleDaSSD object array
637   Int_t         nm = 0;
638   AliITSModuleDaSSD **marray = NULL;
639   for (Int_t modind = 0; modind < fNumberOfModules; modind++)
640     if (fModules[modind]) nm += 1;
641   if (nm == fNumberOfModules) return kTRUE;
642   marray = new (nothrow) AliITSModuleDaSSD* [nm];
643   if (!marray) {
644     AliError(Form("AliITSHandleDaSSD: Error relocating memory for %i AliITSModuleDaSSD* objects!", nm));
645     return kFALSE;
646   }
647   nm = 0;
648   for (Int_t modind = 0; modind < fNumberOfModules; modind++)  
649     if (fModules[modind]) marray[nm++] = fModules[modind];
650   delete [] fModules;
651   fModules = marray;
652   fNumberOfModules = fModIndRead = nm;
653   return kTRUE;
654 }
655
656
657
658 //______________________________________________________________________________
659 Bool_t AliITSHandleDaSSD::AddFeromCm(const AliITSModuleDaSSD *const module)
660 {
661 // Restore the original signal value adding CM calculated and subtracted in ferom
662   AliITSChannelDaSSD *strip;
663   Short_t            *signal, *cmferom;
664
665   if (!module) return kFALSE;
666   if (!module->GetCMFerom()) return kTRUE;
667   for (Int_t chipind = 0; chipind < AliITSModuleDaSSD::GetChipsPerModuleConst(); chipind++) {
668     if (!(cmferom = module->GetCMFerom(chipind))) {
669       AliWarning(Form("AliITSHandleDaSSD: There is no Ferom CM values for chip %i, module %i!", chipind, module->GetModuleId()));
670       continue;
671     }
672     for (Int_t strind = (chipind * AliITSModuleDaSSD::GetStripsPerChip()); 
673                strind < ((chipind + 1) * AliITSModuleDaSSD::GetStripsPerChip()); strind++) {
674       if (!(strip = module->GetStrip(strind))) continue;
675       if (!(signal = strip->GetSignal())) continue;
676 //      if (strip->GetEventsNumber() != module->GetEventsNumber()) return kFALSE;
677       Long_t ovev = 0;
678       for (Long_t ev = 0; ev < strip->GetEventsNumber(); ev++) {
679         if (SignalOutOfRange(signal[ev]) || SignalOutOfRange(cmferom[ev])) ovev += 1;
680         else {
681           Short_t signal1 = signal[ev] + cmferom[ev];
682           strip->SetSignal(ev, signal1);
683             }  
684       } 
685     } 
686   }  
687   return kTRUE;
688 }
689
690
691
692 //______________________________________________________________________________
693 Bool_t AliITSHandleDaSSD::CalculatePedestal(const AliITSModuleDaSSD *const module)
694 {
695 // Calculates Pedestal
696   AliITSChannelDaSSD *strip;
697   Double_t            pedestal, noise;
698   Short_t            *signal;
699   Long_t              ovev, ev, n;
700   if (!module) return kFALSE;
701   for (Int_t strind = 0; strind < module->GetNumberOfStrips(); strind++) {
702     if (!(strip = module->GetStrip(strind))) continue;
703     if (!(signal = strip->GetSignal())) {
704       AliError(Form("AliITSHandleDaSSD: Error CalculatePedestal(): there are no events data for module[%i] strip[%i]->GetSignal()",
705                      module->GetModuleId(), strind));
706       continue; 
707     }
708 //************* pedestal first pass ****************
709     pedestal = 0.0L;
710     ovev = 0l;
711     for (ev = 0; ev < strip->GetEventsNumber(); ev++)
712       if (SignalOutOfRange(signal[ev])) ovev += 1;
713       else pedestal = ((ev - ovev)) ? pedestal + (signal[ev] - pedestal) / static_cast<Double_t>(ev - ovev + 1) : signal[ev];
714     if (ev == ovev) pedestal = AliITSChannelDaSSD::GetUndefinedValue();
715     strip->SetPedestal(static_cast<Float_t>(pedestal)); 
716 //************* noise *******************************
717     Double_t nsum = 0.0L;
718     ovev = 0l;
719     for (ev = 0; ev < strip->GetEventsNumber(); ev++) {
720       if (SignalOutOfRange(signal[ev])) ovev += 1;
721       else nsum += pow((signal[ev] - strip->GetPedestal()), 2);
722     } 
723     if ((n = strip->GetEventsNumber() - ovev - 1) > 0) noise =  TMath::Sqrt(nsum / (Double_t)(n));
724     else  noise = AliITSChannelDaSSD::GetUndefinedValue();
725     strip->SetNoise(static_cast<Float_t>(noise));
726 //************* pedestal second pass ****************
727     pedestal = 0.0L;
728     ovev = 0l;
729     for (ev = 0; ev < strip->GetEventsNumber(); ev++)
730       if (   SignalOutOfRange(signal[ev]) 
731           || TMath::Abs(signal[ev] - strip->GetPedestal()) > (fPedestalThresholdFactor * strip->GetNoise())) ovev += 1;
732       else pedestal = ((ev - ovev)) ? pedestal + (signal[ev] - pedestal) / static_cast<Double_t>(ev - ovev + 1) : signal[ev];
733     if (ev == ovev) pedestal = AliITSChannelDaSSD::GetUndefinedValue();
734     strip->SetPedestal(static_cast<Float_t>(pedestal)); 
735     strip->SetOverflowNumber(ovev);     
736   }
737   return kTRUE;
738 }
739
740
741 //______________________________________________________________________________
742 Bool_t AliITSHandleDaSSD::CalculateNoise(const AliITSModuleDaSSD *const module)
743 {
744 // Calculates Noise
745   AliITSChannelDaSSD *strip;
746   Short_t    *signal;
747   Float_t     noise;
748   Long_t      ovev, n;
749   if (!module) return kFALSE;
750   for (Int_t strind = 0; strind < module->GetNumberOfStrips(); strind++) {
751     if (!(strip = module->GetStrip(strind))) continue;
752     if (!(signal = strip->GetSignal())) {
753       strip->SetNoise(AliITSChannelDaSSD::GetUndefinedValue());
754       AliError(Form("AliITSHandleDaSSD: Error CalculateNoise(): there are no events data for module[%i] strip[%i]->GetSignal()",
755                      module->GetModuleId(), strind));
756       continue;
757     }
758     Double_t nsum = 0.0L;
759     ovev = 0l;
760     for (Long_t ev = 0; ev < strip->GetEventsNumber(); ev++) {
761       if (SignalOutOfRange(signal[ev])) ovev += 1;
762       else nsum += pow((signal[ev] - strip->GetPedestal()), 2);
763     } 
764     if ((n = strip->GetEventsNumber() - ovev - 1) > 0) noise =  static_cast<Float_t>(TMath::Sqrt(nsum / (Float_t)(n)));
765     else  noise = AliITSChannelDaSSD::GetUndefinedValue();
766     strip->SetNoise(noise);
767   }
768   return kTRUE;
769 }
770
771
772
773 //______________________________________________________________________________
774 Bool_t AliITSHandleDaSSD::CalculateNoiseCM(AliITSModuleDaSSD *const module)
775 {
776 // Calculates Noise with CM correction
777   AliITSChannelDaSSD  *strip = NULL;
778   Short_t     *signal;
779   Float_t      noise;
780   Long_t       ovev, n;
781   if (!CalculateCM(module)) { 
782     AliError("Error: AliITSHandleDaSSD::CalculateCM() returned kFALSE");
783     return kFALSE;
784   }  
785   for (Int_t strind = 0; strind < module->GetNumberOfStrips(); strind++) {
786     if (!(strip = module->GetStrip(strind))) continue; //return kFALSE;
787     if (!(signal = strip->GetSignal())) {
788       strip->SetNoiseCM(AliITSChannelDaSSD::GetUndefinedValue());
789       AliError(Form("AliITSHandleDaSSD: Error CalculateNoiseCM(): there are no events data for module[%i] strip[%i]->GetSignal()", 
790                      module->GetModuleId(), strind));
791       continue; //return kFALSE;
792     }
793     Int_t chipind = strind / AliITSModuleDaSSD::GetStripsPerChip();
794     Double_t nsum = 0.0L;
795     ovev = 0l;
796     for (Long_t ev = 0; ev < strip->GetEventsNumber(); ev++) {
797       if (SignalOutOfRange(signal[ev])) ovev += 1;
798       else nsum += pow((signal[ev] - strip->GetPedestal() - module->GetCM(chipind, ev)), 2);
799     } 
800     if ((n = strip->GetEventsNumber() - ovev - 1) > 0) noise = static_cast<Float_t>(TMath::Sqrt(nsum / (Double_t)(n)));
801     else  noise = AliITSChannelDaSSD::GetUndefinedValue();
802     strip->SetNoiseCM(noise);
803   }
804   return kTRUE;
805 }
806
807
808
809 //______________________________________________________________________________
810 Bool_t AliITSHandleDaSSD::CalculateCM(AliITSModuleDaSSD *const module)
811 {
812 // Calculates CM
813   AliITSChannelDaSSD  *strip = NULL;
814   Short_t             *signal;
815   Long_t               ovstr, n;
816   Int_t                stripind;
817   module->SetNumberOfChips(AliITSModuleDaSSD::GetChipsPerModuleConst());
818   for (Int_t chipind = 0; chipind < module->GetNumberOfChips(); chipind++) {
819     stripind = chipind * module->GetStripsPerChip();
820     module->GetCM()[chipind].Set(fNumberOfEvents);
821     module->GetCM()[chipind].Reset(0.0f);
822     for (Long_t ev = 0; ev < fNumberOfEvents; ev++) {
823     // calculate firs approximation of CM.
824       Double_t cm0 = 0.0L;
825       ovstr = 0l;
826       for (Int_t strind = stripind; strind < (stripind + AliITSModuleDaSSD::GetStripsPerChip()); strind++) {
827         if (!(strip = module->GetStrip(strind))) continue; //return kFALSE; 
828         if (!(signal = strip->GetSignal())) {
829           AliError(Form("AliITSHandleDaSSD: Error CalculateCM: there are no events data for module[%i] strip[%i]->GetSignal()", 
830                         module->GetModuleId(), strind));
831           return kFALSE;
832         }
833         if ((SignalOutOfRange(signal[ev])) || (strip->GetPedestal() == AliITSChannelDaSSD::GetUndefinedValue())) ovstr += 1;
834         else cm0 += (signal[ev] - strip->GetPedestal());
835       }
836       if ((n = AliITSModuleDaSSD::GetStripsPerChip() - ovstr)) cm0 /= (Float_t)(n);
837       else { module->SetCM(0.0f, chipind, ev); continue; }
838     // calculate avarage (cm - (signal - pedestal)) over the chip
839       Double_t cmsigma = 0.0L;
840       ovstr = 0l;
841       for (Int_t strind = stripind; strind < (stripind + AliITSModuleDaSSD::GetStripsPerChip()); strind++) {
842         if (!(strip = module->GetStrip(strind))) continue;
843         if (!(signal = strip->GetSignal())) {
844           AliError(Form("AliITSHandleDaSSD: Error CalculateCM: there are no events data for module[%i] strip[%i]->GetSignal()\n",
845                          module->GetModuleId(), strind));
846           return kFALSE;
847         }
848         if ((SignalOutOfRange(signal[ev])) || (strip->GetPedestal() == AliITSChannelDaSSD::GetUndefinedValue())) ovstr += 1;
849         else cmsigma += pow((cm0 - (signal[ev] - strip->GetPedestal())), 2);
850       }
851       if ((n = AliITSModuleDaSSD::GetStripsPerChip() - ovstr)) cmsigma = TMath::Sqrt(cmsigma / (Float_t)(n));
852       else { module->SetCM(0.0f, chipind, ev); continue; }
853    // calculate cm with threshold
854       Double_t cmsum = 0.0L;
855       ovstr = 0l;
856       for (Int_t strind = stripind; strind < (stripind + AliITSModuleDaSSD::GetStripsPerChip()); strind++) {
857         if (!(strip = module->GetStrip(strind))) continue;
858         signal = strip->GetSignal();
859         if ( (SignalOutOfRange(signal[ev])) || (strip->GetPedestal() == AliITSChannelDaSSD::GetUndefinedValue()) 
860                || (TMath::Abs(cm0 - (signal[ev] - strip->GetPedestal())) > (fCmThresholdFactor * cmsigma)) ) ovstr += 1;
861         else cmsum += (signal[ev] - strip->GetPedestal());
862       }
863       if ((n = AliITSModuleDaSSD::GetStripsPerChip() - ovstr)) cmsum /= (Float_t)(n);
864       else cmsum = 0.0L;
865       if (!(module->SetCM(cmsum, chipind, ev))) 
866         AliError(Form("AliITSHandleDaSSD: Error, module->SetCM(...) returned kFALSE module:chip:event : [%d]:[%d]:[%ld]\n",
867                            module->GetModuleId(), chipind, ev));
868     } 
869   }
870   return kTRUE; 
871 }
872
873
874 //______________________________________________________________________________
875 Bool_t AliITSHandleDaSSD::ProcessRawData(const Int_t nmread, const Bool_t usewelford)
876 {
877 // Performs calculation of calibration parameters (pedestal, noise, ...) 
878   Int_t nm = 0;
879   if (nmread <= 0) return kFALSE;
880   if (!fModules) return kFALSE;
881   while ((nm = ReadModuleRawData(nmread)) > 0) {
882     cout << "Processing next " << nm << " modules;" << endl;  
883     for (Int_t modind = fModIndProcessed; modind < fModIndRead; modind++) {
884       if (!fModules[modind]) {
885         AliError(Form("AliITSHandleDaSSD: Error ProcessRawData(): No AliITSModuleDaSSD object with index %i is allocated in AliITSHandleDaSSD\n",
886                        modind));
887         return kFALSE;
888       }
889       AddFeromCm(fModules[modind]);
890       if (usewelford) {
891         CalculatePedNoiseW(fModules[modind]);
892         CalculateNoiseCMW(fModules[modind]);
893       } else {
894         CalculatePedestal(fModules[modind]);
895         CalculateNoise(fModules[modind]);
896         CalculateNoiseCM(fModules[modind]);
897       }
898     }
899     DeleteSignal();
900     DeleteCM();
901     DeleteCMFerom();
902     fModIndProcessed = fModIndRead;
903     cout << fModIndProcessed << " - done" << endl;
904     if (nm < nmread ) break;
905   }
906   return kTRUE;  
907 }
908
909
910 //______________________________________________________________________________
911 Short_t AliITSHandleDaSSD::RetrieveModuleId(const UChar_t ddlID, const UChar_t ad, const UChar_t adc) const
912 {
913 // Retrieve ModuleId from the DDL map which is defined in AliITSRawStreamSSD class
914   if (!fDDLModuleMap) {
915     AliError("Error DDLMap is not initialized, return 0!");
916         return 0;
917   }
918   Int_t mddli = ((ad - 1) * fgkNumberOfSSDModulesPerSlot) + (adc < 6 ? adc : (adc - 2));
919   if ((ddlID < fgkNumberOfSSDDDLs) && (mddli < fgkNumberOfSSDModulesPerDdl)) {
920     mddli = fDDLModuleMap[ddlID * fgkNumberOfSSDModulesPerDdl + mddli];
921   }  
922   else {
923     AliWarning(Form("Module index  = %d or ddlID = %d is out of range 0 is rturned", ddlID, mddli));
924     mddli = 0;
925   }
926   if (mddli > SHRT_MAX) return SHRT_MAX;
927   else return (Short_t)mddli;
928 }
929
930
931
932 //______________________________________________________________________________
933 AliITSNoiseSSDv2* AliITSHandleDaSSD::GetCalibrationOCDBNoise() const
934 {
935 // Fill in the array for OCDB 
936   AliITSNoiseSSDv2         *ldcn = NULL;
937   AliITSModuleDaSSD      *module = NULL;
938   AliITSChannelDaSSD     *strip = NULL; 
939   if (!fModules) return NULL;
940   ldcn = new AliITSNoiseSSDv2;
941   if (!ldcn) {
942     AliError("Error allocation mamory for AliITSBadChannelsSSDv2 object, return NULL!");
943     return NULL;
944   }
945   for (Int_t i = 0; i < fNumberOfModules; i++) {
946     if (!(module = fModules[i])) continue;
947     if (module->GetModuleId() < fgkMinSSDModuleId) continue;
948     for (Int_t strind = 0; strind < module->GetNumberOfStrips(); strind++) {
949       if (!(strip = module->GetStrip(strind))) continue;
950       Short_t modid = module->GetModuleId() - fgkMinSSDModuleId;
951       if (strip->GetStripId() < AliITSModuleDaSSD::GetPNStripsPerModule() ) 
952         ldcn->AddNoiseP(modid, strip->GetStripId(), strip->GetNoiseCM());
953       else
954         ldcn->AddNoiseN(modid, (AliITSChannelDaSSD::GetMaxStripIdConst() - strip->GetStripId()), strip->GetNoiseCM());
955     }
956   }
957   return ldcn;
958 }
959
960
961 //______________________________________________________________________________
962 AliITSBadChannelsSSDv2* AliITSHandleDaSSD::GetCalibrationBadChannels() const
963 {
964 // Fill in the TObjArray with the list of bad channels 
965   AliITSBadChannelsSSDv2   *ldcbc = NULL;
966   AliITSModuleDaSSD      *module = NULL;
967   AliITSChannelDaSSD     *strip = NULL; 
968   if (!fModules) return NULL;
969   ldcbc = new AliITSBadChannelsSSDv2;
970   if (!ldcbc) {
971     AliError("Error allocation mamory for AliITSBadChannelsSSDv2 object, return NULL!");
972     return NULL;
973   }
974   for (Int_t i = 0; i < fNumberOfModules; i++) {
975     if (!(module = fModules[i])) continue;
976     if (module->GetModuleId() < fgkMinSSDModuleId) continue;
977     for (Int_t strind = 0; strind < module->GetNumberOfStrips(); strind++) {
978       if (!(strip = module->GetStrip(strind))) continue;
979       Short_t modid = module->GetModuleId() - fgkMinSSDModuleId;
980       if (strip->GetStripId() < AliITSModuleDaSSD::GetPNStripsPerModule() )
981         ldcbc->AddBadChannelP(modid, strip->GetStripId(), EvaluateIfChannelIsBad(module, strip->GetStripId()));
982       else 
983         ldcbc->AddBadChannelN(modid, (AliITSChannelDaSSD::GetMaxStripIdConst() - strip->GetStripId()), 
984                                      EvaluateIfChannelIsBad(module, strip->GetStripId()));
985     }
986   }
987   return ldcbc;
988 }
989
990
991
992 //______________________________________________________________________________
993 Bool_t AliITSHandleDaSSD::SaveCalibrationSSDLDC(Char_t*& dafname)
994 {
995 // Save Calibration data locally
996   AliITSBadChannelsSSDv2   *ldcbc = NULL;
997   AliITSPedestalSSDv2      *ldcp = NULL;
998   AliITSNoiseSSDv2         *ldcn = NULL;
999   AliITSModuleDaSSD      *module = NULL;
1000   AliITSChannelDaSSD     *strip = NULL; 
1001   Char_t         *tmpfname;
1002   TString         dadatafilename("");
1003   if (!fModules) return kFALSE;
1004   ldcn = new AliITSNoiseSSDv2;
1005   ldcp = new AliITSPedestalSSDv2;
1006   ldcbc = new AliITSBadChannelsSSDv2;
1007   if ((!ldcn) || (!ldcp) || (!ldcp)) {
1008     AliError("Error allocation mamory for calibration objects, return kFALSE!");
1009     return kFALSE;
1010   }
1011   for (Int_t i = 0; i < fNumberOfModules; i++) {
1012     if (!(module = fModules[i])) continue;
1013     if (module->GetModuleId() < fgkMinSSDModuleId) continue;
1014     for (Int_t strind = 0; strind < module->GetNumberOfStrips(); strind++) {
1015       if (!(strip = module->GetStrip(strind))) continue;
1016       Short_t modid = module->GetModuleId() - fgkMinSSDModuleId;
1017       if (strip->GetStripId() < AliITSModuleDaSSD::GetPNStripsPerModule() ) {
1018         ldcn->AddNoiseP(modid, strip->GetStripId(), strip->GetNoiseCM());
1019         ldcp->AddPedestalP(modid, strip->GetStripId(), strip->GetPedestal());
1020         ldcbc->AddBadChannelP(modid, strip->GetStripId(), EvaluateIfChannelIsBad(module, strip->GetStripId()));
1021       } else {
1022         ldcn->AddNoiseN(modid, (AliITSChannelDaSSD::GetMaxStripIdConst() - strip->GetStripId()), strip->GetNoiseCM());
1023         ldcp->AddPedestalN(modid, (AliITSChannelDaSSD::GetMaxStripIdConst() - strip->GetStripId()), strip->GetPedestal()); 
1024         ldcbc->AddBadChannelN(modid, (AliITSChannelDaSSD::GetMaxStripIdConst() - strip->GetStripId()), 
1025                                      EvaluateIfChannelIsBad(module, strip->GetStripId()));
1026       }
1027     }
1028   }
1029   if (dafname) dadatafilename.Form("%s/", dafname);
1030   dadatafilename += TString::Format("ITSSSDda_%i.root", fLdcId);
1031   tmpfname = new Char_t[dadatafilename.Length()+1];
1032   Int_t sz = dadatafilename.Sizeof();
1033   dafname = strncpy(tmpfname, dadatafilename.Data(),sz);
1034   TFile *fileRun = new TFile (dadatafilename.Data(),"RECREATE");
1035   if (fileRun->IsZombie()) {
1036     AliError(Form("AliITSHandleDaSSD: SaveCalibrationSSDLDC() error open file %s", dadatafilename.Data()));
1037     ldcn->Delete();
1038     delete fileRun;
1039     delete ldcn;
1040     delete ldcp;
1041     delete ldcbc;
1042     return kFALSE;
1043   }
1044   fileRun->WriteTObject(ldcn);
1045   fileRun->WriteTObject(ldcp);
1046   if (fBadChannelsList) 
1047     if (fMergeBCLists) {
1048       MergeBadChannels(ldcbc);
1049       fileRun->WriteTObject(ldcbc);
1050     } else fileRun->WriteTObject(fBadChannelsList);
1051   else fileRun->WriteTObject(ldcbc);
1052   fileRun->Close();
1053   delete fileRun;
1054   delete ldcn;
1055   delete ldcp;
1056   delete ldcbc;
1057   return kTRUE;
1058 }
1059
1060
1061 //______________________________________________________________________________
1062 Int_t AliITSHandleDaSSD::MergeBadChannels(AliITSBadChannelsSSDv2*&  bcl) const
1063 {
1064 // Merges the statick bad channels list with bad channels got upon calibration
1065   AliITSModuleDaSSD     *module = 0;
1066   Int_t                  nmpch = 0, nmnch = 0, ngpch = 0, ngnch = 0;
1067   if (!fBadChannelsList || !bcl) {
1068     AliWarning("Either fBadChannelsList == NULL or bad_channels_list == NULL, there is nothing to merge!");
1069         return -1;
1070   }
1071   for (Int_t modind = 0; modind < GetNumberOfModules(); modind++) {
1072     if (!(module = fModules[modind])) continue;
1073     if (module->GetModuleId() < fgkMinSSDModuleId) continue;
1074     Short_t modid = module->GetModuleId() - fgkMinSSDModuleId;
1075     for (Int_t strind = 0; strind < AliITSModuleDaSSD::GetPNStripsPerModule(); strind++) {
1076       if ( (!(fBadChannelsList->GetBadChannelP(modid, strind) & fgkBadChannelMask)) 
1077           && (bcl->GetBadChannelP(modid, strind) & fgkBadChannelMask) ) 
1078         ngpch++;
1079       if ( (!(fBadChannelsList->GetBadChannelN(modid, strind) & fgkBadChannelMask)) 
1080           && (bcl->GetBadChannelN(modid, strind) & fgkBadChannelMask) ) 
1081         ngnch++;
1082       if ( (!(bcl->GetBadChannelP(modid, strind) & fgkBadChannelMask)) 
1083           && (fBadChannelsList->GetBadChannelP(modid, strind) & fgkBadChannelMask) ) {
1084         bcl->AddBadChannelP(modid, strind, fBadChannelsList->GetBadChannelP(modid, strind));
1085         nmpch++;  
1086       }    
1087       if ( (!(bcl->GetBadChannelN(modid, strind) & fgkBadChannelMask)) 
1088           && (fBadChannelsList->GetBadChannelN(modid, strind) & fgkBadChannelMask) ) {
1089         bcl->AddBadChannelN(modid, strind, fBadChannelsList->GetBadChannelN(modid, strind));
1090         nmnch++;  
1091       }
1092     }     
1093   }
1094   AliInfo(Form("Static bad, dynamic good: P%d,  N%d", nmpch, nmnch));
1095   AliInfo(Form("Static good, dynamic bad: P%d,  N%d", ngpch, ngnch));
1096   return (nmnch + nmpch);
1097 }
1098
1099
1100
1101 //______________________________________________________________________________
1102 Bool_t AliITSHandleDaSSD::DumpModInfo(const Float_t meannosethreshold) const
1103 {
1104 // Dump calibration parameters
1105   AliITSModuleDaSSD    *mod;
1106   AliITSChannelDaSSD   *strip;
1107   if (!fModules) {
1108     cout << "SSDDALDC::DumpModInfo():  Error, no modules are allocated!" << endl;
1109     return kFALSE;
1110   }  
1111   cout << "Modules with MeanNoise > " << meannosethreshold << endl;
1112   for (Int_t i = 0; i < fNumberOfModules; i++) {
1113     if (!(mod = fModules[i])) continue;
1114     Double_t  maxnoise = 0.0L, meannoise = 0.0L, meanovf = 0.0L;
1115     Float_t   maxped = 0.0f;
1116     Int_t     maxstrind = 0, novfstr = 0, maxovf = 0; 
1117     for (Int_t strind = 0; strind < mod->GetNumberOfStrips(); strind++) {
1118       if (!(strip = mod->GetStrip(strind))) {novfstr++;  continue; }
1119       if (strip->GetNoiseCM() >= AliITSChannelDaSSD::GetUndefinedValue() ) {novfstr++;  continue; }
1120       if (maxnoise < strip->GetNoiseCM()) { 
1121         maxnoise = strip->GetNoiseCM();
1122         maxstrind = strind;
1123       } 
1124       meannoise = (strind - novfstr) ? meannoise + (strip->GetNoiseCM() - meannoise) / static_cast<Double_t>(strind - novfstr + 1) 
1125                                     : strip->GetNoiseCM();
1126       if (TMath::Abs(maxped) < TMath::Abs(strip->GetPedestal())) maxped = strip->GetPedestal();
1127       meanovf = (strind - novfstr) ? meanovf + (strip->GetOverflowNumber() - meanovf) / static_cast<Double_t>(strind - novfstr + 1) 
1128                                     : strip->GetOverflowNumber();
1129       if (strip->GetOverflowNumber() > maxovf) maxovf = strip->GetOverflowNumber();
1130     } 
1131     if (meannoise > meannosethreshold)
1132       cout << "Mod: " << i << ";  DDl: " << (int)mod->GetDdlId() << ";  AD: " << (int)mod->GetAD()  
1133                            << ";  ADC: " << (int)mod->GetADC() << "; MaxPed = " << maxped
1134                            << ";  MeanNoise = " << meannoise << "; MaxNoise = " << maxnoise << "; MaxNoiseStrip = " << maxstrind 
1135                            << ";  NOfStrips = " << (mod->GetNumberOfStrips() - novfstr) << endl;
1136         if (maxovf > 10) cout << "Max number of events with overflow :  " << maxovf << ";  mean : " << meanovf << endl;
1137   }
1138   return kTRUE;
1139 }
1140
1141
1142
1143 //______________________________________________________________________________
1144 Bool_t AliITSHandleDaSSD::PrintModCalibrationData(const UChar_t ddlID, const UChar_t ad, const UChar_t adc, const Char_t *fname) const
1145 {
1146 // Print Module calibration data whether in file or in cout
1147    AliITSChannelDaSSD  *strip;
1148    ofstream             datafile;
1149    ostream             *outputfile;
1150    if (!fname) { outputfile = &cout; }
1151    else {
1152      datafile.open(fname, ios::out);
1153      if  (datafile.fail()) return kFALSE;
1154      outputfile = dynamic_cast<ostream*>(&datafile); 
1155    }
1156    *outputfile  << "DDL = " << (int)ddlID << ";  AD = " << (int)ad << ";  ADC = " << (int)adc << endl;
1157    for (Int_t strind = 0; strind < AliITSModuleDaSSD::GetStripsPerModuleConst(); strind++) {
1158      if ( (strip = GetStrip(ddlID, ad, adc, strind)) ) {
1159        *outputfile << "Str = " << strind << ";  ped = " << strip->GetPedestal() 
1160                    << ";  noise = " << strip->GetNoiseCM() << endl;
1161      }
1162      else continue;
1163    }
1164   if (datafile.is_open()) datafile.close(); 
1165   return kTRUE;
1166 }
1167
1168
1169
1170 //______________________________________________________________________________
1171 void AliITSHandleDaSSD::DumpInitData(const Char_t *str) const
1172 {
1173 // Print general information retrieved from raw data file
1174   cout << "Raw data file: " << fRawDataFileName << endl
1175        << "LDC: " << (Int_t)fLdcId << "; RunId: " << fRunId << endl
1176        << "Number of physics events: " << fNumberOfEvents << endl
1177        << str;
1178 }
1179
1180
1181 //______________________________________________________________________________
1182 Bool_t AliITSHandleDaSSD::AllocateSimulatedModules(const Int_t copymodind)
1183 {
1184 // Used to allocate simulated modules to test the performance  
1185   AliITSModuleDaSSD *module;
1186   UChar_t      ad, adc, ddlID;
1187   ad = adc = ddlID = 0;
1188   if (!(fModules[copymodind])) return kFALSE;
1189   for (Int_t modind = 0; modind < fNumberOfModules; modind++) {
1190     if (!fModules[modind]) {
1191       module = new AliITSModuleDaSSD(AliITSModuleDaSSD::GetStripsPerModuleConst());
1192       if ((adc < 5) || ((adc > 7) && (adc < 13)) ) adc += 1;
1193       else if (adc == 5) adc = 8;
1194       else if (adc == 13) {
1195         adc = 0;
1196         if (ad < 8) ad += 1;
1197         else {
1198           ad = 0;
1199           ddlID +=1;
1200         }
1201       }
1202       if (!module->SetModuleIdData (ddlID, ad, adc, modind)) return kFALSE;
1203       fModules[modind] = module;
1204       for (Int_t strind = 0; strind < module->GetNumberOfStrips(); strind++) {
1205         AliITSChannelDaSSD *cstrip = fModules[copymodind]->GetStrip(strind);
1206         if(!cstrip)return kFALSE;
1207         Long_t      eventsnumber = cstrip->GetEventsNumber();
1208         AliITSChannelDaSSD *strip = new AliITSChannelDaSSD(strind, eventsnumber);
1209         for (Long_t evind = 0; evind < eventsnumber; evind++) {
1210           Short_t sign = cstrip->GetSignal(evind);
1211           if (!strip->SetSignal(evind, sign)) AliError(Form("AliITSHandleDaSSD: Copy events error! mod = %i, str = %i", modind, strind));
1212         }
1213         module->SetStrip(strip, strind);
1214       }
1215     }
1216     else {
1217       ddlID = fModules[modind]->GetDdlId();
1218       ad    = fModules[modind]->GetAD();
1219       adc   = fModules[modind]->GetADC();
1220     }
1221   }
1222   for (UShort_t modind = 0; modind < fNumberOfModules; modind++) fModules[modind]->SetModuleId(modind + 1080);  
1223   return kTRUE;
1224 }
1225
1226
1227     
1228 //___________________________________________________________________________________________
1229 Bool_t AliITSHandleDaSSD::AdDataPresent(const Int_t ddl, const Int_t ad) const
1230 {
1231 // Check if there are calibration data for given ddl and slot
1232   for (Int_t modind = 0; modind < fNumberOfModules; modind++)
1233     if ((GetModule(modind)->GetAD() == ad) && (GetModule(modind)->GetDdlId() == ddl)) return kTRUE;
1234   return kFALSE;
1235 }
1236
1237    
1238
1239 //___________________________________________________________________________________________
1240 Bool_t AliITSHandleDaSSD::SaveEqSlotCalibrationData(const Int_t ddl, const Int_t ad, const Char_t *fname) const
1241 {
1242 // Saves calibration files for selected equipment (DDL)
1243   fstream    feefile;
1244   Int_t      zsml, offsetml;
1245   ULong_t    zsth, offset, zsoffset;
1246   if (!fname) {
1247     AliError("File name must be specified!");
1248     return kFALSE;   
1249   }
1250   if (!AdDataPresent(ddl, ad)) {
1251     AliError(Form("Error SaveEqSlotCalibrationData(ddl = %i, ad = %i) no data present", ddl, ad)); 
1252     return kFALSE;
1253   }
1254   feefile.open(fname, ios::out);
1255   if (!feefile.is_open()) {
1256         AliError(Form("Can not open the file %s for output!", fname)); 
1257     return kFALSE;
1258   }
1259   for (zsml = 0; fgkZsBitMask >> zsml; zsml++) ;
1260   for (offsetml = 0; fgkOffSetBitMask >> offsetml; offsetml++) ;
1261   for (Int_t strind = 0; strind < AliITSModuleDaSSD::GetStripsPerModuleConst(); strind++) {
1262     for (Int_t adcb = 0; adcb < fgkAdcPerDBlock; adcb++) {
1263       zsoffset = 0x0;
1264       for (Int_t j = 0; j < 2; j++) {
1265         Int_t adc = adcb + j * 8;
1266         zsth = ZsThreshold(ddl, ad, adc, strind);
1267         offset = OffsetValue(ddl, ad, adc, strind);
1268         zsoffset = zsoffset | (((zsth << offsetml) | offset) << ((j == 0) ? (offsetml + zsml) : 0));
1269       }
1270       feefile << "0x" << ConvBase(static_cast<unsigned long>(zsoffset), 16) << endl;
1271     }
1272   }
1273   feefile.close();
1274   return kTRUE;
1275 }
1276
1277
1278 //______________________________________________________________________________
1279 Int_t AliITSHandleDaSSD::ChannelIsBad(const UChar_t ddl, const UChar_t ad, const UChar_t adc, const Int_t strn) const
1280 {
1281 // Check if the channel is bad
1282   AliITSModuleDaSSD     *module = NULL;
1283   Int_t                  modn = -1;
1284   if (fBadChannelsList && fDDLModuleMap) {
1285     modn = RetrieveModuleId(ddl, ad, adc);
1286     if (modn < 0) return -1;
1287     if (modn < fgkMinSSDModuleId) {
1288       AliWarning(Form("Module ddl/ad/adc: %d/%d/%d has number %d which is wrong for SSD module %d", ddl, ad, adc, strn, modn));
1289           return -1;
1290     }
1291     Short_t modid = modn - fgkMinSSDModuleId;
1292     if (strn < AliITSModuleDaSSD::GetPNStripsPerModule()) 
1293       return (fBadChannelsList->GetBadChannelP(modid, strn)  & fgkBadChannelMask);
1294     else return (fBadChannelsList->GetBadChannelN(modid, (AliITSChannelDaSSD::GetMaxStripIdConst() - strn)) & fgkBadChannelMask);
1295   } else {
1296     AliError("Error ether bad channels list or DDLMap is not initialized or both, EvaluateIfChannelIsBad(module, strip) is used!");
1297     if ((module = GetModule(ddl, ad, adc))) {
1298       return (EvaluateIfChannelIsBad(module, strn) & fgkBadChannelMask);
1299     } else {
1300       AliWarning(Form("There is no calibration data for ddl = %i,  ad = %i,  adc = %i, 0 is used!", ddl, ad, adc));
1301       return 0ul;
1302     }  
1303         return 0;
1304   }
1305 }
1306
1307
1308
1309 //______________________________________________________________________________
1310 Int_t AliITSHandleDaSSD::LadderIsOff(const UChar_t ddl, const UChar_t ad, const UChar_t adc) const
1311 {
1312 //Checks if the module with given ddl, ad, adc is on the ladder which is in the list of ladders which are off
1313   const Int_t nm5 =  500;
1314   const Int_t nm6 =  1248;
1315   const Int_t nml5a = 12;
1316   const Int_t nml5c = 10;
1317   const Int_t nml6a = 12;
1318   const Int_t nml6c = 13;
1319   Int_t               modn, ladder, layer, side;
1320   AliITSModuleDaSSD  *module;
1321   if (!(module = GetModule(ddl, ad, adc))) return 0;
1322   if ((modn = module->GetModuleId()) <= 0)  modn = RetrieveModuleId(ddl, ad, adc);
1323   if (modn <= 0) return 0;
1324   layer = modn >= nm6 ? 1 : 0;     // 6 : 5
1325   ladder = (modn - (layer ? nm6 : nm5)) / (layer ? (nml6a + nml6c) : (nml5a + nml5c));
1326   if ( ((modn - (layer ? nm6 : nm5)) % (layer ? (nml6a + nml6c) : (nml5a + nml5c))) < (layer ? nml6a : nml5a))
1327     side = 0;      // A
1328   else side = 1;   // C
1329   ladder += (layer ? 600 : 500);
1330   layer += 5;
1331   if (side)
1332     if (fCLaddersOff.GetSize()) {
1333       for(Int_t i = 0; i < fCLaddersOff.GetSize(); i++) 
1334         if (fCLaddersOff.At(i) == ladder) return fCLaddersOff.At(i);
1335       return 0;
1336     } else return 0;
1337   else
1338     if (fALaddersOff.GetSize()) {
1339       for(Int_t i = 0; i < fALaddersOff.GetSize(); i++) 
1340         if (fALaddersOff.At(i) == ladder) return fALaddersOff.At(i);
1341       return 0;
1342     } else return 0;
1343   return 0;  
1344 }
1345
1346
1347         
1348 //______________________________________________________________________________
1349 ULong_t AliITSHandleDaSSD::OffsetValue(const AliITSChannelDaSSD *strip, 
1350                                        const UChar_t ddl, const UChar_t ad, const UChar_t adc, const Int_t strn) const
1351 {
1352 // Calculate the offset value to be upload to FEROM     
1353   Int_t  pedint;
1354   if (fOffsetDefault < INT_MAX) pedint = fOffsetDefault;
1355   else pedint = TMath::Nint(strip->GetPedestal());
1356   if (pedint > static_cast<Int_t>((fgkOffSetBitMask >> 1))) {
1357     if (!ChannelIsBad(ddl, ad, adc, strn) && !((fMergeBCLists) && (EvaluateIfChannelIsBad(GetModule(ddl, ad, adc), strn)))) 
1358       AliError(Form("Offset %i, channel(ddl/ad/adc/strip) %i/%i/%i/%i  can not be represented with mask 0x%s, Offset = %i",
1359                    pedint, ddl, ad, adc, strn, ConvBase(fgkOffSetBitMask, 16).c_str(), (fgkOffSetBitMask >> 1)));
1360     return (fgkOffSetBitMask >> 1);
1361   }  
1362   if ((-pedint) > static_cast<Int_t>(((fgkOffSetBitMask + 1) >> 1))) {
1363     if (!ChannelIsBad(ddl, ad, adc, strn) && !((fMergeBCLists) && (EvaluateIfChannelIsBad(GetModule(ddl, ad, adc), strn)))) 
1364       AliError(Form("Offset %i, channel(ddl/ad/adc/strip) %i/%i/%i/%i  can not be represented with mask 0x%s, Offset = %i", 
1365                pedint, ddl, ad, adc, strn, ConvBase(fgkOffSetBitMask, 16).c_str(), 
1366                ((fgkOffSetBitMask & (~fgkOffSetBitMask >> 1)) - fgkOffSetBitMask - 1)));
1367     return fgkOffSetBitMask & (~fgkOffSetBitMask >> 1);
1368   }
1369   return fgkOffSetBitMask & (pedint >= 0 ? pedint : pedint + fgkOffSetBitMask + 1);
1370 }
1371
1372
1373
1374 //______________________________________________________________________________
1375 ULong_t AliITSHandleDaSSD::OffsetValue(const UChar_t ddl, const UChar_t ad, const UChar_t adc, const Int_t strn) const
1376 {
1377 // Calculate the offset value to be upload to FEROM     
1378   AliITSChannelDaSSD    *strip = NULL;
1379   AliITSModuleDaSSD     *module = NULL;
1380   if ((module = GetModule(ddl, ad, adc))) {
1381     if ((strip = module->GetStrip(strn))) return OffsetValue(strip, ddl, ad, adc, strn);
1382     else {
1383       AliWarning(Form("There is no calibration data for ddl = %i,  ad = %i,  adc = %i,  strip = %i, 0 is used!", ddl, ad, adc, strn));
1384       return 0ul;
1385     }
1386   } else {
1387     AliWarning(Form("There is no calibration data for ddl = %i,  ad = %i,  adc = %i, 0 is used!", ddl, ad, adc));
1388     return 0ul;
1389   }  
1390 }
1391
1392
1393
1394 //______________________________________________________________________________
1395 ULong_t AliITSHandleDaSSD::ZsThreshold(const AliITSChannelDaSSD *strip) const
1396
1397 // Calculate the value of zero suppression threshold to be upload to FEROM
1398   ULong_t zs;
1399   if (fZsDefault < 0) {
1400     zs = TMath::Nint(fZsFactor * strip->GetNoiseCM());
1401     if (zs < static_cast<ULong_t>(fZsMinimum)) zs = static_cast<ULong_t>(fZsMinimum);
1402   }
1403   else zs = fZsDefault;
1404   return (zs < fgkZsBitMask) ? (zs & fgkZsBitMask) : fgkZsBitMask;
1405 }
1406
1407
1408 //______________________________________________________________________________
1409 ULong_t AliITSHandleDaSSD::ZsThreshold(const UChar_t ddl, const UChar_t ad, const UChar_t adc, const Int_t strn) const
1410 {
1411 // Calculate the value of zero suppression threshold to be upload to FEROM, account bad channels list
1412   AliITSChannelDaSSD    *strip = NULL;
1413   AliITSModuleDaSSD     *module = NULL;
1414   if (ChannelIsBad(ddl, ad, adc, strn)) return fgkZsBitMask;
1415   if (LadderIsOff(ddl, ad, adc)) return fgkZsBitMask;
1416   if (fZsDefault > 0) if (static_cast<ULong_t>(fZsDefault) >= fgkZsBitMask) return fgkZsBitMask;
1417   if ((module = GetModule(ddl, ad, adc))) {
1418         if (fMergeBCLists) if (EvaluateIfChannelIsBad(module, strn)) return fgkZsBitMask;
1419     if ((strip = module->GetStrip(strn)))  return ZsThreshold(strip);
1420     else {
1421       AliWarning(Form("There is no calibration data for ddl = %i,  ad = %i,  adc = %i,  strip = %i, 0 is used!", ddl, ad, adc, strn));
1422       return 0ul;
1423     }
1424   } else {
1425     AliWarning(Form("There is no calibration data for ddl = %i,  ad = %i,  adc = %i, 0 is used!", ddl, ad, adc));
1426     return 0ul;
1427   }
1428 }
1429
1430             
1431 //______________________________________________________________________________
1432 string AliITSHandleDaSSD::ConvBase(const unsigned long value, const long base) const
1433 {
1434 // Converts the unsigned long number into that in another base 
1435   string digits = "0123456789ABCDEF";
1436   string result;
1437   unsigned long v = value;
1438   if((base < 2) || (base > 16)) {
1439     result = "Error: base out of range.";
1440   }
1441   else {
1442     int i = 0;
1443     do {
1444       result = digits[v % base] + result;
1445       v /= base;
1446       i++;
1447     }
1448     while((v) || (i<8));
1449   }
1450   return result;
1451 }
1452
1453
1454
1455 //______________________________________________________________________________
1456 Int_t AliITSHandleDaSSD::CheckOffChips() const
1457 {
1458 // Check if the chip, module are off
1459   AliITSChannelDaSSD *strip;
1460   Int_t       offthreshold;
1461   Int_t       strnd, chipnd, modnd, stroff, chipoff, modoff;
1462   offthreshold = TMath::Nint(fZsMinimum/fZsFactor);
1463   modnd = modoff = 0;
1464   for (Int_t mi = 0; mi < fNumberOfModules; mi++) {
1465     if (!fModules[mi]) { modnd++; continue; }
1466     if (fModules[mi]->GetModuleId() < 0) continue;
1467     if (LadderIsOff(fModules[mi]->GetDdlId(), fModules[mi]->GetAD(), fModules[mi]->GetADC()) ) continue;
1468     chipoff = chipnd = 0;
1469     for (Int_t chipind = 0; chipind < AliITSModuleDaSSD::GetChipsPerModuleConst(); chipind++) {
1470       strnd = stroff = 0;
1471       Int_t stripind = chipind * AliITSModuleDaSSD::GetStripsPerChip();
1472       for (Int_t strind = stripind; strind < (stripind + AliITSModuleDaSSD::GetStripsPerChip()); strind++) {
1473         if (!(strip = fModules[mi]->GetStrip(strind))) { strnd++;  continue; }
1474         if (strip->GetNoiseCM() < offthreshold ) stroff++;
1475       }
1476       if (strnd == AliITSModuleDaSSD::GetStripsPerChip()) chipnd++;
1477       else if (stroff == AliITSModuleDaSSD::GetStripsPerChip()) chipoff++;
1478       else if ((stroff + strnd) == AliITSModuleDaSSD::GetStripsPerChip()) chipoff++;
1479     }
1480     if ((!chipoff) && (!chipnd)) continue;
1481     if (chipnd == AliITSModuleDaSSD::GetChipsPerModuleConst()) {
1482       AliInfo(Form("Module: (ddl/ad/adc) %i/%i/%i seems to be off and it is not on the ladders which are off!", 
1483                fModules[mi]->GetDdlId(), fModules[mi]->GetAD(), fModules[mi]->GetADC()));
1484       modnd++;
1485     }
1486     if (chipoff == AliITSModuleDaSSD::GetChipsPerModuleConst()) {
1487       AliInfo(Form("Module (ddl/ad/adc): %i/%i/%i seems to be off and it is not on the ladders which are off!", 
1488                fModules[mi]->GetDdlId(), fModules[mi]->GetAD(), fModules[mi]->GetADC()));
1489       modoff++;
1490     }
1491     else if ((chipoff + chipnd) == AliITSModuleDaSSD::GetChipsPerModuleConst()) {
1492       AliInfo(Form("Module: (ddl/ad/adc): %i/%i/%i seems to be off and it is not on the ladders which are off!", 
1493                fModules[mi]->GetDdlId(), fModules[mi]->GetAD(), fModules[mi]->GetADC()));
1494       modoff++;
1495     }
1496     else if (chipoff) {
1497       AliInfo(Form("Module: (ddl/ad/adc): %i/%i/%i has %i chips which are off!", 
1498                fModules[mi]->GetDdlId(), fModules[mi]->GetAD(), fModules[mi]->GetADC(), chipoff));
1499       modoff++;
1500     }
1501   }
1502   return (modoff + modnd);
1503 }
1504
1505
1506 //______________________________________________________________________________
1507 Bool_t AliITSHandleDaSSD::CalculatePedNoiseW(const AliITSModuleDaSSD *const module)
1508 {
1509 // Calculates Pedestal and Noise using Welford algorithm
1510   AliITSChannelDaSSD *strip;
1511   Double_t            pedestal, noise, p0, s0;
1512   Short_t            *signal;
1513   Int_t               ovev, n;
1514   if (!module) return kFALSE;
1515   for (Int_t strind = 0; strind < module->GetNumberOfStrips(); strind++) {
1516     if (!(strip = module->GetStrip(strind))) continue;
1517     if (!(signal = strip->GetSignal())) {
1518       AliError(Form("AliITSHandleDaSSD: Error CalculatePedestal(): there are no events data for module[%i] strip[%i]->GetSignal()",
1519                      module->GetModuleId(), strind));
1520       continue; 
1521     }
1522 //************* pedestal and noise first pass ****************
1523     pedestal = p0 = noise = 0.0L;
1524     ovev = 0;
1525     for (Int_t ev = 0; ev < strip->GetEventsNumber(); ev++) {
1526       if (SignalOutOfRange(signal[ev])) ovev += 1;
1527       else 
1528         if (!(ev - ovev)) {
1529           pedestal = p0 = signal[ev];
1530           noise = 0.0L;
1531         } else {
1532           p0 = pedestal + (signal[ev] - pedestal) / static_cast<Double_t>(ev - ovev + 1);
1533           s0 = noise + (signal[ev] - pedestal) * (signal[ev] - p0);
1534           pedestal = p0;
1535           noise = s0;
1536         }
1537     }
1538     if (strip->GetEventsNumber() == ovev) pedestal = AliITSChannelDaSSD::GetUndefinedValue();
1539     strip->SetPedestal(static_cast<Float_t>(pedestal));
1540     if ((n = strip->GetEventsNumber() - ovev - 1) > 0) 
1541       strip->SetNoise( static_cast<Float_t>(TMath::Sqrt(noise / static_cast<Double_t>(n))) );
1542     else {
1543       strip->SetNoise(AliITSChannelDaSSD::GetUndefinedValue());
1544       continue;
1545     }
1546 //************* Second pass excluds event with |p - s|>f*noise *****************
1547     pedestal = p0 = noise = 0.0L;
1548     ovev = 0;
1549     for (Int_t ev = 0; ev < strip->GetEventsNumber(); ev++) {
1550       if (   SignalOutOfRange(signal[ev]) 
1551           || TMath::Abs(signal[ev] - strip->GetPedestal()) > (fPedestalThresholdFactor * strip->GetNoise())) ovev += 1;
1552       else
1553         if (!(ev - ovev)) {
1554           pedestal = p0 = signal[ev];
1555           noise = 0.0L;
1556         } else {
1557           p0 = pedestal + (signal[ev] - pedestal) / static_cast<Double_t>(ev - ovev + 1);
1558           s0 = noise + (signal[ev] - pedestal) * (signal[ev] - p0);
1559           pedestal = p0;
1560           noise = s0;
1561         }
1562     }      
1563     if ((n = strip->GetEventsNumber() - ovev - 1) > 0) noise = TMath::Sqrt(noise / static_cast<Double_t>(n));
1564     else  noise = AliITSChannelDaSSD::GetUndefinedValue();
1565     strip->SetNoise(static_cast<Float_t>(noise));
1566     if (strip->GetEventsNumber() == ovev) pedestal = AliITSChannelDaSSD::GetUndefinedValue();
1567     strip->SetPedestal(static_cast<Float_t>(pedestal));
1568     strip->SetOverflowNumber(ovev);     
1569   }
1570   return kTRUE;
1571 }
1572
1573
1574 //______________________________________________________________________________
1575 Bool_t AliITSHandleDaSSD::CalculateCMW(AliITSModuleDaSSD *const module)
1576 {
1577 // Calculates CM using Welford algorithm
1578   AliITSChannelDaSSD  *strip = NULL;
1579   Short_t             *signal;
1580   Int_t                ovstr, n;
1581   Int_t                stripind;
1582   Double_t             cm0, cm1, cmsigma, cms1;
1583   module->SetNumberOfChips(AliITSModuleDaSSD::GetChipsPerModuleConst());
1584   for (Int_t chipind = 0; chipind < module->GetNumberOfChips(); chipind++) {
1585     stripind = chipind * module->GetStripsPerChip();
1586     module->GetCM()[chipind].Set(fNumberOfEvents);
1587     module->GetCM()[chipind].Reset(0.0f);
1588     for (Long_t ev = 0; ev < fNumberOfEvents; ev++) {
1589     // calculate firs approximation of CM and SigmaCM.
1590       cm0 = cm1 = cmsigma = 0.0L;
1591       ovstr = 0;
1592       for (Int_t strind = stripind; strind < (stripind + AliITSModuleDaSSD::GetStripsPerChip()); strind++) {
1593         if (!(strip = module->GetStrip(strind))) { ovstr += 1; continue; } //return kFALSE; 
1594         if (!(signal = strip->GetSignal())) { ovstr += 1; continue; }  //return kFALSE; 
1595         if ((SignalOutOfRange(signal[ev])) || (strip->GetPedestal() == AliITSChannelDaSSD::GetUndefinedValue())) ovstr += 1;
1596         else {
1597           if (!(strind - stripind - ovstr)) {
1598           cm0 = cm1 = signal[ev] - strip->GetPedestal();
1599           cmsigma = 0.0L;
1600         } else {
1601           cm1 = cm0 + (signal[ev] - strip->GetPedestal() - cm0) / static_cast<Double_t>(strind - stripind - ovstr + 1);
1602           cms1 = cmsigma + (signal[ev] - strip->GetPedestal() - cm0) * (signal[ev] - strip->GetPedestal() - cm1);
1603           cm0 = cm1;
1604           cmsigma = cms1;
1605         } }
1606       }
1607       if ((n = AliITSModuleDaSSD::GetStripsPerChip() - ovstr - 1) > 0) cmsigma = TMath::Sqrt(cmsigma / static_cast<Double_t>(n));
1608       else {
1609         AliWarning(Form("AliITSHandleDaSSD: Too little number of strips have a signal for module:chip:event : [%d]:[%d]:[%ld]\n",
1610                    module->GetModuleId(), chipind, ev));
1611         if (!(module->SetCM(0.0f, chipind, ev))) 
1612           AliError(Form("AliITSHandleDaSSD: Error, module->SetCM(...) returned kFALSE module:chip:event : [%d]:[%d]:[%ld]\n",
1613                    module->GetModuleId(), chipind, ev));
1614         continue;
1615       }
1616    // calculate cm with threshold
1617       Double_t cmsum = 0.0L;
1618       ovstr = 0;
1619       for (Int_t strind = stripind; strind < (stripind + AliITSModuleDaSSD::GetStripsPerChip()); strind++) {
1620         if (!(strip = module->GetStrip(strind))) { ovstr += 1; continue; }
1621         if (!(signal = strip->GetSignal())) { ovstr += 1; continue; }
1622         if ( (SignalOutOfRange(signal[ev])) || (strip->GetPedestal() == AliITSChannelDaSSD::GetUndefinedValue()) 
1623                || (TMath::Abs(cm0 - (signal[ev] - strip->GetPedestal())) > (fCmThresholdFactor * cmsigma)) ) ovstr += 1;
1624         else cmsum += (signal[ev] - strip->GetPedestal());
1625       }
1626       if ((n = AliITSModuleDaSSD::GetStripsPerChip() - ovstr)) cmsum /= (Double_t)(n);
1627       else cmsum = 0.0L;
1628       if (!(module->SetCM(static_cast<Float_t>(cmsum), chipind, ev))) 
1629         AliError(Form("AliITSHandleDaSSD: Error, module->SetCM(...) returned kFALSE module:chip:event : [%d]:[%d]:[%ld]\n",
1630                  module->GetModuleId(), chipind, ev));
1631     } 
1632   }
1633   return kTRUE; 
1634 }
1635
1636
1637 //______________________________________________________________________________
1638 Bool_t AliITSHandleDaSSD::CalculateNoiseCMW(AliITSModuleDaSSD *const module)
1639 {
1640 // Calculates Noise with CM correction
1641   AliITSChannelDaSSD  *strip = NULL;
1642   Short_t     *signal;
1643   Int_t        ovev, n;
1644   if (!CalculateCMW(module)) { 
1645     AliError("Error: AliITSHandleDaSSD::CalculateCMW() returned kFALSE");
1646     return kFALSE;
1647   }  
1648   for (Int_t strind = 0; strind < module->GetNumberOfStrips(); strind++) {
1649     if (!(strip = module->GetStrip(strind))) continue; //return kFALSE;
1650     if (!(signal = strip->GetSignal())) {
1651       strip->SetNoiseCM(AliITSChannelDaSSD::GetUndefinedValue());
1652       AliError(Form("AliITSHandleDaSSD: Error CalculateNoiseCMW(): there are no events data for module[%i] strip[%i]->GetSignal()", 
1653                      module->GetModuleId(), strind));
1654       continue; //return kFALSE;
1655     }
1656 //** To get exactly the same set of events as for pedestal and noise calculation **
1657     Double_t pedestal, noise, p0, s0;
1658     pedestal = p0 = noise = 0.0L;
1659     ovev = 0;
1660     for (Int_t ev = 0; ev < strip->GetEventsNumber(); ev++) {
1661       if (SignalOutOfRange(signal[ev])) ovev += 1;
1662       else 
1663         if (!(ev - ovev)) {
1664           pedestal = p0 = signal[ev];
1665           noise = 0.0L;
1666         } else {
1667           p0 = pedestal + (signal[ev] - pedestal) / static_cast<Double_t>(ev - ovev + 1);
1668           s0 = noise + (signal[ev] - pedestal) * (signal[ev] - p0);
1669           pedestal = p0;
1670           noise = s0;
1671         }
1672     }
1673     if ((n = strip->GetEventsNumber() - ovev - 1) > 0) noise = TMath::Sqrt(noise / static_cast<Double_t>(n));
1674     else  {
1675           strip->SetNoiseCM(AliITSChannelDaSSD::GetUndefinedValue());
1676           continue;
1677     }
1678 //** Calculation of CM corrected noise **
1679     Int_t chipind = strind / AliITSModuleDaSSD::GetStripsPerChip();
1680     Double_t nsum = 0.0L;
1681     ovev = 0;
1682     for (Int_t ev = 0; ev < strip->GetEventsNumber(); ev++) {
1683       if (   SignalOutOfRange(signal[ev])
1684           || TMath::Abs(signal[ev] - pedestal) > (fPedestalThresholdFactor * noise)) ovev += 1;
1685       else nsum += pow((signal[ev] - strip->GetPedestal() - module->GetCM(chipind, ev)), 2);
1686     } 
1687     if ((n = strip->GetEventsNumber() - ovev - 1) > 0) noise =  TMath::Sqrt(nsum / static_cast<Double_t>(n));
1688     else  noise = AliITSChannelDaSSD::GetUndefinedValue();
1689     strip->SetNoiseCM(static_cast<Float_t>(noise));
1690   }
1691   return kTRUE;
1692 }
1693
1694
1695
1696 //______________________________________________________________________________
1697 UChar_t AliITSHandleDaSSD::EvaluateIfChannelIsBad(const AliITSModuleDaSSD *const module, const Int_t stripn) const
1698 {
1699 //Applies the bad channel creteria and set the appropriate flags for returned value
1700   AliITSChannelDaSSD  *strip = 0;
1701   UInt_t               bcflags = 0;
1702   if (fZsDefault >= 0) { if (static_cast<ULong_t>(fZsDefault) >= fgkZsBitMask) bcflags |= 3; }
1703   else if (static_cast<ULong_t>(fZsMinimum) >= fgkZsBitMask) bcflags |= 3;
1704   if (LadderIsOff(module->GetDdlId(), module->GetAD(), module->GetADC()) )  bcflags |= 3;
1705   
1706   if (!(strip = module->GetStrip(stripn))) bcflags |= 3;
1707   else {
1708     if (strip->GetNoiseCM() == AliITSChannelDaSSD::GetUndefinedValue()) bcflags |= 8;
1709     if (static_cast<ULong_t>(TMath::Nint(fZsFactor * strip->GetNoiseCM())) >= fgkZsBitMask) bcflags |= 8;
1710     if (strip->GetNoiseCM() < 1) bcflags |= 16;
1711     if (strip->GetPedestal() > ((fgkOffSetBitMask >> 1) - 1))  bcflags |= 4;
1712     else if ((-(strip->GetPedestal())) > (fgkOffSetBitMask >> 1))  bcflags |= 4;
1713     if (bcflags) bcflags |= 3;
1714   }
1715   return bcflags;
1716 }
1717