From e27cd7fa69b50da2cb6833552a44e9550d9f6791 Mon Sep 17 00:00:00 2001 From: Rob Mina Date: Fri, 30 Oct 2026 06:28:46 -0500 Subject: [PATCH 1/3] Refactor track extrapolation. --- Mu2eKinKal/CMakeLists.txt | 14 + Mu2eKinKal/inc/ExtrapolateCRVRegion.hh | 154 ---- Mu2eKinKal/inc/ExtrapolateCylinders.hh | 104 --- Mu2eKinKal/inc/ExtrapolateIPA.hh | 91 --- Mu2eKinKal/inc/ExtrapolatePlanes.hh | 89 --- Mu2eKinKal/inc/ExtrapolateST.hh | 148 ---- Mu2eKinKal/inc/ExtrapolateSurface.hh | 51 -- Mu2eKinKal/inc/ExtrapolateSweep.hh | 513 ++++++++++++ .../inc/ExtrapolateToTrackerPerimeter.hh | 76 -- Mu2eKinKal/inc/ExtrapolateToZ.hh | 56 -- Mu2eKinKal/inc/KKExtrap.hh | 747 ++++++++--------- Mu2eKinKal/inc/KKFit.hh | 25 +- Mu2eKinKal/inc/KKShellXing.hh | 27 +- Mu2eKinKal/inc/KKTrack.hh | 16 +- Mu2eKinKal/src/CentralHelixFit_module.cc | 7 +- Mu2eKinKal/src/ExtrapolateSweepTest_main.cc | 751 ++++++++++++++++++ Mu2eKinKal/src/KinematicLineFit_module.cc | 10 +- Mu2eKinKal/src/SConscript | 11 + RecoDataProducts/inc/TrkFitFlag.hh | 2 + RecoDataProducts/src/TrkFitFlag.cc | 2 + 20 files changed, 1676 insertions(+), 1218 deletions(-) delete mode 100644 Mu2eKinKal/inc/ExtrapolateCRVRegion.hh delete mode 100644 Mu2eKinKal/inc/ExtrapolateCylinders.hh delete mode 100644 Mu2eKinKal/inc/ExtrapolateIPA.hh delete mode 100644 Mu2eKinKal/inc/ExtrapolatePlanes.hh delete mode 100644 Mu2eKinKal/inc/ExtrapolateST.hh delete mode 100644 Mu2eKinKal/inc/ExtrapolateSurface.hh create mode 100644 Mu2eKinKal/inc/ExtrapolateSweep.hh delete mode 100644 Mu2eKinKal/inc/ExtrapolateToTrackerPerimeter.hh delete mode 100644 Mu2eKinKal/inc/ExtrapolateToZ.hh create mode 100644 Mu2eKinKal/src/ExtrapolateSweepTest_main.cc diff --git a/Mu2eKinKal/CMakeLists.txt b/Mu2eKinKal/CMakeLists.txt index 81492a8cf7..09160ac6c1 100644 --- a/Mu2eKinKal/CMakeLists.txt +++ b/Mu2eKinKal/CMakeLists.txt @@ -102,6 +102,20 @@ cet_build_plugin(KKTruthSeed art::module Offline::TrkReco ) +cet_make_exec(NAME ExtrapolateSweepTest + SOURCE src/ExtrapolateSweepTest_main.cc + LIBRARIES + KinKal::Fit + KinKal::Detector + KinKal::Trajectory + KinKal::Geometry + KinKal::MatEnv + KinKal::General + Offline::DataProducts + ROOT::MathCore + ROOT::GenVector +) + configure_file(${CMAKE_CURRENT_SOURCE_DIR}/data/TrainBkgFinal.dat ${CURRENT_BINARY_DIR} data/TrainBkgFinal.dat COPYONLY) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/data/TrainBkgSeed.dat ${CURRENT_BINARY_DIR} data/TrainBkgSeed.dat COPYONLY) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/data/TrainBkgTrigger.dat ${CURRENT_BINARY_DIR} data/TrainBkgTrigger.dat COPYONLY) diff --git a/Mu2eKinKal/inc/ExtrapolateCRVRegion.hh b/Mu2eKinKal/inc/ExtrapolateCRVRegion.hh deleted file mode 100644 index c0e7ee8c10..0000000000 --- a/Mu2eKinKal/inc/ExtrapolateCRVRegion.hh +++ /dev/null @@ -1,154 +0,0 @@ -// Predicate to extrapolate through the CRV region, crossing BOTH the CRV sector planes AND the -// per-sector aluminium strongback (passive) planes in ONE interleaved, time-ordered pass. -// -// WHY THIS EXISTS -// Each CRV module has a thin (~12.7 mm) Al strongback on the tracker-facing side of its scintillator -// stack. The sector (veto) plane is modeled at the stack center, so the strongback plane sits ~60 mm -// (about a stack half-thickness) toward the tracker from it; going outward the surfaces alternate -// strongback -> sector for every module. KinKal xings can only be ADDED at the trajectory front/back (an interior xing cannot -// be inserted), so these surfaces must be crossed in strict spatial/time order. The previous code -// crossed them in two SEPARATE passes -- all strongbacks (ExtrapolatePlanes), then all sectors -// (ExtrapolateCRV). In a STACKED-sector geometry (the extracted KPP modules EX/T1/T2 sit ~150 mm -// apart in y) the strongback pass advanced the trajectory front PAST the lower sectors, leaving -// them stranded in the interior where they could no longer be added -- CRV_T1 was lost on every -// track, and EX/T2 were under-counted. Searching both surface types together, this predicate stops -// the extrapolation at the NEXT crossing of EITHER type, so the KKExtrap loop adds them strictly -// outward (T1_SB -> T1 -> EX_SB -> EX -> ...) and nothing is stranded. -// -// RUN-2 SAFETY: run-2 geometry presents at most one CRV sector (and its one strongback) per -// extrapolation direction, so the outward order is unchanged (strongback then sector) and no -// stacking occurs. Concrete passive planes are NOT handled here (they stay in -// extrapolatePassiveMaterial); only the CRV strongbacks are merged with the sectors. Sectors and -// strongback planes share the same minvnorm floor (a near-zero guard against the normvel divide in -// time_to_sector, not a physics cut): grazing incidence is not pre-filtered by a velocity threshold, -// it is left to fail at the actual surface intersection (newinter.good()), same as any other surface. -#ifndef Mu2eKinKal_ExtrapolateCRVRegion_hh -#define Mu2eKinKal_ExtrapolateCRVRegion_hh -#include "KinKal/General/TimeDir.hh" -#include "KinKal/General/TimeRange.hh" -#include "KinKal/Geometry/Intersection.hh" -#include "KinKal/Geometry/Rectangle.hh" -#include "KinKal/Geometry/ParticleTrajectoryIntersect.hh" -#include "Offline/KinKalGeom/inc/CRV.hh" -#include "Offline/KinKalGeom/inc/KinKalGeom.hh" -#include -#include -#include -#include -namespace mu2e { - using KinKal::TimeDir; - using KinKal::TimeRange; - using KKGeom::CRV; - using KinKal::Intersection; - using KinKal::timeDirSign; - class ExtrapolateCRVRegion { - public: - using CRVSV = std::vector; - using MaterialPlane = KinKalGeom::PassiveMaterialPlane; - using MaterialPlaneCollection = std::vector; - // a crossing of either a CRV sector or a strongback passive plane - struct RegionXing { - Intersection inter_; - bool isSector_ = false; - int sectorIdx_ = -1; // index into sectors_ (sector crossings) - double whw_ = 0; // sector module half-width (sector crossings) - MaterialPlane const* plane_ = nullptr; // the strongback plane (plane crossings) - RegionXing() {} - RegionXing(Intersection const& inter, int isect, double whw) : - inter_(inter), isSector_(true), sectorIdx_(isect), whw_(whw) {} - RegionXing(Intersection const& inter, MaterialPlane const& plane) : - inter_(inter), isSector_(false), plane_(&plane) {} - }; - using RegionXingCollection = std::vector; - struct sortXings { // sort in the extrapolation time direction - TimeDir tdir_; - bool operator () (RegionXing const& a, RegionXing const& b) { - return tdir_ == TimeDir::forwards ? a.inter_.time_ < b.inter_.time_ : a.inter_.time_ > b.inter_.time_; - } - sortXings(TimeDir tdir) : tdir_(tdir) {} - }; - - ExtrapolateCRVRegion(double maxdt, double maxdtstep, double dptol, double intertol, - double minv, CRV const& crv, MaterialPlaneCollection const& planes, int debug=0) : - maxDt_(maxdt), maxDtStep_(maxdtstep), dptol_(dptol), intertol_(intertol), - minvnorm_(minv), debug_(debug), sectors_(crv.sectors()), planes_(planes) {} - double maxDt() const { return maxDt_; } - double maxDtStep() const { return maxDtStep_; } - double dpTolerance() const { return dptol_; } - double interTolerance() const { return intertol_; } - auto const& sectors() const { return sectors_; } - auto const& sector(size_t isect) const { return sectors_[isect]; } - auto const& intersections() const { return inters_; } - int debug() const { return debug_; } - void reset() const { inters_.clear(); } - template bool needsExtrapolation(KinKal::ParticleTrajectory const& fittraj, TimeDir tdir) const; - private: - double maxDt_ = -1; - double maxDtStep_ = -1; - double dptol_ = 1e10; - double intertol_ = 1e10; - double minvnorm_ = 1e-5; - int debug_ = 0; - CRVSV sectors_; - MaterialPlaneCollection const& planes_; - mutable RegionXingCollection inters_; - }; - - template bool ExtrapolateCRVRegion::needsExtrapolation(KinKal::ParticleTrajectory const& fittraj, TimeDir tdir) const { - // Stop the extrapolation at the NEXT crossing of any CRV sector OR strongback plane. The - // KKExtrap loop adds whichever crossing(s) this piece produced (time-sorted, outermost first) - // then re-extrapolates, so the surfaces are crossed strictly outward and none is left interior. - bool retval(false); - reset(); - auto const& ktraj = tdir == TimeDir::forwards ? fittraj.back() : fittraj.front(); - static const double epsilon(1.0e-6); - static const double coincidenttol(1.0e-3); // ns; crossings closer than this are the same physical point (a seam) - auto stime = tdir == TimeDir::forwards ? ktraj.range().begin()+epsilon : ktraj.range().end()-epsilon; - auto etime = tdir == TimeDir::forwards ? ktraj.range().end() : ktraj.range().begin(); - TimeRange trange(stime,etime,false); - auto pos = ktraj.position3(stime); - auto vel = ktraj.velocity(stime); - double piece_span = fabs(stime - etime); - // helper: has a crossing at this time already been cached (a coplanar seam)? - auto coincident = [&](double t){ for(auto const& p : inters_) if(fabs(p.inter_.time_ - t) < coincidenttol) return true; return false; }; - // --- CRV sectors --- - for(size_t isect = 0; isect < sectors_.size(); ++isect ){ - auto const& sector = sectors_[isect]; - double normvel = vel.Dot(sector.sector_->normal())*timeDirSign(tdir); - double signed_perp = (sector.sector_->center()-pos).Dot(sector.sector_->normal()); - double time_to_sector = signed_perp / normvel; - // skip planes already behind this piece's evaluation point (already crossed/added); grazing - // incidence is not pre-filtered here, it is left to fail at the intersection attempt below - if(fabs(normvel) < minvnorm_ || time_to_sector < 0 )continue; - auto newinter = KinKal::intersect(fittraj,*sector.sector_,trange,intertol_,tdir); - if(newinter.good()){ - if(!coincident(newinter.time_)) inters_.emplace_back(newinter,(int)isect,sector.whw_); - } else if(newinter.onsurface_ && newinter.inbounds_) { - retval |= trange.beyond(newinter.time_,tdir); // crossing just beyond this piece: keep extrapolating - } else if(!newinter.onsurface_) { - // far sector beyond this (short) piece: keep going, in BOTH time directions. - if(time_to_sector > piece_span) retval = true; - } - } - // --- strongback passive planes (minvnorm floor, like ExtrapolatePlanes) --- - for(auto const& plane : planes_){ - double normvel = vel.Dot(plane.surface_->normal())*timeDirSign(tdir); - double signed_perp = (plane.surface_->center()-pos).Dot(plane.surface_->normal()); - double time_to_plane = signed_perp / normvel; - if(fabs(normvel) < minvnorm_ || time_to_plane < 0 )continue; - auto newinter = KinKal::intersect(fittraj,*plane.surface_,trange,intertol_,tdir); - if(newinter.good()){ - if(!coincident(newinter.time_)) inters_.emplace_back(newinter,plane); - } else if(newinter.onsurface_ && newinter.inbounds_) { - retval |= trange.beyond(newinter.time_,tdir); - } else if(!newinter.onsurface_) { - if(time_to_plane > piece_span) retval = true; // as in the sector loop above - } - } - // sort the crossings in the time direction so the KKExtrap loop adds them outermost-first - std::sort(inters_.begin(),inters_.end(),sortXings(tdir)); - if(!inters_.empty()) return false; // stop: this piece crossed the CRV region; record now - return retval; - } -} -#endif diff --git a/Mu2eKinKal/inc/ExtrapolateCylinders.hh b/Mu2eKinKal/inc/ExtrapolateCylinders.hh deleted file mode 100644 index f64b5e6f03..0000000000 --- a/Mu2eKinKal/inc/ExtrapolateCylinders.hh +++ /dev/null @@ -1,104 +0,0 @@ -// Predicate to extrapolate to the next intersection with passive cylindrical material shells. -#ifndef Mu2eKinKal_ExtrapolateCylinders_hh -#define Mu2eKinKal_ExtrapolateCylinders_hh - -#include "KinKal/General/TimeDir.hh" -#include "KinKal/General/TimeRange.hh" -#include "KinKal/Geometry/Intersection.hh" -#include "KinKal/Geometry/ParticleTrajectoryIntersect.hh" -#include "Offline/KinKalGeom/inc/DetectorSolenoid.hh" -#include "Offline/Mu2eKinKal/inc/ExtrapolateSurface.hh" - -#include -#include -#include -#include -#include - -namespace mu2e { - using KinKal::Intersection; - using KinKal::TimeDir; - using KinKal::TimeRange; - using KinKal::timeDirSign; - - struct CylinderIntersection { - using MaterialCylinder = KKGeom::DetectorSolenoid::MaterialCylinder; - Intersection inter_; - MaterialCylinder const* cylinder_ = nullptr; - CylinderIntersection() {} - CylinderIntersection(Intersection const& inter, MaterialCylinder const& cylinder) : - inter_(inter), cylinder_(&cylinder) {} - }; - - class ExtrapolateCylinders : public ExtrapolateSurface { - public: - using Base = ExtrapolateSurface; - using MaterialCylinder = KKGeom::DetectorSolenoid::MaterialCylinder; - using MaterialCylinderCollection = KKGeom::DetectorSolenoid::MaterialCylinderCollection; - - ExtrapolateCylinders(double maxdt, double maxdtstep, double dptol, double intertol, - double minv, MaterialCylinderCollection const& cylinders, int debug=0) : - Base(maxdt,maxdtstep,dptol,intertol,minv,debug), cylinders_(cylinders) { - for(auto const& cylinder : cylinders_) { - maxRadius_ = std::max(maxRadius_, cylinder.surface_->radius() + 0.5*cylinder.thickness_); - } - } - - template bool needsExtrapolation(KinKal::ParticleTrajectory const& fittraj, TimeDir tdir) const; - - private: - double minShellCosine_ = 0.1; // min |cos(incidence)| to accept a shell crossing (~within 84 deg of normal); - // below this the thin-shell path length blows up (near-tangent), so skip it - MaterialCylinderCollection const& cylinders_; - double maxRadius_ = 0.0; - }; - - template bool ExtrapolateCylinders::needsExtrapolation(KinKal::ParticleTrajectory const& fittraj, TimeDir tdir) const { - reset(); - if(cylinders_.empty()) return false; - auto const& ktraj = tdir == TimeDir::forwards ? fittraj.back() : fittraj.front(); - static const double epsilon(1.0e-6); - if(ktraj.range().range() <= epsilon) return true; - double stime = tdir == TimeDir::forwards ? ktraj.range().begin()+epsilon : ktraj.range().end()-epsilon; - double etime = tdir == TimeDir::forwards ? ktraj.range().end() : ktraj.range().begin(); - // March the shell search across the end piece in BOUNDED sub-windows (capped by maxDtStep) from the - // near end outward, rather than one intersect over the whole piece. The thin concentric shells are - // closely spaced (~960-1315mm), so a single intersect over a piece that spans several of them can - // step over the inner ones (they were under-found, innermost worst). Marching brackets the nearest - // crossings and records them HERE, with no overstep; the KKExtrap loop banks/de-dups and re-extends. - double const sgn = (etime >= stime) ? 1.0 : -1.0; - double const dtwin = (maxDtStep_ > 0.0) ? maxDtStep_ : std::fabs(etime - stime); - double t0 = stime; - while(sgn*(etime - t0) > epsilon) { - // stop once we are outside the shells AND moving further out: any shell is behind us - auto p0 = ktraj.position3(t0); - double const rho0 = std::sqrt(p0.X()*p0.X() + p0.Y()*p0.Y()); - auto v0 = ktraj.velocity(t0); - double const vrho0 = rho0 > 0.0 ? (p0.X()*v0.X() + p0.Y()*v0.Y())/rho0 : 0.0; - if(rho0 > maxRadius_ && vrho0*timeDirSign(tdir) > 0.0) return false; - double const t1 = t0 + sgn*std::min(dtwin, std::fabs(etime - t0)); - TimeRange win = (sgn > 0.0) ? TimeRange(t0,t1,false) : TimeRange(t1,t0,false); - for(auto const& cylinder : cylinders_) { - auto newinter = KinKal::intersect(fittraj,*cylinder.surface_,win,intertol_,tdir); - if(debug_ > 3)std::cout << cylinder.sid_ << " " << newinter << std::endl; - if(newinter.good()) { - double const normvel = std::fabs(newinter.norm_.Dot(newinter.pdir_)); - // thin-shell approximation: skip near-tangent crossings (unbounded path through a finite shell) - if(normvel > std::max(minvnorm_,minShellCosine_)) inters_.emplace_back(newinter,cylinder); - else if(debug_ > 1) std::cout << "Skipping grazing DS material intersection " << cylinder.sid_ - << " normvel " << normvel << std::endl; - } - } - if(!inters_.empty()) { - SortIntersections isort(tdir); - std::sort(inters_.begin(),inters_.end(),isort); - return false; // nearest shell crossing(s) found and recorded here -- no overstep - } - t0 = t1; - } - // reached the piece end with no crossing while still approaching the shells: extend and retry - return true; - } -} - -#endif diff --git a/Mu2eKinKal/inc/ExtrapolateIPA.hh b/Mu2eKinKal/inc/ExtrapolateIPA.hh deleted file mode 100644 index 59eaec42f0..0000000000 --- a/Mu2eKinKal/inc/ExtrapolateIPA.hh +++ /dev/null @@ -1,91 +0,0 @@ -// predicate to extrapolate to the next intersection with the IPA -// track changes direction. -#ifndef Mu2eKinKal_ExtrapolateIPA_hh -#define Mu2eKinKal_ExtrapolateIPA_hh -#include "KinKal/Trajectory/ParticleTrajectory.hh" -#include "KinKal/General/TimeDir.hh" -#include "KinKal/General/TimeRange.hh" -#include "KinKal/Geometry/Intersection.hh" -#include "KinKal/Geometry/Cylinder.hh" -#include "KinKal/Geometry/ParticleTrajectoryIntersect.hh" -#include -#include "cetlib_except/exception.h" -namespace mu2e { - using KinKal::TimeDir; - using KinKal::TimeRange; - using KinKal::Intersection; - class ExtrapolateIPA { - public: - using CylPtr = std::shared_ptr; - - ExtrapolateIPA(double maxdt, double maxdtstep, double dptol,double intertol, CylPtr const& ipa, int debug=0) : - maxDt_(maxdt), maxDtStep_(maxdtstep), dptol_(dptol), intertol_(intertol), ipa_(ipa), - zmin_( (ipa_->center() - ipa_->axis()*ipa_->halfLength()).Z()), - zmax_( (ipa_->center() + ipa_->axis()*ipa_->halfLength()).Z()), debug_(debug) {} - // interface for extrapolation - double maxDt() const { return maxDt_; } - double maxDtStep() const { return maxDtStep_; } - double dpTolerance() const { return dptol_; } - double interTolerance() const { return intertol_; } - CylPtr const& IPACylinder() const { return ipa_; } - auto const& intersection() const { return inter_; } - double zmin() const { return zmin_; } - double zmax() const { return zmax_; } - double zmid() const { return 0.5*(zmin_+zmax_); } - int debug() const { return debug_; } - // extrapolation predicate: the track will be extrapolated until this predicate returns false, subject to the maximum time - template bool needsExtrapolation(KinKal::ParticleTrajectory const& fittraj, TimeDir tdir) const; - // reset between tracks - void reset() const { inter_ = Intersection(); } - private: - double maxDt_ = -1; // maximum extrapolation time - double maxDtStep_ = -1; // maximum extrapolation time step in a single iteration - double dptol_ = 1e10; // fractional momentum tolerance - double intertol_ = 1e10; // intersection tolerance (mm) - CylPtr ipa_; // IPA cylinder - mutable Intersection inter_; // cache of most recent intersection - // cache of IPA front and back Z positions - double zmin_ = std::numeric_limits::max(); - double zmax_ = std::numeric_limits::lowest(); - int debug_ = 0; // debug level - }; - - template bool ExtrapolateIPA::needsExtrapolation(KinKal::ParticleTrajectory const& fittraj, TimeDir tdir) const { - // we are answering the question: did the segment last added to this extrapolated trajectory hit the IPA or not? - // if so, stop extrapolating (for now). If not, and if we're still inside or heading towards the IPA, keep going, otherwise stop - reset(); // clear any cache - bool retval(true); // by default keep going - auto const& ktraj = tdir == TimeDir::forwards ? fittraj.back() : fittraj.front(); // most recently added segment - // add a small buffer to the test range to prevent re-intersection with the same piece - static const double epsilon(1e-7); // small step to avoid re-intersecting - if(ktraj.range().range() <= epsilon) return true; // keep going if the step is very small - auto trange = tdir == TimeDir::forwards ? - TimeRange(ktraj.range().begin()+epsilon, ktraj.range().end()) : - TimeRange(ktraj.range().begin(), ktraj.range().end()-epsilon); - auto spos = ktraj.position3(trange.begin()); - auto epos = ktraj.position3(trange.end()); - // if either end of the segment is inside the z range of the IPA, test for an in-range interestection - if( (spos.Z() > zmin_ && spos.Z() < zmax_) || (epos.Z() > zmin_ && epos.Z() < zmax_) ){ - Intersection newinter = KinKal::intersect(ktraj,*ipa_,trange,intertol_,tdir); - if(debug_ > 2)std::cout << "IPA " << newinter << std::endl; - if(newinter.good()){ - // update the cache - inter_ = newinter; - if(debug_ > 0)std::cout << "Good IPA " << newinter << ", Stopping " << std::endl; - retval = false; - } - } else { - // otherwise, if the trajectory is heading towards the IPA keep going - auto vel = ktraj.velocity(trange.end())*timeDirSign(tdir); // sign velocity by extrapolation direction - double vb = vel.Dot(ktraj.bnom().Unit()); // project along the BField axis. This is insensitive to reflection. - if( (epos.Z() > zmax_ && vb < 0) || (epos.Z() < zmin_ && vb > 0) ) { - if(debug_ > 1)std::cout << "Extrapolating towards IPA, z " << epos.Z() << " bvel " << vb << std::endl; - } else { - retval = false; - if(debug_ > 1)std::cout << "Heading away from IPA, z " << epos.Z() << " bvel " << vb << std::endl; - } - } - return retval; - } -} -#endif diff --git a/Mu2eKinKal/inc/ExtrapolatePlanes.hh b/Mu2eKinKal/inc/ExtrapolatePlanes.hh deleted file mode 100644 index d064853a99..0000000000 --- a/Mu2eKinKal/inc/ExtrapolatePlanes.hh +++ /dev/null @@ -1,89 +0,0 @@ -// Predicate to extrapolate to the next intersection with passive planar material shells. -#ifndef Mu2eKinKal_ExtrapolatePlanes_hh -#define Mu2eKinKal_ExtrapolatePlanes_hh - -#include "KinKal/General/TimeDir.hh" -#include "KinKal/General/TimeRange.hh" -#include "KinKal/Geometry/Intersection.hh" -#include "KinKal/Geometry/ParticleTrajectoryIntersect.hh" -#include "Offline/KinKalGeom/inc/KinKalGeom.hh" -#include "Offline/Mu2eKinKal/inc/ExtrapolateSurface.hh" - -#include -#include -#include -#include - -namespace mu2e { - using KinKal::Intersection; - using KinKal::TimeDir; - using KinKal::TimeRange; - using KinKal::timeDirSign; - - struct PlaneIntersection { - using MaterialPlane = KinKalGeom::PassiveMaterialPlane; - Intersection inter_; - MaterialPlane const* plane_ = nullptr; - PlaneIntersection() {} - PlaneIntersection(Intersection const& inter, MaterialPlane const& plane) : - inter_(inter), plane_(&plane) {} - }; - - class ExtrapolatePlanes : public ExtrapolateSurface { - public: - using Base = ExtrapolateSurface; - using MaterialPlane = KinKalGeom::PassiveMaterialPlane; - using MaterialPlaneCollection = KinKalGeom::PassiveMaterialPlaneCollection; - - ExtrapolatePlanes(double maxdt, double maxdtstep, double dptol, double intertol, - double minv, MaterialPlaneCollection const& planes, int debug=0) : - Base(maxdt,maxdtstep,dptol,intertol,minv,debug), planes_(planes) {} - - template bool needsExtrapolation(KinKal::ParticleTrajectory const& fittraj, TimeDir tdir) const; - - private: - MaterialPlaneCollection const& planes_; - }; - - template bool ExtrapolatePlanes::needsExtrapolation(KinKal::ParticleTrajectory const& fittraj, TimeDir tdir) const { - reset(); - if(planes_.empty()) return false; - auto const& ktraj = tdir == TimeDir::forwards ? fittraj.back() : fittraj.front(); - static const double epsilon(1.0e-6); - if(ktraj.range().range() <= epsilon) return true; - auto stime = tdir == TimeDir::forwards ? ktraj.range().begin()+epsilon : ktraj.range().end()-epsilon; - auto etime = tdir == TimeDir::forwards ? ktraj.range().end() : ktraj.range().begin(); - TimeRange trange(stime,etime,false); - auto pos = ktraj.position3(stime); - auto vel = ktraj.velocity(stime); - double piece_span = std::fabs(stime - etime); - bool keepGoing = false; - for(auto const& plane : planes_) { - double normvel = vel.Dot(plane.surface_->normal())*timeDirSign(tdir); - double pdist = (plane.surface_->center()-pos).Dot(plane.surface_->normal()); - if(debug_ > 4)std::cout << "Passive plane extrap " << plane.sid_ << " normvel " << normvel << " pdist " << pdist << std::endl; - if(std::fabs(normvel) < minvnorm_) continue; - if(pdist*normvel < 0.0) continue; - auto newinter = KinKal::intersect(fittraj,*plane.surface_,trange,intertol_,tdir); - if(debug_ > 3)std::cout << plane.sid_ << " " << newinter << std::endl; - if(newinter.good()) { - inters_.emplace_back(newinter,plane); - } else if(newinter.onsurface_ && newinter.inbounds_) { - keepGoing |= trange.beyond(newinter.time_,tdir); - } else if(!newinter.onsurface_ && tdir == TimeDir::backwards) { - // a far plane beyond this (short) piece: the range-bounded stepIntersect can't reach it, so - // use the analytic ray estimate (pdist/normvel) to keep marching outward (mirrors - // ExtrapolateCRVRegion). This lets a tight KinematicLine-tail seed reach the concrete plane - // instead of overshooting it (and the CRV) to maxDt. - if(pdist/normvel > piece_span) keepGoing = true; - } - } - SortIntersections isort(tdir); - std::sort(inters_.begin(),inters_.end(),isort); - // stop as soon as a crossing is cached so the KKExtrap loop records it HERE (no overshoot) - if(!inters_.empty()) return false; - return keepGoing; - } -} - -#endif diff --git a/Mu2eKinKal/inc/ExtrapolateST.hh b/Mu2eKinKal/inc/ExtrapolateST.hh deleted file mode 100644 index 8ed09a8808..0000000000 --- a/Mu2eKinKal/inc/ExtrapolateST.hh +++ /dev/null @@ -1,148 +0,0 @@ -// predicate to extrapolate to foils in the ST -// track changes direction. -#ifndef Mu2eKinKal_ExtrapolateST_hh -#define Mu2eKinKal_ExtrapolateST_hh -#include "Offline/Mu2eKinKal/inc/KKTrack.hh" -#include "KinKal/General/TimeDir.hh" -#include "KinKal/General/TimeRange.hh" -#include "KinKal/Geometry/Intersection.hh" -#include "KinKal/Geometry/ParticleTrajectoryIntersect.hh" -#include "Offline/KinKalGeom/inc/StoppingTarget.hh" -#include "cetlib_except/exception.h" -#include -#include -#include -namespace mu2e { - using KKGeom::StoppingTarget; - using KinKal::TimeDir; - using KinKal::TimeRange; - using KinKal::Annulus; - using KinKal::Intersection; - using AnnPtr = std::shared_ptr; - using FoilCol = std::vector; - using CylPtr = std::shared_ptr; - class ExtrapolateST { - public: - ExtrapolateST(double maxdt, double maxdtstep, double dptol, double intertol, StoppingTarget const& stoptarg, int debug=0) : - maxDt_(maxdt), maxDtStep_(maxdtstep), dptol_(dptol), intertol_(intertol), - zmin_( (stoptarg.outer().center() - stoptarg.outer().axis()*stoptarg.outer().halfLength()).Z()), - zmax_( (stoptarg.outer().center() + stoptarg.outer().axis()*stoptarg.outer().halfLength()).Z()), - rmin_( stoptarg.inner().radius()), rmax_(stoptarg.outer().radius()), - foils_(stoptarg.foils()),debug_(debug) {} - // interface for extrapolation - double maxDt() const { return maxDt_; } - double maxDtStep() const { return maxDtStep_; } - double dpTolerance() const { return dptol_; } - double interTolerance() const { return intertol_; } - double zmin() const { return zmin_; } - double zmax() const { return zmax_; } - double zmid() const { return 0.5*(zmin_+zmax_); } - double rmin() const { return rmin_; } - double rmax() const { return rmax_; } - auto const& foils () const { return foils_; } - auto const& intersection() const { return inter_; } - auto const& foil() const { return ann_; } - auto const& foilId() const { return sid_; } - int debug() const { return debug_; } - // extrapolation predicate: the track will be extrapolated until this predicate returns false, subject to the maximum time - template bool needsExtrapolation(KinKal::ParticleTrajectory const& fittraj, TimeDir tdir) const; - // reset between tracks - void reset() const { inter_ = Intersection(); sid_ = SurfaceId(); ann_ = AnnPtr();} - // find the foils bounded by a set of z positions in a given z direction - void boundedFoils(double spos, double epos, double zdir, std::vector& foils) const; - private: - double maxDt_ = -1; // maximum extrapolation time - double maxDtStep_ = -1; // maximum extrapolation time step in a single iteration - double dptol_ = 1e10; // fractional momentum tolerance - double intertol_ = 1e10; // intersection tolerance (mm) - mutable Intersection inter_; // cache of most recent intersection - mutable SurfaceId sid_; // cache of most recent intersection foil SID - mutable AnnPtr ann_; // cache of most recent intersection foil surface - // cache of front and back Z positions - double zmin_ = std::numeric_limits::max(); - double zmax_ = std::numeric_limits::lowest(); - double rmin_ = std::numeric_limits::max(); - double rmax_ = std::numeric_limits::lowest(); - FoilCol foils_; // foils - int debug_ = 0; // debug level - }; - - template bool ExtrapolateST::needsExtrapolation(KinKal::ParticleTrajectory const& fittraj, TimeDir tdir) const { - // we are answering the question: did the segment last added to this extrapolated track hit a foil or not? If so we are done - // extrapolating (for now) and we want to find all the intersections in that piece. If not, and if we're still inside or heading towards the - // ST, keep going. - reset(); // clear any cache - bool retval = true; // by default keep going - auto const& ktraj = tdir == TimeDir::forwards ? fittraj.back() : fittraj.front(); - // add a small buffer to the test range to prevent re-intersection with the same piece - static const double epsilon(1e-7); // small difference to avoid re-intersecting - if(ktraj.range().range() <= epsilon) return true; // keep going if the step is very small - auto trange = tdir == TimeDir::forwards ? - TimeRange(ktraj.range().begin()+epsilon, ktraj.range().end()) : - TimeRange(ktraj.range().begin(), ktraj.range().end()-epsilon); - auto spos = ktraj.position3(trange.begin()); - auto epos = ktraj.position3(trange.end()); - auto vel = ktraj.velocity(trange.begin())*timeDirSign(tdir); // sign velocity by extrapolation direction - if(debug_ > 2)std::cout << "ST extrap tdir " << tdir << " start z " << spos.Z() << " end z " << epos.Z() << " zvel " << vel.Z() << " rho " << spos.Rho() << std::endl; - // rough geometric test - if( (spos.Z() > zmin_ && spos.Z() < zmax_) || (epos.Z() > zmin_ && epos.Z() < zmax_) ) { - double srho = spos.Rho(); - double erho = epos.Rho(); - if( ( srho > rmin_ && srho < rmax_) || (erho > rmin_ && erho < rmax_)){ - // Find foils bounded by the segment Z positions. These are ordered by the trajectory direction, so they can be tested in order - std::vector foils; - boundedFoils(spos.Z(),epos.Z(),vel.Z(),foils); - if(debug_ > 2)std::cout << "Looping on " << foils.size() << " foils " << std::endl; - // loop over foils in the z range of this piece, and find the first intersection by this piece. - for(auto ifoil : foils){ - auto const& foilptr = foils_[ifoil]; - if(debug_ > 2)std::cout << "foil " << ifoil << " z " << foilptr->center().Z() << std::endl; - auto newinter = KinKal::intersect(ktraj,*foilptr,trange,intertol_,tdir); - if(debug_ > 2)std::cout << "ST foil inter " << newinter << std::endl; - if(newinter.good()){ - // update the cache - inter_ = newinter; - ann_ = foils_[ifoil]; - sid_ = SurfaceId(SurfaceIdEnum::ST_Foils,ifoil); - if(debug_ > 0)std::cout << "Good ST foil " << newinter << " sid " << sid_ << std::endl; - retval = false; - break; - } - } - } - } else { - // if the particle is going in the right direction but hasn't yet reached the ST in Z just keep going - double vb = vel.Dot(ktraj.bnom().Unit()); - if( (epos.Z() > zmax_ && vb < 0) || (epos.Z() < zmin_ && vb > 0) ) { - if(debug_ > 1)std::cout << "Extrapolating towards ST, z " << epos.Z() << " bvel " << vb << std::endl; - } else { - retval = false; - if(debug_ > 1)std::cout << "Heading away from ST, z " << epos.Z() << " bvel " << vb << std::endl; - } - } - return retval; - } - - void ExtrapolateST::boundedFoils(double sz, double ez, double zvel, std::vector& foils) const { - double zmin = min(sz,ez); - double zmax = max(sz,ez); - if(zvel > 0.0){ // going forwards in z - for(size_t ifoil=0;ifoil < foils_.size();++ifoil) { - auto const& foilptr = foils_[ifoil]; - if(foilptr->center().Z() > zmin && foilptr->center().Z() < zmax ){ - foils.push_back(ifoil); - } - } - } else { // backwards in z - for(int ifoil = foils_.size()-1;ifoil >= 0; --ifoil){ - auto jfoil = static_cast(ifoil); - auto const& foilptr = foils_[jfoil]; - if(foilptr->center().Z() > zmin && foilptr->center().Z() < zmax ){ - foils.push_back(jfoil); - } - } - } - } - -} -#endif diff --git a/Mu2eKinKal/inc/ExtrapolateSurface.hh b/Mu2eKinKal/inc/ExtrapolateSurface.hh deleted file mode 100644 index a01d5e0e43..0000000000 --- a/Mu2eKinKal/inc/ExtrapolateSurface.hh +++ /dev/null @@ -1,51 +0,0 @@ -// Common scaffolding shared by the surface-crossing extrapolation predicates (ExtrapolateCylinders, -// ExtrapolatePlanes): dt/tolerance bookkeeping, intersection storage, and time-ordering. Each -// predicate's needsExtrapolation search is geometry-specific and NOT shared here: ExtrapolateCylinders -// marches in bounded sub-windows to avoid stepping over closely-spaced concentric shells, while -// ExtrapolatePlanes gates directly on normal velocity/distance over the whole piece. Forcing those two -// search strategies into one shared body would obscure both, so only the bookkeeping below is common. -#ifndef Mu2eKinKal_ExtrapolateSurface_hh -#define Mu2eKinKal_ExtrapolateSurface_hh - -#include "KinKal/General/TimeDir.hh" - -#include - -namespace mu2e { - using KinKal::TimeDir; - - template class ExtrapolateSurface { - public: - using SurfaceIntersectionCollection = std::vector; - - struct SortIntersections { - TimeDir tdir_; - bool operator () (SurfaceIntersection const& lhs, SurfaceIntersection const& rhs) { - return tdir_ == TimeDir::forwards ? lhs.inter_.time_ < rhs.inter_.time_ : lhs.inter_.time_ > rhs.inter_.time_; - } - SortIntersections(TimeDir tdir) : tdir_(tdir) {} - }; - - double maxDt() const { return maxDt_; } - double maxDtStep() const { return maxDtStep_; } - double dpTolerance() const { return dptol_; } - double interTolerance() const { return intertol_; } - auto const& intersections() const { return inters_; } - int debug() const { return debug_; } - void reset() const { inters_.clear(); } - - protected: - ExtrapolateSurface(double maxdt, double maxdtstep, double dptol, double intertol, double minv, int debug) : - maxDt_(maxdt), maxDtStep_(maxdtstep), dptol_(dptol), intertol_(intertol), minvnorm_(minv), debug_(debug) {} - - double maxDt_ = -1; - double maxDtStep_ = -1; - double dptol_ = 1e10; - double intertol_ = 1e10; - double minvnorm_ = 1e-5; - int debug_ = 0; - mutable SurfaceIntersectionCollection inters_; - }; -} - -#endif diff --git a/Mu2eKinKal/inc/ExtrapolateSweep.hh b/Mu2eKinKal/inc/ExtrapolateSweep.hh new file mode 100644 index 0000000000..f28d00b3bc --- /dev/null +++ b/Mu2eKinKal/inc/ExtrapolateSweep.hh @@ -0,0 +1,513 @@ +// Targets and predicate for the KKExtrap sweep: all requested surfaces are searched together from the last processed crossing. +#ifndef Mu2eKinKal_ExtrapolateSweep_hh +#define Mu2eKinKal_ExtrapolateSweep_hh +#include "KinKal/General/TimeDir.hh" +#include "KinKal/General/TimeRange.hh" +#include "KinKal/General/Vectors.hh" +#include "KinKal/Geometry/Intersection.hh" +#include "KinKal/Geometry/ParticleTrajectoryIntersect.hh" +#include "KinKal/Geometry/Annulus.hh" +#include "KinKal/Geometry/Cylinder.hh" +#include "KinKal/Geometry/Plane.hh" +#include "KinKal/Geometry/Rectangle.hh" +#include "KinKal/MatEnv/DetMaterial.hh" +#include "KinKal/Trajectory/ParticleTrajectory.hh" +#include "Offline/DataProducts/inc/SurfaceId.hh" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace mu2e { + using KinKal::TimeDir; + using KinKal::TimeRange; + using KinKal::Intersection; + using KinKal::VEC3; + using KinKal::timeDirSign; + + // one surface the sweep can cross + struct SweepTarget { + enum Effect { record=0, cylshell, ipashell, stfoil, planeshell, crvsector }; // what a crossing adds to the track + enum Reach { radial=0, plane, zplane, zrange, inside }; // when a driving target can still be reached + static constexpr double inf = std::numeric_limits::max(); + Effect effect_ = record; + Reach reach_ = radial; + SurfaceId sid_; + KinKal::Surface const* surf_ = nullptr; // surface to intersect + KinKal::Plane const* pl_ = nullptr; // the same surface as a plane, for plane reach + std::shared_ptr cyl_; // typed surfaces for the material xings + std::shared_ptr ann_; + std::shared_ptr plane_; + std::shared_ptr rect_; + MatEnv::DetMaterial const* mat_ = nullptr; + double thick_ = 0.0; // material thickness (mm) + unsigned maxcross_ = 1; // crossings kept per sweep, 0 for no limit + int group_ = -1; // targets in a group keep only the first crossing of any of them + bool drives_ = true; // keep extending while this target is reachable + bool terminal_ = false; // a crossing ends the sweep + bool inbounds_ = true; // require the crossing inside the surface bounds + bool active_ = true; // initial state; the upstream reflection logic switches targets on and off + double mincos_ = 0.0; // minimum |cos| between the surface normal and the direction at the crossing + double rmax_ = inf; // unreachable beyond this transverse radius when moving outward (mm) + double zval_ = 0.0; // plane z for zplane reach (mm) + double rreg_ = inf, zreglo_ = -inf, zreghi_ = inf; // region for inside and zrange reach (mm) + }; + using SweepTargetCollection = std::vector; + + class ExtrapolateSweep { + public: + struct Crossing { size_t itarget_ = 0; Intersection inter_; }; + ExtrapolateSweep(SweepTargetCollection const& targets, TimeDir tdir, double maxdt, double maxdtstep, double dptol, + double intertol, double minv, int debug) : targets_(targets), tdir_(tdir), maxDt_(maxdt), maxDtStep_(maxdtstep), + dptol_(dptol), intertol_(intertol), minv_(minv), debug_(debug), active_(targets.size()), count_(targets.size(),0), + tlast_(targets.size(),0.0), episodes_(targets.size()), planes_(targets.size(),nullptr), cylinders_(targets.size(),nullptr) { + for(size_t itg = 0; itg < targets_.size(); ++itg){ + active_[itg] = targets_[itg].active_; + planes_[itg] = dynamic_cast(targets_[itg].surf_); + cylinders_[itg] = dynamic_cast(targets_[itg].surf_); + } + } + // interface used by KinKal::Track::extrapolate + double maxDt() const { return maxDt_; } + double maxDtStep() const { return maxDtStep_; } + double dpTolerance() const { return dptol_; } + int debug() const { return debug_; } + // false (stop extending) once a crossing is cached, nothing driving is reachable, or a watched reflection happened + template bool needsExtrapolation(KinKal::ParticleTrajectory const& ptraj, TimeDir tdir) const; + // sweep control + void start(double tcursor) { searched_ = tcursor; found_ = reflected_ = false; } + void limit(double tlimit, bool recordonly) { limited_ = true; tlimit_ = tlimit; recordonly_ = recordonly; } + void unlimit() { limited_ = recordonly_ = false; } + void watchReflection(double vbsign) { vbsign_ = vbsign; reflected_ = false; } + void setActive(size_t itg, bool active) { active_[itg] = active; } + bool isActive(size_t itg) const { return active_[itg]; } + bool hasCrossing() const { return found_; } + bool reflected() const { return reflected_; } + Crossing const& crossing() const { return crossing_; } + SweepTargetCollection const& targets() const { return targets_; } + // mark the cached crossing processed and move the search start to it + void accept(); + private: + bool usable(size_t itg) const; + bool withinReach(size_t itg, VEC3 const& pos, double reach) const; + template bool search(KinKal::ParticleTrajectory const& ptraj, double tend) const; + template bool firstCrossing(KinKal::ParticleTrajectory const& ptraj, KTRAJ const& piece, size_t itg, TimeRange win, Intersection& inter) const; + template bool visitPlaneExtrema(KTRAJ const& piece, KinKal::Plane const& plane, TimeRange const& range, VISIT&& visit) const; + template Intersection planeCrossing(KTRAJ const& piece, KinKal::Plane const& plane, TimeRange const& query) const; + template void ownBoundary(KTRAJ const& piece, SweepTarget const& tg, Intersection& inter) const; + template bool seam(KinKal::ParticleTrajectory const& ptraj, size_t itg, Intersection const& inter) const; + template bool departed(KinKal::ParticleTrajectory const& ptraj, size_t itg, size_t previous, double accepted, double proposed) const; + template bool reachable(KinKal::ParticleTrajectory const& ptraj) const; + SweepTargetCollection const& targets_; + TimeDir tdir_; + double maxDt_, maxDtStep_, dptol_, intertol_, minv_; + int debug_; + std::vector active_; // per target + std::vector count_; // crossings processed per target + std::vector tlast_; // time of the last processed crossing per target + std::vector doneGroups_; // groups whose first crossing is processed + struct SeamEpisode { size_t itarget_; double time_; }; + std::vector> episodes_; // accepted seam episodes per eligible target, including self + std::vector planes_; // per target, the surface as a plane or cylinder when it is one + std::vector cylinders_; + bool limited_ = false, recordonly_ = false; + double tlimit_ = 0.0; + double vbsign_ = 0.0; // sign of the B-parallel velocity to watch for a reflection; 0 to not watch + mutable double searched_ = 0.0; // the trajectory is searched up to this time + mutable bool found_ = false, reflected_ = false; + mutable Crossing crossing_; + static constexpr unsigned maxRootTrials_ = 256; // per target, piece and window + }; + + inline bool ExtrapolateSweep::usable(size_t itg) const { + auto const& tg = targets_[itg]; + if(!active_[itg]) return false; + if(recordonly_ && tg.effect_ != SweepTarget::record) return false; + if(tg.maxcross_ > 0 && count_[itg] >= tg.maxcross_) return false; + if(tg.group_ >= 0 && std::find(doneGroups_.begin(),doneGroups_.end(),tg.group_) != doneGroups_.end()) return false; + return true; + } + + // A trajectory moves at most speed x time, so a surface farther than that from the window start cannot be crossed in it. + inline bool ExtrapolateSweep::withinReach(size_t itg, VEC3 const& pos, double reach) const { + if(planes_[itg]) return std::fabs(planes_[itg]->distance(pos)) <= reach; + if(cylinders_[itg]){ + auto const& cyl = *cylinders_[itg]; + VEC3 rel = pos - cyl.center(); + double along = rel.Dot(cyl.axis()); + double rho = (rel - along*cyl.axis()).R(); + if(std::fabs(rho - cyl.radius()) > reach) return false; + return !targets_[itg].inbounds_ || std::fabs(along) <= cyl.halfLength() + reach; + } + return true; + } + + inline void ExtrapolateSweep::accept() { + if(!found_) return; + auto itg = crossing_.itarget_; + auto const& tg = targets_[itg]; + double time = crossing_.inter_.time_; + ++count_[itg]; + tlast_[itg] = time; + if(tg.group_ >= 0) doneGroups_.push_back(tg.group_); + if((tg.effect_ == SweepTarget::planeshell || tg.effect_ == SweepTarget::crvsector || tg.effect_ == SweepTarget::stfoil) && tg.pl_){ + for(size_t other = 0; other < targets_.size(); ++other){ + auto const& neighbor = targets_[other]; + if(neighbor.effect_ != tg.effect_ || !neighbor.pl_ || neighbor.mat_ != tg.mat_ || neighbor.thick_ != tg.thick_) continue; + if(std::fabs(neighbor.pl_->normal().Dot(tg.pl_->normal())) < 1.0 - 1.0e-12) continue; + if(std::fabs((neighbor.pl_->center()-tg.pl_->center()).Dot(tg.pl_->normal())) > intertol_) continue; + if(!tg.surf_->inBounds(crossing_.inter_.pos_,intertol_) || !neighbor.surf_->inBounds(crossing_.inter_.pos_,intertol_)) continue; + auto& episodes = episodes_[other]; + auto previous = std::find_if(episodes.begin(),episodes.end(),[itg](SeamEpisode const& episode){ return episode.itarget_ == itg; }); + // A later acceptance of the same source supersedes its earlier episode without erasing other planes. + if(previous == episodes.end()) episodes.push_back({itg,time}); + else previous->time_ = time; + } + } + searched_ = time; + found_ = false; + } + + template bool ExtrapolateSweep::needsExtrapolation(KinKal::ParticleTrajectory const& ptraj, TimeDir) const { + found_ = false; + double sgn = tdir_ == TimeDir::forwards ? 1.0 : -1.0; + double tend = tdir_ == TimeDir::forwards ? ptraj.range().end() : ptraj.range().begin(); + if(limited_ && sgn*(tend - tlimit_) > 0.0) tend = tlimit_; + if(search(ptraj,tend)) return false; + if(limited_) return false; + if(vbsign_ != 0.0){ + auto const& ktraj = tdir_ == TimeDir::forwards ? ptraj.back() : ptraj.front(); + double vb = ktraj.velocity(tend).Dot(ktraj.bnom().Unit())*sgn; + if(vb*vbsign_ < 0.0){ + if(debug_ > 1) std::cout << "Sweep: reflection at time " << tend << " z " << ktraj.position3(tend).Z() << std::endl; + reflected_ = true; + return false; + } + } + return reachable(ptraj); + } + + template bool ExtrapolateSweep::visitPlaneExtrema(KTRAJ const& piece, + KinKal::Plane const& plane, TimeRange const& range, VISIT&& visit) const { + double omega = 0.0; + if constexpr(requires { piece.Omega(); }) omega = std::fabs(piece.Omega()); + else if constexpr(requires { piece.omega(); }) omega = std::fabs(piece.omega()); + if(!std::isfinite(omega)) throw std::runtime_error("KKExtrap: nonfinite plane angular frequency"); + if(omega == 0.0) return false; + double sign = tdir_ == TimeDir::forwards ? 1.0 : -1.0; + double pi = std::acos(-1.0), base = sign > 0.0 ? range.begin() : range.end(); + double stop = sign > 0.0 ? range.end() : range.begin(); + double half = base+pi/omega, quarter = base+0.5*pi/omega; + if(!std::isfinite(half) || !std::isfinite(quarter)) + throw std::runtime_error("KKExtrap: nonfinite plane velocity sample time"); + double v0 = plane.normal().Dot(piece.velocity(base)); + double vhalf = plane.normal().Dot(piece.velocity(half)); + double constant = 0.5*(v0+vhalf), cosine = 0.5*(v0-vhalf); + double sine = plane.normal().Dot(piece.velocity(quarter))-constant; + double amplitude = std::hypot(cosine,sine); + if(!std::isfinite(constant) || !std::isfinite(amplitude)) + throw std::runtime_error("KKExtrap: nonfinite plane velocity coefficients"); + if(amplitude == 0.0 || std::fabs(constant) > amplitude) return false; + double phase = std::atan2(sine,cosine), angle = std::acos(std::clamp(-constant/amplitude,-1.0,1.0)); + std::array next; + unsigned index = 0; + double period = 2.0*pi/omega; + for(double solution : {phase-angle,phase+angle}){ + double normalized = std::fmod(sign*solution,2.0*pi); + if(normalized <= 0.0) normalized += 2.0*pi; + next[index++] = base+sign*normalized/omega; + } + unsigned trials = 0; + while(true){ + index = sign*next[0] < sign*next[1] ? 0 : 1; + double time = next[index]; + if(!std::isfinite(time) || sign*(stop-time) <= 0.0) return false; + if(sign*(time-base) <= 0.0) throw std::runtime_error("KKExtrap: plane extremum did not advance"); + if(++trials > maxRootTrials_) throw std::runtime_error("KKExtrap: plane search exceeded extrema budget"); + if(visit(time)) return true; + next[index] = time+sign*period; + if(!std::isfinite(next[index]) || sign*(next[index]-time) <= 0.0) + throw std::runtime_error("KKExtrap: plane extremum did not advance"); + } + } + + template Intersection ExtrapolateSweep::planeCrossing(KTRAJ const& piece, + KinKal::Plane const& plane, TimeRange const& query) const { + auto distance = [&](double time){ + double value = plane.distance(piece.position3(time)); + if(!std::isfinite(value)) throw std::runtime_error("KKExtrap: nonfinite plane distance"); + return value; + }; + auto root = [&](double time){ + Intersection inter; + inter.time_ = time; + inter.pos_ = piece.position3(time); + inter.pdir_ = piece.direction(time); + inter.norm_ = plane.normal(); + inter.onsurface_ = plane.onSurface(inter.pos_,intertol_); + inter.inbounds_ = plane.inBounds(inter.pos_,intertol_); + inter.inrange_ = query.inRange(time) && piece.range().inRange(time); + return inter; + }; + double cursor = tdir_ == TimeDir::forwards ? query.begin() : query.end(); + auto endpointContact = [&](double time){ + auto inter = root(time); + double normalSpeed = std::fabs(plane.normal().Dot(piece.velocity(time))); + return inter.onsurface_ && inter.inrange_ && normalSpeed <= 1.0e-12*std::max(piece.speed(time),1.0); + }; + if(endpointContact(cursor)) return root(cursor); + Intersection result; + // Plane distance is monotonic between consecutive extrema of the supported line and helix pieces. + auto bracket = [&](double stop){ + double a = cursor, b = stop; + cursor = stop; + double fa = distance(a), fb = distance(b); + if(fa == 0.0 && query.inRange(a)){ result = root(a); return true; } + if(fb == 0.0 && query.inRange(b)){ result = root(b); return true; } + if(fa == 0.0 || fb == 0.0 || std::signbit(fa) == std::signbit(fb)) return false; + for(unsigned iteration = 0; iteration < maxRootTrials_; ++iteration){ + double mid = a+0.5*(b-a); + if(mid == a || mid == b){ + for(double time : {a,b}){ + auto inter = root(time); + if(inter.onsurface_ && inter.inrange_){ result = inter; return true; } + } + throw std::runtime_error("KKExtrap: plane bracket has no representable root"); + } + double fm = distance(mid), speed = piece.speed(mid); + if(!std::isfinite(speed) || !(speed > 0.0)) throw std::runtime_error("KKExtrap: invalid plane-root speed"); + if(fm == 0.0 || (std::fabs(b-a)*speed <= 0.125*intertol_ && std::fabs(fm) < intertol_)){ + result = root(mid); + return true; + } + if(std::signbit(fa) == std::signbit(fm)){ a = mid; fa = fm; } + else { b = mid; fb = fm; } + } + throw std::runtime_error("KKExtrap: plane bracket exceeded bisection budget"); + }; + auto segment = [&](double time){ + if(bracket(time)) return true; + // A tolerance-level extremum is a recordable contact; material incidence cuts still apply. + auto contact = root(time); + if(contact.onsurface_ && contact.inrange_){ result = contact; return true; } + return false; + }; + if(visitPlaneExtrema(piece,plane,query,segment)) return result; + double stop = tdir_ == TimeDir::forwards ? query.end() : query.begin(); + if(!bracket(stop) && endpointContact(stop)) return root(stop); + return result; + } + + template bool ExtrapolateSweep::departed(KinKal::ParticleTrajectory const& ptraj, + size_t itg, size_t previous, double accepted, double proposed) const { + auto const& plane = *targets_[itg].pl_; + auto const& prev = *targets_[previous].pl_; + double sgn = tdir_ == TimeDir::forwards ? 1.0 : -1.0; + if(sgn*(proposed-accepted) <= 0.0) return false; + TimeRange interval(std::min(accepted,proposed),std::max(accepted,proposed)); + if(!interval.restrict(ptraj.range()) || interval.null()) return false; + size_t first = ptraj.nearestIndex(interval.begin()), last = ptraj.nearestIndex(interval.end()); + double offset = 2.0*intertol_ + std::fabs((plane.center()-prev.center()).Dot(prev.normal())); + for(size_t ip = first; ip <= last; ++ip){ + auto const& piece = ptraj.piece(ip); + auto clipped = piece.range(); + if(!clipped.restrict(interval) || clipped.null()) continue; + auto witness = [&](double time){ + if(!std::isfinite(time) || time < clipped.begin() || time > clipped.end() || + sgn*(time-accepted) <= 0.0 || sgn*(proposed-time) <= 0.0) return false; + auto pos = ptraj.position3(time); + return std::fabs(plane.distance(pos)) > intertol_ && std::fabs(prev.distance(pos)) > intertol_; + }; + if(witness(clipped.begin()) || witness(clipped.end())) return true; + if(visitPlaneExtrema(piece,prev,clipped,witness)) return true; + // Offset-plane roots also provide directly verified departure witnesses. + for(double side : {-1.0,1.0}){ + KinKal::Plane outside(prev.normal(),prev.uDirection(),prev.center()+side*offset*prev.normal()); + auto root = KinKal::intersect(piece,outside,clipped,0.125*intertol_,tdir_); + if(root.onsurface_ && witness(root.time_)) return true; + } + } + return false; + } + + template bool ExtrapolateSweep::seam(KinKal::ParticleTrajectory const& ptraj, + size_t itg, Intersection const& inter) const { + // Candidate searches are speculative; only accept() changes episodes, never a future departure witness. + for(auto const& episode : episodes_[itg]) + if(!departed(ptraj,itg,episode.itarget_,episode.time_,inter.time_)) return true; + return false; + } + + template void ExtrapolateSweep::ownBoundary(KTRAJ const& piece, SweepTarget const& tg, Intersection& inter) const { + double time = inter.time_; + double begin = piece.range().begin(), end = piece.range().end(); + if(time != begin && time != end) return; + // Encode exact piece-edge roots one ULP inside their source piece so lookup and material insertion agree. + double inside = std::nextafter(time,time == begin ? end : begin); + if(!(inside > begin && inside < end) || !std::isfinite(inside)) + throw std::runtime_error("KKExtrap: boundary root has no representable piece interior"); + double distance = std::fabs(inside-time)*piece.speed(time); + if(!std::isfinite(distance) || distance > intertol_) + throw std::runtime_error("KKExtrap: boundary-root displacement exceeds intersection tolerance"); + inter.time_ = inside; + inter.pos_ = piece.position3(inside); + inter.pdir_ = piece.direction(inside); + inter.norm_ = tg.surf_->normal(inter.pos_); + inter.onsurface_ = tg.surf_->onSurface(inter.pos_,intertol_); + inter.inbounds_ = tg.surf_->inBounds(inter.pos_,intertol_); + inter.inrange_ = piece.range().inRange(inside); + if(!inter.onsurface_) throw std::runtime_error("KKExtrap: boundary-root displacement leaves surface tolerance"); + } + + template bool ExtrapolateSweep::firstCrossing(KinKal::ParticleTrajectory const& ptraj, KTRAJ const& piece, size_t itg, TimeRange win, Intersection& inter) const { + auto const& tg = targets_[itg]; + double sgn = tdir_ == TimeDir::forwards ? 1.0 : -1.0; + double ts = tdir_ == TimeDir::forwards ? win.begin() : win.end(); + double stop = tdir_ == TimeDir::forwards ? win.end() : win.begin(); + double guard = 4.0*intertol_/std::max(piece.speed(ts),1.0); + if(count_[itg] > 0) ts = sgn > 0.0 ? std::max(ts,tlast_[itg]+guard) : std::min(ts,tlast_[itg]-guard); + auto const* plane = dynamic_cast(tg.surf_); + unsigned nroot(0); + while(sgn*(stop - ts) > 0.0){ + if(++nroot > maxRootTrials_) throw std::runtime_error("KKExtrap: surface-root search exceeded retry limit"); + TimeRange query = sgn > 0.0 ? TimeRange(ts,stop) : TimeRange(stop,ts); + VEC3 pos = piece.position3(ts); + if((nroot == 1 || !plane) && tg.surf_->onSurface(pos,intertol_) && + std::fabs(tg.surf_->normal(pos).Dot(piece.direction(ts))) >= minv_){ + inter = Intersection(); + inter.time_ = ts; + inter.pos_ = pos; + inter.pdir_ = piece.direction(ts); + inter.norm_ = tg.surf_->normal(pos); + inter.onsurface_ = true; + inter.inbounds_ = tg.surf_->inBounds(pos,intertol_); + inter.inrange_ = ts >= piece.range().begin() && ts <= piece.range().end(); + } else if(plane) { + inter = planeCrossing(piece,*plane,query); + } else { + inter = KinKal::intersect(piece,*tg.surf_,query,intertol_,tdir_); + } + if(debug_ > 3) std::cout << "Sweep " << tg.sid_ << " " << inter << std::endl; + if(!inter.onsurface_) return false; + if(!std::isfinite(inter.time_)) throw std::runtime_error("KKExtrap: nonfinite surface-root time"); + if(!inter.inrange_) return false; + if(sgn*(inter.time_ - ts) < 0.0) throw std::runtime_error("KKExtrap: surface-root search did not advance"); + if(sgn*(stop - inter.time_) < 0.0 || inter.time_ < piece.range().begin() || inter.time_ > piece.range().end()) + throw std::runtime_error("KKExtrap: surface root outside its piece/window"); + ownBoundary(piece,tg,inter); + if(sgn*(inter.time_ - ts) < 0.0 || sgn*(stop - inter.time_) < 0.0) return false; + if(!inter.inrange_) throw std::runtime_error("KKExtrap: surface root has no owning piece"); + bool grazing = std::fabs(inter.norm_.Dot(inter.pdir_)) < tg.mincos_; + if((inter.inbounds_ || !tg.inbounds_) && !grazing && !seam(ptraj,itg,inter)) return true; + // Roots within four intersection tolerances of path length are unresolved by this search. + double next = inter.time_ + sgn*guard; + if(!std::isfinite(next) || sgn*(next - ts) <= 0.0) + throw std::runtime_error("KKExtrap: surface-root rejection did not advance"); + ts = next; + } + return false; + } + + template bool ExtrapolateSweep::search(KinKal::ParticleTrajectory const& ptraj, double tend) const { + double sgn = tdir_ == TimeDir::forwards ? 1.0 : -1.0; + double t0 = std::clamp(searched_,ptraj.range().begin(),ptraj.range().end()); + tend = std::clamp(tend,ptraj.range().begin(),ptraj.range().end()); + double dtwin = maxDtStep_ > 0.0 ? maxDtStep_ : std::fabs(tend - t0); + while(sgn*(tend - t0) > 0.0){ + double t1 = t0 + sgn*std::min(dtwin,std::fabs(tend - t0)); + if(sgn*(t1 - t0) <= 0.0) throw std::runtime_error("KKExtrap: search window did not advance"); + TimeRange window(std::min(t0,t1),std::max(t0,t1)); + bool found(false); + Crossing best; + size_t first = ptraj.nearestIndex(window.begin()); + size_t last = ptraj.nearestIndex(window.end()); + for(size_t ip = first; ip <= last; ++ip){ + auto const& piece = ptraj.piece(ip); + auto win = piece.range(); + if(!win.restrict(window) || win.null()) continue; + VEC3 wpos = piece.position3(tdir_ == TimeDir::forwards ? win.begin() : win.end()); + double reach = piece.speed(win.mid())*win.range()*(1.0+1.0e-9) + intertol_; + for(size_t itg = 0; itg < targets_.size(); ++itg){ + if(!usable(itg) || !withinReach(itg,wpos,reach)) continue; + Intersection inter; + if(!firstCrossing(ptraj,piece,itg,win,inter)) continue; + bool earlier = !found || sgn*inter.time_ < sgn*best.inter_.time_; + bool tie = found && inter.time_ == best.inter_.time_ && targets_[itg].sid_ < targets_[best.itarget_].sid_; + if(earlier || tie){ + found = true; + best.itarget_ = itg; + best.inter_ = inter; + } + } + } + if(found){ + crossing_ = best; + found_ = true; + searched_ = t0; + return true; + } + t0 = t1; + searched_ = t1; + } + return false; + } + + template bool ExtrapolateSweep::reachable(KinKal::ParticleTrajectory const& ptraj) const { + double sgn = tdir_ == TimeDir::forwards ? 1.0 : -1.0; + auto const& ktraj = tdir_ == TimeDir::forwards ? ptraj.back() : ptraj.front(); + double time = tdir_ == TimeDir::forwards ? ktraj.range().end() : ktraj.range().begin(); + VEC3 pos = ktraj.position3(time); + VEC3 vel = ktraj.velocity(time)*sgn; // signed by the extrapolation direction + double rho = std::sqrt(pos.X()*pos.X() + pos.Y()*pos.Y()); + double vrho = rho > 0.0 ? (pos.X()*vel.X() + pos.Y()*vel.Y())/rho : 0.0; + for(size_t itg = 0; itg < targets_.size(); ++itg){ + auto const& tg = targets_[itg]; + if(!tg.drives_ || !usable(itg)) continue; + if(rho > tg.rmax_ && vrho > 0.0) continue; + bool reach(false); + switch(tg.reach_) { + case SweepTarget::radial: + reach = true; + break; + case SweepTarget::plane: { + double vn = vel.Dot(tg.pl_->normal()); + double pd = (tg.pl_->center()-pos).Dot(tg.pl_->normal()); + reach = std::fabs(vn) >= minv_ && pd*vn > 0.0; + break; + } + case SweepTarget::zplane: { + double dz = tg.zval_ - pos.Z(); + if(dz*vel.Z() >= 0.0) { + reach = true; + } else { + // near a reflection vz is an unreliable direction estimate: use the linearized trajectory instead + KinKal::Plane zplane(VEC3(0.0,0.0,1.0),VEC3(1.0,0.0,0.0),VEC3(0.0,0.0,tg.zval_)); + double dist(0.0); + zplane.intersect(ktraj.linearize(time),dist,tdir_ == TimeDir::forwards,intertol_); + reach = dist*sgn > 0.0; + } + break; + } + case SweepTarget::zrange: { + double vb = ktraj.bnom().R() > 0.0 ? vel.Dot(ktraj.bnom().Unit()) : vel.Z(); + reach = (pos.Z() > tg.zreglo_ && pos.Z() < tg.zreghi_) || (pos.Z() >= tg.zreghi_ && vb < 0.0) || (pos.Z() <= tg.zreglo_ && vb > 0.0); + break; + } + case SweepTarget::inside: + reach = rho < tg.rreg_ && pos.Z() > tg.zreglo_ && pos.Z() < tg.zreghi_; + break; + } + if(reach){ + if(debug_ > 2) std::cout << "Sweep: " << tg.sid_ << " reachable from time " << time << " z " << pos.Z() << " rho " << rho << std::endl; + return true; + } + } + if(debug_ > 1) std::cout << "Sweep: nothing reachable from time " << time << " z " << pos.Z() << " rho " << rho << std::endl; + return false; + } +} +#endif diff --git a/Mu2eKinKal/inc/ExtrapolateToTrackerPerimeter.hh b/Mu2eKinKal/inc/ExtrapolateToTrackerPerimeter.hh deleted file mode 100644 index 797ae5f32a..0000000000 --- a/Mu2eKinKal/inc/ExtrapolateToTrackerPerimeter.hh +++ /dev/null @@ -1,76 +0,0 @@ -// Predicate for extrapolation to the tracker PERIMETER: the closed cylinder bounding the tracker -// active volume, {rho = sqrt(x^2+y^2) <= R} intersected with {zmin <= z <= zmax}. The track is -// extended until it reaches the FIRST bounding face it meets -- the curved outer wall (constant rho) -// OR either z-end plane (constant z) -- whichever comes first for that track. -// -// This is the direction-agnostic generalization of the two former predicates: ExtrapolateToZ (a -// downstream track exits through a constant-z end plane) and ExtrapolateToR (a cosmic traverses the -// tracker radially -- mostly in y -- and exits through the curved outer wall). One predicate handles -// both, choosing the face per track from its own kinematics, so no configuration switch is needed. -// -// All three bounds (R, zmin, zmax) come from the tracker geometry (KinKalGeom::tracker(), itself -// sourced from GeometryService), so the tracker perimeter is defined in exactly one place -- no -// hand-entered radius/z limits that must be kept in sync with the geometry. -#ifndef Mu2eKinKal_ExtrapolateToTrackerPerimeter_hh -#define Mu2eKinKal_ExtrapolateToTrackerPerimeter_hh -#include "KinKal/Trajectory/ParticleTrajectory.hh" -#include "KinKal/General/TimeDir.hh" -#include -#include -#include -#include "cetlib_except/exception.h" -namespace mu2e { - using KinKal::TimeDir; - using KinKal::timeDirSign; - class ExtrapolateToTrackerPerimeter { - public: - ExtrapolateToTrackerPerimeter(double maxdt, double maxdtstep, double tol, - double rval, double zmin, double zmax, int debug) : - maxDt_(maxdt), maxDtStep_(maxdtstep), dptol_(tol), rval_(rval), zmin_(zmin), zmax_(zmax), debug_(debug) {} - // interface for extrapolation - double maxDt() const { return maxDt_; } // maximum time to extend the track, WRT the time of the first(last) measurement - double maxDtStep() const { return maxDtStep_; } - double dpTolerance() const { return dptol_; } // tolerance on fractional momentum change - double rVal() const { return rval_; } - double zMin() const { return zmin_; } - double zMax() const { return zmax_; } - int debug() const { return debug_; } - // extrapolation predicate: the track will be extrapolated until this predicate returns false, subject to the maximum time - template bool needsExtrapolation(KinKal::ParticleTrajectory const& fittraj, TimeDir tdir) const; - private: - double maxDt_ = -1; // maximum extrapolation time - double maxDtStep_ = -1; // maximum extrapolation time step in a single iteration - double dptol_ = 1e10; // fractional momentum tolerance in BField domain - double rval_ = 0; // outer wall transverse radius (mm) - double zmin_ = -std::numeric_limits::max(); // upstream z-end plane (mm) - double zmax_ = std::numeric_limits::max(); // downstream z-end plane (mm) - int debug_ = 0; // debug level - }; - - template bool ExtrapolateToTrackerPerimeter::needsExtrapolation(KinKal::ParticleTrajectory const& fittraj, KinKal::TimeDir tdir) const { - auto const& ktraj = tdir == TimeDir::forwards ? fittraj.back() : fittraj.front(); - auto time = tdir == TimeDir::forwards ? ktraj.range().end() : ktraj.range().begin(); - auto vel = ktraj.velocity(time); - auto pos = ktraj.position3(time); - double rho = std::sqrt(pos.X()*pos.X() + pos.Y()*pos.Y()); - double z = pos.Z(); - // velocities signed by the extrapolation direction (positive = heading toward that boundary) - double rvel = (rho > 0.0 ? (pos.X()*vel.X() + pos.Y()*vel.Y())/rho : 0.0)*timeDirSign(tdir); // outward radial - double vz = vel.Z()*timeDirSign(tdir); - if(debug_ > 2)std::cout << "Perimeter extrap start time " << time << " rho " << rho << " rvel " << rvel - << " z " << z << " vz " << vz << " R " << rval_ << " z[" << zmin_ << "," << zmax_ << "]" << std::endl; - // already at/outside any bounding face: stop (the recording step finds the precise crossing) - if(rho >= rval_) return false; - if(z <= zmin_ || z >= zmax_) return false; - // time to reach each face we are actually approaching (INF if heading away from it) - static const double INF = std::numeric_limits::max(); - double t_r = rvel > 0.0 ? (rval_ - rho)/rvel : INF; // outer wall - double t_zlo = vz < 0.0 ? (z - zmin_)/(-vz) : INF; // upstream z-end - double t_zhi = vz > 0.0 ? (zmax_ - z)/vz : INF; // downstream z-end - // inside the volume but heading toward no face (e.g. a stalled step): nothing more to reach - if(t_r == INF && t_zlo == INF && t_zhi == INF) return false; - // still strictly inside and closing on a face: keep extending - return true; - } -} -#endif diff --git a/Mu2eKinKal/inc/ExtrapolateToZ.hh b/Mu2eKinKal/inc/ExtrapolateToZ.hh deleted file mode 100644 index 7150e8fc1c..0000000000 --- a/Mu2eKinKal/inc/ExtrapolateToZ.hh +++ /dev/null @@ -1,56 +0,0 @@ -// predicate for extrapolation to a given Z position in a given direction -// track changes direction. -#ifndef Mu2eKinKal_ExtrapolateToZ_hh -#define Mu2eKinKal_ExtrapolateToZ_hh -#include "KinKal/Trajectory/ParticleTrajectory.hh" -#include "KinKal/General/TimeDir.hh" -#include "KinKal/Geometry/Plane.hh" -#include -#include "cetlib_except/exception.h" -namespace mu2e { - using KinKal::TimeDir; - using KinKal::timeDirSign; - class ExtrapolateToZ { - public: - ExtrapolateToZ(double maxdt, double maxdtstep, double tol, double intertol, double zval,int debug) : maxDt_(maxdt), maxDtStep_(maxdtstep), - dptol_(tol), intertol_(intertol), zval_(zval), debug_(debug), plane_(VEC3(0.0,0.0,1.0), VEC3(1.0,0.0,0.0),VEC3(0.0,0.0,zval_)) {} - // interface for extrapolation - double maxDt() const { return maxDt_; } // maximum time to extend the track, WRT the time of the first(last) measurement - double maxDtStep() const { return maxDtStep_; } - double dpTolerance() const { return dptol_; } // tolerance on fractional momentum change - double zVal() const { return zval_; } - int debug() const { return debug_; } - // extrapolation predicate: the track will be extrapolated until this predicate returns false, subject to the maximum time - template bool needsExtrapolation(KinKal::ParticleTrajectory const& fittraj, TimeDir tdir) const; - private: - double maxDt_ = -1; // maximum extrapolation time - double maxDtStep_ = -1; // maximum extrapolation time step in a single iteration - double dptol_ = 1e10; // fractional momentum tolerance in BField domain - double intertol_ = 1e-6; // intersection distance tolerance - double zval_ = 0; // z value targeted - int debug_ = 0; // debug level - KinKal::Plane plane_; // KinKal plane - }; - - template bool ExtrapolateToZ::needsExtrapolation(KinKal::ParticleTrajectory const& fittraj, KinKal::TimeDir tdir) const { - auto const& ktraj = tdir == TimeDir::forwards ? fittraj.back() : fittraj.front(); - auto time = tdir == TimeDir::forwards ? ktraj.range().end() : ktraj.range().begin(); - auto vel = ktraj.velocity(time)*timeDirSign(tdir); // sign by extrapolation direction - auto epos =ktraj.position3(time); - double dz = zval_ - epos.Z(); - if(debug_ > 2)std::cout << "Z extrap start time " << time << " dz " << dz << " zvel " << vel.Z() << " dz " << dz << std::endl; - // false if we're heading away from the target z, otherwise true - bool retval (true); - if(dz*vel.Z() < 0) { - // near reflection vz becomes an unreliable estimator of direction. Use the linearized direction instead - auto axis = ktraj.linearize(time); - double dist; - plane_.intersect(axis,dist,tdir==TimeDir::forwards,intertol_); - retval = dist*timeDirSign(tdir) > 0.0; - if(debug_ > 2)std::cout << "Z extrap ray intersection result " << retval << " distance " << dist << std::endl; - } else if (debug_ > 2) - std::cout << "Z heading towards surface, distance " << dz << std::endl; - return retval; - } -} -#endif diff --git a/Mu2eKinKal/inc/KKExtrap.hh b/Mu2eKinKal/inc/KKExtrap.hh index cb0de2055f..0737512c36 100644 --- a/Mu2eKinKal/inc/KKExtrap.hh +++ b/Mu2eKinKal/inc/KKExtrap.hh @@ -1,42 +1,31 @@ #ifndef Mu2eKinKal_KKExtrap_hh #define Mu2eKinKal_KKExtrap_hh -// -// Helper class for extrapolating fits through materials and surfaces. -// original author: Dave Brown (LBN), 9/8/2025 -// +// Helper class for time-ordered extrapolation through requested materials and surfaces. #include "Offline/Mu2eKinKal/inc/KKFitSettings.hh" #include "Offline/DataProducts/inc/SurfaceId.hh" #include "Offline/KinKalGeom/inc/KinKalGeom.hh" #include "Offline/KinKalGeom/inc/Tracker.hh" #include "Offline/Mu2eKinKal/inc/KKTrack.hh" -#include "Offline/Mu2eKinKal/inc/ExtrapolateToZ.hh" -#include "Offline/Mu2eKinKal/inc/ExtrapolateToTrackerPerimeter.hh" -#include "Offline/Mu2eKinKal/inc/ExtrapolateIPA.hh" -#include "Offline/Mu2eKinKal/inc/ExtrapolateST.hh" -#include "Offline/Mu2eKinKal/inc/ExtrapolateCRVRegion.hh" -#include "Offline/Mu2eKinKal/inc/ExtrapolateCylinders.hh" -#include "Offline/Mu2eKinKal/inc/ExtrapolatePlanes.hh" +#include "Offline/Mu2eKinKal/inc/ExtrapolateSweep.hh" #include "Offline/Mu2eKinKal/inc/KKShellXing.hh" #include "Offline/KinKalGeom/inc/KKMaterial.hh" #include "KinKal/Geometry/ParticleTrajectoryIntersect.hh" #include "cetlib_except/exception.h" #include "Offline/GeometryService/inc/GeomHandle.hh" -#include -#include -#include +#include "Offline/GeometryService/inc/GeometryService.hh" #include #include #include -#include "Offline/GeometryService/inc/GeometryService.hh" -#include "Offline/KinKalGeom/inc/KinKalGeom.hh" +#include +#include +#include +#include +#include +#include +#include namespace mu2e { using KinKal::VEC3; using KinKal::TimeDir; - using SurfacePtr = std::shared_ptr; - using CylPtr = std::shared_ptr; - using DiskPtr = std::shared_ptr; - using FruPtr = std::shared_ptr; - using AnnPtr = std::shared_ptr; using Mu2eKinKal::KKExtrapConfig; class KKExtrap { @@ -44,31 +33,25 @@ namespace mu2e { explicit KKExtrap(KKExtrapConfig const& exconfig); // throw at configuration if the fit config's minimum domain step can't fit this extrapolation's maximum step void checkConfig(KinKal::Config const& config) const; - // extrapolation functions; these are templated on the type of trajectory + // extrapolate the fit in both time directions through every requested surface template void extrapolate(KKTrack& ktrk) const; - template bool extrapolateIPA(KKTrack& ktrk,TimeDir trkdir) const; - template bool extrapolateST(KKTrack& ktrk,TimeDir trkdir) const; - template bool extrapolateTracker(KKTrack& ktrk,TimeDir tdir) const; - template bool extrapolateTSDA(KKTrack& ktrk,TimeDir tdir) const; - template void extrapolateDSMaterial(KKTrack& ktrk,TimeDir tdir) const; - template void extrapolatePassiveMaterial(KKTrack& ktrk,TimeDir tdir) const; - template void extrapolateCRV(KKTrack& ktrk,TimeDir tdir) const; - template void extrapolateOPA(KKTrack& ktrk, double tstart, TimeDir tdir) const; - template void toTrackerPerimeter(KKTrack& ktrk) const; - template void toCaloDisk(KKTrack& ktrk, int idisk, double tref, TimeDir tdir) const; - + // the surfaces requested in one time direction; updir is the direction that leaves the tracker upstream + SweepTargetCollection targets(bool updir) const; private: + template void sweep(KKTrack& ktrk, SweepTargetCollection const& tgts, TimeDir tdir, double t0, bool updir) const; + template void addFailure(KKTrack& ktrk, TimeDir tdir, std::string const& reason) const; + template bool rangeOut(KKTrack& ktrk, SweepTarget const& tg, KinKal::Intersection const& inter) const; + template bool addCrossing(KKTrack& ktrk, SweepTarget const& tg, KinKal::Intersection const& inter, TimeDir tdir) const; + template bool reflect(ExtrapolateSweep& xs, KinKal::ParticleTrajectory const& ftraj, TimeDir tdir) const; int debug_; double btol_, intertol_, maxdt_, maxdtstep_, minv_; bool backToTracker_, extrapolateOPA_, toTrackerPerimeter_, upstream_, toCRV_; bool toCaloD0_, toCaloD1_; - // IPA/ST thicknesses are nominal literals, consistent with the rest of KinKalGeom, whose IPA - // (single Cylinder) and ST (uniform Annulus foils) surfaces are themselves hard-coded nominal - // placeholders (see KinKalGeomMaker::makeDS/makeTarget). Sourcing these from the real geometry - // service is part of the broader "build KinKalGeom from the geometry service" work, not a standalone - // fix -- doing it for the thicknesses alone while the surfaces stay nominal would be inconsistent. TODO + // IPA/ST thicknesses match the nominal KinKalGeom surfaces. double ipathick_ = 0.511; // ipa thickness (mm) double stthick_ = 0.1056; // st foil thickness (mm) + static constexpr unsigned maxCrossings_ = 1000; // per sweep, against endless reflection loops + static constexpr double dsShellMinCos_ = 0.1; // thin-shell approximation: skip near-tangent DS shell crossings }; KKExtrap::KKExtrap(KKExtrapConfig const& extrapconfig) : @@ -94,437 +77,331 @@ namespace mu2e { } template void KKExtrap::extrapolate(KKTrack& ktrk) const { - GeomHandle kkg_h; - // define the time direction according to the fit direction inside the tracker auto const& ftraj = ktrk.fitTraj(); - // capture t0 now: once the fit is extrapolated upstream, ftraj.t0() can resolve onto the reflected leg + if(ftraj.range().null()) return; + // Clamp the anchor because the helix time at z=0 need not lie inside the fitted range. double t0 = ftraj.t0(); - auto dir0 = ftraj.direction(t0); - TimeDir tdir = (dir0.Z() > 0) ? TimeDir::backwards : TimeDir::forwards; - if(toTrackerPerimeter_)toTrackerPerimeter(ktrk); - if(upstream_){ - double starttime = tdir == TimeDir::forwards ? ftraj.range().end() : ftraj.range().begin(); - // extrapolate through the IPA in this direction. - bool exitsIPA = extrapolateIPA(ktrk,tdir); - if(exitsIPA){ // if it exits out the back, extrapolate through the target - bool exitsST = extrapolateST(ktrk,tdir); - if(exitsST) { // if it exits out the back, extrapolate to the TSDA (DS rear absorber) - bool hitTSDA = extrapolateTSDA(ktrk,tdir); - // if we hit the TSDA we are done. Otherwise if we reflected, go back through the ST - if( (!hitTSDA) ){ // reflection upstream of the target: go back through the target - extrapolateST(ktrk,tdir); - if(backToTracker_){ // optionally extrapolate back through the IPA, then to the tracker entrance - extrapolateIPA(ktrk,tdir); - extrapolateTracker(ktrk,tdir); - } - } - } else { // reflection inside the ST; extrapolate back through the IPA, then to the tracker entrance - if(backToTracker_){ - extrapolateIPA(ktrk,tdir); - extrapolateTracker(ktrk,tdir); - } - } - } else { // reflection inside the IPA; extrapolate back through the IPA, then to the tracker entrance - if(backToTracker_)extrapolateTracker(ktrk,tdir); - } - // optionally test for intersection with the OPA - if(extrapolateOPA_)extrapolateOPA(ktrk,starttime,tdir); + ftraj.range().forceRange(t0); + TimeDir updir = (ftraj.direction(t0).Z() > 0) ? TimeDir::backwards : TimeDir::forwards; + if(toTrackerPerimeter_){ + GeomHandle kkg_h; + static const SurfaceId tt_mid("TT_Mid"); + auto midinter = KinKal::intersect(ftraj,kkg_h->tracker()->middle(),ftraj.range(),intertol_); + if(midinter.good()) ktrk.addIntersection(tt_mid,midinter); } - // try CRV in both directions - if(toCRV_){ - extrapolateDSMaterial(ktrk,TimeDir::backwards); - extrapolatePassiveMaterial(ktrk,TimeDir::backwards); - extrapolateCRV(ktrk,TimeDir::backwards); - extrapolateDSMaterial(ktrk,TimeDir::forwards); - extrapolatePassiveMaterial(ktrk,TimeDir::forwards); - extrapolateCRV(ktrk,TimeDir::forwards); + for(auto tdir : {TimeDir::backwards, TimeDir::forwards}){ + auto tgts = targets(updir == tdir); // geometry or service failures stop the job + try { + sweep(ktrk,tgts,tdir,t0,updir == tdir); + } catch(std::bad_alloc const&) { + throw; + } catch(std::exception const& error) { + // a problem with this track ends this direction only; the crossings already added are kept + addFailure(ktrk,tdir,error.what()); + } } - // calorimeter disks MUST stay after all material passes: the calo extension adds no material, and running it - // first moves DS shell crossings onto interior pieces where they are dropped (see PR #2059) - // the calo is downstream of the tracker, opposite to the upstream direction tdir - TimeDir calotdir = tdir == TimeDir::forwards ? TimeDir::backwards : TimeDir::forwards; - if(toCaloD0_)toCaloDisk(ktrk,0,t0,calotdir); - if(toCaloD1_)toCaloDisk(ktrk,1,t0,calotdir); } - // Extrapolate a fit to the tracker perimeter (the closed cylinder bounding the active volume) and record - // the bounding face it reaches: a z-end plane (TT_Front/TT_Back) for a downstream track, the outer wall - // (TT_Outer) for a cosmic. R and the z-ends come from KinKalGeom::tracker(), i.e. from GeometryService. - template void KKExtrap::toTrackerPerimeter(KKTrack& ktrk) const { - GeomHandle kkg_h; - auto const& trk = *kkg_h->tracker(); - double const R = trk.outer().radius(); - double const zf = trk.front().center().Z(); - double const zb = trk.back().center().Z(); - double const zmin = std::min(zf,zb); // upstream z-end plane (do not assume front> best; - double bestdt = std::numeric_limits::max(); - auto consider = [&](SurfaceId const& sid, auto const& surf){ - auto inter = KinKal::intersect(ftraj,surf,rng,intertol_,tdir); - if(inter.good()){ - double const dt = sgn*(inter.time_ - tref); // time from the tracker interior out to this face - if(dt >= 0.0 && dt < bestdt){ bestdt = dt; best.emplace(sid,inter); } - } - }; - consider(tt_outer, trk.outer()); - consider(tt_front, trk.front()); - consider(tt_back, trk.back()); - if(best) ktrk.addIntersection(best->first,best->second); - }; - recordFace(TimeDir::backwards); - recordFace(TimeDir::forwards); + template void KKExtrap::addFailure(KKTrack& ktrk, TimeDir tdir, std::string const& reason) const { + std::string failure = std::string(tdir == TimeDir::forwards ? "forwards: " : "backwards: ") + reason; + if(debug_ > 0) std::cout << "KKExtrap: extrapolation failed " << failure << std::endl; + ktrk.addExtrapolationFailure(failure); } - // Extrapolate a fit to a calorimeter disk (0 or 1) and record the intersections with its front/back faces - // and inner/outer edges. tref is a time inside the tracker and tdir the time direction towards the calo, both - // taken before any extrapolation - template void KKExtrap::toCaloDisk(KKTrack& ktrk, int idisk, double tref, TimeDir tdir) const { - GeomHandle kkg_h; - if(!kkg_h->calo()) return; // no calorimeter in this geometry - auto const& calo = *kkg_h->calo(); - bool d0 = idisk == 0; - auto const& front = d0 ? calo.EMC_Disk_0_Front() : calo.EMC_Disk_1_Front(); - auto const& back = d0 ? calo.EMC_Disk_0_Back() : calo.EMC_Disk_1_Back(); - auto const& inner = d0 ? calo.EMC_Disk_0_Inner() : calo.EMC_Disk_1_Inner(); - auto const& outer = d0 ? calo.EMC_Disk_0_Outer() : calo.EMC_Disk_1_Outer(); - static const SurfaceId frontsid[2] = {SurfaceId("EMC_Disk_0_Front"), SurfaceId("EMC_Disk_1_Front")}; - static const SurfaceId backsid[2] = {SurfaceId("EMC_Disk_0_Back"), SurfaceId("EMC_Disk_1_Back")}; - static const SurfaceId innersid[2] = {SurfaceId("EMC_Disk_0_Inner"), SurfaceId("EMC_Disk_1_Inner")}; - static const SurfaceId outersid[2] = {SurfaceId("EMC_Disk_0_Outer"), SurfaceId("EMC_Disk_1_Outer")}; - auto const& ftraj = ktrk.fitTraj(); - // extend to the back face; the front face and edges are then covered by the trajectory too - ExtrapolateToZ caloBack(maxdt_,maxdtstep_,btol_,intertol_,back.center().Z(),debug_); - if(debug_ > 0)std::cout << "toCaloDisk " << idisk << " front z " << front.center().Z() << " back z " << back.center().Z() << std::endl; - if(!ktrk.extrapolate(tdir,caloBack)) return; - if(debug_ > 0)std::cout << "toCaloDisk " << idisk << " tref " << tref << " range " << ftraj.range().begin() << " " << ftraj.range().end() << std::endl; - // tref is the helix time at z=0, which can lie outside the trajectory (e.g. hits in one tracker half only): - // clamp it into the range as toTrackerPerimeter does, otherwise the TimeRange below is invalid and throws - ftraj.range().forceRange(tref); - // record the calo disk intersections, searching outward from the tracker interior only: after upstream - // extrapolation the far end piece is a nominal-field helix whose range can reach back to the calo z - TimeRange const rng = tdir == TimeDir::forwards ? - TimeRange(tref,ftraj.range().end()) : TimeRange(ftraj.range().begin(),tref); - auto frontinter = KinKal::intersect(ftraj,front,rng,intertol_,tdir); - if(frontinter.good()) ktrk.addIntersection(frontsid[idisk],frontinter); - auto backinter = KinKal::intersect(ftraj,back,rng,intertol_,tdir); - if(backinter.good())ktrk.addIntersection(backsid[idisk],backinter); - // get intersections with inner and outer cylinders - auto innerinter = KinKal::intersect(ftraj,inner,rng,intertol_,tdir); - if(innerinter.good()) ktrk.addIntersection(innersid[idisk],innerinter); - auto outerinter = KinKal::intersect(ftraj,outer,rng,intertol_,tdir); - if(outerinter.good()) ktrk.addIntersection(outersid[idisk],outerinter); + // The particle stops in this material: the forwards direction ends before it, keeping the crossings already added. + template bool KKExtrap::rangeOut(KKTrack& ktrk, SweepTarget const& tg, KinKal::Intersection const& inter) const { + if(debug_ > 0) std::cout << "KKExtrap: ranged out in " << tg.sid_ << " at " << inter.time_ << std::endl; + ktrk.setRangedOut(inter.time_); + return false; } - template bool KKExtrap::extrapolateIPA(KKTrack& ktrk,TimeDir tdir) const { + inline SweepTargetCollection KKExtrap::targets(bool updir) const { GeomHandle kkg_h; GeomHandle kkmat_h; - using KKIPAXING = KKShellXing; - using KKIPAXINGPTR = std::shared_ptr; - // extraplate the fit through the IPA. This will add material effects for each intersection. It will continue till the - // track exits the IPA - ExtrapolateIPA extrapIPA(maxdt_,maxdtstep_,btol_,intertol_,kkg_h->DS()->innerProtonAbsorberPtr(),debug_); - if(debug_ > 2)std::cout << "extrapolating to IPA " << std::endl; - auto const& ftraj = ktrk.fitTraj(); - static const SurfaceId IPASID("IPA"); - double starttime = tdir == TimeDir::forwards ? ftraj.range().end() : ftraj.range().begin(); - double startz = ftraj.position3(starttime).Z() - extrapIPA.zmid(); // z relative to the IPA center - do { - ktrk.extrapolate(tdir,extrapIPA); - if(extrapIPA.intersection().good()){ - // we have a good intersection. Use this to create a Shell material Xing - auto const& reftrajptr = tdir == TimeDir::backwards ? ftraj.frontPtr() : ftraj.backPtr(); - auto const& IPA = kkg_h->DS()->innerProtonAbsorberPtr(); - KKIPAXINGPTR ipaxingptr = std::make_shared(IPA,IPASID,*kkmat_h->IPAMaterial(),extrapIPA.intersection(),reftrajptr,ipathick_,extrapIPA.interTolerance()); - if(debug_ > 2){ - double dmom, paramomvar, perpmomvar; - ipaxingptr->materialEffects(dmom,paramomvar,perpmomvar); - std::cout << "IPA Xing dmom " << dmom << " para momsig " << sqrt(paramomvar) << " perp momsig " << sqrt(perpmomvar) << std::endl; - std::cout << " before append mom = " << reftrajptr->momentum(); + SweepTargetCollection tgts; + auto const& ds = *kkg_h->DS(); + double const bore = ds.inner().radius(); // surfaces inside the DS bore cannot be reached once a track leaves it + auto zrange = [](KinKal::Cylinder const& cyl, double& zlo, double& zhi){ + double z0 = (cyl.center() - cyl.axis()*cyl.halfLength()).Z(); + double z1 = (cyl.center() + cyl.axis()*cyl.halfLength()).Z(); + zlo = std::min(z0,z1); zhi = std::max(z0,z1); + }; + // tracker perimeter: the first face crossed, in each direction + if(toTrackerPerimeter_){ + auto const& trk = *kkg_h->tracker(); + auto face = [&](char const* name, KinKal::Surface const* surf){ + SweepTarget tg; + tg.sid_ = SurfaceId(name); + tg.surf_ = surf; + tg.reach_ = SweepTarget::inside; + tg.group_ = 0; + tg.rreg_ = trk.outer().radius(); + tg.zreglo_ = std::min(trk.front().center().Z(),trk.back().center().Z()); + tg.zreghi_ = std::max(trk.front().center().Z(),trk.back().center().Z()); + return tg; + }; + auto outer = face("TT_Outer",trk.outerPtr().get()); + tgts.push_back(outer); + auto front = face("TT_Front",trk.frontPtr().get()); + tgts.push_back(front); + auto back = face("TT_Back",trk.backPtr().get()); + tgts.push_back(back); + } + // upstream: IPA, ST foils, TSDA (ends the sweep), OPA, and optionally the tracker entrance after a reflection + if(updir && upstream_){ + auto const& ipa = ds.innerProtonAbsorberPtr(); + SweepTarget ipatg; + ipatg.effect_ = SweepTarget::ipashell; + ipatg.reach_ = SweepTarget::zrange; + ipatg.sid_ = SurfaceId("IPA"); + ipatg.surf_ = ipa.get(); + ipatg.cyl_ = ipa; + ipatg.mat_ = &*kkmat_h->IPAMaterial(); + ipatg.thick_ = ipathick_; + ipatg.maxcross_ = 0; + zrange(*ipa,ipatg.zreglo_,ipatg.zreghi_); + tgts.push_back(ipatg); + auto const& st = *kkg_h->ST(); + double stzlo, stzhi; + zrange(st.outer(),stzlo,stzhi); + for(size_t ifoil = 0; ifoil < st.foils().size(); ++ifoil){ + auto const& foil = st.foils()[ifoil]; + SweepTarget tg; + tg.effect_ = SweepTarget::stfoil; + tg.reach_ = SweepTarget::zrange; + tg.sid_ = SurfaceId(SurfaceIdEnum::ST_Foils,ifoil); + tg.surf_ = foil.get(); + tg.pl_ = foil.get(); // a grazing foil is crossed again only after the track leaves its tolerance + tg.ann_ = foil; + tg.mat_ = &*kkmat_h->STMaterial(); + tg.thick_ = stthick_; + tg.maxcross_ = 0; + tg.zreglo_ = stzlo; tg.zreghi_ = stzhi; + tgts.push_back(tg); + } + SweepTarget tsda; + tsda.reach_ = SweepTarget::zplane; + tsda.sid_ = SurfaceId("TSDA"); + tsda.surf_ = ds.upstreamAbsorberPtr().get(); + tsda.zval_ = ds.upstreamAbsorber().center().Z(); + tsda.terminal_ = true; + tsda.inbounds_ = false; + tgts.push_back(tsda); + if(extrapolateOPA_){ + SweepTarget opa; + opa.sid_ = SurfaceId("OPA"); + opa.surf_ = ds.outerProtonAbsorberPtr().get(); + opa.drives_ = false; + tgts.push_back(opa); + } + if(backToTracker_){ + auto const& trk = *kkg_h->tracker(); + SweepTarget entr; + entr.reach_ = SweepTarget::zplane; + entr.sid_ = SurfaceId("TT_Front"); + entr.surf_ = trk.frontPtr().get(); + entr.zval_ = trk.front().center().Z(); + entr.terminal_ = true; + entr.inbounds_ = false; + entr.active_ = false; + tgts.push_back(entr); + } + } + // DS material shells, passive planes (concrete, DS end walls, CRV strongbacks) and CRV sectors, both directions + if(toCRV_){ + for(auto const& cyl : ds.materialCylinders()){ + SweepTarget tg; + tg.effect_ = SweepTarget::cylshell; + tg.reach_ = SweepTarget::radial; + tg.sid_ = cyl.sid_; + tg.surf_ = cyl.surface_.get(); + tg.cyl_ = cyl.surface_; + tg.mat_ = &*kkmat_h->material(cyl.material_); + tg.thick_ = cyl.thickness_; + tg.mincos_ = std::max(minv_,dsShellMinCos_); + tg.rmax_ = cyl.surface_->radius() + 0.5*cyl.thickness_; + tgts.push_back(tg); + } + auto plane = [&](SweepTarget& tg, KinKal::Plane const& pl){ + tg.reach_ = SweepTarget::plane; + tg.pl_ = &pl; + }; + for(auto const& pmp : kkg_h->passiveMaterialPlanes()){ + SweepTarget tg; + tg.effect_ = SweepTarget::planeshell; + tg.sid_ = pmp.sid_; + tg.surf_ = pmp.surface_.get(); + tg.plane_ = pmp.surface_; + tg.mat_ = &*kkmat_h->material(pmp.material_); + tg.thick_ = pmp.thickness_; + plane(tg,*pmp.surface_); + tgts.push_back(tg); + } + if(kkg_h->CRV()){ + for(auto const& sector : kkg_h->CRV()->sectors()){ + SweepTarget tg; + tg.effect_ = SweepTarget::crvsector; + tg.sid_ = SurfaceId(sector.sname_); + tg.surf_ = sector.sector_.get(); + tg.rect_ = sector.sector_; + tg.mat_ = &*kkmat_h->CRVMaterial(); + tg.thick_ = 2*sector.whw_; + plane(tg,*sector.sector_); + tgts.push_back(tg); } - ktrk.addIPAXing(ipaxingptr,tdir); - if(debug_ > 2){ - auto const& newtrajptr = tdir == TimeDir::backwards ? ftraj.frontPtr() : ftraj.backPtr(); - std::cout << " after append mom = " << newtrajptr->momentum() << std::endl; + } + } + // calorimeter disks, downstream only: faces and edges, extending to the back face while the track is in the bore + if(!updir && kkg_h->calo()){ + auto const& calo = *kkg_h->calo(); + for(int idisk = 0; idisk < 2; ++idisk){ + if(!(idisk == 0 ? toCaloD0_ : toCaloD1_)) continue; + bool d0 = idisk == 0; + auto const& front = d0 ? calo.EMC_Disk_0_FrontPtr() : calo.EMC_Disk_1_FrontPtr(); + auto const& back = d0 ? calo.EMC_Disk_0_BackPtr() : calo.EMC_Disk_1_BackPtr(); + auto const& inner = d0 ? calo.EMC_Disk_0_InnerPtr() : calo.EMC_Disk_1_InnerPtr(); + auto const& outer = d0 ? calo.EMC_Disk_0_OuterPtr() : calo.EMC_Disk_1_OuterPtr(); + auto face = [&](char const* name, KinKal::Surface const* surf){ + SweepTarget tg; + tg.sid_ = SurfaceId(name); + tg.surf_ = surf; + tg.drives_ = false; + tg.rmax_ = bore; + return tg; + }; + auto ftg = face(d0 ? "EMC_Disk_0_Front" : "EMC_Disk_1_Front",front.get()); + tgts.push_back(ftg); + auto btg = face(d0 ? "EMC_Disk_0_Back" : "EMC_Disk_1_Back",back.get()); + btg.drives_ = true; + btg.reach_ = SweepTarget::zplane; + btg.zval_ = back->center().Z(); + tgts.push_back(btg); + for(auto const& [name,cyl] : {std::make_pair(d0 ? "EMC_Disk_0_Inner" : "EMC_Disk_1_Inner",inner), + std::make_pair(d0 ? "EMC_Disk_0_Outer" : "EMC_Disk_1_Outer",outer)}){ + auto ctg = face(name,cyl.get()); + tgts.push_back(ctg); } } - } while(extrapIPA.intersection().good()); - // check if the particle exited the same side it entered (ie it reflected inside the IPA) - double endtime = tdir == TimeDir::forwards ? ftraj.range().end() : ftraj.range().begin(); - double endz = ftraj.position3(endtime).Z() - extrapIPA.zmid(); // z relative to the IPA center - if(endz * startz < 0.0){ - if(debug_ > 1)std::cout <<"Exiting opposite side IPA" << std::endl; - return true; - } else { - if(debug_ > 1)std::cout <<"Exiting same side IPA" << std::endl; - return false; } + return tgts; } - template bool KKExtrap::extrapolateST(KKTrack& ktrk,TimeDir tdir) const { - using KKSTXING = KKShellXing; - using KKSTXINGPTR = std::shared_ptr; - GeomHandle kkg_h; - GeomHandle kkmat_h; - - // extraplate the fit through the ST. This will add material effects for each foil intersection. It will continue till the - // track exits the ST in Z - ExtrapolateST extrapST(maxdt_,maxdtstep_,btol_,intertol_,*kkg_h->ST(),debug_); + template void KKExtrap::sweep(KKTrack& ktrk, SweepTargetCollection const& tgts, TimeDir tdir, double t0, bool updir) const { + if(tgts.empty() || !ktrk.fitStatus().usable()) return; auto const& ftraj = ktrk.fitTraj(); - double starttime = tdir == TimeDir::forwards ? ftraj.range().end() : ftraj.range().begin(); - double startz = ftraj.position3(starttime).Z() - extrapST.zmid(); - if(debug_ > 2)std::cout << "extrapolating to ST " << std::endl; - do { - ktrk.extrapolate(tdir,extrapST); - if(extrapST.intersection().good()){ - // we have a good intersection. Use this to create a Shell material Xing - auto const& reftrajptr = tdir == TimeDir::backwards ? ftraj.frontPtr() : ftraj.backPtr(); - KKSTXINGPTR stxingptr = std::make_shared(extrapST.foil(),extrapST.foilId(),*kkmat_h->STMaterial(),extrapST.intersection(),reftrajptr,stthick_,extrapST.interTolerance()); - if(debug_ > 2){ - double dmom, paramomvar, perpmomvar; - stxingptr->materialEffects(dmom,paramomvar,perpmomvar); - std::cout << "ST Xing dmom " << dmom << " para momsig " << sqrt(paramomvar) << " perp momsig " << sqrt(perpmomvar) << std::endl; - std::cout << " before append mom = " << reftrajptr->momentum(); - } - // Add the xing. This truncates the fit - ktrk.addSTXing(stxingptr,tdir); - if(debug_ > 2){ - auto const& newtrajptr = tdir == TimeDir::backwards ? ftraj.frontPtr() : ftraj.backPtr(); - std::cout << " after append mom = " << newtrajptr->momentum() << std::endl; - } + ExtrapolateSweep xs(tgts,tdir,maxdt_,maxdtstep_,btol_,intertol_,minv_,debug_); + // material can only be added on the end piece: the sweep starts there, never before t0 + double tend = tdir == TimeDir::forwards ? ftraj.back().range().begin() : ftraj.front().range().end(); + double tstart = tdir == TimeDir::forwards ? std::max(t0,tend) : std::min(t0,tend); + // record-only surfaces the fitted trajectory already crosses between t0 and the sweep start + xs.start(t0); + xs.limit(tstart,true); + while(!xs.needsExtrapolation(ftraj,tdir) && xs.hasCrossing()){ + addCrossing(ktrk,xs.targets()[xs.crossing().itarget_],xs.crossing().inter_,tdir); + xs.accept(); + } + xs.unlimit(); + xs.start(tstart); + if(updir && upstream_){ + auto const& ktraj = tdir == TimeDir::forwards ? ftraj.back() : ftraj.front(); + if(ktraj.bnom().R() > 0.0){ + double vb = ktraj.velocity(tstart).Dot(ktraj.bnom().Unit())*KinKal::timeDirSign(tdir); + xs.watchReflection(vb > 0.0 ? 1.0 : -1.0); + } + } + unsigned ncross(0); + while(ncross < maxCrossings_){ + if(xs.needsExtrapolation(ftraj,tdir) && !ktrk.extrapolate(tdir,xs)){ + addFailure(ktrk,tdir,ktrk.fitStatus().comment_); // KinKal marked the fit unusable while extending it + break; + } + if(xs.hasCrossing()){ + auto const& tg = xs.targets()[xs.crossing().itarget_]; + if(!addCrossing(ktrk,tg,xs.crossing().inter_,tdir)) break; + xs.accept(); + ++ncross; + if(tg.terminal_ || !ktrk.fitStatus().usable()) break; + } else if(xs.reflected()) { + if(!reflect(xs,ftraj,tdir)) break; + } else { + break; // nothing left to reach, or MaxDt since the last crossing } - } while(extrapST.intersection().good()); - // check if the particle exited in the same physical direction or not (reflection) - double endtime = tdir == TimeDir::forwards ? ftraj.range().end() : ftraj.range().begin(); - double endz = ftraj.position3(endtime).Z() - extrapST.zmid(); // z relative to the ST center - if(endz * startz < 0.0){ - if(debug_ > 1)std::cout <<"Exiting opposite side ST" << std::endl; - return true; - } else { - if(debug_ > 1)std::cout <<"Exiting same side ST" << std::endl; - return false; } + if(ncross >= maxCrossings_) addFailure(ktrk,tdir,"sweep exceeded " + std::to_string(maxCrossings_) + " crossings"); } - template bool KKExtrap::extrapolateTracker(KKTrack& ktrk,TimeDir tdir) const { - GeomHandle kkg_h; - ExtrapolateToZ trackerFront(maxdt_,maxdtstep_,btol_,intertol_,kkg_h->tracker()->front().center().Z(),debug_); - if(debug_ > 2)std::cout << "extrapolating to Tracker " << std::endl; - auto const& ftraj = ktrk.fitTraj(); - double tstart = tdir == TimeDir::forwards ? ftraj.range().end() : ftraj.range().begin(); - static const SurfaceId TrackerSID("TT_Front"); - ktrk.extrapolate(tdir,trackerFront); - TimeRange testrange = tdir == TimeDir::forwards ? TimeRange(tstart, ftraj.range().end()) - : TimeRange(ftraj.range().begin(),tstart); - auto trkfrontinter = KinKal::intersect(ftraj,kkg_h->tracker()->front(),testrange,intertol_,tdir); - if(trkfrontinter.onsurface_){ // dont worry about bounds here - ktrk.addIntersection(TrackerSID,trkfrontinter); + // A reflected track returns to the tracker or finishes crossing its reflecting element. + template bool KKExtrap::reflect(ExtrapolateSweep& xs, KinKal::ParticleTrajectory const& ftraj, TimeDir tdir) const { + xs.watchReflection(0.0); + auto const& tgts = xs.targets(); + if(backToTracker_){ + for(size_t itg = 0; itg < tgts.size(); ++itg){ + if(tgts[itg].sid_ == SurfaceId("TSDA")) xs.setActive(itg,false); + if(tgts[itg].terminal_ && tgts[itg].sid_ == SurfaceId("TT_Front")) xs.setActive(itg,true); + } return true; } - return false; + double z = ftraj.position3(tdir == TimeDir::forwards ? ftraj.range().end() : ftraj.range().begin()).Z(); + SweepTarget::Effect keep(SweepTarget::record); + for(auto const& tg : tgts){ + if(tg.effect_ == SweepTarget::ipashell && z > tg.zreglo_ && z < tg.zreghi_) keep = SweepTarget::ipashell; + if(tg.effect_ == SweepTarget::stfoil && z < tg.zreghi_) keep = SweepTarget::stfoil; + } + if(keep == SweepTarget::record) return false; + for(size_t itg = 0; itg < tgts.size(); ++itg) + if(tgts[itg].drives_ && tgts[itg].effect_ != keep) xs.setActive(itg,false); + return true; } - template bool KKExtrap::extrapolateTSDA(KKTrack& ktrk,TimeDir tdir) const { - GeomHandle kkg_h; - ExtrapolateToZ TSDA(maxdt_,maxdtstep_,btol_,intertol_,kkg_h->DS()->upstreamAbsorber().center().Z(),debug_); - if(debug_ > 2)std::cout << "extrapolating to TSDA " << std::endl; - auto const& ftraj = ktrk.fitTraj(); - double tstart = tdir == TimeDir::forwards ? ftraj.range().end() : ftraj.range().begin(); - static const SurfaceId TSDASID("TSDA"); - ktrk.extrapolate(tdir,TSDA); - TimeRange testrange = tdir == TimeDir::forwards ? TimeRange(tstart, ftraj.range().end()) - : TimeRange(ftraj.range().begin(),tstart); - // test for an intersection with TSDA downstream surface - auto tsdainter = KinKal::intersect(ftraj,kkg_h->DS()->upstreamAbsorber(),testrange,intertol_,tdir); - if(tsdainter.onsurface_){ - ktrk.addIntersection(TSDASID,tsdainter); + template bool KKExtrap::addCrossing(KKTrack& ktrk, SweepTarget const& tg, KinKal::Intersection const& inter, TimeDir tdir) const { + if(debug_ > 0) std::cout << "KKExtrap: " << (tdir == TimeDir::forwards ? "forwards " : "backwards ") << tg.sid_ << " " << inter << std::endl; + if(tg.effect_ == SweepTarget::record){ + ktrk.addIntersection(tg.sid_,inter); return true; } - return false; - } - - //extrapolate to the OPA (DS entrance). only 1 of these is currently possible - // muons can intersect multiple times: TODO - template void KKExtrap::extrapolateOPA(KKTrack& ktrk, double tstart, TimeDir tdir) const { - GeomHandle kkg_h; + // KinKal records why a fit became unusable (e.g. a failed domain walk); the direction just ends + if(!ktrk.fitStatus().usable()) return false; auto const& ftraj = ktrk.fitTraj(); - static const SurfaceId OPASID("OPA"); - TimeRange trange = tdir == TimeDir::forwards ? TimeRange(tstart,ftraj.range().end()) : TimeRange(ftraj.range().begin(),tstart); - auto opainter = KinKal::intersect(ftraj,kkg_h->DS()->outerProtonAbsorber(),trange,intertol_,tdir); - if(opainter.good()){ - ktrk.addIntersection(OPASID,opainter); + auto const& endpiece = tdir == TimeDir::forwards ? ftraj.back() : ftraj.front(); + auto const& reftrajptr = tdir == TimeDir::backwards ? ftraj.frontPtr() : ftraj.backPtr(); + // material can only be added on the end piece, and the shell must reference that same piece + if(!endpiece.range().inRange(inter.time_) || ftraj.nearestTraj(inter.time_) != reftrajptr){ + std::ostringstream reason; + reason << "material crossing " << tg.sid_ << " at " << inter.time_ << " is not owned by the end piece " << endpiece.range(); + addFailure(ktrk,tdir,reason.str()); + return false; } - } - - //extrapolate to the CRV sectors. This only makes sense for KKLine or CentralHelix - template void KKExtrap::extrapolateDSMaterial(KKTrack& ktrk,TimeDir tdir) const { - using KKMATCYLXING = KKShellXing; - GeomHandle kkg_h; - GeomHandle kkmat_h; - auto const& cylinders = kkg_h->DS()->materialCylinders(); - if(cylinders.empty()) return; - auto extrapCylinders = ExtrapolateCylinders(maxdt_,maxdtstep_,btol_,intertol_,minv_,cylinders,debug_); - auto const& ftraj = ktrk.fitTraj(); - using MaterialCylinder = ExtrapolateCylinders::MaterialCylinder; - // NB: this bank-all-sorted idiom differs deliberately from the one-crossing-at-a-time idiom in - // extrapolatePassiveMaterial / extrapolateCRV below. It is safe HERE because the DS shells are - // CONCENTRIC and closely spaced: one step overshoots the whole cluster and the resulting trajectory - // piece spans all of them, so all crossings can be added in a single sorted pass. The planar surfaces - // are STACKED and spatially separated, so adding more than the nearest crossing before re-extrapolating - // advances the front past the farther planes and strands them -- hence they must go one at a time. - std::unordered_set banked; // bank each cylinder once (avoid re-found duplicates) - do { - ktrk.extrapolate(tdir,extrapCylinders); - if(debug_ > 0) std::cout << "Found " << extrapCylinders.intersections().size() << " DS material intersections " << std::endl; - // Bank every crossing found in this pass, in strict tracker-inward time order (descending time - // for backward, ascending for forward). The DS material shells are concentric and closely spaced, - // so a single extrapolation step overshoots the whole cluster and the trajectory piece spans all - // of them; adding the crossings in this order makes each prepend/append shrink the piece down to - // exactly the next crossing, so every one stays within the addable front/back range and none is - // stranded as interior. (intersections() is not reliably time-sorted, so sort a local copy.) The - // 'banked' set skips a crossing re-found on a later step; once a pass adds nothing new, we are done. - auto inters = extrapCylinders.intersections(); - std::sort(inters.begin(),inters.end(),[tdir](auto const& a,auto const& b){ - return tdir == TimeDir::forwards ? a.inter_.time_ < b.inter_.time_ : a.inter_.time_ > b.inter_.time_; }); - bool newbank = false; - for(auto const& inter : inters) { - if(!banked.insert(inter.cylinder_).second) continue; - newbank = true; - auto const& cylinder = *inter.cylinder_; - auto const& reftrajptr = tdir == TimeDir::backwards ? ftraj.frontPtr() : ftraj.backPtr(); - auto matxingptr = std::make_shared(cylinder.surface_,cylinder.sid_,*kkmat_h->material(cylinder.material_), - inter.inter_,reftrajptr,cylinder.thickness_,extrapCylinders.interTolerance()); - ktrk.addMaterialCylXing(matxingptr,tdir); + switch(tg.effect_) { + case SweepTarget::cylshell: + case SweepTarget::ipashell: { + auto shell = std::make_shared>(tg.cyl_,tg.sid_,*tg.mat_,inter,reftrajptr,tg.thick_,intertol_); + if(rangesOut(*shell,tdir)) return rangeOut(ktrk,tg,inter); + if(tg.effect_ == SweepTarget::cylshell) ktrk.addMaterialCylXing(shell,tdir); + else ktrk.addIPAXing(shell,tdir); + return true; } - if(!newbank) break; - } while(extrapCylinders.intersections().size()>0); - } - - template void KKExtrap::extrapolatePassiveMaterial(KKTrack& ktrk,TimeDir tdir) const { - using KKMATRECXING = KKShellXing; // passive plane (Rectangle or Annulus) - using MaterialPlane = ExtrapolatePlanes::MaterialPlane; - GeomHandle kkg_h; - GeomHandle kkmat_h; - auto const& planes = kkg_h->passiveMaterialPlanes(); - if(planes.empty()) return; - auto extrapPlanes = ExtrapolatePlanes(maxdt_,maxdtstep_,btol_,intertol_,minv_,planes,debug_); - auto const& ftraj = ktrk.fitTraj(); - - // Normal path: process each plane at most once, ONE crossing per extrapolate pass (add nearest, - // re-extrapolate, repeat). Unlike extrapolateDSMaterial's bank-all-sorted pass, the passive planes - // are stacked and spatially separated, so adding more than the nearest crossing before re-extrapolating - // would advance the front past the farther planes and strand them (see the cross-reference note there). - // Stop before calling ktrk.extrapolate when all planes have been processed so - // we don't advance the trajectory past the last plane (which would overshoot the - // CRV and prevent extrapolateCRV from finding it). - std::unordered_set processed; - // The CRV strongback planes are crossed together with the CRV sectors in extrapolateCRV - // (interleaved, time-ordered): processing all strongbacks HERE advances the front past the - // lower sectors of a stacked geometry and strands them. Exclude the strongbacks from this - // (concrete-only for the extracted geometry) pass by pre-marking them processed. - SurfaceId const sbid(SurfaceIdEnum::CRV_StrongBack); - for(auto const& plane : planes) if(plane.sid_.id() == sbid.id()) processed.insert(&plane); - do { - if(processed.size() >= planes.size()) break; - ktrk.extrapolate(tdir,extrapPlanes); - if(debug_ > 0) std::cout << "Found " << extrapPlanes.intersections().size() << " passive material plane intersections " << std::endl; - bool found = false; - for(auto const& inter : extrapPlanes.intersections()) { - if(processed.count(inter.plane_) > 0) continue; - auto const& plane = *inter.plane_; - auto const& reftrajptr = tdir == TimeDir::backwards ? ftraj.frontPtr() : ftraj.backPtr(); - auto matxingptr = std::make_shared(plane.surface_,plane.sid_,*kkmat_h->material(plane.material_), - inter.inter_,reftrajptr,plane.thickness_,extrapPlanes.interTolerance()); - ktrk.addMaterialPlaneXing(matxingptr,tdir); - processed.insert(inter.plane_); - found = true; - break; + case SweepTarget::stfoil: { + auto shell = std::make_shared>(tg.ann_,tg.sid_,*tg.mat_,inter,reftrajptr,tg.thick_,intertol_); + if(rangesOut(*shell,tdir)) return rangeOut(ktrk,tg,inter); + ktrk.addSTXing(shell,tdir); + return true; } - if(!found) break; - } while(extrapPlanes.intersections().size()>0); - } - - template void KKExtrap::extrapolateCRV(KKTrack& ktrk,TimeDir tdir) const { - using KKCRVXING = KKShellXing; - using KKMATRECXING = KKShellXing; // strongback (passive) plane - using MaterialPlane = ExtrapolateCRVRegion::MaterialPlane; - GeomHandle kkg_h; - GeomHandle kkmat_h; - // The CRV sector planes and their aluminium strongbacks are spatially interleaved (the sector plane - // is modeled at the scintillator-stack center; its tracker-facing strongback plane sits ~60 mm -- - // a stack half-thickness -- toward the tracker), so they MUST be crossed in ONE outward, - // time-ordered pass -- a xing can only be added at the trajectory front/back, never the interior. - // Crossing all strongbacks first (the old extrapolatePassiveMaterial pass) advanced the front past - // the lower sectors of a stacked geometry (extracted EX/T1/T2 ~150 mm apart in y) and stranded them - // (CRV_T1 lost on every track). Hand both surface types to ExtrapolateCRVRegion, which stops at the - // next crossing of either; add them one at a time, innermost first, re-extrapolating between each - // so every crossing is added at the current front (mirrors extrapolatePassiveMaterial). Run-2 sees - // <=1 sector per direction, so the order (strongback then sector) is unchanged. - ExtrapolateCRVRegion::MaterialPlaneCollection strongbacks; - SurfaceId const sbid(SurfaceIdEnum::CRV_StrongBack); - for(auto const& plane : kkg_h->passiveMaterialPlanes()) - if(plane.sid_.id() == sbid.id()) strongbacks.push_back(plane); - auto extrapCRV = ExtrapolateCRVRegion(maxdt_,maxdtstep_,btol_,intertol_,minv_,*kkg_h->CRV(),strongbacks,debug_); - if(debug_ > 5){std::cout << "Extrapolating to CRV with " << extrapCRV.sectors().size() << " sectors + " - << strongbacks.size() << " strongbacks" << std::endl; - for(auto const& sector : kkg_h->CRV()->sectors()) - std::cout << sector.sname_ << " position " << sector.sector_->center() << " halfwidth " << sector.whw_ << std::endl; - } - auto const& ftraj = ktrk.fitTraj(); - std::unordered_set processedSectors; - std::unordered_set processedPlanes; - do { - ktrk.extrapolate(tdir,extrapCRV); - if(debug_ > 0) std::cout << "Found " << extrapCRV.intersections().size() << " CRV-region intersections " << std::endl; - bool added = false; - // intersections are time-sorted (innermost first for this tdir): add the nearest un-processed - // one, then re-extrapolate so the next is again at the front. - for(auto const& xing : extrapCRV.intersections()){ - auto const& reftrajptr = tdir == TimeDir::backwards ? ftraj.frontPtr() : ftraj.backPtr(); - if(xing.isSector_){ - if(processedSectors.count(xing.sectorIdx_) > 0) continue; - auto crvxingptr = std::make_shared(extrapCRV.sector((size_t)xing.sectorIdx_).sector_, - SurfaceId(kkg_h->CRV()->sectorName(xing.sectorIdx_)),*kkmat_h->CRVMaterial(),xing.inter_,reftrajptr, - 2*xing.whw_, extrapCRV.interTolerance()); - ktrk.addCRVXing(crvxingptr,tdir); - processedSectors.insert(xing.sectorIdx_); - if(debug_ > 1) std::cout << "Good CRV sector " << xing.sectorIdx_ << " " << xing.inter_ << std::endl; - } else { - if(processedPlanes.count(xing.plane_) > 0) continue; - auto const& plane = *xing.plane_; - auto matxingptr = std::make_shared(plane.surface_,plane.sid_,*kkmat_h->material(plane.material_), - xing.inter_,reftrajptr,plane.thickness_,extrapCRV.interTolerance()); - ktrk.addMaterialPlaneXing(matxingptr,tdir); - processedPlanes.insert(xing.plane_); - if(debug_ > 1) std::cout << "Good CRV strongback " << plane.sid_ << " " << xing.inter_ << std::endl; - } - added = true; - break; + case SweepTarget::planeshell: { + auto shell = std::make_shared>(tg.plane_,tg.sid_,*tg.mat_,inter,reftrajptr,tg.thick_,intertol_); + if(rangesOut(*shell,tdir)) return rangeOut(ktrk,tg,inter); + ktrk.addMaterialPlaneXing(shell,tdir); + return true; + } + case SweepTarget::crvsector: { + auto shell = std::make_shared>(tg.rect_,tg.sid_,*tg.mat_,inter,reftrajptr,tg.thick_,intertol_); + if(rangesOut(*shell,tdir)) return rangeOut(ktrk,tg,inter); + ktrk.addCRVXing(shell,tdir); + return true; } - if(!added) break; - } while(extrapCRV.intersections().size()>0); + case SweepTarget::record: + return true; + } + throw cet::exception("RECO") << "mu2e::KKExtrap: unknown sweep effect"; } - } #endif diff --git a/Mu2eKinKal/inc/KKFit.hh b/Mu2eKinKal/inc/KKFit.hh index a316fea4c6..17b2265181 100644 --- a/Mu2eKinKal/inc/KKFit.hh +++ b/Mu2eKinKal/inc/KKFit.hh @@ -690,6 +690,8 @@ namespace mu2e { if(kktrk.fitStatus().status_ == Status::converged) fflag.merge(TrkFitFlag::kalmanConverged); if(matcorr_)fflag.merge(TrkFitFlag::MatCorr); if(kktrk.config().bfcorr_ )fflag.merge(TrkFitFlag::BFCorr); + if(!kktrk.extrapolationFailures().empty())fflag.merge(TrkFitFlag::ExtrapFailed); + if(kktrk.rangedOut())fflag.merge(TrkFitFlag::RangedOut); // explicit T0 is needed for backwards-compatibility; sample from the appropriate trajectory piece auto const& fittraj = kktrk.fitTraj(); double t0val = fittraj.t0(); @@ -785,11 +787,23 @@ namespace mu2e { // save the fit segments as requested if(kktrk.fitStatus().usable()){ static const double minrange(1.0e-2); // minimum time range to save a segment. + // a particle that ranges out stops at that time, so no segment extends past it + double tstop = kktrk.rangeOutTime(); + auto stopped = [tstop](KTRAJ const& traj){ + KTRAJ clipped(traj); + clipped.setRange(TimeRange(traj.range().begin(),std::min(traj.range().end(),tstop))); + return clipped; + }; if (savetraj_ == full){ kseed._segments.reserve(fittraj.pieces().size()); for (auto const& traj : fittraj.pieces() ){ // skip 'zero-range' segments. By convention, sample the state at the mid-time - if(traj->range().range() > minrange) kseed._segments.emplace_back(*traj,traj->range().mid()); + if(traj->range().end() <= tstop){ + if(traj->range().range() > minrange) kseed._segments.emplace_back(*traj,traj->range().mid()); + } else if(std::min(traj->range().end(),tstop) - traj->range().begin() > minrange){ + auto clipped = stopped(*traj); + kseed._segments.emplace_back(clipped,clipped.range().mid()); + } } // a fit that ran without BField correction has no domains at all; the trailing push_back // below would then dereference rbegin() of an empty set, which is undefined behaviour @@ -842,7 +856,12 @@ namespace mu2e { kseed._segments.reserve(fittraj.pieces().size());// this will be oversized for (auto const& traj : fittraj.pieces() ){ // skip segments outside the detector range - if(traj->range().range() > 0.0 && traj->range().overlaps(detrange) ) kseed._segments.emplace_back(*traj,traj->range().mid()); + if(traj->range().end() <= tstop){ + if(traj->range().range() > 0.0 && traj->range().overlaps(detrange) ) kseed._segments.emplace_back(*traj,traj->range().mid()); + } else if(traj->range().begin() < tstop){ + auto clipped = stopped(*traj); + if(clipped.range().overlaps(detrange)) kseed._segments.emplace_back(clipped,clipped.range().mid()); + } } kseed._segments.shrink_to_fit(); if(savedomains_){ @@ -946,7 +965,7 @@ namespace mu2e { } for(auto range : ranges) { double tbeg = range.begin(); - double tend = range.end(); + double tend = std::min(range.end(),kktrk.rangeOutTime()); // a particle that ranges out stops there for(auto const& surf : tosample){ // search for intersections with each surface within the specified time range, going forwards in time bool goodinter(true); diff --git a/Mu2eKinKal/inc/KKShellXing.hh b/Mu2eKinKal/inc/KKShellXing.hh index c895bbe14f..7ca65047f0 100644 --- a/Mu2eKinKal/inc/KKShellXing.hh +++ b/Mu2eKinKal/inc/KKShellXing.hh @@ -7,7 +7,10 @@ #include "KinKal/Detector/ElementXing.hh" #include "KinKal/Geometry/Surface.hh" #include "KinKal/Geometry/ParticleTrajectoryIntersect.hh" +#include "KinKal/Trajectory/PiecewiseClosestApproach.hh" +#include "KinKal/Trajectory/SensorLine.hh" #include "KinKal/MatEnv/DetMaterial.hh" +#include "KinKal/General/TimeDir.hh" #include "Offline/DataProducts/inc/SurfaceId.hh" #include #include @@ -18,8 +21,8 @@ namespace mu2e { using PTRAJ = KinKal::ParticleTrajectory; using KTRAJPTR = std::shared_ptr; using EXING = KinKal::ElementXing; - using PCA = KinKal::PiecewiseClosestApproach; - using CA = KinKal::ClosestApproach; + using PCA = KinKal::PiecewiseClosestApproach; + using CA = KinKal::ClosestApproach; using SURFPTR = std::shared_ptr; // construct from a surface, material, intersection, and transverse thickness. // Material ionization eloss mode (mpv/moyalmean/bethemean) is configured per-material in @@ -36,13 +39,13 @@ namespace mu2e { return rv; }; // ElementXing interface - void updateReference(PTRAJ const& ptraj, MetaIterConfig const&) override; // the intersection time sets the piece, so the piece-move limit does not apply - void updateState(MetaIterConfig const& config,bool first) override; - Parameters params() const override; + void updateReference(PTRAJ const& ptraj, KinKal::MetaIterConfig const&) override; // the intersection time sets the piece, so the piece-move limit does not apply + void updateState(KinKal::MetaIterConfig const& config,bool first) override; + KinKal::Parameters params() const override; double time() const override { return inter_.time_; } double transitTime() const override; KTRAJ const& referenceTrajectory() const override { return *reftrajptr_; } - std::vectorconst& matXings() const override { return mxings_; } + std::vectorconst& matXings() const override { return mxings_; } void print(std::ostream& ost=std::cout,int detail=0) const override; bool active() const override { return mxings_.size() > 0; } // specific accessors @@ -102,7 +105,7 @@ namespace mu2e { } } - template Parameters KKShellXing::params() const { + template KinKal::Parameters KKShellXing::params() const { return fparams_; } @@ -117,5 +120,15 @@ namespace mu2e { ost << std::endl; } + // True if the particle stops in this crossing's material going forwards in time: the mean energy loss reaches the kinetic energy. + template bool rangesOut(KinKal::ElementXing const& xing, KinKal::TimeDir tdir) { + if(tdir != KinKal::TimeDir::forwards) return false; + double dmom, paramomvar, perpmomvar; + xing.materialEffects(dmom,paramomvar,perpmomvar); + auto const& ref = xing.referenceTrajectory(); + double energy = ref.energy(); + return -dmom*ref.momentum()/energy >= energy - ref.mass(); // materialEffects gives dmom = dE E/p + } + } #endif diff --git a/Mu2eKinKal/inc/KKTrack.hh b/Mu2eKinKal/inc/KKTrack.hh index 3f6412726d..44294b6c0c 100644 --- a/Mu2eKinKal/inc/KKTrack.hh +++ b/Mu2eKinKal/inc/KKTrack.hh @@ -13,7 +13,10 @@ #include "Offline/Mu2eKinKal/inc/KKCaloHit.hh" #include "Offline/DataProducts/inc/SurfaceId.hh" #include "KinKal/Geometry/Intersection.hh" +#include +#include #include +#include namespace mu2e { using KinKal::Config; @@ -80,7 +83,9 @@ namespace mu2e { strawhits_(rhs.strawHits()), strawxings_(rhs.strawXings()), calohits_(rhs.caloHits()), - inters_(rhs.intersections()){ + inters_(rhs.intersections()), + extrapfails_(rhs.extrapolationFailures()), + rangeouttime_(rhs.rangeOutTime()){ // hits and crossings were reallocated into the base copy; here, // we propagate references to those reallocations to the subclass this->remap_pointer_collection(strawhits_, this->hits(), context); @@ -144,6 +149,10 @@ namespace mu2e { void addCRVXing(KKCRVXINGPTR const& crvxing,TimeDir const& tdir); // add intersections void addIntersection(SurfaceId const& sid, Intersection const& inter) { inters_.emplace_back(sid,inter); } + // record an extrapolation that ended early on a problem with this track; the fit itself is unaffected + void addExtrapolationFailure(std::string const& reason) { extrapfails_.push_back(reason); } + // record the time the particle stops in an extrapolation material; the forwards extrapolation ends there + void setRangedOut(double time) { rangeouttime_ = time; } // accessors PDGCode::type fitParticle() const { return tpart_;} @@ -157,6 +166,9 @@ namespace mu2e { KKMATCYLXINGCOL const& materialCylXings() const { return matcylxings_; } KKMATRECXINGCOL const& materialPlaneXings() const { return matrecxings_; } KKINTERCOL const& intersections() const { return inters_; } + std::vector const& extrapolationFailures() const { return extrapfails_; } + bool rangedOut() const { return rangeouttime_ < std::numeric_limits::infinity(); } + double rangeOutTime() const { return rangeouttime_; } // infinity unless the particle ranges out KKCALOHITCOL const& caloHits() const { return calohits_; } void printFit(std::ostream& ost=std::cout,int detail=0) const; // allow reversing the charge (in some fits it can change dynamically) @@ -178,6 +190,8 @@ namespace mu2e { KKMATCYLXINGCOL matcylxings_; // passive cylindrical material crossings used in extrapolation KKMATRECXINGCOL matrecxings_; // passive planar material crossings used in extrapolation KKINTERCOL inters_; // other recorded intersections + std::vector extrapfails_; // why an extrapolation direction ended early + double rangeouttime_ = std::numeric_limits::infinity(); // when the particle stops in an extrapolation material KKSTRAWHITCLUSTERCOL strawhitclusters_; // straw hit clusters used in this fit // utility function to convert to generic types void convertTypes( KKSTRAWHITCOL const& strawhits, KKSTRAWXINGCOL const& strawxings,KKCALOHITCOL const& calohits, PARAMHITCOL const& paramhits, diff --git a/Mu2eKinKal/src/CentralHelixFit_module.cc b/Mu2eKinKal/src/CentralHelixFit_module.cc index 11e4fb51a2..e3bf96ffe9 100644 --- a/Mu2eKinKal/src/CentralHelixFit_module.cc +++ b/Mu2eKinKal/src/CentralHelixFit_module.cc @@ -439,7 +439,12 @@ namespace mu2e { // loop to find multiple intersections while(goodinter && cur_inter < max_inter) { cur_inter += 1; - TimeRange irange(tstart,std::max(ftraj.range().end(),tstart)+sampletbuff_); + double tmax = std::max(ftraj.range().end(),tstart)+sampletbuff_; + if(ktrk.rangedOut()){ // a particle that ranges out stops there + tmax = std::min(tmax,ktrk.rangeOutTime()); + if(tstart >= tmax) break; + } + TimeRange irange(tstart,tmax); auto surfinter = KinKal::intersect(ftraj,*surf.second,irange,intertol_); goodinter = surfinter.onsurface_ && ( (! sampleinbounds_) || surfinter.inbounds_ ) && ( (!sampleinrange_) || irange.inRange(surfinter.time_)); if(goodinter) { diff --git a/Mu2eKinKal/src/ExtrapolateSweepTest_main.cc b/Mu2eKinKal/src/ExtrapolateSweepTest_main.cc new file mode 100644 index 0000000000..a4ad717c60 --- /dev/null +++ b/Mu2eKinKal/src/ExtrapolateSweepTest_main.cc @@ -0,0 +1,751 @@ +// Geometry and material-insertion regression checks for the extrapolation sweep. +#include "Offline/Mu2eKinKal/inc/ExtrapolateSweep.hh" +#include "Offline/Mu2eKinKal/inc/KKShellXing.hh" +#include "KinKal/Fit/Material.hh" +#include "KinKal/MatEnv/MatDBInfo.hh" +#include "KinKal/MatEnv/SimpleFileFinder.hh" +#include "KinKal/General/ParticleStateEstimate.hh" +#include "KinKal/General/ParticleState.hh" +#include "KinKal/Trajectory/CentralHelix.hh" +#include "KinKal/Trajectory/LoopHelix.hh" +#include "KinKal/Trajectory/KinematicLine.hh" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + using KinKal::TimeDir; + using KinKal::TimeRange; + using KinKal::VEC3; + using mu2e::ExtrapolateSweep; + using mu2e::SweepTarget; + using mu2e::SweepTargetCollection; + constexpr double tol = 1.0e-4; + + void require(bool ok, std::string const& message) { + if(!ok) throw std::runtime_error(message); + } + + template KinKal::Intersection crossing(KinKal::ParticleTrajectory const& traj, + SweepTargetCollection const& targets, TimeDir dir, double step=1.0e6) { + ExtrapolateSweep sweep(targets,dir,1.0e6,step,1.0e-4,tol,1.0e-6,0); + sweep.start(dir == TimeDir::forwards ? traj.range().begin() : traj.range().end()); + sweep.limit(dir == TimeDir::forwards ? traj.range().end() : traj.range().begin(),false); + require(!sweep.needsExtrapolation(traj,dir),"limited search requests extension"); + require(sweep.hasCrossing(),"no crossing found"); + return sweep.crossing().inter_; + } + + void lineRoots(TimeDir dir, bool split, bool requireBounds) { + bool forward = dir == TimeDir::forwards; + KinKal::ParticleState state(VEC3(-200.0,0.0,forward ? -150.0 : -50.0),VEC3(100.0,0.0,50.0),0.0,105.658,1); + KinKal::KinematicLine line(state,VEC3(0.0,0.0,0.0),TimeRange(0.0,1.0)); + double vx = line.velocity(0.0).X(); + line.setRange(TimeRange(0.0,(split ? 400.0 : 500.0)/vx)); + KinKal::ParticleTrajectory traj(line); + if(split){ + auto tail = line; + tail.setRange(TimeRange(400.0/vx,500.0/vx)); + traj.append(tail); + } + KinKal::Cylinder cyl(VEC3(0.0,0.0,1.0),VEC3(0.0,0.0,0.0),100.0,50.0); + SweepTarget target; + target.sid_ = mu2e::SurfaceId(mu2e::SurfaceIdEnum::DS_CryoInner); + target.surf_ = &cyl; + target.inbounds_ = requireBounds; + auto inter = crossing(traj,{target},dir); + double expected = requireBounds ? (forward ? 100.0 : -100.0) : (forward ? -100.0 : 100.0); + require(std::fabs(inter.pos_.X()-expected) < 10.0*tol,"incorrect cylinder root"); + require(inter.inbounds_ == requireBounds,"unexpected root bounds"); + } + + template void tiltedZ() { + KinKal::ParticleState state(VEC3(10.0,20.0,30.0),VEC3(15.0,80.0,40.0),0.0,105.658,1); + HELIX helix(state,VEC3(1.0,0.0,0.0),TimeRange(0.0,1.0)); + double period = 2.0*std::acos(-1.0)*helix.energy(0.0)/(KinKal::BFieldMap::cbar()*CLHEP::c_light); + double zmax = -1.0e100, tmax = 0.0; + for(unsigned i = 0; i <= 512; ++i){ + double time = period*i/512.0; + double z = helix.position3(time).Z(); + if(z > zmax){ zmax = z; tmax = time; } + } + double lo = tmax-0.2*period, hi = tmax+0.2*period; + helix.setRange(TimeRange(lo,hi)); + double zend = std::max(helix.position3(lo).Z(),helix.position3(hi).Z()); + double planeZ = 0.5*(zend+zmax); + require(planeZ-zend > 100.0*tol,"tilted fixture lacks an interior z extremum"); + KinKal::Plane plane(VEC3(0.0,0.0,1.0),VEC3(1.0,0.0,0.0),VEC3(0.0,0.0,planeZ)); + SweepTarget target; + target.sid_ = mu2e::SurfaceId(mu2e::SurfaceIdEnum::TT_Front); + target.surf_ = &plane; + target.pl_ = &plane; + target.reach_ = SweepTarget::plane; + KinKal::ParticleTrajectory traj(helix); + for(auto dir : {TimeDir::forwards,TimeDir::backwards}){ + double a = dir == TimeDir::forwards ? lo : tmax; + double b = dir == TimeDir::forwards ? tmax : hi; + double fa = helix.position3(a).Z()-planeZ; + for(unsigned iter = 0; iter < 80; ++iter){ + double mid = 0.5*(a+b); + if((helix.position3(mid).Z()-planeZ)*fa > 0.0) a = mid; + else b = mid; + } + double expected = 0.5*(a+b); + for(double step : {period,0.025*period}){ + auto inter = crossing(traj,{target},dir,step); + require(std::fabs(inter.time_-expected)*helix.speed(expected) < 10.0*tol,"incorrect tilted-helix crossing"); + } + } + } + + void stableTieAndSeams() { + KinKal::ParticleState state(VEC3(0.0,0.0,-1.0),VEC3(0.0,0.0,100.0),0.0,105.658,1); + KinKal::KinematicLine line(state,VEC3(0.0,0.0,0.0),TimeRange(0.0,0.1)); + KinKal::ParticleTrajectory traj(line); + KinKal::Plane plane(VEC3(0.0,0.0,1.0),VEC3(1.0,0.0,0.0),VEC3(0.0,0.0,0.0)); + KinKal::Plane nearby(VEC3(0.0,0.0,1.0),VEC3(1.0,0.0,0.0),VEC3(0.0,0.0,0.01)); + SweepTarget a, b; + a.sid_ = mu2e::SurfaceId(mu2e::SurfaceIdEnum::DS_Front); + b.sid_ = mu2e::SurfaceId(mu2e::SurfaceIdEnum::DS_Back); + a.effect_ = b.effect_ = SweepTarget::planeshell; + a.surf_ = b.surf_ = &plane; + a.pl_ = b.pl_ = &plane; + for(bool reverse : {false,true}){ + SweepTargetCollection targets = reverse ? SweepTargetCollection{b,a} : SweepTargetCollection{a,b}; + ExtrapolateSweep sweep(targets,TimeDir::forwards,1.0,1.0,1.0e-4,tol,1.0e-6,0); + sweep.start(0.0); + sweep.limit(0.1,false); + sweep.needsExtrapolation(traj,TimeDir::forwards); + require(sweep.hasCrossing(),"tie has no crossing"); + require(targets[sweep.crossing().itarget_].sid_ == a.sid_,"tie depends on target order"); + sweep.accept(); + sweep.needsExtrapolation(traj,TimeDir::forwards); + require(!sweep.hasCrossing(),"coplanar seam material counted twice"); + } + b.surf_ = &nearby; + b.pl_ = &nearby; + SweepTargetCollection targets{a,b}; + ExtrapolateSweep sweep(targets,TimeDir::forwards,1.0,1.0,1.0e-4,tol,1.0e-6,0); + sweep.start(0.0); + sweep.limit(0.1,false); + sweep.needsExtrapolation(traj,TimeDir::forwards); + require(sweep.hasCrossing(),"first plane absent"); + sweep.accept(); + sweep.needsExtrapolation(traj,TimeDir::forwards); + require(sweep.hasCrossing(),"distinct nearby plane incorrectly seam-suppressed"); + require(targets[sweep.crossing().itarget_].sid_ == b.sid_,"nearby plane identity differs"); + } + + void boundaries(TimeDir dir, bool split) { + KinKal::ParticleState state(VEC3(0.0,0.0,0.0),VEC3(100.0,0.0,0.0),0.0,105.658,1); + KinKal::KinematicLine line(state,VEC3(0.0,0.0,0.0),TimeRange(0.0,1.0)); + double dt = 100.0/line.speed(0.0); + line.setRange(TimeRange(0.0,split ? dt : 2.0*dt)); + KinKal::ParticleTrajectory traj(line); + if(split){ + auto tail = line; + tail.setRange(TimeRange(dt,2.0*dt)); + traj.append(tail); + } + KinKal::Plane plane(VEC3(1.0,0.0,0.0),VEC3(0.0,1.0,0.0),VEC3(100.0,0.0,0.0)); + SweepTarget target; + target.surf_ = &plane; + target.sid_ = mu2e::SurfaceId(mu2e::SurfaceIdEnum::TT_Front); + auto inter = crossing(traj,{target},dir,dt); + require(std::fabs(inter.time_-dt)*line.speed(0.0) < 10.0*tol,"window/piece boundary root lost"); + require(inter.good() && traj.nearestTraj(inter.time_)->range().inRange(inter.time_),"geometry boundary root has no owning piece"); + require((inter.pos_-traj.nearestTraj(inter.time_)->position3(inter.time_)).R() < tol,"geometry boundary root position differs"); + } + + void planarLimits(TimeDir dir) { + KinKal::ParticleState state(VEC3(0.0,0.0,0.0),VEC3(100.0,0.0,0.0),0.0,105.658,1); + KinKal::KinematicLine line(state,VEC3(0.0,0.0,0.0),TimeRange(-1.0,1.0)); + KinKal::ParticleTrajectory traj(line); + KinKal::Plane plane(VEC3(1.0,0.0,0.0),VEC3(0.0,1.0,0.0),VEC3(0.0,0.0,0.0)); + SweepTarget target; + target.surf_ = target.pl_ = &plane; + SweepTargetCollection targets{target}; + ExtrapolateSweep sweep(targets,dir,1.0,1.0,1.0e-4,tol,1.0e-6,0); + sweep.start(dir == TimeDir::forwards ? -1.0 : 1.0); + sweep.limit(0.0,false); + require(!sweep.needsExtrapolation(traj,dir),"terminal-limit search requests extension"); + require(sweep.hasCrossing() == (dir == TimeDir::backwards),"planar limit violates half-open query range"); + if(sweep.hasCrossing()) require(sweep.crossing().inter_.time_ == 0.0,"included lower-limit root moved"); + } + + void solverLowerBoundary() { + KinKal::ParticleState state(VEC3(0.0,0.0,0.0),VEC3(100.0,0.0,0.0),0.0,105.658,1); + KinKal::KinematicLine line(state,VEC3(0.0,0.0,0.0),TimeRange(0.0,1.0)); + KinKal::Plane plane(VEC3(1.0,0.0,0.0),VEC3(0.0,1.0,0.0),VEC3(0.0,0.0,0.0)); + auto raw = KinKal::intersect(line,plane,line.range(),tol,TimeDir::backwards); + require(raw.good() && raw.time_ == line.range().begin(),"solver fixture does not return an exact lower boundary"); + KinKal::ParticleTrajectory traj(line); + SweepTarget target; + target.surf_ = &plane; + auto inter = crossing(traj,{target},TimeDir::backwards); + require(inter.good() && inter.time_ == std::nextafter(0.0,1.0),"solver lower boundary lacks interior ownership"); + require(traj.nearestTraj(inter.time_) == traj.frontPtr(),"solver lower boundary has wrong piece"); + } + + void closeSeam(TimeDir dir) { + double sign = dir == TimeDir::forwards ? 1.0 : -1.0; + KinKal::ParticleState state(VEC3(0.0,0.0,-1.0),VEC3(0.0,0.0,100.0),0.0,105.658,1); + KinKal::KinematicLine line(state,VEC3(0.0,0.0,0.0),TimeRange(0.0,0.02)); + KinKal::ParticleTrajectory traj(line); + KinKal::Plane first(VEC3(0.0,0.0,1.0),VEC3(1.0,0.0,0.0),VEC3(0.0,0.0,0.0)); + KinKal::Plane second(VEC3(0.0,0.0,1.0),VEC3(1.0,0.0,0.0),VEC3(0.0,0.0,sign*0.5*tol)); + SweepTarget a, b; + a.sid_ = mu2e::SurfaceId(mu2e::SurfaceIdEnum::DS_Front); + b.sid_ = mu2e::SurfaceId(mu2e::SurfaceIdEnum::DS_Back); + a.effect_ = b.effect_ = SweepTarget::planeshell; + a.surf_ = a.pl_ = &first; + b.surf_ = b.pl_ = &second; + SweepTargetCollection targets{a,b}; + ExtrapolateSweep sweep(targets,dir,1.0,1.0,1.0e-4,tol,1.0e-6,0); + sweep.start(dir == TimeDir::forwards ? 0.0 : 0.02); + sweep.limit(dir == TimeDir::forwards ? 0.02 : 0.0,false); + sweep.needsExtrapolation(traj,dir); + require(sweep.hasCrossing(),"close seam lacks first plane"); + sweep.accept(); + sweep.needsExtrapolation(traj,dir); + require(!sweep.hasCrossing(),"close coplanar seam not suppressed"); + } + + SweepTarget seamTarget(KinKal::Plane const& plane, mu2e::SurfaceId::enum_type id, SweepTarget::Effect pool, + MatEnv::DetMaterial const& material) { + SweepTarget target; + target.sid_ = mu2e::SurfaceId(id); + target.effect_ = pool; + target.surf_ = target.pl_ = &plane; + target.mat_ = &material; + target.thick_ = 0.01; + return target; + } + + void tangentEpisode(TimeDir dir, bool split, bool windows, SweepTarget::Effect pool, + MatEnv::DetMaterial const& material, MatEnv::DetMaterial const& differentMaterial, unsigned control) { + constexpr double seamTol = 0.1; + double sign = dir == TimeDir::forwards ? 1.0 : -1.0; + KinKal::ParticleState state(VEC3(0.0,0.0,0.0),VEC3(100.0,0.0,10.0),0.0,105.658,1); + KinKal::KinematicLine line(state,VEC3(0.0,0.0,0.0),TimeRange(-1.0,1.0)); + double vx = line.velocity(0.0).X(), end = sign*4.0/vx, begin = -end; + double lo = std::min(begin,end), hi = std::max(begin,end), join = sign*0.6/vx; + line.setRange(TimeRange(lo,split ? join : hi)); + KinKal::ParticleTrajectory traj(line); + if(split){ + auto tail = line; + tail.setRange(TimeRange(join,hi)); + traj.append(tail); + } + KinKal::Rectangle first(VEC3(0.0,0.0,1.0),VEC3(1.0,0.0,0.0),VEC3(0.0,0.0,0.0),control == 5 ? 0.05 : 10.0,10.0); + KinKal::Rectangle second(VEC3(0.0,0.0,-1.0),VEC3(1.0,0.0,0.0),VEC3(sign*0.5,0.0,sign*0.05),10.0,10.0); + KinKal::Rectangle tilted(VEC3(0.02,0.0,1.0),VEC3(1.0,0.0,-0.02),VEC3(0.0,0.0,0.0),10.0,10.0); + KinKal::Rectangle separate(VEC3(0.0,0.0,1.0),VEC3(1.0,0.0,0.0),VEC3(0.0,0.0,sign*0.2),10.0,10.0); + KinKal::Rectangle nonoverlap(VEC3(0.0,0.0,1.0),VEC3(1.0,0.0,0.0),VEC3(sign*2.2,0.0,sign*0.05),1.8,10.0); + KinKal::Plane intervening(VEC3(1.0,0.0,0.0),VEC3(0.0,1.0,0.0),VEC3(sign*0.8,0.0,0.0)); + auto a = seamTarget(first,mu2e::SurfaceIdEnum::DS_Front,pool,material); + auto b = seamTarget(second,mu2e::SurfaceIdEnum::DS_Back,pool,material); + auto c = seamTarget(intervening,mu2e::SurfaceIdEnum::TT_Front,pool,material); + if(control == 1) b.mat_ = &differentMaterial; + if(control == 2) b.thick_ *= 2.0; + if(control == 3) b.surf_ = b.pl_ = &tilted; + if(control == 4) b.surf_ = b.pl_ = &separate; + if(control == 5) b.surf_ = b.pl_ = &nonoverlap; + if(control == 6) b.effect_ = pool == SweepTarget::planeshell ? SweepTarget::crvsector : SweepTarget::planeshell; + if(control == 7) a.maxcross_ = 0; + SweepTargetCollection targets{a,b,c}; + double step = windows ? 0.15/vx : hi-lo; + ExtrapolateSweep sweep(targets,dir,1.0,step,1.0e-4,seamTol,1.0e-6,0); + sweep.start(0.0); + sweep.limit(end,false); + require(!sweep.needsExtrapolation(traj,dir) && sweep.hasCrossing(),"tangent episode lacks first crossing"); + require(sweep.crossing().itarget_ == 0,"tangent first target differs"); + double accepted = sweep.crossing().inter_.time_; + require(std::fabs(first.distance(sweep.crossing().inter_.pos_)) < seamTol,"tangent first point off plane"); + sweep.accept(); + sweep.start(accepted); + if(control == 0 || control == 7){ + sweep.limit(sign*0.15/vx,false); + require(!sweep.needsExtrapolation(traj,dir) && !sweep.hasCrossing(),"tangent seam escaped a short window"); + sweep.start(sign*0.15/vx); + sweep.limit(end,false); + require(!sweep.needsExtrapolation(traj,dir) && sweep.hasCrossing(),"intervening plane absent"); + require(sweep.crossing().itarget_ == 2,"tangent seam escaped before different-plane accept"); + accepted = sweep.crossing().inter_.time_; + sweep.accept(); + sweep.start(accepted); + require(!sweep.needsExtrapolation(traj,dir) && !sweep.hasCrossing(),"episode lost across start/piece/window/different-plane accept"); + } else { + bool neighbor = false; + for(unsigned trial = 0; trial < 3; ++trial){ + require(!sweep.needsExtrapolation(traj,dir),"control requests extrapolation"); + if(!sweep.hasCrossing()) break; + if(sweep.crossing().itarget_ == 1) neighbor = true; + sweep.accept(); + } + require(neighbor,"ineligible seam neighbor incorrectly suppressed"); + } + } + + void helixEpisodes(TimeDir dir, bool split, bool windows, bool self, MatEnv::DetMaterial const& material) { + double sign = dir == TimeDir::forwards ? 1.0 : -1.0; + KinKal::ParticleState state(VEC3(0.0,0.0,0.0),VEC3(100.0,0.0,20.0),0.0,105.658,1); + KinKal::LoopHelix helix(state,VEC3(0.0,0.0,1.0),TimeRange(-1.0,1.0)); + double period = 2.0*std::acos(-1.0)*helix.energy(0.0)/(KinKal::BFieldMap::cbar()*CLHEP::c_light); + double begin = -sign*0.1*period, end = sign*1.2*period; + double lo = std::min(begin,end), hi = std::max(begin,end), join = sign*0.25*period; + helix.setRange(TimeRange(lo,split ? join : hi)); + KinKal::ParticleTrajectory traj(helix); + if(split){ + auto tail = helix; + tail.setRange(TimeRange(join,hi)); + traj.append(tail); + } + KinKal::Rectangle first(VEC3(1.0,0.0,0.0),VEC3(0.0,1.0,0.0),VEC3(0.0,0.0,0.0),2000.0,2000.0); + KinKal::Rectangle second(VEC3(-1.0,0.0,0.0),VEC3(0.0,1.0,0.0),VEC3(0.0,0.0,10.0),2000.0,2000.0); + auto a = seamTarget(first,mu2e::SurfaceIdEnum::DS_Front,SweepTarget::planeshell,material); + auto b = seamTarget(second,mu2e::SurfaceIdEnum::DS_Back,SweepTarget::planeshell,material); + a.maxcross_ = self ? 0 : 1; + SweepTargetCollection targets = self ? SweepTargetCollection{a} : SweepTargetCollection{a,b}; + ExtrapolateSweep sweep(targets,dir,100.0,windows ? 0.13*period : hi-lo,1.0e-4,0.1,1.0e-6,0); + sweep.start(begin); + sweep.limit(end,false); + for(unsigned icross = 0; icross < (self ? 3u : 2u); ++icross){ + require(!sweep.needsExtrapolation(traj,dir) && sweep.hasCrossing(),"depart-return helix crossing absent"); + auto const inter = sweep.crossing().inter_; + require(sweep.crossing().itarget_ == (self ? 0u : icross),"neighbor quota consumed by suppressed seam"); + require(std::fabs(inter.time_-sign*0.5*period*icross)*helix.speed(0.0) < 1.0,"helix recross time differs"); + if(icross > 0){ + auto pos = traj.position3(sign*(0.5*icross-0.25)*period); + require(std::fabs(first.distance(pos)) > 0.1 && std::fabs(second.distance(pos)) > 0.1,"helix lacks out-of-both departure"); + } + sweep.accept(); + sweep.start(inter.time_); + } + require(!sweep.needsExtrapolation(traj,dir) && !sweep.hasCrossing(),"helix episode/quota retained an extra crossing"); + } + + template void shallowEpisode(TimeDir dir, bool split, bool windows, bool reverse, MatEnv::DetMaterial const& material) { + double sign = dir == TimeDir::forwards ? 1.0 : -1.0; + KinKal::ParticleState state(VEC3(0.0,0.0,0.0),VEC3(100.0,0.0,20.0),0.0,105.658,1); + HELIX helix(state,VEC3(0.0,0.0,1.0),TimeRange(-100.0,100.0)); + double omega = KinKal::BFieldMap::cbar()*CLHEP::c_light/helix.energy(), pi = std::acos(-1.0); + double maximum = sign*0.5*pi/omega; + double radius = std::fabs(helix.position3(maximum).X()); + double halfwidth = std::acos(1.0-0.15/radius)/omega; + double begin = maximum-sign*halfwidth, end = maximum+sign*1.5*halfwidth; + double lo = std::min(begin-sign*halfwidth,end), hi = std::max(begin-sign*halfwidth,end); + helix.setRange(TimeRange(lo,split ? maximum : hi)); + KinKal::ParticleTrajectory traj(helix); + if(split){ + auto tail = helix; + tail.setRange(TimeRange(maximum,hi)); + traj.append(tail); + } + KinKal::Rectangle plane(VEC3(1.0,0.0,0.0),VEC3(0.0,1.0,0.0),helix.position3(begin),2000.0,2000.0); + auto a = seamTarget(plane,mu2e::SurfaceIdEnum::DS_Front,SweepTarget::planeshell,material); + auto b = seamTarget(plane,mu2e::SurfaceIdEnum::DS_Back,SweepTarget::planeshell,material); + SweepTargetCollection targets = reverse ? SweepTargetCollection{b,a} : SweepTargetCollection{a,b}; + ExtrapolateSweep sweep(targets,dir,100.0,windows ? 0.3*halfwidth : 100.0,1.0e-4,0.1,1.0e-6,0); + sweep.start(begin); + sweep.limit(end,false); + require(!sweep.needsExtrapolation(traj,dir) && sweep.hasCrossing() && targets[sweep.crossing().itarget_].sid_ == a.sid_,"shallow episode lacks first crossing"); + sweep.accept(); + require(std::fabs(plane.distance(helix.position3(maximum))) > 0.1 && + std::fabs(plane.distance(helix.position3(maximum))) < 0.2,"shallow fixture does not resolve only one tolerance"); + require(!sweep.needsExtrapolation(traj,dir) && sweep.hasCrossing() && targets[sweep.crossing().itarget_].sid_ == b.sid_,"shallow resolved depart-return was suppressed"); + require(sign*(sweep.crossing().inter_.time_-maximum) > 0.0,"shallow return accepted before resolved departure"); + require(std::fabs(plane.distance(sweep.crossing().inter_.pos_)) < 0.1,"shallow return outside plane tolerance"); + // An outgoing query must find the later root without requiring a preceding accepted seam. + targets.front().maxcross_ = targets.back().maxcross_ = 1; + ExtrapolateSweep outgoing(targets,dir,100.0,windows ? 0.3*halfwidth : 100.0,1.0e-4,0.1,1.0e-6,0); + double queryStart = maximum-sign*0.5*halfwidth; + require(std::fabs(plane.distance(helix.position3(queryStart))) > 0.1,"outgoing query starts inside tolerance slab"); + outgoing.start(queryStart); + outgoing.limit(end,false); + require(!outgoing.needsExtrapolation(traj,dir) && outgoing.hasCrossing(),"outgoing query lost bracketed later plane root"); + auto const& inter = outgoing.crossing().inter_; + double expected = maximum+sign*halfwidth; + require(sign*(inter.time_-queryStart) > 0.0 && sign*(inter.time_-maximum) > 0.0,"outgoing query returned earlier plane root"); + if(!windows) require(std::fabs(inter.time_-expected)*helix.speed(inter.time_) < 0.1,"bracketed shallow return time differs"); + require(plane.onSurface(inter.pos_,0.1),"outgoing return is outside plane tolerance"); + require((inter.pdir_-helix.direction(inter.time_)).R() < 1.0e-12,"backwards root reversed physical momentum direction"); + } + + template void planeContacts(TimeDir dir) { + double sign = dir == TimeDir::forwards ? 1.0 : -1.0, tolerance = 0.1; + KinKal::ParticleState state(VEC3(10.0,20.0,30.0),VEC3(100.0,0.0,20.0),0.0,105.658,1); + HELIX helix(state,VEC3(0.0,0.0,1.0),TimeRange(-100.0,100.0)); + double omega = KinKal::BFieldMap::cbar()*CLHEP::c_light/helix.energy(); + double peak = sign*0.5*std::acos(-1.0)/omega, width = 0.05/omega; + helix.setRange(TimeRange(peak-width,peak+width)); + KinKal::ParticleTrajectory traj(helix); + for(double offset : {0.0,0.5*tolerance,1.5*tolerance}){ + auto pos = helix.position3(peak)+VEC3(sign*offset,0.0,0.0); + KinKal::Plane plane(VEC3(1.0,0.0,0.0),VEC3(0.0,1.0,0.0),pos); + SweepTarget target; + target.sid_ = mu2e::SurfaceId(mu2e::SurfaceIdEnum::TT_Front); + target.surf_ = target.pl_ = &plane; + for(unsigned edge : {0u,1u}){ + for(double mincos : {0.0,0.01}){ + target.mincos_ = mincos; + SweepTargetCollection targets{target}; + ExtrapolateSweep sweep(targets,dir,100.0,100.0,1.0e-4,tolerance,1.0e-6,0); + double begin = edge == 1 ? peak : helix.range().begin(); + double end = helix.range().end(); + sweep.start(sign > 0.0 ? begin : end); + sweep.limit(sign > 0.0 ? end : begin,false); + require(!sweep.needsExtrapolation(traj,dir),"contact search requests extension"); + bool expected = offset < tolerance && mincos == 0.0; + require(sweep.hasCrossing() == expected,"plane contact/incidence policy differs"); + if(expected){ + auto const& inter = sweep.crossing().inter_; + require(plane.onSurface(inter.pos_,tolerance),"contact outside plane tolerance"); + require(std::fabs(inter.time_-peak)*helix.speed(peak) < tolerance,"contact time is not the plane-distance extremum"); + } + } + } + } + } + + template void longPlaneQuery(TimeDir dir) { + double sign = dir == TimeDir::forwards ? 1.0 : -1.0; + KinKal::ParticleState state(VEC3(10.0,20.0,30.0),VEC3(100.0,0.0,20.0),0.0,105.658,1); + HELIX helix(state,VEC3(0.0,0.0,1.0),TimeRange(-100.0,100.0)); + double period = 2.0*std::acos(-1.0)*helix.energy()/(KinKal::BFieldMap::cbar()*CLHEP::c_light); + helix.setRange(TimeRange(sign > 0.0 ? 0.0 : -300.0*period,sign > 0.0 ? 300.0*period : 0.0)); + KinKal::ParticleTrajectory traj(helix); + KinKal::Plane plane(VEC3(1.0,0.0,0.0),VEC3(0.0,1.0,0.0),helix.position3(sign*0.125*period)); + SweepTarget target; + target.sid_ = mu2e::SurfaceId(mu2e::SurfaceIdEnum::TT_Front); + target.surf_ = target.pl_ = &plane; + auto inter = crossing(traj,{target},dir); + require(std::fabs(inter.time_-sign*0.125*period)*helix.speed(inter.time_) < tol,"long query lost early bracketed crossing"); + } + + void speculativeEpisode(TimeDir dir, MatEnv::DetMaterial const& material) { + double sign = dir == TimeDir::forwards ? 1.0 : -1.0; + auto makeLine = [](VEC3 const& pos, VEC3 const& momentum, double time){ + KinKal::ParticleState state(pos,momentum,time,105.658,1); + return KinKal::KinematicLine(state,VEC3(0.0,0.0,0.0),TimeRange(time-1.0,time+1.0)); + }; + auto first = makeLine(VEC3(0.0,0.0,0.0),VEC3(100.0,0.0,2.0),0.0); + double t1 = sign*2.0/first.velocity(0.0).X(); + auto middle = makeLine(first.position3(t1),VEC3(100.0,0.0,46.0),t1); + double t2 = t1+sign/middle.velocity(t1).X(); + auto last = makeLine(middle.position3(t2),VEC3(100.0,0.0,-50.0),t2); + double end = t2+sign*1.2/last.velocity(t2).X(); + first.setRange(TimeRange(std::min(0.0,t1),std::max(0.0,t1))); + middle.setRange(TimeRange(std::min(t1,t2),std::max(t1,t2))); + last.setRange(TimeRange(std::min(t2,end),std::max(t2,end))); + KinKal::ParticleTrajectory traj; + if(dir == TimeDir::forwards){ traj.append(first); traj.append(middle); traj.append(last); } + else { traj.append(last); traj.append(middle); traj.append(first); } + KinKal::Rectangle plane(VEC3(0.0,0.0,1.0),VEC3(1.0,0.0,0.0),VEC3(0.0,0.0,0.0),10.0,10.0); + KinKal::Plane other(VEC3(1.0,0.0,0.0),VEC3(0.0,1.0,0.0),VEC3(sign*0.8,0.0,0.0)); + auto a = seamTarget(plane,mu2e::SurfaceIdEnum::DS_Front,SweepTarget::planeshell,material); + auto b = seamTarget(plane,mu2e::SurfaceIdEnum::DS_Back,SweepTarget::planeshell,material); + auto c = seamTarget(other,mu2e::SurfaceIdEnum::TT_Front,SweepTarget::planeshell,material); + SweepTargetCollection targets{a,b,c}; + ExtrapolateSweep sweep(targets,dir,1.0,1.0,1.0e-4,0.1,1.0e-6,0); + sweep.start(0.0); + sweep.limit(end,false); + require(!sweep.needsExtrapolation(traj,dir) && sweep.hasCrossing() && sweep.crossing().itarget_ == 0, + "speculative fixture lacks initial seam crossing"); + double initial = sweep.crossing().inter_.time_; + sweep.accept(); + sweep.setActive(2,false); + require(!sweep.needsExtrapolation(traj,dir) && sweep.hasCrossing() && sweep.crossing().itarget_ == 1 && + sign*(sweep.crossing().inter_.time_-t2) > 0.0,"speculative fixture lacks future return candidate"); + sweep.setActive(2,true); + sweep.start(initial); + require(!sweep.needsExtrapolation(traj,dir) && sweep.hasCrossing() && sweep.crossing().itarget_ == 2, + "earlier different plane did not win over future return"); + double accepted = sweep.crossing().inter_.time_; + sweep.accept(); + auto changed = first; + changed.setRange(TimeRange(std::min(0.0,end),std::max(0.0,end))); + KinKal::ParticleTrajectory updated(changed); + require(std::fabs(plane.distance(updated.position3(end))) < 0.1,"updated trajectory left the seam slab"); + sweep.start(accepted); + require(!sweep.needsExtrapolation(updated,dir) && !sweep.hasCrossing(), + "speculative future witness released an episode before trajectory mutation"); + } + + KinKal::LoopHelix materialPiece(double join, TimeRange const& range, VEC3 const& momentum) { + KinKal::ParticleState state(VEC3(10.0,20.0,30.0),momentum,join,105.658,1); + KinKal::DMAT covariance; + for(unsigned row = 0; row < 6; ++row) + for(unsigned col = 0; col <= row; ++col) covariance(row,col) = row == col ? 0.01 : 0.0; + return KinKal::LoopHelix(KinKal::ParticleStateEstimate(state,covariance),VEC3(0.0,0.0,1.0),range); + } + + void finiteState(KinKal::LoopHelix const& piece, double time) { + auto state = piece.stateEstimate(time); + for(unsigned row = 0; row < 6; ++row){ + require(std::isfinite(state.state()[row]),"nonfinite material state"); + require(state.stateCovariance()(row,row) > 0.0,"material state has nonpositive variance"); + for(unsigned col = 0; col < 6; ++col) + require(std::isfinite(state.stateCovariance()(row,col)),"nonfinite material state covariance"); + } + } + + void sameIntersection(KinKal::Intersection const& a, KinKal::Intersection const& b) { + require(a.time_ == b.time_ && a == b && a.gap_ == b.gap_,"Material constructor changed crossing time/flags"); + require((a.pos_-b.pos_).R() == 0.0 && (a.pdir_-b.pdir_).R() == 0.0 && (a.norm_-b.norm_).R() == 0.0, + "Material constructor changed crossing geometry"); + } + + void materialPieceEdge(TimeDir dir, unsigned npiece, double join, MatEnv::DetMaterial const& targetMaterial, + bool boundary = true) { + using Helix = KinKal::LoopHelix; + using Shell = mu2e::KKShellXing; + bool forward = dir == TimeDir::forwards; + unsigned joinIndex = forward ? npiece-1 : 1; + KinKal::ParticleTrajectory traj; + for(unsigned ip = 0; ip < npiece; ++ip){ + double begin = join+(static_cast(ip)-static_cast(joinIndex))*0.1; + double end = join+(static_cast(ip)+1-static_cast(joinIndex))*0.1; + bool selected = ip == (forward ? npiece-1 : 0); + auto piece = materialPiece(join,TimeRange(begin,end), + selected ? VEC3(60.0,30.0,100.0) : VEC3(65.0+5.0*ip,35.0,110.0+5.0*ip)); + traj.append(piece); + } + // Shared nearestIndex assigns an exact join to the earlier piece. + for(unsigned ip = 1; ip < npiece; ++ip){ + double edge = traj.piece(ip).range().begin(); + require(traj.nearestIndex(edge) == ip-1,"nearestIndex no longer chooses earlier join piece"); + require(traj.nearestTraj(edge) == traj.indexTraj(ip-1),"exact join pointer differs"); + } + auto ref = forward ? traj.backPtr() : traj.frontPtr(); + auto neighbor = traj.indexTraj(forward ? npiece-2 : 1); + require(ref != neighbor && (ref->momentum3(join)-neighbor->momentum3(join)).R() > 1.0, + "material fixture does not distinguish neighboring pieces"); + double root = boundary ? join : join+(forward ? 0.05 : -0.05); + double expected = boundary ? std::nextafter(join,forward ? ref->range().end() : ref->range().begin()) : root; + auto annulus = std::make_shared(VEC3(0.0,0.0,1.0),VEC3(1.0,0.0,0.0),ref->position3(root),0.0,100.0); + SweepTarget target; + target.sid_ = mu2e::SurfaceId(mu2e::SurfaceIdEnum::TT_Front); + target.effect_ = SweepTarget::stfoil; + target.surf_ = target.pl_ = annulus.get(); + target.ann_ = annulus; + target.mat_ = &targetMaterial; + target.thick_ = 0.1056; + target.maxcross_ = 1; + SweepTargetCollection targets{target}; + ExtrapolateSweep sweep(targets,dir,1.0,1.0,1.0e-4,tol,1.0e-6,0); + sweep.start(root); + sweep.limit(forward ? ref->range().end() : std::nextafter(ref->range().begin(),ref->range().end()),false); + require(!sweep.needsExtrapolation(traj,dir) && sweep.hasCrossing(),"piece-edge material crossing absent"); + auto inter = sweep.crossing().inter_; + require(inter.time_ == expected,"piece-edge root is not exactly one ULP interior (or interior root moved)"); + require(inter.good() && !inter.gap_,"piece-edge crossing flags invalid"); + require(inter.time_ > ref->range().begin() && inter.time_ < ref->range().end(),"crossing not strictly inside end piece"); + require(traj.nearestTraj(inter.time_) == ref && ref->range().inRange(inter.time_),"crossing has wrong owning piece"); + require(std::fabs(inter.time_-root)*ref->speed(root) <= tol,"normalized time changed physical root"); + require((inter.pos_-ref->position3(inter.time_)).R() == 0.0 && + (inter.pdir_-ref->direction(inter.time_)).R() == 0.0 && + (inter.norm_-annulus->normal(inter.pos_)).R() == 0.0,"normalized crossing geometry is stale"); + require(annulus->onSurface(inter.pos_,tol) && annulus->inBounds(inter.pos_,tol),"normalized crossing left annulus"); + auto shell = std::make_shared(annulus,target.sid_,targetMaterial,inter,ref,target.thick_,tol); + require(&shell->referenceTrajectory() == ref.get() && shell->active(),"shell lost owning piece or active material"); + KinKal::Material material(shell,traj); + // Constructor reference lookup must retain the accepted root and source piece. + require(material.elementXingPtr() == shell && &material.referenceTrajectory() == ref.get(),"Material constructor changed reference pointer"); + sameIntersection(shell->intersection(),inter); + require(material.time() == expected && material.active() && shell->matXings().size() == 1,"Material constructor lost active crossing"); + require(std::isfinite(shell->matXings().front().plen_) && shell->matXings().front().plen_ > 0.0,"invalid shell material path"); + finiteState(*ref,inter.time_); + KinKal::SVEC3 dmom; + KinKal::SMAT dmomvar; + shell->momentumChange(dmom,dmomvar); + double dm, parallel, perpendicular; + shell->materialEffects(dm,parallel,perpendicular); + require(std::isfinite(dm) && dm < 0.0 && std::isfinite(parallel) && parallel >= 0.0 && + std::isfinite(perpendicular) && perpendicular > 0.0,"material effects inactive or nonfinite"); + for(unsigned row = 0; row < 3; ++row){ + require(std::isfinite(dmom[row]),"nonfinite material momentum change"); + for(unsigned col = 0; col < 3; ++col) require(std::isfinite(dmomvar(row,col)),"nonfinite material momentum variance"); + } + auto originalRange = traj.range(); + auto originalPieces = traj.pieces(); + VEC3 expectedMomentum = ref->momentum3(inter.time_)+(forward ? 1.0 : -1.0)*VEC3(dmom[0],dmom[1],dmom[2]); + material.extrapolate(traj,dir); + require(traj.pieces().size() == npiece+1,"material extrapolation did not add one piece"); + require(traj.range().begin() == originalRange.begin() && traj.range().end() == originalRange.end(),"material extrapolation changed total range"); + for(unsigned ip = 0; ip < traj.pieces().size(); ++ip){ + require(traj.indexTraj(ip) && !traj.piece(ip).range().null(),"material insertion produced null piece/range"); + if(ip > 0) require(traj.piece(ip-1).range().end() == traj.piece(ip).range().begin(),"material insertion ranges not contiguous"); + } + for(unsigned ip = 0; ip < npiece; ++ip) + require(traj.indexTraj(ip+(forward ? 0 : 1)) == originalPieces[ip],"material insertion replaced existing piece pointer"); + auto added = forward ? traj.backPtr() : traj.frontPtr(); + require(added != ref && (forward ? added->range().begin() : added->range().end()) == expected,"new material piece boundary differs"); + require((added->position3(expected)-inter.pos_).R() < tol && + (added->momentum3(expected)-expectedMomentum).R() < tol,"material extrapolation state differs"); + finiteState(*added,expected); + sameIntersection(shell->intersection(),inter); + require(&shell->referenceTrajectory() == ref.get(),"extrapolation changed shell reference"); + sweep.accept(); + require(!sweep.hasCrossing(),"accept retained cached crossing"); + require(!sweep.needsExtrapolation(traj,dir) && !sweep.hasCrossing(),"maxcross=1 material re-found after accept"); + } + + void invalidBoundaryInterior(TimeDir dir, bool narrow) { + bool forward = dir == TimeDir::forwards; + double begin = narrow ? 90208.803182193456 : std::ldexp(1.0,40); + double end = narrow ? std::nextafter(begin,std::numeric_limits::infinity()) : begin+0.1; + double root = forward ? begin : end; + KinKal::ParticleState state(VEC3(10.0,20.0,30.0),VEC3(60.0,30.0,100.0),root,105.658,1); + KinKal::KinematicLine line(state,VEC3(0.0,0.0,0.0),TimeRange(begin,end)); + KinKal::ParticleTrajectory traj(line); + KinKal::Plane plane(VEC3(0.0,0.0,1.0),VEC3(1.0,0.0,0.0),line.position3(root)); + SweepTarget target; + target.surf_ = &plane; + SweepTargetCollection targets{target}; + ExtrapolateSweep sweep(targets,dir,1.0,1.0,1.0e-4,tol,1.0e-6,0); + sweep.start(root); + sweep.limit(forward ? end : begin,false); + bool failed = false; + try { + sweep.needsExtrapolation(traj,dir); + } catch(std::runtime_error const& error) { + auto expected = narrow ? "no representable piece interior" : "displacement exceeds intersection tolerance"; + failed = std::string(error.what()).find(expected) != std::string::npos; + } + require(failed && !sweep.hasCrossing(),"invalid boundary interior must fail explicitly without accepting geometry"); + } + + // The per-window reach bound must keep crossings just before a window end and in later windows. + void reachBound(TimeDir dir) { + KinKal::ParticleState state(VEC3(0.0,0.0,0.0),VEC3(0.0,0.0,100.0),0.0,105.658,1); + KinKal::KinematicLine line(state,VEC3(0.0,0.0,0.0),TimeRange(0.0,10.0)); + KinKal::ParticleTrajectory traj(line); + bool forward = dir == TimeDir::forwards; + for(double dt : {0.999999,1.5,3.25}){ + double tcross = forward ? dt : 10.0-dt; + KinKal::Plane plane(VEC3(0.0,0.0,1.0),VEC3(1.0,0.0,0.0),line.position3(tcross)); + SweepTarget target; + target.surf_ = target.pl_ = &plane; + auto inter = crossing(traj,{target},dir,1.0); + require(std::fabs(inter.time_-tcross)*line.speed(tcross) <= tol,"reach bound dropped a crossing near a window end"); + } + } + + // A crossing ranges out forwards in time exactly when its mean energy loss reaches the kinetic energy, never backwards. + void rangeOut(MatEnv::DetMaterial const& material) { + using Helix = KinKal::LoopHelix; + using Shell = mu2e::KKShellXing; + double const mass = 105.658, thick = 10.0; + for(double pmag : {30.0,1000.0}){ + KinKal::ParticleState state(VEC3(0.0,0.0,0.0),VEC3(0.0,0.2*pmag,pmag),0.0,mass,1); + auto helix = std::make_shared(state,VEC3(0.0,0.0,1.0),TimeRange(0.0,1.0)); + auto plane = std::make_shared(VEC3(0.0,0.0,1.0),VEC3(1.0,0.0,0.0),helix->position3(0.5)); + auto inter = KinKal::intersect(*helix,*plane,helix->range(),tol); + require(inter.good(),"range-out fixture has no crossing"); + Shell shell(plane,mu2e::SurfaceId(mu2e::SurfaceIdEnum::TT_Front),material,inter,helix,thick,tol); + double p = helix->momentum(), ke = helix->energy()-mass; + double eloss = std::fabs(material.energyLoss(p,shell.matXings().front().plen_,mass)); + bool stops = eloss >= ke; + require(stops == (pmag < 100.0),"range-out fixture does not bracket the kinetic energy"); + require(mu2e::rangesOut(shell,TimeDir::forwards) == stops,"forwards range-out disagrees with energy loss vs kinetic energy"); + require(!mu2e::rangesOut(shell,TimeDir::backwards),"backwards extrapolation must never range out"); + } + } + + void retryBudget() { + KinKal::ParticleState state(VEC3(0.0,0.0,0.0),VEC3(100.0,0.0,20.0),0.0,105.658,1); + KinKal::LoopHelix helix(state,VEC3(0.0,0.0,1.0),TimeRange(0.0,1.0)); + double period = 2.0*std::acos(-1.0)/std::fabs(helix.omega()); + helix.setRange(TimeRange(0.0,300.0*period)); + KinKal::ParticleTrajectory traj(helix); + KinKal::Plane plane(VEC3(1.0,0.0,0.0),VEC3(0.0,1.0,0.0),VEC3(2.0*helix.bendRadius(),0.0,0.0)); + SweepTarget target; + target.surf_ = target.pl_ = &plane; + bool failed = false; + try { + crossing(traj,{target},TimeDir::forwards); + } catch(std::runtime_error const& error) { + failed = std::string(error.what()).find("extrema budget") != std::string::npos; + } + require(failed,"unresolved long plane search must fail explicitly at the extrema budget"); + } + + void emptySearch() { + KinKal::ParticleState state(VEC3(0.0,0.0,0.0),VEC3(0.0,0.0,100.0),0.0,105.658,1); + KinKal::KinematicLine line(state,VEC3(0.0,0.0,0.0),TimeRange(0.0,0.1)); + KinKal::ParticleTrajectory traj(line); + SweepTargetCollection targets; + ExtrapolateSweep sweep(targets,TimeDir::forwards,1.0,1.0,1.0e-4,tol,1.0e-6,0); + sweep.start(0.0); + sweep.limit(0.1,false); + require(!sweep.needsExtrapolation(traj,TimeDir::forwards) && !sweep.hasCrossing(),"empty target search"); + } +} + +int main() { + try { + auto workdir = std::getenv("MUSE_WORK_DIR"); + require(workdir && *workdir,"MUSE_WORK_DIR is required for TrackerConditions material data"); + MatEnv::SimpleFileFinder finder("MUSE_WORK_DIR","/Offline/TrackerConditions/data/"); + MatEnv::MatDBInfo materials(finder); + auto targetMaterial = materials.findDetMaterial("Target"); + require(static_cast(targetMaterial),"Target material unavailable"); + auto differentMaterial = materials.findDetMaterial("Mylar"); + require(static_cast(differentMaterial),"Mylar material unavailable"); + for(auto dir : {TimeDir::forwards,TimeDir::backwards}){ + for(unsigned npiece : {2u,3u}) + for(double join : {90208.803182193456,-90208.803182193456,0.0}){ + materialPieceEdge(dir,npiece,join,*targetMaterial); + materialPieceEdge(dir,npiece,join,*targetMaterial,false); + } + reachBound(dir); + invalidBoundaryInterior(dir,true); + invalidBoundaryInterior(dir,false); + closeSeam(dir); + planarLimits(dir); + planeContacts(dir); + planeContacts(dir); + longPlaneQuery(dir); + longPlaneQuery(dir); + speculativeEpisode(dir,*targetMaterial); + for(bool split : {false,true}){ + for(bool windows : {false,true}){ + for(bool reverse : {false,true}){ + shallowEpisode(dir,split,windows,reverse,*targetMaterial); + shallowEpisode(dir,split,windows,reverse,*targetMaterial); + } + for(auto pool : {SweepTarget::planeshell,SweepTarget::crvsector,SweepTarget::stfoil}){ + tangentEpisode(dir,split,windows,pool,*targetMaterial,*differentMaterial,0); + tangentEpisode(dir,split,windows,pool,*targetMaterial,*differentMaterial,7); + } + helixEpisodes(dir,split,windows,false,*targetMaterial); + helixEpisodes(dir,split,windows,true,*targetMaterial); + } + } + for(unsigned control = 1; control <= 6; ++control) + for(bool windows : {false,true}) tangentEpisode(dir,true,windows,SweepTarget::planeshell,*targetMaterial,*differentMaterial,control); + for(bool split : {false,true}){ + boundaries(dir,split); + for(bool bounds : {false,true}) lineRoots(dir,split,bounds); + } + } + rangeOut(*targetMaterial); + solverLowerBoundary(); + tiltedZ(); + tiltedZ(); + stableTieAndSeams(); + retryBudget(); + emptySearch(); + std::cout << "ExtrapolateSweepTest: all checks passed" << std::endl; + return 0; + } catch(std::exception const& error) { + std::cerr << "ExtrapolateSweepTest: " << error.what() << std::endl; + return 1; + } +} diff --git a/Mu2eKinKal/src/KinematicLineFit_module.cc b/Mu2eKinKal/src/KinematicLineFit_module.cc index 1ecc83e40c..ee0d03bf26 100644 --- a/Mu2eKinKal/src/KinematicLineFit_module.cc +++ b/Mu2eKinKal/src/KinematicLineFit_module.cc @@ -378,7 +378,8 @@ namespace mu2e { void KinematicLineFit::sampleFit(KKTRK& kktrk) const { auto const& ftraj = kktrk.fitTraj(); // need to extend range for now even if sampleinrange_ is false - TimeRange extrange(ftraj.range().begin() - sampletbuff_,ftraj.range().end() + sampletbuff_); + // a particle that ranges out stops there, so its trajectory is not extended forwards + TimeRange extrange(ftraj.range().begin() - sampletbuff_,ftraj.range().end() + (kktrk.rangedOut() ? 0.0 : sampletbuff_)); kktrk.extendTraj(extrange); double tbeg = ftraj.range().begin(); @@ -392,7 +393,12 @@ namespace mu2e { // loop to find multiple intersections while(goodinter && cur_inter < max_inter) { cur_inter += 1; - TimeRange irange(tstart,std::max(ftraj.range().end(),tstart)); + double tmax = std::max(ftraj.range().end(),tstart); + if(kktrk.rangedOut()){ + tmax = std::min(tmax,kktrk.rangeOutTime()); + if(tstart >= tmax) break; + } + TimeRange irange(tstart,tmax); auto surfinter = KinKal::intersect(ftraj,*surf.second,irange,intertol_); goodinter = surfinter.onsurface_ && ( (! sampleinbounds_) || surfinter.inbounds_ ) && ( (!sampleinrange_) || irange.inRange(surfinter.time_)); if(goodinter) { diff --git a/Mu2eKinKal/src/SConscript b/Mu2eKinKal/src/SConscript index 1419c781cc..03c2b57683 100644 --- a/Mu2eKinKal/src/SConscript +++ b/Mu2eKinKal/src/SConscript @@ -101,6 +101,17 @@ helper.make_plugins([mainlib, 'pthread' ]) +helper.make_bin("ExtrapolateSweepTest", [ + 'mu2e_DataProducts', + 'KinKal_Fit', + 'KinKal_Detector', + 'KinKal_Trajectory', + 'KinKal_Geometry', + 'KinKal_MatEnv', + 'KinKal_General', + rootlibs +], []) + # This tells emacs to view this file in python mode. # Local Variables: # mode:python diff --git a/RecoDataProducts/inc/TrkFitFlag.hh b/RecoDataProducts/inc/TrkFitFlag.hh index e0d7c8126a..96f5bee1d9 100644 --- a/RecoDataProducts/inc/TrkFitFlag.hh +++ b/RecoDataProducts/inc/TrkFitFlag.hh @@ -20,6 +20,8 @@ namespace mu2e { MatCorr, BFCorr, FitOK, //15 KSF=16, KFF, TPRHelix, CPRHelix, Straight, KKLoopHelix,KKCentralHelix,KKLine, APRHelix, MPRHelix, AmbFitDir, //26 Regrown=27, + ExtrapFailed=28, // an extrapolation direction ended early on a problem with this track + RangedOut=29, // forwards extrapolation ended where the mean energy loss in a material reaches the kinetic energy MCSeed=31, //31 }; diff --git a/RecoDataProducts/src/TrkFitFlag.cc b/RecoDataProducts/src/TrkFitFlag.cc index 029527fe4a..618b0f3547 100644 --- a/RecoDataProducts/src/TrkFitFlag.cc +++ b/RecoDataProducts/src/TrkFitFlag.cc @@ -49,6 +49,8 @@ namespace mu2e { bitnames[std::string("MCSeed")] = bit_to_mask(MCSeed); bitnames[std::string("AmbiguousFitDir")] = bit_to_mask(AmbFitDir); bitnames[std::string("Regrown")] = bit_to_mask(Regrown); + bitnames[std::string("ExtrapolationFailed")] = bit_to_mask(ExtrapFailed); + bitnames[std::string("RangedOut")] = bit_to_mask(RangedOut); } return bitnames; } From 4afa41b1415c687728df129a68cd0e3f31180917 Mon Sep 17 00:00:00 2001 From: Rob Mina Date: Fri, 30 Oct 2026 14:07:13 -0500 Subject: [PATCH 2/3] Fix grazing intersections in extrapolation. --- Mu2eKinKal/inc/ExtrapolateSweep.hh | 135 +++++++++++-------- Mu2eKinKal/inc/KKExtrap.hh | 17 ++- Mu2eKinKal/inc/KKFit.hh | 3 + Mu2eKinKal/src/ExtrapolateSweepTest_main.cc | 65 +++++++-- Mu2eKinKal/src/RegrowKinematicLine_module.cc | 1 + Mu2eKinKal/src/RegrowLoopHelix_module.cc | 1 + 6 files changed, 149 insertions(+), 73 deletions(-) diff --git a/Mu2eKinKal/inc/ExtrapolateSweep.hh b/Mu2eKinKal/inc/ExtrapolateSweep.hh index f28d00b3bc..896f65e15e 100644 --- a/Mu2eKinKal/inc/ExtrapolateSweep.hh +++ b/Mu2eKinKal/inc/ExtrapolateSweep.hh @@ -19,16 +19,12 @@ #include #include #include +#include #include +#include #include namespace mu2e { - using KinKal::TimeDir; - using KinKal::TimeRange; - using KinKal::Intersection; - using KinKal::VEC3; - using KinKal::timeDirSign; - // one surface the sweep can cross struct SweepTarget { enum Effect { record=0, cylshell, ipashell, stfoil, planeshell, crvsector }; // what a crossing adds to the track @@ -60,11 +56,11 @@ namespace mu2e { class ExtrapolateSweep { public: - struct Crossing { size_t itarget_ = 0; Intersection inter_; }; - ExtrapolateSweep(SweepTargetCollection const& targets, TimeDir tdir, double maxdt, double maxdtstep, double dptol, + struct Crossing { size_t itarget_ = 0; KinKal::Intersection inter_; }; + ExtrapolateSweep(SweepTargetCollection const& targets, KinKal::TimeDir tdir, double maxdt, double maxdtstep, double dptol, double intertol, double minv, int debug) : targets_(targets), tdir_(tdir), maxDt_(maxdt), maxDtStep_(maxdtstep), dptol_(dptol), intertol_(intertol), minv_(minv), debug_(debug), active_(targets.size()), count_(targets.size(),0), - tlast_(targets.size(),0.0), episodes_(targets.size()), planes_(targets.size(),nullptr), cylinders_(targets.size(),nullptr) { + tlast_(targets.size(),0.0), coslast_(targets.size(),1.0), episodes_(targets.size()), planes_(targets.size(),nullptr), cylinders_(targets.size(),nullptr) { for(size_t itg = 0; itg < targets_.size(); ++itg){ active_[itg] = targets_[itg].active_; planes_[itg] = dynamic_cast(targets_[itg].surf_); @@ -76,15 +72,16 @@ namespace mu2e { double maxDtStep() const { return maxDtStep_; } double dpTolerance() const { return dptol_; } int debug() const { return debug_; } - // false (stop extending) once a crossing is cached, nothing driving is reachable, or a watched reflection happened - template bool needsExtrapolation(KinKal::ParticleTrajectory const& ptraj, TimeDir tdir) const; + // false (stop extending) once a crossing is cached, nothing driving is reachable, a watched reflection happened or the search failed + template bool needsExtrapolation(KinKal::ParticleTrajectory const& ptraj, KinKal::TimeDir tdir) const; + bool failed() const { return !error_.empty(); } + std::string const& error() const { return error_; } // why the search failed; KinKal's walk never sees the exception // sweep control void start(double tcursor) { searched_ = tcursor; found_ = reflected_ = false; } void limit(double tlimit, bool recordonly) { limited_ = true; tlimit_ = tlimit; recordonly_ = recordonly; } void unlimit() { limited_ = recordonly_ = false; } void watchReflection(double vbsign) { vbsign_ = vbsign; reflected_ = false; } void setActive(size_t itg, bool active) { active_[itg] = active; } - bool isActive(size_t itg) const { return active_[itg]; } bool hasCrossing() const { return found_; } bool reflected() const { return reflected_; } Crossing const& crossing() const { return crossing_; } @@ -92,23 +89,25 @@ namespace mu2e { // mark the cached crossing processed and move the search start to it void accept(); private: + template bool extend(KinKal::ParticleTrajectory const& ptraj) const; bool usable(size_t itg) const; - bool withinReach(size_t itg, VEC3 const& pos, double reach) const; + bool withinReach(size_t itg, KinKal::VEC3 const& pos, double reach) const; template bool search(KinKal::ParticleTrajectory const& ptraj, double tend) const; - template bool firstCrossing(KinKal::ParticleTrajectory const& ptraj, KTRAJ const& piece, size_t itg, TimeRange win, Intersection& inter) const; - template bool visitPlaneExtrema(KTRAJ const& piece, KinKal::Plane const& plane, TimeRange const& range, VISIT&& visit) const; - template Intersection planeCrossing(KTRAJ const& piece, KinKal::Plane const& plane, TimeRange const& query) const; - template void ownBoundary(KTRAJ const& piece, SweepTarget const& tg, Intersection& inter) const; - template bool seam(KinKal::ParticleTrajectory const& ptraj, size_t itg, Intersection const& inter) const; + template bool firstCrossing(KinKal::ParticleTrajectory const& ptraj, KTRAJ const& piece, size_t itg, KinKal::TimeRange win, KinKal::Intersection& inter) const; + template bool visitPlaneExtrema(KTRAJ const& piece, KinKal::Plane const& plane, KinKal::TimeRange const& range, VISIT&& visit) const; + template KinKal::Intersection planeCrossing(KTRAJ const& piece, KinKal::Plane const& plane, KinKal::TimeRange const& query) const; + template void ownBoundary(KTRAJ const& piece, SweepTarget const& tg, KinKal::Intersection& inter) const; + template bool seam(KinKal::ParticleTrajectory const& ptraj, size_t itg, KinKal::Intersection const& inter) const; template bool departed(KinKal::ParticleTrajectory const& ptraj, size_t itg, size_t previous, double accepted, double proposed) const; template bool reachable(KinKal::ParticleTrajectory const& ptraj) const; SweepTargetCollection const& targets_; - TimeDir tdir_; + KinKal::TimeDir tdir_; double maxDt_, maxDtStep_, dptol_, intertol_, minv_; int debug_; std::vector active_; // per target std::vector count_; // crossings processed per target std::vector tlast_; // time of the last processed crossing per target + std::vector coslast_; // |cos| between the surface normal and the direction at that crossing std::vector doneGroups_; // groups whose first crossing is processed struct SeamEpisode { size_t itarget_; double time_; }; std::vector> episodes_; // accepted seam episodes per eligible target, including self @@ -120,6 +119,7 @@ namespace mu2e { mutable double searched_ = 0.0; // the trajectory is searched up to this time mutable bool found_ = false, reflected_ = false; mutable Crossing crossing_; + mutable std::string error_; static constexpr unsigned maxRootTrials_ = 256; // per target, piece and window }; @@ -133,11 +133,11 @@ namespace mu2e { } // A trajectory moves at most speed x time, so a surface farther than that from the window start cannot be crossed in it. - inline bool ExtrapolateSweep::withinReach(size_t itg, VEC3 const& pos, double reach) const { + inline bool ExtrapolateSweep::withinReach(size_t itg, KinKal::VEC3 const& pos, double reach) const { if(planes_[itg]) return std::fabs(planes_[itg]->distance(pos)) <= reach; if(cylinders_[itg]){ auto const& cyl = *cylinders_[itg]; - VEC3 rel = pos - cyl.center(); + KinKal::VEC3 rel = pos - cyl.center(); double along = rel.Dot(cyl.axis()); double rho = (rel - along*cyl.axis()).R(); if(std::fabs(rho - cyl.radius()) > reach) return false; @@ -153,6 +153,7 @@ namespace mu2e { double time = crossing_.inter_.time_; ++count_[itg]; tlast_[itg] = time; + coslast_[itg] = std::fabs(crossing_.inter_.norm_.Dot(crossing_.inter_.pdir_)); if(tg.group_ >= 0) doneGroups_.push_back(tg.group_); if((tg.effect_ == SweepTarget::planeshell || tg.effect_ == SweepTarget::crvsector || tg.effect_ == SweepTarget::stfoil) && tg.pl_){ for(size_t other = 0; other < targets_.size(); ++other){ @@ -172,15 +173,29 @@ namespace mu2e { found_ = false; } - template bool ExtrapolateSweep::needsExtrapolation(KinKal::ParticleTrajectory const& ptraj, TimeDir) const { + template bool ExtrapolateSweep::needsExtrapolation(KinKal::ParticleTrajectory const& ptraj, KinKal::TimeDir) const { + if(failed()) return false; + try { + return extend(ptraj); + } catch(std::bad_alloc const&) { + throw; + } catch(std::exception const& err) { + // a problem with this track must not reach KinKal's field walk, which would mark the whole fit unusable + error_ = err.what(); + found_ = false; + return false; + } + } + + template bool ExtrapolateSweep::extend(KinKal::ParticleTrajectory const& ptraj) const { found_ = false; - double sgn = tdir_ == TimeDir::forwards ? 1.0 : -1.0; - double tend = tdir_ == TimeDir::forwards ? ptraj.range().end() : ptraj.range().begin(); + double sgn = tdir_ == KinKal::TimeDir::forwards ? 1.0 : -1.0; + double tend = tdir_ == KinKal::TimeDir::forwards ? ptraj.range().end() : ptraj.range().begin(); if(limited_ && sgn*(tend - tlimit_) > 0.0) tend = tlimit_; if(search(ptraj,tend)) return false; if(limited_) return false; if(vbsign_ != 0.0){ - auto const& ktraj = tdir_ == TimeDir::forwards ? ptraj.back() : ptraj.front(); + auto const& ktraj = tdir_ == KinKal::TimeDir::forwards ? ptraj.back() : ptraj.front(); double vb = ktraj.velocity(tend).Dot(ktraj.bnom().Unit())*sgn; if(vb*vbsign_ < 0.0){ if(debug_ > 1) std::cout << "Sweep: reflection at time " << tend << " z " << ktraj.position3(tend).Z() << std::endl; @@ -192,13 +207,13 @@ namespace mu2e { } template bool ExtrapolateSweep::visitPlaneExtrema(KTRAJ const& piece, - KinKal::Plane const& plane, TimeRange const& range, VISIT&& visit) const { + KinKal::Plane const& plane, KinKal::TimeRange const& range, VISIT&& visit) const { double omega = 0.0; if constexpr(requires { piece.Omega(); }) omega = std::fabs(piece.Omega()); else if constexpr(requires { piece.omega(); }) omega = std::fabs(piece.omega()); if(!std::isfinite(omega)) throw std::runtime_error("KKExtrap: nonfinite plane angular frequency"); if(omega == 0.0) return false; - double sign = tdir_ == TimeDir::forwards ? 1.0 : -1.0; + double sign = tdir_ == KinKal::TimeDir::forwards ? 1.0 : -1.0; double pi = std::acos(-1.0), base = sign > 0.0 ? range.begin() : range.end(); double stop = sign > 0.0 ? range.end() : range.begin(); double half = base+pi/omega, quarter = base+0.5*pi/omega; @@ -235,15 +250,15 @@ namespace mu2e { } } - template Intersection ExtrapolateSweep::planeCrossing(KTRAJ const& piece, - KinKal::Plane const& plane, TimeRange const& query) const { + template KinKal::Intersection ExtrapolateSweep::planeCrossing(KTRAJ const& piece, + KinKal::Plane const& plane, KinKal::TimeRange const& query) const { auto distance = [&](double time){ double value = plane.distance(piece.position3(time)); if(!std::isfinite(value)) throw std::runtime_error("KKExtrap: nonfinite plane distance"); return value; }; auto root = [&](double time){ - Intersection inter; + KinKal::Intersection inter; inter.time_ = time; inter.pos_ = piece.position3(time); inter.pdir_ = piece.direction(time); @@ -253,14 +268,14 @@ namespace mu2e { inter.inrange_ = query.inRange(time) && piece.range().inRange(time); return inter; }; - double cursor = tdir_ == TimeDir::forwards ? query.begin() : query.end(); + double cursor = tdir_ == KinKal::TimeDir::forwards ? query.begin() : query.end(); auto endpointContact = [&](double time){ auto inter = root(time); double normalSpeed = std::fabs(plane.normal().Dot(piece.velocity(time))); return inter.onsurface_ && inter.inrange_ && normalSpeed <= 1.0e-12*std::max(piece.speed(time),1.0); }; if(endpointContact(cursor)) return root(cursor); - Intersection result; + KinKal::Intersection result; // Plane distance is monotonic between consecutive extrema of the supported line and helix pieces. auto bracket = [&](double stop){ double a = cursor, b = stop; @@ -297,7 +312,7 @@ namespace mu2e { return false; }; if(visitPlaneExtrema(piece,plane,query,segment)) return result; - double stop = tdir_ == TimeDir::forwards ? query.end() : query.begin(); + double stop = tdir_ == KinKal::TimeDir::forwards ? query.end() : query.begin(); if(!bracket(stop) && endpointContact(stop)) return root(stop); return result; } @@ -306,9 +321,9 @@ namespace mu2e { size_t itg, size_t previous, double accepted, double proposed) const { auto const& plane = *targets_[itg].pl_; auto const& prev = *targets_[previous].pl_; - double sgn = tdir_ == TimeDir::forwards ? 1.0 : -1.0; + double sgn = tdir_ == KinKal::TimeDir::forwards ? 1.0 : -1.0; if(sgn*(proposed-accepted) <= 0.0) return false; - TimeRange interval(std::min(accepted,proposed),std::max(accepted,proposed)); + KinKal::TimeRange interval(std::min(accepted,proposed),std::max(accepted,proposed)); if(!interval.restrict(ptraj.range()) || interval.null()) return false; size_t first = ptraj.nearestIndex(interval.begin()), last = ptraj.nearestIndex(interval.end()); double offset = 2.0*intertol_ + std::fabs((plane.center()-prev.center()).Dot(prev.normal())); @@ -335,14 +350,14 @@ namespace mu2e { } template bool ExtrapolateSweep::seam(KinKal::ParticleTrajectory const& ptraj, - size_t itg, Intersection const& inter) const { + size_t itg, KinKal::Intersection const& inter) const { // Candidate searches are speculative; only accept() changes episodes, never a future departure witness. for(auto const& episode : episodes_[itg]) if(!departed(ptraj,itg,episode.itarget_,episode.time_,inter.time_)) return true; return false; } - template void ExtrapolateSweep::ownBoundary(KTRAJ const& piece, SweepTarget const& tg, Intersection& inter) const { + template void ExtrapolateSweep::ownBoundary(KTRAJ const& piece, SweepTarget const& tg, KinKal::Intersection& inter) const { double time = inter.time_; double begin = piece.range().begin(), end = piece.range().end(); if(time != begin && time != end) return; @@ -363,22 +378,26 @@ namespace mu2e { if(!inter.onsurface_) throw std::runtime_error("KKExtrap: boundary-root displacement leaves surface tolerance"); } - template bool ExtrapolateSweep::firstCrossing(KinKal::ParticleTrajectory const& ptraj, KTRAJ const& piece, size_t itg, TimeRange win, Intersection& inter) const { + template bool ExtrapolateSweep::firstCrossing(KinKal::ParticleTrajectory const& ptraj, KTRAJ const& piece, size_t itg, KinKal::TimeRange win, KinKal::Intersection& inter) const { auto const& tg = targets_[itg]; - double sgn = tdir_ == TimeDir::forwards ? 1.0 : -1.0; - double ts = tdir_ == TimeDir::forwards ? win.begin() : win.end(); - double stop = tdir_ == TimeDir::forwards ? win.end() : win.begin(); - double guard = 4.0*intertol_/std::max(piece.speed(ts),1.0); + double sgn = tdir_ == KinKal::TimeDir::forwards ? 1.0 : -1.0; + double ts = tdir_ == KinKal::TimeDir::forwards ? win.begin() : win.end(); + double stop = tdir_ == KinKal::TimeDir::forwards ? win.end() : win.begin(); + double speed = std::max(piece.speed(ts),1.0); + double step = 4.0*intertol_/speed; + // a track at incidence |cos| stays within the tolerance for about tolerance/|cos| of path; skip past it before finding this target again + double leave = tg.mincos_ > 0.0 ? 2.0*intertol_/(std::max(coslast_[itg],tg.mincos_)*speed) : 0.0; + double guard = std::max(step,leave); if(count_[itg] > 0) ts = sgn > 0.0 ? std::max(ts,tlast_[itg]+guard) : std::min(ts,tlast_[itg]-guard); auto const* plane = dynamic_cast(tg.surf_); unsigned nroot(0); while(sgn*(stop - ts) > 0.0){ if(++nroot > maxRootTrials_) throw std::runtime_error("KKExtrap: surface-root search exceeded retry limit"); - TimeRange query = sgn > 0.0 ? TimeRange(ts,stop) : TimeRange(stop,ts); - VEC3 pos = piece.position3(ts); + KinKal::TimeRange query = sgn > 0.0 ? KinKal::TimeRange(ts,stop) : KinKal::TimeRange(stop,ts); + KinKal::VEC3 pos = piece.position3(ts); if((nroot == 1 || !plane) && tg.surf_->onSurface(pos,intertol_) && std::fabs(tg.surf_->normal(pos).Dot(piece.direction(ts))) >= minv_){ - inter = Intersection(); + inter = KinKal::Intersection(); inter.time_ = ts; inter.pos_ = pos; inter.pdir_ = piece.direction(ts); @@ -403,8 +422,8 @@ namespace mu2e { if(!inter.inrange_) throw std::runtime_error("KKExtrap: surface root has no owning piece"); bool grazing = std::fabs(inter.norm_.Dot(inter.pdir_)) < tg.mincos_; if((inter.inbounds_ || !tg.inbounds_) && !grazing && !seam(ptraj,itg,inter)) return true; - // Roots within four intersection tolerances of path length are unresolved by this search. - double next = inter.time_ + sgn*guard; + // Roots within four intersection tolerances of path length are unresolved by this search; a grazing track first leaves the tolerance. + double next = inter.time_ + sgn*(grazing ? std::max(step,2.0*intertol_/(tg.mincos_*speed)) : step); if(!std::isfinite(next) || sgn*(next - ts) <= 0.0) throw std::runtime_error("KKExtrap: surface-root rejection did not advance"); ts = next; @@ -413,14 +432,14 @@ namespace mu2e { } template bool ExtrapolateSweep::search(KinKal::ParticleTrajectory const& ptraj, double tend) const { - double sgn = tdir_ == TimeDir::forwards ? 1.0 : -1.0; + double sgn = tdir_ == KinKal::TimeDir::forwards ? 1.0 : -1.0; double t0 = std::clamp(searched_,ptraj.range().begin(),ptraj.range().end()); tend = std::clamp(tend,ptraj.range().begin(),ptraj.range().end()); double dtwin = maxDtStep_ > 0.0 ? maxDtStep_ : std::fabs(tend - t0); while(sgn*(tend - t0) > 0.0){ double t1 = t0 + sgn*std::min(dtwin,std::fabs(tend - t0)); if(sgn*(t1 - t0) <= 0.0) throw std::runtime_error("KKExtrap: search window did not advance"); - TimeRange window(std::min(t0,t1),std::max(t0,t1)); + KinKal::TimeRange window(std::min(t0,t1),std::max(t0,t1)); bool found(false); Crossing best; size_t first = ptraj.nearestIndex(window.begin()); @@ -429,11 +448,11 @@ namespace mu2e { auto const& piece = ptraj.piece(ip); auto win = piece.range(); if(!win.restrict(window) || win.null()) continue; - VEC3 wpos = piece.position3(tdir_ == TimeDir::forwards ? win.begin() : win.end()); + KinKal::VEC3 wpos = piece.position3(tdir_ == KinKal::TimeDir::forwards ? win.begin() : win.end()); double reach = piece.speed(win.mid())*win.range()*(1.0+1.0e-9) + intertol_; for(size_t itg = 0; itg < targets_.size(); ++itg){ if(!usable(itg) || !withinReach(itg,wpos,reach)) continue; - Intersection inter; + KinKal::Intersection inter; if(!firstCrossing(ptraj,piece,itg,win,inter)) continue; bool earlier = !found || sgn*inter.time_ < sgn*best.inter_.time_; bool tie = found && inter.time_ == best.inter_.time_ && targets_[itg].sid_ < targets_[best.itarget_].sid_; @@ -457,11 +476,11 @@ namespace mu2e { } template bool ExtrapolateSweep::reachable(KinKal::ParticleTrajectory const& ptraj) const { - double sgn = tdir_ == TimeDir::forwards ? 1.0 : -1.0; - auto const& ktraj = tdir_ == TimeDir::forwards ? ptraj.back() : ptraj.front(); - double time = tdir_ == TimeDir::forwards ? ktraj.range().end() : ktraj.range().begin(); - VEC3 pos = ktraj.position3(time); - VEC3 vel = ktraj.velocity(time)*sgn; // signed by the extrapolation direction + double sgn = tdir_ == KinKal::TimeDir::forwards ? 1.0 : -1.0; + auto const& ktraj = tdir_ == KinKal::TimeDir::forwards ? ptraj.back() : ptraj.front(); + double time = tdir_ == KinKal::TimeDir::forwards ? ktraj.range().end() : ktraj.range().begin(); + KinKal::VEC3 pos = ktraj.position3(time); + KinKal::VEC3 vel = ktraj.velocity(time)*sgn; // signed by the extrapolation direction double rho = std::sqrt(pos.X()*pos.X() + pos.Y()*pos.Y()); double vrho = rho > 0.0 ? (pos.X()*vel.X() + pos.Y()*vel.Y())/rho : 0.0; for(size_t itg = 0; itg < targets_.size(); ++itg){ @@ -485,9 +504,9 @@ namespace mu2e { reach = true; } else { // near a reflection vz is an unreliable direction estimate: use the linearized trajectory instead - KinKal::Plane zplane(VEC3(0.0,0.0,1.0),VEC3(1.0,0.0,0.0),VEC3(0.0,0.0,tg.zval_)); + KinKal::Plane zplane(KinKal::VEC3(0.0,0.0,1.0),KinKal::VEC3(1.0,0.0,0.0),KinKal::VEC3(0.0,0.0,tg.zval_)); double dist(0.0); - zplane.intersect(ktraj.linearize(time),dist,tdir_ == TimeDir::forwards,intertol_); + zplane.intersect(ktraj.linearize(time),dist,tdir_ == KinKal::TimeDir::forwards,intertol_); reach = dist*sgn > 0.0; } break; diff --git a/Mu2eKinKal/inc/KKExtrap.hh b/Mu2eKinKal/inc/KKExtrap.hh index 0737512c36..cdeaa56f79 100644 --- a/Mu2eKinKal/inc/KKExtrap.hh +++ b/Mu2eKinKal/inc/KKExtrap.hh @@ -47,11 +47,13 @@ namespace mu2e { double btol_, intertol_, maxdt_, maxdtstep_, minv_; bool backToTracker_, extrapolateOPA_, toTrackerPerimeter_, upstream_, toCRV_; bool toCaloD0_, toCaloD1_; - // IPA/ST thicknesses match the nominal KinKalGeom surfaces. + // nominal literals like the hard-coded KinKalGeom IPA and ST surfaces (KinKalGeomMaker::makeDS/makeTarget); TODO: take both from the geometry service double ipathick_ = 0.511; // ipa thickness (mm) double stthick_ = 0.1056; // st foil thickness (mm) static constexpr unsigned maxCrossings_ = 1000; // per sweep, against endless reflection loops static constexpr double dsShellMinCos_ = 0.1; // thin-shell approximation: skip near-tangent DS shell crossings + static constexpr double ipaMinCos_ = 0.1; // as the DS shells; no truth IPA crossing on CE has |cos| < 0.2 + static constexpr double stFoilMinCos_ = 0.02; // no truth foil crossing on CE has |cos| < 0.02; the thin-foil path is then 50x the thickness }; KKExtrap::KKExtrap(KKExtrapConfig const& extrapconfig) : @@ -159,6 +161,7 @@ namespace mu2e { ipatg.mat_ = &*kkmat_h->IPAMaterial(); ipatg.thick_ = ipathick_; ipatg.maxcross_ = 0; + ipatg.mincos_ = std::max(minv_,ipaMinCos_); zrange(*ipa,ipatg.zreglo_,ipatg.zreghi_); tgts.push_back(ipatg); auto const& st = *kkg_h->ST(); @@ -176,6 +179,7 @@ namespace mu2e { tg.mat_ = &*kkmat_h->STMaterial(); tg.thick_ = stthick_; tg.maxcross_ = 0; + tg.mincos_ = std::max(minv_,stFoilMinCos_); tg.zreglo_ = stzlo; tg.zreghi_ = stzhi; tgts.push_back(tg); } @@ -300,6 +304,10 @@ namespace mu2e { addCrossing(ktrk,xs.targets()[xs.crossing().itarget_],xs.crossing().inter_,tdir); xs.accept(); } + if(xs.failed()){ + addFailure(ktrk,tdir,xs.error()); + return; + } xs.unlimit(); xs.start(tstart); if(updir && upstream_){ @@ -311,7 +319,12 @@ namespace mu2e { } unsigned ncross(0); while(ncross < maxCrossings_){ - if(xs.needsExtrapolation(ftraj,tdir) && !ktrk.extrapolate(tdir,xs)){ + bool extended = !xs.needsExtrapolation(ftraj,tdir) || ktrk.extrapolate(tdir,xs); + if(xs.failed()){ + addFailure(ktrk,tdir,xs.error()); // the search failed, before or during KinKal's walk; the fit stays usable + break; + } + if(!extended){ addFailure(ktrk,tdir,ktrk.fitStatus().comment_); // KinKal marked the fit unusable while extending it break; } diff --git a/Mu2eKinKal/inc/KKFit.hh b/Mu2eKinKal/inc/KKFit.hh index 17b2265181..4e416f2bfa 100644 --- a/Mu2eKinKal/inc/KKFit.hh +++ b/Mu2eKinKal/inc/KKFit.hh @@ -690,6 +690,9 @@ namespace mu2e { if(kktrk.fitStatus().status_ == Status::converged) fflag.merge(TrkFitFlag::kalmanConverged); if(matcorr_)fflag.merge(TrkFitFlag::MatCorr); if(kktrk.config().bfcorr_ )fflag.merge(TrkFitFlag::BFCorr); + // extrapolation flags describe this track only, not the seed it was regrown from + fflag.clear(TrkFitFlag::ExtrapFailed); + fflag.clear(TrkFitFlag::RangedOut); if(!kktrk.extrapolationFailures().empty())fflag.merge(TrkFitFlag::ExtrapFailed); if(kktrk.rangedOut())fflag.merge(TrkFitFlag::RangedOut); // explicit T0 is needed for backwards-compatibility; sample from the appropriate trajectory piece diff --git a/Mu2eKinKal/src/ExtrapolateSweepTest_main.cc b/Mu2eKinKal/src/ExtrapolateSweepTest_main.cc index a4ad717c60..23927d95af 100644 --- a/Mu2eKinKal/src/ExtrapolateSweepTest_main.cc +++ b/Mu2eKinKal/src/ExtrapolateSweepTest_main.cc @@ -17,6 +17,7 @@ #include #include #include +#include namespace { using KinKal::TimeDir; @@ -611,13 +612,9 @@ namespace { ExtrapolateSweep sweep(targets,dir,1.0,1.0,1.0e-4,tol,1.0e-6,0); sweep.start(root); sweep.limit(forward ? end : begin,false); - bool failed = false; - try { - sweep.needsExtrapolation(traj,dir); - } catch(std::runtime_error const& error) { - auto expected = narrow ? "no representable piece interior" : "displacement exceeds intersection tolerance"; - failed = std::string(error.what()).find(expected) != std::string::npos; - } + require(!sweep.needsExtrapolation(traj,dir),"a failed search must stop the extension"); + auto expected = narrow ? "no representable piece interior" : "displacement exceeds intersection tolerance"; + bool failed = sweep.failed() && sweep.error().find(expected) != std::string::npos; require(failed && !sweep.hasCrossing(),"invalid boundary interior must fail explicitly without accepting geometry"); } @@ -667,13 +664,54 @@ namespace { KinKal::Plane plane(VEC3(1.0,0.0,0.0),VEC3(0.0,1.0,0.0),VEC3(2.0*helix.bendRadius(),0.0,0.0)); SweepTarget target; target.surf_ = target.pl_ = &plane; - bool failed = false; - try { - crossing(traj,{target},TimeDir::forwards); - } catch(std::runtime_error const& error) { - failed = std::string(error.what()).find("extrema budget") != std::string::npos; + SweepTargetCollection targets{target}; + ExtrapolateSweep sweep(targets,TimeDir::forwards,1.0e6,1.0e6,1.0e-4,tol,1.0e-6,0); + sweep.start(traj.range().begin()); + sweep.limit(traj.range().end(),false); + require(!sweep.needsExtrapolation(traj,TimeDir::forwards),"a failed search must stop the extension"); + bool failed = sweep.failed() && sweep.error().find("extrema budget") != std::string::npos; + require(failed && !sweep.hasCrossing(),"unresolved long plane search must fail explicitly at the extrema budget"); + require(!sweep.needsExtrapolation(traj,TimeDir::forwards) && sweep.failed(),"a failed search stays failed"); + } + + // All crossings of a full sweep, each accepted as KKExtrap does. + template std::vector allCrossings(KinKal::ParticleTrajectory const& traj, + SweepTargetCollection const& targets, TimeDir dir, double tolerance) { + ExtrapolateSweep sweep(targets,dir,1.0e6,1.0e6,1.0e-4,tolerance,1.0e-6,0); + sweep.start(dir == TimeDir::forwards ? traj.range().begin() : traj.range().end()); + sweep.limit(dir == TimeDir::forwards ? traj.range().end() : traj.range().begin(),false); + std::vector found; + while(!sweep.needsExtrapolation(traj,dir) && sweep.hasCrossing()){ + found.push_back(sweep.crossing().inter_); + sweep.accept(); + require(found.size() < 100,"runaway repeated crossings"); + } + require(!sweep.failed(),"sweep failed: " + sweep.error()); + return found; + } + + // A repeatable shell (the IPA) is crossed once per traversal at any incidence above its floor, never below it. + void shellIncidence(TimeDir dir) { + double const radius = 300.0, tolerance = 0.1; + KinKal::Cylinder cyl(VEC3(0.0,0.0,1.0),VEC3(0.0,0.0,0.0),radius,1000.0); + SweepTarget target; + target.effect_ = SweepTarget::ipashell; + target.surf_ = &cyl; + target.maxcross_ = 0; + target.mincos_ = 0.1; + for(double incidence : {0.003,0.05,0.12,0.2,0.5}){ + // a line at distance radius*sqrt(1-c^2) from the axis meets the cylinder at incidence c, entering and leaving + double offset = radius*std::sqrt(1.0-incidence*incidence); + KinKal::ParticleState state(VEC3(-400.0,offset,0.0),VEC3(100.0,0.0,0.0),0.0,105.658,1); + KinKal::KinematicLine line(state,VEC3(0.0,0.0,0.0),TimeRange(0.0,1.0)); + line.setRange(TimeRange(0.0,800.0/line.speed(0.0))); + KinKal::ParticleTrajectory traj(line); + auto found = allCrossings(traj,{target},dir,tolerance); + size_t expected = incidence < target.mincos_ ? 0 : 2; + require(found.size() == expected,"shell crossed " + std::to_string(found.size()) + " times at incidence " + std::to_string(incidence)); + for(auto const& inter : found) + require(std::fabs(std::fabs(inter.norm_.Dot(inter.pdir_))-incidence) < 1.0e-3,"shell crossing at the wrong incidence"); } - require(failed,"unresolved long plane search must fail explicitly at the extrema budget"); } void emptySearch() { @@ -705,6 +743,7 @@ int main() { materialPieceEdge(dir,npiece,join,*targetMaterial,false); } reachBound(dir); + shellIncidence(dir); invalidBoundaryInterior(dir,true); invalidBoundaryInterior(dir,false); closeSeam(dir); diff --git a/Mu2eKinKal/src/RegrowKinematicLine_module.cc b/Mu2eKinKal/src/RegrowKinematicLine_module.cc index ef0af9ee5c..f50de269fd 100644 --- a/Mu2eKinKal/src/RegrowKinematicLine_module.cc +++ b/Mu2eKinKal/src/RegrowKinematicLine_module.cc @@ -164,6 +164,7 @@ namespace mu2e { produces(); produces(); if(settings().extrapSettings())extrap_ = make_unique(*settings().extrapSettings()); + if(extrap_) extrap_->checkConfig(config_); if( fillMCAssns_){ consumes(ksmca_T_); produces (); diff --git a/Mu2eKinKal/src/RegrowLoopHelix_module.cc b/Mu2eKinKal/src/RegrowLoopHelix_module.cc index fe28da03d5..9276be7b9c 100644 --- a/Mu2eKinKal/src/RegrowLoopHelix_module.cc +++ b/Mu2eKinKal/src/RegrowLoopHelix_module.cc @@ -181,6 +181,7 @@ namespace mu2e { produces(); produces(); if(settings().extrapSettings())extrap_ = make_unique(*settings().extrapSettings()); + if(extrap_) extrap_->checkConfig(config_); if( fillMCAssns_){ consumes(ksmca_T_); produces (); From 445cd49a915e429d71d59dc8d84e87721ada4872 Mon Sep 17 00:00:00 2001 From: Rob Mina Date: Thu, 5 Nov 2026 20:33:36 -0600 Subject: [PATCH 3/3] Remove seams, ranged-out track trimming, add clarifying comments. --- Mu2eKinKal/inc/ExtrapolateSweep.hh | 90 ++++++------- Mu2eKinKal/inc/KKExtrap.hh | 6 +- Mu2eKinKal/inc/KKFit.hh | 23 +--- Mu2eKinKal/inc/KKTrack.hh | 14 +- Mu2eKinKal/src/CentralHelixFit_module.cc | 7 +- Mu2eKinKal/src/ExtrapolateSweepTest_main.cc | 136 +++++++++----------- Mu2eKinKal/src/KinematicLineFit_module.cc | 10 +- 7 files changed, 121 insertions(+), 165 deletions(-) diff --git a/Mu2eKinKal/inc/ExtrapolateSweep.hh b/Mu2eKinKal/inc/ExtrapolateSweep.hh index 3d2f863e0c..ca66b63739 100644 --- a/Mu2eKinKal/inc/ExtrapolateSweep.hh +++ b/Mu2eKinKal/inc/ExtrapolateSweep.hh @@ -1,4 +1,16 @@ // Targets and predicate for the KKExtrap sweep: all requested surfaces are searched together from the last processed crossing. +// +// How a sweep runs (one per time direction, driven by KKExtrap::sweep): +// - Targets: one SweepTarget per surface; effect_ says what a crossing adds (a recorded intersection or a material xing). +// - Cursor: searched_ is the time up to which the trajectory has been searched; it only moves in the sweep direction. +// - Search: from the cursor to the trajectory end, in MaxDtStep windows, every piece and every usable target is intersected and the earliest crossing is cached. +// - Predicate: KinKal::Track::extrapolate calls needsExtrapolation as it extends the end piece; a cached crossing returns false, so KinKal stops there. +// - Accept: KKExtrap adds the crossing's effect on the end piece, then accept() moves the cursor to the crossing, so no crossing is found twice and all are processed in time order. +// - Stop: nothing driving is reachable (reachable), MaxDt passes without a crossing, a terminal target is crossed, a watched reflection occurs, or the search fails (error()). +// - Limit: limit(t,recordonly) caps the search at t (optionally to record targets only); KKExtrap uses it for the fitted trajectory before the end piece, where no material can be added, and unlimit() removes the cap. +// - Re-crossing guard: a plane, CRV sector or foil is crossed again only after the trajectory has left the slab of half-width intertol around it (departed). +// - Planes: the signed plane distance of a helix or line is monotonic between the extrema of its normal velocity, which are known in closed form (visitPlaneExtrema), so plane roots are bracketed and bisected (planeCrossing); cylinders use KinKal::intersect. +// Adding a material target: see KKExtrap::targets and KKExtrap::addCrossing. #ifndef Mu2eKinKal_ExtrapolateSweep_hh #define Mu2eKinKal_ExtrapolateSweep_hh #include "KinKal/General/TimeDir.hh" @@ -69,7 +81,7 @@ namespace mu2e { double intertol, double minv, int debug) : targets_(targets), tdir_(tdir), maxDt_(maxdt), maxDtStep_(maxdtstep), dptol_(dptol), intertol_(intertol), minv_(minv), debug_(debug), active_(targets.size()), count_(targets.size(),0), tlast_(targets.size(),0.0), coslast_(targets.size(),1.0), notbefore_(targets.size(),std::numeric_limits::quiet_NaN()), - episodes_(targets.size()), planes_(targets.size(),nullptr), cylinders_(targets.size(),nullptr) { + guarded_(targets.size(),false), planes_(targets.size(),nullptr), cylinders_(targets.size(),nullptr) { for(size_t itg = 0; itg < targets_.size(); ++itg){ active_[itg] = targets_[itg].active_; planes_[itg] = dynamic_cast(targets_[itg].surf_); @@ -86,11 +98,11 @@ namespace mu2e { bool failed() const { return !error_.empty(); } std::string const& error() const { return error_; } // why the search failed; KinKal's walk never sees the exception // sweep control - void start(double tcursor) { searched_ = tcursor; found_ = reflected_ = false; } - void limit(double tlimit, bool recordonly) { limited_ = true; tlimit_ = tlimit; recordonly_ = recordonly; } - void unlimit() { limited_ = recordonly_ = false; } - void watchReflection(double vbsign) { vbsign_ = vbsign; reflected_ = false; } - void setActive(size_t itg, bool active) { active_[itg] = active; } + void start(double tcursor) { searched_ = tcursor; found_ = reflected_ = false; } // place the cursor: the search starts here + void limit(double tlimit, bool recordonly) { limited_ = true; tlimit_ = tlimit; recordonly_ = recordonly; } // search no further than tlimit, and only record targets if recordonly; the trajectory is not extended + void unlimit() { limited_ = recordonly_ = false; } // search to the trajectory end and let KinKal extend it + void watchReflection(double vbsign) { vbsign_ = vbsign; reflected_ = false; } // stop when the velocity along B changes sign from vbsign; 0 to not watch + void setActive(size_t itg, bool active) { active_[itg] = active; } // switch a target on or off for the rest of the sweep void notBefore(size_t itg, double time) { notbefore_[itg] = time; } // crossings of this target earlier in the sweep direction are skipped bool hasCrossing() const { return found_; } bool reflected() const { return reflected_; } @@ -99,17 +111,16 @@ namespace mu2e { // mark the cached crossing processed and move the search start to it void accept(); private: - template bool extend(KinKal::ParticleTrajectory const& ptraj) const; - bool usable(size_t itg) const; - bool withinReach(size_t itg, KinKal::VEC3 const& pos, double reach) const; - template bool search(KinKal::ParticleTrajectory const& ptraj, double tend) const; - template bool firstCrossing(KinKal::ParticleTrajectory const& ptraj, KTRAJ const& piece, size_t itg, KinKal::TimeRange win, KinKal::Intersection& inter) const; - template bool visitPlaneExtrema(KTRAJ const& piece, KinKal::Plane const& plane, KinKal::TimeRange const& range, VISIT&& visit) const; - template KinKal::Intersection planeCrossing(KTRAJ const& piece, KinKal::Plane const& plane, KinKal::TimeRange const& query) const; - template void ownBoundary(KTRAJ const& piece, SweepTarget const& tg, KinKal::Intersection& inter) const; - template bool seam(KinKal::ParticleTrajectory const& ptraj, size_t itg, KinKal::Intersection const& inter) const; - template bool departed(KinKal::ParticleTrajectory const& ptraj, size_t itg, size_t previous, double accepted, double proposed) const; - template bool reachable(KinKal::ParticleTrajectory const& ptraj) const; + template bool extend(KinKal::ParticleTrajectory const& ptraj) const; // the predicate body: search, then decide whether KinKal keeps extending + bool usable(size_t itg) const; // active, not over its crossing count or group, and allowed by the limit + bool withinReach(size_t itg, KinKal::VEC3 const& pos, double reach) const; // cheap distance cut before intersecting a target in a window + template bool search(KinKal::ParticleTrajectory const& ptraj, double tend) const; // cache the earliest crossing between the cursor and tend + template bool firstCrossing(KinKal::ParticleTrajectory const& ptraj, KTRAJ const& piece, size_t itg, KinKal::TimeRange win, KinKal::Intersection& inter) const; // first acceptable crossing of one target on one piece in a window + template bool visitPlaneExtrema(KTRAJ const& piece, KinKal::Plane const& plane, KinKal::TimeRange const& range, VISIT&& visit) const; // times where the plane distance is extremal, in sweep order + template KinKal::Intersection planeCrossing(KTRAJ const& piece, KinKal::Plane const& plane, KinKal::TimeRange const& query) const; // first plane root in query, bracketed between extrema + template void ownBoundary(KTRAJ const& piece, SweepTarget const& tg, KinKal::Intersection& inter) const; // move a root on a piece edge just inside that piece + template bool departed(KinKal::ParticleTrajectory const& ptraj, size_t itg, double accepted, double proposed) const; // the trajectory left the plane's tolerance slab between two crossing times + template bool reachable(KinKal::ParticleTrajectory const& ptraj) const; // a driving target can still be crossed from the trajectory end SweepTargetCollection const& targets_; KinKal::TimeDir tdir_; double maxDt_, maxDtStep_, dptol_, intertol_, minv_; @@ -120,12 +131,11 @@ namespace mu2e { std::vector coslast_; // |cos| between the surface normal and the direction at that crossing std::vector notbefore_; // per target, NaN for no limit std::vector doneGroups_; // groups whose first crossing is processed - struct SeamEpisode { size_t itarget_; double time_; }; - std::vector> episodes_; // accepted seam episodes per eligible target, including self + std::vector guarded_; // plane targets crossed again only after the track leaves their tolerance slab std::vector planes_; // per target, the surface as a plane or cylinder when it is one std::vector cylinders_; - bool limited_ = false, recordonly_ = false; - double tlimit_ = 0.0; + bool limited_ = false, recordonly_ = false; // see limit() + double tlimit_ = 0.0; // the search stops here while limited_ double vbsign_ = 0.0; // sign of the B-parallel velocity to watch for a reflection; 0 to not watch mutable double searched_ = 0.0; // the trajectory is searched up to this time mutable bool found_ = false, reflected_ = false; @@ -166,20 +176,8 @@ namespace mu2e { tlast_[itg] = time; coslast_[itg] = std::fabs(crossing_.inter_.norm_.Dot(crossing_.inter_.pdir_)); if(tg.group_ >= 0) doneGroups_.push_back(tg.group_); - if((tg.effect_ == SweepTarget::planeshell || tg.effect_ == SweepTarget::crvsector || tg.effect_ == SweepTarget::stfoil) && tg.pl_){ - for(size_t other = 0; other < targets_.size(); ++other){ - auto const& neighbor = targets_[other]; - if(neighbor.effect_ != tg.effect_ || !neighbor.pl_ || neighbor.mat_ != tg.mat_ || neighbor.thick_ != tg.thick_) continue; - if(std::fabs(neighbor.pl_->normal().Dot(tg.pl_->normal())) < 1.0 - 1.0e-12) continue; - if(std::fabs((neighbor.pl_->center()-tg.pl_->center()).Dot(tg.pl_->normal())) > intertol_) continue; - if(!tg.surf_->inBounds(crossing_.inter_.pos_,intertol_) || !neighbor.surf_->inBounds(crossing_.inter_.pos_,intertol_)) continue; - auto& episodes = episodes_[other]; - auto previous = std::find_if(episodes.begin(),episodes.end(),[itg](SeamEpisode const& episode){ return episode.itarget_ == itg; }); - // A later acceptance of the same source supersedes its earlier episode without erasing other planes. - if(previous == episodes.end()) episodes.push_back({itg,time}); - else previous->time_ = time; - } - } + guarded_[itg] = (tg.effect_ == SweepTarget::planeshell || tg.effect_ == SweepTarget::crvsector || tg.effect_ == SweepTarget::stfoil) && + tg.pl_ && tg.surf_->inBounds(crossing_.inter_.pos_,intertol_); searched_ = time; found_ = false; } @@ -329,15 +327,15 @@ namespace mu2e { } template bool ExtrapolateSweep::departed(KinKal::ParticleTrajectory const& ptraj, - size_t itg, size_t previous, double accepted, double proposed) const { + size_t itg, double accepted, double proposed) const { + // Candidate searches are speculative: only the current trajectory between the accepted and proposed crossings is a witness. auto const& plane = *targets_[itg].pl_; - auto const& prev = *targets_[previous].pl_; double sgn = tdir_ == KinKal::TimeDir::forwards ? 1.0 : -1.0; if(sgn*(proposed-accepted) <= 0.0) return false; KinKal::TimeRange interval(std::min(accepted,proposed),std::max(accepted,proposed)); if(!interval.restrict(ptraj.range()) || interval.null()) return false; size_t first = ptraj.nearestIndex(interval.begin()), last = ptraj.nearestIndex(interval.end()); - double offset = 2.0*intertol_ + std::fabs((plane.center()-prev.center()).Dot(prev.normal())); + double offset = 2.0*intertol_; for(size_t ip = first; ip <= last; ++ip){ auto const& piece = ptraj.piece(ip); auto clipped = piece.range(); @@ -346,13 +344,13 @@ namespace mu2e { if(!std::isfinite(time) || time < clipped.begin() || time > clipped.end() || sgn*(time-accepted) <= 0.0 || sgn*(proposed-time) <= 0.0) return false; auto pos = ptraj.position3(time); - return std::fabs(plane.distance(pos)) > intertol_ && std::fabs(prev.distance(pos)) > intertol_; + return std::fabs(plane.distance(pos)) > intertol_; }; if(witness(clipped.begin()) || witness(clipped.end())) return true; - if(visitPlaneExtrema(piece,prev,clipped,witness)) return true; + if(visitPlaneExtrema(piece,plane,clipped,witness)) return true; // Offset-plane roots also provide directly verified departure witnesses. for(double side : {-1.0,1.0}){ - KinKal::Plane outside(prev.normal(),prev.uDirection(),prev.center()+side*offset*prev.normal()); + KinKal::Plane outside(plane.normal(),plane.uDirection(),plane.center()+side*offset*plane.normal()); auto root = KinKal::intersect(piece,outside,clipped,0.125*intertol_,tdir_); if(root.onsurface_ && witness(root.time_)) return true; } @@ -360,14 +358,6 @@ namespace mu2e { return false; } - template bool ExtrapolateSweep::seam(KinKal::ParticleTrajectory const& ptraj, - size_t itg, KinKal::Intersection const& inter) const { - // Candidate searches are speculative; only accept() changes episodes, never a future departure witness. - for(auto const& episode : episodes_[itg]) - if(!departed(ptraj,itg,episode.itarget_,episode.time_,inter.time_)) return true; - return false; - } - template void ExtrapolateSweep::ownBoundary(KTRAJ const& piece, SweepTarget const& tg, KinKal::Intersection& inter) const { double time = inter.time_; double begin = piece.range().begin(), end = piece.range().end(); @@ -433,7 +423,7 @@ namespace mu2e { if(sgn*(inter.time_ - ts) < 0.0 || sgn*(stop - inter.time_) < 0.0) return false; if(!inter.inrange_) throw std::runtime_error("KKExtrap: surface root has no owning piece"); bool grazing = std::fabs(inter.norm_.Dot(inter.pdir_)) < tg.mincos_; - if((inter.inbounds_ || !tg.inbounds_) && !grazing && !seam(ptraj,itg,inter)) return true; + if((inter.inbounds_ || !tg.inbounds_) && !grazing && (!guarded_[itg] || departed(ptraj,itg,tlast_[itg],inter.time_))) return true; // Roots within four intersection tolerances of path length are unresolved by this search; a grazing track first leaves the tolerance. double next = inter.time_ + sgn*(grazing ? std::max(step,2.0*intertol_/(tg.mincos_*speed)) : step); if(!std::isfinite(next) || sgn*(next - ts) <= 0.0) diff --git a/Mu2eKinKal/inc/KKExtrap.hh b/Mu2eKinKal/inc/KKExtrap.hh index b73d59ef0e..9ae5ffe4f8 100644 --- a/Mu2eKinKal/inc/KKExtrap.hh +++ b/Mu2eKinKal/inc/KKExtrap.hh @@ -38,6 +38,9 @@ namespace mu2e { // extrapolate the fit in both time directions through every requested surface template void extrapolate(KKTrack& ktrk) const; // the surfaces requested in one time direction; updir is the direction that leaves the tracker upstream + // To add passive material: give it a SurfaceId and a KinKalGeom surface, add a SweepTarget here (effect_, surf_ and the typed surface, mat_, thick_, reach_, mincos_), + // and, for a new Effect, a case in addCrossing that builds its KinKal material xing; a surface that is neither a Plane nor a Cylinder is searched with KinKal::intersect + // and is never cut by withinReach; add a case to ExtrapolateSweepTest and, if optional, a KKExtrapConfig switch. SweepTargetCollection targets(bool updir) const; private: // where a track entered a calorimeter crystal case inner support: the material still to cross at the carbon fiber ring inner radius @@ -121,7 +124,7 @@ namespace mu2e { // The particle stops in this material: the forwards direction ends before it, keeping the crossings already added. template bool KKExtrap::rangeOut(KKTrack& ktrk, SweepTarget const& tg, KinKal::Intersection const& inter) const { if(debug_ > 0) std::cout << "KKExtrap: ranged out in " << tg.sid_ << " at " << inter.time_ << std::endl; - ktrk.setRangedOut(inter.time_); + ktrk.setRangedOut(); return false; } @@ -372,6 +375,7 @@ namespace mu2e { addFailure(ktrk,tdir,xs.error()); return; } + // then extend the end piece from the sweep start, one crossing at a time xs.unlimit(); xs.start(tstart); if(updir && upstream_){ diff --git a/Mu2eKinKal/inc/KKFit.hh b/Mu2eKinKal/inc/KKFit.hh index 0bc910229b..9e69963a72 100644 --- a/Mu2eKinKal/inc/KKFit.hh +++ b/Mu2eKinKal/inc/KKFit.hh @@ -866,23 +866,11 @@ namespace mu2e { // save the fit segments as requested if(kktrk.fitStatus().usable()){ static const double minrange(1.0e-2); // minimum time range to save a segment. - // a particle that ranges out stops at that time, so no segment extends past it - double tstop = kktrk.rangeOutTime(); - auto stopped = [tstop](KTRAJ const& traj){ - KTRAJ clipped(traj); - clipped.setRange(TimeRange(traj.range().begin(),std::min(traj.range().end(),tstop))); - return clipped; - }; if (savetraj_ == full){ kseed._segments.reserve(fittraj.pieces().size()); for (auto const& traj : fittraj.pieces() ){ // skip 'zero-range' segments. By convention, sample the state at the mid-time - if(traj->range().end() <= tstop){ - if(traj->range().range() > minrange) kseed._segments.emplace_back(*traj,traj->range().mid()); - } else if(std::min(traj->range().end(),tstop) - traj->range().begin() > minrange){ - auto clipped = stopped(*traj); - kseed._segments.emplace_back(clipped,clipped.range().mid()); - } + if(traj->range().range() > minrange) kseed._segments.emplace_back(*traj,traj->range().mid()); } // a fit that ran without BField correction has no domains at all; the trailing push_back // below would then dereference rbegin() of an empty set, which is undefined behaviour @@ -935,12 +923,7 @@ namespace mu2e { kseed._segments.reserve(fittraj.pieces().size());// this will be oversized for (auto const& traj : fittraj.pieces() ){ // skip segments outside the detector range - if(traj->range().end() <= tstop){ - if(traj->range().range() > 0.0 && traj->range().overlaps(detrange) ) kseed._segments.emplace_back(*traj,traj->range().mid()); - } else if(traj->range().begin() < tstop){ - auto clipped = stopped(*traj); - if(clipped.range().overlaps(detrange)) kseed._segments.emplace_back(clipped,clipped.range().mid()); - } + if(traj->range().range() > 0.0 && traj->range().overlaps(detrange) ) kseed._segments.emplace_back(*traj,traj->range().mid()); } kseed._segments.shrink_to_fit(); if(savedomains_){ @@ -1058,7 +1041,7 @@ namespace mu2e { } for(auto range : ranges) { double tbeg = range.begin(); - double tend = std::min(range.end(),kktrk.rangeOutTime()); // a particle that ranges out stops there + double tend = range.end(); for(auto const& surf : tosample){ // search for intersections with each surface within the specified time range, going forwards in time bool goodinter(true); diff --git a/Mu2eKinKal/inc/KKTrack.hh b/Mu2eKinKal/inc/KKTrack.hh index 8f6a72c991..3ec15813af 100644 --- a/Mu2eKinKal/inc/KKTrack.hh +++ b/Mu2eKinKal/inc/KKTrack.hh @@ -13,7 +13,6 @@ #include "Offline/Mu2eKinKal/inc/KKCaloHit.hh" #include "Offline/DataProducts/inc/SurfaceId.hh" #include "KinKal/Geometry/Intersection.hh" -#include #include #include #include @@ -85,7 +84,7 @@ namespace mu2e { calohits_(rhs.caloHits()), inters_(rhs.intersections()), extrapfails_(rhs.extrapolationFailures()), - rangeouttime_(rhs.rangeOutTime()){ + rangedout_(rhs.rangedOut()){ // hits and crossings were reallocated into the base copy; here, // we propagate references to those reallocations to the subclass this->remap_pointer_collection(strawhits_, this->hits(), context); @@ -155,8 +154,8 @@ namespace mu2e { void addIntersection(SurfaceId const& sid, Intersection const& inter) { inters_.emplace_back(sid,inter); } // record an extrapolation that ended early on a problem with this track; the fit itself is unaffected void addExtrapolationFailure(std::string const& reason) { extrapfails_.push_back(reason); } - // record the time the particle stops in an extrapolation material; the forwards extrapolation ends there - void setRangedOut(double time) { rangeouttime_ = time; } + // record that the particle stops in an extrapolation material; the forwards extrapolation ends there + void setRangedOut() { rangedout_ = true; } // accessors PDGCode::type fitParticle() const { return tpart_;} @@ -173,8 +172,7 @@ namespace mu2e { KKMATRECXINGCOL const& caloMaterialPlaneXings() const { return calomatrecxings_; } KKINTERCOL const& intersections() const { return inters_; } std::vector const& extrapolationFailures() const { return extrapfails_; } - bool rangedOut() const { return rangeouttime_ < std::numeric_limits::infinity(); } - double rangeOutTime() const { return rangeouttime_; } // infinity unless the particle ranges out + bool rangedOut() const { return rangedout_; } KKCALOHITCOL const& caloHits() const { return calohits_; } void printFit(std::ostream& ost=std::cout,int detail=0) const; // allow reversing the charge (in some fits it can change dynamically) @@ -198,8 +196,8 @@ namespace mu2e { KKMATCYLXINGCOL calomatcylxings_; // calorimeter cylindrical material crossings used in the fit KKMATRECXINGCOL calomatrecxings_; // calorimeter planar material crossings used in the fit KKINTERCOL inters_; // other recorded intersections - std::vector extrapfails_; // why an extrapolation direction ended early - double rangeouttime_ = std::numeric_limits::infinity(); // when the particle stops in an extrapolation material + std::vector extrapfails_; // why an extrapolation direction ended early (diagnostic text); the KalSeed carries the condition as TrkFitFlag::ExtrapFailed + bool rangedout_ = false; // the particle stops in an extrapolation material; the KalSeed carries it as TrkFitFlag::RangedOut KKSTRAWHITCLUSTERCOL strawhitclusters_; // straw hit clusters used in this fit // utility function to convert to generic types void convertTypes( KKSTRAWHITCOL const& strawhits, KKSTRAWXINGCOL const& strawxings,KKCALOHITCOL const& calohits, PARAMHITCOL const& paramhits, diff --git a/Mu2eKinKal/src/CentralHelixFit_module.cc b/Mu2eKinKal/src/CentralHelixFit_module.cc index e3bf96ffe9..11e4fb51a2 100644 --- a/Mu2eKinKal/src/CentralHelixFit_module.cc +++ b/Mu2eKinKal/src/CentralHelixFit_module.cc @@ -439,12 +439,7 @@ namespace mu2e { // loop to find multiple intersections while(goodinter && cur_inter < max_inter) { cur_inter += 1; - double tmax = std::max(ftraj.range().end(),tstart)+sampletbuff_; - if(ktrk.rangedOut()){ // a particle that ranges out stops there - tmax = std::min(tmax,ktrk.rangeOutTime()); - if(tstart >= tmax) break; - } - TimeRange irange(tstart,tmax); + TimeRange irange(tstart,std::max(ftraj.range().end(),tstart)+sampletbuff_); auto surfinter = KinKal::intersect(ftraj,*surf.second,irange,intertol_); goodinter = surfinter.onsurface_ && ( (! sampleinbounds_) || surfinter.inbounds_ ) && ( (!sampleinrange_) || irange.inRange(surfinter.time_)); if(goodinter) { diff --git a/Mu2eKinKal/src/ExtrapolateSweepTest_main.cc b/Mu2eKinKal/src/ExtrapolateSweepTest_main.cc index 5107c0acfb..18a2c13a3f 100644 --- a/Mu2eKinKal/src/ExtrapolateSweepTest_main.cc +++ b/Mu2eKinKal/src/ExtrapolateSweepTest_main.cc @@ -105,7 +105,7 @@ namespace { } } - void stableTieAndSeams() { + void stableTie() { KinKal::ParticleState state(VEC3(0.0,0.0,-1.0),VEC3(0.0,0.0,100.0),0.0,105.658,1); KinKal::KinematicLine line(state,VEC3(0.0,0.0,0.0),TimeRange(0.0,0.1)); KinKal::ParticleTrajectory traj(line); @@ -127,7 +127,10 @@ namespace { require(targets[sweep.crossing().itarget_].sid_ == a.sid_,"tie depends on target order"); sweep.accept(); sweep.needsExtrapolation(traj,TimeDir::forwards); - require(!sweep.hasCrossing(),"coplanar seam material counted twice"); + require(sweep.hasCrossing() && targets[sweep.crossing().itarget_].sid_ == b.sid_,"coplanar plane not crossed"); + sweep.accept(); + sweep.needsExtrapolation(traj,TimeDir::forwards); + require(!sweep.hasCrossing(),"coplanar plane crossed twice"); } b.surf_ = &nearby; b.pl_ = &nearby; @@ -139,7 +142,7 @@ namespace { require(sweep.hasCrossing(),"first plane absent"); sweep.accept(); sweep.needsExtrapolation(traj,TimeDir::forwards); - require(sweep.hasCrossing(),"distinct nearby plane incorrectly seam-suppressed"); + require(sweep.hasCrossing(),"distinct nearby plane not crossed"); require(targets[sweep.crossing().itarget_].sid_ == b.sid_,"nearby plane identity differs"); } @@ -194,7 +197,7 @@ namespace { require(traj.nearestTraj(inter.time_) == traj.frontPtr(),"solver lower boundary has wrong piece"); } - void closeSeam(TimeDir dir) { + void closeCoplanar(TimeDir dir) { double sign = dir == TimeDir::forwards ? 1.0 : -1.0; KinKal::ParticleState state(VEC3(0.0,0.0,-1.0),VEC3(0.0,0.0,100.0),0.0,105.658,1); KinKal::KinematicLine line(state,VEC3(0.0,0.0,0.0),TimeRange(0.0,0.02)); @@ -212,13 +215,13 @@ namespace { sweep.start(dir == TimeDir::forwards ? 0.0 : 0.02); sweep.limit(dir == TimeDir::forwards ? 0.02 : 0.0,false); sweep.needsExtrapolation(traj,dir); - require(sweep.hasCrossing(),"close seam lacks first plane"); + require(sweep.hasCrossing(),"close coplanar fixture lacks first plane"); sweep.accept(); sweep.needsExtrapolation(traj,dir); - require(!sweep.hasCrossing(),"close coplanar seam not suppressed"); + require(sweep.hasCrossing() && sweep.crossing().itarget_ == 1,"close coplanar plane not crossed"); } - SweepTarget seamTarget(KinKal::Plane const& plane, mu2e::SurfaceId::enum_type id, SweepTarget::Effect pool, + SweepTarget planeTarget(KinKal::Plane const& plane, mu2e::SurfaceId::enum_type id, SweepTarget::Effect pool, MatEnv::DetMaterial const& material) { SweepTarget target; target.sid_ = mu2e::SurfaceId(id); @@ -229,9 +232,9 @@ namespace { return target; } - void tangentEpisode(TimeDir dir, bool split, bool windows, SweepTarget::Effect pool, + void tangentRecross(TimeDir dir, bool split, bool windows, SweepTarget::Effect pool, MatEnv::DetMaterial const& material, MatEnv::DetMaterial const& differentMaterial, unsigned control) { - constexpr double seamTol = 0.1; + constexpr double planeTol = 0.1; double sign = dir == TimeDir::forwards ? 1.0 : -1.0; KinKal::ParticleState state(VEC3(0.0,0.0,0.0),VEC3(100.0,0.0,10.0),0.0,105.658,1); KinKal::KinematicLine line(state,VEC3(0.0,0.0,0.0),TimeRange(-1.0,1.0)); @@ -250,9 +253,9 @@ namespace { KinKal::Rectangle separate(VEC3(0.0,0.0,1.0),VEC3(1.0,0.0,0.0),VEC3(0.0,0.0,sign*0.2),10.0,10.0); KinKal::Rectangle nonoverlap(VEC3(0.0,0.0,1.0),VEC3(1.0,0.0,0.0),VEC3(sign*2.2,0.0,sign*0.05),1.8,10.0); KinKal::Plane intervening(VEC3(1.0,0.0,0.0),VEC3(0.0,1.0,0.0),VEC3(sign*0.8,0.0,0.0)); - auto a = seamTarget(first,mu2e::SurfaceIdEnum::DS_Front,pool,material); - auto b = seamTarget(second,mu2e::SurfaceIdEnum::DS_Back,pool,material); - auto c = seamTarget(intervening,mu2e::SurfaceIdEnum::TT_Front,pool,material); + auto a = planeTarget(first,mu2e::SurfaceIdEnum::DS_Front,pool,material); + auto b = planeTarget(second,mu2e::SurfaceIdEnum::DS_Back,pool,material); + auto c = planeTarget(intervening,mu2e::SurfaceIdEnum::TT_Front,pool,material); if(control == 1) b.mat_ = &differentMaterial; if(control == 2) b.thick_ *= 2.0; if(control == 3) b.surf_ = b.pl_ = &tilted; @@ -262,39 +265,27 @@ namespace { if(control == 7) a.maxcross_ = 0; SweepTargetCollection targets{a,b,c}; double step = windows ? 0.15/vx : hi-lo; - ExtrapolateSweep sweep(targets,dir,1.0,step,1.0e-4,seamTol,1.0e-6,0); + ExtrapolateSweep sweep(targets,dir,1.0,step,1.0e-4,planeTol,1.0e-6,0); sweep.start(0.0); sweep.limit(end,false); - require(!sweep.needsExtrapolation(traj,dir) && sweep.hasCrossing(),"tangent episode lacks first crossing"); + require(!sweep.needsExtrapolation(traj,dir) && sweep.hasCrossing(),"tangent fixture lacks first crossing"); require(sweep.crossing().itarget_ == 0,"tangent first target differs"); double accepted = sweep.crossing().inter_.time_; - require(std::fabs(first.distance(sweep.crossing().inter_.pos_)) < seamTol,"tangent first point off plane"); + require(std::fabs(first.distance(sweep.crossing().inter_.pos_)) < planeTol,"tangent first point off plane"); sweep.accept(); sweep.start(accepted); - if(control == 0 || control == 7){ - sweep.limit(sign*0.15/vx,false); - require(!sweep.needsExtrapolation(traj,dir) && !sweep.hasCrossing(),"tangent seam escaped a short window"); - sweep.start(sign*0.15/vx); - sweep.limit(end,false); - require(!sweep.needsExtrapolation(traj,dir) && sweep.hasCrossing(),"intervening plane absent"); - require(sweep.crossing().itarget_ == 2,"tangent seam escaped before different-plane accept"); - accepted = sweep.crossing().inter_.time_; + bool neighbor = false; + for(unsigned trial = 0; trial < 3; ++trial){ + require(!sweep.needsExtrapolation(traj,dir),"tangent search requests extrapolation"); + if(!sweep.hasCrossing()) break; + require(sweep.crossing().itarget_ != 0,"plane crossed again inside its tolerance slab"); + if(sweep.crossing().itarget_ == 1) neighbor = true; sweep.accept(); - sweep.start(accepted); - require(!sweep.needsExtrapolation(traj,dir) && !sweep.hasCrossing(),"episode lost across start/piece/window/different-plane accept"); - } else { - bool neighbor = false; - for(unsigned trial = 0; trial < 3; ++trial){ - require(!sweep.needsExtrapolation(traj,dir),"control requests extrapolation"); - if(!sweep.hasCrossing()) break; - if(sweep.crossing().itarget_ == 1) neighbor = true; - sweep.accept(); - } - require(neighbor,"ineligible seam neighbor incorrectly suppressed"); } + require(neighbor,"neighbor plane not crossed"); } - void helixEpisodes(TimeDir dir, bool split, bool windows, bool self, MatEnv::DetMaterial const& material) { + void helixRecross(TimeDir dir, bool split, bool windows, bool self, MatEnv::DetMaterial const& material) { double sign = dir == TimeDir::forwards ? 1.0 : -1.0; KinKal::ParticleState state(VEC3(0.0,0.0,0.0),VEC3(100.0,0.0,20.0),0.0,105.658,1); KinKal::LoopHelix helix(state,VEC3(0.0,0.0,1.0),TimeRange(-1.0,1.0)); @@ -310,8 +301,8 @@ namespace { } KinKal::Rectangle first(VEC3(1.0,0.0,0.0),VEC3(0.0,1.0,0.0),VEC3(0.0,0.0,0.0),2000.0,2000.0); KinKal::Rectangle second(VEC3(-1.0,0.0,0.0),VEC3(0.0,1.0,0.0),VEC3(0.0,0.0,10.0),2000.0,2000.0); - auto a = seamTarget(first,mu2e::SurfaceIdEnum::DS_Front,SweepTarget::planeshell,material); - auto b = seamTarget(second,mu2e::SurfaceIdEnum::DS_Back,SweepTarget::planeshell,material); + auto a = planeTarget(first,mu2e::SurfaceIdEnum::DS_Front,SweepTarget::planeshell,material); + auto b = planeTarget(second,mu2e::SurfaceIdEnum::DS_Back,SweepTarget::planeshell,material); a.maxcross_ = self ? 0 : 1; SweepTargetCollection targets = self ? SweepTargetCollection{a} : SweepTargetCollection{a,b}; ExtrapolateSweep sweep(targets,dir,100.0,windows ? 0.13*period : hi-lo,1.0e-4,0.1,1.0e-6,0); @@ -320,19 +311,19 @@ namespace { for(unsigned icross = 0; icross < (self ? 3u : 2u); ++icross){ require(!sweep.needsExtrapolation(traj,dir) && sweep.hasCrossing(),"depart-return helix crossing absent"); auto const inter = sweep.crossing().inter_; - require(sweep.crossing().itarget_ == (self ? 0u : icross),"neighbor quota consumed by suppressed seam"); - require(std::fabs(inter.time_-sign*0.5*period*icross)*helix.speed(0.0) < 1.0,"helix recross time differs"); - if(icross > 0){ + require(sweep.crossing().itarget_ == (self ? 0u : icross),"helix crossing target differs"); + require(std::fabs(inter.time_-(self ? sign*0.5*period*icross : 0.0))*helix.speed(0.0) < 1.0,"helix recross time differs"); + if(self && icross > 0){ auto pos = traj.position3(sign*(0.5*icross-0.25)*period); require(std::fabs(first.distance(pos)) > 0.1 && std::fabs(second.distance(pos)) > 0.1,"helix lacks out-of-both departure"); } sweep.accept(); sweep.start(inter.time_); } - require(!sweep.needsExtrapolation(traj,dir) && !sweep.hasCrossing(),"helix episode/quota retained an extra crossing"); + require(!sweep.needsExtrapolation(traj,dir) && !sweep.hasCrossing(),"helix sweep found an extra crossing"); } - template void shallowEpisode(TimeDir dir, bool split, bool windows, bool reverse, MatEnv::DetMaterial const& material) { + template void shallowRecross(TimeDir dir, bool split, bool windows, bool reverse, MatEnv::DetMaterial const& material) { double sign = dir == TimeDir::forwards ? 1.0 : -1.0; KinKal::ParticleState state(VEC3(0.0,0.0,0.0),VEC3(100.0,0.0,20.0),0.0,105.658,1); HELIX helix(state,VEC3(0.0,0.0,1.0),TimeRange(-100.0,100.0)); @@ -350,21 +341,22 @@ namespace { traj.append(tail); } KinKal::Rectangle plane(VEC3(1.0,0.0,0.0),VEC3(0.0,1.0,0.0),helix.position3(begin),2000.0,2000.0); - auto a = seamTarget(plane,mu2e::SurfaceIdEnum::DS_Front,SweepTarget::planeshell,material); - auto b = seamTarget(plane,mu2e::SurfaceIdEnum::DS_Back,SweepTarget::planeshell,material); - SweepTargetCollection targets = reverse ? SweepTargetCollection{b,a} : SweepTargetCollection{a,b}; - ExtrapolateSweep sweep(targets,dir,100.0,windows ? 0.3*halfwidth : 100.0,1.0e-4,0.1,1.0e-6,0); + auto a = planeTarget(plane,mu2e::SurfaceIdEnum::DS_Front,SweepTarget::planeshell,material); + auto b = planeTarget(plane,mu2e::SurfaceIdEnum::DS_Back,SweepTarget::planeshell,material); + SweepTargetCollection single{a}; + single.front().maxcross_ = 0; + ExtrapolateSweep sweep(single,dir,100.0,windows ? 0.3*halfwidth : 100.0,1.0e-4,0.1,1.0e-6,0); sweep.start(begin); sweep.limit(end,false); - require(!sweep.needsExtrapolation(traj,dir) && sweep.hasCrossing() && targets[sweep.crossing().itarget_].sid_ == a.sid_,"shallow episode lacks first crossing"); + require(!sweep.needsExtrapolation(traj,dir) && sweep.hasCrossing(),"shallow fixture lacks first crossing"); sweep.accept(); require(std::fabs(plane.distance(helix.position3(maximum))) > 0.1 && std::fabs(plane.distance(helix.position3(maximum))) < 0.2,"shallow fixture does not resolve only one tolerance"); - require(!sweep.needsExtrapolation(traj,dir) && sweep.hasCrossing() && targets[sweep.crossing().itarget_].sid_ == b.sid_,"shallow resolved depart-return was suppressed"); + require(!sweep.needsExtrapolation(traj,dir) && sweep.hasCrossing(),"shallow resolved depart-return was suppressed"); require(sign*(sweep.crossing().inter_.time_-maximum) > 0.0,"shallow return accepted before resolved departure"); require(std::fabs(plane.distance(sweep.crossing().inter_.pos_)) < 0.1,"shallow return outside plane tolerance"); - // An outgoing query must find the later root without requiring a preceding accepted seam. - targets.front().maxcross_ = targets.back().maxcross_ = 1; + // An outgoing query must find the later root without a preceding accepted crossing. + SweepTargetCollection targets = reverse ? SweepTargetCollection{b,a} : SweepTargetCollection{a,b}; ExtrapolateSweep outgoing(targets,dir,100.0,windows ? 0.3*halfwidth : 100.0,1.0e-4,0.1,1.0e-6,0); double queryStart = maximum-sign*0.5*halfwidth; require(std::fabs(plane.distance(helix.position3(queryStart))) > 0.1,"outgoing query starts inside tolerance slab"); @@ -430,7 +422,7 @@ namespace { require(std::fabs(inter.time_-sign*0.125*period)*helix.speed(inter.time_) < tol,"long query lost early bracketed crossing"); } - void speculativeEpisode(TimeDir dir, MatEnv::DetMaterial const& material) { + void speculativeRecross(TimeDir dir, MatEnv::DetMaterial const& material) { double sign = dir == TimeDir::forwards ? 1.0 : -1.0; auto makeLine = [](VEC3 const& pos, VEC3 const& momentum, double time){ KinKal::ParticleState state(pos,momentum,time,105.658,1); @@ -450,33 +442,33 @@ namespace { else { traj.append(last); traj.append(middle); traj.append(first); } KinKal::Rectangle plane(VEC3(0.0,0.0,1.0),VEC3(1.0,0.0,0.0),VEC3(0.0,0.0,0.0),10.0,10.0); KinKal::Plane other(VEC3(1.0,0.0,0.0),VEC3(0.0,1.0,0.0),VEC3(sign*0.8,0.0,0.0)); - auto a = seamTarget(plane,mu2e::SurfaceIdEnum::DS_Front,SweepTarget::planeshell,material); - auto b = seamTarget(plane,mu2e::SurfaceIdEnum::DS_Back,SweepTarget::planeshell,material); - auto c = seamTarget(other,mu2e::SurfaceIdEnum::TT_Front,SweepTarget::planeshell,material); - SweepTargetCollection targets{a,b,c}; + auto a = planeTarget(plane,mu2e::SurfaceIdEnum::DS_Front,SweepTarget::planeshell,material); + auto c = planeTarget(other,mu2e::SurfaceIdEnum::TT_Front,SweepTarget::planeshell,material); + a.maxcross_ = 0; + SweepTargetCollection targets{a,c}; ExtrapolateSweep sweep(targets,dir,1.0,1.0,1.0e-4,0.1,1.0e-6,0); sweep.start(0.0); sweep.limit(end,false); require(!sweep.needsExtrapolation(traj,dir) && sweep.hasCrossing() && sweep.crossing().itarget_ == 0, - "speculative fixture lacks initial seam crossing"); + "speculative fixture lacks initial plane crossing"); double initial = sweep.crossing().inter_.time_; sweep.accept(); - sweep.setActive(2,false); - require(!sweep.needsExtrapolation(traj,dir) && sweep.hasCrossing() && sweep.crossing().itarget_ == 1 && + sweep.setActive(1,false); + require(!sweep.needsExtrapolation(traj,dir) && sweep.hasCrossing() && sweep.crossing().itarget_ == 0 && sign*(sweep.crossing().inter_.time_-t2) > 0.0,"speculative fixture lacks future return candidate"); - sweep.setActive(2,true); + sweep.setActive(1,true); sweep.start(initial); - require(!sweep.needsExtrapolation(traj,dir) && sweep.hasCrossing() && sweep.crossing().itarget_ == 2, + require(!sweep.needsExtrapolation(traj,dir) && sweep.hasCrossing() && sweep.crossing().itarget_ == 1, "earlier different plane did not win over future return"); double accepted = sweep.crossing().inter_.time_; sweep.accept(); auto changed = first; changed.setRange(TimeRange(std::min(0.0,end),std::max(0.0,end))); KinKal::ParticleTrajectory updated(changed); - require(std::fabs(plane.distance(updated.position3(end))) < 0.1,"updated trajectory left the seam slab"); + require(std::fabs(plane.distance(updated.position3(end))) < 0.1,"updated trajectory left the plane tolerance slab"); sweep.start(accepted); require(!sweep.needsExtrapolation(updated,dir) && !sweep.hasCrossing(), - "speculative future witness released an episode before trajectory mutation"); + "speculative future witness released the plane before trajectory mutation"); } KinKal::LoopHelix materialPiece(double join, TimeRange const& range, VEC3 const& momentum) { @@ -780,29 +772,29 @@ int main() { notBefore(dir); invalidBoundaryInterior(dir,true); invalidBoundaryInterior(dir,false); - closeSeam(dir); + closeCoplanar(dir); planarLimits(dir); planeContacts(dir); planeContacts(dir); longPlaneQuery(dir); longPlaneQuery(dir); - speculativeEpisode(dir,*targetMaterial); + speculativeRecross(dir,*targetMaterial); for(bool split : {false,true}){ for(bool windows : {false,true}){ for(bool reverse : {false,true}){ - shallowEpisode(dir,split,windows,reverse,*targetMaterial); - shallowEpisode(dir,split,windows,reverse,*targetMaterial); + shallowRecross(dir,split,windows,reverse,*targetMaterial); + shallowRecross(dir,split,windows,reverse,*targetMaterial); } for(auto pool : {SweepTarget::planeshell,SweepTarget::crvsector,SweepTarget::stfoil}){ - tangentEpisode(dir,split,windows,pool,*targetMaterial,*differentMaterial,0); - tangentEpisode(dir,split,windows,pool,*targetMaterial,*differentMaterial,7); + tangentRecross(dir,split,windows,pool,*targetMaterial,*differentMaterial,0); + tangentRecross(dir,split,windows,pool,*targetMaterial,*differentMaterial,7); } - helixEpisodes(dir,split,windows,false,*targetMaterial); - helixEpisodes(dir,split,windows,true,*targetMaterial); + helixRecross(dir,split,windows,false,*targetMaterial); + helixRecross(dir,split,windows,true,*targetMaterial); } } for(unsigned control = 1; control <= 6; ++control) - for(bool windows : {false,true}) tangentEpisode(dir,true,windows,SweepTarget::planeshell,*targetMaterial,*differentMaterial,control); + for(bool windows : {false,true}) tangentRecross(dir,true,windows,SweepTarget::planeshell,*targetMaterial,*differentMaterial,control); for(bool split : {false,true}){ boundaries(dir,split); for(bool bounds : {false,true}) lineRoots(dir,split,bounds); @@ -812,7 +804,7 @@ int main() { solverLowerBoundary(); tiltedZ(); tiltedZ(); - stableTieAndSeams(); + stableTie(); retryBudget(); emptySearch(); std::cout << "ExtrapolateSweepTest: all checks passed" << std::endl; diff --git a/Mu2eKinKal/src/KinematicLineFit_module.cc b/Mu2eKinKal/src/KinematicLineFit_module.cc index ee0d03bf26..1ecc83e40c 100644 --- a/Mu2eKinKal/src/KinematicLineFit_module.cc +++ b/Mu2eKinKal/src/KinematicLineFit_module.cc @@ -378,8 +378,7 @@ namespace mu2e { void KinematicLineFit::sampleFit(KKTRK& kktrk) const { auto const& ftraj = kktrk.fitTraj(); // need to extend range for now even if sampleinrange_ is false - // a particle that ranges out stops there, so its trajectory is not extended forwards - TimeRange extrange(ftraj.range().begin() - sampletbuff_,ftraj.range().end() + (kktrk.rangedOut() ? 0.0 : sampletbuff_)); + TimeRange extrange(ftraj.range().begin() - sampletbuff_,ftraj.range().end() + sampletbuff_); kktrk.extendTraj(extrange); double tbeg = ftraj.range().begin(); @@ -393,12 +392,7 @@ namespace mu2e { // loop to find multiple intersections while(goodinter && cur_inter < max_inter) { cur_inter += 1; - double tmax = std::max(ftraj.range().end(),tstart); - if(kktrk.rangedOut()){ - tmax = std::min(tmax,kktrk.rangeOutTime()); - if(tstart >= tmax) break; - } - TimeRange irange(tstart,tmax); + TimeRange irange(tstart,std::max(ftraj.range().end(),tstart)); auto surfinter = KinKal::intersect(ftraj,*surf.second,irange,intertol_); goodinter = surfinter.onsurface_ && ( (! sampleinbounds_) || surfinter.inbounds_ ) && ( (!sampleinrange_) || irange.inRange(surfinter.time_)); if(goodinter) {