From e2e55145254dea1f5355876eeff9a04d1b1e057a Mon Sep 17 00:00:00 2001 From: Rob Mina Date: Thu, 5 Nov 2026 21:10:35 -0600 Subject: [PATCH 1/4] New tracker-CRV association data object. --- CRVReco/CMakeLists.txt | 21 + CRVReco/fcl/prolog_v12.fcl | 8 + CRVReco/inc/TrkCrvMatchTool.hh | 109 +++++ CRVReco/inc/TrkCrvPlaneError.hh | 31 ++ CRVReco/src/SConscript | 12 + CRVReco/src/TrkCrvMatchTool.cc | 371 +++++++++++++++ CRVReco/src/TrkCrvMatcher_module.cc | 121 +++++ CRVResponse/CMakeLists.txt | 13 + CRVResponse/fcl/prolog_v12.fcl | 10 + CRVResponse/src/SConscript | 3 + CRVResponse/src/TrkCrvMatchMCMaker_module.cc | 459 +++++++++++++++++++ MCDataProducts/inc/TrkCrvMatchMC.hh | 63 +++ MCDataProducts/src/classes.h | 1 + MCDataProducts/src/classes_def.xml | 9 + RecoDataProducts/inc/TrkCrvMatch.hh | 95 ++++ RecoDataProducts/src/classes.h | 1 + RecoDataProducts/src/classes_def.xml | 17 + 17 files changed, 1344 insertions(+) create mode 100644 CRVReco/inc/TrkCrvMatchTool.hh create mode 100644 CRVReco/inc/TrkCrvPlaneError.hh create mode 100644 CRVReco/src/TrkCrvMatchTool.cc create mode 100644 CRVReco/src/TrkCrvMatcher_module.cc create mode 100644 CRVResponse/src/TrkCrvMatchMCMaker_module.cc create mode 100644 MCDataProducts/inc/TrkCrvMatchMC.hh create mode 100644 RecoDataProducts/inc/TrkCrvMatch.hh diff --git a/CRVReco/CMakeLists.txt b/CRVReco/CMakeLists.txt index d5424624ec..c99542abbf 100644 --- a/CRVReco/CMakeLists.txt +++ b/CRVReco/CMakeLists.txt @@ -2,11 +2,19 @@ cet_make_library( SOURCE src/CrvHelper.cc src/MakeCrvRecoPulses.cc + src/TrkCrvMatchTool.cc LIBRARIES PUBLIC Offline::CosmicRayShieldGeom Offline::DataProducts Offline::GeometryService + Offline::KinKalGeom + Offline::RecoDataProducts + KinKal::General + KinKal::Geometry + art::Framework_Services_Registry + fhiclcpp::types + messagefacility::MF_MessageLogger ROOT::Hist ) @@ -30,6 +38,19 @@ cet_build_plugin(CrvCoincidenceFinder art::module Offline::RecoDataProducts ) +cet_build_plugin(TrkCrvMatcher art::module + REG_SOURCE src/TrkCrvMatcher_module.cc + LIBRARIES REG + Offline::CRVReco + Offline::CosmicRayShieldGeom + Offline::DataProducts + Offline::GeometryService + Offline::KinKalGeom + Offline::RecoDataProducts + KinKal::General + KinKal::Geometry +) + cet_build_plugin(CrvFPGArate art::module REG_SOURCE src/CrvFPGArate_module.cc diff --git a/CRVReco/fcl/prolog_v12.fcl b/CRVReco/fcl/prolog_v12.fcl index 185dbffb43..6fbfac5ffa 100644 --- a/CRVReco/fcl/prolog_v12.fcl +++ b/CRVReco/fcl/prolog_v12.fcl @@ -389,6 +389,14 @@ BEGIN_PROLOG addOppositeSidePulses : true //add pulses without a coincidence at their own side to the cluster containing the other end of their counter } + # track-CRV association, one instance per KalSeed collection (set KalSeedCollection); see TrkCrvMatchTool.hh for the settings + TrkCrvMatcher : + { + module_type : TrkCrvMatcher + CrvCoincidenceClusterCollection : "SelectReco:CrvCoincidenceClusterFinder" + CrvRecoPulseCollection : "CrvRecoPulses" + } + CrvRecoPackage : { diff --git a/CRVReco/inc/TrkCrvMatchTool.hh b/CRVReco/inc/TrkCrvMatchTool.hh new file mode 100644 index 0000000000..7c3b4ab06d --- /dev/null +++ b/CRVReco/inc/TrkCrvMatchTool.hh @@ -0,0 +1,109 @@ +// +// Track-CRV matching shared by the TrkCrvMatcher producer and any fit that uses CRV clusters as constraints, so that +// both apply one definition of a match. See TrkCrvMatch.hh for the output. +// +#ifndef CRVReco_TrkCrvMatchTool_hh +#define CRVReco_TrkCrvMatchTool_hh +#include "Offline/RecoDataProducts/inc/CrvCoincidenceCluster.hh" +#include "Offline/RecoDataProducts/inc/CrvRecoPulse.hh" +#include "Offline/RecoDataProducts/inc/KalSeed.hh" +#include "Offline/RecoDataProducts/inc/TrkCrvMatch.hh" +#include "Offline/DataProducts/inc/SurfaceId.hh" +#include "KinKal/General/Vectors.hh" +#include "canvas/Persistency/Common/Ptr.h" +#include "fhiclcpp/types/Atom.h" +#include "fhiclcpp/types/Sequence.h" +#include +#include +#include +#include +#include +#include +#include + +namespace mu2e { + class CosmicRayShield; + class DetectorSystem; + + class TrkCrvMatchTool { + public: + struct Config { + using Name = fhicl::Name; + using Comment = fhicl::Comment; + fhicl::Sequence refSurfaces{Name("ReferenceSurfaces"), Comment("track reference-time surfaces in order of preference; KalSeed t0 if none present"), std::vector{"TT_Front","TT_Mid"}}; + fhicl::Sequence dtRefWindow{Name("DtRefWindow"), Comment("storage window on t_track(ref) - t_cluster [ns]"), std::vector{-350.0, 350.0}}; + fhicl::Atom dtRefCenter{Name("DtRefCenter"), Comment("dtRef value the time ranking is centred on [ns]"), 75.0}; + fhicl::Sequence dtXingWindow{Name("DtXingWindow"), Comment("storage window on t_cluster - t_track at the cluster plane [ns]"), std::vector{-100.0, 100.0}}; + fhicl::Atom maxDv{Name("MaxDv"), Comment("storage window on |across-bar residual| [mm]"), 500.0}; + fhicl::Atom maxDu{Name("MaxDu"), Comment("storage window on |along-bar residual| for two-ended clusters [mm]"), 3000.0}; + fhicl::Atom doGeometric{Name("DoGeometric"), Comment("form geometric candidates from CRV KalIntersections"), true}; + fhicl::Atom requireSameSector{Name("RequireSameSector"), Comment("project only from a crossing of the cluster's own sector"), false}; + fhicl::Sequence sigmaV{Name("SigmaV"), Comment("CRV across-bar resolution [mm], per cluster sector type 1-4 (EX, T1, T2, muon taggers; last entry for higher types); MC fit on 50 MDC2025bb files"), std::vector{7.0, 13.0, 7.0, 17.0}}; + fhicl::Sequence sigmaU{Name("SigmaU"), Comment("CRV along-bar resolution of two-ended clusters [mm], per sector type"), std::vector{300.0}}; + fhicl::Sequence sigmaT{Name("SigmaT"), Comment("CRV time resolution of two-ended clusters [ns], per sector type"), std::vector{5.0}}; + fhicl::Atom sigmaTSingleEnded{Name("SigmaTSingleEnded"), Comment("CRV time resolution of single-ended clusters [ns]"), 15.0}; + fhicl::Atom trackErrorScale{Name("TrackErrorScale"), Comment("scale on the propagated track position error; sigma = sqrt((scale*err)^2 + TrackPosErrQuad^2)"), 1.5}; + fhicl::Atom trackPosErrQuad{Name("TrackPosErrQuad"), Comment("added in quadrature to the scaled track position error [mm]"), 25.0}; + fhicl::Atom minTrackTimeErr{Name("MinTrackTimeErr"), Comment("floor on the (unscaled) track time error [ns]"), 1.0}; + fhicl::Atom timeOffset{Name("TimeOffset"), Comment("added to cluster and pulse times [ns]; test knob, data offsets belong in conditions"), 0.0}; + fhicl::Atom keepAll{Name("KeepAllClusters"), Comment("ignore every storage window (commissioning)"), false}; + fhicl::Atom layerProbe{Name("LayerProbe"), Comment("probe each layer of every crossed sector for pulses near the predicted bar; needs the reco pulses"), true}; + fhicl::Atom probeBarWindow{Name("ProbeBarWindow"), Comment("layer probe: bars searched on each side of the predicted bar"), 1}; + fhicl::Sequence probeDtWindow{Name("ProbeDtWindow"), Comment("layer probe: window on pulse time - predicted pulse time [ns]"), std::vector{-50.0, 50.0}}; + fhicl::Atom fiberSignalSpeed{Name("FiberSignalSpeed"), Comment("layer probe: signal speed in the fibres [mm/ns], as in CrvCoincidenceFinder"), 140.0}; + fhicl::Atom pulseDelay{Name("ProbePulseDelay"), Comment("layer probe: electronics and scintillation delay subtracted from pulse times [ns], as the CrvCoincidenceFinder timeOffset"), 34.5}; + }; + explicit TrkCrvMatchTool(Config const& conf); + + void beginRun(); // caches the CRV geometry + // per-event inputs; pulses may be null (no layer probe) + void setEvent(std::vector> const& clusters, CrvRecoPulseCollection const* pulses); + // one track; usedInFit lists the clusters its fit used as constraints + TrkCrvMatch match(art::Ptr const& seed, std::vector> const& usedInFit = {}) const; + // cross-track pass over one collection: nShare, bestForCluster, exclusive + void resolve(TrkCrvMatchCollection& matches) const; + bool probeActive() const { return layerProbe_; } + + private: + struct SectorGeom { // CRV sector mid-plane, detector frame + bool valid = false; + KinKal::VEC3 center, u, v, w; + double uHalf = 0, vHalf = 0; + }; + struct ClusterInfo { // per-event cluster quantities + KinKal::VEC3 pos; // detector frame + double time = 0; + int shield = -1; + int sectorType = 0; + bool multiSector = false; + bool singleEnded = false; + }; + double resolution(std::vector const& tab, int sectorType) const; + double trkPosErr(double err) const { return std::sqrt(trkErrScale_ * trkErrScale_ * err * err + posErrQuad_ * posErrQuad_); } + void probe(TrkCrvXing& x, double speed) const; + static bool sameCluster(art::Ptr const& a, art::Ptr const& b); + + std::vector refSurfaces_; + double dtRefLo_, dtRefHi_, dtRefCenter_, dtXingLo_, dtXingHi_, maxDv_, maxDu_; + bool doGeometric_, requireSameSector_; + std::vector sigmaV_, sigmaU_, sigmaT_; + double sigmaTSingle_, trkErrScale_, posErrQuad_, minTimeErr_, timeOffset_; + bool keepAll_, layerProbe_; + int probeBarWindow_; + double probeDtLo_, probeDtHi_, fiberSpeed_, pulseDelay_; + + CosmicRayShield const* crs_ = nullptr; + DetectorSystem const* det_ = nullptr; + std::map sidToShield_; + std::vector sectors_; // indexed by shield + + std::vector> clusters_; + std::vector cinfo_; + CrvRecoPulseCollection const* pulses_ = nullptr; + std::unordered_map> pulsesByBar_; // bar index -> pulses + std::set> clusteredPulses_; // (bar, SiPM, time) of the pulses in clusters + + static constexpr double cLight_ = 299.792458; // mm/ns + }; +} +#endif diff --git a/CRVReco/inc/TrkCrvPlaneError.hh b/CRVReco/inc/TrkCrvPlaneError.hh new file mode 100644 index 0000000000..0f159e0c25 --- /dev/null +++ b/CRVReco/inc/TrkCrvPlaneError.hh @@ -0,0 +1,31 @@ +// +// Track position error on a plane reached by a straight step, shared by TrkCrvMatcher and its truth module. +// +#ifndef CRVReco_TrkCrvPlaneError_hh +#define CRVReco_TrkCrvPlaneError_hh +#include "KinKal/General/Vectors.hh" +#include +#include + +namespace mu2e { + // Track position error along the in-plane direction a, on the plane with normal w reached by a straight step of + // signed path length s from a state (position, momentum p) with 6x6 covariance C (position first). With + // d = p/|p| and P = I - d w^T/(d.w) (move along d onto the plane), the gradient of a.(position on the plane) is + // P^T a for the position block and (s/|p|)(I - d d^T) P^T a for the momentum block. s = 0 gives the error of the + // state itself, measured in the plane rather than in 3D. Returns 0 for a track parallel to the plane. + template double trkCrvPlaneError(COV const& C, KinKal::VEC3 const& p, KinKal::VEC3 const& a, + KinKal::VEC3 const& w, double s) { + double pm = std::sqrt(p.Mag2()); + if(pm <= 0) return 0; + KinKal::VEC3 d = p / pm; + double dw = d.Dot(w); + if(std::fabs(dw) < 1e-3) return 0; + KinKal::VEC3 gp = a - w * (d.Dot(a) / dw); + KinKal::VEC3 gm = (s / pm) * (gp - d * d.Dot(gp)); + double g[6] = {gp.X(), gp.Y(), gp.Z(), gm.X(), gm.Y(), gm.Z()}; + double var = 0; + for(int i = 0; i < 6; ++i) for(int j = 0; j < 6; ++j) var += g[i] * C(i, j) * g[j]; + return std::sqrt(std::max(var, 0.0)); + } +} +#endif diff --git a/CRVReco/src/SConscript b/CRVReco/src/SConscript index fbb4148bbf..647ee422ab 100644 --- a/CRVReco/src/SConscript +++ b/CRVReco/src/SConscript @@ -17,7 +17,16 @@ mainlib = helper.make_mainlib ( [ 'CLHEP', 'mu2e_RecoDataProducts', 'mu2e_DataProducts', 'mu2e_GeomPrimitives', + 'mu2e_GeometryService', + 'mu2e_CosmicRayShieldGeom', + 'mu2e_KinKalGeom', + 'KinKal_Geometry', + 'KinKal_General', + 'fhiclcpp', + 'fhiclcpp_types', + 'MF_MessageLogger', 'art_Framework_Principal', + 'art_Framework_Services_Registry', 'art_Persistency_Provenance', 'art_Persistency_Common', 'art_Utilities', @@ -36,6 +45,9 @@ helper.make_plugins( [ mainlib, 'mu2e_GlobalConstantsService', 'mu2e_RecoDataProducts', 'mu2e_CosmicRayShieldGeom', + 'mu2e_KinKalGeom', + 'KinKal_Geometry', + 'KinKal_General', 'mu2e_ConfigTools', 'mu2e_DataProducts', 'mu2e_DbTables', diff --git a/CRVReco/src/TrkCrvMatchTool.cc b/CRVReco/src/TrkCrvMatchTool.cc new file mode 100644 index 0000000000..a45429630f --- /dev/null +++ b/CRVReco/src/TrkCrvMatchTool.cc @@ -0,0 +1,371 @@ +#include "Offline/CRVReco/inc/TrkCrvMatchTool.hh" +#include "Offline/CRVReco/inc/TrkCrvPlaneError.hh" +#include "Offline/CosmicRayShieldGeom/inc/CosmicRayShield.hh" +#include "Offline/GeometryService/inc/DetectorSystem.hh" +#include "Offline/GeometryService/inc/GeomHandle.hh" +#include "Offline/KinKalGeom/inc/KinKalGeom.hh" +#include "cetlib_except/exception.h" +#include "messagefacility/MessageLogger/MessageLogger.h" +#include +#include +#include + +namespace mu2e { + + TrkCrvMatchTool::TrkCrvMatchTool(Config const& conf) : + dtRefCenter_(conf.dtRefCenter()), maxDv_(conf.maxDv()), maxDu_(conf.maxDu()), + doGeometric_(conf.doGeometric()), requireSameSector_(conf.requireSameSector()), + sigmaV_(conf.sigmaV()), sigmaU_(conf.sigmaU()), sigmaT_(conf.sigmaT()), + sigmaTSingle_(conf.sigmaTSingleEnded()), trkErrScale_(conf.trackErrorScale()), posErrQuad_(conf.trackPosErrQuad()), + minTimeErr_(conf.minTrackTimeErr()), timeOffset_(conf.timeOffset()), keepAll_(conf.keepAll()), + layerProbe_(conf.layerProbe()), probeBarWindow_(conf.probeBarWindow()), fiberSpeed_(conf.fiberSignalSpeed()), + pulseDelay_(conf.pulseDelay()) + { + auto w = conf.dtRefWindow(); auto x = conf.dtXingWindow(); auto p = conf.probeDtWindow(); + if(w.size() != 2 || x.size() != 2 || p.size() != 2) throw cet::exception("CONFIG") << "TrkCrvMatchTool: windows need 2 values"; + if(sigmaV_.empty() || sigmaU_.empty() || sigmaT_.empty()) throw cet::exception("CONFIG") << "TrkCrvMatchTool: empty resolution table"; + if(probeBarWindow_ < 0 || probeBarWindow_ > 100 || fiberSpeed_ <= 0) throw cet::exception("CONFIG") << "TrkCrvMatchTool: bad layer-probe settings"; + dtRefLo_ = w[0]; dtRefHi_ = w[1]; dtXingLo_ = x[0]; dtXingHi_ = x[1]; probeDtLo_ = p[0]; probeDtHi_ = p[1]; + for(auto const& s : conf.refSurfaces()) refSurfaces_.emplace_back(s); + } + + double TrkCrvMatchTool::resolution(std::vector const& tab, int sectorType) const { + size_t i = sectorType > 0 ? static_cast(sectorType - 1) : 0; + return tab[std::min(i, tab.size() - 1)]; + } + + void TrkCrvMatchTool::beginRun() { + GeomHandle crs; + GeomHandle det; + GeomHandle kkg; + crs_ = crs.get(); + det_ = det.get(); + auto const& shields = crs_->getCRSScintillatorShields(); + sidToShield_.clear(); + sectors_.assign(shields.size(), SectorGeom()); + std::map nameToShield; + for(size_t i = 0; i < shields.size(); ++i) nameToShield[shields[i].getName()] = static_cast(i); + for(auto const& sec : kkg->CRV()->sectors()) { + auto it = nameToShield.find(sec.sname_); + if(it == nameToShield.end()) continue; + SectorGeom& g = sectors_[it->second]; + g.valid = true; + g.center = sec.sector_->center(); + g.u = sec.sector_->uDirection(); + g.v = sec.sector_->vDirection(); + g.w = sec.sector_->normal(); + g.uHalf = sec.sector_->uHalfLength(); + g.vHalf = sec.sector_->vHalfLength(); + try { sidToShield_[SurfaceId(sec.sname_)] = it->second; } + catch(std::exception const&) { mf::LogWarning("TrkCrvMatchTool") << "no SurfaceId for CRV sector " << sec.sname_; } + } + } + + void TrkCrvMatchTool::setEvent(std::vector> const& clusters, CrvRecoPulseCollection const* pulses) { + if(!crs_) throw cet::exception("CONFIG") << "TrkCrvMatchTool: beginRun was not called"; + clusters_ = clusters; + cinfo_.assign(clusters_.size(), ClusterInfo()); + clusteredPulses_.clear(); + for(size_t ic = 0; ic < clusters_.size(); ++ic) { + auto const& cc = *clusters_[ic]; + auto& ci = cinfo_[ic]; + auto p = det_->toDetector(cc.GetAvgHitPos()); + ci.pos = KinKal::VEC3(p.x(), p.y(), p.z()); + ci.time = cc.GetAvgHitTime() + timeOffset_; + ci.sectorType = cc.GetCrvSectorType(); + ci.singleEnded = !cc.HitPosAndTimeCalculated(); + std::map pes; + for(auto const& rp : cc.GetCrvRecoPulses()) { + pes[crs_->getBar(rp->GetScintillatorBarIndex()).id().getShieldNumber()] += rp->GetPEs(); + clusteredPulses_.emplace(rp->GetScintillatorBarIndex().asInt(), rp->GetSiPMNumber(), rp->GetPulseTime()); + } + double best = -1; + for(auto const& [s, pe] : pes) if(pe > best) { best = pe; ci.shield = s; } + ci.multiSector = pes.size() > 1; + } + pulses_ = layerProbe_ ? pulses : nullptr; + pulsesByBar_.clear(); + if(pulses_) for(size_t ip = 0; ip < pulses_->size(); ++ip) pulsesByBar_[(*pulses_)[ip].GetScintillatorBarIndex().asInt()].push_back(ip); + } + + bool TrkCrvMatchTool::sameCluster(art::Ptr const& a, art::Ptr const& b) { + if(a.id() == b.id()) return a.key() == b.key(); + // a copy in another collection (e.g. SelectReco): same time, position and PEs + return a->GetAvgHitTime() == b->GetAvgHitTime() && a->GetPEs() == b->GetPEs() && a->GetAvgHitPos() == b->GetAvgHitPos(); + } + + void TrkCrvMatchTool::probe(TrkCrvXing& x, double speed) const { + if(x.sector_ < 0 || static_cast(x.sector_) >= crs_->getCRSScintillatorShields().size()) return; + auto const& shield = crs_->getCRSScintillatorShields()[x.sector_]; + auto const& bd = shield.getCRSScintillatorBarDetail(); + int td = bd.getThicknessDirection(), wd = bd.getWidthDirection(), ld = bd.getLengthDirection(); + double pitch = 2.0 * bd.getHalfWidth(); + CLHEP::Hep3Vector p0 = det_->toMu2e(CLHEP::Hep3Vector(x.pos_.X(), x.pos_.Y(), x.pos_.Z())); + CLHEP::Hep3Vector d(x.dir_.X(), x.dir_.Y(), x.dir_.Z()); + auto const& modules = shield.getCRSScintillatorModules(); + if(modules.empty() || std::fabs(d[td]) < 1e-6) return; // no layers, or a line parallel to them + size_t nLayers = modules.front().getLayers().size(); + x.layers_.assign(nLayers, TrkCrvLayerProbe()); + for(size_t L = 0; L < nLayers; ++L) { + auto& pr = x.layers_[L]; + // the predicted bar: nearest bar of the module whose layer L contains the line's crossing of that layer + CRSScintillatorBar const* pbar = nullptr; + CLHEP::Hep3Vector pp; + double s = 0; + for(auto const& mod : modules) { + if(L >= mod.getLayers().size()) continue; + auto const& lay = mod.getLayers()[L]; + double sl = (lay.getPosition()[td] - p0[td]) / d[td]; + CLHEP::Hep3Vector pl = p0 + sl * d; + if(std::fabs(pl[wd] - lay.getPosition()[wd]) > lay.getHalfWidth() || std::fabs(pl[ld] - lay.getPosition()[ld]) > lay.getHalfLength()) continue; + double bw = 1e30; + for(auto const& b : lay.getBars()) { + double dw = std::fabs(pl[wd] - b->getPosition()[wd]); + if(dw < bw) { bw = dw; pbar = b.get(); } + } + pp = pl; s = sl; + break; + } + if(!pbar) continue; + pr.bar_ = static_cast(pbar->index().asInt()); + pr.uPred_ = pp[ld] - pbar->getPosition()[ld]; + pr.tPred_ = x.time_ + (speed > 0 ? s / speed : 0.0); + if(!pulses_) continue; + auto pulseDt = [&](CrvRecoPulse const& rp, CRSScintillatorBar const& b) { // measured - predicted pulse time + double dist = std::fabs(b.getSiPMPosition(rp.GetSiPMNumber())[ld] - pp[ld]); + return rp.GetPulseTime() - pulseDelay_ + timeOffset_ - (pr.tPred_ + dist / fiberSpeed_); + }; + // the selected bar: nearest to the predicted one within the bar window with an in-window pulse, then smallest |dt| + CRSScintillatorBar const* sbar = nullptr; + int sdb = 0, babs = INT_MAX; + double bdt = 1e30; + for(auto const& mod : modules) { + if(L >= mod.getLayers().size()) continue; + for(auto const& b : mod.getLayers()[L].getBars()) { + int db = static_cast(std::lround((b->getPosition()[wd] - pbar->getPosition()[wd]) / pitch)); + if(std::abs(db) > probeBarWindow_) continue; + auto it = pulsesByBar_.find(b->index().asInt()); + if(it == pulsesByBar_.end()) continue; + for(size_t ip : it->second) { + double dt = pulseDt((*pulses_)[ip], *b); + if(dt < probeDtLo_ || dt > probeDtHi_) continue; + if(std::abs(db) < babs || (std::abs(db) == babs && std::fabs(dt) < std::fabs(bdt))) { babs = std::abs(db); bdt = dt; sbar = b.get(); sdb = db; } + } + } + } + if(!sbar) continue; + pr.dBar_ = static_cast(sdb); + pr.dt_ = bdt; + double tside[2] = {NAN, NAN}; + for(size_t ip : pulsesByBar_.at(sbar->index().asInt())) { + auto const& rp = (*pulses_)[ip]; + double dt = pulseDt(rp, *sbar); + if(dt < probeDtLo_ || dt > probeDtHi_) continue; + pr.pe_ += rp.GetPEs(); + if(clusteredPulses_.count({rp.GetScintillatorBarIndex().asInt(), rp.GetSiPMNumber(), rp.GetPulseTime()})) pr.inCluster_ = true; + int side = sbar->getSiPMPosition(rp.GetSiPMNumber())[ld] < sbar->getPosition()[ld] ? 0 : 1; + double t = rp.GetPulseTime(); + if(std::isnan(tside[side]) || t < tside[side]) tside[side] = t; + } + if(!std::isnan(tside[0]) && !std::isnan(tside[1])) pr.uTdiv_ = 0.5 * (tside[0] - tside[1]) * fiberSpeed_; + } + } + + TrkCrvMatch TrkCrvMatchTool::match(art::Ptr const& seed, std::vector> const& usedInFit) const { + auto const& ks = *seed; + TrkCrvMatch m; + m.track_ = seed; + double t0 = ks.t0Val(); + double t0err = std::sqrt(std::max(ks.t0Var(), 0.0)); + // reference times: the intersection on each surface nearest in time to t0 + auto nearest = [&](SurfaceId const& sid) -> int { + int best = -1; double bdt = 1e30; + for(size_t k = 0; k < ks.intersections().size(); ++k) { + auto const& ki = ks.intersections()[k]; + if(ki.surfaceId() != sid) continue; + double d = std::fabs(ki.time() - t0); + if(d < bdt) { bdt = d; best = static_cast(k); } + } + return best; + }; + int kf = nearest(SurfaceId(SurfaceIdDetail::TT_Front)); + int km = nearest(SurfaceId(SurfaceIdDetail::TT_Mid)); + if(kf >= 0) { m.hasFront_ = true; m.tFront_ = ks.intersections()[kf].time(); } + if(km >= 0) { m.hasMid_ = true; m.tMid_ = ks.intersections()[km].time(); } + m.tRef_ = t0; + bool hasRefPos = false; + KinKal::VEC3 refPos; + for(auto const& rs : refSurfaces_) { + int k = nearest(rs); + if(k < 0) continue; + m.refSurface_ = rs; + m.tRef_ = ks.intersections()[k].time(); + refPos = ks.intersections()[k].position3(); + hasRefPos = true; + break; + } + m.timeOffset_ = timeOffset_; + + // CRV crossings + double sigT = std::max(t0err, minTimeErr_); + if(doGeometric_) { + for(size_t k = 0; k < ks.intersections().size(); ++k) { + auto const& ki = ks.intersections()[k]; + auto it = sidToShield_.find(ki.surfaceId()); + if(it == sidToShield_.end()) continue; + auto const& g = sectors_[it->second]; + TrkCrvXing x; + x.sid_ = ki.surfaceId(); + x.inter_ = static_cast(k); + x.sector_ = static_cast(it->second); + auto p = ki.position3(); + auto d = ki.momentum3().Unit(); + x.pos_ = XYZVectorF(p.X(), p.Y(), p.Z()); + x.dir_ = XYZVectorF(d.X(), d.Y(), d.Z()); + x.time_ = ki.time(); + x.inBounds_ = ki.inBounds(); + auto const& cov = ki.pstate_.stateCovariance(); + auto mom = ki.momentum3(); + x.sigU_ = trkPosErr(trkCrvPlaneError(cov, mom, g.u, g.w, 0.0)); + x.sigV_ = trkPosErr(trkCrvPlaneError(cov, mom, g.v, g.w, 0.0)); + x.sigT_ = sigT; + x.mom_ = ki.mom(); + x.momErr_ = ki.momerr(); + KinKal::VEC3 loc = p - g.center; + x.dEdgeU_ = g.uHalf - std::fabs(loc.Dot(g.u)); + x.dEdgeV_ = g.vHalf - std::fabs(loc.Dot(g.v)); + x.edgeSig_ = (x.sigU_ > 0 && x.sigV_ > 0) ? std::min(x.dEdgeU_ / x.sigU_, x.dEdgeV_ / x.sigV_) : 0.f; + if(layerProbe_) probe(x, std::sqrt(ki.velocity().Mag2())); + m.xings_.push_back(x); + } + } + + // candidates + for(size_t ic = 0; ic < clusters_.size(); ++ic) { + auto const& ci = cinfo_[ic]; + TrkCrvCandidate c; + c.cluster_ = clusters_[ic]; + c.sector_ = static_cast(ci.shield); + c.dtRef_ = m.tRef_ - ci.time; + c.dtRefToF_ = hasRefPos ? c.dtRef_ - std::sqrt((refPos - ci.pos).Mag2()) / cLight_ : c.dtRef_; + if(ci.singleEnded) c.setFlag(TrkCrvCandidate::singleEnded); + if(ci.multiSector) c.setFlag(TrkCrvCandidate::multiSector); + bool timeOK = keepAll_ || (c.dtRef_ >= dtRefLo_ && c.dtRef_ <= dtRefHi_); + if(timeOK) c.setFlag(TrkCrvCandidate::timeCand); + // geometric evidence: project from the CRV crossing nearest in path to the cluster's plane (straight line outside the field) + int bestx = -1; double bds = 1e30; + bool hasPlane = ci.shield >= 0 && static_cast(ci.shield) < sectors_.size() && sectors_[ci.shield].valid; + if(hasPlane) { + auto const& g = sectors_[ci.shield]; + for(size_t k = 0; k < m.xings_.size(); ++k) { + if(requireSameSector_ && m.xings_[k].sector_ != ci.shield) continue; + auto const& xk = m.xings_[k]; + KinKal::VEC3 pk(xk.pos_.X(), xk.pos_.Y(), xk.pos_.Z()), dk(xk.dir_.X(), xk.dir_.Y(), xk.dir_.Z()); + double dn = dk.Dot(g.w); + if(std::fabs(dn) < 1e-3) continue; + double ds = std::fabs((ci.pos - pk).Dot(g.w) / dn); + if(ds < bds) { bds = ds; bestx = static_cast(k); } + } + } + if(bestx >= 0) { + auto const& g = sectors_[ci.shield]; + auto const& x = m.xings_[bestx]; + KinKal::VEC3 px(x.pos_.X(), x.pos_.Y(), x.pos_.Z()), dx(x.dir_.X(), x.dir_.Y(), x.dir_.Z()); + double dn = dx.Dot(g.w); + auto const& ki = ks.intersections()[x.inter_]; + double speed = std::sqrt(ki.velocity().Mag2()); + double ds = (ci.pos - px).Dot(g.w) / dn; // path length from the crossing to the cluster plane + KinKal::VEC3 pp = px + ds * dx; + double tp = x.time_ + (speed > 0 ? ds / speed : 0.0); + KinKal::VEC3 r = ci.pos - pp; + c.du_ = r.Dot(g.u); + c.dv_ = r.Dot(g.v); + c.dtXing_ = ci.time - tp; + // track errors on the cluster's plane: the reference crossing's covariance carried over the straight step + auto const& cov = ki.pstate_.stateCovariance(); + double tsu = trkPosErr(trkCrvPlaneError(cov, ki.momentum3(), g.u, g.w, ds)); + double tsv = trkPosErr(trkCrvPlaneError(cov, ki.momentum3(), g.v, g.w, ds)); + c.sigU_ = static_cast(tsu); + c.sigV_ = static_cast(tsv); + double sv = resolution(sigmaV_, ci.sectorType), su = resolution(sigmaU_, ci.sectorType); + double st = ci.singleEnded ? sigmaTSingle_ : resolution(sigmaT_, ci.sectorType); + c.chi2_ = c.dv_*c.dv_/(sv*sv + tsv*tsv) + c.dtXing_*c.dtXing_/(st*st + x.sigT_*x.sigT_); + c.ndof_ = 2; + if(!ci.singleEnded) { c.chi2_ += c.du_*c.du_/(su*su + tsu*tsu); c.ndof_ = 3; } + bool geomOK = keepAll_ || (std::fabs(c.dv_) < maxDv_ && (ci.singleEnded || std::fabs(c.du_) < maxDu_) + && c.dtXing_ >= dtXingLo_ && c.dtXing_ <= dtXingHi_); + if(geomOK) { + c.xing_ = static_cast(bestx); + c.setFlag(TrkCrvCandidate::geomCand); + if(x.sector_ == ci.shield) c.setFlag(TrkCrvCandidate::sameSector); + KinKal::VEC3 loc = pp - g.center; + if(std::fabs(loc.Dot(g.u)) > g.uHalf || std::fabs(loc.Dot(g.v)) > g.vHalf) c.setFlag(TrkCrvCandidate::outOfBounds); + } + } + if(!c.hasFlag(TrkCrvCandidate::geomCand)) { c.chi2_ = -1; c.ndof_ = 0; c.du_ = c.dv_ = c.dtXing_ = c.sigU_ = c.sigV_ = 0; } + if(c.hasFlag(TrkCrvCandidate::geomCand) || timeOK) { + for(auto const& u : usedInFit) if(sameCluster(u, c.cluster_)) { c.setFlag(TrkCrvCandidate::usedInFit); break; } + m.cands_.push_back(c); + } + } + + // rank: geometric by chi2, then time-only by distance from the time centre + std::stable_sort(m.cands_.begin(), m.cands_.end(), [&](TrkCrvCandidate const& a, TrkCrvCandidate const& b) { + bool ga = a.hasFlag(TrkCrvCandidate::geomCand), gb = b.hasFlag(TrkCrvCandidate::geomCand); + if(ga != gb) return ga; + if(ga) return a.chi2_ < b.chi2_; + return std::fabs(a.dtRef_ - dtRefCenter_) < std::fabs(b.dtRef_ - dtRefCenter_); + }); + double bt = 1e30; + std::map bestInSector; // cluster sector -> lowest-chi2 geometric candidate + for(size_t j = 0; j < m.cands_.size(); ++j) { + auto& c = m.cands_[j]; + if(c.hasFlag(TrkCrvCandidate::geomCand)) { + if(m.bestGeom_ < 0) m.bestGeom_ = static_cast(j); + if(bestInSector.emplace(c.sector_, static_cast(j)).second) c.setFlag(TrkCrvCandidate::bestInSector); + } + if(c.hasFlag(TrkCrvCandidate::timeCand) && std::fabs(c.dtRef_ - dtRefCenter_) < bt) { + bt = std::fabs(c.dtRef_ - dtRefCenter_); + m.bestTime_ = static_cast(j); + } + } + for(auto& x : m.xings_) { + auto ib = bestInSector.find(x.sector_); + if(ib != bestInSector.end()) x.best_ = ib->second; + } + int bf = m.bestGeom_ >= 0 ? m.bestGeom_ : m.bestTime_; + if(bf >= 0) m.cands_[bf].setFlag(TrkCrvCandidate::bestForTrack); + return m; + } + + void TrkCrvMatchTool::resolve(TrkCrvMatchCollection& out) const { + struct Ref { size_t trk, cand; }; + std::map> byCluster; + for(size_t it = 0; it < out.size(); ++it) + for(size_t j = 0; j < out[it].cands_.size(); ++j) byCluster[out[it].cands_[j].cluster_.key()].push_back({it, j}); + auto metric = [&](Ref const& r) { // geometric chi2 first, then time distance (offset so geometric always wins) + auto const& c = out[r.trk].cands_[r.cand]; + return c.hasFlag(TrkCrvCandidate::geomCand) ? static_cast(c.chi2_) : 1e9 + std::fabs(c.dtRef_ - dtRefCenter_); + }; + std::vector> geomPairs; + for(auto& [key, refs] : byCluster) { + Ref best = refs.front(); + for(auto const& r : refs) { + out[r.trk].cands_[r.cand].nShare_ = static_cast(std::min(refs.size(), 255)); + if(metric(r) < metric(best)) best = r; + if(out[r.trk].cands_[r.cand].hasFlag(TrkCrvCandidate::geomCand)) geomPairs.push_back({metric(r), r}); + } + out[best.trk].cands_[best.cand].setFlag(TrkCrvCandidate::bestForCluster); + } + std::stable_sort(geomPairs.begin(), geomPairs.end(), [](auto const& a, auto const& b) { return a.first < b.first; }); + std::map usedCluster; + std::map,bool> usedXing; // (track, cluster sector) + for(auto const& [chi2, r] : geomPairs) { + auto& c = out[r.trk].cands_[r.cand]; + auto xk = std::make_pair(r.trk, static_cast(c.sector_)); + if(usedCluster[c.cluster_.key()] || usedXing[xk]) continue; + usedCluster[c.cluster_.key()] = usedXing[xk] = true; + c.setFlag(TrkCrvCandidate::exclusive); + } + } +} diff --git a/CRVReco/src/TrkCrvMatcher_module.cc b/CRVReco/src/TrkCrvMatcher_module.cc new file mode 100644 index 0000000000..a9f574087d --- /dev/null +++ b/CRVReco/src/TrkCrvMatcher_module.cc @@ -0,0 +1,121 @@ +// +// Associate reconstructed tracks (KalSeeds) with CRV coincidence clusters, one TrkCrvMatch per KalSeed, using +// TrkCrvMatchTool. Storage windows are loose on purpose: selections belong to the analysis. +// +#include "art/Framework/Core/EDProducer.h" +#include "art/Framework/Core/ModuleMacros.h" +#include "art/Framework/Principal/Event.h" +#include "art/Framework/Principal/Handle.h" +#include "art/Framework/Principal/Run.h" +#include "canvas/Utilities/InputTag.h" +#include "fhiclcpp/types/Atom.h" +#include "fhiclcpp/types/TableFragment.h" +#include "messagefacility/MessageLogger/MessageLogger.h" + +#include "Offline/CRVReco/inc/TrkCrvMatchTool.hh" +#include "Offline/RecoDataProducts/inc/CrvCoincidenceCluster.hh" +#include "Offline/RecoDataProducts/inc/CrvRecoPulse.hh" +#include "Offline/RecoDataProducts/inc/KalSeed.hh" +#include "Offline/RecoDataProducts/inc/TrkCrvMatch.hh" + +#include +#include +#include + +namespace mu2e { + + class TrkCrvMatcher : public art::EDProducer { + public: + struct Config { + using Name = fhicl::Name; + using Comment = fhicl::Comment; + fhicl::Atom kalSeedTag{Name("KalSeedCollection"), Comment("KalSeed collection; one TrkCrvMatch per KalSeed")}; + fhicl::Atom clusterTag{Name("CrvCoincidenceClusterCollection"), Comment("CRV clusters; must be the persisted collection"), art::InputTag("SelectReco:CrvCoincidenceClusterFinder")}; + fhicl::Atom pulseTag{Name("CrvRecoPulseCollection"), Comment("all CRV reco pulses, for the layer probe; empty turns the probe off"), art::InputTag("CrvRecoPulses")}; + fhicl::Atom usedInFitTag{Name("UsedInFitAssns"), Comment("KalSeed-cluster associations of the clusters each fit used as constraints; empty: none"), art::InputTag()}; + fhicl::Atom diag{Name("diagLevel"), Comment("diagnostic printout level"), 0}; + fhicl::TableFragment tool; + }; + using Parameters = art::EDProducer::Table; + explicit TrkCrvMatcher(const Parameters& conf); + void beginRun(art::Run& run) override; + void produce(art::Event& event) override; + + private: + art::ProductToken kalSeedToken_; + art::ProductToken clusterToken_; + art::InputTag pulseTag_, usedInFitTag_; + int diag_; + TrkCrvMatchTool tool_; + bool warnedNoPulses_ = false; + }; + + TrkCrvMatcher::TrkCrvMatcher(const Parameters& conf) : + art::EDProducer(conf), + kalSeedToken_(consumes(conf().kalSeedTag())), + clusterToken_(consumes(conf().clusterTag())), + pulseTag_(conf().pulseTag()), usedInFitTag_(conf().usedInFitTag()), diag_(conf().diag()), + tool_(conf().tool()) + { + if(tool_.probeActive() && !pulseTag_.empty()) mayConsume(pulseTag_); + if(!usedInFitTag_.empty()) consumes(usedInFitTag_); + produces(); + } + + void TrkCrvMatcher::beginRun(art::Run&) { tool_.beginRun(); } + + void TrkCrvMatcher::produce(art::Event& event) { + auto const& ksH = event.getValidHandle(kalSeedToken_); + auto const& ccH = event.getValidHandle(clusterToken_); + std::vector> clusters; + clusters.reserve(ccH->size()); + for(size_t ic = 0; ic < ccH->size(); ++ic) clusters.emplace_back(ccH, ic); + + CrvRecoPulseCollection const* pulses = nullptr; + if(tool_.probeActive() && !pulseTag_.empty()) { + auto pH = event.getHandle(pulseTag_); + if(pH.isValid()) pulses = pH.product(); + else if(!warnedNoPulses_) { + mf::LogWarning("TrkCrvMatcher") << "no CrvRecoPulseCollection " << pulseTag_ << ": the layer probe records predicted bars only"; + warnedNoPulses_ = true; + } + } + tool_.setEvent(clusters, pulses); + + std::map>> used; // KalSeed key -> clusters its fit used + if(!usedInFitTag_.empty()) { + auto const& aH = event.getValidHandle(usedInFitTag_); + for(auto const& a : *aH) if(a.first.id() == ksH.id()) used[a.first.key()].push_back(a.second); + } + + auto out = std::make_unique(); + out->reserve(ksH->size()); + static const std::vector> none; + for(size_t is = 0; is < ksH->size(); ++is) { + auto iu = used.find(is); + out->push_back(tool_.match(art::Ptr(ksH, is), iu != used.end() ? iu->second : none)); + } + tool_.resolve(*out); + + if(diag_ > 0) { + for(auto const& m : *out) { + mf::LogInfo log("TrkCrvMatcher"); + log << "event " << event.id() << " track " << m.track_.key() << " tRef " << m.tRef_ << " (" << m.refSurface_ << ")" + << " xings " << m.xings_.size() << " cands " << m.cands_.size() << " bestGeom " << m.bestGeom_ << " bestTime " << m.bestTime_; + if(diag_ > 1) { + for(auto const& c : m.cands_) + log << "\n cluster " << c.cluster_.key() << " shield " << c.sector_ << " xing " << c.xing_ << " dtRef " << c.dtRef_ + << " dtXing " << c.dtXing_ << " du " << c.du_ << " dv " << c.dv_ << " chi2 " << c.chi2_ << " flags " << c.flags_; + for(auto const& x : m.xings_) + for(size_t L = 0; L < x.layers_.size(); ++L) + log << "\n probe shield " << x.sector_ << " layer " << L << " bar " << x.layers_[L].bar_ << " dBar " << int(x.layers_[L].dBar_) + << " uPred " << x.layers_[L].uPred_ << " dt " << x.layers_[L].dt_ << " pe " << x.layers_[L].pe_ + << " inCluster " << x.layers_[L].inCluster_ << " uTdiv " << x.layers_[L].uTdiv_; + } + } + } + event.put(std::move(out)); + } +} + +DEFINE_ART_MODULE(mu2e::TrkCrvMatcher) diff --git a/CRVResponse/CMakeLists.txt b/CRVResponse/CMakeLists.txt index e2b669a3ff..6d2ce31a70 100644 --- a/CRVResponse/CMakeLists.txt +++ b/CRVResponse/CMakeLists.txt @@ -144,6 +144,19 @@ cet_build_plugin(MakeCrvCoincidenceClusterMCAssns art::module Offline::MCDataProducts ) +cet_build_plugin(TrkCrvMatchMCMaker art::module + REG_SOURCE src/TrkCrvMatchMCMaker_module.cc + LIBRARIES REG + Offline::CosmicRayShieldGeom + Offline::DataProducts + Offline::GeometryService + Offline::KinKalGeom + Offline::MCDataProducts + Offline::RecoDataProducts + KinKal::General + KinKal::Geometry +) + configure_file(${CMAKE_CURRENT_SOURCE_DIR}/fcl/prolog.fcl ${CURRENT_BINARY_DIR} fcl/prolog.fcl) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/fcl/epilog_extracted.fcl ${CURRENT_BINARY_DIR} fcl/epilog_extracted.fcl ) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/fcl/epilog_extracted_v02.fcl ${CURRENT_BINARY_DIR} fcl/epilog_extracted_v02.fcl ) diff --git a/CRVResponse/fcl/prolog_v12.fcl b/CRVResponse/fcl/prolog_v12.fcl index c7cae1c430..705a9bf5fa 100644 --- a/CRVResponse/fcl/prolog_v12.fcl +++ b/CRVResponse/fcl/prolog_v12.fcl @@ -192,6 +192,16 @@ BEGIN_PROLOG crvCoincidenceMCTags : [ "CrvCoincidenceClusterMatchMC" ] } + # MC truth for one TrkCrvMatcher instance (set TrkCrvMatchCollection); needs the simulation geometry + TrkCrvMatchMC : { + module_type : TrkCrvMatchMCMaker + KalSeedMCAssns : "SelectReco" + SimParticleCollection : "compressRecoMCs" + MCTrajectoryCollection : "compressRecoMCs" + CrvStepCollection : "compressDigiMCs" + CrvCoincidenceClusterMCAssns : "CrvCoincidenceClusterMCAssns" + } + CrvDAQPackage : { diff --git a/CRVResponse/src/SConscript b/CRVResponse/src/SConscript index 5a1cf9466a..1144f87310 100644 --- a/CRVResponse/src/SConscript +++ b/CRVResponse/src/SConscript @@ -39,6 +39,9 @@ helper.make_plugins( [ mainlib, 'mu2e_MCDataProducts', 'mu2e_RecoDataProducts', 'mu2e_CosmicRayShieldGeom', + 'mu2e_KinKalGeom', + 'KinKal_Geometry', + 'KinKal_General', 'mu2e_ConfigTools', 'mu2e_DataProducts', 'mu2e_DbTables', diff --git a/CRVResponse/src/TrkCrvMatchMCMaker_module.cc b/CRVResponse/src/TrkCrvMatchMCMaker_module.cc new file mode 100644 index 0000000000..c1bdae30f3 --- /dev/null +++ b/CRVResponse/src/TrkCrvMatchMCMaker_module.cc @@ -0,0 +1,459 @@ +// +// MC truth for TrkCrvMatch by SimParticle identity. For each track: its particle (KalSeedMC primary contributor), the +// true CRV sector crossings of that particle and its ancestors (MCTrajectory chords through the sector mid-plane +// rectangles, gap-inclusive, plus CrvStep deposits), the truth of each reco crossing, and the relation of each +// candidate cluster's deposits to the track's particle. The geometry service must hold the SIMULATION geometry. +// Particles are identified by (simStage, key), so steps and trajectories from different compressed SimParticle +// collections of one stage compare correctly. +// +#include "art/Framework/Core/EDProducer.h" +#include "art/Framework/Core/ModuleMacros.h" +#include "art/Framework/Principal/Event.h" +#include "art/Framework/Principal/Handle.h" +#include "art/Framework/Principal/Run.h" +#include "canvas/Utilities/InputTag.h" +#include "fhiclcpp/types/Atom.h" +#include "messagefacility/MessageLogger/MessageLogger.h" + +#include "Offline/CRVReco/inc/TrkCrvPlaneError.hh" +#include "Offline/CosmicRayShieldGeom/inc/CosmicRayShield.hh" +#include "Offline/DataProducts/inc/SurfaceId.hh" +#include "Offline/GeometryService/inc/DetectorSystem.hh" +#include "Offline/GeometryService/inc/GeomHandle.hh" +#include "Offline/KinKalGeom/inc/KinKalGeom.hh" +#include "Offline/MCDataProducts/inc/CrvCoincidenceClusterMCAssns.hh" +#include "Offline/MCDataProducts/inc/CrvStep.hh" +#include "Offline/MCDataProducts/inc/KalSeedMC.hh" +#include "Offline/MCDataProducts/inc/MCTrajectory.hh" +#include "Offline/MCDataProducts/inc/SimParticle.hh" +#include "Offline/MCDataProducts/inc/TrkCrvMatchMC.hh" +#include "Offline/RecoDataProducts/inc/TrkCrvMatch.hh" +#include "KinKal/General/Vectors.hh" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace mu2e { + + class TrkCrvMatchMCMaker : public art::EDProducer { + public: + struct Config { + using Name = fhicl::Name; + using Comment = fhicl::Comment; + fhicl::Atom matchTag{Name("TrkCrvMatchCollection"), Comment("TrkCrvMatch collection to add truth to")}; + fhicl::Atom kalSeedMCAssnsTag{Name("KalSeedMCAssns"), Comment("KalSeed to KalSeedMC associations"), art::InputTag("SelectReco")}; + fhicl::Atom simParticleTag{Name("SimParticleCollection"), Comment("SimParticles the KalSeedMC keys refer to"), art::InputTag("compressRecoMCs")}; + fhicl::Atom mcTrajectoryTag{Name("MCTrajectoryCollection"), Comment("MC trajectories for the gap-inclusive crossings"), art::InputTag("compressRecoMCs")}; + fhicl::Atom crvStepTag{Name("CrvStepCollection"), Comment("CRV steps for the deposits; the digi-stage collection holds every digitised step"), art::InputTag("compressDigiMCs")}; + fhicl::Atom clusterMCAssnsTag{Name("CrvCoincidenceClusterMCAssns"), Comment("cluster to cluster-MC associations, over the clusters the matcher used"), art::InputTag("CrvCoincidenceClusterMCAssns")}; + fhicl::Atom edgeSigCut{Name("EdgeSigCut"), Comment("summary: a fake counts as near-edge when its edgeSig is below this"), 3.0}; + fhicl::Atom maxGenerations{Name("MaxGenerations"), Comment("ancestors of the track's particle searched for CRV crossings"), 3}; + fhicl::Atom printSummary{Name("PrintSummary"), Comment("print per-sector crossing truth counts at end of job"), true}; + fhicl::Atom diag{Name("diagLevel"), Comment("diagnostic printout level"), 0}; + }; + using Parameters = art::EDProducer::Table; + explicit TrkCrvMatchMCMaker(const Parameters& conf); + void beginRun(art::Run& run) override; + void produce(art::Event& event) override; + void endJob() override; + + private: + using PKey = std::pair; // (simStage, key): particle identity across collections + static PKey pkey(art::Ptr const& p) { return {p->simStage(), p.key()}; } + struct SectorGeom { bool valid = false; std::shared_ptr rect; SurfaceId sid; }; + struct Counts { // per shield + unsigned recoX = 0, recoTrueDep = 0, recoTrueGap = 0, recoTrueAnc = 0, recoFake = 0, recoFakeEdge = 0; + unsigned recoFakeNbr = 0, trueMissedNbr = 0; + unsigned trueClu = 0, trueCluGeom = 0, trueCluExcl = 0; // the particle's own cluster in this sector + unsigned trueCluBest = 0, trueCluProj = 0; // ... best in its sector; projected from another sector + double chi2nd = 0, chi2ndProj = 0; // sums of chi2/ndof of those geometric candidates + unsigned trueX = 0, trueFound = 0, trueMissed = 0, trueNoGeom = 0; + }; + // relation of particle q to the track's particle: walk q's ancestry + uint8_t relation(art::Ptr q, std::set const& self, std::set const& anc, PKey const& trkRoot) const; + PKey root(art::Ptr p) const; + + art::InputTag matchTag_, ksmcTag_, spTag_, trajTag_, stepTag_, ccmcTag_; + double edgeSigCut_; + unsigned maxGen_; + bool printSummary_; + int diag_; + std::vector sectors_; // indexed by shield + std::vector planeGroup_; // per shield: sectors sharing one plane get one id, -1 = no rectangle + std::vector shieldNames_; + std::map counts_; + std::array bestGeomRel_{}, bestTimeRel_{}; + unsigned nTracks_ = 0, nTracksMC_ = 0, nTracksCrossing_ = 0; + }; + + TrkCrvMatchMCMaker::TrkCrvMatchMCMaker(const Parameters& conf) : + art::EDProducer(conf), + matchTag_(conf().matchTag()), ksmcTag_(conf().kalSeedMCAssnsTag()), spTag_(conf().simParticleTag()), + trajTag_(conf().mcTrajectoryTag()), stepTag_(conf().crvStepTag()), ccmcTag_(conf().clusterMCAssnsTag()), + edgeSigCut_(conf().edgeSigCut()), maxGen_(conf().maxGenerations()), printSummary_(conf().printSummary()), diag_(conf().diag()) + { + consumes(matchTag_); + consumes(ksmcTag_); + consumes(spTag_); + consumes(trajTag_); + consumes(stepTag_); + consumes(ccmcTag_); + produces(); + } + + void TrkCrvMatchMCMaker::beginRun(art::Run&) { + GeomHandle crs; + GeomHandle kkg; + auto const& shields = crs->getCRSScintillatorShields(); + sectors_.assign(shields.size(), SectorGeom()); + shieldNames_.clear(); + std::map nameToShield; + for(size_t i = 0; i < shields.size(); ++i) { nameToShield[shields[i].getName()] = static_cast(i); shieldNames_.push_back(shields[i].getName()); } + for(auto const& sec : kkg->CRV()->sectors()) { + auto it = nameToShield.find(sec.sname_); + if(it == nameToShield.end()) continue; + auto& g = sectors_[it->second]; + g.valid = true; + g.rect = sec.sector_; + try { g.sid = SurfaceId(sec.sname_); } catch(std::exception const&) {} + } + // coplanar sectors: parallel normals and centres within 5 mm of one plane + planeGroup_.assign(sectors_.size(), -1); + int ng = 0; + for(size_t s = 0; s < sectors_.size(); ++s) { + if(!sectors_[s].valid || planeGroup_[s] >= 0) continue; + planeGroup_[s] = ng; + auto const& rs = *sectors_[s].rect; + for(size_t t = s + 1; t < sectors_.size(); ++t) { + if(!sectors_[t].valid || planeGroup_[t] >= 0) continue; + auto const& rt = *sectors_[t].rect; + if(std::fabs(rs.normal().Dot(rt.normal())) > 0.999 && std::fabs((rt.center() - rs.center()).Dot(rs.normal())) < 5.0) planeGroup_[t] = ng; + } + ++ng; + } + } + + TrkCrvMatchMCMaker::PKey TrkCrvMatchMCMaker::root(art::Ptr p) const { + for(int i = 0; i < 1000 && p->parent().isNonnull(); ++i) p = p->parent(); + return pkey(p); + } + + uint8_t TrkCrvMatchMCMaker::relation(art::Ptr q, std::set const& self, std::set const& anc, PKey const& trkRoot) const { + if(q.isNull()) return TrkCrvTruth::Background; + bool family = false; + for(int i = 0; i < 1000 && q.isNonnull(); ++i) { + auto k = pkey(q); + if(self.count(k)) return TrkCrvTruth::SameParticle; // the track's particle (any stage) or a descendant of it + if(anc.count(k)) family = true; // an ancestor or another descendant of an ancestor + if(q->parent().isNull()) return family ? TrkCrvTruth::SameFamily : (k == trkRoot ? TrkCrvTruth::SamePrimary : TrkCrvTruth::Unrelated); + q = q->parent(); + } + return family ? TrkCrvTruth::SameFamily : TrkCrvTruth::Unrelated; + } + + void TrkCrvMatchMCMaker::produce(art::Event& event) { + auto const& mH = event.getValidHandle(matchTag_); + auto const& ksmcH = event.getValidHandle(ksmcTag_); + auto spH = event.getHandle(spTag_); + auto trajH = event.getHandle(trajTag_); + auto stepH = event.getHandle(stepTag_); + auto ccmcH = event.getHandle(ccmcTag_); + GeomHandle crs; + GeomHandle det; + auto toDet = [&](CLHEP::Hep3Vector const& v) { auto d = det->toDetector(v); return KinKal::VEC3(d.x(), d.y(), d.z()); }; + + // (KalSeed collection, key) -> KalSeedMC: SelectRecoMC writes one Assns over every KalSeed collection it selects + std::map, art::Ptr> ksmc; + for(auto const& a : *ksmcH) ksmc[{a.first.id(), a.first.key()}] = a.second; + // cluster key -> cluster MC, and each cluster's dominant shield + std::map> ccmc; + std::map clusterShield; + art::ProductID clusterPid; + if(ccmcH.isValid()) for(auto const& a : *ccmcH) { + ccmc[a.first.key()] = a.second; + clusterPid = a.first.id(); + std::map pes; + for(auto const& rp : a.first->GetCrvRecoPulses()) pes[crs->getBar(rp->GetScintillatorBarIndex()).id().getShieldNumber()] += rp->GetPEs(); + double best = -1; + for(auto const& [s, pe] : pes) if(pe > best) { best = pe; clusterShield[a.first.key()] = s; } + } + + auto out = std::make_unique(); + for(size_t imatch = 0; imatch < mH->size(); ++imatch) { + auto const& m = (*mH)[imatch]; + TrkCrvMatchMC mc; + mc.match_ = art::Ptr(mH, imatch); + mc.recoXingTruth_.assign(m.xings_.size(), -1); + mc.recoXingNeighbor_.assign(m.xings_.size(), -1); + mc.cands_.assign(m.cands_.size(), TrkCrvCandidateMC()); + ++nTracks_; + auto im = ksmc.find({m.track_.id(), m.track_.key()}); + bool ok = im != ksmc.end() && spH.isValid(); + if(ok && !im->second->simParticles().empty()) mc.trackSim_ = im->second->simParticle().simParticle(spH); + if(mc.trackSim_.isNull() || !mc.trackSim_.isAvailable()) { out->push_back(std::move(mc)); continue; } + ++nTracksMC_; + PKey trk = pkey(mc.trackSim_); + PKey trkRoot = root(mc.trackSim_); + + // lineage: generation 0 = the track's particle (and its earlier-stage selves), then ancestors + std::vector,uint8_t>> lineage; + std::set anc, self; + art::Ptr p = mc.trackSim_; + uint8_t gen = 0; + for(int i = 0; i < 1000 && p.isNonnull() && gen <= maxGen_; ++i) { + lineage.push_back({p, gen}); + if(gen > 0) anc.insert(pkey(p)); else self.insert(pkey(p)); + bool self = p->selfParent(); + p = p->parent(); + if(!self) ++gen; + } + + // true crossings: trajectory chords through the sector rectangles, then deposits + std::map, TrkCrvXingMC> xmap; // (lineage index, shield) + for(size_t il = 0; il < lineage.size(); ++il) { + auto const& [sp, g] = lineage[il]; + if(trajH.isValid()) { + auto it = trajH->find(sp); + if(it != trajH->end()) { + auto const& pts = it->second.points(); + double mass = sp->startMomentum().m(); + for(size_t j = 1; j < pts.size(); ++j) { + KinKal::VEC3 a = toDet(pts[j-1].pos()), b = toDet(pts[j].pos()); + for(size_t s = 0; s < sectors_.size(); ++s) { + auto const& sg = sectors_[s]; + if(!sg.valid) continue; + double da = (a - sg.rect->center()).Dot(sg.rect->normal()), db = (b - sg.rect->center()).Dot(sg.rect->normal()); + if(da * db > 0 || da == db) continue; + double f = da / (da - db); + KinKal::VEC3 x = a + f * (b - a); + if(!sg.rect->inBounds(x, 0.0)) continue; + auto key = std::make_pair(il, static_cast(s)); + double t = pts[j-1].t() + f * (pts[j].t() - pts[j-1].t()); + auto& xm = xmap[key]; + if(xm.geom_ && xm.time_ <= t) continue; // keep the earliest crossing of a sector + xm.geom_ = true; + xm.pos_ = XYZVectorF(x.X(), x.Y(), x.Z()); + auto d = (b - a).Unit(); + xm.dir_ = XYZVectorF(d.X(), d.Y(), d.Z()); + xm.time_ = t; + double ke = pts[j-1].kineticEnergy() + f * (pts[j].kineticEnergy() - pts[j-1].kineticEnergy()); + xm.mom_ = std::sqrt(std::max(ke * (ke + 2.0 * mass), 0.0)); + auto loc = x - sg.rect->center(); + xm.dEdgeU_ = sg.rect->uHalfLength() - std::fabs(loc.Dot(sg.rect->uDirection())); + xm.dEdgeV_ = sg.rect->vHalfLength() - std::fabs(loc.Dot(sg.rect->vDirection())); + } + } + } + } + if(stepH.isValid()) { + std::map> layers; + std::map wpos; + PKey k = pkey(sp); + for(auto const& st : *stepH) { + if(st.simParticle().isNull() || pkey(st.simParticle()) != k || st.visibleEDep() <= 0) continue; + auto const& bid = crs->getBar(st.barIndex()).id(); + int s = bid.getShieldNumber(); + auto& xm = xmap[std::make_pair(il, s)]; + xm.edep_ += st.visibleEDep(); + layers[s].insert(bid.getLayerNumber()); + wpos[s] += st.visibleEDep() * 0.5 * (toDet(st.startPosition()) + toDet(st.endPosition())); + } + for(auto const& [s, ls] : layers) { + auto& xm = xmap[std::make_pair(il, s)]; + xm.nLayers_ = static_cast(ls.size()); + auto w = wpos[s] / xm.edep_; + xm.depPos_ = XYZVectorF(w.X(), w.Y(), w.Z()); + } + } + } + for(auto& [key, xm] : xmap) { + xm.sector_ = static_cast(key.second); + xm.generation_ = lineage[key.first].second; + xm.sim_ = lineage[key.first].first; + if(key.second >= 0 && static_cast(key.second) < sectors_.size()) xm.sid_ = sectors_[key.second].sid; + mc.xings_.push_back(xm); + } + + // the cluster with the most energy from each crossing's particle in that sector + if(ccmcH.isValid()) { + for(size_t ix = 0; ix < mc.xings_.size(); ++ix) { + auto& xm = mc.xings_[ix]; + PKey k = pkey(xm.sim_); + double best = 0; + for(auto const& [ckey, cmc] : ccmc) { + auto cs = clusterShield.find(ckey); + if(cs == clusterShield.end() || cs->second != xm.sector_ || !cmc->HasMCInfo()) continue; + double e = 0; + for(auto const& pi : cmc->GetPulses()) if(pi._simParticle.isNonnull() && pkey(pi._simParticle) == k) e += pi._energyDeposited; + if(e > best) { best = e; xm.trueCluster_ = static_cast(ckey); } + } + for(size_t ic = 0; ic < m.cands_.size() && xm.trueCluster_ >= 0; ++ic) + if(static_cast(m.cands_[ic].cluster_.key()) == xm.trueCluster_) { xm.trueCand_ = static_cast(ic); break; } + } + } + + // reco crossings <-> true crossings by sector; prefer the track's own particle, then the nearest ancestor + for(size_t ir = 0; ir < m.xings_.size(); ++ir) { + int best = -1; + for(size_t ix = 0; ix < mc.xings_.size(); ++ix) { + auto const& xm = mc.xings_[ix]; + if(xm.sector_ != m.xings_[ir].sector_ || !(xm.geom_ || xm.edep_ > 0)) continue; + if(best < 0 || xm.generation_ < mc.xings_[best].generation_) best = static_cast(ix); + } + mc.recoXingTruth_[ir] = static_cast(best); + if(best >= 0 && mc.xings_[best].recoXing_ < 0) mc.xings_[best].recoXing_ = static_cast(ir); + if(best < 0) { // the track's particle crossed a coplanar neighbour instead + int rs = m.xings_[ir].sector_; + for(size_t ix = 0; ix < mc.xings_.size(); ++ix) { + auto const& xm = mc.xings_[ix]; + if(xm.generation_ != 0 || !(xm.geom_ || xm.edep_ > 0) || xm.sector_ == rs) continue; + if(rs >= 0 && xm.sector_ >= 0 && planeGroup_[rs] >= 0 && planeGroup_[rs] == planeGroup_[xm.sector_]) { mc.recoXingNeighbor_[ir] = static_cast(ix); break; } + } + } + } + + // candidate clusters: relation of their deposits to the track's particle + if(ccmcH.isValid() && !m.cands_.empty() && m.cands_.front().cluster_.id() != clusterPid && !ccmc.empty()) + mf::LogWarning("TrkCrvMatchMCMaker") << "cluster MC associations are over a different cluster collection than the matcher used"; + for(size_t ic = 0; ic < m.cands_.size(); ++ic) { + auto& cm = mc.cands_[ic]; + auto it = ccmc.find(m.cands_[ic].cluster_.key()); + if(it == ccmc.end() || m.cands_[ic].cluster_.id() != clusterPid) continue; + if(!it->second->HasMCInfo()) { cm.rel_ = TrkCrvTruth::Background; continue; } + uint8_t rel = TrkCrvTruth::Background; + for(auto const& pi : it->second->GetPulses()) { + if(pi._energyDeposited <= 0) continue; + uint8_t r = relation(pi._simParticle, self, anc, trkRoot); + cm.edepTotal_ += pi._energyDeposited; + if(r == TrkCrvTruth::SameParticle) cm.edepSame_ += pi._energyDeposited; + if(r == TrkCrvTruth::SameFamily) cm.edepFamily_ += pi._energyDeposited; + rel = std::min(rel, r); + } + cm.rel_ = rel; + } + + // bookkeeping for the end-of-job summary + bool crosses = false; + for(size_t ir = 0; ir < m.xings_.size(); ++ir) { + auto& c = counts_[m.xings_[ir].sector_]; + ++c.recoX; + int t = mc.recoXingTruth_[ir]; + if(t < 0) { ++c.recoFake; if(m.xings_[ir].edgeSig_ < edgeSigCut_) ++c.recoFakeEdge; if(mc.recoXingNeighbor_[ir] >= 0) ++c.recoFakeNbr; } + else if(mc.xings_[t].generation_ > 0) ++c.recoTrueAnc; + else if(mc.xings_[t].edep_ > 0) ++c.recoTrueDep; + else ++c.recoTrueGap; + } + for(auto const& xm : mc.xings_) { + if(xm.generation_ != 0) continue; + auto& c = counts_[xm.sector_]; + if(!xm.geom_) { if(xm.edep_ > 0) ++c.trueNoGeom; continue; } + crosses = true; + ++c.trueX; + if(xm.recoXing_ >= 0) ++c.trueFound; + else { + ++c.trueMissed; + for(auto const& rx : m.xings_) + if(rx.sector_ >= 0 && xm.sector_ >= 0 && planeGroup_[rx.sector_] >= 0 && planeGroup_[rx.sector_] == planeGroup_[xm.sector_]) { ++c.trueMissedNbr; break; } + } + } + for(auto const& xm : mc.xings_) { // is the particle's own cluster in each sector associated geometrically? + if(xm.generation_ != 0 || xm.trueCluster_ < 0) continue; + auto& c = counts_[xm.sector_]; + ++c.trueClu; + bool geom = false, excl = false; + if(xm.trueCand_ >= 0) { + auto const& cand = m.cands_[xm.trueCand_]; + if(cand.hasFlag(TrkCrvCandidate::geomCand)) { + geom = true; + excl = cand.hasFlag(TrkCrvCandidate::exclusive); + if(cand.hasFlag(TrkCrvCandidate::bestInSector)) ++c.trueCluBest; + double cn = cand.ndof_ > 0 ? cand.chi2_ / cand.ndof_ : 0.0; + c.chi2nd += cn; + if(!cand.hasFlag(TrkCrvCandidate::sameSector)) { ++c.trueCluProj; c.chi2ndProj += cn; } + } + } + if(geom) ++c.trueCluGeom; + if(excl) ++c.trueCluExcl; + } + if(crosses) ++nTracksCrossing_; + if(m.bestGeom_ >= 0) ++bestGeomRel_[mc.cands_[m.bestGeom_].rel_]; + if(m.bestTime_ >= 0) ++bestTimeRel_[mc.cands_[m.bestTime_].rel_]; + + if(diag_ > 0) { + mf::LogInfo log("TrkCrvMatchMCMaker"); + log << "event " << event.id() << " track " << m.track_.key() << " sim " << mc.trackSim_->pdgId() << " stage/key " + << trk.first << "/" << trk.second << " reco xings " << m.xings_.size() << " true xings " << mc.xings_.size(); + for(size_t ir = 0; ir < m.xings_.size(); ++ir) + log << "\n reco " << m.xings_[ir].sid_ << " inb " << m.xings_[ir].inBounds_ << " edgeU " << m.xings_[ir].dEdgeU_ + << " edgeV " << m.xings_[ir].dEdgeV_ << " edgeSig " << m.xings_[ir].edgeSig_ << " truth " << mc.recoXingTruth_[ir] << " nbr " << mc.recoXingNeighbor_[ir]; + for(auto const& xm : mc.xings_) + log << "\n true shield " << xm.sector_ << " gen " << int(xm.generation_) << " geom " << xm.geom_ << " edep " << xm.edep_ + << " layers " << int(xm.nLayers_) << " edgeU " << xm.dEdgeU_ << " edgeV " << xm.dEdgeV_ + << " recoXing " << xm.recoXing_ << " cluster " << xm.trueCluster_; + // pulls of own-cluster geometric candidates: matcher residuals, and the raw-error track against the true crossing + for(auto const& xm : mc.xings_) { + if(xm.generation_ != 0 || !xm.geom_ || xm.trueCand_ < 0) continue; + auto const& c = m.cands_[xm.trueCand_]; + if(!c.hasFlag(TrkCrvCandidate::geomCand) || c.xing_ < 0) continue; + if(xm.sector_ < 0 || static_cast(xm.sector_) >= sectors_.size() || !sectors_[xm.sector_].valid) continue; + auto const& rect = *sectors_[xm.sector_].rect; + auto const& rx = m.xings_[c.xing_]; + auto const& ki = m.track_->intersections()[rx.inter_]; + KinKal::VEC3 px(rx.pos_.X(), rx.pos_.Y(), rx.pos_.Z()); + KinKal::VEC3 mom = ki.momentum3(), d = mom.Unit(); + KinKal::VEC3 const& w = rect.normal(); + double dw = d.Dot(w); + if(std::fabs(dw) < 1e-3) continue; + double s = (rect.center() - px).Dot(w) / dw; + KinKal::VEC3 r = KinKal::VEC3(xm.pos_.X(), xm.pos_.Y(), xm.pos_.Z()) - (px + s * d); + auto const& cov = ki.pstate_.stateCovariance(); + log << "\n pull shield " << xm.sector_ << " same " << c.hasFlag(TrkCrvCandidate::sameSector) + << " single " << c.hasFlag(TrkCrvCandidate::singleEnded) << " s " << s << " dw " << dw + << " du " << c.du_ << " dv " << c.dv_ << " sigU " << c.sigU_ << " sigV " << c.sigV_ + << " tdu " << r.Dot(rect.uDirection()) << " tdv " << r.Dot(rect.vDirection()) + << " teu " << trkCrvPlaneError(cov, mom, rect.uDirection(), w, s) + << " tev " << trkCrvPlaneError(cov, mom, rect.vDirection(), w, s) + << " teu0 " << trkCrvPlaneError(cov, mom, rect.uDirection(), w, 0.0) + << " tev0 " << trkCrvPlaneError(cov, mom, rect.vDirection(), w, 0.0); + } + } + out->push_back(std::move(mc)); + } + event.put(std::move(out)); + } + + void TrkCrvMatchMCMaker::endJob() { + if(!printSummary_) return; + static const char* relName[6] = {"SameParticle","SameFamily","SamePrimary","Unrelated","Background","NoMC"}; + mf::LogInfo log("TrkCrvMatchMCMaker"); + log << "TrkCrvMatchMC summary (" << moduleDescription().moduleLabel() << "): tracks " << nTracks_ << ", with MC " << nTracksMC_ + << ", whose particle crosses a CRV sector " << nTracksCrossing_ << "\n" + << std::setw(10) << "sector" << std::setw(8) << "reco" << std::setw(9) << "true:dep" << std::setw(9) << "true:gap" + << std::setw(9) << "true:anc" << std::setw(7) << "fake" << std::setw(10) << "fake:edge" << std::setw(9) << "fake:nbr" << " |" << std::setw(7) << "truth" << std::setw(7) << "found" + << std::setw(8) << "missed" << std::setw(9) << "miss:nbr" << std::setw(12) << "dep-no-geom"; + for(auto const& [s, c] : counts_) { + std::string n = (s >= 0 && static_cast(s) < shieldNames_.size()) ? shieldNames_[s] : std::to_string(s); + log << "\n" << std::setw(10) << n << std::setw(8) << c.recoX << std::setw(9) << c.recoTrueDep << std::setw(9) << c.recoTrueGap + << std::setw(9) << c.recoTrueAnc << std::setw(7) << c.recoFake << std::setw(10) << c.recoFakeEdge << std::setw(9) << c.recoFakeNbr << " |" << std::setw(7) << c.trueX << std::setw(7) << c.trueFound + << std::setw(8) << c.trueMissed << std::setw(9) << c.trueMissedNbr << std::setw(12) << c.trueNoGeom; + } + for(auto const& [s, c] : counts_) { + std::string n = (s >= 0 && static_cast(s) < shieldNames_.size()) ? shieldNames_[s] : std::to_string(s); + log << "\nclusters " << n << " true " << c.trueClu << " geom " << c.trueCluGeom << " exclusive " << c.trueCluExcl + << " best " << c.trueCluBest << " chi2nd " << c.chi2nd << " proj " << c.trueCluProj << " chi2ndProj " << c.chi2ndProj; + } + log << "\nbest geometric candidate:"; + for(int i = 0; i < 6; ++i) log << " " << relName[i] << " " << bestGeomRel_[i]; + log << "\nbest time candidate: "; + for(int i = 0; i < 6; ++i) log << " " << relName[i] << " " << bestTimeRel_[i]; + } +} + +DEFINE_ART_MODULE(mu2e::TrkCrvMatchMCMaker) diff --git a/MCDataProducts/inc/TrkCrvMatchMC.hh b/MCDataProducts/inc/TrkCrvMatchMC.hh new file mode 100644 index 0000000000..9c6ea486f0 --- /dev/null +++ b/MCDataProducts/inc/TrkCrvMatchMC.hh @@ -0,0 +1,63 @@ +// +// MC truth for a TrkCrvMatch, by SimParticle identity: the true CRV sector crossings of the track's particle and its +// ancestors, the truth of each reco crossing, and the relation of each candidate cluster to the track's particle. +// One TrkCrvMatchMC per TrkCrvMatch, in the same order; candidates and reco crossings are parallel to the reco record. +// +#ifndef MCDataProducts_TrkCrvMatchMC_hh +#define MCDataProducts_TrkCrvMatchMC_hh +#include "Offline/DataProducts/inc/GenVector.hh" +#include "Offline/DataProducts/inc/SurfaceId.hh" +#include "Offline/MCDataProducts/inc/SimParticle.hh" +#include "Offline/RecoDataProducts/inc/TrkCrvMatch.hh" +#include "canvas/Persistency/Common/Ptr.h" +#include +#include + +namespace mu2e { + + struct TrkCrvTruth { + // relation of a cluster's energy deposits to the track's particle, best first + enum Relation : uint8_t { SameParticle = 0, SameFamily, SamePrimary, Unrelated, Background, NoMC }; + }; + + // one true crossing of a CRV sector by the track's particle (generation 0) or one of its ancestors + struct TrkCrvXingMC { + SurfaceId sid_; // sector surface, as the reco crossings + int16_t sector_ = -1; // CRSScintillatorShield index + uint8_t generation_ = 0; // 0 = the track's particle, 1 = its parent, ... + art::Ptr sim_; + bool geom_ = false; // the particle's trajectory crosses the sector mid-plane rectangle (gap-inclusive) + XYZVectorF pos_; // trajectory crossing of the mid-plane, detector frame [mm] (geom_ only) + XYZVectorF dir_; // unit direction of the trajectory chord at the crossing (geom_ only) + float time_ = 0; // time of the mid-plane crossing [ns] (geom_ only) + float mom_ = 0; // momentum magnitude at the mid-plane crossing [MeV/c] (geom_ only) + float dEdgeU_ = 0; // distance of that crossing inside the sector edge along the bars [mm] (geom_ only) + float dEdgeV_ = 0; // distance of that crossing inside the sector edge across the bars [mm] (geom_ only) + float edep_ = 0; // visible energy the particle deposited in the sector's bars [MeV] + uint8_t nLayers_ = 0; // layers of the sector with a deposit from the particle + XYZVectorF depPos_; // energy-weighted position of those deposits, detector frame [mm] + int16_t trueCluster_ = -1; // cluster (index in the matched collection) with the most energy from the particle here + int16_t trueCand_ = -1; // index into TrkCrvMatch::cands_ of trueCluster_, -1 if it is not a candidate + int16_t recoXing_ = -1; // index of the reco crossing of the same sector, -1 = not extrapolated there + }; + + struct TrkCrvCandidateMC { + uint8_t rel_ = TrkCrvTruth::NoMC; // a TrkCrvTruth::Relation + float edepSame_ = 0; // cluster energy from the track's particle and its descendants [MeV] + float edepFamily_ = 0; // cluster energy from the track particle's ancestors and their other descendants [MeV] + float edepTotal_ = 0; // all cluster energy with MC information [MeV] + }; + + struct TrkCrvMatchMC { + art::Ptr match_; // the reco record this truth belongs to + art::Ptr trackSim_; // the KalSeedMC primary contributor + std::vector xings_; // true crossings + std::vector recoXingTruth_; // per reco crossing: index into xings_ of the same sector, -1 = no true crossing + std::vector recoXingNeighbor_; // per reco crossing without one: true crossing of a coplanar sector by the track's particle, -1 = none + std::vector cands_; // parallel to TrkCrvMatch::cands_ + auto const& xings() const { return xings_; } + auto const& candidates() const { return cands_; } + }; + using TrkCrvMatchMCCollection = std::vector; +} +#endif diff --git a/MCDataProducts/src/classes.h b/MCDataProducts/src/classes.h index 599c746f68..8cdc7fb110 100644 --- a/MCDataProducts/src/classes.h +++ b/MCDataProducts/src/classes.h @@ -78,6 +78,7 @@ #include "Offline/MCDataProducts/inc/CrvCoincidenceClusterMC.hh" #include "Offline/DataProducts/inc/CRSScintillatorBarIndex.hh" #include "Offline/MCDataProducts/inc/CrvCoincidenceClusterMCAssns.hh" +#include "Offline/MCDataProducts/inc/TrkCrvMatchMC.hh" // ExtMon #include "Offline/MCDataProducts/inc/ExtMonFNALSimHit.hh" diff --git a/MCDataProducts/src/classes_def.xml b/MCDataProducts/src/classes_def.xml index e69a90d402..a5af5ff520 100644 --- a/MCDataProducts/src/classes_def.xml +++ b/MCDataProducts/src/classes_def.xml @@ -308,6 +308,15 @@ include="Math/Vector3D.h, Math/Vector4D.h, CLHEP/Vector/LorentzVector.h, CLHEP/V + + + + + + + + + +#include +#include + +namespace mu2e { + + // clusters a track fit used as constraints; the matcher flags those candidates usedInFit + using TrkCrvFitClusterAssns = art::Assns; + + // one CRV layer on the track's straight line through a crossed sector, with the best pulse near the predicted bar + struct TrkCrvLayerProbe { + int16_t bar_ = -1; // predicted CRSScintillatorBarIndex in this layer, -1 if the line misses the layer + int8_t dBar_ = INT8_MAX; // bar offset of the selected pulse from the predicted bar, INT8_MAX if none in the windows + float uPred_ = 0; // predicted position along the bar from its centre, along the Mu2e length axis [mm] + float tPred_ = 0; // track time at the layer [ns] + float pe_ = 0; // PEs of the in-window pulses of the selected bar (both ends) + float dt_ = 0; // pulse time - predicted pulse time (track time plus fibre propagation) [ns] + bool inCluster_ = false; // an in-window pulse of the selected bar belongs to a coincidence cluster + float uTdiv_ = NAN; // position along the bar from the two-end time difference [mm], NaN if one-ended + }; + + // one CRV sector crossing of the track's extrapolation (a CRV KalIntersection) + struct TrkCrvXing { + SurfaceId sid_; // CRV sector surface (CRV_EX ... CRV_M8) + int16_t inter_ = -1; // index into KalSeed::intersections() + int16_t sector_ = -1; // CRSScintillatorShield index + XYZVectorF pos_; // crossing position on the sector mid-plane, detector frame [mm] + XYZVectorF dir_; // unit direction of the track at the crossing + float time_ = 0; // crossing time [ns] + float sigU_ = 0; // track position error along the bars, in the sector plane, error model applied [mm] + float sigV_ = 0; // track position error across the bars, in the sector plane, error model applied [mm] + float sigT_ = 0; // track time error [ns] + float mom_ = 0; // track momentum magnitude at the crossing [MeV/c] + float momErr_ = 0; // its error [MeV/c] + bool inBounds_ = false; // crossing inside the sector rectangle + float dEdgeU_ = 0; // distance inside the sector edge along the bars [mm], negative outside + float dEdgeV_ = 0; // distance inside the sector edge across the bars [mm], negative outside + float edgeSig_ = 0; // min(dEdgeU_/sigU_, dEdgeV_/sigV_): edge distance in units of the track error + int16_t best_ = -1; // index into TrkCrvMatch::cands_ of the best geometric candidate in this crossing's sector, -1 if none + std::vector layers_; // one per layer of the sector, in layer order; empty unless the layer probe ran + }; + + // one CRV coincidence cluster associated with the track + struct TrkCrvCandidate { + enum Flag : uint16_t { timeCand = 1, geomCand = 2, singleEnded = 4, multiSector = 8, bestForTrack = 16, + bestForCluster = 32, exclusive = 64, outOfBounds = 128, usedInFit = 256, + sameSector = 512, bestInSector = 1024 }; + art::Ptr cluster_; + int16_t xing_ = -1; // reference crossing (nearest in path, projected to the cluster plane), -1 = time only + int16_t sector_ = -1; // dominant shield of the cluster (largest PE sum) + float dtRef_ = 0; // t_track(reference surface) - cluster avgHitTime [ns] + float dtRefToF_ = 0; // dtRef - |x_ref - x_cluster|/c (beta = 1 straight path) [ns] + float dtXing_ = 0; // cluster avgHitTime - t_track at the cluster plane [ns] + float du_ = 0; // cluster - track along the bars, at the cluster plane [mm] + float dv_ = 0; // cluster - track across the bars, at the cluster plane [mm] + float sigU_ = 0; // track error on du_, carried from the reference crossing over the step, error model applied [mm] + float sigV_ = 0; // track error on dv_, carried from the reference crossing over the step, error model applied [mm] + float chi2_ = -1; // space + time chi2 (geometric candidates only) + uint8_t ndof_ = 0; // chi2 degrees of freedom: 2 for single-ended clusters (no along-bar term), else 3 + uint8_t nShare_ = 0; // tracks of this collection holding this cluster as a candidate + uint16_t flags_ = 0; + bool hasFlag(Flag f) const { return flags_ & f; } + void setFlag(Flag f) { flags_ |= f; } + }; + + struct TrkCrvMatch { + art::Ptr track_; + SurfaceId refSurface_; // surface that defined tRef_ (unknown = KalSeed t0) + float tRef_ = 0; // reference track time used by dtRef [ns] + float tFront_ = 0, tMid_ = 0;// track time at TT_Front / TT_Mid, 0 if the KalSeed has no such intersection + bool hasFront_ = false, hasMid_ = false; + float timeOffset_ = 0; // CRV - tracker time offset applied to the cluster times [ns] + std::vector xings_; + std::vector cands_; // geometric candidates by chi2, then time-only by |dtRef - centre| + int16_t bestGeom_ = -1; // lowest-chi2 geometric candidate, -1 if none + int16_t bestTime_ = -1; // candidate closest in dtRef to the configured centre, -1 if none + auto const& xings() const { return xings_; } + auto const& candidates() const { return cands_; } + }; + using TrkCrvMatchCollection = std::vector; +} +#endif diff --git a/RecoDataProducts/src/classes.h b/RecoDataProducts/src/classes.h index 3848f38611..b01a6088ed 100644 --- a/RecoDataProducts/src/classes.h +++ b/RecoDataProducts/src/classes.h @@ -69,6 +69,7 @@ #include "Offline/RecoDataProducts/inc/CrvRecoPulse.hh" #include "Offline/RecoDataProducts/inc/CrvRecoPulseFlags.hh" #include "Offline/RecoDataProducts/inc/CrvCoincidenceCluster.hh" +#include "Offline/RecoDataProducts/inc/TrkCrvMatch.hh" #include "Offline/RecoDataProducts/inc/CrvStatus.hh" #include "Offline/DataProducts/inc/CRSScintillatorBarIndex.hh" #include "artdaq-core-mu2e/Overlays/Decoders/CRVDataDecoder.hh" diff --git a/RecoDataProducts/src/classes_def.xml b/RecoDataProducts/src/classes_def.xml index e1531c55dc..8f476656b8 100644 --- a/RecoDataProducts/src/classes_def.xml +++ b/RecoDataProducts/src/classes_def.xml @@ -342,6 +342,23 @@ + + + + + + + + + + + + + + + + + Date: Fri, 6 Nov 2026 14:32:07 -0600 Subject: [PATCH 2/4] Address PR review comments. --- CRVReco/CMakeLists.txt | 1 + CRVReco/fcl/prolog_v12.fcl | 33 +++- CRVReco/inc/TrkCrvGeom.hh | 34 ++++ CRVReco/inc/TrkCrvMatchTool.hh | 61 +++--- CRVReco/inc/TrkCrvPlaneError.hh | 47 +++-- CRVReco/src/TrkCrvGeom.cc | 48 +++++ CRVReco/src/TrkCrvMatchTool.cc | 130 ++++++------ CRVReco/src/TrkCrvMatcher_module.cc | 11 +- CRVResponse/CMakeLists.txt | 1 + CRVResponse/fcl/prolog_v12.fcl | 1 + CRVResponse/src/SConscript | 1 + CRVResponse/src/TrkCrvMatchMCMaker_module.cc | 198 +++++++++---------- MCDataProducts/inc/TrkCrvMatchMC.hh | 46 ++--- RecoDataProducts/inc/TrkCrvMatch.hh | 31 +-- 14 files changed, 390 insertions(+), 253 deletions(-) create mode 100644 CRVReco/inc/TrkCrvGeom.hh create mode 100644 CRVReco/src/TrkCrvGeom.cc diff --git a/CRVReco/CMakeLists.txt b/CRVReco/CMakeLists.txt index c99542abbf..a662f812d8 100644 --- a/CRVReco/CMakeLists.txt +++ b/CRVReco/CMakeLists.txt @@ -2,6 +2,7 @@ cet_make_library( SOURCE src/CrvHelper.cc src/MakeCrvRecoPulses.cc + src/TrkCrvGeom.cc src/TrkCrvMatchTool.cc LIBRARIES PUBLIC diff --git a/CRVReco/fcl/prolog_v12.fcl b/CRVReco/fcl/prolog_v12.fcl index 6fbfac5ffa..8a334786fe 100644 --- a/CRVReco/fcl/prolog_v12.fcl +++ b/CRVReco/fcl/prolog_v12.fcl @@ -389,12 +389,43 @@ BEGIN_PROLOG addOppositeSidePulses : true //add pulses without a coincidence at their own side to the cluster containing the other end of their counter } - # track-CRV association, one instance per KalSeed collection (set KalSeedCollection); see TrkCrvMatchTool.hh for the settings + # track-CRV association, one instance per KalSeed collection (set KalSeedCollection); see TrkCrvMatchTool.hh. + # Resolutions and the track error model are from an MC truth study of 1.07M KKLine tracks (50 MDC2025bb cosmic + # files, extracted v06 geometry); the windows are loose storage windows, not selections. TrkCrvMatcher : { module_type : TrkCrvMatcher CrvCoincidenceClusterCollection : "SelectReco:CrvCoincidenceClusterFinder" CrvRecoPulseCollection : "CrvRecoPulses" + ProbeAllPulses : true # CrvRecoPulses holds every reco pulse (SelectReco only the clustered ones) + ReferenceSurfaces : [ "TT_Front", "TT_Back", "TT_Outer" ] + EarliestReference : true # reference time = tracker entry + DtRefWindow : [ -350, 350 ] # ns + # DtRefCenter centres the best-time ranking only (the window is not shifted). It depends on the fit type and the + # geometry: this default is the median dtRef of each track's own cluster for KKLine on extracted-geometry MC + # (MDC2025bb cosmics); set it per instance for other fits (Production JobConfig/reco/prolog.fcl). + DtRefCenter : 13 # ns + DtXingWindow : [ -100, 100 ] # ns + MaxDv : 500 # mm + MaxDu : 3000 # mm + DoGeometric : true + # CRV resolution per cluster sector type (type 1 first). Sector type numbering depends on the geometry: these are + # the extracted geometry's types 1-4 (EX, T1, T2, muon taggers; crv_counters_extracted_v04.txt); other geometries + # need their own lists. SigmaV: robust spread of (cluster - true crossing) across the bars; SigmaU: along the bars, + # two-ended clusters (T1 and the taggers are single-ended). + SigmaV : [ 7, 13, 7, 17 ] # mm + SigmaU : [ 300 ] # mm + SigmaT : [ 5 ] # ns provisional (MC dtXing robust width 2.0-2.4 ns, two-ended) + SigmaTSingleEnded : 15 # ns provisional (MC dtXing robust width about 4 ns) + # track position error model: k^2 C + a^2 I, from pulls of the track against the true CRV crossing + TrackErrorScale : 1.5 + TrackPosErrQuad : 24 # mm + MinTrackTimeErr : 1 # ns + LayerProbe : true + ProbeBarWindow : 1 # bars on each side of the predicted bar + ProbeDtWindow : [ -50, 50 ] # ns + FiberSignalSpeed : @local::CrvCoincidenceClusterFinder.fiberSignalSpeed + ProbePulseDelay : @local::CrvCoincidenceClusterFinder.timeOffset } diff --git a/CRVReco/inc/TrkCrvGeom.hh b/CRVReco/inc/TrkCrvGeom.hh new file mode 100644 index 0000000000..5dbd24ba95 --- /dev/null +++ b/CRVReco/inc/TrkCrvGeom.hh @@ -0,0 +1,34 @@ +// +// CRV geometry used by the track-CRV association and its truth: the sector planes (KinKalGeom CRV rectangles, per +// CRSScintillatorShield index) and the dominant shield of a coincidence cluster. +// Sector frame: u along the bars (uDirection), v across the bars (vDirection), w the sector normal, all in the +// detector frame; TrkCrvMatch residuals and covariances are expressed in (u, v). +// +#ifndef CRVReco_TrkCrvGeom_hh +#define CRVReco_TrkCrvGeom_hh +#include "Offline/DataProducts/inc/SurfaceId.hh" +#include "KinKal/General/Vectors.hh" +#include "KinKal/Geometry/Rectangle.hh" +#include +#include +#include + +namespace mu2e { + class CosmicRayShield; + class CrvCoincidenceCluster; + + struct TrkCrvSector { + bool valid = false; // the shield has a KinKalGeom CRV rectangle + std::string name; // CRSScintillatorShield name + SurfaceId sid; // its SurfaceId (unknown if the name has none) + std::shared_ptr rect; // mid-plane rectangle, detector frame + KinKal::VEC3 center, u, v, w; // rectangle centre and axes + double uHalf = 0, vHalf = 0; // half lengths along u and v [mm] + }; + + // one entry per CRSScintillatorShield, in shield order (the sector_ index of TrkCrvMatch); call once per run + std::vector trkCrvSectors(); + // the shield with the largest PE sum among the cluster's pulses, -1 if none; multiSector set if pulses span shields + int trkCrvDominantShield(CrvCoincidenceCluster const& cluster, CosmicRayShield const& crs, bool* multiSector = nullptr); +} +#endif diff --git a/CRVReco/inc/TrkCrvMatchTool.hh b/CRVReco/inc/TrkCrvMatchTool.hh index 7c3b4ab06d..e4cc39c5f4 100644 --- a/CRVReco/inc/TrkCrvMatchTool.hh +++ b/CRVReco/inc/TrkCrvMatchTool.hh @@ -8,6 +8,7 @@ #include "Offline/RecoDataProducts/inc/CrvRecoPulse.hh" #include "Offline/RecoDataProducts/inc/KalSeed.hh" #include "Offline/RecoDataProducts/inc/TrkCrvMatch.hh" +#include "Offline/CRVReco/inc/TrkCrvGeom.hh" #include "Offline/DataProducts/inc/SurfaceId.hh" #include "KinKal/General/Vectors.hh" #include "canvas/Persistency/Common/Ptr.h" @@ -27,49 +28,48 @@ namespace mu2e { class TrkCrvMatchTool { public: + // physics settings have no C++ default: CRVReco/fcl/prolog_v12.fcl (TrkCrvMatcher) sets them with their sources struct Config { using Name = fhicl::Name; using Comment = fhicl::Comment; - fhicl::Sequence refSurfaces{Name("ReferenceSurfaces"), Comment("track reference-time surfaces in order of preference; KalSeed t0 if none present"), std::vector{"TT_Front","TT_Mid"}}; - fhicl::Sequence dtRefWindow{Name("DtRefWindow"), Comment("storage window on t_track(ref) - t_cluster [ns]"), std::vector{-350.0, 350.0}}; - fhicl::Atom dtRefCenter{Name("DtRefCenter"), Comment("dtRef value the time ranking is centred on [ns]"), 75.0}; - fhicl::Sequence dtXingWindow{Name("DtXingWindow"), Comment("storage window on t_cluster - t_track at the cluster plane [ns]"), std::vector{-100.0, 100.0}}; - fhicl::Atom maxDv{Name("MaxDv"), Comment("storage window on |across-bar residual| [mm]"), 500.0}; - fhicl::Atom maxDu{Name("MaxDu"), Comment("storage window on |along-bar residual| for two-ended clusters [mm]"), 3000.0}; - fhicl::Atom doGeometric{Name("DoGeometric"), Comment("form geometric candidates from CRV KalIntersections"), true}; - fhicl::Atom requireSameSector{Name("RequireSameSector"), Comment("project only from a crossing of the cluster's own sector"), false}; - fhicl::Sequence sigmaV{Name("SigmaV"), Comment("CRV across-bar resolution [mm], per cluster sector type 1-4 (EX, T1, T2, muon taggers; last entry for higher types); MC fit on 50 MDC2025bb files"), std::vector{7.0, 13.0, 7.0, 17.0}}; - fhicl::Sequence sigmaU{Name("SigmaU"), Comment("CRV along-bar resolution of two-ended clusters [mm], per sector type"), std::vector{300.0}}; - fhicl::Sequence sigmaT{Name("SigmaT"), Comment("CRV time resolution of two-ended clusters [ns], per sector type"), std::vector{5.0}}; - fhicl::Atom sigmaTSingleEnded{Name("SigmaTSingleEnded"), Comment("CRV time resolution of single-ended clusters [ns]"), 15.0}; - fhicl::Atom trackErrorScale{Name("TrackErrorScale"), Comment("scale on the propagated track position error; sigma = sqrt((scale*err)^2 + TrackPosErrQuad^2)"), 1.5}; - fhicl::Atom trackPosErrQuad{Name("TrackPosErrQuad"), Comment("added in quadrature to the scaled track position error [mm]"), 25.0}; - fhicl::Atom minTrackTimeErr{Name("MinTrackTimeErr"), Comment("floor on the (unscaled) track time error [ns]"), 1.0}; + fhicl::Sequence refSurfaces{Name("ReferenceSurfaces"), Comment("surfaces whose KalSeed intersection gives the track reference time; KalSeed t0 if none present")}; + fhicl::Atom earliestReference{Name("EarliestReference"), Comment("true: the earliest intersection on any of ReferenceSurfaces (the tracker entry); false: the first surface in list order present, nearest in time to t0")}; + fhicl::Sequence dtRefWindow{Name("DtRefWindow"), Comment("storage window on t_track(ref) - t_cluster [ns]")}; + fhicl::Atom dtRefCenter{Name("DtRefCenter"), Comment("dtRef value the time ranking is centred on [ns]")}; + fhicl::Sequence dtXingWindow{Name("DtXingWindow"), Comment("storage window on t_cluster - t_track at the cluster plane [ns]")}; + fhicl::Atom maxDv{Name("MaxDv"), Comment("storage window on |across-bar residual| [mm]")}; + fhicl::Atom maxDu{Name("MaxDu"), Comment("storage window on |along-bar residual| for two-ended clusters [mm]")}; + fhicl::Atom doGeometric{Name("DoGeometric"), Comment("form geometric candidates from CRV KalIntersections")}; + fhicl::Atom requireSameSector{Name("RequireSameSector"), Comment("project only from a crossing of the cluster's own sector (A/B tests)"), false}; + fhicl::Sequence sigmaV{Name("SigmaV"), Comment("CRV across-bar resolution [mm], indexed by the cluster's sector type (1 first; the last entry serves higher types); sector type numbering depends on the geometry")}; + fhicl::Sequence sigmaU{Name("SigmaU"), Comment("CRV along-bar resolution of two-ended clusters [mm], by sector type")}; + fhicl::Sequence sigmaT{Name("SigmaT"), Comment("CRV time resolution of two-ended clusters [ns], by sector type")}; + fhicl::Atom sigmaTSingleEnded{Name("SigmaTSingleEnded"), Comment("CRV time resolution of single-ended clusters [ns]")}; + fhicl::Atom trackErrorScale{Name("TrackErrorScale"), Comment("scale k on the propagated track position covariance: k^2 C + TrackPosErrQuad^2 I")}; + fhicl::Atom trackPosErrQuad{Name("TrackPosErrQuad"), Comment("added in quadrature to the scaled track position errors [mm]")}; + fhicl::Atom minTrackTimeErr{Name("MinTrackTimeErr"), Comment("floor on the (unscaled) track time error [ns]")}; fhicl::Atom timeOffset{Name("TimeOffset"), Comment("added to cluster and pulse times [ns]; test knob, data offsets belong in conditions"), 0.0}; fhicl::Atom keepAll{Name("KeepAllClusters"), Comment("ignore every storage window (commissioning)"), false}; - fhicl::Atom layerProbe{Name("LayerProbe"), Comment("probe each layer of every crossed sector for pulses near the predicted bar; needs the reco pulses"), true}; - fhicl::Atom probeBarWindow{Name("ProbeBarWindow"), Comment("layer probe: bars searched on each side of the predicted bar"), 1}; - fhicl::Sequence probeDtWindow{Name("ProbeDtWindow"), Comment("layer probe: window on pulse time - predicted pulse time [ns]"), std::vector{-50.0, 50.0}}; - fhicl::Atom fiberSignalSpeed{Name("FiberSignalSpeed"), Comment("layer probe: signal speed in the fibres [mm/ns], as in CrvCoincidenceFinder"), 140.0}; - fhicl::Atom pulseDelay{Name("ProbePulseDelay"), Comment("layer probe: electronics and scintillation delay subtracted from pulse times [ns], as the CrvCoincidenceFinder timeOffset"), 34.5}; + fhicl::Atom layerProbe{Name("LayerProbe"), Comment("probe each layer of every crossed sector for pulses near the predicted bar; needs the reco pulses")}; + fhicl::Atom probeAllPulses{Name("ProbeAllPulses"), Comment("the pulse collection holds every reco pulse (true) or only the clustered ones, e.g. SelectReco (false)")}; + fhicl::Atom probeBarWindow{Name("ProbeBarWindow"), Comment("layer probe: bars searched on each side of the predicted bar")}; + fhicl::Sequence probeDtWindow{Name("ProbeDtWindow"), Comment("layer probe: window on pulse time - predicted pulse time [ns]")}; + fhicl::Atom fiberSignalSpeed{Name("FiberSignalSpeed"), Comment("layer probe: signal speed in the fibres [mm/ns]")}; + fhicl::Atom pulseDelay{Name("ProbePulseDelay"), Comment("layer probe: electronics and scintillation delay subtracted from pulse times [ns]")}; }; explicit TrkCrvMatchTool(Config const& conf); void beginRun(); // caches the CRV geometry - // per-event inputs; pulses may be null (no layer probe) + // per-event inputs; pulses may be null (the layer probe then records predicted bars only) void setEvent(std::vector> const& clusters, CrvRecoPulseCollection const* pulses); // one track; usedInFit lists the clusters its fit used as constraints TrkCrvMatch match(art::Ptr const& seed, std::vector> const& usedInFit = {}) const; // cross-track pass over one collection: nShare, bestForCluster, exclusive void resolve(TrkCrvMatchCollection& matches) const; bool probeActive() const { return layerProbe_; } + std::vector const& sectors() const { return sectors_; } // per shield index, after beginRun private: - struct SectorGeom { // CRV sector mid-plane, detector frame - bool valid = false; - KinKal::VEC3 center, u, v, w; - double uHalf = 0, vHalf = 0; - }; struct ClusterInfo { // per-event cluster quantities KinKal::VEC3 pos; // detector frame double time = 0; @@ -79,31 +79,30 @@ namespace mu2e { bool singleEnded = false; }; double resolution(std::vector const& tab, int sectorType) const; - double trkPosErr(double err) const { return std::sqrt(trkErrScale_ * trkErrScale_ * err * err + posErrQuad_ * posErrQuad_); } + TrkCrvPlaneCov errorModel(ROOT::Math::SMatrix> const& cov) const; // k^2 C + a^2 I void probe(TrkCrvXing& x, double speed) const; static bool sameCluster(art::Ptr const& a, art::Ptr const& b); std::vector refSurfaces_; + bool earliestRef_; double dtRefLo_, dtRefHi_, dtRefCenter_, dtXingLo_, dtXingHi_, maxDv_, maxDu_; bool doGeometric_, requireSameSector_; std::vector sigmaV_, sigmaU_, sigmaT_; double sigmaTSingle_, trkErrScale_, posErrQuad_, minTimeErr_, timeOffset_; - bool keepAll_, layerProbe_; + bool keepAll_, layerProbe_, probeAllPulses_; int probeBarWindow_; double probeDtLo_, probeDtHi_, fiberSpeed_, pulseDelay_; CosmicRayShield const* crs_ = nullptr; DetectorSystem const* det_ = nullptr; std::map sidToShield_; - std::vector sectors_; // indexed by shield + std::vector sectors_; // indexed by shield std::vector> clusters_; std::vector cinfo_; CrvRecoPulseCollection const* pulses_ = nullptr; std::unordered_map> pulsesByBar_; // bar index -> pulses std::set> clusteredPulses_; // (bar, SiPM, time) of the pulses in clusters - - static constexpr double cLight_ = 299.792458; // mm/ns }; } #endif diff --git a/CRVReco/inc/TrkCrvPlaneError.hh b/CRVReco/inc/TrkCrvPlaneError.hh index 0f159e0c25..8b67b4f979 100644 --- a/CRVReco/inc/TrkCrvPlaneError.hh +++ b/CRVReco/inc/TrkCrvPlaneError.hh @@ -1,31 +1,44 @@ // -// Track position error on a plane reached by a straight step, shared by TrkCrvMatcher and its truth module. +// Temporary stand-in for a KinKal projection of a track state's spatial covariance onto a plane; replace with the +// KinKal implementation when it exists (both modules call only trkCrvPlaneCovariance). // #ifndef CRVReco_TrkCrvPlaneError_hh #define CRVReco_TrkCrvPlaneError_hh #include "KinKal/General/Vectors.hh" -#include +#include "Math/SMatrix.h" #include namespace mu2e { - // Track position error along the in-plane direction a, on the plane with normal w reached by a straight step of - // signed path length s from a state (position, momentum p) with 6x6 covariance C (position first). With - // d = p/|p| and P = I - d w^T/(d.w) (move along d onto the plane), the gradient of a.(position on the plane) is - // P^T a for the position block and (s/|p|)(I - d d^T) P^T a for the momentum block. s = 0 gives the error of the - // state itself, measured in the plane rather than in 3D. Returns 0 for a track parallel to the plane. - template double trkCrvPlaneError(COV const& C, KinKal::VEC3 const& p, KinKal::VEC3 const& a, - KinKal::VEC3 const& w, double s) { + using TrkCrvCov2 = ROOT::Math::SMatrix>; + + // Covariance of the track position on the plane with normal w, in the in-plane axes (a, b), after a straight step of + // signed path length s from a state (position, momentum p) with 6x6 covariance C (position first). With d = p/|p| + // and P = I - d w^T/(d.w) (move along d onto the plane), the gradient of e.(position on the plane) is P^T e for the + // position block and (s/|p|)(I - d d^T) P^T e for the momentum block. s = 0 gives the covariance of the state itself, + // measured in the plane. Returns a zero matrix for a track parallel to the plane. + template TrkCrvCov2 trkCrvPlaneCovariance(COV const& C, KinKal::VEC3 const& p, KinKal::VEC3 const& a, + KinKal::VEC3 const& b, KinKal::VEC3 const& w, double s) { + TrkCrvCov2 out; double pm = std::sqrt(p.Mag2()); - if(pm <= 0) return 0; + if(pm <= 0) return out; KinKal::VEC3 d = p / pm; double dw = d.Dot(w); - if(std::fabs(dw) < 1e-3) return 0; - KinKal::VEC3 gp = a - w * (d.Dot(a) / dw); - KinKal::VEC3 gm = (s / pm) * (gp - d * d.Dot(gp)); - double g[6] = {gp.X(), gp.Y(), gp.Z(), gm.X(), gm.Y(), gm.Z()}; - double var = 0; - for(int i = 0; i < 6; ++i) for(int j = 0; j < 6; ++j) var += g[i] * C(i, j) * g[j]; - return std::sqrt(std::max(var, 0.0)); + if(std::fabs(dw) < 1e-3) return out; + double g[2][6]; + KinKal::VEC3 const* axes[2] = {&a, &b}; + for(int k = 0; k < 2; ++k) { + KinKal::VEC3 gp = *axes[k] - w * (d.Dot(*axes[k]) / dw); + KinKal::VEC3 gm = (s / pm) * (gp - d * d.Dot(gp)); + double gk[6] = {gp.X(), gp.Y(), gp.Z(), gm.X(), gm.Y(), gm.Z()}; + for(int i = 0; i < 6; ++i) g[k][i] = gk[i]; + } + for(int k = 0; k < 2; ++k) + for(int l = k; l < 2; ++l) { + double v = 0; + for(int i = 0; i < 6; ++i) for(int j = 0; j < 6; ++j) v += g[k][i] * C(i, j) * g[l][j]; + out(k, l) = v; + } + return out; } } #endif diff --git a/CRVReco/src/TrkCrvGeom.cc b/CRVReco/src/TrkCrvGeom.cc new file mode 100644 index 0000000000..4e049f1634 --- /dev/null +++ b/CRVReco/src/TrkCrvGeom.cc @@ -0,0 +1,48 @@ +#include "Offline/CRVReco/inc/TrkCrvGeom.hh" +#include "Offline/CosmicRayShieldGeom/inc/CosmicRayShield.hh" +#include "Offline/GeometryService/inc/GeomHandle.hh" +#include "Offline/KinKalGeom/inc/KinKalGeom.hh" +#include "Offline/RecoDataProducts/inc/CrvCoincidenceCluster.hh" +#include "messagefacility/MessageLogger/MessageLogger.h" +#include + +namespace mu2e { + + std::vector trkCrvSectors() { + GeomHandle crs; + GeomHandle kkg; + auto const& shields = crs->getCRSScintillatorShields(); + std::vector sectors(shields.size()); + std::map nameToShield; + for(size_t i = 0; i < shields.size(); ++i) { + sectors[i].name = shields[i].getName(); + nameToShield[sectors[i].name] = static_cast(i); + } + for(auto const& sec : kkg->CRV()->sectors()) { + auto it = nameToShield.find(sec.sname_); + if(it == nameToShield.end()) continue; + auto& g = sectors[it->second]; + g.valid = true; + g.rect = sec.sector_; + g.center = sec.sector_->center(); + g.u = sec.sector_->uDirection(); + g.v = sec.sector_->vDirection(); + g.w = sec.sector_->normal(); + g.uHalf = sec.sector_->uHalfLength(); + g.vHalf = sec.sector_->vHalfLength(); + try { g.sid = SurfaceId(sec.sname_); } + catch(std::exception const&) { mf::LogWarning("TrkCrvGeom") << "no SurfaceId for CRV sector " << sec.sname_; } + } + return sectors; + } + + int trkCrvDominantShield(CrvCoincidenceCluster const& cluster, CosmicRayShield const& crs, bool* multiSector) { + std::map pes; + for(auto const& rp : cluster.GetCrvRecoPulses()) pes[crs.getBar(rp->GetScintillatorBarIndex()).id().getShieldNumber()] += rp->GetPEs(); + int shield = -1; + double best = -1; + for(auto const& [s, pe] : pes) if(pe > best) { best = pe; shield = s; } + if(multiSector) *multiSector = pes.size() > 1; + return shield; + } +} diff --git a/CRVReco/src/TrkCrvMatchTool.cc b/CRVReco/src/TrkCrvMatchTool.cc index a45429630f..5f54a6a75a 100644 --- a/CRVReco/src/TrkCrvMatchTool.cc +++ b/CRVReco/src/TrkCrvMatchTool.cc @@ -3,8 +3,8 @@ #include "Offline/CosmicRayShieldGeom/inc/CosmicRayShield.hh" #include "Offline/GeometryService/inc/DetectorSystem.hh" #include "Offline/GeometryService/inc/GeomHandle.hh" -#include "Offline/KinKalGeom/inc/KinKalGeom.hh" #include "cetlib_except/exception.h" +#include "CLHEP/Units/PhysicalConstants.h" #include "messagefacility/MessageLogger/MessageLogger.h" #include #include @@ -13,12 +13,12 @@ namespace mu2e { TrkCrvMatchTool::TrkCrvMatchTool(Config const& conf) : - dtRefCenter_(conf.dtRefCenter()), maxDv_(conf.maxDv()), maxDu_(conf.maxDu()), + earliestRef_(conf.earliestReference()), dtRefCenter_(conf.dtRefCenter()), maxDv_(conf.maxDv()), maxDu_(conf.maxDu()), doGeometric_(conf.doGeometric()), requireSameSector_(conf.requireSameSector()), sigmaV_(conf.sigmaV()), sigmaU_(conf.sigmaU()), sigmaT_(conf.sigmaT()), sigmaTSingle_(conf.sigmaTSingleEnded()), trkErrScale_(conf.trackErrorScale()), posErrQuad_(conf.trackPosErrQuad()), minTimeErr_(conf.minTrackTimeErr()), timeOffset_(conf.timeOffset()), keepAll_(conf.keepAll()), - layerProbe_(conf.layerProbe()), probeBarWindow_(conf.probeBarWindow()), fiberSpeed_(conf.fiberSignalSpeed()), + layerProbe_(conf.layerProbe()), probeAllPulses_(conf.probeAllPulses()), probeBarWindow_(conf.probeBarWindow()), fiberSpeed_(conf.fiberSignalSpeed()), pulseDelay_(conf.pulseDelay()) { auto w = conf.dtRefWindow(); auto x = conf.dtXingWindow(); auto p = conf.probeDtWindow(); @@ -29,6 +29,13 @@ namespace mu2e { for(auto const& s : conf.refSurfaces()) refSurfaces_.emplace_back(s); } + TrkCrvPlaneCov TrkCrvMatchTool::errorModel(TrkCrvCov2 const& cov) const { + TrkCrvPlaneCov out; + for(int i = 0; i < 2; ++i) + for(int j = i; j < 2; ++j) out(i, j) = trkErrScale_ * trkErrScale_ * cov(i, j) + (i == j ? posErrQuad_ * posErrQuad_ : 0.0); + return out; + } + double TrkCrvMatchTool::resolution(std::vector const& tab, int sectorType) const { size_t i = sectorType > 0 ? static_cast(sectorType - 1) : 0; return tab[std::min(i, tab.size() - 1)]; @@ -37,28 +44,12 @@ namespace mu2e { void TrkCrvMatchTool::beginRun() { GeomHandle crs; GeomHandle det; - GeomHandle kkg; crs_ = crs.get(); det_ = det.get(); - auto const& shields = crs_->getCRSScintillatorShields(); + sectors_ = trkCrvSectors(); sidToShield_.clear(); - sectors_.assign(shields.size(), SectorGeom()); - std::map nameToShield; - for(size_t i = 0; i < shields.size(); ++i) nameToShield[shields[i].getName()] = static_cast(i); - for(auto const& sec : kkg->CRV()->sectors()) { - auto it = nameToShield.find(sec.sname_); - if(it == nameToShield.end()) continue; - SectorGeom& g = sectors_[it->second]; - g.valid = true; - g.center = sec.sector_->center(); - g.u = sec.sector_->uDirection(); - g.v = sec.sector_->vDirection(); - g.w = sec.sector_->normal(); - g.uHalf = sec.sector_->uHalfLength(); - g.vHalf = sec.sector_->vHalfLength(); - try { sidToShield_[SurfaceId(sec.sname_)] = it->second; } - catch(std::exception const&) { mf::LogWarning("TrkCrvMatchTool") << "no SurfaceId for CRV sector " << sec.sname_; } - } + for(size_t i = 0; i < sectors_.size(); ++i) + if(sectors_[i].valid && sectors_[i].sid != SurfaceId()) sidToShield_[sectors_[i].sid] = static_cast(i); } void TrkCrvMatchTool::setEvent(std::vector> const& clusters, CrvRecoPulseCollection const* pulses) { @@ -74,14 +65,9 @@ namespace mu2e { ci.time = cc.GetAvgHitTime() + timeOffset_; ci.sectorType = cc.GetCrvSectorType(); ci.singleEnded = !cc.HitPosAndTimeCalculated(); - std::map pes; - for(auto const& rp : cc.GetCrvRecoPulses()) { - pes[crs_->getBar(rp->GetScintillatorBarIndex()).id().getShieldNumber()] += rp->GetPEs(); + ci.shield = trkCrvDominantShield(cc, *crs_, &ci.multiSector); + for(auto const& rp : cc.GetCrvRecoPulses()) clusteredPulses_.emplace(rp->GetScintillatorBarIndex().asInt(), rp->GetSiPMNumber(), rp->GetPulseTime()); - } - double best = -1; - for(auto const& [s, pe] : pes) if(pe > best) { best = pe; ci.shield = s; } - ci.multiSector = pes.size() > 1; } pulses_ = layerProbe_ ? pulses : nullptr; pulsesByBar_.clear(); @@ -177,34 +163,39 @@ namespace mu2e { m.track_ = seed; double t0 = ks.t0Val(); double t0err = std::sqrt(std::max(ks.t0Var(), 0.0)); - // reference times: the intersection on each surface nearest in time to t0 - auto nearest = [&](SurfaceId const& sid) -> int { - int best = -1; double bdt = 1e30; + // reference time: the earliest intersection on any reference surface (tracker entry), or the first surface in + // list order present, nearest in time to t0; KalSeed t0 if none + int kref = -1; + if(earliestRef_) { for(size_t k = 0; k < ks.intersections().size(); ++k) { auto const& ki = ks.intersections()[k]; - if(ki.surfaceId() != sid) continue; - double d = std::fabs(ki.time() - t0); - if(d < bdt) { bdt = d; best = static_cast(k); } + if(std::find(refSurfaces_.begin(), refSurfaces_.end(), ki.surfaceId()) == refSurfaces_.end()) continue; + if(kref < 0 || ki.time() < ks.intersections()[kref].time()) kref = static_cast(k); } - return best; - }; - int kf = nearest(SurfaceId(SurfaceIdDetail::TT_Front)); - int km = nearest(SurfaceId(SurfaceIdDetail::TT_Mid)); - if(kf >= 0) { m.hasFront_ = true; m.tFront_ = ks.intersections()[kf].time(); } - if(km >= 0) { m.hasMid_ = true; m.tMid_ = ks.intersections()[km].time(); } + } else { + for(auto const& rs : refSurfaces_) { + double bdt = 1e30; + for(size_t k = 0; k < ks.intersections().size(); ++k) { + auto const& ki = ks.intersections()[k]; + if(ki.surfaceId() != rs || std::fabs(ki.time() - t0) >= bdt) continue; + bdt = std::fabs(ki.time() - t0); + kref = static_cast(k); + } + if(kref >= 0) break; + } + } m.tRef_ = t0; - bool hasRefPos = false; + bool hasRefPos = kref >= 0; KinKal::VEC3 refPos; - for(auto const& rs : refSurfaces_) { - int k = nearest(rs); - if(k < 0) continue; - m.refSurface_ = rs; - m.tRef_ = ks.intersections()[k].time(); - refPos = ks.intersections()[k].position3(); - hasRefPos = true; - break; + if(hasRefPos) { + auto const& ki = ks.intersections()[kref]; + m.refSurface_ = ki.surfaceId(); + m.tRef_ = ki.time(); + refPos = ki.position3(); } m.timeOffset_ = timeOffset_; + if(layerProbe_ && doGeometric_) + m.probe_ = !pulses_ ? TrkCrvMatch::probeNoPulses : (probeAllPulses_ ? TrkCrvMatch::probeAllPulses : TrkCrvMatch::probeClusteredPulses); // CRV crossings double sigT = std::max(t0err, minTimeErr_); @@ -224,17 +215,14 @@ namespace mu2e { x.dir_ = XYZVectorF(d.X(), d.Y(), d.Z()); x.time_ = ki.time(); x.inBounds_ = ki.inBounds(); - auto const& cov = ki.pstate_.stateCovariance(); - auto mom = ki.momentum3(); - x.sigU_ = trkPosErr(trkCrvPlaneError(cov, mom, g.u, g.w, 0.0)); - x.sigV_ = trkPosErr(trkCrvPlaneError(cov, mom, g.v, g.w, 0.0)); + x.cov_ = errorModel(trkCrvPlaneCovariance(ki.pstate_.stateCovariance(), ki.momentum3(), g.u, g.v, g.w, 0.0)); x.sigT_ = sigT; x.mom_ = ki.mom(); x.momErr_ = ki.momerr(); KinKal::VEC3 loc = p - g.center; x.dEdgeU_ = g.uHalf - std::fabs(loc.Dot(g.u)); x.dEdgeV_ = g.vHalf - std::fabs(loc.Dot(g.v)); - x.edgeSig_ = (x.sigU_ > 0 && x.sigV_ > 0) ? std::min(x.dEdgeU_ / x.sigU_, x.dEdgeV_ / x.sigV_) : 0.f; + x.edgeSig_ = (x.sigU() > 0 && x.sigV() > 0) ? std::min(x.dEdgeU_ / x.sigU(), x.dEdgeV_ / x.sigV()) : 0.f; if(layerProbe_) probe(x, std::sqrt(ki.velocity().Mag2())); m.xings_.push_back(x); } @@ -247,7 +235,7 @@ namespace mu2e { c.cluster_ = clusters_[ic]; c.sector_ = static_cast(ci.shield); c.dtRef_ = m.tRef_ - ci.time; - c.dtRefToF_ = hasRefPos ? c.dtRef_ - std::sqrt((refPos - ci.pos).Mag2()) / cLight_ : c.dtRef_; + c.dtRefToF_ = hasRefPos ? c.dtRef_ - std::sqrt((refPos - ci.pos).Mag2()) / CLHEP::c_light : c.dtRef_; if(ci.singleEnded) c.setFlag(TrkCrvCandidate::singleEnded); if(ci.multiSector) c.setFlag(TrkCrvCandidate::multiSector); bool timeOK = keepAll_ || (c.dtRef_ >= dtRefLo_ && c.dtRef_ <= dtRefHi_); @@ -281,17 +269,19 @@ namespace mu2e { c.du_ = r.Dot(g.u); c.dv_ = r.Dot(g.v); c.dtXing_ = ci.time - tp; - // track errors on the cluster's plane: the reference crossing's covariance carried over the straight step - auto const& cov = ki.pstate_.stateCovariance(); - double tsu = trkPosErr(trkCrvPlaneError(cov, ki.momentum3(), g.u, g.w, ds)); - double tsv = trkPosErr(trkCrvPlaneError(cov, ki.momentum3(), g.v, g.w, ds)); - c.sigU_ = static_cast(tsu); - c.sigV_ = static_cast(tsv); + // track covariance on the cluster's plane: the reference crossing's covariance carried over the straight step + c.cov_ = errorModel(trkCrvPlaneCovariance(ki.pstate_.stateCovariance(), ki.momentum3(), g.u, g.v, g.w, ds)); double sv = resolution(sigmaV_, ci.sectorType), su = resolution(sigmaU_, ci.sectorType); double st = ci.singleEnded ? sigmaTSingle_ : resolution(sigmaT_, ci.sectorType); - c.chi2_ = c.dv_*c.dv_/(sv*sv + tsv*tsv) + c.dtXing_*c.dtXing_/(st*st + x.sigT_*x.sigT_); - c.ndof_ = 2; - if(!ci.singleEnded) { c.chi2_ += c.du_*c.du_/(su*su + tsu*tsu); c.ndof_ = 3; } + c.chi2_ = c.dtXing_*c.dtXing_/(st*st + x.sigT_*x.sigT_); + if(ci.singleEnded) { // no along-bar measurement: across-bar term only + c.chi2_ += c.dv_*c.dv_/(sv*sv + c.cov_(1,1)); + c.ndof_ = 2; + } else { // full (u, v) covariance plus the CRV resolution on the diagonal + double a = c.cov_(0,0) + su*su, b = c.cov_(0,1), d = c.cov_(1,1) + sv*sv, det = a*d - b*b; + c.chi2_ += det > 0 ? (d*c.du_*c.du_ - 2*b*c.du_*c.dv_ + a*c.dv_*c.dv_)/det : 0.0; + c.ndof_ = 3; + } bool geomOK = keepAll_ || (std::fabs(c.dv_) < maxDv_ && (ci.singleEnded || std::fabs(c.du_) < maxDu_) && c.dtXing_ >= dtXingLo_ && c.dtXing_ <= dtXingHi_); if(geomOK) { @@ -302,7 +292,7 @@ namespace mu2e { if(std::fabs(loc.Dot(g.u)) > g.uHalf || std::fabs(loc.Dot(g.v)) > g.vHalf) c.setFlag(TrkCrvCandidate::outOfBounds); } } - if(!c.hasFlag(TrkCrvCandidate::geomCand)) { c.chi2_ = -1; c.ndof_ = 0; c.du_ = c.dv_ = c.dtXing_ = c.sigU_ = c.sigV_ = 0; } + if(!c.hasFlag(TrkCrvCandidate::geomCand)) { c.chi2_ = -1; c.ndof_ = 0; c.du_ = c.dv_ = c.dtXing_ = 0; c.cov_ = TrkCrvPlaneCov(); } if(c.hasFlag(TrkCrvCandidate::geomCand) || timeOK) { for(auto const& u : usedInFit) if(sameCluster(u, c.cluster_)) { c.setFlag(TrkCrvCandidate::usedInFit); break; } m.cands_.push_back(c); @@ -359,12 +349,12 @@ namespace mu2e { } std::stable_sort(geomPairs.begin(), geomPairs.end(), [](auto const& a, auto const& b) { return a.first < b.first; }); std::map usedCluster; - std::map,bool> usedXing; // (track, cluster sector) + std::map,bool> usedTrackSector; // (track, cluster sector): one cluster per track per sector for(auto const& [chi2, r] : geomPairs) { auto& c = out[r.trk].cands_[r.cand]; - auto xk = std::make_pair(r.trk, static_cast(c.sector_)); - if(usedCluster[c.cluster_.key()] || usedXing[xk]) continue; - usedCluster[c.cluster_.key()] = usedXing[xk] = true; + auto ts = std::make_pair(r.trk, static_cast(c.sector_)); + if(usedCluster[c.cluster_.key()] || usedTrackSector[ts]) continue; + usedCluster[c.cluster_.key()] = usedTrackSector[ts] = true; c.setFlag(TrkCrvCandidate::exclusive); } } diff --git a/CRVReco/src/TrkCrvMatcher_module.cc b/CRVReco/src/TrkCrvMatcher_module.cc index a9f574087d..b6c3df468b 100644 --- a/CRVReco/src/TrkCrvMatcher_module.cc +++ b/CRVReco/src/TrkCrvMatcher_module.cc @@ -1,6 +1,15 @@ // // Associate reconstructed tracks (KalSeeds) with CRV coincidence clusters, one TrkCrvMatch per KalSeed, using -// TrkCrvMatchTool. Storage windows are loose on purpose: selections belong to the analysis. +// TrkCrvMatchTool: +// - time: every cluster with t_track(reference) - t_cluster inside DtRefWindow is a time candidate; the reference +// is by default the track's entry into the tracker (earliest of TT_Front, TT_Back, TT_Outer); +// - space: from the track's CRV crossing nearest to the cluster's sector plane, a straight-line projection onto that +// plane gives du, dv and dtXing, and a space+time chi2 with the full (u, v) covariance; clusters inside MaxDu, +// MaxDv and DtXingWindow are geometric candidates; +// - every candidate is kept: a track can have several, and a cluster can be a candidate of several tracks. They are +// ranked by chi2, then by time, with bestGeom and bestTime per track and bestInSector per sector; across the +// collection nShare, bestForCluster and a greedy one-to-one 'exclusive' assignment resolve shared clusters. +// Storage windows are loose on purpose: selections belong to the analysis. // #include "art/Framework/Core/EDProducer.h" #include "art/Framework/Core/ModuleMacros.h" diff --git a/CRVResponse/CMakeLists.txt b/CRVResponse/CMakeLists.txt index 6d2ce31a70..ca9694dc87 100644 --- a/CRVResponse/CMakeLists.txt +++ b/CRVResponse/CMakeLists.txt @@ -147,6 +147,7 @@ cet_build_plugin(MakeCrvCoincidenceClusterMCAssns art::module cet_build_plugin(TrkCrvMatchMCMaker art::module REG_SOURCE src/TrkCrvMatchMCMaker_module.cc LIBRARIES REG + Offline::CRVReco Offline::CosmicRayShieldGeom Offline::DataProducts Offline::GeometryService diff --git a/CRVResponse/fcl/prolog_v12.fcl b/CRVResponse/fcl/prolog_v12.fcl index 705a9bf5fa..f4145ef32d 100644 --- a/CRVResponse/fcl/prolog_v12.fcl +++ b/CRVResponse/fcl/prolog_v12.fcl @@ -200,6 +200,7 @@ BEGIN_PROLOG MCTrajectoryCollection : "compressRecoMCs" CrvStepCollection : "compressDigiMCs" CrvCoincidenceClusterMCAssns : "CrvCoincidenceClusterMCAssns" + RequireCrvSteps : true # false on reco output, which drops the digi-stage CrvSteps: no deposits then } diff --git a/CRVResponse/src/SConscript b/CRVResponse/src/SConscript index 1144f87310..5abd8bc102 100644 --- a/CRVResponse/src/SConscript +++ b/CRVResponse/src/SConscript @@ -31,6 +31,7 @@ mainlib = helper.make_mainlib ( [ 'CLHEP', ) helper.make_plugins( [ mainlib, + 'mu2e_CRVReco', 'mu2e_SeedService', 'mu2e_Mu2eUtilities', 'mu2e_GeometryService', diff --git a/CRVResponse/src/TrkCrvMatchMCMaker_module.cc b/CRVResponse/src/TrkCrvMatchMCMaker_module.cc index c1bdae30f3..2f63f13802 100644 --- a/CRVResponse/src/TrkCrvMatchMCMaker_module.cc +++ b/CRVResponse/src/TrkCrvMatchMCMaker_module.cc @@ -1,9 +1,9 @@ // -// MC truth for TrkCrvMatch by SimParticle identity. For each track: its particle (KalSeedMC primary contributor), the -// true CRV sector crossings of that particle and its ancestors (MCTrajectory chords through the sector mid-plane -// rectangles, gap-inclusive, plus CrvStep deposits), the truth of each reco crossing, and the relation of each -// candidate cluster's deposits to the track's particle. The geometry service must hold the SIMULATION geometry. -// Particles are identified by (simStage, key), so steps and trajectories from different compressed SimParticle +// MC truth for TrkCrvMatch. For each track: its KalSeedMC and particle (primary contributor), the true CRV sector +// crossings of that particle and its ancestors (MCTrajectory segments through the sector mid-plane rectangles, +// gap-inclusive, plus CrvStep deposits), the truth of each reco crossing, and the MCRelationship of each candidate +// cluster's deposits to the track's particle. The geometry service must hold the SIMULATION geometry. +// Steps and trajectories are matched to particles by (simStage, key), so different compressed SimParticle // collections of one stage compare correctly. // #include "art/Framework/Core/EDProducer.h" @@ -12,15 +12,16 @@ #include "art/Framework/Principal/Handle.h" #include "art/Framework/Principal/Run.h" #include "canvas/Utilities/InputTag.h" +#include "cetlib_except/exception.h" #include "fhiclcpp/types/Atom.h" #include "messagefacility/MessageLogger/MessageLogger.h" +#include "Offline/CRVReco/inc/TrkCrvGeom.hh" #include "Offline/CRVReco/inc/TrkCrvPlaneError.hh" #include "Offline/CosmicRayShieldGeom/inc/CosmicRayShield.hh" #include "Offline/DataProducts/inc/SurfaceId.hh" #include "Offline/GeometryService/inc/DetectorSystem.hh" #include "Offline/GeometryService/inc/GeomHandle.hh" -#include "Offline/KinKalGeom/inc/KinKalGeom.hh" #include "Offline/MCDataProducts/inc/CrvCoincidenceClusterMCAssns.hh" #include "Offline/MCDataProducts/inc/CrvStep.hh" #include "Offline/MCDataProducts/inc/KalSeedMC.hh" @@ -29,7 +30,9 @@ #include "Offline/MCDataProducts/inc/TrkCrvMatchMC.hh" #include "Offline/RecoDataProducts/inc/TrkCrvMatch.hh" #include "KinKal/General/Vectors.hh" +#include "KinKal/Geometry/LineSegment.hh" +#include #include #include #include @@ -52,6 +55,7 @@ namespace mu2e { fhicl::Atom simParticleTag{Name("SimParticleCollection"), Comment("SimParticles the KalSeedMC keys refer to"), art::InputTag("compressRecoMCs")}; fhicl::Atom mcTrajectoryTag{Name("MCTrajectoryCollection"), Comment("MC trajectories for the gap-inclusive crossings"), art::InputTag("compressRecoMCs")}; fhicl::Atom crvStepTag{Name("CrvStepCollection"), Comment("CRV steps for the deposits; the digi-stage collection holds every digitised step"), art::InputTag("compressDigiMCs")}; + fhicl::Atom requireCrvSteps{Name("RequireCrvSteps"), Comment("throw if the CRV steps are missing; false fills no deposits (hasDeposits_ false), e.g. on reco output, which drops them"), true}; fhicl::Atom clusterMCAssnsTag{Name("CrvCoincidenceClusterMCAssns"), Comment("cluster to cluster-MC associations, over the clusters the matcher used"), art::InputTag("CrvCoincidenceClusterMCAssns")}; fhicl::Atom edgeSigCut{Name("EdgeSigCut"), Comment("summary: a fake counts as near-edge when its edgeSig is below this"), 3.0}; fhicl::Atom maxGenerations{Name("MaxGenerations"), Comment("ancestors of the track's particle searched for CRV crossings"), 3}; @@ -67,7 +71,7 @@ namespace mu2e { private: using PKey = std::pair; // (simStage, key): particle identity across collections static PKey pkey(art::Ptr const& p) { return {p->simStage(), p.key()}; } - struct SectorGeom { bool valid = false; std::shared_ptr rect; SurfaceId sid; }; + static constexpr int nRel = 9; // summary bins: no MC, then MCRelationship none ... usibling struct Counts { // per shield unsigned recoX = 0, recoTrueDep = 0, recoTrueGap = 0, recoTrueAnc = 0, recoFake = 0, recoFakeEdge = 0; unsigned recoFakeNbr = 0, trueMissedNbr = 0; @@ -76,20 +80,18 @@ namespace mu2e { double chi2nd = 0, chi2ndProj = 0; // sums of chi2/ndof of those geometric candidates unsigned trueX = 0, trueFound = 0, trueMissed = 0, trueNoGeom = 0; }; - // relation of particle q to the track's particle: walk q's ancestry - uint8_t relation(art::Ptr q, std::set const& self, std::set const& anc, PKey const& trkRoot) const; - PKey root(art::Ptr p) const; - art::InputTag matchTag_, ksmcTag_, spTag_, trajTag_, stepTag_, ccmcTag_; + bool requireSteps_; double edgeSigCut_; unsigned maxGen_; bool printSummary_; int diag_; - std::vector sectors_; // indexed by shield + std::vector sectors_; // indexed by shield std::vector planeGroup_; // per shield: sectors sharing one plane get one id, -1 = no rectangle std::vector shieldNames_; std::map counts_; - std::array bestGeomRel_{}, bestTimeRel_{}; + std::array bestGeomRel_{}, bestTimeRel_{}; + std::vector dtRefSame_; // dtRef of time candidates whose cluster is the track's own particle (DtRefCenter) unsigned nTracks_ = 0, nTracksMC_ = 0, nTracksCrossing_ = 0; }; @@ -97,33 +99,22 @@ namespace mu2e { art::EDProducer(conf), matchTag_(conf().matchTag()), ksmcTag_(conf().kalSeedMCAssnsTag()), spTag_(conf().simParticleTag()), trajTag_(conf().mcTrajectoryTag()), stepTag_(conf().crvStepTag()), ccmcTag_(conf().clusterMCAssnsTag()), - edgeSigCut_(conf().edgeSigCut()), maxGen_(conf().maxGenerations()), printSummary_(conf().printSummary()), diag_(conf().diag()) + requireSteps_(conf().requireCrvSteps()), edgeSigCut_(conf().edgeSigCut()), maxGen_(conf().maxGenerations()), printSummary_(conf().printSummary()), diag_(conf().diag()) { consumes(matchTag_); consumes(ksmcTag_); consumes(spTag_); consumes(trajTag_); - consumes(stepTag_); + if(requireSteps_) consumes(stepTag_); + else mayConsume(stepTag_); consumes(ccmcTag_); produces(); } void TrkCrvMatchMCMaker::beginRun(art::Run&) { - GeomHandle crs; - GeomHandle kkg; - auto const& shields = crs->getCRSScintillatorShields(); - sectors_.assign(shields.size(), SectorGeom()); + sectors_ = trkCrvSectors(); shieldNames_.clear(); - std::map nameToShield; - for(size_t i = 0; i < shields.size(); ++i) { nameToShield[shields[i].getName()] = static_cast(i); shieldNames_.push_back(shields[i].getName()); } - for(auto const& sec : kkg->CRV()->sectors()) { - auto it = nameToShield.find(sec.sname_); - if(it == nameToShield.end()) continue; - auto& g = sectors_[it->second]; - g.valid = true; - g.rect = sec.sector_; - try { g.sid = SurfaceId(sec.sname_); } catch(std::exception const&) {} - } + for(auto const& sg : sectors_) shieldNames_.push_back(sg.name); // coplanar sectors: parallel normals and centres within 5 mm of one plane planeGroup_.assign(sectors_.size(), -1); int ng = 0; @@ -140,31 +131,16 @@ namespace mu2e { } } - TrkCrvMatchMCMaker::PKey TrkCrvMatchMCMaker::root(art::Ptr p) const { - for(int i = 0; i < 1000 && p->parent().isNonnull(); ++i) p = p->parent(); - return pkey(p); - } - - uint8_t TrkCrvMatchMCMaker::relation(art::Ptr q, std::set const& self, std::set const& anc, PKey const& trkRoot) const { - if(q.isNull()) return TrkCrvTruth::Background; - bool family = false; - for(int i = 0; i < 1000 && q.isNonnull(); ++i) { - auto k = pkey(q); - if(self.count(k)) return TrkCrvTruth::SameParticle; // the track's particle (any stage) or a descendant of it - if(anc.count(k)) family = true; // an ancestor or another descendant of an ancestor - if(q->parent().isNull()) return family ? TrkCrvTruth::SameFamily : (k == trkRoot ? TrkCrvTruth::SamePrimary : TrkCrvTruth::Unrelated); - q = q->parent(); - } - return family ? TrkCrvTruth::SameFamily : TrkCrvTruth::Unrelated; - } - void TrkCrvMatchMCMaker::produce(art::Event& event) { auto const& mH = event.getValidHandle(matchTag_); auto const& ksmcH = event.getValidHandle(ksmcTag_); - auto spH = event.getHandle(spTag_); - auto trajH = event.getHandle(trajTag_); + auto spH = event.getHandle(spTag_); // a plain Handle, as SimPartStub::simParticle takes + if(!spH.isValid()) throw cet::exception("TrkCrvMatchMCMaker") << "no SimParticleCollection " << spTag_; + auto const& trajH = event.getValidHandle(trajTag_); + auto const& ccmcH = event.getValidHandle(ccmcTag_); auto stepH = event.getHandle(stepTag_); - auto ccmcH = event.getHandle(ccmcTag_); + if(!stepH.isValid() && requireSteps_) + throw cet::exception("TrkCrvMatchMCMaker") << "no CrvStepCollection " << stepTag_ << " (reco output drops it; set RequireCrvSteps : false to run without deposits)"; GeomHandle crs; GeomHandle det; auto toDet = [&](CLHEP::Hep3Vector const& v) { auto d = det->toDetector(v); return KinKal::VEC3(d.x(), d.y(), d.z()); }; @@ -176,14 +152,15 @@ namespace mu2e { std::map> ccmc; std::map clusterShield; art::ProductID clusterPid; - if(ccmcH.isValid()) for(auto const& a : *ccmcH) { + for(auto const& a : *ccmcH) { ccmc[a.first.key()] = a.second; clusterPid = a.first.id(); - std::map pes; - for(auto const& rp : a.first->GetCrvRecoPulses()) pes[crs->getBar(rp->GetScintillatorBarIndex()).id().getShieldNumber()] += rp->GetPEs(); - double best = -1; - for(auto const& [s, pe] : pes) if(pe > best) { best = pe; clusterShield[a.first.key()] = s; } + clusterShield[a.first.key()] = trkCrvDominantShield(*a.first, *crs); } + // a deposit's particle in the track's SimParticle collection (same key), so MCRelationship compares like Ptrs + auto inTrackCollection = [&](art::Ptr const& q) { + return (q.isNonnull() && spH->has(cet::map_vector_key(q.key()))) ? art::Ptr(spH, q.key()) : art::Ptr(); + }; auto out = std::make_unique(); for(size_t imatch = 0; imatch < mH->size(); ++imatch) { @@ -194,60 +171,63 @@ namespace mu2e { mc.recoXingNeighbor_.assign(m.xings_.size(), -1); mc.cands_.assign(m.cands_.size(), TrkCrvCandidateMC()); ++nTracks_; + mc.hasDeposits_ = stepH.isValid(); auto im = ksmc.find({m.track_.id(), m.track_.key()}); - bool ok = im != ksmc.end() && spH.isValid(); - if(ok && !im->second->simParticles().empty()) mc.trackSim_ = im->second->simParticle().simParticle(spH); - if(mc.trackSim_.isNull() || !mc.trackSim_.isAvailable()) { out->push_back(std::move(mc)); continue; } + art::Ptr trackSim; + if(im != ksmc.end()) { + mc.kalSeedMC_ = im->second; + if(!im->second->simParticles().empty()) trackSim = im->second->simParticle().simParticle(spH); + } + if(trackSim.isNull() || !trackSim.isAvailable()) { out->push_back(std::move(mc)); continue; } ++nTracksMC_; - PKey trk = pkey(mc.trackSim_); - PKey trkRoot = root(mc.trackSim_); + PKey trk = pkey(trackSim); // lineage: generation 0 = the track's particle (and its earlier-stage selves), then ancestors std::vector,uint8_t>> lineage; - std::set anc, self; - art::Ptr p = mc.trackSim_; + art::Ptr p = trackSim; uint8_t gen = 0; for(int i = 0; i < 1000 && p.isNonnull() && gen <= maxGen_; ++i) { lineage.push_back({p, gen}); - if(gen > 0) anc.insert(pkey(p)); else self.insert(pkey(p)); - bool self = p->selfParent(); + bool selfParent = p->selfParent(); p = p->parent(); - if(!self) ++gen; + if(!selfParent) ++gen; } - // true crossings: trajectory chords through the sector rectangles, then deposits + // true crossings: trajectory segments through the sector rectangles, then deposits std::map, TrkCrvXingMC> xmap; // (lineage index, shield) for(size_t il = 0; il < lineage.size(); ++il) { auto const& [sp, g] = lineage[il]; - if(trajH.isValid()) { + { auto it = trajH->find(sp); if(it != trajH->end()) { auto const& pts = it->second.points(); double mass = sp->startMomentum().m(); for(size_t j = 1; j < pts.size(); ++j) { KinKal::VEC3 a = toDet(pts[j-1].pos()), b = toDet(pts[j].pos()); + if((b - a).Mag2() <= 0) continue; + KinKal::LineSegment seg(a, b); // the trajectory between two saved points for(size_t s = 0; s < sectors_.size(); ++s) { auto const& sg = sectors_[s]; if(!sg.valid) continue; - double da = (a - sg.rect->center()).Dot(sg.rect->normal()), db = (b - sg.rect->center()).Dot(sg.rect->normal()); - if(da * db > 0 || da == db) continue; - double f = da / (da - db); - KinKal::VEC3 x = a + f * (b - a); - if(!sg.rect->inBounds(x, 0.0)) continue; + double dist = 0; + auto flag = sg.rect->intersect(seg, dist, true, 0.0); + if(!flag.onsurface_ || !flag.inbounds_ || dist < 0 || dist > seg.length()) continue; + double f = dist / seg.length(); + KinKal::VEC3 x = seg.position(dist); auto key = std::make_pair(il, static_cast(s)); double t = pts[j-1].t() + f * (pts[j].t() - pts[j-1].t()); auto& xm = xmap[key]; if(xm.geom_ && xm.time_ <= t) continue; // keep the earliest crossing of a sector xm.geom_ = true; xm.pos_ = XYZVectorF(x.X(), x.Y(), x.Z()); - auto d = (b - a).Unit(); + auto const& d = seg.direction(); xm.dir_ = XYZVectorF(d.X(), d.Y(), d.Z()); xm.time_ = t; double ke = pts[j-1].kineticEnergy() + f * (pts[j].kineticEnergy() - pts[j-1].kineticEnergy()); xm.mom_ = std::sqrt(std::max(ke * (ke + 2.0 * mass), 0.0)); - auto loc = x - sg.rect->center(); - xm.dEdgeU_ = sg.rect->uHalfLength() - std::fabs(loc.Dot(sg.rect->uDirection())); - xm.dEdgeV_ = sg.rect->vHalfLength() - std::fabs(loc.Dot(sg.rect->vDirection())); + auto loc = x - sg.center; + xm.dEdgeU_ = sg.uHalf - std::fabs(loc.Dot(sg.u)); + xm.dEdgeV_ = sg.vHalf - std::fabs(loc.Dot(sg.v)); } } } @@ -282,7 +262,7 @@ namespace mu2e { } // the cluster with the most energy from each crossing's particle in that sector - if(ccmcH.isValid()) { + { for(size_t ix = 0; ix < mc.xings_.size(); ++ix) { auto& xm = mc.xings_[ix]; PKey k = pkey(xm.sim_); @@ -295,7 +275,7 @@ namespace mu2e { if(e > best) { best = e; xm.trueCluster_ = static_cast(ckey); } } for(size_t ic = 0; ic < m.cands_.size() && xm.trueCluster_ >= 0; ++ic) - if(static_cast(m.cands_[ic].cluster_.key()) == xm.trueCluster_) { xm.trueCand_ = static_cast(ic); break; } + if(m.cands_[ic].cluster_.id() == clusterPid && static_cast(m.cands_[ic].cluster_.key()) == xm.trueCluster_) { xm.trueCand_ = static_cast(ic); break; } } } @@ -319,24 +299,38 @@ namespace mu2e { } } - // candidate clusters: relation of their deposits to the track's particle - if(ccmcH.isValid() && !m.cands_.empty() && m.cands_.front().cluster_.id() != clusterPid && !ccmc.empty()) + // candidate clusters: the closest MCRelationship of their deposit particles to the track's particle. A particle + // simulated in several stages has a copy per stage (self-parent chain), and a deposit can point at any of them, + // so each deposit is compared with every copy of the track's particle and the closest relation is kept + std::vector> trackSelves; + for(auto const& [sp, g] : lineage) if(g == 0) trackSelves.push_back(sp); + if(!m.cands_.empty() && m.cands_.front().cluster_.id() != clusterPid && !ccmc.empty()) mf::LogWarning("TrkCrvMatchMCMaker") << "cluster MC associations are over a different cluster collection than the matcher used"; for(size_t ic = 0; ic < m.cands_.size(); ++ic) { auto& cm = mc.cands_[ic]; auto it = ccmc.find(m.cands_[ic].cluster_.key()); - if(it == ccmc.end() || m.cands_[ic].cluster_.id() != clusterPid) continue; - if(!it->second->HasMCInfo()) { cm.rel_ = TrkCrvTruth::Background; continue; } - uint8_t rel = TrkCrvTruth::Background; + if(it == ccmc.end() || m.cands_[ic].cluster_.id() != clusterPid || !it->second->HasMCInfo()) continue; + cm.hasMC_ = true; for(auto const& pi : it->second->GetPulses()) { if(pi._energyDeposited <= 0) continue; - uint8_t r = relation(pi._simParticle, self, anc, trkRoot); + auto q = inTrackCollection(pi._simParticle); + MCRelationship r; + for(auto const& self : trackSelves) { MCRelationship rs(q, self); if(r < rs) r = rs; } + if(diag_ > 1) { + mf::LogInfo dl("TrkCrvMatchMCMaker"); + dl << "event " << event.id() << " track " << m.track_.key() << " cand " << ic << " deposit sim " + << (pi._simParticle.isNonnull() ? std::to_string(pi._simParticle.id().value()) + ":" + std::to_string(pi._simParticle.key()) : std::string("null")) + << " in track collection " << q.isNonnull(); + if(q.isNonnull()) dl << " stage " << q->simStage() << " selfParent " << q->selfParent(); + dl << " rel " << int(r.relationship()) << "/" << int(r.removal()) << " | track copies"; + for(auto const& self : trackSelves) dl << " " << self.id().value() << ":" << self.key() << "(stage " << self->simStage() << ")"; + } cm.edepTotal_ += pi._energyDeposited; - if(r == TrkCrvTruth::SameParticle) cm.edepSame_ += pi._energyDeposited; - if(r == TrkCrvTruth::SameFamily) cm.edepFamily_ += pi._energyDeposited; - rel = std::min(rel, r); + if(r == MCRelationship::same) cm.edepSame_ += pi._energyDeposited; + if(r != MCRelationship::none) cm.edepRelated_ += pi._energyDeposited; + if(cm.rel_ < r) cm.rel_ = r; } - cm.rel_ = rel; + if(cm.rel_ == MCRelationship::same && m.cands_[ic].hasFlag(TrkCrvCandidate::timeCand)) dtRefSame_.push_back(m.cands_[ic].dtRef_); } // bookkeeping for the end-of-job summary @@ -383,12 +377,13 @@ namespace mu2e { if(excl) ++c.trueCluExcl; } if(crosses) ++nTracksCrossing_; - if(m.bestGeom_ >= 0) ++bestGeomRel_[mc.cands_[m.bestGeom_].rel_]; - if(m.bestTime_ >= 0) ++bestTimeRel_[mc.cands_[m.bestTime_].rel_]; + auto relBin = [](TrkCrvCandidateMC const& cm) { return cm.hasMC_ ? cm.rel_.relationship() + 2 : 0; }; + if(m.bestGeom_ >= 0) ++bestGeomRel_[relBin(mc.cands_[m.bestGeom_])]; + if(m.bestTime_ >= 0) ++bestTimeRel_[relBin(mc.cands_[m.bestTime_])]; if(diag_ > 0) { mf::LogInfo log("TrkCrvMatchMCMaker"); - log << "event " << event.id() << " track " << m.track_.key() << " sim " << mc.trackSim_->pdgId() << " stage/key " + log << "event " << event.id() << " track " << m.track_.key() << " sim " << trackSim->pdgId() << " stage/key " << trk.first << "/" << trk.second << " reco xings " << m.xings_.size() << " true xings " << mc.xings_.size(); for(size_t ir = 0; ir < m.xings_.size(); ++ir) log << "\n reco " << m.xings_[ir].sid_ << " inb " << m.xings_[ir].inBounds_ << " edgeU " << m.xings_[ir].dEdgeU_ @@ -414,14 +409,14 @@ namespace mu2e { double s = (rect.center() - px).Dot(w) / dw; KinKal::VEC3 r = KinKal::VEC3(xm.pos_.X(), xm.pos_.Y(), xm.pos_.Z()) - (px + s * d); auto const& cov = ki.pstate_.stateCovariance(); + auto ce = trkCrvPlaneCovariance(cov, mom, rect.uDirection(), rect.vDirection(), w, s); + auto c0 = trkCrvPlaneCovariance(cov, mom, rect.uDirection(), rect.vDirection(), w, 0.0); log << "\n pull shield " << xm.sector_ << " same " << c.hasFlag(TrkCrvCandidate::sameSector) << " single " << c.hasFlag(TrkCrvCandidate::singleEnded) << " s " << s << " dw " << dw - << " du " << c.du_ << " dv " << c.dv_ << " sigU " << c.sigU_ << " sigV " << c.sigV_ + << " du " << c.du_ << " dv " << c.dv_ << " sigU " << c.sigU() << " sigV " << c.sigV() << " tdu " << r.Dot(rect.uDirection()) << " tdv " << r.Dot(rect.vDirection()) - << " teu " << trkCrvPlaneError(cov, mom, rect.uDirection(), w, s) - << " tev " << trkCrvPlaneError(cov, mom, rect.vDirection(), w, s) - << " teu0 " << trkCrvPlaneError(cov, mom, rect.uDirection(), w, 0.0) - << " tev0 " << trkCrvPlaneError(cov, mom, rect.vDirection(), w, 0.0); + << " teu " << std::sqrt(ce(0,0)) << " tev " << std::sqrt(ce(1,1)) << " rhouv " << (ce(0,0) > 0 && ce(1,1) > 0 ? ce(0,1)/std::sqrt(ce(0,0)*ce(1,1)) : 0.0) + << " teu0 " << std::sqrt(c0(0,0)) << " tev0 " << std::sqrt(c0(1,1)); } } out->push_back(std::move(mc)); @@ -431,7 +426,7 @@ namespace mu2e { void TrkCrvMatchMCMaker::endJob() { if(!printSummary_) return; - static const char* relName[6] = {"SameParticle","SameFamily","SamePrimary","Unrelated","Background","NoMC"}; + static const char* relName[nRel] = {"noMC","none","same","daughter","mother","sibling","udaughter","umother","usibling"}; mf::LogInfo log("TrkCrvMatchMCMaker"); log << "TrkCrvMatchMC summary (" << moduleDescription().moduleLabel() << "): tracks " << nTracks_ << ", with MC " << nTracksMC_ << ", whose particle crosses a CRV sector " << nTracksCrossing_ << "\n" @@ -450,9 +445,14 @@ namespace mu2e { << " best " << c.trueCluBest << " chi2nd " << c.chi2nd << " proj " << c.trueCluProj << " chi2ndProj " << c.chi2ndProj; } log << "\nbest geometric candidate:"; - for(int i = 0; i < 6; ++i) log << " " << relName[i] << " " << bestGeomRel_[i]; + for(int i = 0; i < nRel; ++i) log << " " << relName[i] << " " << bestGeomRel_[i]; log << "\nbest time candidate: "; - for(int i = 0; i < 6; ++i) log << " " << relName[i] << " " << bestTimeRel_[i]; + for(int i = 0; i < nRel; ++i) log << " " << relName[i] << " " << bestTimeRel_[i]; + if(!dtRefSame_.empty()) { + std::sort(dtRefSame_.begin(), dtRefSame_.end()); + auto q = [&](double f) { return dtRefSame_[std::min(dtRefSame_.size() - 1, static_cast(f * dtRefSame_.size()))]; }; + log << "\nown-particle time candidates: " << dtRefSame_.size() << ", dtRef median " << q(0.5) << " ns, 16-84% " << q(0.16) << " " << q(0.84) << " ns"; + } } } diff --git a/MCDataProducts/inc/TrkCrvMatchMC.hh b/MCDataProducts/inc/TrkCrvMatchMC.hh index 9c6ea486f0..f387efdb3f 100644 --- a/MCDataProducts/inc/TrkCrvMatchMC.hh +++ b/MCDataProducts/inc/TrkCrvMatchMC.hh @@ -1,12 +1,14 @@ // -// MC truth for a TrkCrvMatch, by SimParticle identity: the true CRV sector crossings of the track's particle and its -// ancestors, the truth of each reco crossing, and the relation of each candidate cluster to the track's particle. +// MC truth for a TrkCrvMatch: the true CRV sector crossings of the track's particle and its ancestors, the truth of +// each reco crossing, and the relation of each candidate cluster to the track's particle. // One TrkCrvMatchMC per TrkCrvMatch, in the same order; candidates and reco crossings are parallel to the reco record. // #ifndef MCDataProducts_TrkCrvMatchMC_hh #define MCDataProducts_TrkCrvMatchMC_hh #include "Offline/DataProducts/inc/GenVector.hh" #include "Offline/DataProducts/inc/SurfaceId.hh" +#include "Offline/MCDataProducts/inc/KalSeedMC.hh" +#include "Offline/MCDataProducts/inc/MCRelationship.hh" #include "Offline/MCDataProducts/inc/SimParticle.hh" #include "Offline/RecoDataProducts/inc/TrkCrvMatch.hh" #include "canvas/Persistency/Common/Ptr.h" @@ -15,42 +17,40 @@ namespace mu2e { - struct TrkCrvTruth { - // relation of a cluster's energy deposits to the track's particle, best first - enum Relation : uint8_t { SameParticle = 0, SameFamily, SamePrimary, Unrelated, Background, NoMC }; - }; - - // one true crossing of a CRV sector by the track's particle (generation 0) or one of its ancestors + // one true crossing of a CRV sector by the track's particle (generation 0) or one of its ancestors (sim_); the + // position, direction, time and momentum are those of sim_'s MC trajectory at the sector mid-plane struct TrkCrvXingMC { SurfaceId sid_; // sector surface, as the reco crossings int16_t sector_ = -1; // CRSScintillatorShield index uint8_t generation_ = 0; // 0 = the track's particle, 1 = its parent, ... - art::Ptr sim_; - bool geom_ = false; // the particle's trajectory crosses the sector mid-plane rectangle (gap-inclusive) - XYZVectorF pos_; // trajectory crossing of the mid-plane, detector frame [mm] (geom_ only) - XYZVectorF dir_; // unit direction of the trajectory chord at the crossing (geom_ only) - float time_ = 0; // time of the mid-plane crossing [ns] (geom_ only) - float mom_ = 0; // momentum magnitude at the mid-plane crossing [MeV/c] (geom_ only) - float dEdgeU_ = 0; // distance of that crossing inside the sector edge along the bars [mm] (geom_ only) - float dEdgeV_ = 0; // distance of that crossing inside the sector edge across the bars [mm] (geom_ only) - float edep_ = 0; // visible energy the particle deposited in the sector's bars [MeV] - uint8_t nLayers_ = 0; // layers of the sector with a deposit from the particle + art::Ptr sim_; // the crossing particle + bool geom_ = false; // sim_'s trajectory crosses the sector mid-plane rectangle (gap-inclusive) + XYZVectorF pos_; // sim_'s trajectory at the mid-plane, detector frame [mm] (geom_ only) + XYZVectorF dir_; // unit direction of sim_'s trajectory there (geom_ only) + float time_ = 0; // sim_'s time at the mid-plane [ns] (geom_ only) + float mom_ = 0; // sim_'s momentum magnitude at the mid-plane [MeV/c] (geom_ only) + float dEdgeU_ = 0; // distance of that point inside the sector edge along the bars [mm] (geom_ only) + float dEdgeV_ = 0; // distance of that point inside the sector edge across the bars [mm] (geom_ only) + float edep_ = 0; // visible energy sim_ deposited in the sector's bars [MeV] (CrvSteps; 0 without them) + uint8_t nLayers_ = 0; // layers of the sector with a deposit from sim_ XYZVectorF depPos_; // energy-weighted position of those deposits, detector frame [mm] - int16_t trueCluster_ = -1; // cluster (index in the matched collection) with the most energy from the particle here + int16_t trueCluster_ = -1; // cluster (index in the matched collection) with the most energy from sim_ here int16_t trueCand_ = -1; // index into TrkCrvMatch::cands_ of trueCluster_, -1 if it is not a candidate int16_t recoXing_ = -1; // index of the reco crossing of the same sector, -1 = not extrapolated there }; struct TrkCrvCandidateMC { - uint8_t rel_ = TrkCrvTruth::NoMC; // a TrkCrvTruth::Relation - float edepSame_ = 0; // cluster energy from the track's particle and its descendants [MeV] - float edepFamily_ = 0; // cluster energy from the track particle's ancestors and their other descendants [MeV] + MCRelationship rel_; // closest relation of the cluster's deposit particles to the track's particle (none: unrelated or no MC) + bool hasMC_ = false; // the cluster has MC information (false: background or no MC) + float edepSame_ = 0; // cluster energy from the track's particle (relation same) [MeV] + float edepRelated_ = 0; // cluster energy from any related particle, the track's particle included [MeV] float edepTotal_ = 0; // all cluster energy with MC information [MeV] }; struct TrkCrvMatchMC { art::Ptr match_; // the reco record this truth belongs to - art::Ptr trackSim_; // the KalSeedMC primary contributor + art::Ptr kalSeedMC_; // the track's KalSeedMC; its primary contributor is the track's particle + bool hasDeposits_ = false; // CrvSteps were available: edep_, nLayers_ and depPos_ are filled std::vector xings_; // true crossings std::vector recoXingTruth_; // per reco crossing: index into xings_ of the same sector, -1 = no true crossing std::vector recoXingNeighbor_; // per reco crossing without one: true crossing of a coplanar sector by the track's particle, -1 = none diff --git a/RecoDataProducts/inc/TrkCrvMatch.hh b/RecoDataProducts/inc/TrkCrvMatch.hh index 117ee65853..1e398489ff 100644 --- a/RecoDataProducts/inc/TrkCrvMatch.hh +++ b/RecoDataProducts/inc/TrkCrvMatch.hh @@ -2,6 +2,9 @@ // Association of one reconstructed track (KalSeed) with CRV coincidence clusters: the track's CRV crossings and // every cluster inside the loose time or geometry storage windows, with signed residuals, ranks and flags. // One TrkCrvMatch per input KalSeed, in the KalSeed collection's order. +// Sector frame of the residuals and covariances: u along the bars, v across the bars (the uDirection and vDirection +// of the sector's KinKalGeom CRV rectangle, detector frame); trkCrvSectors() in CRVReco/inc/TrkCrvGeom.hh returns +// them per sector_ index. // #ifndef RecoDataProducts_TrkCrvMatch_hh #define RecoDataProducts_TrkCrvMatch_hh @@ -11,14 +14,18 @@ #include "Offline/RecoDataProducts/inc/CrvCoincidenceCluster.hh" #include "canvas/Persistency/Common/Assns.h" #include "canvas/Persistency/Common/Ptr.h" +#include "Math/SMatrix.h" #include #include #include namespace mu2e { - // clusters a track fit used as constraints; the matcher flags those candidates usedInFit + // clusters a track fit used as constraints, for a future fit with CRV constraints (nothing produces it yet); the + // matcher flags those candidates usedInFit using TrkCrvFitClusterAssns = art::Assns; + // symmetric covariance in the sector plane, (u, v) order [mm^2] + using TrkCrvPlaneCov = ROOT::Math::SMatrix>; // one CRV layer on the track's straight line through a crossed sector, with the best pulse near the predicted bar struct TrkCrvLayerProbe { @@ -26,7 +33,7 @@ namespace mu2e { int8_t dBar_ = INT8_MAX; // bar offset of the selected pulse from the predicted bar, INT8_MAX if none in the windows float uPred_ = 0; // predicted position along the bar from its centre, along the Mu2e length axis [mm] float tPred_ = 0; // track time at the layer [ns] - float pe_ = 0; // PEs of the in-window pulses of the selected bar (both ends) + float pe_ = 0; // PEs of the in-window pulses of the selected bar (both ends); kept since unclustered pulses are not persisted float dt_ = 0; // pulse time - predicted pulse time (track time plus fibre propagation) [ns] bool inCluster_ = false; // an in-window pulse of the selected bar belongs to a coincidence cluster float uTdiv_ = NAN; // position along the bar from the two-end time difference [mm], NaN if one-ended @@ -40,17 +47,18 @@ namespace mu2e { XYZVectorF pos_; // crossing position on the sector mid-plane, detector frame [mm] XYZVectorF dir_; // unit direction of the track at the crossing float time_ = 0; // crossing time [ns] - float sigU_ = 0; // track position error along the bars, in the sector plane, error model applied [mm] - float sigV_ = 0; // track position error across the bars, in the sector plane, error model applied [mm] + TrkCrvPlaneCov cov_; // track position covariance in the sector plane (u, v), error model applied [mm^2] float sigT_ = 0; // track time error [ns] float mom_ = 0; // track momentum magnitude at the crossing [MeV/c] float momErr_ = 0; // its error [MeV/c] bool inBounds_ = false; // crossing inside the sector rectangle float dEdgeU_ = 0; // distance inside the sector edge along the bars [mm], negative outside float dEdgeV_ = 0; // distance inside the sector edge across the bars [mm], negative outside - float edgeSig_ = 0; // min(dEdgeU_/sigU_, dEdgeV_/sigV_): edge distance in units of the track error + float edgeSig_ = 0; // min(dEdgeU_/sigU(), dEdgeV_/sigV()): edge distance in units of the track error int16_t best_ = -1; // index into TrkCrvMatch::cands_ of the best geometric candidate in this crossing's sector, -1 if none std::vector layers_; // one per layer of the sector, in layer order; empty unless the layer probe ran + float sigU() const { return std::sqrt(cov_(0,0)); } + float sigV() const { return std::sqrt(cov_(1,1)); } }; // one CRV coincidence cluster associated with the track @@ -66,23 +74,24 @@ namespace mu2e { float dtXing_ = 0; // cluster avgHitTime - t_track at the cluster plane [ns] float du_ = 0; // cluster - track along the bars, at the cluster plane [mm] float dv_ = 0; // cluster - track across the bars, at the cluster plane [mm] - float sigU_ = 0; // track error on du_, carried from the reference crossing over the step, error model applied [mm] - float sigV_ = 0; // track error on dv_, carried from the reference crossing over the step, error model applied [mm] - float chi2_ = -1; // space + time chi2 (geometric candidates only) + TrkCrvPlaneCov cov_; // track covariance of (du, dv), carried from the reference crossing over the step, error model applied [mm^2] + float chi2_ = -1; // space + time chi2 (geometric candidates only), with the full (u, v) covariance uint8_t ndof_ = 0; // chi2 degrees of freedom: 2 for single-ended clusters (no along-bar term), else 3 uint8_t nShare_ = 0; // tracks of this collection holding this cluster as a candidate uint16_t flags_ = 0; bool hasFlag(Flag f) const { return flags_ & f; } void setFlag(Flag f) { flags_ |= f; } + float sigU() const { return std::sqrt(cov_(0,0)); } + float sigV() const { return std::sqrt(cov_(1,1)); } }; struct TrkCrvMatch { + enum Probe : uint8_t { probeOff = 0, probeNoPulses, probeClusteredPulses, probeAllPulses }; art::Ptr track_; - SurfaceId refSurface_; // surface that defined tRef_ (unknown = KalSeed t0) + SurfaceId refSurface_; // surface that defined tRef_ (unknown = KalSeed t0); other surface times are in the KalSeed float tRef_ = 0; // reference track time used by dtRef [ns] - float tFront_ = 0, tMid_ = 0;// track time at TT_Front / TT_Mid, 0 if the KalSeed has no such intersection - bool hasFront_ = false, hasMid_ = false; float timeOffset_ = 0; // CRV - tracker time offset applied to the cluster times [ns] + uint8_t probe_ = probeOff; // pulses the layer probe saw: none (predicted bars only), clustered only, or all std::vector xings_; std::vector cands_; // geometric candidates by chi2, then time-only by |dtRef - centre| int16_t bestGeom_ = -1; // lowest-chi2 geometric candidate, -1 if none From addceca1281ee40c0404f4d86496331cabfce94e Mon Sep 17 00:00:00 2001 From: Rob Mina Date: Fri, 6 Nov 2026 15:40:41 -0600 Subject: [PATCH 3/4] TrkCrvXingMC: MCRelationship replaces generation_; add MCRelationship(relation, removal) constructor. --- CRVResponse/src/TrkCrvMatchMCMaker_module.cc | 23 +++++++++++++------- MCDataProducts/inc/MCRelationship.hh | 2 ++ MCDataProducts/inc/TrkCrvMatchMC.hh | 5 +++-- 3 files changed, 20 insertions(+), 10 deletions(-) diff --git a/CRVResponse/src/TrkCrvMatchMCMaker_module.cc b/CRVResponse/src/TrkCrvMatchMCMaker_module.cc index 2f63f13802..e580183874 100644 --- a/CRVResponse/src/TrkCrvMatchMCMaker_module.cc +++ b/CRVResponse/src/TrkCrvMatchMCMaker_module.cc @@ -45,6 +45,13 @@ namespace mu2e { + // relation of an ancestor to the track's particle, from its generation in the stage-aware lineage (MCRelationship + // from the Ptrs would count each simulation-stage copy as a generation) + inline MCRelationship ancestorRelation(unsigned gen) { + if(gen == 0) return MCRelationship(MCRelationship::same, 0); + return MCRelationship(gen == 1 ? MCRelationship::mother : MCRelationship::umother, static_cast(gen)); + } + class TrkCrvMatchMCMaker : public art::EDProducer { public: struct Config { @@ -255,7 +262,7 @@ namespace mu2e { } for(auto& [key, xm] : xmap) { xm.sector_ = static_cast(key.second); - xm.generation_ = lineage[key.first].second; + xm.rel_ = ancestorRelation(lineage[key.first].second); xm.sim_ = lineage[key.first].first; if(key.second >= 0 && static_cast(key.second) < sectors_.size()) xm.sid_ = sectors_[key.second].sid; mc.xings_.push_back(xm); @@ -285,7 +292,7 @@ namespace mu2e { for(size_t ix = 0; ix < mc.xings_.size(); ++ix) { auto const& xm = mc.xings_[ix]; if(xm.sector_ != m.xings_[ir].sector_ || !(xm.geom_ || xm.edep_ > 0)) continue; - if(best < 0 || xm.generation_ < mc.xings_[best].generation_) best = static_cast(ix); + if(best < 0 || xm.rel_.removal() < mc.xings_[best].rel_.removal()) best = static_cast(ix); } mc.recoXingTruth_[ir] = static_cast(best); if(best >= 0 && mc.xings_[best].recoXing_ < 0) mc.xings_[best].recoXing_ = static_cast(ir); @@ -293,7 +300,7 @@ namespace mu2e { int rs = m.xings_[ir].sector_; for(size_t ix = 0; ix < mc.xings_.size(); ++ix) { auto const& xm = mc.xings_[ix]; - if(xm.generation_ != 0 || !(xm.geom_ || xm.edep_ > 0) || xm.sector_ == rs) continue; + if(xm.rel_ != MCRelationship::same || !(xm.geom_ || xm.edep_ > 0) || xm.sector_ == rs) continue; if(rs >= 0 && xm.sector_ >= 0 && planeGroup_[rs] >= 0 && planeGroup_[rs] == planeGroup_[xm.sector_]) { mc.recoXingNeighbor_[ir] = static_cast(ix); break; } } } @@ -340,12 +347,12 @@ namespace mu2e { ++c.recoX; int t = mc.recoXingTruth_[ir]; if(t < 0) { ++c.recoFake; if(m.xings_[ir].edgeSig_ < edgeSigCut_) ++c.recoFakeEdge; if(mc.recoXingNeighbor_[ir] >= 0) ++c.recoFakeNbr; } - else if(mc.xings_[t].generation_ > 0) ++c.recoTrueAnc; + else if(mc.xings_[t].rel_ != MCRelationship::same) ++c.recoTrueAnc; else if(mc.xings_[t].edep_ > 0) ++c.recoTrueDep; else ++c.recoTrueGap; } for(auto const& xm : mc.xings_) { - if(xm.generation_ != 0) continue; + if(xm.rel_ != MCRelationship::same) continue; auto& c = counts_[xm.sector_]; if(!xm.geom_) { if(xm.edep_ > 0) ++c.trueNoGeom; continue; } crosses = true; @@ -358,7 +365,7 @@ namespace mu2e { } } for(auto const& xm : mc.xings_) { // is the particle's own cluster in each sector associated geometrically? - if(xm.generation_ != 0 || xm.trueCluster_ < 0) continue; + if(xm.rel_ != MCRelationship::same || xm.trueCluster_ < 0) continue; auto& c = counts_[xm.sector_]; ++c.trueClu; bool geom = false, excl = false; @@ -389,12 +396,12 @@ namespace mu2e { log << "\n reco " << m.xings_[ir].sid_ << " inb " << m.xings_[ir].inBounds_ << " edgeU " << m.xings_[ir].dEdgeU_ << " edgeV " << m.xings_[ir].dEdgeV_ << " edgeSig " << m.xings_[ir].edgeSig_ << " truth " << mc.recoXingTruth_[ir] << " nbr " << mc.recoXingNeighbor_[ir]; for(auto const& xm : mc.xings_) - log << "\n true shield " << xm.sector_ << " gen " << int(xm.generation_) << " geom " << xm.geom_ << " edep " << xm.edep_ + log << "\n true shield " << xm.sector_ << " gen " << int(xm.rel_.removal()) << " geom " << xm.geom_ << " edep " << xm.edep_ << " layers " << int(xm.nLayers_) << " edgeU " << xm.dEdgeU_ << " edgeV " << xm.dEdgeV_ << " recoXing " << xm.recoXing_ << " cluster " << xm.trueCluster_; // pulls of own-cluster geometric candidates: matcher residuals, and the raw-error track against the true crossing for(auto const& xm : mc.xings_) { - if(xm.generation_ != 0 || !xm.geom_ || xm.trueCand_ < 0) continue; + if(xm.rel_ != MCRelationship::same || !xm.geom_ || xm.trueCand_ < 0) continue; auto const& c = m.cands_[xm.trueCand_]; if(!c.hasFlag(TrkCrvCandidate::geomCand) || c.xing_ < 0) continue; if(xm.sector_ < 0 || static_cast(xm.sector_) >= sectors_.size() || !sectors_[xm.sector_].valid) continue; diff --git a/MCDataProducts/inc/MCRelationship.hh b/MCDataProducts/inc/MCRelationship.hh index 30d2df0604..cdc55c6307 100644 --- a/MCDataProducts/inc/MCRelationship.hh +++ b/MCDataProducts/inc/MCRelationship.hh @@ -34,6 +34,8 @@ namespace mu2e { bool operator !=(relation rval) const { return _rel != rval; } // trivial constructor MCRelationship(relation rval=none) : _rel(rval), _rem(-1) {} + // from a relation and its removal, when the caller has walked the genealogy itself + MCRelationship(relation rval, int8_t rem) : _rel(rval), _rem(rem) {} // construct from SimParticles MCRelationship(SPPtr const& sppi,SPPtr const& sppj); // construct from StrawDigiMCs diff --git a/MCDataProducts/inc/TrkCrvMatchMC.hh b/MCDataProducts/inc/TrkCrvMatchMC.hh index f387efdb3f..8a9ce5036a 100644 --- a/MCDataProducts/inc/TrkCrvMatchMC.hh +++ b/MCDataProducts/inc/TrkCrvMatchMC.hh @@ -17,12 +17,13 @@ namespace mu2e { - // one true crossing of a CRV sector by the track's particle (generation 0) or one of its ancestors (sim_); the + // one true crossing of a CRV sector by the track's particle or one of its ancestors (sim_); the // position, direction, time and momentum are those of sim_'s MC trajectory at the sector mid-plane struct TrkCrvXingMC { SurfaceId sid_; // sector surface, as the reco crossings int16_t sector_ = -1; // CRSScintillatorShield index - uint8_t generation_ = 0; // 0 = the track's particle, 1 = its parent, ... + MCRelationship rel_; // sim_ relative to the track's particle: same, mother (its parent) or umother (further + // up); removal() counts the generations, not counting simulation-stage copies art::Ptr sim_; // the crossing particle bool geom_ = false; // sim_'s trajectory crosses the sector mid-plane rectangle (gap-inclusive) XYZVectorF pos_; // sim_'s trajectory at the mid-plane, detector frame [mm] (geom_ only) From f24602b5b6e817b1fb2ac77b6f1f5ab3d0dd9283 Mon Sep 17 00:00:00 2001 From: Rob Mina Date: Fri, 6 Nov 2026 18:17:14 -0600 Subject: [PATCH 4/4] TrkCrvMatchMCMaker: stage-aware MCRelationship for candidate deposits (ancestors and siblings simulated in an earlier stage). --- CRVResponse/src/TrkCrvMatchMCMaker_module.cc | 56 ++++++++++++++++---- 1 file changed, 47 insertions(+), 9 deletions(-) diff --git a/CRVResponse/src/TrkCrvMatchMCMaker_module.cc b/CRVResponse/src/TrkCrvMatchMCMaker_module.cc index e580183874..3fc3ec34f3 100644 --- a/CRVResponse/src/TrkCrvMatchMCMaker_module.cc +++ b/CRVResponse/src/TrkCrvMatchMCMaker_module.cc @@ -52,6 +52,30 @@ namespace mu2e { return MCRelationship(gen == 1 ? MCRelationship::mother : MCRelationship::umother, static_cast(gen)); } + // MCRelationship of particle i to particle j (the convention of MCRelationship(i, j)) from their origin chains: one + // entry per generation, the particle itself first, each entry the earliest simulation-stage copy of that + // generation's particle. MCRelationship(i, j) walks the Ptrs, in which a particle simulated in several stages + // appears as a different copy depending on the path, so an ancestor's or a sibling's relation can be lost. + using SimChain = std::vector>; + inline MCRelationship stageAwareRelation(SimChain const& ci, SimChain const& cj) { + if(ci.empty() || cj.empty()) return MCRelationship(); + if(ci[0] == cj[0]) return MCRelationship(MCRelationship::same, 0); + auto at = [](SimChain const& c, art::Ptr const& p) { + auto it = std::find(c.begin(), c.end(), p); + return it == c.end() ? -1 : static_cast(std::distance(c.begin(), it)); + }; + int n = at(cj, ci[0]); // i is an ancestor of j + if(n > 0) return MCRelationship(n == 1 ? MCRelationship::mother : MCRelationship::umother, static_cast(n)); + n = at(ci, cj[0]); // i is a descendant of j + if(n > 0) return MCRelationship(n == 1 ? MCRelationship::daughter : MCRelationship::udaughter, static_cast(n)); + if(ci.size() > 1 && cj.size() > 1 && ci[1] == cj[1]) return MCRelationship(MCRelationship::sibling, 1); + for(size_t ii = 1; ii < ci.size(); ++ii) { // nearest common ancestor + int jj = at(cj, ci[ii]); + if(jj > 0) return MCRelationship(MCRelationship::usibling, static_cast(ii + jj)); + } + return MCRelationship(); + } + class TrkCrvMatchMCMaker : public art::EDProducer { public: struct Config { @@ -168,6 +192,23 @@ namespace mu2e { auto inTrackCollection = [&](art::Ptr const& q) { return (q.isNonnull() && spH->has(cet::map_vector_key(q.key()))) ? art::Ptr(spH, q.key()) : art::Ptr(); }; + // origin chain of a particle (see stageAwareRelation), cached per event + std::map chainCache; + auto originChain = [&](art::Ptr const& q) -> SimChain const& { + auto [it, isNew] = chainCache.try_emplace(q.isNonnull() ? q.key() : size_t(-1)); + if(!isNew || q.isNull()) return it->second; + art::Ptr p = inTrackCollection(q); + for(int i = 0; i < 1000 && p.isNonnull(); ++i) { + for(int k = 0; k < 100 && p->selfParent(); ++k) { + auto pp = inTrackCollection(p->parent()); + if(pp.isNull()) break; + p = pp; + } + it->second.push_back(p); + p = inTrackCollection(p->parent()); + } + return it->second; + }; auto out = std::make_unique(); for(size_t imatch = 0; imatch < mH->size(); ++imatch) { @@ -306,11 +347,9 @@ namespace mu2e { } } - // candidate clusters: the closest MCRelationship of their deposit particles to the track's particle. A particle - // simulated in several stages has a copy per stage (self-parent chain), and a deposit can point at any of them, - // so each deposit is compared with every copy of the track's particle and the closest relation is kept - std::vector> trackSelves; - for(auto const& [sp, g] : lineage) if(g == 0) trackSelves.push_back(sp); + // candidate clusters: the closest MCRelationship of their deposit particles to the track's particle, with + // simulation-stage copies treated as one particle at every generation (stageAwareRelation) + SimChain const trackChain = originChain(trackSim); if(!m.cands_.empty() && m.cands_.front().cluster_.id() != clusterPid && !ccmc.empty()) mf::LogWarning("TrkCrvMatchMCMaker") << "cluster MC associations are over a different cluster collection than the matcher used"; for(size_t ic = 0; ic < m.cands_.size(); ++ic) { @@ -321,16 +360,15 @@ namespace mu2e { for(auto const& pi : it->second->GetPulses()) { if(pi._energyDeposited <= 0) continue; auto q = inTrackCollection(pi._simParticle); - MCRelationship r; - for(auto const& self : trackSelves) { MCRelationship rs(q, self); if(r < rs) r = rs; } + MCRelationship r = q.isNonnull() ? stageAwareRelation(originChain(q), trackChain) : MCRelationship(); if(diag_ > 1) { mf::LogInfo dl("TrkCrvMatchMCMaker"); dl << "event " << event.id() << " track " << m.track_.key() << " cand " << ic << " deposit sim " << (pi._simParticle.isNonnull() ? std::to_string(pi._simParticle.id().value()) + ":" + std::to_string(pi._simParticle.key()) : std::string("null")) << " in track collection " << q.isNonnull(); if(q.isNonnull()) dl << " stage " << q->simStage() << " selfParent " << q->selfParent(); - dl << " rel " << int(r.relationship()) << "/" << int(r.removal()) << " | track copies"; - for(auto const& self : trackSelves) dl << " " << self.id().value() << ":" << self.key() << "(stage " << self->simStage() << ")"; + dl << " rel " << int(r.relationship()) << "/" << int(r.removal()) << " | track origin chain"; + for(auto const& g : trackChain) dl << " " << g.key() << "(stage " << g->simStage() << ")"; } cm.edepTotal_ += pi._energyDeposited; if(r == MCRelationship::same) cm.edepSame_ += pi._energyDeposited;