Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-11-24 09:33:22

0001 // SPDX-License-Identifier: LGPL-3.0-or-later
0002 // Copyright (C) 2022 - 2024 Sylvester Joosten, Chao, Chao Peng, Whitney Armstrong, Dhevan Gangadharan, Derek Anderson
0003 
0004 /*
0005  *  Reconstruct the cluster with Center of Gravity method
0006  *  Logarithmic weighting is used for mimicking energy deposit in transverse direction
0007  *
0008  *  Author: Chao Peng (ANL), 09/27/2020
0009  */
0010 
0011 #include <Evaluator/DD4hepUnits.h>
0012 #include <boost/algorithm/string/join.hpp>
0013 #include <boost/range/adaptor/map.hpp>
0014 #include <edm4eic/CalorimeterHitCollection.h>
0015 #include <edm4eic/Cov3f.h>
0016 #include <edm4hep/CaloHitContribution.h>
0017 #include <edm4hep/MCParticle.h>
0018 #include <edm4hep/RawCalorimeterHit.h>
0019 #include <edm4hep/SimCalorimeterHitCollection.h>
0020 #include <edm4hep/Vector3f.h>
0021 #include <edm4hep/utils/vector_utils.h>
0022 #include <gsl/pointers>
0023 #include <podio/LinkNavigator.h>
0024 #include <podio/ObjectID.h>
0025 #include <podio/RelationRange.h>
0026 #include <algorithm>
0027 #include <cctype>
0028 #include <cstddef>
0029 #include <limits>
0030 #include <map>
0031 #include <optional>
0032 #include <tuple>
0033 #include <vector>
0034 
0035 #include "CalorimeterClusterRecoCoG.h"
0036 #include "algorithms/calorimetry/CalorimeterClusterRecoCoGConfig.h"
0037 #include "algorithms/interfaces/CompareObjectID.h"
0038 #include "algorithms/interfaces/LinkTruthUtils.h"
0039 
0040 namespace eicrecon {
0041 
0042 using namespace dd4hep;
0043 
0044 void CalorimeterClusterRecoCoG::init() {
0045   // select weighting method
0046   std::string ew = m_cfg.energyWeight;
0047   // make it case-insensitive
0048   std::ranges::transform(ew, ew.begin(), [](char s) { return std::tolower(s); });
0049   auto it = weightMethods.find(ew);
0050   if (it == weightMethods.end()) {
0051     error("Cannot find energy weighting method {}, choose one from [{}]", m_cfg.energyWeight,
0052           boost::algorithm::join(weightMethods | boost::adaptors::map_keys, ", "));
0053     return;
0054   }
0055   weightFunc = it->second;
0056 }
0057 
0058 void CalorimeterClusterRecoCoG::process(const CalorimeterClusterRecoCoG::Input& input,
0059                                         const CalorimeterClusterRecoCoG::Output& output) const {
0060   const auto [proto, mchitlinks, mchitassociations] = input;
0061   auto [clusters, links, associations]              = output;
0062 
0063   // Check if truth associations are possible
0064   const truth::EventLinkNavigator<edm4eic::MCRecoCalorimeterHitLinkCollection> link_nav(mchitlinks);
0065   const bool do_assoc = link_nav.enabled();
0066   if (!do_assoc) {
0067     debug("Provided MCRecoCalorimeterHitLink collection is empty. No truth associations "
0068           "will be performed.");
0069   }
0070 
0071   for (const auto& pcl : *proto) {
0072     // skip protoclusters with no hits
0073     if (pcl.hits_size() == 0) {
0074       continue;
0075     }
0076 
0077     auto cl_opt = reconstruct(pcl);
0078     if (!cl_opt.has_value()) {
0079       continue;
0080     }
0081     auto cl = *std::move(cl_opt);
0082 
0083     debug("{} hits: {} GeV, ({}, {}, {})", cl.getNhits(), cl.getEnergy() / dd4hep::GeV,
0084           cl.getPosition().x / dd4hep::mm, cl.getPosition().y / dd4hep::mm,
0085           cl.getPosition().z / dd4hep::mm);
0086     clusters->push_back(cl);
0087 
0088     // If sim hits are available, associate cluster with MCParticle
0089     if (do_assoc) {
0090       associate(cl, mchitassociations, link_nav, links, associations);
0091     }
0092   }
0093 }
0094 
0095 std::optional<edm4eic::MutableCluster>
0096 CalorimeterClusterRecoCoG::reconstruct(const edm4eic::ProtoCluster& pcl) const {
0097   edm4eic::MutableCluster cl;
0098   cl.setNhits(pcl.hits_size());
0099 
0100   debug("hit size = {}", pcl.hits_size());
0101 
0102   // no hits
0103   if (pcl.hits_size() == 0) {
0104     return {};
0105   }
0106 
0107   // calculate total energy, find the cell with the maximum energy deposit
0108   float totalE = 0.;
0109   // Used to optionally constrain the cluster eta to those of the contributing hits
0110   float minHitEta = std::numeric_limits<float>::max();
0111   float maxHitEta = std::numeric_limits<float>::min();
0112 
0113   double time      = 0;
0114   double timeError = 0;
0115   for (unsigned i = 0; i < pcl.getHits().size(); ++i) {
0116     const auto& hit   = pcl.getHits()[i];
0117     const auto weight = pcl.getWeights()[i];
0118     debug("hit energy = {} hit weight: {}", hit.getEnergy(), weight);
0119     auto energy = hit.getEnergy() * weight;
0120     totalE += energy;
0121     time += (hit.getTime() - time) * energy / totalE;
0122     timeError += std::pow(hit.getTimeError() * energy, 2);
0123     cl.addToHits(hit);
0124     cl.addToHitContributions(energy);
0125     const float eta = edm4hep::utils::eta(hit.getPosition());
0126     minHitEta       = std::min(eta, minHitEta);
0127     maxHitEta       = std::max(eta, maxHitEta);
0128   }
0129   cl.setEnergy(totalE / m_cfg.sampFrac);
0130   cl.setEnergyError(0.);
0131   cl.setTime(time);
0132   cl.setTimeError(totalE > 0 ? std::sqrt(timeError) / totalE : 0);
0133 
0134   // center of gravity with logarithmic weighting
0135   float tw = 0.;
0136   auto v   = cl.getPosition();
0137 
0138   double logWeightBase = m_cfg.logWeightBase;
0139   if (!m_cfg.logWeightBaseCoeffs.empty()) {
0140     double l      = std::log(cl.getEnergy() / m_cfg.logWeightBase_Eref);
0141     logWeightBase = 0;
0142     for (std::size_t i = 0; i < m_cfg.logWeightBaseCoeffs.size(); i++) {
0143       logWeightBase += m_cfg.logWeightBaseCoeffs[i] * pow(l, i);
0144     }
0145   }
0146 
0147   for (unsigned i = 0; i < pcl.getHits().size(); ++i) {
0148     const auto& hit   = pcl.getHits()[i];
0149     const auto weight = pcl.getWeights()[i];
0150     //      _DBG_<<" -- weight = " << weight << "  E=" << hit.getEnergy() << " totalE=" <<totalE << " log(E/totalE)=" << std::log(hit.getEnergy()/totalE) << std::endl;
0151     float w = weightFunc(hit.getEnergy() * weight, totalE, logWeightBase, 0);
0152     tw += w;
0153     v = v + (hit.getPosition() * w);
0154   }
0155   if (tw == 0.) {
0156     warning("zero total weights encountered, you may want to adjust your weighting parameter.");
0157     return {};
0158   }
0159   cl.setPosition(v / tw);
0160   cl.setPositionError({}); // @TODO: Covariance matrix
0161 
0162   // Optionally constrain the cluster to the hit eta values
0163   if (m_cfg.enableEtaBounds) {
0164     const bool overflow  = (edm4hep::utils::eta(cl.getPosition()) > maxHitEta);
0165     const bool underflow = (edm4hep::utils::eta(cl.getPosition()) < minHitEta);
0166     if (overflow || underflow) {
0167       const double newEta   = overflow ? maxHitEta : minHitEta;
0168       const double newTheta = edm4hep::utils::etaToAngle(newEta);
0169       const double newR     = edm4hep::utils::magnitude(cl.getPosition());
0170       const double newPhi   = edm4hep::utils::angleAzimuthal(cl.getPosition());
0171       cl.setPosition(edm4hep::utils::sphericalToVector(newR, newTheta, newPhi));
0172       debug("Bound cluster position to contributing hits due to {}",
0173             (overflow ? "overflow" : "underflow"));
0174     }
0175   }
0176   return cl;
0177 }
0178 
0179 void CalorimeterClusterRecoCoG::associate(
0180     const edm4eic::Cluster& cl,
0181     [[maybe_unused]] const edm4eic::MCRecoCalorimeterHitAssociationCollection* mchitassociations,
0182     const truth::EventLinkNavigator<edm4eic::MCRecoCalorimeterHitLinkCollection>& link_nav,
0183     edm4eic::MCRecoClusterParticleLinkCollection* links,
0184     edm4eic::MCRecoClusterParticleAssociationCollection* assocs) const {
0185   // --------------------------------------------------------------------------
0186   // Association Logic
0187   // --------------------------------------------------------------------------
0188   /*  1. identify all sim hits associated with a given protocluster, and sum
0189    *     the energy of the sim hits.
0190    *  2. for each sim hit
0191    *     - identify parents of each contributing particles; and
0192    *     - if parent is a primary particle, add to list of contributors
0193    *       and sum the energy contributed by the parent.
0194    *  3. create an association for each contributing primary with a weight
0195    *     of contributed energy over total sim hit energy.
0196    */
0197 
0198   // bookkeeping maps for associated primaries
0199   std::map<edm4hep::MCParticle, double, CompareObjectID<edm4hep::MCParticle>> mapMCParToContrib;
0200 
0201   // --------------------------------------------------------------------------
0202   // 1. get associated sim hits and sum energy
0203   // --------------------------------------------------------------------------
0204   double eSimHitSum = 0.;
0205   for (auto clhit : cl.getHits()) {
0206 
0207     // Get linked sim hits using LinkNavigator
0208     const auto vecAssocSimHits = link_nav.linked(clhit.getRawHit());
0209 
0210     for (const auto& [simHit, weight] : vecAssocSimHits) {
0211       eSimHitSum += simHit.getEnergy();
0212     }
0213 
0214     debug("{} associated sim hits found for reco hit (cell ID = {})", vecAssocSimHits.size(),
0215           clhit.getCellID());
0216 
0217     // ------------------------------------------------------------------------
0218     // 2. loop through associated sim hits
0219     // ------------------------------------------------------------------------
0220     for (const auto& [simHit, weight] : vecAssocSimHits) {
0221       for (const auto& contrib : simHit.getContributions()) {
0222         // --------------------------------------------------------------------
0223         // grab primary responsible for contribution & increment relevant sum
0224         // --------------------------------------------------------------------
0225         edm4hep::MCParticle primary = truth::primaryFrom(contrib, m_cfg.promptDecayPDGs);
0226         mapMCParToContrib[primary] += contrib.getEnergy();
0227 
0228         trace("Identified primary: id = {}, pid = {}, total energy = {}, contributed = {}",
0229               primary.getObjectID().index, primary.getPDG(), primary.getEnergy(),
0230               mapMCParToContrib[primary]);
0231       }
0232     }
0233   }
0234   debug("Found {} primaries contributing a total of {} GeV", mapMCParToContrib.size(), eSimHitSum);
0235 
0236   // --------------------------------------------------------------------------
0237   // 3. create association for each contributing primary
0238   // --------------------------------------------------------------------------
0239   for (auto [part, contribution] : mapMCParToContrib) {
0240     // calculate weight
0241     const double weight = contribution / eSimHitSum;
0242 
0243     truth::addWeightedRelation(
0244         cl, part, static_cast<float>(weight),
0245         gsl::not_null<edm4eic::MCRecoClusterParticleLinkCollection*>{links},
0246         gsl::not_null<edm4eic::MCRecoClusterParticleAssociationCollection*>{assocs});
0247 
0248     debug("Associated cluster #{} to MC Particle #{} (pid = {}, status = {}, energy = {}) with "
0249           "weight ({})",
0250           cl.getObjectID().index, part.getObjectID().index, part.getPDG(),
0251           part.getGeneratorStatus(), part.getEnergy(), weight);
0252   }
0253 }
0254 
0255 } // namespace eicrecon