ATLAS Offline Software
Loading...
Searching...
No Matches
MuonPhaseII/MuonDigitization/sTgcDigitizationR4/src/sTgcDigitMaker.cxx
Go to the documentation of this file.
1/*
2 Copyright (C) 2002-2025 CERN for the benefit of the ATLAS collaboration
3*/
4
7#include "CLHEP/Units/SystemOfUnits.h"
8#include "CLHEP/Random/RandomEngine.h"
9#include "CLHEP/Random/RandFlat.h"
10#include "CLHEP/Random/RandGaussZiggurat.h"
11#include "CLHEP/Random/RandGamma.h"
13
14#include "Acts/Utilities/detail/Polynomials.hpp"
15
16#include "TF1.h"
17#include <cmath>
18#include <iostream>
19#include <fstream>
20#include <algorithm>
21#include <ranges>
22
23namespace MuonR4{
24//---------------------------------------------------
25// Constructor and Destructor
26//---------------------------------------------------
28
30 digitMode mode,
31 double meanGasGain,
32 bool doPadChargeSharing)
33 : AthMessaging("sTgcDigitMaker"),
34 m_detMgr{detMgr},
35 m_digitMode(mode),
36 m_meanGasGain{meanGasGain},
37 m_doPadSharing{doPadChargeSharing}{}
38
40
41//------------------------------------------------------
42// Initialize digitization parameters
43//------------------------------------------------------
45 // Read arrival time data
47
48 // Read strip time correction if enabled
51 }
52
53 return StatusCode::SUCCESS;
54}
55
56//------------------------------------------------------
57// Compute ionization point for a hit
58//------------------------------------------------------
60 const DigiConditions& condContainers,
61 Ionization& ionization) const {
62 const MuonGMR4::sTgcReadoutElement* reEle = m_detMgr->getsTgcReadoutElement(hit->identify());
63
64 // Projecting the hit position on wire surface
65 const Amg::Vector3D locHitDir = xAOD::toEigen(hit->localDirection());
66 const Amg::Vector3D locHitPos = xAOD::toEigen(hit->localPosition());
67 ATH_MSG_VERBOSE("sTgc hit: time " << hit->globalTime()
68 << " position " << Amg::toString(locHitPos, 2) << " direction" << Amg::toString(locHitDir, 2)
69 << " mclink " << hit->genParticleLink() << " PDG ID " << hit->pdgId() );
70
71 Amg::Vector3D hitOnWireSurf = locHitPos;
72 const double scale = Amg::intersect<3>(locHitPos, locHitDir, Amg::Vector3D::UnitZ(), 0.).value_or(0);
73 const double halfStep = 0.5 * hit->stepLength();
74
75 // If Geant step length is smaller than the scale to wire plane, use the steplength
76 // to find the closest point to the wire plane.
77 if (std::abs(scale) <= halfStep) {
78 hitOnWireSurf = locHitPos + scale * locHitDir;
79 }
80 else {
81 hitOnWireSurf = locHitPos + Acts::copySign(halfStep, scale) * locHitDir;
82 }
83
84 const Identifier hitId = hit->identify();
85 const IdentifierHash wireLayHash = reEle->createHash(m_idHelper.gasGap(hitId),
86 ReadoutChannelType::Wire, 1);
87 const MuonGMR4::WireGroupDesign& wireDesign{reEle->wireDesign(wireLayHash)};
88 const MuonGMR4::StripLayer& stripLayer = reEle->stripLayer(wireLayHash);
89 const Amg::Vector2D hitOnWire2D = stripLayer.to2D(hitOnWireSurf, true);
90
91 if(!wireDesign.insideTrapezoid(hitOnWire2D)) {
92 return false;
93 }
94
95 // Check to see if a valid wire exists for the hit on wire surface, if not
96 // revert back to hit position, prestep and poststep, and check if there is a
97 // wire close to it, else, skip the hit.
98 std::pair<int, int> wireGrpWireNum = wireDesign.wireNumber(hitOnWire2D);
99
100 // Check if hit position gives valid wire group number
101 if (wireGrpWireNum.first < 0) {
102 const Amg::Vector2D locHitPos2D = stripLayer.to2D(locHitPos, true);
103 wireGrpWireNum = wireDesign.wireNumber(locHitPos2D);
104
105 // Check if prestep position gives valid wire group number
106 if (wireGrpWireNum.first < 0) {
107 const Amg::Vector3D preStepPos = locHitPos - halfStep * locHitDir;
108 const Amg::Vector2D preStepPos2D = stripLayer.to2D(preStepPos, true);
109 wireGrpWireNum = wireDesign.wireNumber(preStepPos2D);
110
111 // Check if poststep position gives valid wire group number
112 if (wireGrpWireNum.first < 0) {
113 const Amg::Vector3D postStepPos = locHitPos + halfStep * locHitDir;
114 const Amg::Vector2D postStepPos2D = stripLayer.to2D(postStepPos, true);
115 wireGrpWireNum = wireDesign.wireNumber(postStepPos2D);
116
117 // else return empty digit
118 if (wireGrpWireNum.first < 0) {
119 ATH_MSG_WARNING(__func__<<"() "<<__LINE__<<" - Unable to retrieve the wire number, skipping the hit: "
120 << m_idHelperSvc->toString(hitId)<<" @"<<Amg::toString(locHitPos2D));
121 return false;
122 }
123 }
124 }
125 }
126 int wireNumber = wireDesign.numPitchesToGroup(wireGrpWireNum.first) + wireGrpWireNum.second;
127 const int numWires = wireDesign.nAllWires();
128
129 if((wireNumber < 1) || (wireNumber > numWires)) {
130 ATH_MSG_WARNING(__func__<<"() "<<__LINE__<<" - Unable to retrieve the wire number, skipping the hit: "
131 << m_idHelperSvc->toString(hitId)<<" @"<<Amg::toString(hitOnWire2D));
132 return false;
133 }
134
135 // Compute the position of the ionization and its distance to the closest wire
136 ionization = pointClosestApproach(stripLayer, wireNumber, locHitPos, locHitDir, hit->stepLength());
137 double distToWire = ionization.distance;
138
139 if(distToWire > 0.) {
140 // Determine on which side of the wire does the particle cross
141 int adjacent = Acts::copySign(1, ionization.posOnSegment.y() - ionization.posOnWire.y());
142
143 Ionization ionizationAdj = pointClosestApproach(stripLayer, wireNumber+adjacent, locHitPos, locHitDir, hit->stepLength());
144 double distToWireAdj = ionizationAdj.distance;
145
146 if ((distToWireAdj > 0.) && (distToWireAdj < distToWire)) {
147 distToWire = distToWireAdj;
148 wireNumber += adjacent;
149 ionization = std::move(ionizationAdj);
150 }
151 } else {
152 ATH_MSG_DEBUG("Failed to get the distance between the wire " << wireNumber << " and hit " << Amg::toString(hitOnWire2D, 2));
153 return false;
154 }
155
156 // Do not digitize hits that are too far from the nearest wire
157 if (distToWire > wireDesign.stripPitch()) {
158 ATH_MSG_DEBUG("Distance to nearest wire: " << distToWire << " greater than wirePitch.");
159 return false;
160 }
161
162 // Get the gamma pdf parameters and calculate digit time
163 const GammaParameter gamParam = getGammaParameter(distToWire);
164 const double most_prob_time = getMostProbableArrivalTime(distToWire);
165 const double gamma_mpv = std::max((gamParam.kParameter - 1) * gamParam.thetaParameter, 0.);
166 const double t0_par = most_prob_time - gamma_mpv;
167 const double inv_theta = 1./gamParam.thetaParameter;
168
169 double digitTime = t0_par + CLHEP::RandGamma::shoot(condContainers.rndEngine, gamParam.kParameter, inv_theta);
170
171 constexpr unsigned shoot_limit = 4;
172 unsigned shoot_counter = 0;
173 while (digitTime < 0. && ++shoot_counter <= shoot_limit) {
174 digitTime = t0_par + CLHEP::RandGamma::shoot(condContainers.rndEngine, gamParam.kParameter,inv_theta);
175 }
176
177 ionization.time = std::max(0., digitTime);
178 return true;
179}
180
181//------------------------------------------------------
182// Calculate total charge from energy deposit
183//------------------------------------------------------
184double sTgcDigitMaker::calculateTotalCharge(double energyDeposit, CLHEP::HepRandomEngine* rndEngine) const {
185 // Ionized charge in pC per keV deposited
186 const double ionized_charge = (5.65E-6) * energyDeposit / CLHEP::keV;
187
188 // Calculate avalanche gain using gamma distribution (Polya function approximation)
189 const double gain = CLHEP::RandGamma::shoot(rndEngine, 1. + m_theta, (1. + m_theta) / m_meanGasGain);
190
191 return gain * ionized_charge;
192}
193
194//------------------------------------------------------
195// Execute digitization for a given hit
196//------------------------------------------------------
198 const TimedHit& hit) const {
199 sTgcDigitVec allDigits{};
200 // Extract energy deposit from the hit
201 const double energyDeposit = hit->energyDeposit();
202 if (energyDeposit < std::numeric_limits<float>::epsilon()) {
203 return allDigits; // Ignore hits with no energy deposit
204 }
205
206 // Retrieve the detector element for the given hit
207 const Identifier hitId = hit->identify();
208
209 // HV efficiency correction
210 if (condContainers.efficiencies) {
211 const double efficiency = condContainers.efficiencies->getEfficiency(hitId);
212 if (CLHEP::RandFlat::shoot(condContainers.rndEngine,0.0,1.0) > efficiency) {
213 return allDigits;
214 }
215 }
216
217
218 ATH_MSG_DEBUG("Retrieving detector element for: "<< m_idHelperSvc->toStringDetEl(hitId)
219 << " energyDeposit "<< energyDeposit );
220
221
222 // Get ionization point and time
223 Ionization ionization{};
224 if (!getIonizationPoint(hit, condContainers, ionization)) {
225 ATH_MSG_DEBUG("Failed to get ionization point for hit "<< m_idHelperSvc->toStringDetEl(hitId));
226 return allDigits;
227 }
228
229 DigiInput digiInput{};
230 digiInput.hitId = hitId;
231 digiInput.totalCharge = calculateTotalCharge(energyDeposit, condContainers.rndEngine);
232 digiInput.time = ionization.time;
233 digiInput.posOnSurf = ionization.posOnWire;
234 digiInput.hitDir = xAOD::toEigen(hit->localDirection());
235 digiInput.reEle = m_detMgr->getsTgcReadoutElement(hitId);
236
237 ATH_MSG_DEBUG("Ionization_info: distance: " << ionization.distance
238 << " locHitPos: " <<Amg::toString(xAOD::toEigen(hit->localPosition()), 3)
239 << " locHitDir: " <<Amg::toString(xAOD::toEigen(hit->localDirection()), 3)
240 << " posOnTrack: " <<Amg::toString(ionization.posOnSegment, 3)
241 << " posOnWire: " << Amg::toString(ionization.posOnWire, 3)
242 << " total charge: " << calculateTotalCharge(energyDeposit, condContainers.rndEngine)
243 << " EDep: " << energyDeposit
244 <<" "<<m_idHelperSvc->toStringGasGap(hitId));
245
246 //##################################################################################
247 //######################################### strip readout ##########################
248 //##################################################################################
249 sTgcDigitVec stripDigits = processStripDigitization(condContainers, digiInput);
250
252 ATH_MSG_WARNING("Only digitize strip response !");
253 return stripDigits;
254 }
255 std::ranges::move(stripDigits, std::back_inserter(allDigits));
256
257 //##################################################################################
258 //######################################### pad readout ############################
259 //##################################################################################
260 sTgcDigitVec padDigits = processPadDigitization(digiInput);
261
262 std::ranges::move(padDigits, std::back_inserter(allDigits));
263
265 ATH_MSG_WARNING("Only digitize strip/pad response !");
266 return allDigits;
267 }
268
269 //##################################################################################
270 //######################################### wire readout ###########################
271 //##################################################################################
272 sTgcDigitVec wireDigits = processWireDigitization(digiInput);
273 std::ranges::move(wireDigits, std::back_inserter(allDigits));
274
275 return allDigits;
276}
277
278//------------------------------------------------------
279// Process strip digitization
280//------------------------------------------------------
282 const DigiInput& digiInput) const {
283 ATH_MSG_DEBUG("sTgcDigitMaker::strip response ");
284
285 const int gasGap = m_idHelper.gasGap(digiInput.hitId);
286 const IdentifierHash stripLayHash = digiInput.reEle->createHash(gasGap,
287 ReadoutChannelType::Strip, 1);
288 const Identifier stripLayId = digiInput.reEle->measurementId(stripLayHash);
289 const MuonGMR4::StripDesign& stripDesign{digiInput.reEle->stripDesign(stripLayHash)};
290 const Amg::Vector2D hitOnStripSurf = digiInput.reEle->stripLayer(stripLayHash).to2D(digiInput.posOnSurf, false);
291
292 if(!stripDesign.insideTrapezoid(hitOnStripSurf)) {
293 ATH_MSG_DEBUG("Outside of the strip surface boundary : "
294 << m_idHelperSvc->toString(stripLayId)
295 << "; local position " <<Amg::toString(hitOnStripSurf, 2));
296 return {};
297 }
298
299 constexpr double tolerance_length = 0.01*Gaudi::Units::mm;
300 int stripNumber = stripDesign.stripNumber(hitOnStripSurf);
301 if( stripNumber < 0){
302 const double newPosX = hitOnStripSurf.x() - std::copysign(tolerance_length, hitOnStripSurf.x());
303 const Amg::Vector2D newPos(newPosX, hitOnStripSurf.y());
304 stripNumber = stripDesign.stripNumber(newPos);
305 if (stripNumber < 0) {
306 ATH_MSG_WARNING("Failed to obtain strip number " << m_idHelperSvc->toString(stripLayId) );
307 return {};
308 }
309 }
310
311
312 const double tan_theta = digiInput.hitDir.perp() / digiInput.hitDir.z();
313 const double angle_dependency = std::hypot(m_posResIncident, m_posResAngular * tan_theta);
314
315 const double peak_position = CLHEP::RandGaussZiggurat::shoot(condContainers.rndEngine,
316 hitOnStripSurf.x(), m_StripResolution*angle_dependency);
317 ATH_MSG_VERBOSE(__func__<<"() - "<<__LINE__<<" Smeared hit from "<<hitOnStripSurf.x()<<" -> "<<
318 peak_position<<". Assign strip charges");
319 return processStripChargeSharing(digiInput,
320 peak_position,
321 stripNumber);
322}
323//------------------------------------------------------
324// Process strip charge sharing across neighboring strips
325//------------------------------------------------------
327 const double peak_position,
328 const int stripNumber) const {
329
330 const double norm = 0.5 * digiInput.totalCharge;
331
332 sTgcDigitVec digits{};
333 const double tan_theta = digiInput.hitDir.perp() / digiInput.hitDir.z();
334
335 constexpr double tolerance_charge = 0.0005;
336 constexpr int max_neighbor = 10;
337
338 const int gasGap = m_idHelper.gasGap(digiInput.hitId);
339 const auto& design = digiInput.reEle->stripDesign(digiInput.reEle->measurementHash(digiInput.hitId));
340 // Upper half of the strip cluster
341 for (int sign : {-1, 1}) {
342 for (int iStrip = 0; iStrip <= max_neighbor; ++iStrip) {
343
344 if (iStrip == 0 && sign == +1) continue; // center only once
345 int currentStrip = stripNumber + sign*iStrip;
346 if (currentStrip > design.numStrips() || currentStrip < 1) {
347 ATH_MSG_VERBOSE(__func__<<"() - "<<__LINE__<<" Breaking the upper half strip loop stripNumber: "
348 << currentStrip << " > " << design.numStrips());
349 break;
350 }
351 bool isValid = false;
352 const Identifier currentStripId = m_idHelper.channelID(digiInput.hitId,
353 digiInput.reEle->multilayer(),
354 gasGap, ReadoutChannelType::Strip,
355 currentStrip, isValid);
356 if (!isValid) {
357 continue;
358 }
359 const Amg::Vector2D currentStripPos = digiInput.reEle->localChannelPosition(digiInput.reEle->measurementHash(currentStripId));
360 const double x_relative = (currentStripPos.x() - peak_position);
361 const double normX = x_relative / design.stripPitch();
362 const double charge = std::hypot(1., m_chargeAngularFactor * tan_theta) * norm *
363 chargeIntegral(normX - 0.5, normX + 0.5);
364
365 if (charge < tolerance_charge) {
366 ATH_MSG_VERBOSE(__func__<<"() - "<<__LINE__<<" Breaking the upper half strip loop stripCharge: "
367 << charge << " < " << tolerance_charge);
368 break;
369 }
370
371 double strip_time = digiInput.time;
373 const bool shift = ((iStrip > 0) && ((x_relative + (0.5*0.75 - iStrip) * design.stripPitch()) < 0));
374 strip_time += getTimeOffsetStrip(iStrip - shift);
375 }
376
377 addDigit(digits, currentStripId, strip_time, charge);
378 ATH_MSG_VERBOSE(__func__<<"() - "<<__LINE__<<" Created a strip digit: strip number = "
379 << currentStrip << ", charge = " << charge);
380 }
381 }
382
383 return digits;
384}
385
386
387//------------------------------------------------------
388// Process pad digitization
389//------------------------------------------------------
391 ATH_MSG_DEBUG("sTgcDigitMaker::pad response ");
392
393 const int gasGap = m_idHelper.gasGap(digiInput.hitId);
394 const IdentifierHash padLayHash = digiInput.reEle->createHash(gasGap,ReadoutChannelType::Pad, 1);
395 const Amg::Vector2D hitOnPadSurf = digiInput.reEle->stripLayer(padLayHash).to2D(digiInput.posOnSurf, true);
396 const MuonGMR4::PadDesign& padDesign{digiInput.reEle->padDesign(padLayHash)};
397 if(!padDesign.insideTrapezoid(hitOnPadSurf)) {
398 ATH_MSG_DEBUG(__func__<<"() -"<<__LINE__<<" Outside of the pad surface boundary :"
399 << m_idHelperSvc->toString(digiInput.hitId)
400 << " local position " <<Amg::toString(hitOnPadSurf, 2));
401 return {};
402 }
403
404 constexpr double tolerance_length = 0.01*Gaudi::Units::mm;
405 auto [padEta, padPhi] = padDesign.channelNumber(hitOnPadSurf);
406
407 if( padEta < 1 || padPhi < 1){
408 const double newPosX = hitOnPadSurf.x() - std::copysign(tolerance_length, hitOnPadSurf.x());
409 const double newPosY = hitOnPadSurf.y() - std::copysign(tolerance_length, hitOnPadSurf.y());
410 const Amg::Vector2D newPosition(newPosX, newPosY);
411 auto [newPadEta, newPadPhi] = padDesign.channelNumber(newPosition);
412 padEta = newPadEta;
413 padPhi = newPadPhi;
414 if( padEta < 1 || padPhi < 1) {
415 ATH_MSG_WARNING("Failed to obtain pad number for " << m_idHelperSvc->toString(digiInput.hitId) );
416 return {};
417 }
418 }
419
420 return processPadChargeSharing(digiInput, padEta, padPhi);
421}
422
423//------------------------------------------------------
424// Process pad charge sharing
425//------------------------------------------------------
427 const int padEta,
428 const int padPhi) const {
429
430 bool isValid = false;
431 const int gasGap = m_idHelper.gasGap(digiInput.hitId);
432 const Identifier padHitId = m_idHelper.padID(digiInput.hitId,
433 digiInput.reEle->multilayer(),
434 gasGap, ReadoutChannelType::Pad, padEta, padPhi, isValid);
435 if(!isValid) {
436 return {};
437 }
438 sTgcDigitVec digits{};
439
440 const IdentifierHash padHitHash = digiInput.reEle->measurementHash(padHitId);
441 const MuonGMR4::PadDesign& padDesign{digiInput.reEle->padDesign(padHitHash)};
442
443 const Amg::Vector2D padPos = digiInput.reEle->localChannelPosition(padHitHash);
444 const Amg::Vector2D hitOnPadSurf = digiInput.reEle->stripLayer(padHitHash).to2D(digiInput.posOnSurf, true);
445
446 const Amg::Vector2D diff = hitOnPadSurf - padPos;
447 const double halfPadHeight = 0.5 * digiInput.reEle->padHeight(padHitHash);
448
449 const std::array<Amg::Vector2D, 4> padHitCorners = padDesign.padCorners(std::make_pair(padEta, padPhi));
450 const double padBottomBase = (padHitCorners[0] - padHitCorners[1]).norm();
451 const double padTopBase = (padHitCorners[2] - padHitCorners[3]).norm();
452 const double halfPadWidth = 0.5 * padBottomBase + 0.25 * (1 + diff.y()/halfPadHeight) * (padTopBase - padBottomBase);
453
454 double deltaX = halfPadWidth - std::abs(diff.x());
455 double deltaY = halfPadHeight - std::abs(diff.y());
456 const bool isNeighX = deltaX < 2.5*m_clusterParams[1];
457 const bool isNeighY = deltaY < 2.5*m_clusterParams[1];
458
459 if (deltaX < 0.) {
460 deltaX = 0.1;
461 }
462 if (deltaY < 0.) {
463 deltaY = 0.1;
464 }
465
466 if (m_doPadSharing && (isNeighX || isNeighY)) {
467 unsigned newPhi = padPhi - Acts::copySign(1, diff.x());
468 unsigned newEta = padEta + Acts::copySign(1, diff.y());
469 bool validEta = newEta > 0 && newEta <= digiInput.reEle->numPadEta(padHitHash);
470 bool validPhi = newPhi > 0 && newPhi <= digiInput.reEle->numPadPhi(padHitHash);
471
472 if (isNeighX && isNeighY && validEta && validPhi) {
473 const Identifier neigh_ID_X = m_idHelper.padID(padHitId, digiInput.reEle->multilayer(),
474 gasGap, ReadoutChannelType::Pad,
475 padEta, newPhi);
476 const Identifier neigh_ID_Y = m_idHelper.padID(padHitId, digiInput.reEle->multilayer(), gasGap,
477 ReadoutChannelType::Pad, newEta, padPhi);
478 const Identifier neigh_ID_XY = m_idHelper.padID(padHitId, digiInput.reEle->multilayer(), gasGap,
479 ReadoutChannelType::Pad, newEta, newPhi);
480 double xQfraction = getPadChargeFraction(deltaX);
481 double yQfraction = getPadChargeFraction(deltaY);
482
483 addDigit(digits, neigh_ID_X, digiInput.time, xQfraction*(1.-yQfraction)*0.5*digiInput.totalCharge);
484 addDigit(digits, neigh_ID_Y, digiInput.time, yQfraction*(1.-xQfraction)*0.5*digiInput.totalCharge);
485 addDigit(digits, neigh_ID_XY, digiInput.time, xQfraction*yQfraction*0.5*digiInput.totalCharge);
486 addDigit(digits, padHitId, digiInput.time, (1.-xQfraction-yQfraction+xQfraction*yQfraction)*0.5*digiInput.totalCharge);
487 } else if (isNeighX && validPhi){
488 const Identifier neigh_ID = m_idHelper.padID(padHitId, digiInput.reEle->multilayer(), gasGap,
489 ReadoutChannelType::Pad, padEta, newPhi);
490 double xQfraction = getPadChargeFraction(deltaX);
491 addDigit(digits, padHitId, digiInput.time, (1.-xQfraction)*0.5*digiInput.totalCharge);
492 addDigit(digits, neigh_ID, digiInput.time, xQfraction*0.5*digiInput.totalCharge);
493 }
494 else if (isNeighY && validEta){
495 const Identifier neigh_ID = m_idHelper.padID(padHitId, digiInput.reEle->multilayer(), gasGap,
496 ReadoutChannelType::Pad, newEta, padPhi);
497 double yQfraction = getPadChargeFraction(deltaY);
498 addDigit(digits, padHitId, digiInput.time, (1.-yQfraction)*0.5*digiInput.totalCharge);
499 addDigit(digits, neigh_ID, digiInput.time, yQfraction*0.5*digiInput.totalCharge);
500 }
501 } else{
502 addDigit(digits, padHitId, digiInput.time, 0.5*digiInput.totalCharge);
503 }
504 return digits;
505}
506
507
508//------------------------------------------------------
509// Process wire digitization
510//------------------------------------------------------
512 ATH_MSG_DEBUG("sTgcDigitMaker::wire response ");
513
514 const int gasGap = m_idHelper.gasGap(digiInput.hitId);
515 const IdentifierHash wireLayHash = digiInput.reEle->createHash(gasGap,
516 ReadoutChannelType::Wire, 1);
517 const MuonGMR4::WireGroupDesign& wireDesign{digiInput.reEle->wireDesign(wireLayHash)};
518
519 const Amg::Vector2D hitOnWireSurf = digiInput.reEle->stripLayer(wireLayHash).to2D(digiInput.posOnSurf, true);
520 if(!wireDesign.insideTrapezoid(hitOnWireSurf)) {
521 ATH_MSG_DEBUG("Outside of the wire surface boundary :" << m_idHelperSvc->toString(digiInput.hitId)
522 << " local position " <<Amg::toString(hitOnWireSurf, 2));
523 return {};
524 }
525
526 if (digiInput.reEle->isEtaZero(digiInput.reEle->measurementHash(digiInput.hitId), digiInput.posOnSurf.block<2,1>(0,0))) {
527 ATH_MSG_DEBUG("Hit inside wireCutout :" << m_idHelperSvc->toString(digiInput.hitId)
528 << " local position " <<Amg::toString(hitOnWireSurf, 2));
529 return {};
530 }
531
532 constexpr double tolerance_length = 0.01*Gaudi::Units::mm;
533 int wiregroupNumber = (wireDesign.wireNumber(hitOnWireSurf)).first;
534 if( wiregroupNumber < 1) {
535 const double newPosX = hitOnWireSurf.x() - std::copysign(tolerance_length, hitOnWireSurf.x());
536 const Amg::Vector2D newPos{newPosX, hitOnWireSurf.y()};
537 wiregroupNumber = (wireDesign.wireNumber(newPos)).first;
538 if (wiregroupNumber < 1) {
539 ATH_MSG_WARNING("Failed to obtain wire number " << m_idHelperSvc->toString(digiInput.hitId) );
540 return {};
541 }
542 }
543
544 bool isValid = false;
545 const Identifier wireGroupHitId = m_idHelper.channelID(digiInput.hitId, digiInput.reEle->multilayer(), gasGap,
546 ReadoutChannelType::Wire, wiregroupNumber, isValid);
547
548 if(!isValid) {
549 return {};
550 }
551 sTgcDigitVec digits{};
552 addDigit(digits, wireGroupHitId, digiInput.time, digiInput.totalCharge);
553 return digits;
554}
555
556//------------------------------------------------------
557// Compute closest approach between hit trajectory and wire
558//------------------------------------------------------
560 int wireNumber,
561 const Amg::Vector3D& locHitPos,
562 const Amg::Vector3D& locHitDir,
563 const double stepLength) const {
564
565 constexpr double angular_tolerance = 1e-3;
566 // Position of the ionization
567 Ionization ionization;
568 // Finding smallest distance and the points at the smallest distance.
569 // The smallest distance between two lines is perpendicular to both lines.
570 // Previous logic was to find the perpendicular distance between two lines using projection geometry
571 // We can construct two lines in the wire surface local coordinate frame:
572 // - one for the hit segment with equation h0 + t * v_h, where h0 is a point
573 // and v_h is the unit vector of the hit segment
574 // - another for the wire with similar equation w0 + s * v_w, where w0 is a
575 // point and v_w is the unit vector of the wire line
576 // Then it is possible to determine the closest points on each line
577 // by requiring that the vector between them is perpendicular to both:
578 // 1. (h0 + t*v_h - w0 - s*v_w) · v_h = 0
579 // 2. (h0 + t*v_h - w0 - s*v_w) · v_w = 0
580
581 // We have replaced this logic with using Amg::intersect<3> method
582 const MuonGMR4::WireGroupDesign& wireDesign = static_cast<const MuonGMR4::WireGroupDesign&>(stripLayer.design(true));
583 // Geometry setup defined in the eta surface local coordinate frame
584 const double wirePitch = wireDesign.stripPitch();
585 const double wirePosX = wireDesign.firstStripPos().x() + (wireNumber - 1) * wirePitch;
586 const Amg::Vector3D wireDir{stripLayer.to3D(wireDesign.stripDir(),true)};
587 const Amg::Vector3D wirePos(locHitPos.x(), -wirePosX, 0.);
588
589 // Use Amg::intersect to find closest point on hit segment to wire plane
590 std::optional<double> scaleHit = Amg::intersect<3>(locHitPos, locHitDir, Amg::Vector3D::UnitZ(), 0);
591 if (!scaleHit || std::abs(std::abs(wireDir.dot(locHitDir)) - 1.0) < angular_tolerance) {
592 ATH_MSG_DEBUG("The track segment is parallel to the wire, position of digit is undefined");
593 ionization.posOnSegment = locHitPos;
594 ionization.posOnWire = wirePos;
595 ionization.distance = std::hypot(locHitPos.y() + wirePosX, locHitPos.z());
596 if (ionization.distance > wirePitch) {
597 ATH_MSG_DEBUG(" localHitPos: " << Amg::toString(locHitPos, 2) << " localHitDir: " << Amg::toString(locHitDir, 2) << " scaleHit: " << scaleHit.value()
598 << " wirePos: " << Amg::toString(wirePos, 2) << " IonizationDistance: " << ionization.distance);
599 }
600 return ionization;
601 }
602 // Position on hit segment
603 Amg::Vector3D ionizationPos = locHitPos + scaleHit.value() * locHitDir;
604
605 if (scaleHit.value() > stepLength) {
606 ionization.posOnSegment = locHitPos;
607 const Amg::Vector3D closestPointToWirePlane = locHitPos + stepLength * locHitDir;
608 ionization.posOnWire = wirePos;
609 ionization.distance = std::abs(closestPointToWirePlane.z());
610 return ionization;
611 }
612
613 // Project ionization position onto the wire line
614 const double scaleWire = (ionizationPos - wirePos).dot(wireDir);
615 const Amg::Vector3D closestPointOnWire = wirePos + scaleWire * wireDir;
616
617 // Fill ionization result
618 ionization.posOnSegment = ionizationPos;
619 ionization.posOnWire = closestPointOnWire;
620 ionization.distance = (ionizationPos - closestPointOnWire).mag();
621
622 return ionization;
623}
624
625//------------------------------------------------------
626// Adds a digit to the appropriate cache
627//------------------------------------------------------
629 const Identifier& id,
630 const double digittime,
631 const double charge) {
632
633 constexpr double tolerance = 0.1;
634 if (!std::ranges::any_of(digits, [&](std::unique_ptr<sTgcDigit>& known) {
635 return known->identify() == id && std::abs(digittime - known->time()) < tolerance;
636 })) {
637 digits.push_back(std::make_unique<sTgcDigit>(id, 0, digittime, charge, 0, 0));
638 }
639}
640
641//------------------------------------------------------
642// Reads time arrival data file
643//------------------------------------------------------
645 const std::string file_name = "sTGC_Digitization_timeArrival.dat";
646 std::string file_path = PathResolver::find_file(file_name, "DATAPATH");
647 if(file_path.empty()) {
648 ATH_MSG_FATAL("readFileOfTimeWindowOffset(): Could not find file " << file_name );
649 return StatusCode::FAILURE;
650 }
651
652 std::ifstream ifs{file_path, std::ios::in};
653 if(ifs.bad()) {
654 ATH_MSG_FATAL("sTgcDigitMaker: Failed to open time of arrival file " << file_name );
655 return StatusCode::FAILURE;
656 }
657
658 // Read the sTGC_Digitization_timeWindowOffset.dat file
659 std::string line;
660 GammaParameter param{};
661 while (std::getline(ifs, line)) {
662 std::string key;
663 std::istringstream iss(line);
664 iss >> key;
665 if (key == "bin") {
666 iss >> param.lowEdge >> param.kParameter >> param.thetaParameter;
667 m_gammaParameter.push_back(param);
668 } else if (key == "mpv") {
669 double mpt{};
670 int idx{0};
671 while (iss >> mpt) {m_mostProbableArrivalTime[idx++] = mpt;}
672 }
673 }
674 ifs.close();
675 return StatusCode::SUCCESS;
676}
677
678//------------------------------------------------------
679// Retrieves gamma distribution parameters based on distance
680//------------------------------------------------------
682 const double d = std::abs(distance);
683 // Find the parameters assuming the container is sorted in ascending order of 'lowEdge'
684 if (d < m_gammaParameter.front().lowEdge) {
685 return m_gammaParameter.front();
686 }
687 int index{-1};
688 for (const auto& par: m_gammaParameter) {
689 if (d < par.lowEdge) {
690 break;
691 }
692 ++index;
693 }
694 return m_gammaParameter.at(index);
695}
696
697//------------------------------------------------------
698// Computes the most probable arrival time based on the distance of closest approach
699//------------------------------------------------------
700double sTgcDigitMaker::getMostProbableArrivalTime(double distance) const {
701 return Acts::detail::polynomialSum(std::abs(distance), m_mostProbableArrivalTime);
702}
703//------------------------------------------------------
704// Computes the charge on each strip
705//------------------------------------------------------
706
707double sTgcDigitMaker::chargeIntegral(double N, double M) const {
708
709 double term1 = 0.25 * std::erf( M / (std::sqrt(2) * m_clusterParams[0]));
710 double term2 = 0.25 * std::erf( N / (std::sqrt(2) * m_clusterParams[0]));
711 double term3 = 0.25 * std::erf( M / (std::sqrt(2) * m_clusterParams[1]));
712 double term4 = 0.25 * std::erf( N / (std::sqrt(2) * m_clusterParams[1]));
713
714 return (term1 - term2 + term3 - term4);
715}
716//------------------------------------------------------
717// Reads strip time offset data file
718//------------------------------------------------------
720 const std::string file_name = "sTGC_Digitization_timeOffsetStrip.dat";
721 std::string file_path = PathResolver::find_file(file_name, "DATAPATH");
722 if(file_path.empty()) {
723 ATH_MSG_FATAL("readFileOfTimeWindowOffset(): Could not find file " << file_name );
724 return StatusCode::FAILURE;
725 }
726
727 // Open the sTGC_Digitization_timeOffsetStrip.dat file
728 std::ifstream ifs{file_path, std::ios::in};
729 if(ifs.bad()) {
730 ATH_MSG_FATAL("Failed to open time of arrival file " << file_name );
731 return StatusCode::FAILURE;
732 }
733
734 // Initialize the container to store the time offset.
735 // The number of parameters, 6, corresponds to the number of lines to be read
736 // from sTGC_Digitization_timeOffsetStrip.dat.
737 // Setting the default offset to 0 ns.
738 std::string line;
739 size_t index{0};
740 double value{0.0};
741 while (std::getline(ifs, line)) {
742 std::string key;
743 std::istringstream iss(line);
744 iss >> key;
745 if (key == "strip") {
746 iss >> index >> value;
747 if (index >= m_timeOffsetStrip.size()) continue;
748 m_timeOffsetStrip.at(index) = value;
749 }
750 }
751 return StatusCode::SUCCESS;
752}
753
754//------------------------------------------------------
755// Retrieves time offset for strip clusters
756//------------------------------------------------------
757double sTgcDigitMaker::getTimeOffsetStrip(size_t neighbor_index) const {
758 return m_timeOffsetStrip.at(std::min(neighbor_index, m_timeOffsetStrip.size() -1));
759}
760
761//------------------------------------------------------
762// Computes pad charge fraction
763//------------------------------------------------------
765 // The charge fraction that is found past a distance x away from the
766 // centre of a 2D gaussian distribution of width of cluster profile is
767 // described by a modified error function.
768
769 // The modified error function perfectly describes
770 // the pad charge sharing distribution figure 16 of the sTGC
771 // testbeam paper https://arxiv.org/pdf/1509.06329.pdf
772 return 0.5 * (1.0 - std::erf( distance / (std::sqrt(2) * m_clusterParams[1])));
773}
774}
Scalar mag() const
mag method
#define ATH_CHECK
Evaluate an expression and check for errors.
#define ATH_MSG_DEBUG(x,...)
#define ATH_MSG_WARNING(x,...)
#define ATH_MSG_VERBOSE(x,...)
#define ATH_MSG_FATAL(x,...)
double charge(const T &p)
Definition AtlasPID.h:1054
bool hit(const Container &ids, int pdgId)
int sign(int a)
void diff(const TrigInDetTrack &a, const TrigInDetTrack &b, std::map< std::string, double > &variableChange)
comparison with feedback Function compares two objects and returns "semi verbose" output in the form ...
AthMessaging(IMessageSvc *msgSvc, const std::string &name)
Constructor.
This is a "hash" representation of an Identifier.
std::pair< int, int > channelNumber(const Amg::Vector2D &hitPos) const
Function to retrieve the pad eta and phi given a local position coordinate.
const Amg::Vector2D & firstStripPos() const
Vector indicating the first strip position.
double stripPitch() const
Distance between two adjacent strips.
bool insideTrapezoid(const Amg::Vector2D &extPos) const
Checks whether an external point is inside the trapezoidal area.
virtual int stripNumber(const Amg::Vector2D &pos) const
Calculates the number of the strip whose center is closest to the given point.
const Amg::Vector2D & stripDir() const
Vector pointing along the strip.
The StripLayer interfaces the 2D description of the strip plane layout with the 3D description of the...
Definition StripLayer.h:19
const StripDesign & design(bool phiView=false) const
Returns the underlying strip design.
Amg::Vector2D to2D(const Amg::Vector3D &vec, const bool phiView) const
Transforms a 3D vector from the strip design into a 2D vector.
Amg::Vector3D to3D(CheckVector2D &&vec, const bool phiView) const
Transforms the 2D vector from the strip design into a 3D vector If phi view is switched on,...
unsigned int numPitchesToGroup(unsigned int groupNum) const
Returns the number of wire pitches to reach the given group.
std::pair< int, int > wireNumber(const Amg::Vector2D &extPos) const
Returns a pair where the first component indicate the wire group number and the second one returns th...
unsigned int nAllWires() const
Returns the number of all wires.
IdentifierHash measurementHash(const Identifier &measId) const override final
Constructs the identifier hash from the full measurement Identifier.
const PadDesign & padDesign(const IdentifierHash &measHash) const
Retrieves the readoutElement Layer given the Identifier/Hash.
double padHeight(const IdentifierHash &measHash) const
Returns the height of all the pads that are not adjacent to the bottom edge of the trapezoid active a...
int multilayer() const
Returns the multilayer of the sTgcReadoutElement.
Identifier measurementId(const IdentifierHash &measHash) const override final
Converts the measurement hash back to the full Identifier.
const StripDesign & stripDesign(const IdentifierHash &measHash) const
Retrieves the readoutElement Layer given the Identifier/Hash.
bool isEtaZero(const IdentifierHash &measurementHash, const Amg::Vector2D &localPosition) const
unsigned numPadEta(const IdentifierHash &measHash) const
Returns the number of pads in the eta direction in the given layer.
unsigned numPadPhi(const IdentifierHash &measHash) const
Returns the number of pads in the Phi direction in the given gasGap layer.
Amg::Vector2D localChannelPosition(const IdentifierHash &measHash) const
Returns the local position of the measurement in the repsective frame.
const WireGroupDesign & wireDesign(const IdentifierHash &measHash) const
Retrieves the readoutElement Layer given the Identifier/Hash.
static IdentifierHash createHash(const unsigned gasGap, const unsigned channelType, const unsigned channel, const unsigned wireInGrp=0)
Create a measurement hash from the Identifier fields.
const StripLayer & stripLayer(const IdentifierHash &measId) const
std::vector< std::unique_ptr< sTgcDigit > > sTgcDigitVec
Digitize a given hit.
sTgcDigitVec processWireDigitization(const DigiInput &digiInput) const
Processes wire digitization for a given hit.
StatusCode readFileOfTimeOffsetStrip()
Reads strip time offset data file.
sTgcDigitVec processPadDigitization(const DigiInput &digiInput) const
Processes pad digitization for a given hit.
static double getPadChargeFraction(double distance)
Computes charge fraction shared among pads.
double getTimeOffsetStrip(size_t neighbor_index) const
Gets the time offset for a strip cluster.
bool getIonizationPoint(const TimedHit &hit, const DigiConditions &condContainers, Ionization &ionization) const
Computes the ionization point for a hit.
digitMode m_digitMode
define offsets and widths of time windows for signals from wiregroups and strips.
GammaParameter getGammaParameter(double distance) const
Retrieves gamma distribution parameters based on distance.
static void addDigit(sTgcDigitVec &digits, const Identifier &id, double digittime, double charge)
Adds a digit to the appropriate cache.
sTgcDigitVec processStripChargeSharing(const DigiInput &digiInput, const double peak_position, const int stripNumber) const
Handles charge sharing for strip clusters.
StatusCode initialize()
Initialize digitization parameters, including reading necessary data files.
sTgcDigitMaker(const MuonGMR4::MuonDetectorManager *detMgr, digitMode mode, double meanGasGain, bool doPadChargeSharing)
sTgcDigitVec processStripDigitization(const DigiConditions &condContainers, const DigiInput &digiInput) const
Processes strip digitization for a given hit.
double getMostProbableArrivalTime(double distance) const
Computes the most probable arrival time based on the distance of closest approach.
double calculateTotalCharge(double energyDeposit, CLHEP::HepRandomEngine *rndEngine) const
Calculates total charge from energy deposit, including gas gain.
Ionization pointClosestApproach(const MuonGMR4::StripLayer &stripLayer, int wireNumber, const Amg::Vector3D &locHitPos, const Amg::Vector3D &locHitDir, const double stepLength) const
Computes the closest approach between a trajectory and a wire segment.
sTgcDigitVec processPadChargeSharing(const DigiInput &digiInput, const int padEta, const int padPhi) const
Handles charge sharing for pad clusters.
sTgcDigitVec executeDigi(const DigiConditions &condContainers, const TimedHit &hit) const
virtual ~sTgcDigitMaker()
Destructor.
double getEfficiency(const Identifier &channelId, bool isInnerQ1=false) const
Returns the signal generation efficiency of the sTgc channel.
static std::string find_file(const std::string &logical_file_name, const std::string &search_path)
void efficiency(std::vector< double > &bins, std::vector< double > &values, const std::vector< std::string > &files, const std::string &histname, const std::string &tplotname, const std::string &label="")
std::optional< double > intersect(const AmgVector(N)&posA, const AmgVector(N)&dirA, const AmgVector(N)&posB, const AmgVector(N)&dirB)
Calculates the point B' along the line B that's closest to a second line A.
std::string toString(const Translation3D &translation, int precision=4)
GeoPrimitvesToStringConverter.
Eigen::Matrix< double, 2, 1 > Vector2D
Eigen::Matrix< double, 3, 1 > Vector3D
constexpr std::size_t N
This header ties the generic definitions in this package.
Definition dot.py:1
Definition index.py:1