Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-11-20 09:33:14

0001 // SPDX-License-Identifier: LGPL-3.0-or-later
0002 // Copyright (C) 2022 - 2025 Whitney Armstrong, Wouter Deconinck, Sylvester Joosten, Dmitry Romanov, Yann Bedfer
0003 
0004 /*
0005   Digitization specific to MPGDs.
0006   - What's special in MPGDs is their 2D-strip readout: i.e. simultaneous
0007    registering along two sets of coordinate strips.
0008   - The fact imposes strong constraints on digitization, stemming from DD4hep's
0009    provision that one and only one readout surface be associated to a sensitive
0010    volume. The one-and-only-one rule is enforced through to ACTS's TrackState,
0011    forbidding simple solutions exploiting MultiSegmentation to create two strip
0012    hits on a same surface.
0013   - Present solution is based on multiple sensitive SUBVOLUMES. FIVE of them:
0014     + TWO persistent ones, acting as READOUT SURFACES (i.e. to which raw hits
0015      are assigned, in both RealData and MC): very thin and sitting very close
0016      to mid-plane,
0017     + THREE HELPER ones: TWO RADIATORS, thick, serving temporarily to collect
0018      energy deposit and ONE REFERENCE, thin and sitting exactly at mid-plane.
0019      (The REFERENCE is not essential, but found to help rationalize the source
0020      code.)
0021   - Each SUBVOLUME has a distinct ID, w/ a distinctive "STRIP" FIELD, but all
0022    share a common XML <readout> thanks to a MultiSegmentation based on the
0023    "STRIP" FIELD.
0024   - Several subHits are created (up to five, one per individual SUBVOLUME)
0025    corresponding to a SINGLE I[ONISATION]+A[MPLIFICATION] process, inducing in
0026    turn CORRELATED signals on two coordinates.
0027   - These subHits are EXTENDED so as to span the full sensitive volume and be
0028    on the sensitive surface of the REFERENCE SUBVOLUME (its mid-plane), and
0029    hence reconstitute the proper hit position of the TRAVERSING particle.
0030     This, for particles that are determined to be indeed traversing.
0031   - We then want to preserve the I+A correlation when accumulating hits on the
0032    readout channels. This could be obtained by accumulating directly subHits (
0033    as is done in "SiliconTrackerDigi", as of commit #151496af). For such a
0034    scheme to preserve CORRELATION, we would have to collect all related subHits
0035    (i.e. those deemed to originate from a given I+A) and apply to them a common
0036    smearing (in amplitude and time). Here, we go one step further and COALESCE
0037    the related subHits. Our guideline can be formulated as: reproduce what we
0038    would get would there be a single volume. This comes with a cost of extra
0039    complication in the source code, but a limited one. This should go on w/
0040    the common smearing simulating I+A, independent smearings simulating CHARGE
0041    SHARING and CHARGE SPREADING. Then accumulation channel by channel. Then,
0042    possibly, apply smearing simulating FE electronics.
0043   - In any case, we therefore have a DOUBLE LOOP ON INPUT SimTrackerHits, to
0044    collect those subHits arising from the same I+A. I.e. SAME P[ARTICLE],
0045    M[ODULE] (a particle can fire two overlapping modules, not to be mixed) and
0046    O[RIGIN] (direct or via secondary).
0047   - The double loop is optimized for speed (by keeping track of the start index
0048    of the second loop) in order to not waste time on high multiplicity events.
0049   - We assume subHits originating from the same ionization process to come in
0050    sequences unbroken by any intertwining.
0051   - A number of checks are conducted before undertaking subHit COALESCENCE:
0052     I) SubHits should be TRAVERSING, i.e. exiting and then entering through
0053     opposite walls, as opposed to exiting or entering through the edge or
0054     dying/being-born within their SUBVOLUME, see methods "(c|b)Traversing".
0055     II) SubHits have SAME PMO, see "samePMO".
0056     III) SubHits extrapolate to a common point, see "outInDistance".
0057     All these checks are done to be on the safe side. A subset of them, hinging
0058    on (III), should be sufficient. But there are so many cases to take into
0059    account that it's difficult to settle on a minimal subset.
0060   - Evaluation:
0061     + MIPs are found to be properly handled, whether a cutoff on deposited
0062      energy is applied or not: hits are COALESCED when needed. They are
0063      assigned to mid-plane, except for few cases, see "flagUnexpected".
0064     + For lower energy particles, there are at times ambiguous cases where
0065      seemingly related subHits turn out to not be COALESCED, because they fail
0066      to pass above-mentioned checks due to their erratic trajectories.
0067       Note that even if they are genuinely related, this is not dramatic:
0068      subHits will still be directly accumulated on their common (within pitch
0069      precision) cell, only that we miss the correlation.
0070     + Special cases of i) particle exiting and reEntering the same SUBVOLUME
0071      in the cylindrical setup, ii) SimHit positioned outside the SUBVOLUME (
0072      cylindrical setup once again) it is assigned to, are catered for. In case
0073      (i), subHits are COALESCED but not EXTENDED.
0074   - Imperfections:
0075     + In order to validate (III), one has to decide on a TOLERANCE. The ideal
0076      would be to do this based on multiscattering. Instead, what's used are
0077      guesstimates, and a recipe to RELAX TOLERANCE for low energy stuff.
0078   - SIMULATION
0079     In addition to DIGITIZATION proper, the method involves a SIMULATION of
0080    some of the inner workings of the MPGD, viz. AMPLIFICATION, SIGNAL SHARING
0081    and SPREADING.
0082     + This SIMULATION relies on parameterizations obtained from beam tests.
0083     + Present version is simplistic: 2-hit clusters (except when on the edge),
0084      with identical timing and amplitude, and possibly, BELOW-THRESHOLD charge.
0085   - DIGITIZATION:
0086     + It involves the production of 2-hit clusters, called here CLUSTERIZATION.
0087     + It otherwise follows the standard steps. Remains to agree on the handling
0088      of the discrimination threshold, see Issue #1722.
0089  */
0090 
0091 #include "MPGDTrackerDigi.h"
0092 
0093 #include <DD4hep/Alignments.h>
0094 #include <DD4hep/DetElement.h>
0095 #include <DD4hep/IDDescriptor.h>
0096 #include <DD4hep/Objects.h>
0097 #include <DD4hep/Readout.h>
0098 #include <DD4hep/Shapes.h>
0099 #include <DD4hep/VolumeManager.h>
0100 #include <DD4hep/detail/SegmentationsInterna.h>
0101 #include <DDSegmentation/BitFieldCoder.h>
0102 #include <DDSegmentation/CartesianGridUV.h>
0103 #include <DDSegmentation/CartesianGridXY.h>
0104 #include <DDSegmentation/CylindricalGridPhiZ.h>
0105 #include <DDSegmentation/MultiSegmentation.h>
0106 #include <DDSegmentation/Segmentation.h>
0107 #include <Evaluator/DD4hepUnits.h>
0108 #include <Math/GenVector/Cartesian3D.h>
0109 #include <Math/GenVector/DisplacementVector3D.h>
0110 #include <Parsers/Primitives.h>
0111 #include <TGeoMatrix.h>
0112 #include <TMath.h>
0113 // Access "algorithms:GeoSvc"
0114 #include <algorithms/geo.h>
0115 #include <algorithms/logger.h>
0116 #include <edm4eic/unit_system.h>
0117 #include <edm4hep/MCParticleCollection.h>
0118 #include <edm4hep/Vector3d.h>
0119 #include <edm4hep/Vector3f.h>
0120 #include <format>
0121 #include <podio/detail/Link.h>
0122 #include <podio/detail/LinkCollectionImpl.h>
0123 #include <algorithm>
0124 #include <array>
0125 #include <cmath>
0126 #include <cstdint>
0127 #include <gsl/pointers>
0128 #include <gsl/util>
0129 #include <initializer_list>
0130 #include <iterator>
0131 #include <map>
0132 #include <memory>
0133 #include <random>
0134 #include <stdexcept>
0135 #include <tuple>
0136 #include <utility>
0137 #include <vector>
0138 
0139 #include "algorithms/digi/MPGDTrackerDigiConfig.h"
0140 
0141 using namespace dd4hep;
0142 
0143 namespace eicrecon {
0144 
0145 void MPGDTrackerDigi::init() {
0146   // Access id decoder
0147   m_detector = algorithms::GeoSvc::instance().detector();
0148 
0149   if (m_cfg.readout.empty()) {
0150     throw std::runtime_error("Readout is empty");
0151   }
0152   try {
0153     m_seg    = m_detector->readout(m_cfg.readout).segmentation();
0154     m_id_dec = m_detector->readout(m_cfg.readout).idSpec().decoder();
0155   } catch (const std::runtime_error&) {
0156     critical(R"(Failed to load ID decoder for "{}" readout.)", m_cfg.readout);
0157     throw std::runtime_error("Failed to load ID decoder");
0158   }
0159 
0160   // IDDescriptor and Segmentation
0161   parseIDDescriptor();
0162   parseSegmentation();
0163 
0164   // Ordering of SUBVOLUMES (based on "STRIP" FIELD)
0165   m_stripRank = [&](CellID vID) {
0166     CellID sID = vID & m_stripBits;
0167     for (int rank = 0; rank < 5; rank++) {
0168       if (sID == m_stripIDs[rank]) {
0169         return rank;
0170       }
0171     }
0172     return -1;
0173   };
0174   m_orientation = [&](CellID vID, CellID vJD) {
0175     int ranki = m_stripRank(vID);
0176     int rankj = m_stripRank(vJD);
0177     if (rankj > ranki) {
0178       return +1;
0179     }
0180     if (rankj < ranki) {
0181       return -1;
0182     }
0183     return 0;
0184   };
0185   m_isUpstream = [](int orientation, unsigned int status) {
0186     // Outgoing particle exits...
0187     bool isUpstream =
0188         (orientation < 0 && (status & 0x2)) ||           // ...lower wall
0189         (orientation > 0 && (status & 0x8)) ||           // ...upper wall
0190         (orientation == 0 && (status & 0x102) == 0x102); // ...lower wall and can reEnter
0191     return isUpstream;
0192   };
0193   m_isDownstream = [](int orientation, unsigned int status) {
0194     // Incoming particle enters...
0195     bool isDownstream =
0196         (orientation > 0 && (status & 0x1)) ||           // ...lower wall
0197         (orientation < 0 && (status & 0x4)) ||           // ...upper wall
0198         (orientation == 0 && (status & 0x101) == 0x101); // ...lower wall and can be reEntering
0199     return isDownstream;
0200   };
0201   // RELAXED TOLERANCE
0202   m_toleranceFactor = [](double P) {
0203     int factor = 0;
0204     if (P < 1 * dd4hep::MeV) {
0205       factor = 4;
0206     } else if (P < 10 * dd4hep::MeV) {
0207       factor = 2;
0208     } else {
0209       factor = 1;
0210     }
0211     return factor;
0212   };
0213 
0214   // CLUSTERIZATION
0215   m_binToPosition = [](FieldID bin, double cellSize, double offset) {
0216     return bin * cellSize + offset;
0217   };
0218 }
0219 
0220 // Interfaces
0221 void getLocalPosMom(const edm4hep::SimTrackerHit& sim_hit, const TGeoHMatrix& toModule,
0222                     double* lpos, double* lmom);
0223 bool cExtrapolate(const double* lpos, const double* lmom, // Input subHit
0224                   double rT,                              // Target radius
0225                   double* lext);                          // Extrapolated position @ <rT>
0226 double getRef2Cur(DetElement refVol, DetElement curVol);
0227 bool bExtrapolate(const double* lpos, const double* lmom, // Input subHit
0228                   double zT,                              // Target Z
0229                   double* lext);                          // Extrapolated position @ <zT>
0230 std::string inconsistency(const edm4hep::EventHeader& event, unsigned int status, CellID cID,
0231                           const double* lpos, const double* lmom);
0232 std::string oddity(const edm4hep::EventHeader& event, unsigned int status, double dist, CellID cID,
0233                    const double* lpos, const double* lmom, CellID cJD, const double* lpoj,
0234                    const double* lmoj);
0235 double outInDistance(int shape, int orientation, double lintos[][3], double louts[][3],
0236                      double* lmom, double* lmoj);
0237 void flagUnexpected(const edm4hep::EventHeader& event, int shape, double expected,
0238                     const edm4hep::SimTrackerHit& sim_hit, double* lpini, double* lpend,
0239                     double* lpos, double* lmom);
0240 
0241 void MPGDTrackerDigi::process(const MPGDTrackerDigi::Input& input,
0242                               const MPGDTrackerDigi::Output& output) const {
0243 
0244   const auto [headers, sim_hits]       = input;
0245   auto [raw_hits, links, associations] = output;
0246 
0247   // local random generator
0248   auto seed = m_uid.getUniqueID(*headers, name());
0249   std::default_random_engine generator(seed);
0250   std::normal_distribution<double> gaussian;
0251 
0252   // Maps of unique cellIDs with temporary structure RawHit
0253   std::map<std::uint64_t, edm4eic::MutableRawTrackerHit> cell_hit_maps[2];
0254   // A map of strip cellIDs with vector of contributing cellIDs
0255   std::map<std::uint64_t, std::vector<std::uint64_t>> stripID2cIDs;
0256   // Prepare for strip segmentation
0257   const VolumeManager& volman = m_detector->volumeManager();
0258 
0259   // Reference to event, to be used to document error messages
0260   // (N.B.: I don't know how to properly handle these "headers": may there
0261   // be more than one? none?...)
0262   const edm4hep::EventHeader& header = headers->at(0);
0263 
0264   // *************** LOOP ON sim_hits
0265   size_t sim_size = sim_hits->size();
0266   for (int idx = 0; idx < (int)sim_size; idx++) {
0267     const edm4hep::SimTrackerHit& sim_hit = sim_hits->at(idx);
0268 
0269     // ***** TIME SMEARING
0270     // - Simplistic treatment.
0271     // - A more realistic one would have to distinguish a smearing common to
0272     //  both coordinates of the 2D-strip readout (mainly due to the drifting of
0273     //  the leading primary electrons of the I+A process) from other smearing
0274     //  effects, specific to each coordinate.
0275     double time_smearing = gaussian(generator) * m_cfg.timeResolution;
0276 
0277     // ***** REFERENCE SUBVOLUME
0278     CellID refID      = sim_hit.getCellID() & m_moduleBits;
0279     DetElement refVol = volman.lookupDetElement(refID);
0280     // ***** COALESCE ALL MUTUALLY CONSISTENT SUBHITS
0281     //       EXTEND TRAVERSING SUBHITS
0282     // - Needed because we want to preserve the correlation between 'p' and
0283     //  'n' strip hits resulting from a given I+A process (which is lost when
0284     //  one accumulates hits independently based on cellID).
0285     double lpos[3], eDep, time;
0286     std::vector<std::uint64_t> cIDs;
0287     const auto& shape = refVol.solid();
0288     if (std::string_view{shape.type()} == "TGeoTubeSeg") {
0289       // ********** TUBE GEOMETRY
0290       if (!cCoalesceExtend(input, idx, cIDs, lpos, eDep, time))
0291         continue;
0292     } else if (std::string_view{shape.type()} == "TGeoBBox") {
0293       // ********** BOX GEOMETRY
0294       if (!bCoalesceExtend(input, idx, cIDs, lpos, eDep, time))
0295         continue;
0296     } else {
0297       critical(R"(Bad input data: CellID {:x} has invalid shape "{}")", refID, shape.type());
0298       throw std::runtime_error(R"(Inconsistency: Inappropriate SimHits fed to "MPGDTrackerDigi".)");
0299     }
0300 
0301     // ***** 2D-position on sensitive surface
0302     double surfPos[2];
0303     Position locPos;
0304     if (std::string_view{shape.type()} == "TGeoTubeSeg") {
0305       // Sensitive surface radius = REFERENCE VOLUME radius
0306       const Tube& tRef = refVol.solid();
0307       double R         = (tRef.rMin() + tRef.rMax()) / 2;
0308       double phi       = atan2(lpos[1], lpos[0]);
0309       surfPos[0]       = phi * R;
0310       surfPos[1]       = lpos[2];
0311       locPos           = Position(R * cos(phi), R * sin(phi), lpos[2]);
0312     } else {
0313       locPos = Position(lpos[0], lpos[1], lpos[2]);
0314       if (m_gridAngle != 0.0) { // Transform to strip frame
0315         dd4hep::DDSegmentation::Vector3D position;
0316         position.X = lpos[0];
0317         position.Y = lpos[1];
0318         position   = RotationZ(m_gridAngle) * position;
0319         surfPos[0] = position.X;
0320         surfPos[1] = position.Y;
0321       } else {
0322         surfPos[0] = lpos[0];
0323         surfPos[1] = lpos[1];
0324       }
0325     }
0326 
0327     // ********** WITHIN ACCEPTANCE?
0328     // - It's assumed that strips are so arranged that acceptance is same along
0329     //  the two coordinates. => Let's require 'p' and 'n' strips simultaneously.
0330     if (m_cfg.hasDeadZone && isInActive(refID, locPos, surfPos) != 0x3) {
0331       continue;
0332     }
0333 
0334     // ********** LOOP ON p|n STRIPS
0335     for (int pn = 0; pn < 2; pn++) {
0336       // ***** CLUSTERIZATION
0337       // Cluster = (CellID, energy fraction)
0338       Cluster cluster;
0339       int status = get2HitCluster(refID, locPos, surfPos, pn, generator, cluster);
0340       if (status != 0) {
0341         CellID vIDs = (std::uint32_t)refID;
0342         CellID hIDs = refID >> 32;
0343         error(R"(SimHit (= 0x{:08x}, 0x{:08x}, {:.2f},{:.2f} cm) beyond limits of {}Strips.)", hIDs,
0344               vIDs, surfPos[0] / cm, surfPos[1] / cm, (pn != 0) ? 'n' : 'p');
0345       }
0346       // ***** DEBUGGING INFO
0347       if (level() >= algorithms::LogLevel::kDebug) {
0348         std::string sCellID = (pn != 0) ? "cellIDn" : "cellIDp";
0349         if (pn == 0) {
0350           debug("  =>=>");
0351         }
0352         for (auto clusterHit : cluster) {
0353           CellID cID = clusterHit.first;
0354           CellID hID = cID >> 32;
0355           CellID vID = (std::uint32_t)cID;
0356           debug("Hit {} = 0x{:08x}, 0x{:08x}", sCellID, hID, vID);
0357           debug("  edep = {:.0f} [eV]", clusterHit.second * eDep / eV);
0358         }
0359       }
0360       // ***** APPLY THRESHOLD / STORE (sim_hit -> stripIDs) / ACCUMULATION
0361       // (Note: Threshold is applied first. See issue #1722 in
0362       // "https://github.com/eic/EICrecon/issues/1722".)
0363       std::map<std::uint64_t, edm4eic::MutableRawTrackerHit>& cell_hit_map =
0364           gsl::at(cell_hit_maps, pn);
0365       double g = m_cfg.gain;
0366       for (auto clusterHit : cluster) {
0367         CellID cID = clusterHit.first;
0368         double f   = clusterHit.second;
0369         // Threshold
0370         // - Let's apply same threshold to the two components of the cluster.
0371         // - This, so that cluster position be preserved at Hit Reconstruction
0372         //  time (when clustering is performed).
0373         // => This has the obvious drawback of creating BELOW-THRESHOLD RawHits.
0374         if (eDep < m_cfg.threshold) {
0375           debug("  eDep {:.2f} is below threshold of {:.2f} [keV]", eDep, m_cfg.threshold / keV);
0376           continue;
0377         }
0378         stripID2cIDs[cID]  = cIDs;
0379         double result_time = time + time_smearing;
0380         auto hit_time_stamp =
0381             static_cast<std::int32_t>(std::llround(result_time / edm4eic::unit::ps));
0382         if (!cell_hit_map.contains(cID)) {
0383           // This cell doesn't have hits
0384           cell_hit_map[cID] = {
0385               cID, (std::int32_t)std::llround(eDep * 1e6 * f * g),
0386               hit_time_stamp // ns->ps
0387           };
0388         } else {
0389           // There is previous values in the cell
0390           auto& hit = cell_hit_map[cID];
0391           debug("  Hit already exists in cell ID={}, prev. hit time: {}", cID, hit.getTimeStamp());
0392 
0393           // keep earliest time for hit
0394           hit.setTimeStamp(std::min(hit_time_stamp, hit.getTimeStamp()));
0395 
0396           // sum deposited energy
0397           auto charge = hit.getCharge();
0398           hit.setCharge(charge + (std::int32_t)std::llround(eDep * 1e6 * f * g));
0399         }
0400       }
0401     } // End loop on strip = p,n
0402   } // End loop on sim_hit's
0403 
0404   // ***** RawHit INSTANTIATION AND RawHit<-SimHits ASSOCIATION:
0405   for (auto& cell_hit_map : cell_hit_maps) {
0406     for (const auto& [stripID, hit] : cell_hit_map) {
0407       raw_hits->push_back(hit);
0408       const auto raw_hit = raw_hits->at(raw_hits->size() - 1);
0409       const auto is      = stripID2cIDs.find(stripID);
0410       if (is == stripID2cIDs.end()) {
0411         error(R"(Inconsistency: CellID {:x} not found in "stripID2cIDs" map)", stripID);
0412         throw std::runtime_error(R"(Inconsistency in the handling of "stripID2cIDs" map)");
0413       }
0414       std::vector<std::uint64_t> cIDs = is->second;
0415       for (CellID cID : cIDs) {
0416         for (const auto& sim_hit : *sim_hits) {
0417           if (sim_hit.getCellID() == cID) {
0418             // create link
0419             auto link = links->create();
0420             link.setFrom(raw_hit);
0421             link.setTo(sim_hit);
0422             link.setWeight(1.0);
0423             // set association
0424             auto hitassoc = associations->create();
0425             hitassoc.setWeight(1.0);
0426             hitassoc.setRawHit(raw_hit);
0427             hitassoc.setSimHit(sim_hit);
0428           }
0429         }
0430       }
0431     }
0432   }
0433 }
0434 
0435 //  The whole of MPGDTrackerDigi relies on a number of assumptions concerning
0436 // the structure of the MPGD detector and its subdivision into SUBVOLUMES.
0437 // These assumptions imply in turn a specific segmentation scheme. In
0438 // particular, a MultiSegmentation allowing to navigate among the SUBVOLUMES.
0439 // This MultiSegmentation, based on a "strip" discriminator, cf. IDDescriptor,
0440 // can be embedded in yet another MultiSegmentation (case of 8-sector CyMBaL).
0441 //  On the other hand, the CLUSTERIZATION procedure requires accessing
0442 // segmentation parameters (pitch, offset, etc...), which in turn requires a
0443 // navigation through the multiple levels of MultiSegmentation. In order to
0444 // simplify this navigation, we decide to impose the following strict schemes:
0445 // - CyMBaL (identified by its <readout> name, viz.: "MPGDBarrelHits"):
0446 //   + (Optional) MultiSegmentation discriminating on "sensor",
0447 //   + MultiSegmentation discriminating on "strip",
0448 //   + CylindricalGridPhiZ, with 'p' = "phi" and 'n' = "z".
0449 // - OuterBarrel ("OuterMPGDBarrelHits"):
0450 //   + MultiSegmentation discriminating on "strip",
0451 //   + CartesianGridUV, with 'p' = "u" and 'n' = "v".
0452 // - Else:
0453 //   + MultiSegmentation discriminating on "strip",
0454 //   + CartesianGridXY, with 'p' = "x" and 'n' = "y".
0455 //  Additional restrictions:
0456 // I) Concerning parameters:
0457 //  Resolution sigma must be small enough compared to pitch that smearing does
0458 // not bring us beyond closest neighbor.
0459 // II) Concerning IDDescriptor:
0460 //  The two coordinate fields span [32,48[ and [48,64[, cf. "(in|de)crementID".
0461 // => Let's check.
0462 void MPGDTrackerDigi::parseIDDescriptor() {
0463   // Parse IDDescriptor: Retrieve CellIDs of relevant fields.
0464   // (As an illustration, here is the IDDescriptor of CyMBaL (as of 2025/11):
0465   // <id>system:8,layer:4,module:12,sensor:2,strip:28:4,phi:-16,z:-16</id>.)
0466 
0467   // - "m_volumeBits" (Volume = CellID excluding channel specification)
0468   // - "m_stripBits".
0469   // - "m_sensorStripBits"
0470   debug(R"(Parsing IDDescriptor for "{}" readout)", m_cfg.readout);
0471   CellID sensorBits = 0;
0472   for (int field = 0; field < 5; field++) {
0473     const char* fieldName = m_fieldNames[field];
0474     CellID fieldID        = 0;
0475     try {
0476       fieldID = m_id_dec->get(~((CellID)0x0), fieldName);
0477     } catch (const std::runtime_error& error) {
0478       critical(R"(No field "{}" in IDDescriptor of readout "{}".)", fieldName, m_cfg.readout);
0479       throw std::runtime_error("Invalid IDDescriptor");
0480     }
0481     const BitFieldElement& fieldElement = (*m_id_dec)[fieldName];
0482     CellID fieldBits                    = fieldID << fieldElement.offset();
0483     m_volumeBits |= fieldBits;
0484     // - "m_stripBits".
0485     if (std::string_view{fieldName} == "strip") {
0486       m_stripBits = fieldBits;
0487       // SUBVOLUMES are assigned specific bits by convention
0488       CellID bits[5] = {0x3, 0x1, 0, 0x2, 0x4};
0489       for (int subVolume = 0; subVolume < 5; subVolume++) {
0490         m_stripIDs[subVolume] = bits[subVolume] << fieldElement.offset();
0491       }
0492     }
0493     // - "m_sensorStripBits"
0494     else if (m_cfg.readout == "MPGDBarrelHits" && std::string_view{fieldName} == "sensor") {
0495       sensorBits     = fieldBits;
0496       m_sensorOffset = fieldElement.offset();
0497     }
0498   }
0499   // CellIDs derived from above
0500   m_moduleBits = m_volumeBits & ~m_stripBits;
0501   m_pStripBit  = m_stripIDs[1];
0502   m_nStripBit  = m_stripIDs[3];
0503   // Sensor|strip mask: Will serve to index the parameter map.
0504   if (m_cfg.readout == "MPGDBarrelHits") {
0505     m_sensorStripBits = sensorBits | m_stripBits;
0506   } else {
0507     m_sensorStripBits = m_stripBits;
0508   }
0509   // Get coordinate field and index.
0510   // Require coordinate fields to start @ bits 32 and 48. This is taken
0511   // advantage of by "(in|de)crementID" (and by debug messages, to cleanly
0512   // separate coordinates from the rest of CellID).
0513   int coordOffsets[2] = {64, 64};
0514   for (int pn = 0; pn < 2; pn++) {
0515     std::string coordName;
0516     if (m_cfg.readout == "MPGDBarrelHits") {
0517       coordName = pn ? "z" : "phi";
0518     } else if (m_cfg.readout == "OuterMPGDBarrelHits") {
0519       coordName = pn ? "v" : "u";
0520     } else {
0521       coordName = pn ? "y" : "x";
0522     }
0523     try {
0524       m_stripIndices[pn] = m_id_dec->index(coordName);
0525     } catch (const std::runtime_error& error) {
0526       critical(R"(No "{}" field in IDDescriptor of readout "{}".)", coordName, m_cfg.readout);
0527       throw std::runtime_error("Invalid IDDescriptor");
0528     }
0529     const BitFieldElement& fieldElement = (*m_id_dec)[coordName];
0530     int offset                          = fieldElement.offset();
0531     m_stripIncs[pn]                     = ((CellID)0x1) << offset;
0532     if (offset < coordOffsets[pn])
0533       coordOffsets[pn] = offset;
0534   }
0535   if (coordOffsets[0] != 32 || coordOffsets[1] != 48) {
0536     critical(R"(Coordinate fields in IDDescriptor of readout "{}" do not start @ bits 32 and 48.)",
0537              m_cfg.readout);
0538     throw std::runtime_error("Invalid IDDescriptor");
0539   }
0540 }
0541 void MPGDTrackerDigi::parseSegmentation() {
0542   debug(R"(Find valid "MultiSegmentation" for "{}" readout.)", m_cfg.readout);
0543 
0544   // Local function: Check restriction (I).
0545   std::function<void(int, double)> checkResolutionVsPitch = [&](int pn, double pitch) {
0546     double sigma = gsl::at(m_cfg.stripResolutions, pn);
0547     if (m_truncation * sigma > pitch) {
0548       critical(R"(stripResolutions[{}] (= {} um) too large for pitch (={} mm) of "{}" readout.)",
0549                pn, sigma / dd4hep::um, pitch / dd4hep::mm, m_cfg.readout);
0550       throw std::runtime_error("Space resolution parameter too large");
0551     }
0552     return;
0553   };
0554   // Local function: Get CylindricalGridPhiZ Parameters
0555   StripParameters pars{};
0556   using PhiZSeg = dd4hep::DDSegmentation::CylindricalGridPhiZ;
0557   std::function<void(const PhiZSeg&, unsigned int)> getGridPhiZParams = [&](const PhiZSeg& gridPhiZ,
0558                                                                             unsigned int stripID) {
0559     double radius = gridPhiZ.radius();
0560     int pn        = 0;
0561     if (stripID == m_pStripBit) {
0562       pars.pitch  = gridPhiZ.gridSizePhi() * radius;
0563       pars.offset = gridPhiZ.offsetPhi() * radius;
0564       pn          = 0;
0565     } else {
0566       pars.pitch  = gridPhiZ.gridSizeZ();
0567       pars.offset = gridPhiZ.offsetZ();
0568       pn          = 1;
0569     }
0570     pars.index = gsl::at(m_stripIndices, pn);
0571     // Check restriction (I)
0572     checkResolutionVsPitch(pn, pars.pitch);
0573     int nStrips = gsl::at(m_cfg.stripNumbers, pn);
0574     // The center of the Cartesian grid is at the center of the detector, see, e.g.:
0575     //  "https://github.com/HEP-FCC/FCCDetectors/blob/main/doc/DD4hepInFCCSW.md".
0576     // I(Y.B.) recommend an offset = pitch/2, so that layout be symmetric, i.e.
0577     // min = -max.
0578     pars.max = (+nStrips / 2. - .5) * pars.pitch + pars.offset;
0579     pars.min = (-nStrips / 2. - .5) * pars.pitch + pars.offset;
0580   };
0581   using Segmentation               = dd4hep::DDSegmentation::Segmentation;
0582   const Segmentation* segmentation = m_seg->segmentation;
0583   // ***** RETRIEVE <segmentation> PARAMETERS: pitch, offset, min, max, index.
0584   unsigned int required  = 0;
0585   unsigned int fulfilled = 0;
0586   bool isCyMBaL_8S       = false;
0587   if (segmentation->type() == "MultiSegmentation") {
0588     using MultiSegmentation = dd4hep::DDSegmentation::MultiSegmentation;
0589     const auto* multiSeg    = dynamic_cast<const MultiSegmentation*>(segmentation);
0590     if (m_cfg.readout == "MPGDBarrelHits") {
0591       // ********** "MPGDBarrelHits": SPECIFIC CASE of 8-SECTOR CyMBaL
0592       required              = 0x3 | m_pStripBit | m_nStripBit; // 0x3 sectors | stripBits
0593       unsigned int innerBit = 0x0;
0594       unsigned int outerBit = 0x1;
0595       for (unsigned int sectorBit : {innerBit, outerBit}) {
0596         CellID sensorID               = ((CellID)sectorBit) << m_sensorOffset;
0597         const Segmentation& sectorSeg = multiSeg->subsegmentation(sensorID);
0598         if (sectorSeg.type() == "MultiSegmentation") {
0599           isCyMBaL_8S = true;
0600         } else {
0601           continue;
0602         }
0603         const auto& stripMultiSeg = dynamic_cast<const MultiSegmentation&>(sectorSeg);
0604         for (CellID stripID : {m_pStripBit, m_nStripBit}) {
0605           const Segmentation& stripSeg = stripMultiSeg.subsegmentation(stripID);
0606           if (stripSeg.type() != "CylindricalGridPhiZ") {
0607             critical(
0608                 R"(Segmentation type for "{}" readout = "{}", whereas expected = "CylindricalGridPhiZ".)",
0609                 m_cfg.readout, stripSeg.type());
0610             continue;
0611           }
0612           const auto& gridPhiZ = dynamic_cast<const PhiZSeg&>(stripSeg);
0613           fulfilled |= sectorBit == innerBit ? 0x1 : 0x2;
0614           fulfilled |= stripID;
0615           // Get parameters into "pars"
0616           getGridPhiZParams(gridPhiZ, stripID);
0617           // "pars" stored in "m_stripParameters" map.
0618           CellID sensorStripID             = sensorID | stripID;
0619           m_stripParameters[sensorStripID] = pars;
0620         }
0621       }
0622     }
0623     if (!isCyMBaL_8S && m_cfg.readout == "MPGDBarrelHits") {
0624       // ********** "MPGDBarrelHits": SPECIFIC CASE of 12-SECTOR CyMBaL
0625       required = m_pStripBit | m_nStripBit;
0626       for (unsigned int stripID : {m_pStripBit, m_nStripBit}) {
0627         const dd4hep::DDSegmentation::Segmentation& stripSeg = multiSeg->subsegmentation(stripID);
0628         if (stripSeg.type() != "CylindricalGridPhiZ") {
0629           critical(
0630               R"(Segmentation type for "{}" readout = "{}", whereas expected = "CylindricalGridPhiZ".)",
0631               m_cfg.readout, stripSeg.type());
0632           continue;
0633         }
0634         const auto& gridPhiZ = dynamic_cast<const PhiZSeg&>(stripSeg);
0635         fulfilled |= stripID;
0636         // Get parameters into "pars"
0637         getGridPhiZParams(gridPhiZ, stripID);
0638         // "pars" stored in "m_stripParameters" map.
0639         m_stripParameters[stripID] = pars;
0640       }
0641     }
0642     if (m_cfg.readout == "OuterMPGDBarrelHits") {
0643       // ********** SPECIFIC CASE: "OuterMPGDBarrelHits"
0644       required = m_pStripBit | m_nStripBit;
0645       double gridAngles[2];
0646       for (unsigned int stripID : {m_pStripBit, m_nStripBit}) {
0647         const dd4hep::DDSegmentation::Segmentation& stripSeg = multiSeg->subsegmentation(stripID);
0648         if (stripSeg.type() != "CartesianGridUV") {
0649           critical(
0650               R"(Segmentation type for "{}" readout = "{}", whereas expected = "CartesianGridUV".)",
0651               m_cfg.readout, stripSeg.type());
0652           continue;
0653         }
0654         const dd4hep::DDSegmentation::CartesianGridUV& gridUV =
0655             dynamic_cast<const dd4hep::DDSegmentation::CartesianGridUV&>(stripSeg);
0656         fulfilled |= stripID;
0657         // Parameters -> StripParameters "pars"
0658         int pn;
0659         if (stripID == m_pStripBit) {
0660           pars.pitch  = gridUV.gridSizeU();
0661           pars.offset = gridUV.offsetU();
0662           pn          = 0;
0663         } else {
0664           pars.pitch  = gridUV.gridSizeV();
0665           pars.offset = gridUV.offsetV();
0666           pn          = 1;
0667         }
0668         pars.index     = m_stripIndices[pn];
0669         gridAngles[pn] = gridUV.gridAngle();
0670         // Check restriction (I)
0671         checkResolutionVsPitch(pn, pars.pitch);
0672         int nStrips = gsl::at(m_cfg.stripNumbers, pn);
0673         pars.max    = (+nStrips / 2. - .5) * pars.pitch + pars.offset;
0674         pars.min    = (-nStrips / 2. - .5) * pars.pitch + pars.offset;
0675         // "pars" stored in "m_stripParameters" map.
0676         m_stripParameters[stripID] = pars;
0677       }
0678       if (fabs(gridAngles[0] - gridAngles[1]) > 1e-6) {
0679         critical(
0680             R"(Inconsistent gridAngles of "CartesianGridUV" for readout "{}": 'p' = {:.6f}, 'n' = {:.6f}.)",
0681             m_cfg.readout, gridAngles[0], gridAngles[1]);
0682         fulfilled = 0;
0683       }
0684       m_gridAngle = gridAngles[0];
0685     } else if (m_cfg.readout != "MPGDBarrelHits") {
0686       // ********** DEFAULT: "CartesianGridXY" Segmentation assumed
0687       required = m_pStripBit | m_nStripBit;
0688       for (unsigned int stripID : {m_pStripBit, m_nStripBit}) {
0689         const dd4hep::DDSegmentation::Segmentation& stripSeg = multiSeg->subsegmentation(stripID);
0690         if (stripSeg.type() != "CartesianGridXY") {
0691           critical(
0692               R"(Segmentation type for "{}" readout = "{}", whereas expected = "CartesianGridXY".)",
0693               m_cfg.readout, stripSeg.type());
0694           continue;
0695         }
0696         const dd4hep::DDSegmentation::CartesianGridXY& gridXY =
0697             dynamic_cast<const dd4hep::DDSegmentation::CartesianGridXY&>(stripSeg);
0698         fulfilled |= stripID;
0699         // Parameters -> StripParameters "pars"
0700         int pn;
0701         if (stripID == m_pStripBit) {
0702           pars.pitch  = gridXY.gridSizeX();
0703           pars.offset = gridXY.offsetX();
0704           pn          = 0;
0705         } else {
0706           pars.pitch  = gridXY.gridSizeY();
0707           pars.offset = gridXY.offsetY();
0708           pn          = 1;
0709         }
0710         pars.index = m_stripIndices[pn];
0711         // Check restriction (I)
0712         checkResolutionVsPitch(pn, pars.pitch);
0713         int nStrips = gsl::at(m_cfg.stripNumbers, pn);
0714         pars.max    = (+nStrips / 2. - .5) * pars.pitch + pars.offset;
0715         pars.min    = (-nStrips / 2. - .5) * pars.pitch + pars.offset;
0716         // "pars" stored in "m_stripParameters" map.
0717         m_stripParameters[stripID] = pars;
0718       }
0719     }
0720   } else {
0721     critical(
0722         R"(Segmentation type for "{}" readout = "{}", whereas expected = "MultiSegmentation".)",
0723         m_cfg.readout, segmentation->type());
0724   }
0725   if (fulfilled != required) {
0726     critical(R"(Error retrieving Segmentation parameters for "{}" readout.)", m_cfg.readout);
0727     throw std::runtime_error("Error retrieving Segmentation parameters");
0728   }
0729 }
0730 
0731 // ***** COALESCE subHits with same PMO
0732 //       EXTEND hits (subHits or coalesced hits) to full sensitive volume
0733 // - Input = Elementary subHit, specified as index into collection of SimHits.
0734 // - Output = Coalesced/extended hit, specified by:
0735 //  + list of cellIDs of elementary subHits contributing,
0736 //  + local position,
0737 //  + EDep,
0738 //  + time.
0739 //   Given that all segmentation classes foreseen for MPGDs ("CartesianGrid.."
0740 //  for Outer and EndCaps, "CylindricalGridPhiZ" for "CyMBaL") disregard the
0741 //  _global_ position argument to "dd4hep::Segmentation::cellID", we need
0742 //  the _local_ position and only that.
0743 // - Also returned: updated index.
0744 bool MPGDTrackerDigi::cCoalesceExtend(const Input& input, int& idx,
0745                                       std::vector<std::uint64_t>& cIDs, double* lpos, double& eDep,
0746                                       double& time) const {
0747   const auto [headers, sim_hits]        = input;
0748   const edm4hep::EventHeader& header    = headers->at(0);
0749   const edm4hep::SimTrackerHit& sim_hit = sim_hits->at(idx);
0750   CellID vID                            = sim_hit.getCellID() & m_volumeBits;
0751   CellID refID                          = vID & m_moduleBits; // => The REFERENCE SUBVOLUME
0752   const VolumeManager& volman           = m_detector->volumeManager();
0753   DetElement refVol                     = volman.lookupDetElement(refID);
0754   // TGeoHMatrix: In order to avoid a "dangling-reference" warning, let's take
0755   // a copy of the matrix instead of a reference to it.
0756   const TGeoHMatrix toRefVol = refVol.nominal().worldTransformation();
0757   double lmom[3];
0758   getLocalPosMom(sim_hit, toRefVol, lpos, lmom);
0759   const double edmm = edm4eic::unit::mm, ed2dd = dd4hep::mm / edmm;
0760   using dd4hep::mm;
0761   using edm4eic::unit::eV, edm4eic::unit::GeV;
0762   // Hit in progress
0763   eDep = sim_hit.getEDep();
0764   time = sim_hit.getTime();
0765   // Get VOLUME parameters
0766   const Tube& tRef = refVol.solid();
0767   double dZ        = tRef.dZ();
0768   // phi?
0769   // In "https://root.cern.ch/root/html534/guides/users-guide/Geometry.html"
0770   // TGeoTubeSeg: "phi1 is converted to [0,360] (but still expressed in
0771   // radian, as far as I can tell) and phi2 > phi1."
0772   // => Convert it to [-pi,+pi].
0773   double startPhi = tRef.startPhi() * radian;
0774   startPhi -= 2 * TMath::Pi();
0775   double endPhi = tRef.endPhi() * radian;
0776   endPhi -= 2 * TMath::Pi();
0777   // Get current SUBVOLUME
0778   DetElement curVol = volman.lookupDetElement(vID);
0779   const Tube& tCur  = curVol.solid();
0780   double rMin = tCur.rMin(), rMax = tCur.rMax();
0781   // Is TRAVERSING?
0782   double lintos[2][3], louts[2][3], lpini[3], lpend[3], lmend[3];
0783   std::copy(std::begin(lmom), std::end(lmom), std::begin(lmend));
0784   unsigned int status =
0785       cTraversing(lpos, lmom, sim_hit.getPathLength() * ed2dd, sim_hit.isProducedBySecondary(),
0786                   rMin, rMax, dZ, startPhi, endPhi, lintos, louts, lpini, lpend);
0787   if (status & m_inconsistency) { // Inconsistency => Drop current "sim_hit"
0788     error(inconsistency(header, status, sim_hit.getCellID(), lpos, lmom));
0789     return false;
0790   }
0791   cIDs.push_back(sim_hit.getCellID());
0792   std::vector<int> subHitList;
0793   if (level() >= algorithms::LogLevel::kDebug) {
0794     subHitList.push_back(idx);
0795   }
0796   // Continuations?
0797   bool isContinuation  = status & (m_intoLower | m_intoUpper);
0798   bool hasContinuation = status & (m_outLower | m_outUpper);
0799   bool canReEnter      = status & m_canReEnter;
0800   int rank             = m_stripRank(vID);
0801   if (!canReEnter) {
0802     if (rank == 0 && (status & m_intoLower))
0803       isContinuation = false;
0804     if (rank == 0 && (status & m_outLower))
0805       hasContinuation = false;
0806   }
0807   if (rank == 4 && (status & m_intoUpper))
0808     isContinuation = false;
0809   if (rank == 4 && (status & m_outUpper))
0810     hasContinuation = false;
0811   if (hasContinuation) {
0812     // ***** LOOP OVER HITS
0813     int jdx;
0814     CellID vIDPrv   = vID;
0815     size_t sim_size = sim_hits->size();
0816     for (jdx = idx + 1; jdx < (int)sim_size; jdx++) {
0817       const edm4hep::SimTrackerHit& sim_hjt = sim_hits->at(jdx);
0818       CellID vJD                            = sim_hjt.getCellID() & m_volumeBits;
0819       // Particle may start inward and re-enter, being then outward-going.
0820       // => Orientation has to be evaluated w.r.t. previous vID.
0821       int orientation = m_orientation(vIDPrv, vJD);
0822       bool isUpstream = m_isUpstream(orientation, status);
0823       bool pmoStatus  = samePMO(sim_hit, sim_hjt);
0824       if (!pmoStatus || !isUpstream) {
0825         if ((pmoStatus && !isUpstream) && !sim_hit.isProducedBySecondary()) {
0826           // Bizarre, except if it's a low energy stuff (when it then can be a
0827           // looping particle). If it's not let's flag the case, for debugging.
0828           double P = sqrt(lmom[0] * lmom[0] + lmom[1] * lmom[1] + lmom[2] * lmom[2]);
0829           if (P > 10 * dd4hep::MeV)
0830             debug(inconsistency(header, 0, sim_hit.getCellID(), lpos, lmom));
0831         }
0832         break;
0833       }
0834       // Get 'j' radii
0835       curVol           = volman.lookupDetElement(vJD);
0836       const Tube& tubj = curVol.solid();
0837       rMin             = tubj.rMin();
0838       rMax             = tubj.rMax();
0839       double lpoj[3], lmoj[3];
0840       getLocalPosMom(sim_hjt, toRefVol, lpoj, lmoj);
0841       // Is TRAVERSING through the (quasi-)common wall?
0842       double ljns[2][3], lovts[2][3], lpjni[3], lpfnd[3];
0843       status =
0844           cTraversing(lpoj, lmoj, sim_hjt.getPathLength() * ed2dd, sim_hit.isProducedBySecondary(),
0845                       rMin, rMax, dZ, startPhi, endPhi, ljns, lovts, lpjni, lpfnd);
0846       if (status & m_inconsistency) { // Inconsistency => Drop current "sim_hjt"
0847         error(inconsistency(header, status, sim_hjt.getCellID(), lpoj, lmoj));
0848         break;
0849       }
0850       // ij-Compatibility: status
0851       bool jsDownstream = m_isDownstream(orientation, status);
0852       if (!jsDownstream)
0853         break;
0854       // ij-Compatibility: close exit/entrance-distance
0855       double dist = outInDistance(0, orientation, ljns, louts, lmom, lmoj);
0856       // RELAXED TOLERANCE for low energy stuff
0857       double P          = sqrt(lmom[0] * lmom[0] + lmom[1] * lmom[1] + lmom[2] * lmom[2]);
0858       double tolerance  = m_toleranceFactor(P) * 25 * dd4hep::um;
0859       bool isCompatible = dist > 0 && dist < tolerance;
0860       if (!isCompatible) {
0861         if (!sim_hit.isProducedBySecondary())
0862           debug(oddity(header, status, dist, sim_hit.getCellID(), lpos, lmom,
0863                        /* */ sim_hjt.getCellID(), lpoj, lmoj));
0864         break;
0865       }
0866       // ***** UPDATE
0867       vIDPrv = vJD;
0868       eDep += sim_hjt.getEDep();
0869       for (int i = 0; i < 3; i++) { // Update end point position/momentum.
0870         lpend[i] = lpfnd[i];
0871         lmend[i] = lmoj[i];
0872       }
0873       // ***** BOOK-KEEPING
0874       cIDs.push_back(sim_hjt.getCellID());
0875       if (level() >= algorithms::LogLevel::kDebug) {
0876         subHitList.push_back(jdx);
0877       }
0878       // ***** CONTINUATION?
0879       hasContinuation = status & 0xa;
0880       canReEnter      = status & 0x100;
0881       if (!canReEnter && m_stripRank(vJD) == 4)
0882         hasContinuation = false;
0883       if (!hasContinuation) {
0884         jdx++;
0885         break;
0886       } else { // Update outgoing position/momentum for next iteration.
0887         for (int i = 0; i < 3; i++) {
0888           louts[0][i] = lovts[0][i];
0889           louts[1][i] = lovts[1][i];
0890         }
0891       }
0892     }
0893     idx = jdx - 1;
0894   }
0895   // ***** EXTENSION?...
0896   if (sim_hit.isProducedBySecondary() && cIDs.size() < 2)
0897     if (denyExtension(sim_hit, tCur.rMax() - tCur.rMin())) {
0898       isContinuation = hasContinuation = false;
0899     }
0900   for (int io = 0; io < 2; io++) { // ...into/out-of
0901     if ((io == 0 && !isContinuation) || (io == 1 && !hasContinuation))
0902       continue;
0903     int direction = io ? +1 : -1;
0904     extendHit(refID, cIDs, direction, lpini, lmom, lpend, lmend);
0905   }
0906   // ***** FLAG CASES W/ UNEXPECTED OUTCOME
0907   flagUnexpected(header, 0, (tRef.rMin() + tRef.rMax()) / 2, sim_hit, lpini, lpend, lpos, lmom);
0908   // ***** UPDATE (local position <lpos>, DoF)
0909   double DoF2 = 0, dir = 0;
0910   for (int i = 0; i < 3; i++) {
0911     double neu = (lpini[i] + lpend[i]) / 2, alt = lpos[i];
0912     lpos[i]  = neu;
0913     double d = neu - alt;
0914     dir += d * lmom[i];
0915     DoF2 += d * d;
0916   }
0917   // Update time by ToF from original subHit to extended/COALESCED.
0918   time += ((dir > 0) ? 1 : ((dir < 0) ? -1 : 0)) * sqrt(DoF2) / dd4hep::c_light;
0919   if (level() >= algorithms::LogLevel::kDebug) {
0920     debug("--------------------");
0921     printSubHitList(input, subHitList);
0922     debug("  =");
0923     // Print position, eDep and time of coalesced/extended hit
0924     Position locPos(lpos[0], lpos[1], lpos[2]); // Simplification: strip surface = REFERENCE surface
0925     Position globPos = refVol.nominal().localToWorld(locPos);
0926     debug("  position  = ({:7.2f},{:7.2f},{:7.2f}) [mm]", globPos.X() / mm, globPos.Y() / mm,
0927           globPos.Z() / mm);
0928     debug("  edep = {:.0f} [eV]", eDep / eV);
0929     debug("  time = {:.2f} [ns]", time);
0930   }
0931   return true;
0932 }
0933 bool MPGDTrackerDigi::bCoalesceExtend(const Input& input, int& idx,
0934                                       std::vector<std::uint64_t>& cIDs, double* lpos, double& eDep,
0935                                       double& time) const {
0936   const auto [headers, sim_hits]        = input;
0937   const edm4hep::EventHeader& header    = headers->at(0);
0938   const edm4hep::SimTrackerHit& sim_hit = sim_hits->at(idx);
0939   CellID vID                            = sim_hit.getCellID() & m_volumeBits;
0940   CellID refID                          = vID & m_moduleBits; // => The REFERENCE SUBVOLUME
0941   const VolumeManager& volman           = m_detector->volumeManager();
0942   DetElement refVol                     = volman.lookupDetElement(refID);
0943   // TGeoHMatrix: In order to avoid a "dangling-reference" warning, let's take
0944   // a copy of the matrix instead of a reference to it.
0945   const TGeoHMatrix toRefVol = refVol.nominal().worldTransformation();
0946   double lmom[3];
0947   getLocalPosMom(sim_hit, toRefVol, lpos, lmom);
0948   const double edmm = edm4eic::unit::mm, ed2dd = dd4hep::mm / edmm;
0949   using dd4hep::mm;
0950   using edm4eic::unit::eV, edm4eic::unit::GeV;
0951   // Hit in progress
0952   eDep = sim_hit.getEDep();
0953   time = sim_hit.getTime();
0954   // Get VOLUME parameters
0955   const Box& bRef = refVol.solid(); // REFERENCE SUBVOLUME
0956   double dX = bRef.x(), dY = bRef.y();
0957   // Get current SUBVOLUME
0958   DetElement curVol = volman.lookupDetElement(vID);
0959   const Box& bCur   = curVol.solid();
0960   double dZ         = bCur.z();
0961   double ref2Cur    = getRef2Cur(refVol, curVol);
0962   // Is TRAVERSING?
0963   double lintos[2][3], louts[2][3], lpini[3], lpend[3], lmend[3];
0964   std::copy(std::begin(lmom), std::end(lmom), std::begin(lmend));
0965   unsigned int status =
0966       bTraversing(lpos, lmom, ref2Cur, sim_hit.getPathLength() * ed2dd,
0967                   sim_hit.isProducedBySecondary(), dZ, dX, dY, lintos, louts, lpini, lpend);
0968   if (status & m_inconsistency) { // Inconsistency => Drop current "sim_hit"
0969     error(inconsistency(header, status, sim_hit.getCellID(), lpos, lmom));
0970     return false;
0971   }
0972   cIDs.push_back(sim_hit.getCellID());
0973   std::vector<int> subHitList;
0974   if (level() >= algorithms::LogLevel::kDebug) {
0975     subHitList.push_back(idx);
0976   }
0977   // Continuations?
0978   int rank             = m_stripRank(vID);
0979   bool isContinuation  = status & (m_intoLower | m_intoUpper);
0980   bool hasContinuation = status & (m_outLower | m_outUpper);
0981   if ((rank == 0 && (status & m_intoLower)) || (rank == 4 && (status & m_intoUpper)))
0982     isContinuation = false;
0983   if ((rank == 0 && (status & m_outLower)) || (rank == 4 && (status & m_outUpper)))
0984     hasContinuation = false;
0985   if (hasContinuation) {
0986     // ***** LOOP OVER SUBHITS
0987     int jdx;
0988     CellID vIDPrv   = vID;
0989     size_t sim_size = sim_hits->size();
0990     for (jdx = idx + 1; jdx < (int)sim_size; jdx++) {
0991       const edm4hep::SimTrackerHit& sim_hjt = sim_hits->at(jdx);
0992       CellID vJD                            = sim_hjt.getCellID() & m_volumeBits;
0993       int orientation                       = m_orientation(vIDPrv, vJD);
0994       bool isUpstream                       = m_isUpstream(orientation, status);
0995       bool pmoStatus                        = samePMO(sim_hit, sim_hjt);
0996       if (!pmoStatus || !isUpstream) {
0997         if ((pmoStatus && !isUpstream) && !sim_hit.isProducedBySecondary()) {
0998           // Bizarre: let's flag the case for debugging, if not low energy.
0999           double P = sqrt(lmom[0] * lmom[0] + lmom[1] * lmom[1] + lmom[2] * lmom[2]);
1000           if (P > 10 * dd4hep::MeV)
1001             debug(inconsistency(header, 0, sim_hit.getCellID(), lpos, lmom));
1002         }
1003         break;
1004       }
1005       // Get 'j' Z
1006       curVol          = volman.lookupDetElement(vJD); // 'j' SUBVOLUME
1007       const Box& boxj = curVol.solid();
1008       dZ              = boxj.z();
1009       double ref2j    = getRef2Cur(refVol, curVol);
1010       // Is TRAVERSING through the (quasi)-common border?
1011       double lpoj[3], lmoj[3];
1012       getLocalPosMom(sim_hjt, toRefVol, lpoj, lmoj);
1013       double ljns[2][3], lovts[2][3], lpjni[3], lpfnd[3];
1014       status = bTraversing(lpoj, lmoj, ref2j, sim_hjt.getPathLength() * ed2dd,
1015                            sim_hit.isProducedBySecondary(), dZ, dX, dY, ljns, lovts, lpjni, lpfnd);
1016       if (status & m_inconsistency) { // Inconsistency => Drop current "sim_hjt"
1017         error(inconsistency(header, status, sim_hjt.getCellID(), lpoj, lmoj));
1018         break;
1019       }
1020       // ij-Compatibility: status
1021       bool jsDownstream = m_isDownstream(orientation, status);
1022       if (!jsDownstream)
1023         break;
1024       // ij-Compatibility: close exit/entrance-distance
1025       double dist = outInDistance(1, orientation, ljns, louts, lmom, lmoj);
1026       // RELAXED TOLERANCE for low energy stuff
1027       double P          = sqrt(lmom[0] * lmom[0] + lmom[1] * lmom[1] + lmom[2] * lmom[2]);
1028       double tolerance  = m_toleranceFactor(P) * 25 * dd4hep::um;
1029       bool isCompatible = dist > 0 && dist < tolerance;
1030       if (!isCompatible) {
1031         if (!sim_hit.isProducedBySecondary())
1032           debug(oddity(header, status, dist, sim_hit.getCellID(), lpos, lmom,
1033                        /* */ sim_hjt.getCellID(), lpoj, lmoj));
1034         break;
1035       }
1036       // ***** UPDATE
1037       vIDPrv = vJD;
1038       eDep += sim_hjt.getEDep();
1039       for (int i = 0; i < 3; i++) { // Update end point position/momentum.
1040         lpend[i] = lpfnd[i];
1041         lmend[i] = lmoj[i];
1042       }
1043       // ***** BOOK-KEEPING
1044       cIDs.push_back(sim_hjt.getCellID());
1045       if (level() >= algorithms::LogLevel::kDebug) {
1046         subHitList.push_back(jdx);
1047       }
1048       // ***** CONTINUATION?
1049       hasContinuation = status & 0xa;
1050       if (!hasContinuation) {
1051         jdx++;
1052         break;
1053       } else { // Update outgoing position/momentum for next iteration.
1054         for (int i = 0; i < 3; i++) {
1055           louts[0][i] = lovts[0][i];
1056           louts[1][i] = lovts[1][i];
1057         }
1058       }
1059     }
1060     idx = jdx - 1;
1061   }
1062   // ***** EXTENSION?...
1063   if (sim_hit.isProducedBySecondary() && cIDs.size() < 2)
1064     if (denyExtension(sim_hit, bCur.z())) {
1065       isContinuation = hasContinuation = false;
1066     }
1067   for (int io = 0; io < 2; io++) { // ...into/out-of
1068     if ((io == 0 && !isContinuation) || (io == 1 && !hasContinuation))
1069       continue;
1070     int direction = io ? +1 : -1;
1071     extendHit(refID, cIDs, direction, lpini, lmom, lpend, lmend);
1072   }
1073   // ***** FLAG CASES W/ UNEXPECTED OUTCOME
1074   flagUnexpected(header, 1, 0, sim_hit, lpini, lpend, lpos, lmom);
1075   // ***** UPDATE (local position <lpos>, DoF)
1076   double DoF2 = 0, dir = 0;
1077   for (int i = 0; i < 3; i++) {
1078     double neu = (lpini[i] + lpend[i]) / 2, alt = lpos[i];
1079     lpos[i]  = neu;
1080     double d = neu - alt;
1081     dir += d * lmom[i];
1082     DoF2 += d * d;
1083   }
1084   // Update time by ToF from original subHit to extended/COALESCED.
1085   time += ((dir > 0) ? 1 : ((dir < 0) ? -1 : 0)) * sqrt(DoF2) / dd4hep::c_light;
1086   if (level() >= algorithms::LogLevel::kDebug) {
1087     debug("--------------------");
1088     printSubHitList(input, subHitList);
1089     debug("  =");
1090     // Print position, eDep and time of coalesced/extended hit
1091     Position locPos(lpos[0], lpos[1], lpos[2]); // Simplification: strip surface = REFERENCE surface
1092     Position globPos = refVol.nominal().localToWorld(locPos);
1093     debug("  position  = ({:7.2f},{:7.2f},{:7.2f}) [mm]", globPos.X() / mm, globPos.Y() / mm,
1094           globPos.Z() / mm);
1095     debug("  edep = {:.0f} [eV]", eDep / eV);
1096     debug("  time = {:.2f} [ns]", time);
1097   }
1098   return true;
1099 }
1100 void MPGDTrackerDigi::printSubHitList(const Input& input, std::vector<int>& subHitList) const {
1101   const auto [headers, sim_hits] = input;
1102   const double edmm              = edm4eic::unit::mm;
1103   using edm4eic::unit::eV, edm4eic::unit::GeV;
1104   int ldx = 0;
1105   for (int kdx : subHitList) {
1106     const edm4hep::SimTrackerHit& sim_hp = sim_hits->at(kdx);
1107     CellID cIDk                          = sim_hp.getCellID();
1108     CellID hIDk = cIDk >> 32, vIDk = cIDk & m_volumeBits;
1109     if (ldx == 0) {
1110       debug("Hit cellID{:d} = 0x{:08x}, 0x{:08x}", ldx++, hIDk, vIDk);
1111     } else {
1112       debug("  + cellID{:d} = 0x{:08x}, 0x{:08x}", ldx++, hIDk, vIDk);
1113     }
1114     debug("  position  = ({:7.2f},{:7.2f},{:7.2f}) [mm]", sim_hp.getPosition().x / edmm,
1115           sim_hp.getPosition().y / edmm, sim_hp.getPosition().z / edmm);
1116     debug("  xy_radius = {:.2f}",
1117           std::hypot(sim_hp.getPosition().x, sim_hp.getPosition().y) / edmm);
1118     debug("  momentum  = ({:.2f}, {:.2f}, {:.2f}) [GeV]", sim_hp.getMomentum().x / GeV,
1119           sim_hp.getMomentum().y / GeV, sim_hp.getMomentum().z / GeV);
1120     debug("  edep = {:.0f} [eV]", sim_hp.getEDep() / eV);
1121     debug("  time = {:.2f} [ns]", sim_hp.getTime());
1122   }
1123 }
1124 
1125 void getLocalPosMom(const edm4hep::SimTrackerHit& sim_hit, const TGeoHMatrix& toModule,
1126                     double* lpos, double* lmom) {
1127   const edm4hep::Vector3d& pos = sim_hit.getPosition();
1128   // Length: Inputs are in EDM4eic units. Let's move to DD4hep units.
1129   const double edmm = edm4eic::unit::mm, ed2dd = dd4hep::mm / edmm;
1130   const double gpos[3]         = {pos.x * ed2dd, pos.y * ed2dd, pos.z * ed2dd};
1131   const edm4hep::Vector3f& mom = sim_hit.getMomentum();
1132   const double gmom[3]         = {mom.x, mom.y, mom.z};
1133   toModule.MasterToLocal(gpos, lpos);
1134   toModule.MasterToLocalVect(gmom, lmom);
1135 }
1136 
1137 // ******************** TRAVERSING?
1138 // Particle can be born/dead (then its position is not (entrance+exit)/2).
1139 // Or it can exit through the edge.
1140 // - Returned Status code, see header.
1141 //     Also, for internal use:
1142 //     0x10: Enters through edge
1143 //     0x20: Exits  through edge
1144 // - <lintos>/<louts>: Positions @ lower/upper wall upon Enter-/Exit-ing (when endorsed by <status>)
1145 // - <lpini>/<lpend>: Positions of extrema
1146 // - TOLERANCE? For MIPs, a tolerance of 1 µM works fine. But for lower energy,
1147 //  looks like we need something somewhat larger. The ideal would be to base
1148 //  the value on Molière width. Here, I use a somewhat arbitrary built-in.
1149 //  - If particle found to reach wall, w/in tolerance, assign end points to
1150 //   walls (instead of <lpos>+/-path/2). It will make so that the eventual
1151 //   extrapolated position falls exactly at mid-plane, even in the case of a
1152 //   low energy particle, where path may be affected by multiscattering. This,
1153 //   provided that particle is not a secondary.
1154 unsigned int MPGDTrackerDigi::cTraversing(const double* lpos, const double* lmom, double path,
1155                                           bool isSecondary,         // Input subHit
1156                                           double rMin, double rMax, // Current instance of SUBVOLUME
1157                                           double dZ, double startPhi,
1158                                           double endPhi, // Module parameters
1159                                           double lintos[][3], double louts[][3], double* lpini,
1160                                           double* lpend) const {
1161   unsigned int status = 0;
1162   double Mx = lpos[0], My = lpos[1], Mz = lpos[2], M2 = Mx * Mx + My * My;
1163   double Px = lmom[0], Py = lmom[1], Pz = lmom[2];
1164   // Intersection w/ the edge in phi
1165   double tIn = 0, tOut = 0;
1166   for (double phi : {startPhi, endPhi}) {
1167     // M+t*P = 0 + t'*U. t = (My*Ux-Mx*Uy)/(Px*Uy-Py*Ux);
1168     double Ux = cos(phi), Uy = sin(phi);
1169     double D = Px * Uy - Py * Ux;
1170     if (D) { // If P not // to U
1171       double t  = (My * Ux - Mx * Uy) / D;
1172       double Ex = Mx + t * Px, Ey = My + t * Py, Ez = Mz + t * Pz;
1173       double rE = sqrt(Ex * Ex + Ey * Ey), phiE = atan2(Ey, Ex);
1174       // The above does not distinguish between phi and phi+pi.
1175       // => Have to explicitly discard the latter.
1176       if (rMin < rE && rE < rMax && fabs(Ez) < dZ && fabs(phiE - phi) < 1) {
1177         if (t < 0) {
1178           status |= 0x10;
1179           tIn = t;
1180         } else {
1181           status |= 0x20;
1182           tOut = t;
1183         }
1184       }
1185     }
1186   }
1187   // Intersection w/ the edge in Z
1188   double zLow = -dZ, zUp = +dZ;
1189   for (double Z : {zLow, zUp}) {
1190     // Mz+t*Pz = Z
1191     if (Pz) {
1192       double t  = (Z - Mz) / Pz;
1193       double Ex = Mx + t * Px, Ey = My + t * Py, rE = sqrt(Ex * Ex + Ey * Ey);
1194       double phi = atan2(Ey, Ex);
1195       if (rMin < rE && rE < rMax && startPhi < phi && phi < endPhi) {
1196         if (t < 0) {
1197           if (!(status & 0x10) || ((status & 0x10) && t > tIn)) {
1198             status |= 0x10;
1199             tIn = t;
1200           }
1201         } else if (t > 0) {
1202           if (!(status & 0x20) || ((status & 0x20) && t < tOut)) {
1203             status |= 0x20;
1204             tOut = t;
1205           }
1206         }
1207       }
1208     }
1209   }
1210   // Intersection w/ tube walls
1211   double ts[3 /* rMin/rMax/edge */][2 /* In/Out */] = {
1212       {0, 0}, {0, 0}, {tIn, tOut}}; // Up to two intersections
1213   double a = Px * Px + Py * Py, b = Px * Mx + Py * My;
1214   for (int lu = 0; lu < 2; lu++) { // rMin/rMax
1215     double R;
1216     unsigned int statGene;
1217     if (lu == 1) {
1218       R        = rMax;
1219       statGene = 0x4;
1220     } else {
1221       R        = rMin;
1222       statGene = 0x1;
1223     }
1224     double c = M2 - R * R;
1225     if (!a) { // P is // to Z. Yet no intersect w/ Z edge.
1226       if ((status & 0x30) != 0x30)
1227         status |= 0x1000;
1228       continue;      // Inconsistency
1229     } else if (!c) { // Hit is on wall: inconsistency.
1230       status |= 0x2000;
1231       continue;
1232     } else {
1233       double det = b * b - a * c;
1234       if (det < 0) {
1235         if (lu == 1) { // No intersection w/ outer wall: inconsistency.
1236           status |= 0x4000;
1237           continue;
1238         }
1239       } else {
1240         double sqdet = sqrt(det);
1241         for (int is = 0; is < 2; is++) {
1242           int s     = 1 - 2 * is;
1243           double t  = (-b + s * sqdet) / a;
1244           double Ix = Mx + t * Px, Iy = My + t * Py, Iz = Mz + t * Pz, phi = atan2(Iy, Ix);
1245           if (fabs(Iz) > dZ || phi < startPhi || endPhi < phi)
1246             continue;
1247           if (t < 0) {
1248             // Two rMin intersects in same back/forward direction may happen
1249             // (one and and only one of them may then be hidden by edge).
1250             // => Have to allow wall intersect to coexist w/ edge intersect.
1251             //   This only for rMin, but for simplicity's sake...
1252             if (status & statGene) { // Two <0 ts: can only happen when rMin
1253               double tPrv = ts[lu][0];
1254               if (t > tPrv) {
1255                 ts[lu][0] = t;
1256                 ts[lu][1] = tPrv; // Current is actually IN, previous is OUT despite being <0
1257               }
1258               status |= statGene << 1;
1259             } else {
1260               ts[lu][0] = t;
1261               status |= statGene;
1262             }
1263           } else {                        // (if t > 0)
1264             if (status & statGene << 1) { // Two >0 ts: can only happen when rMin
1265               double tPrv = ts[lu][1];
1266               if (t < tPrv) {
1267                 ts[lu][1] = t;
1268                 ts[lu][0] = tPrv; // Current is actually OUT, previous is IN despite being >0
1269               }
1270               status |= statGene;
1271             } else {
1272               ts[lu][1] = t;
1273               status |= statGene << 1;
1274             }
1275           }
1276         }
1277       }
1278     }
1279   }
1280   // Combine w/ edge in/out, based on "t".
1281   // - A priori, wall crossing (conditioned by w/in edges) and edge crossing (
1282   //  conditioned by rMin<rE<rMax) are mutually exclusive...
1283   // - ...This, except when particle re-enters through the lower wall...
1284   // =>
1285   //  - No reEntrance: Let's double-check that the above holds, canceling wall
1286   //   crossing and raising an inconsistency status bit when not.
1287   //  - Else:
1288   //    - If doesReEnter, reEntrance is a mere transient trip outside the
1289   //     SUBVOLUME. => Cancel it.
1290   //    - Else disregard edge, possibly raising an inconsistency status bit.
1291   // Hit lies outside?
1292   // - ...Or when hit position lies outside volume (it can happen, thanks to
1293   //  limited precision).
1294   //  => If this is the case, let's swap their exit vs. entrance status. This
1295   //  will prevent inconsistencies from showing up below.
1296   // Can reEnter: does reEnter?
1297   bool canReEnter = (status & 0x3) == 0x3;
1298   double norm     = sqrt(a + Pz * Pz);
1299   if (canReEnter) {
1300     bool doesReEnter = true;
1301     for (int i12 = 0; i12 < 2; i12++) {
1302       double t               = ts[0][i12];
1303       int s                  = t > 0 ? +1 : -1;
1304       const double tolerance = 20 * dd4hep::um;
1305       if (path / 2 - s * t * norm < tolerance)
1306         doesReEnter = false;
1307     }
1308     if (doesReEnter) {
1309       status &= ~0x3;
1310       canReEnter = false;
1311     }
1312   }
1313   double rHit = sqrt(M2);
1314   if (rHit < rMin && !canReEnter) {
1315     unsigned int statvs = status;
1316     if (statvs & 0x1) {
1317       status &= ~0x1;
1318       status |= 0x2;
1319       ts[0][1] = -ts[0][0];
1320     }
1321     if (statvs & 0x2) {
1322       status &= ~0x2;
1323       status |= 0x1;
1324       ts[0][0] = -ts[0][1];
1325     }
1326   } else if (rHit > rMax) {
1327     unsigned int statvs = status;
1328     if (statvs & 0x4) {
1329       status &= ~0x4;
1330       status |= 0x8;
1331       ts[1][1] = -ts[1][0];
1332     }
1333     if (statvs & 0x8) {
1334       status &= ~0x8;
1335       status |= 0x4;
1336       ts[1][0] = -ts[1][1];
1337     }
1338   }
1339   for (int lu = 0; lu < 2; lu++) { // rMin/rMax
1340     unsigned int statGene = lu ? 0x4 : 0x1;
1341     if (status & statGene) {
1342       double t = ts[lu][0];
1343       if (t < 0) {
1344         if (status & 0x10) {
1345           if (lu == 1 || !canReEnter) { // No reEntrance:
1346             status |= 0x10000;          //   Inconsistency
1347             status &= ~statGene;        //   Cancel wall crossing
1348           } else {                      // ReEntrance: disregard edge crossing
1349             if (t < tIn)
1350               status |= 0x10000; // Inconsistency
1351           }
1352         }
1353       } else { // if (t > 0)
1354         if (status & 0x20) {
1355           if (lu == 1 || !canReEnter) {
1356             status |= 0x20000;
1357             status &= ~statGene;
1358           } else {
1359             if (t > tOut)
1360               status |= 0x20000;
1361           }
1362         }
1363       }
1364     }
1365     if (status & statGene << 1) {
1366       double t = ts[lu][1];
1367       if (t < 0) {
1368         if (status & 0x10) {
1369           if (lu == 1 || !canReEnter) {
1370             status |= 0x40000;
1371             status &= ~(statGene << 1);
1372           } else {
1373             if (t < tIn)
1374               status |= 0x40000;
1375           }
1376         }
1377       } else { // if (t > 0)
1378         if (status & 0x20) {
1379           if (lu == 1 || !canReEnter) {
1380             status |= 0x80000;
1381             status &= ~(statGene << 1);
1382           } else {
1383             if (t > tOut)
1384               status |= 0x80000;
1385           }
1386         }
1387       }
1388     }
1389   }
1390   // Is particle born/dead prior to entering/exiting?
1391   // - sim_hit must have been assigned the mean position: (entrance+exit)/2
1392   // - Let's then check entrance/exit against sim_hit's position +/- path/2.
1393   //   When the latter is too short, it means that the particle firing the
1394   //  hit gets born or dies in the SUBVOLUME ("dying" taken here in the broad
1395   //  sense of undergoing a discrete physics process).
1396   // => We remove the corresponding bit in the <status> pattern.
1397   // - Note that we not only require that the path be long enough, but also
1398   //  that it matches exactly distances to entrance/exit.
1399   if (canReEnter)
1400     status |= 0x100; // Remember that particle can re-enter.
1401   double at           = path / 2 / norm;
1402   unsigned int statws = 0;
1403   for (int is = 0; is < 2; is++) {
1404     int s     = 1 - 2 * is;
1405     double Ix = s * at * Px, Iy = s * at * Py, Iz = s * at * Pz;
1406     for (int lu = 0; lu < 2; lu++) { // Lower/upper wall
1407       unsigned int statvs = lu ? 0x4 : 0x1;
1408       for (int io = 0; io < 2; io++) {
1409         statvs <<= io;
1410         if (status & statvs) {
1411           double t = ts[lu][io];
1412           if (t * s < 0)
1413             continue;
1414           double dIx = t * Px - Ix, dIy = t * Py - Iy, dIz = t * Pz - Iz;
1415           double dist = sqrt(dIx * dIx + dIy * dIy + dIz * dIz);
1416           // RELAXED TOLERANCE for low energy stuff
1417           double tolerance = m_toleranceFactor(norm) * 20 * dd4hep::um;
1418           if (dist < tolerance)
1419             statws |= statvs;
1420         }
1421       }
1422     }
1423   }
1424   if (!(statws & 0x5)) /* No entrance */
1425     status &= ~0x5;
1426   if (!(statws & 0xa)) /* No exit */
1427     status &= ~0xa;
1428   // ***** End points
1429   // Assign end points to walls, if not a secondary and provided it's not a
1430   // reEntrance case, which case is more difficult to handle and we leave aside.
1431   if (((status & 0x5) == 0x1 || (status & 0x5) == 0x4) && !isSecondary) {
1432     double tIn = (status & 0x1) ? ts[0][0] : ts[1][0];
1433     lpini[0]   = Mx + tIn * Px;
1434     lpini[1]   = My + tIn * Py;
1435     lpini[2]   = Mz + tIn * Pz;
1436   } else {
1437     lpini[0] = Mx - at * Px;
1438     lpini[1] = My - at * Py;
1439     lpini[2] = Mz - at * Pz;
1440   }
1441   if (((status & 0xa) == 0x2 || (status & 0xa) == 0x8) && !isSecondary) {
1442     double tOut = (status & 0x2) ? ts[0][1] : ts[1][1];
1443     lpend[0]    = Mx + tOut * Px;
1444     lpend[1]    = My + tOut * Py;
1445     lpend[2]    = Mz + tOut * Pz;
1446   } else {
1447     lpend[0] = Mx + at * Px;
1448     lpend[1] = My + at * Py;
1449     lpend[2] = Mz + at * Pz;
1450   }
1451   // End points when on the walls
1452   for (int lu = 0; lu < 2; lu++) {
1453     unsigned int statvs = lu ? 0x4 : 0x1;
1454     double tIn = ts[lu][0], tOut = ts[lu][1];
1455     if (status & statvs) {
1456       lintos[lu][0] = Mx + tIn * Px;
1457       lintos[lu][1] = My + tIn * Py;
1458       lintos[lu][2] = Mz + tIn * Pz;
1459     }
1460     statvs <<= 1;
1461     if (status & statvs) {
1462       louts[lu][0] = Mx + tOut * Px;
1463       louts[lu][1] = My + tOut * Py;
1464       louts[lu][2] = Mz + tOut * Pz;
1465     }
1466   }
1467   return status;
1468 }
1469 unsigned int MPGDTrackerDigi::bTraversing(const double* lpos, const double* lmom, double ref2Cur,
1470                                           double path,
1471                                           bool isSecondary,     // Input subHit
1472                                           double dZ,            // Current instance of SUBVOLUME
1473                                           double dX, double dY, // Module parameters
1474                                           double lintos[][3], double louts[][3], double* lpini,
1475                                           double* lpend) const {
1476   unsigned int status = 0;
1477   double Mx = lpos[0], My = lpos[1], Mxy[2] = {Mx, My};
1478   double Px = lmom[0], Py = lmom[1], Pxy[2] = {Px, Py};
1479   double Mz = lpos[2] + ref2Cur, Pz = lmom[2];
1480   // Intersection w/ the edge in X,Y
1481   double tIn = 0, tOut = 0;
1482   double xyLow[2] = {-dX, -dY}, xyUp[2] = {+dX, +dY};
1483   for (int xy = 0; xy < 2; xy++) {
1484     int yx       = 1 - xy;
1485     double a_Low = xyLow[xy], a_Up = xyUp[xy], Ma = Mxy[xy], Pa = Pxy[xy];
1486     double b_Low = xyLow[yx], b_Up = xyUp[yx], Mb = Mxy[yx], Pb = Pxy[yx];
1487     for (double A : {a_Low, a_Up}) {
1488       // Ma+t*Pa = A
1489       if (Pa) {
1490         double t  = (A - Ma) / Pa;
1491         double Eb = Mb + t * Pb, Ez = Mz + t * Pz;
1492         if (b_Low < Eb && Eb < b_Up && fabs(Ez) < dZ) {
1493           if (t < 0) {
1494             if (!(status & 0x10) || ((status & 0x10) && t > tIn)) {
1495               status |= 0x10;
1496               tIn = t;
1497             }
1498           } else if (t > 0) {
1499             if (!(status & 0x20) || ((status & 0x20) && t < tOut)) {
1500               status |= 0x20;
1501               tOut = t;
1502             }
1503           }
1504         }
1505       }
1506     }
1507   }
1508   // Intersection w/ box walls
1509   for (int lu = 0; lu < 2; lu++) {
1510     int s                 = 2 * lu - 1;
1511     double Z              = s * dZ;
1512     unsigned int statGene = lu ? 0x4 : 0x1;
1513     // Mz+t*Pz = Z
1514     if (Pz) {
1515       double t = (Z - Mz) / Pz;
1516       if (t < 0) {
1517         if (!(status & 0x10) || ((status & 0x10) && t > tIn)) {
1518           status |= statGene;
1519           tIn = t;
1520         }
1521       } else if (t > 0) {
1522         if (!(status & 0x20) || ((status & 0x20) && t < tOut)) {
1523           status |= statGene << 1;
1524           tOut = t;
1525         }
1526       }
1527     }
1528   }
1529   // Is particle born/dead prior to entering/exiting?
1530   // - sim_hit must have been assigned the mean position: (entrance+exit)/2
1531   // - Let's then check entrance/exit against sim_hit's position +/- path/2.
1532   //   When the latter is too short, it means that the particle firing the
1533   //  hit gets born or dies in the SUBVOLUME ("dying" taken here in the broad
1534   //  sense of undergoing a discrete physics process).
1535   // => We remove the corresponding bit in the <status> pattern.
1536   // - Note that we not only require that the path be long enough, but also
1537   //  that it matches exactly distances to entrance/exit.
1538   double norm = sqrt(Px * Px + Py * Py + Pz * Pz), at = path / 2 / norm;
1539   unsigned int statws = 0;
1540   for (int is = 0; is < 2; is++) {
1541     int s     = 1 - 2 * is;
1542     double Ix = s * at * Px, Iy = s * at * Py, Iz = s * at * Pz;
1543     for (int lu = 0; lu < 2; lu++) { // Lower/upper wall
1544       unsigned int statvs = lu ? 0x4 : 0x1;
1545       for (int io = 0; io < 2; io++) {
1546         statvs <<= io;
1547         if (status & statvs) {
1548           double t = io ? tOut : tIn;
1549           if (t * s < 0)
1550             continue;
1551           double dIx = t * Px - Ix, dIy = t * Py - Iy, dIz = t * Pz - Iz;
1552           double dist = sqrt(dIx * dIx + dIy * dIy + dIz * dIz);
1553           // RELAXED TOLERANCE for low energy stuff
1554           double tolerance = m_toleranceFactor(norm) * 20 * dd4hep::um;
1555           if (dist < tolerance)
1556             statws |= statvs;
1557         }
1558       }
1559     }
1560   }
1561   if (!(statws & 0x5)) /* No entrance */
1562     status &= ~0x5;
1563   if (!(statws & 0xa)) /* No exit */
1564     status &= ~0xa;
1565   // ***** OUTPUT POSITIONS
1566   Mz -= ref2Cur; // Go back to REFERENCE SUBVOLUME
1567   // End points:
1568   // Assign end points to walls, if not a secondary.
1569   if ((status & 0x5) && !isSecondary) {
1570     lpini[0] = Mx + tIn * Px;
1571     lpini[1] = My + tIn * Py;
1572     lpini[2] = Mz + tIn * Pz;
1573   } else {
1574     lpini[0] = Mx - at * Px;
1575     lpini[1] = My - at * Py;
1576     lpini[2] = Mz - at * Pz;
1577   }
1578   if ((status & 0xa) && !isSecondary) {
1579     lpend[0] = Mx + tOut * Px;
1580     lpend[1] = My + tOut * Py;
1581     lpend[2] = Mz + tOut * Pz;
1582   } else {
1583     lpend[0] = Mx + at * Px;
1584     lpend[1] = My + at * Py;
1585     lpend[2] = Mz + at * Pz;
1586   }
1587   // End points when on the walls:
1588   for (int lu = 0; lu < 2; lu++) {
1589     unsigned int statvs = lu ? 0x4 : 0x1;
1590     if (status & statvs) {
1591       lintos[lu][0] = Mx + tIn * Px;
1592       lintos[lu][1] = My + tIn * Py;
1593       lintos[lu][2] = Mz + tIn * Pz;
1594     }
1595     statvs <<= 1;
1596     if (status & statvs) {
1597       louts[lu][0] = Mx + tOut * Px;
1598       louts[lu][1] = My + tOut * Py;
1599       louts[lu][2] = Mz + tOut * Pz;
1600     }
1601   }
1602   return status;
1603 }
1604 
1605 // ***** EXTRAPOLATE
1606 bool cExtrapolate(const double* lpos, const double* lmom, // Input subHit
1607                   double rT,                              // Target radius
1608                   double* lext)                           // Extrapolated position @ <rT>
1609 {
1610   bool ok   = false;
1611   double Mx = lpos[0], My = lpos[1], Mz = lpos[2], M2 = Mx * Mx + My * My;
1612   double Px = lmom[0], Py = lmom[1], Pz = lmom[2];
1613   double a = Px * Px + Py * Py, b = Px * Mx + Py * My, c = M2 - rT * rT;
1614   double tF = 0;
1615   if (!c)
1616     ok = true;
1617   else if (a) { // P is not // to Z
1618     double det = b * b - a * c;
1619     if (det >= 0) {
1620       double sqdet = sqrt(det);
1621       for (int is = 0; is < 2; is++) {
1622         int s    = 1 - 2 * is;
1623         double t = (-b + s * sqdet) / a, norm = sqrt(a + Pz * Pz);
1624         // "t" may happen to be slightly <0, because of limited precision
1625         if (t * norm < -dd4hep::nm)
1626           continue;
1627         if (!ok ||
1628             // Two intersects: let's retain the earliest one.
1629             (ok && fabs(t) < fabs(tF))) {
1630           tF = t;
1631           ok = true;
1632         }
1633       }
1634     }
1635   }
1636   if (ok) {
1637     lext[0] = Mx + tF * Px;
1638     lext[1] = My + tF * Py;
1639     lext[2] = Mz + tF * Pz;
1640   }
1641   return ok;
1642 }
1643 bool bExtrapolate(const double* lpos, const double* lmom, // Input subHit
1644                   double zT,                              // Target Z
1645                   double* lext)                           // Extrapolated position @ <zT>
1646 {
1647   bool ok   = false;
1648   double Mx = lpos[0], My = lpos[1], Mz = lpos[2];
1649   double Px = lmom[0], Py = lmom[1], Pz = lmom[2], norm = sqrt(Px * Px + Py * Py + Pz * Pz);
1650   double tF = 0;
1651   if (Pz) {
1652     tF = (zT - Mz) / Pz;
1653     // "t" may happen to be slightly <0, because of limited precision
1654     ok = tF * norm > -dd4hep::nm;
1655   }
1656   if (ok) {
1657     lext[0] = Mx + tF * Px;
1658     lext[1] = My + tF * Py;
1659     lext[2] = Mz + tF * Pz;
1660   }
1661   return ok;
1662 }
1663 
1664 // ***** EXTENSION
1665 // At variance to EXTRAPOLATION, we take edges (phi,Z/X,Y) into account.
1666 // - Returns 0x1 if
1667 //   - there is an extrapolation between position <lpos> and target,
1668 //   - within edge limits,
1669 //   - along momentum <lmom>,
1670 //   - in direction <direction>.
1671 // - Else returns 0 or something in the "m_inconsistency" range.
1672 // - <lext> contains the position of farthest extension.
1673 unsigned int MPGDTrackerDigi::cExtension(double const* lpos, double const* lmom, // Input subHit
1674                                          double rT, int direction,               // Target radius
1675                                          double dZ, double startPhi,
1676                                          double endPhi, // Module parameters
1677                                          double* lext) const {
1678   unsigned int status = 0;
1679   double Mx = lpos[0], My = lpos[1], Mz = lpos[2];
1680   double Px = lmom[0], Py = lmom[1], Pz = lmom[2], norm = sqrt(Px * Px + Py * Py + Pz * Pz);
1681   // Move some distance away from <lpos>, which is expected to be sitting on
1682   // the wall of the SUBVOLUME to be ``extended''.
1683   const double margin = 10 * dd4hep::um;
1684   double t            = direction * margin / norm;
1685   Mx += t * Px;
1686   My += t * Py;
1687   Mz += t * Pz;
1688   double M2 = Mx * Mx + My * My, rIni = sqrt(M2), rLow, rUp;
1689   if (rIni < rT) {
1690     rLow = rIni;
1691     rUp  = rT;
1692   } else {
1693     rLow = rT;
1694     rUp  = rIni;
1695   }
1696   // Intersection w/ the edge in phi
1697   double tF = 0;
1698   for (double phi : {startPhi, endPhi}) {
1699     // M+t*P = 0 + t'*U. t = (My*Ux-Mx*Uy)/(Px*Uy-Py*Ux);
1700     double Ux = cos(phi), Uy = sin(phi);
1701     double D = Px * Uy - Py * Ux;
1702     if (D) { // If P not // to U
1703       double t = (My * Ux - Mx * Uy) / D;
1704       if (t * direction < 0)
1705         continue;
1706       double Ex = Mx + t * Px, Ey = My + t * Py, Ez = Mz + t * Pz;
1707       double rE = sqrt(Ex * Ex + Ey * Ey), phiE = atan2(Ey, Ex);
1708       // Note: have to discard the phi+pi solution.
1709       if (rLow < rE && rE < rUp && fabs(Ez) < dZ && fabs(phiE - phi) < 1) {
1710         status |= 0x1;
1711         tF = t;
1712       }
1713     }
1714   }
1715   // Intersection w/ the edge in Z
1716   double zLow = -dZ, zUp = +dZ;
1717   for (double Z : {zLow, zUp}) {
1718     // Mz+t*Pz = Z
1719     if (Pz) {
1720       double t = (Z - Mz) / Pz;
1721       if (t * direction < 0)
1722         continue;
1723       double Ex = Mx + t * Px, Ey = My + t * Py, rE = sqrt(Ex * Ex + Ey * Ey);
1724       double phi = atan2(Ey, Ex);
1725       if (rLow < rE && rE < rUp && startPhi < phi && phi < endPhi) {
1726         if (t < 0) {
1727           if (!status || (status && t > tF)) {
1728             status |= 0x1;
1729             tF = t;
1730           }
1731         } else if (t > 0) {
1732           if (!status || (status && t < tF)) {
1733             status |= 0x1;
1734             tF = t;
1735           }
1736         }
1737       }
1738     }
1739   }
1740   // Else intersection w/ target radius
1741   if (!status) {
1742     double a = Px * Px + Py * Py, b = Px * Mx + Py * My, c = M2 - rT * rT;
1743     if (!a) {           // P is // to Z (while it did no intersect the edge in Z)
1744       status |= 0x1000; // Inconsistency
1745     } else if (!c) {    // Hit is on target (while we've moved away from it)
1746       status |= 0x2000; // Inconsistency
1747     } else {
1748       double det = b * b - a * c;
1749       if (det >= 0) {
1750         double sqdet = sqrt(det);
1751         for (int is = 0; is < 2; is++) {
1752           int s    = 1 - 2 * is;
1753           double t = (-b + s * sqdet) / a;
1754           if (t * direction < 0)
1755             continue;
1756           double Ix = Mx + t * Px, Iy = My + t * Py, Iz = Mz + t * Pz, phi = atan2(Iy, Ix);
1757           if (fabs(Iz) > dZ || phi < startPhi || endPhi < phi)
1758             continue;
1759           if (!(status & 0x1) ||
1760               // Two intersects: let's retain the earliest one.
1761               ((status & 0x1) && fabs(t) < fabs(tF))) {
1762             tF = t;
1763             status |= 0x1;
1764           }
1765         }
1766       }
1767     }
1768   }
1769   if (status & 0x1) {
1770     lext[0] = Mx + tF * Px;
1771     lext[1] = My + tF * Py;
1772     lext[2] = Mz + tF * Pz;
1773   }
1774   return status;
1775 }
1776 unsigned int MPGDTrackerDigi::bExtension(const double* lpos, const double* lmom, // Input subHit
1777                                          double zT, int direction,               // Target Z
1778                                          double dX, double dY, // Module parameters
1779                                          double* lext) const {
1780   unsigned int status = 0;
1781   double Mx = lpos[0], My = lpos[1], Mxy[2] = {Mx, My};
1782   double Px = lmom[0], Py = lmom[1], Pxy[2] = {Px, Py};
1783   double Mz = lpos[2], Pz = lmom[2];
1784   double norm = sqrt(Px * Px + Py * Py + Pz * Pz);
1785   // Move some distance away from <lpos>, which is expected to be sitting on
1786   // the wall of the SUBVOLUME to be ``extended''.
1787   const double margin = 10 * dd4hep::um;
1788   double t            = direction * margin / norm;
1789   Mx += t * Px;
1790   My += t * Py;
1791   Mz += t * Pz;
1792   double &zIni = Mz, zLow, zUp;
1793   if (zIni < zT) {
1794     zLow = zIni;
1795     zUp  = zT;
1796   } else {
1797     zLow = zT;
1798     zUp  = zIni;
1799   }
1800   // Intersection w/ the edge in X,Y
1801   double tF       = 0;
1802   double xyLow[2] = {-dX, -dY}, xyUp[2] = {+dX, +dY};
1803   for (int xy = 0; xy < 2; xy++) {
1804     int yx       = 1 - xy;
1805     double a_Low = xyLow[xy], a_Up = xyUp[xy], Ma = Mxy[xy], Pa = Pxy[xy];
1806     double b_Low = xyLow[yx], b_Up = xyUp[yx], Mb = Mxy[yx], Pb = Pxy[yx];
1807     for (double A : {a_Low, a_Up}) {
1808       // Ma+t*Pa = A
1809       if (Pa) {
1810         double t = (A - Ma) / Pa;
1811         if (t * direction < 0)
1812           continue;
1813         double Eb = Mb + t * Pb, Ez = Mz + t * Pz;
1814         if (zLow < Ez && Ez < zUp && b_Low < Eb && Eb < b_Up) {
1815           if (!status || (status && fabs(t) < fabs(tF))) {
1816             status |= 0x1;
1817             tF = t;
1818           }
1819         }
1820       }
1821     }
1822   }
1823   // Else intersection w/ target Z
1824   if (!status) {
1825     if (Pz) {
1826       tF = (zT - Mz) / Pz;
1827       if (tF * direction > 0)
1828         status = 0x1;
1829     }
1830   }
1831   if (status) {
1832     lext[0] = Mx + tF * Px;
1833     lext[1] = My + tF * Py;
1834     lext[2] = Mz + tF * Pz;
1835   }
1836   return status;
1837 }
1838 
1839 double getRef2Cur(DetElement refVol, DetElement curVol) {
1840   // TGeoHMatrix: In order to avoid a "dangling-reference" warning,
1841   // let's take a copy of the matrix instead of a reference to it.
1842   const TGeoHMatrix toRefVol = refVol.nominal().worldTransformation();
1843   const TGeoHMatrix toCurVol = curVol.nominal().worldTransformation();
1844   const double* TRef         = toRefVol.GetTranslation();
1845   const double* TCur         = toCurVol.GetTranslation();
1846   // For some reason, it has to be "Ref-Cur", while I (Y.B) would have expected the opposite...
1847   double gdT[3];
1848   for (int i = 0; i < 3; i++)
1849     gdT[i] = TRef[i] - TCur[i];
1850   double ldT[3];
1851   toRefVol.MasterToLocalVect(gdT, ldT);
1852   return ldT[2];
1853 }
1854 
1855 std::string inconsistency(const edm4hep::EventHeader& event, unsigned int status, CellID cID,
1856                           const double* lpos, const double* lmom) {
1857   using edm4eic::unit::GeV, dd4hep::mm;
1858   return std::format("Event {}#{}, SimHit 0x{:016x} @ {:.2f},{:.2f},{:.2f} mm, P = "
1859                      "{:.2f},{:.2f},{:.2f} GeV inconsistency 0x{:x}",
1860                      event.getRunNumber(), event.getEventNumber(), cID, lpos[0] / mm, lpos[1] / mm,
1861                      lpos[2] / mm, lmom[0] / GeV, lmom[1] / GeV, lmom[2] / GeV, status);
1862 }
1863 std::string oddity(const edm4hep::EventHeader& event, unsigned int status, double dist, CellID cID,
1864                    const double* lpos, const double* lmom, CellID cJD, const double* lpoj,
1865                    const double* lmoj) {
1866   using edm4eic::unit::GeV, dd4hep::mm;
1867   return std::format("Event {}#{}, Bizarre SimHit sequence: 0x{:016x} @ {:.4f},{:.4f},{:.4f} mm, P "
1868                      "= {:.2f},{:.2f},{:.2f} GeV and 0x{:016x} @ {:.4f},{:.4f},{:.4f} mm, P = "
1869                      "{:.2f},{:.2f},{:.2f} GeV: status 0x{:x}, distance {:.4f}",
1870                      event.getRunNumber(), event.getEventNumber(), cID, lpos[0] / mm, lpos[1] / mm,
1871                      lpos[2] / mm, lmom[0] / GeV, lmom[1] / GeV, lmom[2] / GeV, cJD, lpoj[0] / mm,
1872                      lpoj[1] / mm, lpoj[2] / mm, lmoj[0] / GeV, lmoj[1] / GeV, lmoj[2] / GeV,
1873                      status, dist);
1874 }
1875 
1876 bool MPGDTrackerDigi::samePMO(const edm4hep::SimTrackerHit& sim_hit,
1877                               const edm4hep::SimTrackerHit& sim_hjt) const {
1878   // Status:
1879   // 0: Same Particle, same Module, same Origin
1880   // 0x1: Not same
1881   // Particle
1882   bool sameParticle = sim_hjt.getParticle() == sim_hit.getParticle();
1883   // Module
1884   CellID vID      = sim_hit.getCellID() & m_volumeBits;
1885   CellID refID    = vID & m_moduleBits; // => the middle slice
1886   CellID vJD      = sim_hjt.getCellID() & m_volumeBits;
1887   CellID refJD    = vJD & m_moduleBits; // => the middle slice
1888   bool sameModule = refJD == refID;
1889   // Origin
1890   // Note: edm4hep::SimTrackerHit possesses an "Overlay" quality. Since I don't
1891   // know what this is, I ignore it.
1892   bool isSecondary = sim_hit.isProducedBySecondary();
1893   bool jsSecondary = sim_hjt.isProducedBySecondary();
1894   bool sameOrigin  = jsSecondary == isSecondary;
1895   return sameParticle && sameModule && sameOrigin;
1896 }
1897 
1898 double outInDistance(int shape, int orientation, double lintos[][3], double louts[][3],
1899                      double* lmom, double* lmoj) {
1900   // Outgoing/incoming distance
1901   bool ok;
1902   double lExt[3];
1903   double lmOI[3];
1904   for (int i = 0; i < 3; i++)
1905     lmOI[i] = (lmom[i] + lmoj[i]) / 2;
1906   double *lOut, *lInto;
1907   if (orientation > 0) {
1908     lOut  = louts[1];
1909     lInto = lintos[0];
1910   } else if (orientation < 0) {
1911     lOut  = louts[0];
1912     lInto = lintos[1];
1913   } else {
1914     lOut  = louts[0];
1915     lInto = lintos[0];
1916   }
1917   if (shape == 0) { // "TGeoTubeSeg"
1918     double rInto = sqrt(lInto[0] * lInto[0] + lInto[1] * lInto[1]);
1919     ok           = cExtrapolate(lOut, lmOI, rInto, lExt);
1920   } else { // "TGeoBBox"
1921     ok = bExtrapolate(lOut, lmOI, lInto[2], lExt);
1922   }
1923   if (ok) {
1924     double dist2 = 0;
1925     for (int i = 0; i < 3; i++) {
1926       double d = lExt[i] - lInto[i];
1927       dist2 += d * d;
1928     }
1929     return sqrt(dist2);
1930   } else
1931     return -1;
1932 }
1933 
1934 unsigned int MPGDTrackerDigi::extendHit(CellID refID, std::vector<std::uint64_t>& cIDs,
1935                                         int direction, double* lpini, double* lmini, double* lpend,
1936                                         double* lmend) const {
1937   unsigned int status         = 0;
1938   const VolumeManager& volman = m_detector->volumeManager();
1939   DetElement refVol           = volman.lookupDetElement(refID);
1940   const auto& shape           = refVol.solid();
1941   double *lpoE, *lmoE; // Starting position/momentum
1942   if (direction < 0) {
1943     lpoE = lpini;
1944     lmoE = lmini;
1945   } else {
1946     lpoE = lpend;
1947     lmoE = lmend;
1948   }
1949   // Let's target successively both extreme SUBVOLUMES, disregarding those
1950   // already contributing to the COALESCED hit.
1951   // => This proscribes reEntrance extension, i.e. extending past exit point
1952   //   on a path reEntering into the same SUBVOLUME.
1953   //    That option could make sense if the reEntering path is at grazing
1954   //   incidence w.r.t. SUBVOLUME inner wall. But otherwise, it leads to a
1955   //   very large difference between initial and extended hit.
1956   for (int rankE : {0, 4}) {
1957     CellID vIDE      = refID | m_stripIDs[rankE];
1958     int alreadyThere = 0;
1959     for (int i = 0; i < (int)cIDs.size(); i++) {
1960       if ((cIDs[i] & m_volumeBits) == vIDE) {
1961         alreadyThere = 1;
1962         break;
1963       }
1964     }
1965     if (alreadyThere)
1966       continue;
1967     if (std::find(cIDs.begin(), cIDs.end(), vIDE) != cIDs.end())
1968       continue;
1969     DetElement volE = volman.lookupDetElement(vIDE);
1970     double lext[3];
1971     if (std::string_view{shape.type()} == "TGeoTubeSeg") {
1972       const Tube& tExt = volE.solid();
1973       double R         = rankE == 0 ? tExt.rMin() : tExt.rMax();
1974       double startPhi  = tExt.startPhi() * radian;
1975       startPhi -= 2 * TMath::Pi();
1976       double endPhi = tExt.endPhi() * radian;
1977       endPhi -= 2 * TMath::Pi();
1978       double dZ = tExt.dZ();
1979       status    = cExtension(lpoE, lmoE, R, direction, dZ, startPhi, endPhi, lext);
1980     } else if (std::string_view{shape.type()} == "TGeoBBox") {
1981       double ref2E    = getRef2Cur(refVol, volE);
1982       const Box& bExt = volE.solid();
1983       double Z        = rankE == 0 ? -bExt.z() : +bExt.z();
1984       Z -= ref2E;
1985       double dX = bExt.x(), dY = bExt.y();
1986       status = bExtension(lpoE, lmoE, Z, direction, dX, dY, lext);
1987     } else {
1988       critical(R"(Bad input data: CellID {:x} has invalid shape "{}")", refID, shape.type());
1989       throw std::runtime_error(R"(Inconsistency: Inappropriate SimHits fed to "MPGDTrackerDigi".)");
1990     }
1991     if (status != 0x1)
1992       continue;
1993     if (direction < 0) {
1994       for (int i = 0; i < 3; i++)
1995         lpini[i] = lext[i];
1996     } else {
1997       for (int i = 0; i < 3; i++)
1998         lpend[i] = lext[i];
1999     }
2000     break;
2001   }
2002   return status;
2003 }
2004 
2005 bool MPGDTrackerDigi::denyExtension(const edm4hep::SimTrackerHit& sim_hit, double depth) const {
2006   // Non COALESCED secondary: do not extend...
2007   //  ...if in HELPER SUBVOLUME: if it is TRAVERSING, it's probably
2008   //   merely because SUBVOLUME is very thin.
2009   CellID vID          = sim_hit.getCellID() & m_volumeBits;
2010   bool isHelperVolume = m_stripRank(vID) != 0 && m_stripRank(vID) != 4;
2011   //  ...else if path length is negligible compared to potential
2012   //    extension (here, we cannot avoid using a built-in: 10%).
2013   const double fraction = .10;
2014   const double edmm = edm4eic::unit::mm, ed2dd = dd4hep::mm / edmm;
2015   bool smallPathLength = sim_hit.getPathLength() * ed2dd < fraction * depth;
2016   return isHelperVolume || smallPathLength;
2017 }
2018 
2019 void MPGDTrackerDigi::flagUnexpected(const edm4hep::EventHeader& event, int shape, double expected,
2020                                      const edm4hep::SimTrackerHit& sim_hit, double* lpini,
2021                                      double* lpend, double* lpos, double* lmom) const {
2022   //  Expectations:
2023   // I) Primary particle: position = middle of overall sensitive volume.
2024   // II) Secondary particle: no diff w.r.t. initial.
2025   //  These expectations are naive ones. When a delta ray is created w/in a
2026   // sensitive SUBVOLUME, it creates one distinct SimHit and the primary itself
2027   // no longer spans the whole SUBVOLUME nor sits at the middle. The path of
2028   // the delta ray is short, typically, but may still turn out to be extendable.
2029   //  Therefore expectations (I) and (II) are not systematically fulfilled.
2030   //  The "flagUnexpected" method is mainly there as a placeholder for a
2031   // debugging tool that would require further development.
2032   double Rnew2 = 0, Znew, diff2 = 0;
2033   for (int i = 0; i < 3; i++) {
2034     double neu = (lpini[i] + lpend[i]) / 2, alt = lpos[i];
2035     double d = neu - alt;
2036     diff2 += d * d;
2037     if (i != 2)
2038       Rnew2 += neu * neu;
2039     if (i == 2)
2040       Znew = neu;
2041   }
2042   double found = shape ? Znew : sqrt(Rnew2), residual = found - expected;
2043   bool isSecondary = sim_hit.isProducedBySecondary();
2044   bool isPrimary =
2045       !isSecondary && sqrt(lmom[0] * lmom[0] + lmom[1] * lmom[1] + lmom[2] * lmom[2]) > .1 * GeV;
2046   if ((fabs(residual) > .000001 && isPrimary) || (sqrt(diff2) > .000001 && isSecondary)) {
2047     debug("Event {}#{}, SimHit 0x{:016x} origin {:d}: d{:c} = {:.5f} diff = {:.5f}",
2048           event.getRunNumber(), event.getEventNumber(), sim_hit.getCellID(), isSecondary,
2049           shape ? 'Z' : 'R', residual, sqrt(diff2));
2050   }
2051 }
2052 
2053 // ***** CLUSTERIZATION
2054 // Returns:
2055 // 0: OK
2056 // 1: input hit is beyond limits
2057 int MPGDTrackerDigi::get2HitCluster(CellID refID,
2058                                     const Position& locPos,  // In DD4hep frame
2059                                     const double surfPos[2], // In Surface frame
2060                                     int pn,                  // 'p' or 'n' strip
2061                                     std::default_random_engine& generator, Cluster& cluster) const {
2062   // Master CellID, from "locPos"
2063   int stripIdx   = (pn != 0) ? 3 : 1; // 'p' is 2nd in line, 'n' is 4th.
2064   CellID stripID = gsl::at(m_stripIDs, stripIdx);
2065   const Position dummy(0, 0, 0);
2066   CellID masterID = m_seg->cellID(locPos, dummy, refID | stripID);
2067   // Retrieve StripParameters (for current sensor, current strip)
2068   const StripParameters* pars;
2069   CellID sensorStripID = masterID & m_sensorStripBits;
2070   try {
2071     pars = &m_stripParameters.at(sensorStripID);
2072   } catch (const std::out_of_range& oor) {
2073     critical(R"(Error retrieving StripParameters for readout "{}", cellID 0x{:0>16x}: {}.)",
2074              m_cfg.readout, masterID, oor.what());
2075     throw std::runtime_error("Error retrieving StripParameters");
2076   }
2077   // Abscissa = coordinate along measurement axis.
2078   // hA = SimHit   Abscissa (or abscissa of input hit)
2079   // mA = master   Abscissa (or abscissa of strip fired by input hit)
2080   // sA = smeared  Abscissa
2081   // nA = neighbor Abscissa
2082   const double& sigma = m_cfg.stripResolutions[pn];
2083   const double &min = pars->min, &max = pars->max, &pitch = pars->pitch;
2084   double hA = surfPos[pn];
2085   // Exclude hits beyond limits.
2086   // - This condition here is less restrictive than that in "isInActive": we
2087   //  allow hits to lie outside [min,max], but still require that they are
2088   //  close enough that the _truncated_ Gaussian smearing be able to move us
2089   //  back w/in [min,max].
2090   if (hA < min - (m_truncation - .1 * dd4hep::cm) * sigma ||
2091       hA > max + (m_truncation - .1 * dd4hep::cm) * sigma) {
2092     // - In standard situations, min/max are extrema extremorum.
2093     // - Here we allow for a little more (.1 cm), to cope with whatever
2094     //  non-standard case.
2095     return 1;
2096   }
2097   FieldID stripNum = m_id_dec->get(masterID, pars->index);
2098   double mA        = m_binToPosition(stripNum, pitch, pars->offset);
2099   std::normal_distribution<double> gaussian;
2100   auto stripGauss = [&](double abscissa, double sigma, double min, double max) {
2101     // Truncated Gaussian: +/-n*sigmas or readout extrema
2102     double low = abscissa - m_truncation * sigma;
2103     double up  = abscissa + m_truncation * sigma;
2104     if (min > low)
2105       low = min;
2106     if (max < up)
2107       up = max;
2108     double x;
2109     do {
2110       x = abscissa + gaussian(generator) * sigma;
2111     } while (x < low || up < x);
2112     return x;
2113   };
2114   double sA = stripGauss(hA, sigma, min, max);
2115   // ***** CLUSTER
2116   // Are we on the edge? Edge being extreme half-cell .
2117   if (sA < min + pitch / 2 || sA > max - pitch / 2) {
2118     // If indeed, single-hit cluster
2119     cluster.push_back({masterID, 1});
2120   } else {
2121     // Else two-hit cluster
2122     CellID neighID, inc = m_stripIncs[pn];
2123     double nA;
2124     // (In|de)crement neighbor w.r.t. master:
2125     // - Simple addition works well in most cases...
2126     // - ...But not when the overall coordinate field is =0 and the pCoordinate
2127     //  is decremented: we then get, overall, 0xffffffff, i.e. -1 (if decrement
2128     //  is 1, that is), nor when vice versa, pCoordinate of 0xffff (=-1) is
2129     //  incremented.
2130     // - In practice, the pCoordinate is the only one affected. Yet, to be on
2131     //  the safe side, let's ensure the spectator coordinate (i.e. "1-pn") is
2132     //  left unchanged for both (p|n)Coordinates.
2133     auto incrementID = [&](int pn) {
2134       CellID spectatorBits = pn == 0 ? ((CellID)0xffff) << 48 : ((CellID)0xffff) << 32;
2135       CellID iniID         = masterID & spectatorBits;
2136       neighID              = masterID + inc;
2137       neighID &= ~spectatorBits;
2138       neighID |= iniID;
2139     };
2140     auto decrementID = [&](int pn) {
2141       CellID spectatorBits = pn == 0 ? ((CellID)0xffff) << 48 : ((CellID)0xffff) << 32;
2142       CellID iniID         = masterID & spectatorBits;
2143       neighID              = masterID - inc;
2144       neighID &= ~spectatorBits;
2145       neighID |= iniID;
2146     };
2147     if (sA < mA) {
2148       decrementID(pn);
2149       nA = mA - pitch;
2150     } else {
2151       incrementID(pn);
2152       nA = mA + pitch;
2153     }
2154     // Amplitude Faction (Note: It can't be but >0, see "init").
2155     double fn = (sA - mA) / (nA - mA);
2156     cluster.push_back({masterID, 1 - fn});
2157     cluster.push_back({neighID, fn});
2158   }
2159   return 0;
2160 }
2161 unsigned int MPGDTrackerDigi::isInActive(CellID refID, const Position& locPos,
2162                                          const double surfPos[2]) const {
2163   // Active area is defined as #strips x pitch
2164   unsigned int status = 0;
2165   for (int pn = 0; pn < 2; pn++) {
2166     // Master CellID, from "locPos"
2167     CellID stripID = m_stripIDs[pn ? 3 : 1]; // 'p' is 2nd in line, 'n' is 4th.
2168     const Position dummy(0, 0, 0);
2169     CellID masterID = m_seg->cellID(locPos, dummy, refID | stripID);
2170     // Retrieve StripParameters (for current sensor, current strip)
2171     CellID sensorStripID        = masterID & m_sensorStripBits;
2172     const StripParameters* pars = 0;
2173     try {
2174       pars = &m_stripParameters.at(sensorStripID);
2175     } catch (const std::out_of_range& oor) {
2176       critical(R"(Error retrieving StripParameters for readout "{}", cellID 0x{:0>16x}: {}.)",
2177                m_cfg.readout, masterID, oor.what());
2178       throw std::runtime_error("Error retrieving StripParameters");
2179     }
2180     double hA         = surfPos[pn];
2181     const double &min = pars->min, &max = pars->max;
2182     if (hA > min && hA < max) {
2183       status |= 0x1 << pn;
2184     }
2185   }
2186   return status;
2187 }
2188 
2189 } // namespace eicrecon