]> git.uio.no Git - u/mrichter/AliRoot.git/blob - EMCAL/AliEMCALRawUtils.cxx
included adjustments to better fit saturated channels which should have been committe...
[u/mrichter/AliRoot.git] / EMCAL / AliEMCALRawUtils.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 /* History of cvs commits:
18  *
19  * $Log$
20  * Revision 1.10  2007/12/06 13:58:11  hristov
21  * Additional pritection. Do not delete the mapping, it is owned by another class
22  *
23  * Revision 1.9  2007/12/06 02:19:51  jklay
24  * incorporated fitting procedure from testbeam analysis into AliRoot
25  *
26  * Revision 1.8  2007/12/05 02:30:51  jklay
27  * modification to read Altro mappings into AliEMCALRecParam and pass to AliEMCALRawUtils from AliEMCALReconstructor; add option to AliEMCALRawUtils to set old RCU format (for testbeam) or not
28  *
29  * Revision 1.7  2007/11/14 15:51:46  gustavo
30  * Take out few unnecessary prints
31  *
32  * Revision 1.6  2007/11/01 01:23:51  mvl
33  * Removed call to SetOldRCUFormat, which is only needed for testbeam data
34  *
35  * Revision 1.5  2007/11/01 01:20:33  mvl
36  * Further improvement of peak finding; more robust fit
37  *
38  * Revision 1.4  2007/10/31 17:15:24  mvl
39  * Fixed bug in raw data unpacking; Added pedestal to signal fit; Added logic to deal with high/low gain
40  *
41  * Revision 1.3  2007/09/27 08:36:46  mvl
42  * More robust setting of fit range in FitRawSignal (P. Hristov)
43  *
44  * Revision 1.2  2007/09/03 20:55:35  jklay
45  * EMCAL e-by-e reconstruction methods from Cvetan
46  *
47  * Revision 1.1  2007/03/17 19:56:38  mvl
48  * Moved signal shape routines from AliEMCAL to separate class AliEMCALRawUtils to streamline raw data reconstruction code.
49  * */
50
51 //*-- Author: Marco van Leeuwen (LBL)
52 #include "AliEMCALRawUtils.h"
53
54 #include "TF1.h"
55 #include "TGraph.h"
56 #include "TSystem.h"
57
58 #include "AliLog.h"
59 #include "AliRun.h"
60 #include "AliRunLoader.h"
61 #include "AliCaloAltroMapping.h"
62 #include "AliAltroBuffer.h"
63 #include "AliRawReader.h"
64 #include "AliCaloRawStream.h"
65 #include "AliDAQ.h"
66
67 #include "AliEMCALRecParam.h"
68 #include "AliEMCALLoader.h"
69 #include "AliEMCALGeometry.h"
70 #include "AliEMCALDigitizer.h"
71 #include "AliEMCALDigit.h"
72
73 ClassImp(AliEMCALRawUtils)
74
75 // Signal shape parameters
76 Double_t AliEMCALRawUtils::fgTimeBinWidth  = 100E-9 ; // each sample is 100 ns
77 Double_t AliEMCALRawUtils::fgTimeTrigger = 1.5E-6 ;   // 15 time bins ~ 1.5 musec
78
79 // some digitization constants
80 Int_t    AliEMCALRawUtils::fgThreshold = 1;
81 Int_t    AliEMCALRawUtils::fgDDLPerSuperModule = 2;  // 2 ddls per SuperModule
82 Int_t    AliEMCALRawUtils::fgPedestalValue = 32;      // pedestal value for digits2raw
83 Double_t AliEMCALRawUtils::fgFEENoise = 3.;            // 3 ADC channels of noise (sampled)
84
85 AliEMCALRawUtils::AliEMCALRawUtils()
86   : fHighLowGainFactor(0.), fOrder(0), fTau(0.), fNoiseThreshold(0),
87     fNPedSamples(0), fGeom(0), fOption("")
88 {
89
90   //These are default parameters.  
91   //Can be re-set from without with setter functions
92   fHighLowGainFactor = 16. ;          // adjusted for a low gain range of 82 GeV (10 bits) 
93   fOrder = 2;                         // order of gamma fn
94   fTau = 2.35;                        // in units of timebin, from CERN 2007 testbeam
95   fNoiseThreshold = 3;
96   fNPedSamples = 5;
97
98   //Get Mapping RCU files from the AliEMCALRecParam                                 
99   const TObjArray* maps = AliEMCALRecParam::GetMappings();
100   if(!maps) AliFatal("Cannot retrieve ALTRO mappings!!");
101
102   for(Int_t i = 0; i < 2; i++) {
103     fMapping[i] = (AliAltroMapping*)maps->At(i);
104   }
105
106   //To make sure we match with the geometry in a simulation file,
107   //let's try to get it first.  If not, take the default geometry
108   AliRunLoader *rl = AliRunLoader::GetRunLoader();
109   if (rl->GetAliRun() && rl->GetAliRun()->GetDetector("EMCAL")) {
110     fGeom = dynamic_cast<AliEMCAL*>(rl->GetAliRun()->GetDetector("EMCAL"))->GetGeometry();
111   } else {
112     AliInfo(Form("Using default geometry in raw reco"));
113     fGeom =  AliEMCALGeometry::GetInstance(AliEMCALGeometry::GetDefaultGeometryName());
114   }
115
116   if(!fGeom) AliFatal(Form("Could not get geometry!"));
117
118 }
119
120 //____________________________________________________________________________
121 AliEMCALRawUtils::AliEMCALRawUtils(const AliEMCALRawUtils& rawU)
122   : TObject(),
123     fHighLowGainFactor(rawU.fHighLowGainFactor), 
124     fOrder(rawU.fOrder),
125     fTau(rawU.fTau),
126     fNoiseThreshold(rawU.fNoiseThreshold),
127     fNPedSamples(rawU.fNPedSamples),
128     fGeom(rawU.fGeom), 
129     fOption(rawU.fOption)
130 {
131   //copy ctor
132   fMapping[0] = rawU.fMapping[0];
133   fMapping[1] = rawU.fMapping[1];
134 }
135
136 //____________________________________________________________________________
137 AliEMCALRawUtils& AliEMCALRawUtils::operator =(const AliEMCALRawUtils &rawU)
138 {
139   //assignment operator
140
141   if(this != &rawU) {
142     fHighLowGainFactor = rawU.fHighLowGainFactor;
143     fOrder = rawU.fOrder;
144     fTau = rawU.fTau;
145     fNoiseThreshold = rawU.fNoiseThreshold;
146     fNPedSamples = rawU.fNPedSamples;
147     fGeom = rawU.fGeom;
148     fOption = rawU.fOption;
149     fMapping[0] = rawU.fMapping[0];
150     fMapping[1] = rawU.fMapping[1];
151   }
152
153   return *this;
154
155 }
156
157 //____________________________________________________________________________
158 AliEMCALRawUtils::~AliEMCALRawUtils() {
159
160 }
161
162 //____________________________________________________________________________
163 void AliEMCALRawUtils::Digits2Raw()
164 {
165   // convert digits of the current event to raw data
166   
167   AliRunLoader *rl = AliRunLoader::GetRunLoader();
168   AliEMCALLoader *loader = dynamic_cast<AliEMCALLoader*>(rl->GetDetectorLoader("EMCAL"));
169
170   // get the digits
171   loader->LoadDigits("EMCAL");
172   loader->GetEvent();
173   TClonesArray* digits = loader->Digits() ;
174   
175   if (!digits) {
176     Warning("Digits2Raw", "no digits found !");
177     return;
178   }
179
180   static const Int_t nDDL = 12*2; // 12 SM hardcoded for now. Buffers allocated dynamically, when needed, so just need an upper limit here
181   AliAltroBuffer* buffers[nDDL];
182   for (Int_t i=0; i < nDDL; i++)
183     buffers[i] = 0;
184
185   Int_t adcValuesLow[fgkTimeBins];
186   Int_t adcValuesHigh[fgkTimeBins];
187
188   // loop over digits (assume ordered digits)
189   for (Int_t iDigit = 0; iDigit < digits->GetEntries(); iDigit++) {
190     AliEMCALDigit* digit = dynamic_cast<AliEMCALDigit *>(digits->At(iDigit)) ;
191     if (digit->GetAmp() < fgThreshold) 
192       continue;
193
194     //get cell indices
195     Int_t nSM = 0;
196     Int_t nIphi = 0;
197     Int_t nIeta = 0;
198     Int_t iphi = 0;
199     Int_t ieta = 0;
200     Int_t nModule = 0;
201     fGeom->GetCellIndex(digit->GetId(), nSM, nModule, nIphi, nIeta);
202     fGeom->GetCellPhiEtaIndexInSModule(nSM, nModule, nIphi, nIeta,iphi, ieta) ;
203     
204     //Check which is the RCU of the cell.
205     Int_t iRCU = -111;
206     //RCU0
207     if (0<=iphi&&iphi<8) iRCU=0; // first cable row
208     else if (8<=iphi&&iphi<16 && 0<=ieta&&ieta<24) iRCU=0; // first half; 
209     //second cable row
210     //RCU1
211     else if(8<=iphi&&iphi<16 && 24<=ieta&&ieta<48) iRCU=1; // second half; 
212     //second cable row
213     else if(16<=iphi&&iphi<24) iRCU=1; // third cable row
214     if (iRCU<0) 
215       Fatal("Digits2Raw()","Non-existent RCU number: %d", iRCU);
216     
217     //Which DDL?
218     Int_t iDDL = fgDDLPerSuperModule* nSM + iRCU;
219     if (iDDL >= nDDL)
220       Fatal("Digits2Raw()","Non-existent DDL board number: %d", iDDL);
221
222     if (buffers[iDDL] == 0) {      
223       // open new file and write dummy header
224       TString fileName = AliDAQ::DdlFileName("EMCAL",iDDL);
225       buffers[iDDL] = new AliAltroBuffer(fileName.Data(),fMapping[iRCU]);
226       buffers[iDDL]->WriteDataHeader(kTRUE, kFALSE);  //Dummy;
227     }
228     
229     // out of time range signal (?)
230     if (digit->GetTimeR() > GetRawFormatTimeMax() ) {
231       AliInfo("Signal is out of time range.\n");
232       buffers[iDDL]->FillBuffer((Int_t)digit->GetAmp());
233       buffers[iDDL]->FillBuffer(GetRawFormatTimeBins() );  // time bin
234       buffers[iDDL]->FillBuffer(3);          // bunch length      
235       buffers[iDDL]->WriteTrailer(3, ieta, iphi, nSM);  // trailer
236       // calculate the time response function
237     } else {
238       Bool_t lowgain = RawSampledResponse(digit->GetTimeR(), digit->GetAmp(), adcValuesHigh, adcValuesLow) ; 
239       if (lowgain) 
240         buffers[iDDL]->WriteChannel(ieta, iphi, 0, GetRawFormatTimeBins(), adcValuesLow, fgThreshold);
241       else 
242         buffers[iDDL]->WriteChannel(ieta,iphi, 1, GetRawFormatTimeBins(), adcValuesHigh, fgThreshold);
243     }
244   }
245   
246   // write headers and close files
247   for (Int_t i=0; i < nDDL; i++) {
248     if (buffers[i]) {
249       buffers[i]->Flush();
250       buffers[i]->WriteDataHeader(kFALSE, kFALSE);
251       delete buffers[i];
252     }
253   }
254
255   loader->UnloadDigits();
256 }
257
258 //____________________________________________________________________________
259 void AliEMCALRawUtils::Raw2Digits(AliRawReader* reader,TClonesArray *digitsArr)
260 {
261   // convert raw data of the current event to digits                                                                                     
262
263   digitsArr->Clear(); 
264
265   if (!digitsArr) {
266     Error("Raw2Digits", "no digits found !");
267     return;
268   }
269   if (!reader) {
270     Error("Raw2Digits", "no raw reader found !");
271     return;
272   }
273
274   AliCaloRawStream in(reader,"EMCAL",fMapping);
275   // Select EMCAL DDL's;
276   reader->Select("EMCAL");
277
278   TString option = GetOption();
279   if (option.Contains("OldRCUFormat"))
280     in.SetOldRCUFormat(kTRUE); // Needed for testbeam data
281   else
282     in.SetOldRCUFormat(kFALSE);
283
284   //Updated fitting routine from 2007 beam test takes into account
285   //possibility of two peaks in data and selects first one for fitting
286   //Also sets some of the starting parameters based on the shape of the
287   //given raw signal being fit
288
289   TF1 * signalF = new TF1("signal", RawResponseFunction, 0, GetRawFormatTimeBins(), 5);
290   signalF->SetParameters(10.,0.,fTau,fOrder,5.); //set all defaults once, just to be safe
291   signalF->SetParNames("amp","t0","tau","N","ped");
292   signalF->SetParameter(2,fTau); // tau in units of time bin
293   signalF->SetParLimits(2,2,-1);
294   signalF->SetParameter(3,fOrder); // order
295   signalF->SetParLimits(3,2,-1);
296   
297   Int_t id =  -1;
298   Float_t time = 0. ; 
299   Float_t amp = 0. ; 
300
301   //Graph to hold data we will fit (should be converted to an array
302   //later to speed up processing
303   TGraph * gSig = new TGraph(GetRawFormatTimeBins()); 
304
305   Int_t readOk = 1;
306   Int_t lowGain = 0;
307
308   while (readOk && in.GetModule() < 0) 
309     readOk = in.Next();  // Go to first digit
310
311   Int_t col = 0;
312   Int_t row = 0;
313
314   while (readOk) { 
315     id =  fGeom->GetAbsCellIdFromCellIndexes(in.GetModule(), in.GetRow(), in.GetColumn()) ;
316     lowGain = in.IsLowGain();
317     Int_t maxTime = in.GetTime();  // timebins come in reverse order
318     if (maxTime < 0 || maxTime >= GetRawFormatTimeBins()) {
319       AliWarning(Form("Invalid time bin %d",maxTime));
320       maxTime = GetRawFormatTimeBins();
321     }
322     gSig->Set(maxTime+1);
323     // There is some kind of zero-suppression in the raw data, 
324     // so set up the TGraph in advance
325     for (Int_t i=0; i < maxTime; i++) {
326       gSig->SetPoint(i, i , 0);
327     }
328
329     Int_t iTime = 0;
330     do {
331       if (in.GetTime() >= gSig->GetN()) {
332           AliWarning("Too many time bins");
333           gSig->Set(in.GetTime());
334       }
335       col = in.GetColumn();
336       row = in.GetRow();
337       
338       gSig->SetPoint(in.GetTime(), in.GetTime(), in.GetSignal()) ;
339
340       if (in.GetTime() > maxTime)
341         maxTime = in.GetTime();
342       iTime++;
343     } while ((readOk = in.Next()) && !in.IsNewHWAddress());
344
345     FitRaw(gSig, signalF, amp, time) ; 
346     
347     if (amp > 0 && amp < 10000) {  //check both high and low end of
348                                    //result, 10000 is somewhat arbitrary
349       AliDebug(2,Form("id %d lowGain %d amp %g", id, lowGain, amp));
350       //cout << "col " << col-40 << " row " << row-8 << " lowGain " << lowGain << " amp " << amp << endl;
351
352       AddDigit(digitsArr, id, lowGain, (Int_t)amp, time);
353     }
354         
355     // Reset graph
356     for (Int_t index = 0; index < gSig->GetN(); index++) {
357       gSig->SetPoint(index, index, 0) ;  
358     } 
359     // Reset starting parameters for fit function
360     signalF->SetParameters(10.,0.,fTau,fOrder,5.); //reset all defaults just to be safe
361
362   }; // EMCAL entries loop
363   
364   delete signalF ; 
365   delete gSig;
366   
367   return ; 
368 }
369
370 //____________________________________________________________________________ 
371 void AliEMCALRawUtils::AddDigit(TClonesArray *digitsArr, Int_t id, Int_t lowGain, Int_t amp, Float_t time) {
372   //
373   // Add a new digit. 
374   // This routine checks whether a digit exists already for this tower 
375   // and then decides whether to use the high or low gain info
376   //
377   // Called by Raw2Digits
378   
379   AliEMCALDigit *digit = 0, *tmpdigit = 0;
380   
381   TIter nextdigit(digitsArr);
382   while (digit == 0 && (tmpdigit = (AliEMCALDigit*) nextdigit())) {
383     if (tmpdigit->GetId() == id)
384       digit = tmpdigit;
385   }
386
387   if (!digit) { // no digit existed for this tower; create one
388     if (lowGain) 
389       amp = Int_t(fHighLowGainFactor * amp); 
390     Int_t idigit = digitsArr->GetEntries();
391     new((*digitsArr)[idigit]) AliEMCALDigit( -1, -1, id, amp, time, idigit) ;   
392   }
393   else { // a digit already exists, check range 
394          // (use high gain if signal < cut value, otherwise low gain)
395     if (lowGain) { // new digit is low gain
396       if (digit->GetAmp() > fgkOverflowCut) {  // use if stored digit is out of range
397         digit->SetAmp(Int_t(fHighLowGainFactor * amp));
398         digit->SetTime(time);
399       }
400     }
401     else if (amp < fgkOverflowCut) { // new digit is high gain; use if not out of range
402       digit->SetAmp(amp);
403       digit->SetTime(time);
404     }
405   }
406 }
407
408 //____________________________________________________________________________ 
409 void AliEMCALRawUtils::FitRaw(TGraph * gSig, TF1* signalF, Float_t & amp, Float_t & time)
410 {
411   // Fits the raw signal time distribution; from AliEMCALGetter 
412
413   amp = time = 0. ; 
414   Double_t ped = 0;
415   Int_t nPed = 0;
416
417   for (Int_t index = 0; index < fNPedSamples; index++) {
418     Double_t ttime, signal;
419     gSig->GetPoint(index, ttime, signal) ; 
420     if (signal > 0) {
421       ped += signal;
422       nPed++;
423     }
424   }
425
426   if (nPed > 0)
427     ped /= nPed;
428   else {
429     AliWarning("Could not determine pedestal");   
430     ped = 10; // put some small value as first guess
431   }
432
433   Int_t max_found = 0;
434   Int_t i_max = 0;
435   Float_t max = -1;
436   Float_t max_fit = gSig->GetN();
437   Float_t min_after_sig = 9999;
438   Int_t tmin_after_sig = gSig->GetN();
439   Int_t n_ped_after_sig = 0;
440   Int_t plateau_width = 0;
441   Int_t plateau_start = 9999;
442
443   for (Int_t i=fNPedSamples; i < gSig->GetN(); i++) {
444     Double_t ttime, signal;
445     gSig->GetPoint(i, ttime, signal) ; 
446     if (!max_found && signal > max) {
447       i_max = i;
448       max = signal;
449     }
450     else if ( max > ped + fNoiseThreshold ) {
451       max_found = 1;
452       min_after_sig = signal;
453       tmin_after_sig = i;
454     }
455     if (max_found) {
456       if ( signal < min_after_sig) {
457         min_after_sig = signal;
458         tmin_after_sig = i;
459       }
460       if (i > tmin_after_sig + 5) {  // Two close peaks; end fit at minimum
461         max_fit = tmin_after_sig;
462         break;
463       }
464       if ( signal < ped + fNoiseThreshold)
465         n_ped_after_sig++;
466       if (n_ped_after_sig >= 5) {  // include 5 pedestal bins after peak
467         max_fit = i;
468         break;
469       }
470     }
471     //Add check on plateau
472     if (signal >= fgkRawSignalOverflow - fNoiseThreshold) {
473       if(plateau_width == 0) plateau_start = i;
474       plateau_width++;
475     }
476   }
477
478   if(plateau_width > 0) {
479     for(int j = 0; j < plateau_width-2; j++) {
480       //Note, have to remove the same point N times because after each
481       //remove, the positions of all subsequent points have shifted down
482       //We leave the first and last as anchor points
483       gSig->RemovePoint(plateau_start+1);
484     }
485   }
486
487   if ( max - ped > fNoiseThreshold ) { // else its noise 
488     AliDebug(2,Form("Fitting max %d ped %d", max, ped));
489     signalF->SetRange(0,max_fit);
490
491     if(max-ped > 50) 
492       signalF->SetParLimits(2,1,3);
493
494     signalF->SetParameter(4, ped) ; 
495     signalF->SetParameter(1, i_max);
496     signalF->SetParameter(0, max);
497     
498     gSig->Fit(signalF, "QROW"); // Note option 'W': equal errors on all points
499     amp = signalF->GetParameter(0); 
500     time = signalF->GetParameter(1)*GetRawFormatTimeBinWidth() - fgTimeTrigger;
501   }
502   return;
503 }
504 //__________________________________________________________________
505 Double_t AliEMCALRawUtils::RawResponseFunction(Double_t *x, Double_t *par)
506 {
507   // Matches version used in 2007 beam test
508   //
509   // Shape of the electronics raw reponse:
510   // It is a semi-gaussian, 2nd order Gamma function of the general form
511   //
512   // t' = (t - t0 + tau) / tau
513   // F = A * t**N * exp( N * ( 1 - t) )   for t >= 0
514   // F = 0                                for t < 0 
515   //
516   // parameters:
517   // A:   par[0]   // Amplitude = peak value
518   // t0:  par[1]
519   // tau: par[2]
520   // N:   par[3]
521   // ped: par[4]
522   //
523   Double_t signal ;
524   Double_t tau =par[2];
525   Double_t N =par[3];
526   Double_t ped = par[4];
527   Double_t xx = ( x[0] - par[1] + tau ) / tau ;
528
529   if (xx <= 0) 
530     signal = ped ;  
531   else {  
532     signal = ped + par[0] * TMath::Power(xx , N) * TMath::Exp(N * (1 - xx )) ; 
533   }
534   return signal ;  
535 }
536
537 //__________________________________________________________________
538 Bool_t AliEMCALRawUtils::RawSampledResponse(
539 const Double_t dtime, const Double_t damp, Int_t * adcH, Int_t * adcL) const 
540 {
541   // for a start time dtime and an amplitude damp given by digit, 
542   // calculates the raw sampled response AliEMCAL::RawResponseFunction
543
544   Bool_t lowGain = kFALSE ; 
545
546   // A:   par[0]   // Amplitude = peak value
547   // t0:  par[1]                            
548   // tau: par[2]                            
549   // N:   par[3]                            
550   // ped: par[4]
551
552   TF1 signalF("signal", RawResponseFunction, 0, GetRawFormatTimeMax(), 5);
553   signalF.SetParameter(0, damp) ; 
554   signalF.SetParameter(1, dtime + fgTimeTrigger) ; 
555   signalF.SetParameter(2, fTau) ; 
556   signalF.SetParameter(3, fOrder);
557   signalF.SetParameter(4, fgPedestalValue);
558
559   for (Int_t iTime = 0; iTime < GetRawFormatTimeBins(); iTime++) {
560     Double_t time = iTime * GetRawFormatTimeBinWidth() ;
561     Double_t signal = signalF.Eval(time) ;     
562
563     //According to Terry Awes, 13-Apr-2008
564     //add gaussian noise in quadrature to each sample
565     //Double_t noise = gRandom->Gaus(0.,fgFEENoise);
566     //signal = sqrt(signal*signal + noise*noise);
567
568     adcH[iTime] =  static_cast<Int_t>(signal + 0.5) ;
569     if ( adcH[iTime] > fgkRawSignalOverflow ){  // larger than 10 bits 
570       adcH[iTime] = fgkRawSignalOverflow ;
571       lowGain = kTRUE ; 
572     }
573
574     signal /= fHighLowGainFactor;
575
576     adcL[iTime] =  static_cast<Int_t>(signal + 0.5) ;
577     if ( adcL[iTime] > fgkRawSignalOverflow)  // larger than 10 bits 
578       adcL[iTime] = fgkRawSignalOverflow ;
579   }
580   return lowGain ; 
581 }