Project
Loading...
Searching...
No Matches
Digitizer.cxx
Go to the documentation of this file.
1// Copyright 2019-2020 CERN and copyright holders of ALICE O2.
2// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders.
3// All rights not expressly granted are reserved.
4//
5// This software is distributed under the terms of the GNU General Public
6// License v3 (GPL Version 3), copied verbatim in the file "COPYING".
7//
8// In applying this license CERN does not waive the privileges and immunities
9// granted to it by virtue of its status as an Intergovernmental Organization
10// or submit itself to any jurisdiction.
11
15
16#include "TH3.h"
17
25#include "TPCSimulation/Point.h"
29#include "TPCBase/Mapper.h"
31
32#include <fairlogger/Logger.h>
33#include <TRandom3.h>
34#include <mutex>
35
37
38using namespace o2::tpc;
39
40Digitizer::~Digitizer() = default;
41
42Digitizer::Digitizer() = default;
43
44namespace
45{
47std::mutex& calibrationMutex()
48{
49 static std::mutex mutex;
50 return mutex;
51}
52
53// splitmix64 finaliser, to derive well separated seeds from the base seed
54ULong64_t mixSeed(ULong64_t x)
55{
56 x += 0x9e3779b97f4a7c15ULL;
57 x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9ULL;
58 x = (x ^ (x >> 27)) * 0x94d049bb133111ebULL;
59 return x ^ (x >> 31);
60}
61
62// TRandom3 takes 32 bits of the seed and treats 0 as a request for a random seed
63UInt_t toTRandom3Seed(ULong64_t x)
64{
65 const UInt_t seed = static_cast<UInt_t>(x ^ (x >> 32));
66 return seed ? seed : 1;
67}
68} // namespace
69
70ElectronTransport& Digitizer::electronTransport()
71{
72 return mElectronTransport ? *mElectronTransport : ElectronTransport::instance();
73}
74
75GEMAmplification& Digitizer::gemAmplification()
76{
77 return mGEMAmplification ? *mGEMAmplification : GEMAmplification::instance();
78}
79
80SAMPAProcessing& Digitizer::sampaProcessing()
81{
82 return mSAMPAProcessing ? *mSAMPAProcessing : SAMPAProcessing::instance();
83}
84
86{
87 mUseSectorSeeding = true;
88 mSeed = seed;
89}
90
91void Digitizer::initSectorSeeding()
92{
93 if (mUseSectorSeeding && !mGEMAmplification) {
94 // the rings are filled once, in the construction order of the singletons
95 TRandom3 rng(toTRandom3Seed(mixSeed(mSeed)));
96 mGEMAmplification = std::make_unique<GEMAmplification>(&rng);
97 mElectronTransport = std::make_unique<ElectronTransport>(&rng);
98 mSAMPAProcessing = std::make_unique<SAMPAProcessing>(&rng);
99 mDigitContainer.setSAMPAProcessing(mSAMPAProcessing.get());
100 }
101}
102
104{
105 other.initSectorSeeding();
106 mUseSectorSeeding = other.mUseSectorSeeding;
107 mSeed = other.mSeed;
108 if (other.mGEMAmplification) {
109 mGEMAmplification = std::make_unique<GEMAmplification>(*other.mGEMAmplification);
110 mElectronTransport = std::make_unique<ElectronTransport>(*other.mElectronTransport);
111 mSAMPAProcessing = std::make_unique<SAMPAProcessing>(*other.mSAMPAProcessing);
112 mDigitContainer.setSAMPAProcessing(mSAMPAProcessing.get());
113 }
114}
115
117{
118 std::lock_guard<std::mutex> lock(calibrationMutex());
119 if (mUseSectorSeeding) {
120 initSectorSeeding();
121 const ULong64_t sectorSeed = mixSeed(mSeed ^ mixSeed(static_cast<ULong64_t>(mSector) + 1));
122 TRandom3 rng(toTRandom3Seed(mixSeed(sectorSeed ^ mixSeed(mSeedingTimeframe))));
123 mGEMAmplification->setRandomRingPositions(rng);
124 mElectronTransport->setRandomRingPositions(rng);
125 mSAMPAProcessing->setRandomRingPositions(rng);
126 }
127 auto& gemAmplification = this->gemAmplification();
128 gemAmplification.updateParameters();
129 auto& electronTransport = this->electronTransport();
130 electronTransport.updateParameters(mVDrift);
131 auto& sampaProcessing = this->sampaProcessing();
132 // the calibration update may reload FEE parameters from file, so SAMPAProcessing picks up its pointers afterwards
133 mDigitContainer.updateCalibrations();
134 sampaProcessing.updateParameters(mVDrift);
135}
136
137void Digitizer::process(const std::vector<o2::tpc::HitGroup>& hits,
138 const int eventID, const int sourceID)
139{
140 const Mapper& mapper = Mapper::instance();
141 auto& detParam = ParameterDetector::Instance();
142 auto& eleParam = ParameterElectronics::Instance();
143 auto& gemParam = ParameterGEM::Instance();
144
145 auto& gemAmplification = this->gemAmplification();
146 auto& electronTransport = this->electronTransport();
147 auto& sampaProcessing = this->sampaProcessing();
148
149 const int nShapedPoints = eleParam.NShapedPoints;
150 const auto amplificationMode = gemParam.AmplMode;
151 mSignalArray.resize(nShapedPoints);
152
154 mDigitContainer.reserve(sampaProcessing.getTimeBinFromTime(mEventTime - mOutputDigitTimeOffset));
155
157 float maxEleTime = (int(mDigitContainer.size()) - nShapedPoints) * eleParam.ZbinWidth;
158
159 for (auto& hitGroup : hits) {
160 const int MCTrackID = hitGroup.GetTrackID();
161 for (size_t hitindex = 0; hitindex < hitGroup.getSize(); ++hitindex) {
162 const auto& eh = hitGroup.getHit(hitindex);
163
164 GlobalPosition3D posEle(eh.GetX(), eh.GetY(), eh.GetZ());
165
166 // Distort the electron position in case space-charge distortions are used
167 if (mDistortionScaleType == 1) {
168 mSpaceCharge->distortElectron(posEle);
169 } else if (mDistortionScaleType == 2) {
170 mSpaceCharge->distortElectron(posEle, (mUseScaledDistortions ? nullptr : mSpaceChargeDer), mLumiScaleFactor);
171 }
172
175 if (electronTransport.isCompletelyOutOfSectorCoarseElectronDrift(posEle, mSector)) {
176 continue;
177 }
178
180 const int nPrimaryElectrons = static_cast<int>(eh.GetEnergyLoss());
181 const float hitTime = eh.GetTime() * 0.001;
182 float driftTime = 0.f;
183
185
187 for (int iEle = 0; iEle < nPrimaryElectrons; ++iEle) {
188
190 const GlobalPosition3D posEleDiff = electronTransport.getElectronDrift(posEle, driftTime);
191 const float eleTime = driftTime + hitTime;
192 if (eleTime >= maxEleTime) {
193 // LOG(warning) << "Skipping electron with driftTime " << driftTime << " from hit at time " << hitTime;
194 continue;
195 }
196 const float absoluteTime = eleTime + mTDriftOffset + (mEventTime - mOutputDigitTimeOffset);
197
200 if (!(absoluteTime >= 0 /* && absoluteTime <= timeframelength */)) {
201 continue;
202 }
203
205 if (electronTransport.isElectronAttachment(driftTime)) {
206 continue;
207 }
208
210 if (std::abs(posEleDiff.Z()) > detParam.TPClength) {
211 continue;
212 }
213
215 if (mapper.isOutOfSector(posEleDiff, mSector)) {
216 continue;
217 }
218
220 const DigitPos digiPadPos = mapper.findDigitPosFromGlobalPosition(posEleDiff, mSector);
221 if (!digiPadPos.isValid()) {
222 continue;
223 }
224
226 if (digiPadPos.getCRU().sector() != mSector) {
227 continue;
228 }
229
231 const int nElectronsGEM = gemAmplification.getStackAmplification(digiPadPos.getCRU(), digiPadPos.getPadPos(), amplificationMode);
232 if (nElectronsGEM == 0) {
233 continue;
234 }
235
236 const GlobalPadNumber globalPad = mapper.globalPadNumber(digiPadPos.getGlobalPadPos());
237 const float ADCsignal = sampaProcessing.getADCvalue(static_cast<float>(nElectronsGEM));
238 const MCCompLabel label(MCTrackID, eventID, sourceID, false);
239 sampaProcessing.getShapedSignal(ADCsignal, absoluteTime, mSignalArray);
240 for (float i = 0; i < nShapedPoints; ++i) {
241 const float time = absoluteTime + i * eleParam.ZbinWidth;
242 mDigitContainer.addDigit(label, digiPadPos.getCRU(), sampaProcessing.getTimeBinFromTime(time), globalPad,
243 mSignalArray[i]);
244 }
246 }
248 }
249 }
250}
251
252void Digitizer::flush(std::vector<o2::tpc::Digit>& digits,
254 std::vector<o2::tpc::CommonMode>& commonModeOutput,
255 bool finalFlush)
256{
257 SAMPAProcessing& sampaProcessing = this->sampaProcessing();
258 mDigitContainer.fillOutputContainer(digits, labels, commonModeOutput, mSector, sampaProcessing.getTimeBinFromTime(mEventTime - mOutputDigitTimeOffset), mIsContinuous, finalFlush);
259 // flushing debug output to file
260 if (mFlushDebugStreamer && ((finalFlush && mIsContinuous) || (!mIsContinuous)) && mSpaceCharge) {
261 o2::utils::DebugStreamer::instance()->flush();
262 }
263}
264
265void Digitizer::setUseSCDistortions(const SCDistortionType& distortionType, const TH3* hisInitialSCDensity)
266{
267 mUseSCDistortions = true;
268 if (!mSpaceCharge) {
269 mSpaceChargeOwned = std::make_unique<SC>();
270 mSpaceCharge = mSpaceChargeOwned.get();
271 }
272 mSpaceCharge->setSCDistortionType(distortionType);
273 if (hisInitialSCDensity) {
274 mSpaceCharge->fillChargeDensityFromHisto(*hisInitialSCDensity);
275 mSpaceCharge->setUseInitialSCDensity(true);
276 }
277}
278
280{
281 mUseSCDistortions = true;
282 if (spaceCharge != mSpaceChargeOwned.get()) {
283 mSpaceChargeOwned.reset();
284 }
285 mSpaceCharge = spaceCharge;
286 mSpaceCharge->initAfterReadingFromFile();
287 mSpaceCharge->printMetaData();
288}
289
291{
292 mSpaceChargeDer = spaceCharge;
293 mSpaceChargeDer->initAfterReadingFromFile();
294 mSpaceChargeDer->printMetaData();
295}
296
297void Digitizer::setUseSCDistortions(std::string_view finp)
298{
299 mUseSCDistortions = true;
300 if (!mSpaceCharge) {
301 mSpaceChargeOwned = std::make_unique<SC>();
302 mSpaceCharge = mSpaceChargeOwned.get();
303 }
304
305 // in case analytical distortions are loaded from file they are applied
307 if (!mSpaceCharge->getUseAnalyticalDistCorr()) {
308 mSpaceCharge->setGlobalDistortionsFromFile(finp, Side::A);
309 mSpaceCharge->setGlobalDistortionsFromFile(finp, Side::C);
310 }
311}
312
314{
315 // this is setting the first timebin index for the digit container
316 // note that negative times w.r.t start of timeframe/data-taking == mOutputDigitTimeOffset
317 // will yield the 0-th bin (due to casting logic in sampaProcessing)
318 SAMPAProcessing& sampaProcessing = this->sampaProcessing();
319 {
320 std::lock_guard<std::mutex> lock(calibrationMutex());
321 sampaProcessing.updateParameters(mVDrift);
322 }
323 const auto timediff = time - mOutputDigitTimeOffset;
324 const auto starttimebin = sampaProcessing.getTimeBinFromTime(timediff);
325 mDigitContainer.setStartTime(starttimebin);
326}
327
329{
330 mSpaceChargeOwned.reset();
331 mSpaceCharge = other.mSpaceCharge;
332 mSpaceChargeDer = other.mSpaceChargeDer;
333 mUseSCDistortions = other.mUseSCDistortions;
334 mLumiScaleFactor = other.mLumiScaleFactor;
335 mUseScaledDistortions = other.mUseScaledDistortions;
336}
337
339{
340 mLumiScaleFactor = (CorrMapParam::Instance().lumiInst - mSpaceCharge->getMeanLumi()) / mSpaceChargeDer->getMeanLumi();
341 LOGP(info, "Setting Lumi scale factor: lumiInst: {} lumi mean: {} lumi mean derivative: {} lumi scale factor: {}", CorrMapParam::Instance().lumiInst, mSpaceCharge->getMeanLumi(), mSpaceChargeDer->getMeanLumi(), mLumiScaleFactor);
342}
343
345{
346 mSpaceCharge->setMeanLumi(meanLumi);
347}
348
350{
351 mSpaceChargeDer->setMeanLumi(meanLumi);
352}
353
355{
356 if (!mSpaceCharge || !mSpaceChargeDer) {
357 LOGP(info, "Average or derivative distortions not set");
358 return;
359 }
360
361 // recalculate distortions only in case the inst lumi differs from the avg lumi
362 if (mSpaceCharge->getMeanLumi() != CorrMapParam::Instance().lumiInst) {
363 for (int iside = 0; iside < 2; ++iside) {
364 const o2::tpc::Side side = (iside == 0) ? Side::A : Side::C;
365 // this needs to be done only once
366 LOGP(info, "Calculating corrections for average distortions");
367 mSpaceCharge->calcGlobalCorrWithGlobalDistIterative(side, nullptr, 0);
368
369 LOGP(info, "Calculating corrections for derivative distortions");
370 mSpaceChargeDer->calcGlobalCorrWithGlobalDistIterative(side, nullptr, 0);
371
372 LOGP(info, "Calculating scaled distortions with scaling factor {}", mLumiScaleFactor);
373 mSpaceCharge->calcGlobalDistWithGlobalCorrIterativeLinearCartesian(side, mSpaceChargeDer, mLumiScaleFactor);
374 }
375 // set new lumi of avg map
376 mSpaceCharge->setMeanLumi(CorrMapParam::Instance().lumiInst);
377 } else {
378 LOGP(info, "Inst. lumi {} is same as mean lumi {}. Skip recalculation of distortions", CorrMapParam::Instance().lumiInst, mSpaceCharge->getMeanLumi());
379 }
380
381 mUseScaledDistortions = true;
382}
Simple interface to the CDB manager.
Implementation of the parameter class for the CorrectionMapsLoader options.
Definition of the electron transport.
int16_t time
Definition RawEventData.h:4
Definition of the GEM amplification.
int32_t i
std::vector< o2::MCCompLabel > labels
Definition of the parameter class for the detector.
Definition of the parameter class for the detector electronics.
Definition of the parameter class for the GEM stack.
Definition of the parameter class for the detector gas.
Class for TPC Point.
uint32_t side
Definition RawData.h:0
Definition of the SAMPA response.
This class contains the algorithms for calculation the distortions and corrections.
Definition of the ALICE TPC digitizer.
ClassImp(o2::tpc::Digitizer)
A container to hold and manage MC truth information/labels.
const Sector sector() const
Definition CRU.h:65
void setStartTime(TimeBin time)
void setSAMPAProcessing(SAMPAProcessing *sampaProcessing)
Use this SAMPAProcessing instead of the singleton when filling the output.
size_t size() const
Get the size of the container for one event.
void fillOutputContainer(std::vector< Digit > &output, dataformats::MCTruthContainer< MCCompLabel > &mcTruth, std::vector< CommonMode > &commonModeOutput, const Sector &sector, TimeBin eventTimeBin=0, bool isContinuous=true, bool finalFlush=false)
void addDigit(const MCCompLabel &label, const CRU &cru, TimeBin timeBin, GlobalPadNumber globalPad, float signal)
void reserve(TimeBin eventTimeBin)
Reserve space in the container for a given event.
const CRU & getCRU() const
Definition DigitPos.h:30
bool isValid() const
Definition DigitPos.h:38
PadPos getGlobalPadPos() const
Definition DigitPos.cxx:20
PadPos getPadPos() const
Definition DigitPos.h:32
void setMeanLumiDistortions(float meanLumi)
void setUseSCDistortions(const SCDistortionType &distortionType, const TH3 *hisInitialSCDensity)
void setMeanLumiDistortionsDerivative(float meanLumi)
void flush(std::vector< o2::tpc::Digit > &digits, o2::dataformats::MCTruthContainer< o2::MCCompLabel > &labels, std::vector< o2::tpc::CommonMode > &commonModeOutput, bool finalFlush=false)
void setUseSectorSeeding(ULong64_t seed)
Definition Digitizer.cxx:85
void setSCDistortionsFrom(const Digitizer &other)
Use the distortion maps and scaling of another digitizer, which keeps ownership of the maps.
void setSCDistortionsDerivative(SC *spaceCharge)
void setStartTime(double time)
void recalculateDistortions()
in case of scaled distortions, the distortions can be recalculated to ensure consistent distortions a...
void process(const std::vector< o2::tpc::HitGroup > &hits, const int eventID, const int sourceID=0)
~Digitizer()
Destructor.
void setSectorSeedingFrom(Digitizer &other)
Use copies of the sector-seeding random rings of another digitizer, which fills them if needed.
void init()
Initializer.
Digitizer()
Default constructor.
bool isElectronAttachment(float driftTime)
void updateParameters(float vdrift=0)
Update the OCDB parameters cached in the class. To be called once per event.
bool isCompletelyOutOfSectorCoarseElectronDrift(GlobalPosition3D posEle, const Sector &sector) const
GlobalPosition3D getElectronDrift(GlobalPosition3D posEle, float &driftTime)
static ElectronTransport & instance()
void updateParameters()
Update the OCDB parameters cached in the class. To be called once per event.
int getStackAmplification(int nElectrons=1)
static GEMAmplification & instance()
Default constructor.
GlobalPadNumber globalPadNumber(const PadPos &globalPadPosition) const
Definition Mapper.h:56
const DigitPos findDigitPosFromGlobalPosition(const GlobalPosition3D &pos) const
Definition Mapper.h:716
bool isOutOfSector(GlobalPosition3D posEle, const Sector &sector, const float margin=0.f) const
Definition Mapper.h:739
static Mapper & instance(const std::string mappingDir="")
Definition Mapper.h:44
void getShapedSignal(float ADCsignal, float driftTime, std::vector< float > &signalArray) const
T getADCvalue(T nElectrons) const
static SAMPAProcessing & instance()
void updateParameters(float vdrift=0)
Update the OCDB parameters cached in the class. To be called once per event.
TimeBin getTimeBinFromTime(float time) const
bool getUseAnalyticalDistCorr() const
void printMetaData() const
void setAnalyticalCorrectionsDistortionsFromFile(std::string_view inpf)
void setUseInitialSCDensity(const bool useInitialSCDensity)
void calcGlobalCorrWithGlobalDistIterative(const Side side, const SpaceCharge< DataT > *scSCale=nullptr, float scale=0, const int maxIter=100, const DataT approachZ=1, const DataT approachR=1, const DataT approachPhi=1, const DataT diffCorr=50e-6)
void setGlobalDistortionsFromFile(std::string_view file, const Side side)
float getMeanLumi() const
static void setSCDistortionType(SCDistortionType distortionType)
void setMeanLumi(float lumi)
void calcGlobalDistWithGlobalCorrIterativeLinearCartesian(const Side side, const SpaceCharge< DataT > *scSCale=nullptr, float scale=0, const int maxIter=100, const DataT approachX=1, const DataT approachY=1, const DataT approachZ=1, const DataT diffCorr=50e-6)
void fillChargeDensityFromHisto(const TH3 &hisSCDensity3D)
void distortElectron(GlobalPosition3D &point, const SpaceCharge< DataT > *scSCale=nullptr, float scale=0) const
GLint GLenum GLint x
Definition glcorearb.h:403
GLuint GLsizei const GLchar * label
Definition glcorearb.h:2519
int const float const TrackSeed< NLayers > & seed
Global TPC definitions and constants.
math_utils::Point3D< float > GlobalPosition3D
Definition Defs.h:110
Side
TPC readout sidE.
Definition Defs.h:37
@ A
Definition Defs.h:37
@ C
Definition Defs.h:38
unsigned short GlobalPadNumber
global pad number
Definition Defs.h:114
SCDistortionType
Enumerator for setting the space-charge distortion mode.
Definition SpaceCharge.h:57
VectorOfTObjectPtrs other
std::vector< Digit > digits