Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-11-28 09:20:35

0001 // SPDX-License-Identifier: LGPL-3.0-or-later
0002 // Copyright (C) 2026 Chun Yuen Tsang, Minho Kim
0003 
0004 // Temporary BEMC compatibility implementation until its single-sided CALOROC migration.
0005 
0006 #include "CalorimeterCALOROCRecoLegacy.h"
0007 
0008 #include <DD4hep/Alignments.h>
0009 #include <DD4hep/IDDescriptor.h>
0010 #include <DD4hep/Objects.h>
0011 #include <DD4hep/Readout.h>
0012 #include <DD4hep/Segmentations.h>
0013 #include <DD4hep/Shapes.h>
0014 #include <DD4hep/VolumeManager.h>
0015 #include <DD4hep/Volumes.h>
0016 #include <DD4hep/detail/SegmentationsInterna.h>
0017 #include <DDSegmentation/BitFieldCoder.h>
0018 #include <DDSegmentation/MultiSegmentation.h>
0019 #include <DDSegmentation/Segmentation.h>
0020 #include <Evaluator/DD4hepUnits.h>
0021 #include <Math/GenVector/Cartesian3D.h>
0022 #include <Math/GenVector/DisplacementVector3D.h>
0023 #include <edm4eic/CALOROC1BSample.h>
0024 #include <edm4eic/unit_system.h>
0025 #include <edm4hep/CaloHitContribution.h>
0026 #include <edm4hep/MCParticle.h>
0027 #include <edm4hep/Vector3f.h>
0028 #include <fmt/ranges.h>
0029 #include <podio/ObjectID.h>
0030 #include <podio/RelationRange.h>
0031 #include <podio/detail/Link.h>
0032 #include <podio/detail/LinkCollectionImpl.h>
0033 #include <algorithm>
0034 #include <cctype>
0035 #include <cmath>
0036 #include <cstdint>
0037 #include <fstream>
0038 #include <functional>
0039 #include <initializer_list>
0040 #include <iterator>
0041 #include <memory>
0042 #include <sstream>
0043 #include <string>
0044 #include <tuple>
0045 #include <unordered_map>
0046 #include <utility>
0047 #include <vector>
0048 
0049 #include "algorithms/calorimetry/CalorimeterCALOROCRecoLegacyConfig.h"
0050 
0051 using namespace dd4hep;
0052 
0053 namespace eicrecon {
0054 
0055 double CalorimeterCALOROCRecoLegacy::_energyCor(double referencePos, double energy,
0056                                                 double z) const {
0057   double length = std::abs(referencePos - z);
0058   double factor =
0059       m_cfg.attenuationParameters[0] * std::exp(-length / m_cfg.attenuationParameters[1]) +
0060       (1 - m_cfg.attenuationParameters[0]) * std::exp(-length / m_cfg.attenuationParameters[2]);
0061   return energy / factor;
0062 }
0063 
0064 void CalorimeterCALOROCRecoLegacy::init() {
0065 
0066   if (m_cfg.attenuationReferencePositionNamePos.empty() ||
0067       m_cfg.attenuationReferencePositionNameNeg.empty()) {
0068     error("You MUST provide the name of reference positions for attenuation correction");
0069   }
0070 
0071   m_reference_z_p = m_geo.detector()->constant<double>(m_cfg.attenuationReferencePositionNamePos) *
0072                     edm4eic::unit::mm / dd4hep::mm;
0073   m_reference_z_n = m_geo.detector()->constant<double>(m_cfg.attenuationReferencePositionNameNeg) *
0074                     edm4eic::unit::mm / dd4hep::mm;
0075 
0076   // do not get the layer/sector ID if no readout class provided
0077   if (m_cfg.readout.empty()) {
0078     error("You MUST provide the name of the readout to decode CellID.");
0079   }
0080 
0081   // First, try and get the IDDescriptor. This will throw an exception if it fails.
0082   try {
0083     id_spec = m_detector->readout(m_cfg.readout).idSpec();
0084   } catch (...) {
0085     warning("Failed to get idSpec for {}", m_cfg.readout);
0086     return;
0087   }
0088   // Next, try and get the readout fields. This will throw a different exception.
0089   try {
0090     id_dec = id_spec.decoder();
0091     if (!m_cfg.sectorField.empty()) {
0092       sector_idx = id_dec->index(m_cfg.sectorField);
0093       debug("Find sector field {}, index = {}", m_cfg.sectorField, sector_idx);
0094     }
0095     if (!m_cfg.layerField.empty()) {
0096       layer_idx = id_dec->index(m_cfg.layerField);
0097       debug("Find layer field {}, index = {}", m_cfg.layerField, layer_idx);
0098     }
0099     if (!m_cfg.maskPosFields.empty()) {
0100       std::size_t tmp_mask = 0;
0101       for (auto& field : m_cfg.maskPosFields) {
0102         tmp_mask |= id_spec.field(field)->mask();
0103       }
0104       // assign this mask if all fields succeed
0105       gpos_mask = tmp_mask;
0106     }
0107   } catch (...) {
0108     if (id_dec == nullptr) {
0109       warning("Failed to load ID decoder for {}", m_cfg.readout);
0110       std::stringstream readouts;
0111       for (auto r : m_detector->readouts()) {
0112         readouts << "\"" << r.first << "\", ";
0113       }
0114       warning("Available readouts: {}", readouts.str());
0115     } else {
0116       warning("Failed to find field index for {}.", m_cfg.readout);
0117       if (!m_cfg.sectorField.empty()) {
0118         warning(" -- looking for sector field \"{}\".", m_cfg.sectorField);
0119       }
0120       if (!m_cfg.layerField.empty()) {
0121         warning(" -- looking for layer field  \"{}\".", m_cfg.layerField);
0122       }
0123       if (!m_cfg.maskPosFields.empty()) {
0124         warning(" -- looking for masking fields  \"{}\".", fmt::join(m_cfg.maskPosFields, ", "));
0125       }
0126       std::stringstream fields;
0127       for (auto field : id_spec.decoder()->fields()) {
0128         fields << "\"" << field.name() << "\", ";
0129       }
0130       warning("Available fields: {}", fields.str());
0131       warning("n.b. The local position, sector id and layer id will not be correct for this.");
0132       warning("Position masking may not be applied.");
0133       warning("however, the position, energy, and time values should still be good.");
0134     }
0135 
0136     return;
0137   }
0138 
0139   id_spec = m_detector->readout(m_cfg.readout).idSpec();
0140 
0141   // local detector name has higher priority
0142   if (!m_cfg.localDetElement.empty()) {
0143     try {
0144       m_local = m_detector->detector(m_cfg.localDetElement);
0145     } catch (...) {
0146       error("failed to load local coordinate system from DetElement {}", m_cfg.localDetElement);
0147       return;
0148     }
0149   } else {
0150     std::vector<std::pair<std::string, int>> fields;
0151     for (auto f : m_cfg.localDetFields) {
0152       fields.emplace_back(f, 0);
0153     }
0154     local_mask = id_spec.get_mask(fields);
0155     // use all fields if nothing provided
0156     if (fields.empty()) {
0157       local_mask = ~static_cast<decltype(local_mask)>(0);
0158     }
0159   }
0160 
0161   // Get the field indices and field-dependent conversion factors if necessary
0162   if (m_cfg.edep_to_npe_fields.empty() || m_cfg.edep_to_npe_filename.empty()) {
0163     error("You MUST provide edep_to_npe files and filename for layer-by-layer calibration.");
0164   }
0165 
0166   for (const auto& field : m_cfg.edep_to_npe_fields) {
0167     auto field_idx = id_dec->index(field);
0168     m_field_idxs.push_back(field_idx);
0169   }
0170 
0171   std::ifstream infile(m_cfg.edep_to_npe_filename);
0172   if (!infile) {
0173     error("Unable to open LUT file: {}", m_cfg.edep_to_npe_filename);
0174   }
0175   std::string line;
0176   while (std::getline(infile, line)) {
0177     std::istringstream iss(line);
0178     std::vector<int> keys;
0179     for (std::size_t i = 0; i < m_cfg.edep_to_npe_fields.size(); i++) {
0180       int value = 0;
0181       iss >> value;
0182       keys.push_back(value);
0183     }
0184     double factor = NAN;
0185     if (!(iss >> factor)) {
0186       error("Malformed LUT file: {}", m_cfg.edep_to_npe_filename);
0187     }
0188     m_edep_to_npe_lut[keys] = factor;
0189   }
0190 }
0191 
0192 double CalorimeterCALOROCRecoLegacy::_sumADC(const edm4eic::RawCALOROCHit& ADC) const {
0193   double sum = 0;
0194 
0195   // check high gain ADC first. If it saturates, we switch to lowGainADC
0196   for (const auto& bSample : ADC.getBSamples()) {
0197     if (bSample.highGainADC >= m_cfg.highGainDR) {
0198       sum += static_cast<double>(bSample.lowGainADC);
0199     } else {
0200       sum += static_cast<double>(bSample.highGainADC) / m_cfg.gainRatio;
0201     }
0202   }
0203   return sum;
0204 }
0205 
0206 double CalorimeterCALOROCRecoLegacy::_toa(const edm4eic::RawCALOROCHit& ADC) {
0207   // find the relative toa
0208   int samplePhase        = ADC.getSamplePhase();
0209   int timeStamp          = ADC.getTimeStamp();
0210   const auto& bSamples   = ADC.getBSamples();
0211   size_t idx_toa         = 0;
0212   uint16_t timeOfArrival = 0;
0213   for (; idx_toa < bSamples.size(); ++idx_toa) {
0214     timeOfArrival = bSamples.at(idx_toa).timeOfArrival;
0215     if (timeOfArrival > 0) {
0216       break;
0217     }
0218   }
0219 
0220   return samplePhase * (25. / 1042.) + (timeStamp + idx_toa) * 25. - timeOfArrival * (25. / 1024.);
0221 }
0222 
0223 double CalorimeterCALOROCRecoLegacy::_timeWalkCorrection(double toa, double lowGainADC) const {
0224   if (lowGainADC - m_cfg.timeWalkCorrectionParameters[2] > 0) {
0225     return toa - (m_cfg.timeWalkCorrectionParameters[1] *
0226                       pow(lowGainADC - m_cfg.timeWalkCorrectionParameters[2],
0227                           m_cfg.timeWalkCorrectionParameters[3]) +
0228                   m_cfg.timeWalkCorrectionParameters[0]);
0229   }
0230   return toa;
0231 }
0232 
0233 void CalorimeterCALOROCRecoLegacy::process(
0234     const CalorimeterCALOROCRecoLegacy::Input& input,
0235     const CalorimeterCALOROCRecoLegacy::Output& output) const {
0236 
0237   const auto [npeHitsP, ADCPs, npeHitsN, ADCNs]       = input;
0238   auto [recohits, rawhits, rawhitsLink, rawhitsAssoc] = output;
0239 
0240   // match NpeHits and ADC hits by cellID
0241   std::unordered_map<dd4hep::rec::CellID, size_t> cellID2NpeHitNID;
0242   std::unordered_map<dd4hep::rec::CellID, size_t> cellID2ADCNID;
0243   std::unordered_map<dd4hep::rec::CellID, size_t> cellID2ADCPID;
0244   for (size_t i = 0; i < npeHitsN->size(); ++i) {
0245     const auto& hit                   = npeHitsN->at(i);
0246     cellID2NpeHitNID[hit.getCellID()] = i;
0247   }
0248 
0249   for (size_t i = 0; i < ADCPs->size(); ++i) {
0250     const auto& ADCP                = ADCPs->at(i);
0251     cellID2ADCPID[ADCP.getCellID()] = i;
0252   }
0253 
0254   for (size_t i = 0; i < ADCNs->size(); ++i) {
0255     const auto& ADCN                = ADCNs->at(i);
0256     cellID2ADCNID[ADCN.getCellID()] = i;
0257   }
0258 
0259   for (const auto& npeHitP : *npeHitsP) {
0260     auto cellID = npeHitP.getCellID();
0261 
0262     // ignore data point if the hit is not showing up on all ADC and NpeHit collections
0263     auto it = cellID2NpeHitNID.find(cellID);
0264     if (it == cellID2NpeHitNID.end()) {
0265       continue;
0266     }
0267     const auto& npeHitN = npeHitsN->at(it->second);
0268     it                  = cellID2ADCPID.find(cellID);
0269     if (it == cellID2ADCPID.end()) {
0270       continue;
0271     }
0272     const auto& ADCP = ADCPs->at(it->second);
0273     it               = cellID2ADCNID.find(cellID);
0274     if (it == cellID2ADCNID.end()) {
0275       continue;
0276     }
0277     const auto& ADCN = ADCNs->at(it->second);
0278 
0279     // get layer and sector ID
0280     const int lid = id_dec != nullptr && !m_cfg.layerField.empty()
0281                         ? static_cast<int>(id_dec->get(cellID, layer_idx))
0282                         : -1;
0283     const int sid = id_dec != nullptr && !m_cfg.sectorField.empty()
0284                         ? static_cast<int>(id_dec->get(cellID, sector_idx))
0285                         : -1;
0286 
0287     auto tP = _toa(ADCP);
0288     auto tN = _toa(ADCN);
0289 
0290     // get position of the hit;
0291     double zpos = NAN;
0292 
0293     if (m_cfg.useNpeHitPos) {
0294       zpos = static_cast<double>(npeHitP.getPosition().z);
0295     } else {
0296       if (m_cfg.timeWalkCor) {
0297         tP = _timeWalkCorrection(tP, this->_sumADC(ADCP));
0298         tN = _timeWalkCorrection(tN, this->_sumADC(ADCN));
0299       }
0300       auto dt = tN - tP;
0301       zpos    = dt * m_cfg.lightSpeedParameters[0] + m_cfg.lightSpeedParameters[1];
0302     }
0303     double time = 0.5 * (tP + tN);
0304     // bound zpos by sipm location
0305     zpos = std::max(m_reference_z_n, std::min(m_reference_z_p, zpos));
0306 
0307     // fetch edep to npe factor on this layer
0308     std::vector<int> key;
0309     key.reserve(m_field_idxs.size());
0310     for (const auto idx : m_field_idxs) {
0311       key.push_back(static_cast<int>(id_dec->get(cellID, idx)));
0312     }
0313 
0314     const auto lut_it = m_edep_to_npe_lut.find(key);
0315     if (lut_it == m_edep_to_npe_lut.end() || lut_it->second == 0.0) {
0316       warning("Missing/invalid edep->npe factor for key {} (cellID={})", fmt::join(key, ","),
0317               cellID);
0318       continue;
0319     }
0320     const double eDep2NpeFactor = lut_it->second;
0321     // find averaged energy
0322     double npeP = 0.0;
0323     double npeN = 0.0;
0324     // get values from both sides in a loop
0325     for (bool NSide : {true, false}) {
0326       const auto& ADC = NSide ? ADCN : ADCP;
0327       auto& npe       = NSide ? npeN : npeP;
0328       switch (m_cfg.proxy_type) {
0329       case CalorimeterCALOROCRecoLegacyConfig::ProxyType::sum:
0330         npe = _sumADC(ADC);
0331         break;
0332       case CalorimeterCALOROCRecoLegacyConfig::ProxyType::templateFit:
0333       case CalorimeterCALOROCRecoLegacyConfig::ProxyType::simpson:
0334         error("Proxy type not implemented.");
0335         break;
0336       default:
0337         error("Proxy type not implemented.");
0338       }
0339     }
0340 
0341     // perform layer-by-layer energy correction
0342     double chargeP = npeP / eDep2NpeFactor;
0343     double chargeN = npeN / eDep2NpeFactor;
0344 
0345     // attenuation correction
0346     double corEP = _energyCor(m_reference_z_p, chargeP, zpos) * m_cfg.slope + m_cfg.intercept;
0347     double corEN = _energyCor(m_reference_z_n, chargeN, zpos) * m_cfg.slope + m_cfg.intercept;
0348     double corE  = std::sqrt(corEP * corEN);
0349 
0350     // raw hits for all pulses
0351     edm4hep::MutableRawCalorimeterHit rawhit;
0352     rawhit.setCellID(cellID);
0353     rawhit.setAmplitude(static_cast<decltype(edm4hep::RawCalorimeterHitData::amplitude)>(npeP));
0354     rawhit.setTimeStamp(static_cast<decltype(edm4hep::RawCalorimeterHitData::timeStamp)>(time));
0355 
0356     double edep = 0;
0357 
0358     // link to parents
0359     std::unordered_map<podio::ObjectID, edm4eic::MutableMCRecoCalorimeterHitLink> links_staging;
0360     std::unordered_map<podio::ObjectID, edm4eic::MutableMCRecoCalorimeterHitAssociation>
0361         rawassocs_staging;
0362 
0363     for (bool NSide : {true, false}) {
0364       const auto& npeHit = NSide ? npeHitN : npeHitP;
0365       for (const auto& contrib : npeHit.getContributions()) {
0366         if (links_staging.contains(contrib.getParticle().getObjectID())) {
0367           continue;
0368         }
0369 
0370         edep += contrib.getEnergy();
0371         edm4eic::MutableMCRecoCalorimeterHitAssociation assoc;
0372         assoc.setRawHit(rawhit);
0373 
0374         edm4eic::MutableMCRecoCalorimeterHitLink link;
0375         link.setFrom(rawhit);
0376 
0377         assoc.setSimHit(npeHit);
0378         assoc.setWeight(contrib.getEnergy());
0379 
0380         link.setTo(npeHit);
0381         link.setWeight(contrib.getEnergy());
0382 
0383         rawassocs_staging[contrib.getParticle().getObjectID()] = assoc;
0384         links_staging[contrib.getParticle().getObjectID()]     = link;
0385       }
0386     }
0387 
0388     if (edep > 0.0) {
0389       for (auto& [key, link] : links_staging) {
0390         auto newLink = rawhitsLink->create();
0391         newLink.setTo(link.getTo());
0392         newLink.setFrom(link.getFrom());
0393         newLink.setWeight(link.getWeight() / edep);
0394       }
0395       for (auto& [key, assoc] : rawassocs_staging) {
0396         assoc.setWeight(assoc.getWeight() / edep);
0397         rawhitsAssoc->push_back(assoc);
0398       }
0399     }
0400 
0401     dd4hep::DetElement local;
0402     dd4hep::Position gpos;
0403     try {
0404       // global positions
0405       gpos = m_converter->position(cellID);
0406 
0407       // masked position (look for a mother volume)
0408       if (gpos_mask != 0) {
0409         auto mpos = m_converter->position(cellID & ~gpos_mask);
0410         // replace corresponding coords
0411         for (const char& c : m_cfg.maskPos) {
0412           switch (std::tolower(c)) {
0413           case 'x':
0414             gpos.SetX(mpos.X());
0415             break;
0416           case 'y':
0417             gpos.SetY(mpos.Y());
0418             break;
0419           case 'z':
0420             gpos.SetZ(mpos.Z());
0421             break;
0422           default:
0423             break;
0424           }
0425         }
0426       }
0427       gpos.SetZ(zpos * dd4hep::mm);
0428 
0429       // local positions
0430       if (m_cfg.localDetElement.empty()) {
0431         auto volman = m_detector->volumeManager();
0432         local       = volman.lookupDetElement(cellID & local_mask);
0433       } else {
0434         local = m_local;
0435       }
0436     } catch (...) {
0437       continue;
0438     }
0439 
0440     const auto lpos = local.nominal().worldToLocal(gpos);
0441     std::vector<double> cdim;
0442     // get segmentation dimensions
0443 
0444     const dd4hep::DDSegmentation::Segmentation* segmentation =
0445         m_converter->findReadout(local).segmentation()->segmentation;
0446     auto segmentation_type = segmentation->type();
0447 
0448     while (segmentation_type == "MultiSegmentation") {
0449       const auto* multi_segmentation =
0450           dynamic_cast<const dd4hep::DDSegmentation::MultiSegmentation*>(segmentation);
0451       const dd4hep::DDSegmentation::Segmentation& sub_segmentation =
0452           multi_segmentation->subsegmentation(cellID);
0453 
0454       segmentation      = &sub_segmentation;
0455       segmentation_type = segmentation->type();
0456     }
0457 
0458     if (segmentation_type == "CartesianGridXY" || segmentation_type == "HexGridXY" ||
0459         segmentation_type == "CartesianGridXYStaggered") {
0460       auto cell_dim = m_converter->cellDimensions(cellID);
0461       cdim.resize(3);
0462       cdim[0] = cell_dim[0];
0463       cdim[1] = cell_dim[1];
0464       debug("Using segmentation for cell dimensions: {}", fmt::join(cdim, ", "));
0465     } else if (segmentation_type == "CartesianStripZ") {
0466       auto cell_dim = m_converter->cellDimensions(cellID);
0467       cdim.resize(3);
0468       cdim[2] = cell_dim[0];
0469       debug("Using segmentation for cell dimensions: {}", fmt::join(cdim, ", "));
0470     } else {
0471       if ((segmentation_type != "NoSegmentation") && (!warned_unsupported_segmentation)) {
0472         warning("Unsupported segmentation type \"{}\"", segmentation_type);
0473         warned_unsupported_segmentation = true;
0474       }
0475 
0476       // Using bounding box instead of actual solid so the dimensions are always in dim_x, dim_y, dim_z
0477       cdim =
0478           m_converter->findContext(cellID)->volumePlacement().volume().boundingBox().dimensions();
0479       std::ranges::transform(cdim, cdim.begin(), [](auto&& PH1) {
0480         return std::multiplies<double>()(std::forward<decltype(PH1)>(PH1), 2);
0481       });
0482       debug("Using bounding box for cell dimensions: {}", fmt::join(cdim, ", "));
0483     }
0484 
0485     //create constant vectors for passing to hit initializer list
0486     //FIXME: needs to come from the geometry service/converter
0487     const decltype(edm4eic::CalorimeterHitData::position) position(
0488         gpos.x() / dd4hep::mm, gpos.y() / dd4hep::mm, gpos.z() / dd4hep::mm);
0489     const decltype(edm4eic::CalorimeterHitData::dimension) dimension(
0490         cdim.at(0) / dd4hep::mm, cdim.at(1) / dd4hep::mm, cdim.at(2) / dd4hep::mm);
0491     const decltype(edm4eic::CalorimeterHitData::local) local_position(
0492         lpos.x() / dd4hep::mm, lpos.y() / dd4hep::mm, lpos.z() / dd4hep::mm);
0493 
0494     auto recohit =
0495         recohits->create(cellID, corE, 0, time, 0, position, dimension, sid, lid, local_position);
0496     recohit.setRawHit(rawhit);
0497     rawhits->push_back(rawhit);
0498   }
0499 }
0500 
0501 } // namespace eicrecon