Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-08-26 08:25:51

0001 // SPDX-License-Identifier: LGPL-3.0-or-later
0002 // Copyright (C) 2022, 2023, Chao Peng, Thomas Britton, Christopher Dilks, Luigi Dello Stritto
0003 
0004 /*  General PhotoMultiplier Digitization
0005  *
0006  *  Apply the given quantum efficiency for photon detection
0007  *  Converts the number of detected photons to signal amplitude
0008  *
0009  *  Author: Chao Peng (ANL)
0010  *  Date: 10/02/2020
0011  *
0012  *  Ported from Juggler by Thomas Britton (JLab)
0013  */
0014 
0015 #include "PhotoMultiplierHitDigi.h"
0016 
0017 #include <Evaluator/DD4hepUnits.h>
0018 #include <algorithms/logger.h>
0019 #include <edm4hep/Vector3d.h>
0020 #include <podio/ObjectID.h>
0021 #include <podio/detail/Link.h>
0022 #include <podio/detail/LinkCollectionImpl.h>
0023 #include <algorithm>
0024 #include <cmath>
0025 #include <iterator>
0026 #include <memory>
0027 #include <tuple>
0028 
0029 #include "algorithms/digi/PhotoMultiplierHitDigiConfig.h"
0030 
0031 namespace eicrecon {
0032 
0033 //------------------------
0034 // init
0035 //------------------------
0036 void PhotoMultiplierHitDigi::init() {
0037   // print the configuration parameters
0038   debug() << m_cfg << endmsg;
0039 
0040   // initialize quantum efficiency table
0041   qe_init();
0042 }
0043 
0044 //------------------------
0045 // process
0046 //------------------------
0047 void PhotoMultiplierHitDigi::process(const PhotoMultiplierHitDigi::Input& input,
0048                                      const PhotoMultiplierHitDigi::Output& output) const {
0049   const auto [headers, sim_hits]     = input;
0050   auto [raw_hits, links, hit_assocs] = output;
0051 
0052   // local random generator
0053   auto seed = m_uid.getUniqueID(*headers, name());
0054   std::default_random_engine generator(seed);
0055   std::normal_distribution<double> gaussian;
0056   std::uniform_real_distribution<double> uniform;
0057 
0058   trace("{:=^70}", " call PhotoMultiplierHitDigi::process ");
0059   std::unordered_map<CellIDType, std::vector<HitData>> hit_groups;
0060   // collect the photon hit in the same cell
0061   // calculate signal
0062   trace("{:-<70}", "Loop over simulated hits ");
0063   for (std::size_t sim_hit_index = 0; sim_hit_index < sim_hits->size(); sim_hit_index++) {
0064     const auto& sim_hit = sim_hits->at(sim_hit_index);
0065     auto edep_eV        = sim_hit.getEDep() *
0066                           1e9; // [GeV] -> [eV] // FIXME: use common unit converters, when available
0067     auto id             = sim_hit.getCellID();
0068     trace("hit: pixel id={:#018X}  edep = {} eV", id, edep_eV);
0069 
0070     // overall safety factor
0071     if (uniform(generator) > m_cfg.safetyFactor) {
0072       continue;
0073     }
0074 
0075     // quantum efficiency
0076     if (m_cfg.enableQuantumEfficiency and !qe_pass(edep_eV, uniform(generator))) {
0077       continue;
0078     }
0079 
0080     // pixel gap cuts
0081     if (m_cfg.enablePixelGaps) {
0082       auto pos = sim_hit.getPosition();
0083       if (!m_PixelGapMask(
0084               id, dd4hep::Position(pos.x * dd4hep::mm, pos.y * dd4hep::mm, pos.z * dd4hep::mm))) {
0085         continue;
0086       }
0087     }
0088 
0089     // cell time, signal amplitude, truth photon
0090     trace(" -> hit accepted");
0091     trace(" -> MC hit id={}", sim_hit.getObjectID().index);
0092     auto time  = sim_hit.getTime();
0093     double amp = m_cfg.speMean + gaussian(generator) * m_cfg.speError;
0094 
0095     // insert hit to `hit_groups`
0096     InsertHit(hit_groups, id, amp, time, sim_hit_index, generator, gaussian);
0097   }
0098 
0099   // print `hit_groups`
0100   if (level() <= algorithms::LogLevel::kTrace) {
0101     trace("{:-<70}", "Accepted hit groups ");
0102     for (auto& [id, hitVec] : hit_groups) {
0103       for (auto& hit : hitVec) {
0104         trace("hit_group: pixel id={:#018X} -> npe={} signal={} time={}", id, hit.npe, hit.signal,
0105               hit.time);
0106         for (auto i : hit.sim_hit_indices) {
0107           trace(" - MC hit: EDep={}, id={}", sim_hits->at(i).getEDep(),
0108                 sim_hits->at(i).getObjectID().index);
0109         }
0110       }
0111     }
0112   }
0113 
0114   //build noise raw hits
0115   if (m_cfg.enableNoise) {
0116     trace("{:=^70}", " BEGIN NOISE INJECTION ");
0117     float p            = m_cfg.noiseRate * m_cfg.noiseTimeWindow;
0118     auto cellID_action = [this, &gaussian, &generator, &hit_groups, &uniform](auto id) {
0119       // cell time, signal amplitude
0120       double amp    = m_cfg.speMean + gaussian(generator) * m_cfg.speError;
0121       TimeType time = m_cfg.noiseTimeWindow * uniform(generator) / dd4hep::ns;
0122 
0123       // insert in `hit_groups`, or if the pixel already has a hit, update `npe` and `signal`
0124       this->InsertHit(hit_groups, id, amp, time,
0125                       0, // not used
0126                       generator, gaussian, true);
0127     };
0128     m_VisitRngCellIDs(cellID_action, p);
0129   }
0130 
0131   // build output `RawTrackerHit` and `MCRecoTrackerHitAssociation` collections
0132   trace("{:-<70}", "Digitized raw hits ");
0133   for (auto& it : hit_groups) {
0134     for (auto& data : it.second) {
0135 
0136       // build `RawTrackerHit`
0137       auto raw_hit = raw_hits->create();
0138       raw_hit.setCellID(it.first);
0139       raw_hit.setCharge(static_cast<decltype(edm4eic::RawTrackerHitData::charge)>(data.signal));
0140       raw_hit.setTimeStamp(static_cast<decltype(edm4eic::RawTrackerHitData::timeStamp)>(
0141           data.time / m_cfg.timeResolution));
0142       trace("raw_hit: cellID={:#018X} -> charge={} timeStamp={}", raw_hit.getCellID(),
0143             raw_hit.getCharge(), raw_hit.getTimeStamp());
0144 
0145       // build `MCRecoTrackerHitAssociation` (for non-noise hits only)
0146       if (!data.sim_hit_indices.empty()) {
0147         for (auto i : data.sim_hit_indices) {
0148           // create link
0149           auto link = links->create();
0150           link.setFrom(raw_hit);
0151           link.setTo(sim_hits->at(i));
0152           link.setWeight(1.0 / data.sim_hit_indices.size());
0153           auto hit_assoc = hit_assocs->create();
0154           hit_assoc.setWeight(1.0 / data.sim_hit_indices.size()); // not used
0155           hit_assoc.setRawHit(raw_hit);
0156           hit_assoc.setSimHit(sim_hits->at(i));
0157         }
0158       }
0159     }
0160   }
0161 }
0162 
0163 void PhotoMultiplierHitDigi::qe_init() {
0164   // get quantum efficiency table
0165   qeff.clear();
0166   auto hc = dd4hep::h_Planck * dd4hep::c_light / (dd4hep::eV * dd4hep::nm); // [eV*nm]
0167   for (const auto& [wl, qe] : m_cfg.quantumEfficiency) {
0168     qeff.emplace_back(hc / wl, qe); // convert wavelength [nm] -> energy [eV]
0169   }
0170 
0171   // sort quantum efficiency data first
0172   std::ranges::sort(qeff, [](const std::pair<double, double>& v1,
0173                              const std::pair<double, double>& v2) { return v1.first < v2.first; });
0174 
0175   // print the table
0176   debug("{:-^60}", " Quantum Efficiency vs. Energy ");
0177   for (auto& [en, qe] : qeff) {
0178     debug("  {:>10.4} {:<}", en, qe);
0179   }
0180   trace("{:=^60}", "");
0181 
0182   if (m_cfg.enableQuantumEfficiency) {
0183     // sanity checks
0184     if (qeff.empty()) {
0185       qeff = {{2.6, 0.3}, {7.0, 0.3}};
0186       warning("Invalid quantum efficiency data provided, using default values {} {:.2f} {} {:.2f} "
0187               "{} {:.2f} {} {:.2f} {}",
0188               "{{", qeff.front().first, ",", qeff.front().second, "},{", qeff.back().first, ",",
0189               qeff.back().second, "}}");
0190     }
0191     if (qeff.front().first > 3.0) {
0192       warning("Quantum efficiency data start from {:.2f} {}", qeff.front().first,
0193               " eV, maybe you are using wrong units?");
0194     }
0195     if (qeff.back().first < 3.0) {
0196       warning("Quantum efficiency data end at {:.2f} {}", qeff.back().first,
0197               " eV, maybe you are using wrong units?");
0198     }
0199   }
0200 }
0201 
0202 template <class RndmIter, typename T, class Compare>
0203 RndmIter PhotoMultiplierHitDigi::interval_search(RndmIter beg, RndmIter end, const T& val,
0204                                                  Compare comp) const {
0205   // special cases
0206   auto dist = std::distance(beg, end);
0207   if ((dist < 2) || (comp(*beg, val) > 0) || (comp(*std::prev(end), val) < 0)) {
0208     return end;
0209   }
0210   auto mid = std::next(beg, dist / 2);
0211 
0212   while (mid != end) {
0213     if (comp(*mid, val) == 0) {
0214       return mid;
0215     }
0216     if (comp(*mid, val) > 0) {
0217       end = mid;
0218     } else {
0219       beg = std::next(mid);
0220     }
0221     mid = std::next(beg, std::distance(beg, end) / 2);
0222   }
0223 
0224   if (mid == end || comp(*mid, val) > 0) {
0225     return std::prev(mid);
0226   }
0227   return mid;
0228 }
0229 
0230 bool PhotoMultiplierHitDigi::qe_pass(double ev, double rand) const {
0231   auto it = interval_search(
0232       qeff.begin(), qeff.end(), ev,
0233       [](const std::pair<double, double>& vals, double val) { return vals.first - val; });
0234 
0235   if (it == qeff.end()) {
0236     // warning("{} eV is out of QE data range, assuming 0\% efficiency",ev);
0237     return false;
0238   }
0239 
0240   double prob = it->second;
0241   auto itn    = std::next(it);
0242   if (itn != qeff.end() && (itn->first - it->first != 0)) {
0243     prob = (it->second * (itn->first - ev) + itn->second * (ev - it->first)) /
0244            (itn->first - it->first);
0245   }
0246 
0247   // trace("{} eV, QE: {}\%",ev,prob*100.);
0248   return rand <= prob;
0249 }
0250 
0251 // add a hit to local `hit_groups` data structure
0252 // NOLINTBEGIN(bugprone-easily-swappable-parameters)
0253 void PhotoMultiplierHitDigi::InsertHit(
0254     std::unordered_map<CellIDType, std::vector<HitData>>& hit_groups, CellIDType id, double amp,
0255     TimeType time, std::size_t sim_hit_index, std::default_random_engine& generator,
0256     std::normal_distribution<double>& gaussian,
0257     bool is_noise_hit) const // NOLINTEND(bugprone-easily-swappable-parameters)
0258 {
0259   auto it = hit_groups.find(id);
0260   if (it != hit_groups.end()) {
0261     std::size_t i = 0;
0262     for (auto ghit = it->second.begin(); ghit != it->second.end(); ++ghit, ++i) {
0263       if (std::abs(time - ghit->time) <= (m_cfg.hitTimeWindow)) {
0264         // hit group found, update npe, signal, and list of MC hits
0265         ghit->npe += 1;
0266         ghit->signal += amp;
0267         if (!is_noise_hit) {
0268           ghit->sim_hit_indices.push_back(sim_hit_index);
0269         }
0270         trace(" -> add to group @ {:#018X}: signal={}", id, ghit->signal);
0271         break;
0272       }
0273     }
0274     // no hits group found
0275     if (i >= it->second.size()) {
0276       auto sig = amp + m_cfg.pedMean + m_cfg.pedError * gaussian(generator);
0277       decltype(HitData::sim_hit_indices) indices;
0278       if (!is_noise_hit) {
0279         indices.push_back(sim_hit_index);
0280       }
0281       hit_groups.insert(
0282           {id, {HitData{.npe = 1, .signal = sig, .time = time, .sim_hit_indices = indices}}});
0283       trace(" -> no group found,");
0284       trace("    so new group @ {:#018X}: signal={}", id, sig);
0285     }
0286   } else {
0287     auto sig = amp + m_cfg.pedMean + m_cfg.pedError * gaussian(generator);
0288     decltype(HitData::sim_hit_indices) indices;
0289     if (!is_noise_hit) {
0290       indices.push_back(sim_hit_index);
0291     }
0292     hit_groups.insert(
0293         {id, {HitData{.npe = 1, .signal = sig, .time = time, .sim_hit_indices = indices}}});
0294     trace(" -> new group @ {:#018X}: signal={}", id, sig);
0295   }
0296 }
0297 
0298 } // namespace eicrecon