1 /**************************************************************************
2 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
4 * Author: The ALICE Off-line Project. *
5 * Contributors are mentioned in the code where appropriate. *
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 **************************************************************************/
18 //_________________________________________________________________________
19 // Utility Class for handling Raw data
20 // Does all transitions from Digits to Raw and vice versa,
21 // for simu and reconstruction
23 // Note: the current version is still simplified. Only
24 // one raw signal per digit is generated; either high-gain or low-gain
25 // Need to add concurrent high and low-gain info in the future
26 // No pedestal is added to the raw signal.
27 //*-- Author: Marco van Leeuwen (LBL)
29 #include "AliEMCALRawUtils.h"
39 #include "AliRunLoader.h"
40 class AliCaloAltroMapping;
41 #include "AliAltroBuffer.h"
42 #include "AliRawReader.h"
43 #include "AliCaloRawStreamV3.h"
46 #include "AliEMCALRecParam.h"
47 #include "AliEMCALLoader.h"
48 #include "AliEMCALGeometry.h"
49 class AliEMCALDigitizer;
50 #include "AliEMCALDigit.h"
51 #include "AliEMCALRawDigit.h"
53 #include "AliCaloCalibPedestal.h"
54 #include "AliCaloFastAltroFitv0.h"
55 #include "AliCaloNeuralFit.h"
56 #include "AliCaloBunchInfo.h"
57 #include "AliCaloFitResults.h"
58 #include "AliCaloRawAnalyzerFastFit.h"
59 #include "AliCaloRawAnalyzerNN.h"
60 #include "AliCaloRawAnalyzerLMS.h"
61 #include "AliCaloRawAnalyzerPeakFinder.h"
62 #include "AliCaloRawAnalyzerCrude.h"
64 ClassImp(AliEMCALRawUtils)
66 // Signal shape parameters
67 Int_t AliEMCALRawUtils::fgTimeBins = 256; // number of sampling bins of the raw RO signal (we typically use 15-50; theoretical max is 1k+)
68 Double_t AliEMCALRawUtils::fgTimeBinWidth = 100E-9 ; // each sample is 100 ns
69 Double_t AliEMCALRawUtils::fgTimeTrigger = 1.5E-6 ; // 15 time bins ~ 1.5 musec
71 // some digitization constants
72 Int_t AliEMCALRawUtils::fgThreshold = 1;
73 Int_t AliEMCALRawUtils::fgDDLPerSuperModule = 2; // 2 ddls per SuperModule
74 Int_t AliEMCALRawUtils::fgPedestalValue = 0; // pedestal value for digits2raw, default generate ZS data
75 Double_t AliEMCALRawUtils::fgFEENoise = 3.; // 3 ADC channels of noise (sampled)
77 AliEMCALRawUtils::AliEMCALRawUtils(fitAlgorithm fitAlgo)
78 : fHighLowGainFactor(0.), fOrder(0), fTau(0.), fNoiseThreshold(0),
79 fNPedSamples(0), fGeom(0), fOption(""),
80 fRemoveBadChannels(kTRUE),fFittingAlgorithm(0),
81 fTimeMin(-1.),fTimeMax(1.),
82 fUseFALTRO(kFALSE),fRawAnalyzer(0)
85 //These are default parameters.
86 //Can be re-set from without with setter functions
87 //Already set in the OCDB and passed via setter in the AliEMCALReconstructor
88 fHighLowGainFactor = 16. ; // Adjusted for a low gain range of 82 GeV (10 bits)
89 fOrder = 2; // Order of gamma fn
90 fTau = 2.35; // in units of timebin, from CERN 2007 testbeam
91 fNoiseThreshold = 3; // 3 ADC counts is approx. noise level
92 fNPedSamples = 4; // Less than this value => likely pedestal samples
93 fRemoveBadChannels = kFALSE; // Do not remove bad channels before fitting
94 fUseFALTRO = kTRUE; // Get the trigger FALTRO information and pass it to digits.
95 SetFittingAlgorithm(fitAlgo);
97 //Get Mapping RCU files from the AliEMCALRecParam
98 const TObjArray* maps = AliEMCALRecParam::GetMappings();
99 if(!maps) AliFatal("Cannot retrieve ALTRO mappings!!");
101 for(Int_t i = 0; i < 4; i++) {
102 fMapping[i] = (AliAltroMapping*)maps->At(i);
105 //To make sure we match with the geometry in a simulation file,
106 //let's try to get it first. If not, take the default geometry
107 AliRunLoader *rl = AliRunLoader::Instance();
108 if (rl && rl->GetAliRun() && rl->GetAliRun()->GetDetector("EMCAL")) {
109 fGeom = dynamic_cast<AliEMCAL*>(rl->GetAliRun()->GetDetector("EMCAL"))->GetGeometry();
111 AliDebug(1, Form("Using default geometry in raw reco"));
112 fGeom = AliEMCALGeometry::GetInstance(AliEMCALGeometry::GetDefaultGeometryName());
115 if(!fGeom) AliFatal(Form("Could not get geometry!"));
119 //____________________________________________________________________________
120 AliEMCALRawUtils::AliEMCALRawUtils(AliEMCALGeometry *pGeometry, fitAlgorithm fitAlgo)
121 : fHighLowGainFactor(0.), fOrder(0), fTau(0.), fNoiseThreshold(0),
122 fNPedSamples(0), fGeom(pGeometry), fOption(""),
123 fRemoveBadChannels(kTRUE),fFittingAlgorithm(0),
124 fTimeMin(-1.),fTimeMax(1.),
125 fUseFALTRO(kFALSE),fRawAnalyzer()
128 // Initialize with the given geometry - constructor required by HLT
129 // HLT does not use/support AliRunLoader(s) instances
130 // This is a minimum intervention solution
131 // Comment by MPloskon@lbl.gov
134 //These are default parameters.
135 //Can be re-set from without with setter functions
136 //Already set in the OCDB and passed via setter in the AliEMCALReconstructor
137 fHighLowGainFactor = 16. ; // adjusted for a low gain range of 82 GeV (10 bits)
138 fOrder = 2; // order of gamma fn
139 fTau = 2.35; // in units of timebin, from CERN 2007 testbeam
140 fNoiseThreshold = 3; // 3 ADC counts is approx. noise level
141 fNPedSamples = 4; // Less than this value => likely pedestal samples
142 fRemoveBadChannels = kFALSE; // Do not remove bad channels before fitting
143 fUseFALTRO = kTRUE; // Get the trigger FALTRO information and pass it to digits.
144 SetFittingAlgorithm(fitAlgo);
146 //Get Mapping RCU files from the AliEMCALRecParam
147 const TObjArray* maps = AliEMCALRecParam::GetMappings();
148 if(!maps) AliFatal("Cannot retrieve ALTRO mappings!!");
150 for(Int_t i = 0; i < 4; i++) {
151 fMapping[i] = (AliAltroMapping*)maps->At(i);
154 if(!fGeom) AliFatal(Form("Could not get geometry!"));
158 //____________________________________________________________________________
159 AliEMCALRawUtils::AliEMCALRawUtils(const AliEMCALRawUtils& rawU)
161 fHighLowGainFactor(rawU.fHighLowGainFactor),
164 fNoiseThreshold(rawU.fNoiseThreshold),
165 fNPedSamples(rawU.fNPedSamples),
167 fOption(rawU.fOption),
168 fRemoveBadChannels(rawU.fRemoveBadChannels),
169 fFittingAlgorithm(rawU.fFittingAlgorithm),
170 fTimeMin(rawU.fTimeMin),fTimeMax(rawU.fTimeMax),
171 fUseFALTRO(rawU.fUseFALTRO),
172 fRawAnalyzer(rawU.fRawAnalyzer)
175 fMapping[0] = rawU.fMapping[0];
176 fMapping[1] = rawU.fMapping[1];
177 fMapping[2] = rawU.fMapping[2];
178 fMapping[3] = rawU.fMapping[3];
181 //____________________________________________________________________________
182 AliEMCALRawUtils& AliEMCALRawUtils::operator =(const AliEMCALRawUtils &rawU)
184 //assignment operator
187 fHighLowGainFactor = rawU.fHighLowGainFactor;
188 fOrder = rawU.fOrder;
190 fNoiseThreshold = rawU.fNoiseThreshold;
191 fNPedSamples = rawU.fNPedSamples;
193 fOption = rawU.fOption;
194 fRemoveBadChannels = rawU.fRemoveBadChannels;
195 fFittingAlgorithm = rawU.fFittingAlgorithm;
196 fTimeMin = rawU.fTimeMin;
197 fTimeMax = rawU.fTimeMax;
198 fUseFALTRO = rawU.fUseFALTRO;
199 fRawAnalyzer = rawU.fRawAnalyzer;
200 fMapping[0] = rawU.fMapping[0];
201 fMapping[1] = rawU.fMapping[1];
202 fMapping[2] = rawU.fMapping[2];
203 fMapping[3] = rawU.fMapping[3];
210 //____________________________________________________________________________
211 AliEMCALRawUtils::~AliEMCALRawUtils() {
216 //____________________________________________________________________________
217 void AliEMCALRawUtils::Digits2Raw()
219 // convert digits of the current event to raw data
221 AliRunLoader *rl = AliRunLoader::Instance();
222 AliEMCALLoader *loader = dynamic_cast<AliEMCALLoader*>(rl->GetDetectorLoader("EMCAL"));
225 loader->LoadDigits("EMCAL");
227 TClonesArray* digits = loader->Digits() ;
230 Warning("Digits2Raw", "no digits found !");
234 static const Int_t nDDL = 12*2; // 12 SM hardcoded for now. Buffers allocated dynamically, when needed, so just need an upper limit here
235 AliAltroBuffer* buffers[nDDL];
236 for (Int_t i=0; i < nDDL; i++)
239 TArrayI adcValuesLow(fgTimeBins);
240 TArrayI adcValuesHigh(fgTimeBins);
242 // loop over digits (assume ordered digits)
243 for (Int_t iDigit = 0; iDigit < digits->GetEntries(); iDigit++) {
244 AliEMCALDigit* digit = dynamic_cast<AliEMCALDigit *>(digits->At(iDigit)) ;
245 if (digit->GetAmplitude() < fgThreshold)
255 fGeom->GetCellIndex(digit->GetId(), nSM, nModule, nIphi, nIeta);
256 fGeom->GetCellPhiEtaIndexInSModule(nSM, nModule, nIphi, nIeta,iphi, ieta) ;
258 //Check which is the RCU, 0 or 1, of the cell.
261 if (0<=iphi&&iphi<8) iRCU=0; // first cable row
262 else if (8<=iphi&&iphi<16 && 0<=ieta&&ieta<24) iRCU=0; // first half;
265 else if(8<=iphi&&iphi<16 && 24<=ieta&&ieta<48) iRCU=1; // second half;
267 else if(16<=iphi&&iphi<24) iRCU=1; // third cable row
269 if (nSM%2==1) iRCU = 1 - iRCU; // swap for odd=C side, to allow us to cable both sides the same
272 Fatal("Digits2Raw()","Non-existent RCU number: %d", iRCU);
275 Int_t iDDL = fgDDLPerSuperModule* nSM + iRCU;
277 Fatal("Digits2Raw()","Non-existent DDL board number: %d", iDDL);
279 if (buffers[iDDL] == 0) {
280 // open new file and write dummy header
281 TString fileName = AliDAQ::DdlFileName("EMCAL",iDDL);
282 //Select mapping file RCU0A, RCU0C, RCU1A, RCU1C
283 Int_t iRCUside=iRCU+(nSM%2)*2;
284 //iRCU=0 and even (0) SM -> RCU0A.data 0
285 //iRCU=1 and even (0) SM -> RCU1A.data 1
286 //iRCU=0 and odd (1) SM -> RCU0C.data 2
287 //iRCU=1 and odd (1) SM -> RCU1C.data 3
288 //cout<<" nSM "<<nSM<<"; iRCU "<<iRCU<<"; iRCUside "<<iRCUside<<endl;
289 buffers[iDDL] = new AliAltroBuffer(fileName.Data(),fMapping[iRCUside]);
290 buffers[iDDL]->WriteDataHeader(kTRUE, kFALSE); //Dummy;
293 // out of time range signal (?)
294 if (digit->GetTimeR() > GetRawFormatTimeMax() ) {
295 AliInfo("Signal is out of time range.\n");
296 buffers[iDDL]->FillBuffer((Int_t)digit->GetAmplitude());
297 buffers[iDDL]->FillBuffer(GetRawFormatTimeBins() ); // time bin
298 buffers[iDDL]->FillBuffer(3); // bunch length
299 buffers[iDDL]->WriteTrailer(3, ieta, iphi, nSM); // trailer
300 // calculate the time response function
302 Bool_t lowgain = RawSampledResponse(digit->GetTimeR(), digit->GetAmplitude(), adcValuesHigh.GetArray(), adcValuesLow.GetArray()) ;
304 buffers[iDDL]->WriteChannel(ieta, iphi, 0, GetRawFormatTimeBins(), adcValuesLow.GetArray(), fgThreshold);
306 buffers[iDDL]->WriteChannel(ieta,iphi, 1, GetRawFormatTimeBins(), adcValuesHigh.GetArray(), fgThreshold);
310 // write headers and close files
311 for (Int_t i=0; i < nDDL; i++) {
314 buffers[i]->WriteDataHeader(kFALSE, kFALSE);
319 loader->UnloadDigits();
322 //____________________________________________________________________________
323 void AliEMCALRawUtils::Raw2Digits(AliRawReader* reader,TClonesArray *digitsArr, const AliCaloCalibPedestal* pedbadmap, TClonesArray *digitsTRG)
325 // convert raw data of the current event to digits
330 Error("Raw2Digits", "no digits found !");
334 Error("Raw2Digits", "no raw reader found !");
338 AliCaloRawStreamV3 in(reader,"EMCAL",fMapping);
339 // Select EMCAL DDL's;
340 reader->Select("EMCAL",0,43); // 43 = AliEMCALGeoParams::fgkLastAltroDDL
342 // fRawAnalyzer setup
343 fRawAnalyzer->SetNsampleCut(5); // requirement for fits to be done, for the new methods
344 fRawAnalyzer->SetOverflowCut(fgkOverflowCut);
345 fRawAnalyzer->SetAmpCut(fNoiseThreshold);
346 fRawAnalyzer->SetFitArrayCut(fNoiseThreshold);
347 fRawAnalyzer->SetIsZeroSuppressed(true); // TMP - should use stream->IsZeroSuppressed(), or altro cfg registers later
349 // channel info parameters
351 Int_t caloFlag = 0; // low, high gain, or TRU, or LED ref.
353 // start loop over input stream
354 while (in.NextDDL()) {
356 // if ( in.GetDDLNumber() != 0 && in.GetDDLNumber() != 2 ) continue;
358 while (in.NextChannel()) {
360 //Check if the signal is high or low gain and then do the fit,
361 //if it is from TRU or LEDMon do not fit
362 caloFlag = in.GetCaloFlag();
363 // if (caloFlag != 0 && caloFlag != 1) continue;
364 if (caloFlag > 2) continue; // Work with ALTRO and FALTRO
366 //Do not fit bad channels of ALTRO
367 if(caloFlag < 2 && fRemoveBadChannels && pedbadmap->IsBadChannel(in.GetModule(),in.GetColumn(),in.GetRow())) {
368 //printf("Tower from SM %d, column %d, row %d is BAD!!! Skip \n", in.GetModule(),in.GetColumn(),in.GetRow());
372 vector<AliCaloBunchInfo> bunchlist;
373 while (in.NextBunch()) {
374 bunchlist.push_back( AliCaloBunchInfo(in.GetStartTimeBin(), in.GetBunchLength(), in.GetSignals() ) );
375 } // loop over bunches
378 if ( caloFlag < 2 ){ // ALTRO
382 short timeEstimate = 0;
383 Float_t ampEstimate = 0;
384 Bool_t fitDone = kFALSE;
388 if ( fFittingAlgorithm == kFastFit || fFittingAlgorithm == kNeuralNet || fFittingAlgorithm == kLMS || fFittingAlgorithm == kPeakFinder || fFittingAlgorithm == kCrude) {
389 // all functionality to determine amp and time etc is encapsulated inside the Evaluate call for these methods
390 AliCaloFitResults fitResults = fRawAnalyzer->Evaluate( bunchlist, in.GetAltroCFG1(), in.GetAltroCFG2());
392 amp = fitResults.GetAmp();
393 time = fitResults.GetTime();
394 timeEstimate = fitResults.GetMaxTimebin();
395 ampEstimate = fitResults.GetMaxSig();
396 chi2 = fitResults.GetChi2();
397 ndf = fitResults.GetNdf();
398 if (fitResults.GetStatus() == AliCaloFitResults::kFitPar) {
402 else { // for the other methods we for now use the functionality of
403 // AliCaloRawAnalyzer as well, to select samples and prepare for fits,
404 // if it looks like there is something to fit
407 Float_t pedEstimate = 0;
411 Int_t bunchIndex = 0;
413 // The PreFitEvaluateSamples + later call to FitRaw will hopefully
414 // be replaced by a single Evaluate call or so soon, like for the other
415 // methods, but this should be good enough for evaluation of
416 // the methods for now (Jan. 2010)
418 int nsamples = fRawAnalyzer->PreFitEvaluateSamples( bunchlist, in.GetAltroCFG1(), in.GetAltroCFG2(), bunchIndex, ampEstimate, maxADC, timeEstimate, pedEstimate, first, last);
420 if (ampEstimate >= fNoiseThreshold) { // something worth looking at
422 time = timeEstimate; // maxrev in AliCaloRawAnalyzer speak; comes with an offset w.r.t. real timebin
423 Int_t timebinOffset = bunchlist.at(bunchIndex).GetStartBin() - (bunchlist.at(bunchIndex).GetLength()-1);
426 if ( nsamples > 1 && maxADC<fgkOverflowCut ) { // possibly something to fit
427 FitRaw(first, last, amp, time, chi2, fitDone);
428 time += timebinOffset;
429 timeEstimate += timebinOffset;
433 } // ampEstimate check
434 } // method selection
436 if ( fitDone ) { // brief sanity check of fit results
437 Float_t ampAsymm = (amp - ampEstimate)/(amp + ampEstimate);
438 Float_t timeDiff = time - timeEstimate;
439 if ( (TMath::Abs(ampAsymm) > 0.1) || (TMath::Abs(timeDiff) > 2) ) {
440 // AliDebug(2,Form("Fit results amp %f time %f not consistent with expectations amp %f time %d", amp, time, ampEstimate, timeEstimate));
442 // for now just overwrite the fit results with the simple/initial estimate
449 if (amp >= fNoiseThreshold) { // something to be stored
450 if ( ! fitDone) { // smear ADC with +- 0.5 uniform (avoid discrete effects)
451 amp += (0.5 - gRandom->Rndm()); // Rndm generates a number in ]0,1]
454 Int_t id = fGeom->GetAbsCellIdFromCellIndexes(in.GetModule(), in.GetRow(), in.GetColumn()) ;
455 lowGain = in.IsLowGain();
457 // go from time-bin units to physical time fgtimetrigger
458 time = time * GetRawFormatTimeBinWidth(); // skip subtraction of fgTimeTrigger?
459 // subtract RCU L1 phase (L1Phase is in seconds) w.r.t. L0:
460 time -= in.GetL1Phase();
462 AliDebug(2,Form("id %d lowGain %d amp %g", id, lowGain, amp));
463 // printf("Added tower: SM %d, row %d, column %d, amp %3.2f\n",in.GetModule(), in.GetRow(), in.GetColumn(),amp);
464 AddDigit(digitsArr, id, lowGain, amp, time, chi2, ndf);
470 // if (maxTimeBin && gSig->GetN() > maxTimeBin + 10) gSig->Set(maxTimeBin + 10); // set actual max size of TGraph
471 Int_t hwAdd = in.GetHWAddress();
472 UShort_t iRCU = in.GetDDLNumber() % 2; // 0/1
473 UShort_t iBranch = ( hwAdd >> 11 ) & 0x1; // 0/1
475 // Now find TRU number
476 Int_t itru = 3 * in.GetModule() + ( (iRCU << 1) | iBranch ) - 1;
478 AliDebug(1,Form("Found TRG digit in TRU: %2d ADC: %2d",itru,in.GetColumn()));
482 Bool_t isOK = fGeom->GetAbsFastORIndexFromTRU(itru, in.GetColumn(), idtrg);
484 Int_t timeSamples[256]; for (Int_t j=0;j<256;j++) timeSamples[j] = 0;
487 for (std::vector<AliCaloBunchInfo>::iterator itVectorData = bunchlist.begin(); itVectorData != bunchlist.end(); itVectorData++)
489 AliCaloBunchInfo bunch = *(itVectorData);
491 const UShort_t* sig = bunch.GetData();
492 Int_t startBin = bunch.GetStartBin();
494 for (Int_t iS = 0; iS < bunch.GetLength(); iS++)
496 Int_t time = startBin--;
499 if ( amp ) timeSamples[nSamples++] = ( ( time << 12 ) & 0xFF000 ) | ( amp & 0xFFF );
503 if (nSamples && isOK) AddDigit(digitsTRG, idtrg, timeSamples, nSamples);
505 } // end while over channel
506 } //end while over DDL's, of input stream
508 TrimDigits(digitsArr);
513 //____________________________________________________________________________
514 void AliEMCALRawUtils::AddDigit(TClonesArray *digitsArr, Int_t id, Int_t timeSamples[], Int_t nSamples)
516 //Add raw sample to raw digit
517 new((*digitsArr)[digitsArr->GetEntriesFast()]) AliEMCALRawDigit(id, timeSamples, nSamples);
519 // Int_t idx = digitsArr->GetEntriesFast()-1;
520 // AliEMCALRawDigit* d = (AliEMCALRawDigit*)digitsArr->At(idx);
523 //____________________________________________________________________________
524 void AliEMCALRawUtils::AddDigit(TClonesArray *digitsArr, Int_t id, Int_t lowGain, Float_t amp, Float_t time, Float_t chi2, Int_t ndf) {
527 // This routine checks whether a digit exists already for this tower
528 // and then decides whether to use the high or low gain info
530 // Called by Raw2Digits
532 AliEMCALDigit *digit = 0, *tmpdigit = 0;
533 TIter nextdigit(digitsArr);
534 while (digit == 0 && (tmpdigit = (AliEMCALDigit*) nextdigit())) {
535 if (tmpdigit->GetId() == id) digit = tmpdigit;
538 if (!digit) { // no digit existed for this tower; create one
539 Int_t type = AliEMCALDigit::kHG; // use enum in AliEMCALDigit
541 amp *= fHighLowGainFactor;
542 type = AliEMCALDigit::kLGnoHG;
544 Int_t idigit = digitsArr->GetEntries();
545 new((*digitsArr)[idigit]) AliEMCALDigit( -1, -1, id, amp, time, type, idigit, chi2, ndf);
546 AliDebug(2,Form("Add digit Id %d for the first time, type %d", id, type));
547 }//digit added first time
548 else { // a digit already exists, check range
549 // (use high gain if signal < cut value, otherwise low gain)
550 if (lowGain) { // new digit is low gain
551 if (digit->GetAmplitude() > fgkOverflowCut) { // use if previously stored (HG) digit is out of range
552 digit->SetAmplitude(fHighLowGainFactor * amp);
553 digit->SetTime(time);
554 digit->SetType(AliEMCALDigit::kLG);
555 AliDebug(2,Form("Add LG digit ID %d for the second time, type %d", digit->GetId(), digit->GetType()));
557 }//new low gain digit
558 else { // new digit is high gain
559 if (amp < fgkOverflowCut) { // new digit is high gain; use if not out of range
560 digit->SetAmplitude(amp);
561 digit->SetTime(time);
562 digit->SetType(AliEMCALDigit::kHG);
563 AliDebug(2,Form("Add HG digit ID %d for the second time, type %d", digit->GetId(), digit->GetType()));
565 else { // HG out of range, just change flag value to show that HG did exist
566 digit->SetType(AliEMCALDigit::kLG);
567 AliDebug(2,Form("Change LG digit to HG, ID %d, type %d", digit->GetId(), digit->GetType()));
569 }//new high gain digit
570 }//digit existed replace it
574 //____________________________________________________________________________
575 void AliEMCALRawUtils::TrimDigits(TClonesArray *digitsArr)
577 // Remove digits with only low gain and large time
579 AliEMCALDigit *digit = 0;
581 Int_t nDigits = digitsArr->GetEntriesFast();
582 TIter nextdigit(digitsArr);
583 while ((digit = (AliEMCALDigit*) nextdigit())) {
585 //Check if only LG existed, remove if so
586 if (digit->GetType() == AliEMCALDigit::kLGnoHG) {
587 AliDebug(1,Form("Remove digit with id %d, LGnoHG",digit->GetId()));
588 digitsArr->Remove(digit);
590 //Check if time is too large or too small, remove if so
591 else if(fTimeMin > digit->GetTime() || fTimeMax < digit->GetTime()) {
592 digitsArr->Remove(digit);
593 AliDebug(1,Form("Remove digit with id %d, Bad Time %e",digit->GetId(), digit->GetTime()));
595 // Check if Chi2 is undefined
596 else if (0 > digit->GetChi2()) {
597 digitsArr->Remove(digit);
598 AliDebug(1,Form("Remove digit with id %d, Bad Chi2 %e",digit->GetId(), digit->GetChi2()));
600 //Good digit, just reassign the index of the digit in case there was a previous removal
602 digit->SetIndexInList(n);
607 digitsArr->Compress();
608 AliDebug(1,Form("N Digits before trimming : %d; after array compression %d",nDigits,digitsArr->GetEntriesFast()));
612 //____________________________________________________________________________
613 void AliEMCALRawUtils::FitRaw(const Int_t firstTimeBin, const Int_t lastTimeBin, Float_t & amp, Float_t & time, Float_t & chi2, Bool_t & fitDone) const
614 { // Fits the raw signal time distribution
616 //--------------------------------------------------
617 //Do the fit, different fitting algorithms available
618 //--------------------------------------------------
619 int nsamples = lastTimeBin - firstTimeBin + 1;
622 switch(fFittingAlgorithm) {
625 if (nsamples < 3) { return; } // nothing much to fit
626 //printf("Standard fitter \n");
628 // Create Graph to hold data we will fit
629 TGraph *gSig = new TGraph( nsamples);
630 for (int i=0; i<nsamples; i++) {
631 Int_t timebin = firstTimeBin + i;
632 gSig->SetPoint(i, timebin, fRawAnalyzer->GetReversed(timebin));
635 TF1 * signalF = new TF1("signal", RawResponseFunction, 0, GetRawFormatTimeBins(), 5);
636 signalF->SetParameters(10.,5.,fTau,fOrder,0.); //set all defaults once, just to be safe
637 signalF->SetParNames("amp","t0","tau","N","ped");
638 signalF->FixParameter(2,fTau); // tau in units of time bin
639 signalF->FixParameter(3,fOrder); // order
640 signalF->FixParameter(4, 0); // pedestal should be subtracted when we get here
641 signalF->SetParameter(1, time);
642 signalF->SetParameter(0, amp);
643 // set rather loose parameter limits
644 signalF->SetParLimits(0, 0.5*amp, 2*amp );
645 signalF->SetParLimits(1, time - 4, time + 4);
648 gSig->Fit(signalF, "QROW"); // Note option 'W': equal errors on all points
649 // assign fit results
650 amp = signalF->GetParameter(0);
651 time = signalF->GetParameter(1);
652 chi2 = signalF->GetChisquare();
655 catch (const std::exception & e) {
656 AliError( Form("TGraph Fit exception %s", e.what()) );
657 // stay with default amp and time in case of exception, i.e. no special action required
662 //printf("Std : Amp %f, time %g\n",amp, time);
663 delete gSig; // delete TGraph
667 //----------------------------
670 if (nsamples < 3) { return; } // nothing much to fit
671 //printf("LogFit \n");
673 // Create Graph to hold data we will fit
674 TGraph *gSigLog = new TGraph( nsamples);
675 for (int i=0; i<nsamples; i++) {
676 Int_t timebin = firstTimeBin + i;
677 gSigLog->SetPoint(timebin, timebin, TMath::Log(fRawAnalyzer->GetReversed(timebin) ) );
680 TF1 * signalFLog = new TF1("signalLog", RawResponseFunctionLog, 0, GetRawFormatTimeBins(), 5);
681 signalFLog->SetParameters(2.3, 5.,fTau,fOrder,0.); //set all defaults once, just to be safe
682 signalFLog->SetParNames("amplog","t0","tau","N","ped");
683 signalFLog->FixParameter(2,fTau); // tau in units of time bin
684 signalFLog->FixParameter(3,fOrder); // order
685 signalFLog->FixParameter(4, 0); // pedestal should be subtracted when we get here
686 signalFLog->SetParameter(1, time);
688 signalFLog->SetParameter(0, TMath::Log(amp));
691 gSigLog->Fit(signalFLog, "QROW"); // Note option 'W': equal errors on all points
693 // assign fit results
694 Double_t amplog = signalFLog->GetParameter(0); //Not Amp, but Log of Amp
695 amp = TMath::Exp(amplog);
696 time = signalFLog->GetParameter(1);
700 //printf("LogFit: Amp %f, time %g\n",amp, time);
704 //----------------------------
706 //----------------------------
707 }//switch fitting algorithms
712 //__________________________________________________________________
713 void AliEMCALRawUtils::FitParabola(const TGraph *gSig, Float_t & amp) const
715 //BEG YS alternative methods to calculate the amplitude
716 Double_t * ymx = gSig->GetX() ;
717 Double_t * ymy = gSig->GetY() ;
719 Double_t ymMaxX[kN] = {0., 0., 0.} ;
720 Double_t ymMaxY[kN] = {0., 0., 0.} ;
722 // find the maximum amplitude
724 for (Int_t ymi = 0; ymi < gSig->GetN(); ymi++) {
725 if (ymy[ymi] > ymMaxY[0] ) {
726 ymMaxY[0] = ymy[ymi] ; //<========== This is the maximum amplitude
727 ymMaxX[0] = ymx[ymi] ;
731 // find the maximum by fitting a parabola through the max and the two adjacent samples
732 if ( ymiMax < gSig->GetN()-1 && ymiMax > 0) {
733 ymMaxY[1] = ymy[ymiMax+1] ;
734 ymMaxY[2] = ymy[ymiMax-1] ;
735 ymMaxX[1] = ymx[ymiMax+1] ;
736 ymMaxX[2] = ymx[ymiMax-1] ;
737 if (ymMaxY[0]*ymMaxY[1]*ymMaxY[2] > 0) {
738 //fit a parabola through the 3 points y= a+bx+x*x*x
746 for (Int_t i = 0; i < kN ; i++) {
749 sx2 += ymMaxX[i]*ymMaxX[i] ;
750 sx3 += ymMaxX[i]*ymMaxX[i]*ymMaxX[i] ;
751 sx4 += ymMaxX[i]*ymMaxX[i]*ymMaxX[i]*ymMaxX[i] ;
752 sxy += ymMaxX[i]*ymMaxY[i] ;
753 sx2y += ymMaxX[i]*ymMaxX[i]*ymMaxY[i] ;
755 Double_t cN = (sx2y*kN-sy*sx2)*(sx3*sx-sx2*sx2)-(sx2y*sx-sxy*sx2)*(sx3*kN-sx*sx2);
756 Double_t cD = (sx4*kN-sx2*sx2)*(sx3*sx-sx2*sx2)-(sx4*sx-sx3*sx2)*(sx3*kN-sx*sx2) ;
757 Double_t c = cN / cD ;
758 Double_t b = ((sx2y*kN-sy*sx2)-c*(sx4*kN-sx2*sx2))/(sx3*kN-sx*sx2) ;
759 Double_t a = (sy-b*sx-c*sx2)/kN ;
760 Double_t xmax = -b/(2*c) ;
761 ymax = a + b*xmax + c*xmax*xmax ;//<========== This is the maximum amplitude
766 Double_t diff = TMath::Abs(1-ymMaxY[0]/amp) ;
769 //printf("Yves : Amp %f, time %g\n",amp, time);
774 //__________________________________________________________________
775 Double_t AliEMCALRawUtils::RawResponseFunction(Double_t *x, Double_t *par)
777 // Matches version used in 2007 beam test
779 // Shape of the electronics raw reponse:
780 // It is a semi-gaussian, 2nd order Gamma function of the general form
782 // xx = (t - t0 + tau) / tau [xx is just a convenient help variable]
783 // F = A * (xx**N * exp( N * ( 1 - xx) ) for xx >= 0
787 // A: par[0] // Amplitude = peak value
794 Double_t tau =par[2];
796 Double_t ped = par[4];
797 Double_t xx = ( x[0] - par[1] + tau ) / tau ;
802 signal = ped + par[0] * TMath::Power(xx , n) * TMath::Exp(n * (1 - xx )) ;
807 //__________________________________________________________________
808 Double_t AliEMCALRawUtils::RawResponseFunctionLog(Double_t *x, Double_t *par)
810 // Matches version used in 2007 beam test
812 // Shape of the electronics raw reponse:
813 // It is a semi-gaussian, 2nd order Gamma function of the general form
815 // xx = (t - t0 + tau) / tau [xx is just a convenient help variable]
816 // F = A * (xx**N * exp( N * ( 1 - xx) ) for xx >= 0
820 // Log[A]: par[0] // Amplitude = peak value
827 Double_t tau =par[2];
829 //Double_t ped = par[4]; // not used
830 Double_t xx = ( x[0] - par[1] + tau ) / tau ;
833 signal = par[0] - n*TMath::Log(TMath::Abs(xx)) + n * (1 - xx ) ;
835 signal = par[0] + n*TMath::Log(xx) + n * (1 - xx ) ;
840 //__________________________________________________________________
841 Bool_t AliEMCALRawUtils::RawSampledResponse(const Double_t dtime, const Double_t damp, Int_t * adcH, Int_t * adcL, const Int_t keyErr) const
843 // for a start time dtime and an amplitude damp given by digit,
844 // calculates the raw sampled response AliEMCAL::RawResponseFunction
846 Bool_t lowGain = kFALSE ;
848 // A: par[0] // Amplitude = peak value
854 TF1 signalF("signal", RawResponseFunction, 0, GetRawFormatTimeBins(), 5);
855 signalF.SetParameter(0, damp) ;
856 signalF.SetParameter(1, (dtime + fgTimeTrigger)/fgTimeBinWidth) ;
857 signalF.SetParameter(2, fTau) ;
858 signalF.SetParameter(3, fOrder);
859 signalF.SetParameter(4, fgPedestalValue);
861 Double_t signal=0.0, noise=0.0;
862 for (Int_t iTime = 0; iTime < GetRawFormatTimeBins(); iTime++) {
863 signal = signalF.Eval(iTime) ;
865 // Next lines commeted for the moment but in principle it is not necessary to add
866 // extra noise since noise already added at the digits level.
868 //According to Terry Awes, 13-Apr-2008
869 //add gaussian noise in quadrature to each sample
870 //Double_t noise = gRandom->Gaus(0.,fgFEENoise);
871 //signal = sqrt(signal*signal + noise*noise);
873 // March 17,09 for fast fit simulations by Alexei Pavlinov.
874 // Get from PHOS analysis. In some sense it is open questions.
876 noise = gRandom->Gaus(0.,fgFEENoise);
880 adcH[iTime] = static_cast<Int_t>(signal + 0.5) ;
881 if ( adcH[iTime] > fgkRawSignalOverflow ){ // larger than 10 bits
882 adcH[iTime] = fgkRawSignalOverflow ;
886 signal /= fHighLowGainFactor;
888 adcL[iTime] = static_cast<Int_t>(signal + 0.5) ;
889 if ( adcL[iTime] > fgkRawSignalOverflow) // larger than 10 bits
890 adcL[iTime] = fgkRawSignalOverflow ;
895 //__________________________________________________________________
896 void AliEMCALRawUtils::CalculateChi2(const Double_t* t, const Double_t* y, const Int_t nPoints,
897 const Double_t sig, const Double_t tau, const Double_t amp, const Double_t t0, Double_t &chi2)
900 // t[] - array of time bins
901 // y[] - array of amplitudes after pedestal subtractions;
902 // nPoints - number of points
903 // sig - error of amplitude measurement (one value for all channels)
904 // if sig<0 that mean sig=1.
905 // tau - filter time response (in timebin units)
906 // amp - amplitude at t0;
907 // t0 - time of max amplitude;
910 // ndf = nPoints - 2 when tau fixed
911 // ndf = nPoints - 3 when tau free
912 static Double_t par[5]={0.0, 0.0, 0.0, 2.0, 0.0};
917 // par[3]=n=2.; par[4]=ped=0.0
919 Double_t dy = 0.0, x = 0.0, f=0.0;
920 for(Int_t i=0; i<nPoints; i++){
922 f = RawResponseFunction(&x, par);
925 printf(" AliEMCALRawUtils::CalculateChi2 : %i : y %f -> f %f : dy %f \n", i, y[i], f, dy);
927 if(sig>0.0) chi2 /= (sig*sig);
930 //__________________________________________________________________
931 void AliEMCALRawUtils::SetFittingAlgorithm(Int_t fitAlgo)
933 //Set fitting algorithm and initialize it if this same algorithm was not set before.
934 //printf("**** Set Algorithm , number %d ****\n",fitAlgo);
936 if(fitAlgo == fFittingAlgorithm && fRawAnalyzer) {
937 //Do nothing, this same algorithm already set before.
938 //printf("**** Algorithm already set before, number %d, %s ****\n",fitAlgo, fRawAnalyzer->GetName());
941 //Initialize the requested algorithm
942 if(fitAlgo != fFittingAlgorithm || !fRawAnalyzer) {
943 //printf("**** Init Algorithm , number %d ****\n",fitAlgo);
945 fFittingAlgorithm = fitAlgo;
946 if (fRawAnalyzer) delete fRawAnalyzer; // delete prev. analyzer if existed.
948 if (fitAlgo == kFastFit) {
949 fRawAnalyzer = new AliCaloRawAnalyzerFastFit();
951 else if (fitAlgo == kNeuralNet) {
952 fRawAnalyzer = new AliCaloRawAnalyzerNN();
954 else if (fitAlgo == kLMS) {
955 fRawAnalyzer = new AliCaloRawAnalyzerLMS();
957 else if (fitAlgo == kPeakFinder) {
958 fRawAnalyzer = new AliCaloRawAnalyzerPeakFinder();
960 else if (fitAlgo == kCrude) {
961 fRawAnalyzer = new AliCaloRawAnalyzerCrude();
964 fRawAnalyzer = new AliCaloRawAnalyzer();