From 9cce2acab28e4a19d06f0135768ac33822de78ca Mon Sep 17 00:00:00 2001 From: David Nathan Brown Date: Fri, 20 Nov 2026 15:55:34 -0800 Subject: [PATCH 1/7] Add a projection of the spatial covariance to the Intersection payload. Address https://github.com/KFTrack/KinKal/issues/237 in the process. Code by Claude --- Geometry/Intersect.hh | 22 +++- Geometry/Intersection.hh | 6 + Tests/CMakeLists.txt | 1 + Tests/IntersectionCovariance_unit.cc | 181 +++++++++++++++++++++++++++ Trajectory/CentralHelix.cc | 23 +++- Trajectory/CentralHelix.hh | 1 + Trajectory/KinematicLine.cc | 16 ++- Trajectory/LoopHelix.cc | 16 ++- 8 files changed, 248 insertions(+), 18 deletions(-) create mode 100644 Tests/IntersectionCovariance_unit.cc diff --git a/Geometry/Intersect.hh b/Geometry/Intersect.hh index 954e6073..23b45eb4 100644 --- a/Geometry/Intersect.hh +++ b/Geometry/Intersect.hh @@ -17,6 +17,20 @@ #include "Math/VectorUtil.h" #include namespace KinKal { + // + // fill the local plane UV system and the projection of the trajectory spatial covariance onto it. + // The projection (see KTRAJ::planeCovariance) is along the trajectory direction, so it describes the covariance of where the trajectory crosses the plane. + // If the trajectory is (nearly) parallel to the plane, the projection is singular and the covariance is left 0. + // + template void fillPlaneCovariance(KTRAJ const& ktraj, Surface const& surf, Intersection& inter) { + auto plane = surf.tangentPlane(inter.pos_); + inter.udir_ = plane.uDirection(); + inter.vdir_ = plane.vDirection(); + inter.pcov_ = PMAT(); + // the projection is singular if the trajectory lies in the plane + if(fabs(plane.normal().Dot(ktraj.direction(inter.time_))) < 1.0e-10) return; + inter.pcov_ = ktraj.planeCovariance(inter.time_,plane); + } // // generic intersection implementation based on stepping across the surface within a given range in the given time direction // @@ -96,6 +110,7 @@ namespace KinKal { retval.pdir_ = ktraj.direction(retval.time_); retval.inbounds_ = surf.inBounds(retval.pos_,tol); retval.norm_ = surf.normal(retval.pos_); + fillPlaneCovariance(ktraj,surf,retval); } } // check the final time to be in range @@ -188,7 +203,7 @@ namespace KinKal { } else { // the trajectory curves macroscopically over this range: see if the axis is normal double tstart = tdir == TimeDir::forwards ? trange.begin() : trange.end(); - auto ray = helix.linearize(tstart); + auto ray = helix.axis(tstart); auto velo = helix.velocity(tstart); if(tdir == TimeDir::backwards) ray.reverse(); // reverse if going backwards in time double vax = velo.Dot(ray.direction()); // speed along axis @@ -196,8 +211,8 @@ namespace KinKal { double ddot = fabs(ray.direction().Dot(plane.normal())); double zrange = fabs(vax*trange.range()); if(zrange > tol && ddot > tol/zrange ){ - // Find where the trajectory's linearized ray (the helix axis for LoopHelix, the tangent for CentralHelix) crosses - // the plane, to reduce the range. The ray crossing can be behind the start even when the trajectory crosses the + // Find where the helix axis crosses the plane, to reduce the range. All plane crossings of the helix lie within + // R*tan(theta) of this point along the axis. The ray crossing can be behind the start even when the trajectory crosses the // plane after it, so accept either direction double dist(0.0); auto pinter = plane.intersect(ray,dist,false,tol); @@ -312,6 +327,7 @@ namespace KinKal { retval.norm_ = surf.normal(retval.pos_); retval.time_ = tstart + dist*timeDirSign(tdir)/kkline.speed(tstart); retval.pdir_ = kkline.direction(retval.time_); + fillPlaneCovariance(kkline,surf,retval); } // check the final time to be in range; retval.inrange_ = trange.inRange(retval.time_); diff --git a/Geometry/Intersection.hh b/Geometry/Intersection.hh index 8cf60f47..9f5744ee 100644 --- a/Geometry/Intersection.hh +++ b/Geometry/Intersection.hh @@ -18,6 +18,12 @@ namespace KinKal { VEC3 pdir_; // particle direction at intersection double time_ = 0.0; // time at intersection (from particle) bool gap_ = false; // intersection is in a piecewise-trajectory gap + // local plane (tangent to the surface at the intersection) coordinate system; W = norm_ + VEC3 udir_; // local plane U direction + VEC3 vdir_; // local plane V direction + // projected spatial covariance of the trajectory at the intersection onto the local plane, in UV coordinates. + // This is filled for all onsurface intersections (in bounds or not), as long as the trajectory isn't parallel to the plane + PMAT pcov_; Ray ray() const { return Ray(pdir_,pos_); } // linear particle trajectory at intersection friend std::ostream& operator << (std::ostream& ost, KinKal::Intersection const& inter); }; diff --git a/Tests/CMakeLists.txt b/Tests/CMakeLists.txt index 6c7073a3..82023068 100644 --- a/Tests/CMakeLists.txt +++ b/Tests/CMakeLists.txt @@ -28,6 +28,7 @@ set( TEST_SOURCE_FILES Geometry_unit.cc Intersection_unit.cc IntersectReturn_unit.cc + IntersectionCovariance_unit.cc MatEnv_unit.cc Truncate_unit.cc ) diff --git a/Tests/IntersectionCovariance_unit.cc b/Tests/IntersectionCovariance_unit.cc new file mode 100644 index 00000000..2876f523 --- /dev/null +++ b/Tests/IntersectionCovariance_unit.cc @@ -0,0 +1,181 @@ +// +// Test the projected spatial covariance of a trajectory onto the local plane at an intersection (Intersection::pcov_) +// by comparing it with a toy MC: the trajectory parameters are randomized according to their covariance, the +// intersection is recomputed, and the spread of the intersection points in the local plane UV system is measured. +// Also tests consistency of pcov_ with KTRAJ::planeCovariance, and that the covariance is filled for +// intersections that are on the surface but out of bounds. +// original author: David Brown (LBNL) 2026 +// +#include "KinKal/Geometry/Intersection.hh" +#include "KinKal/Geometry/Intersect.hh" +#include "KinKal/Geometry/Plane.hh" +#include "KinKal/Geometry/Rectangle.hh" +#include "KinKal/Geometry/Cylinder.hh" +#include +#include +#include +#include +#include + +using namespace KinKal; +using std::cout; +using std::endl; + +static struct option long_options[] = { + {"ntoy", required_argument, 0, 'n' }, + {"seed", required_argument, 0, 's' }, + {"verbose", required_argument, 0, 'v' }, + {NULL, 0,0,0} +}; + +void print_usage() { + printf("Usage: IntersectionCovariance --ntoy (number of toy MC trials) --seed (random seed) --verbose (verbosity)\n"); +} + +// set a diagonal parameter covariance +template void setCovariance(KTRAJ& ktraj, std::array const& sigmas) { + for(size_t ipar=0;ipar < NParams(); ++ipar){ + for(size_t jpar=0;jpar < NParams(); ++jpar){ + ktraj.params().covariance()(ipar,jpar) = ipar == jpar ? sigmas[ipar]*sigmas[ipar] : 0.0; + } + } +} + +// INTERF is a callable (KTRAJ const&, SURF const&, TimeRange const&) -> Intersection +template int testCovariance(std::string const& name, KTRAJ const& ktraj, SURF const& surf, + TimeRange const& trange, INTERF interf, bool expectinbounds, unsigned ntoy, unsigned seed, int verbose) { + static const double vartol(0.05); // relative tolerance on toy variance (statistical precision ~1% for 20K toys) + static const double rhotol(0.03); // absolute tolerance on the toy correlation coefficient + static const double ctol(1.0e-9); // relative tolerance on consistency checks + auto inter = interf(ktraj,surf,trange); + if(verbose > 0) cout << name << " " << inter << endl; + if(!inter.onsurface_){ + cout << name << ": intersection not on surface" << endl; + return -1; + } + if(inter.inbounds_ != expectinbounds){ + cout << name << ": unexpected inbounds state " << inter.inbounds_ << endl; + return -1; + } + // check the UV system is orthonormal and right-handed with the normal + if(fabs(inter.udir_.Dot(inter.vdir_)) > ctol || fabs(inter.udir_.Dot(inter.norm_)) > ctol || + fabs(inter.udir_.R()-1.0) > ctol || fabs(inter.vdir_.R()-1.0) > ctol || + (inter.udir_.Cross(inter.vdir_) - inter.norm_).R() > ctol){ + cout << name << ": local plane UV system is not orthonormal" << endl; + return -1; + } + auto const& pcov = inter.pcov_; + if(pcov(0,0) <= 0.0 || pcov(1,1) <= 0.0 || pcov(0,0)*pcov(1,1) <= pcov(0,1)*pcov(0,1)){ + cout << name << ": plane covariance not positive definite " << pcov << endl; + return -1; + } + // consistency with the trajectory planeCovariance function, using the local tangent plane + auto tplane = surf.tangentPlane(inter.pos_); + auto tcov = ktraj.planeCovariance(inter.time_,tplane); + for(int irow=0;irow<2;++irow){ + for(int icol=0;icol<2;++icol){ + if(fabs(tcov(irow,icol)-pcov(irow,icol)) > ctol*sqrt(pcov(0,0)*pcov(1,1))){ + cout << name << ": inconsistent with planeCovariance " << tcov << " " << pcov << endl; + return -1; + } + } + } + // toy MC: randomize the parameters and measure the spread of the intersection points in the local plane + // restrict the toy intersection search to a small window around the nominal intersection, to avoid finding other + // (physically different) intersections on other loops + static const double dt(0.5); // ns + TimeRange toyrange(inter.time_-dt,inter.time_+dt); + std::mt19937 gen(seed); + std::normal_distribution gauss(0.0,1.0); + double su(0.0), sv(0.0), suu(0.0), svv(0.0), suv(0.0); + unsigned nsurf(0); + for(unsigned itoy=0; itoy < ntoy; ++itoy){ + auto pars = ktraj.params(); + for(size_t ipar=0;ipar < NParams(); ++ipar) + pars.parameters()[ipar] += gauss(gen)*sqrt(ktraj.params().covariance()(ipar,ipar)); + KTRAJ toytraj(pars,ktraj); + auto toyinter = interf(toytraj,surf,toyrange); + if(!toyinter.onsurface_) continue; + auto dpos = toyinter.pos_ - inter.pos_; + double du = dpos.Dot(inter.udir_); + double dv = dpos.Dot(inter.vdir_); + su += du; sv += dv; suu += du*du; svv += dv*dv; suv += du*dv; + ++nsurf; + } + if(nsurf < 0.99*ntoy){ + cout << name << ": too many toy intersections failed " << nsurf << " of " << ntoy << endl; + return -1; + } + su /= nsurf; sv /= nsurf; + double toyuu = suu/nsurf - su*su; + double toyvv = svv/nsurf - sv*sv; + double toyuv = suv/nsurf - su*sv; + double toyrho = toyuv/sqrt(toyuu*toyvv); + double rho = pcov(0,1)/sqrt(pcov(0,0)*pcov(1,1)); + if(verbose > 0){ + cout << name << " pcov uu " << pcov(0,0) << " vv " << pcov(1,1) << " rho " << rho << endl; + cout << name << " toyMC uu " << toyuu << " vv " << toyvv << " rho " << toyrho << " ntoy " << nsurf << endl; + } + if(fabs(toyuu-pcov(0,0)) > vartol*pcov(0,0) || fabs(toyvv-pcov(1,1)) > vartol*pcov(1,1) || fabs(toyrho-rho) > rhotol){ + cout << name << ": plane covariance disagrees with toy MC: pcov uu " << pcov(0,0) << " vv " << pcov(1,1) << " rho " << rho + << " toy uu " << toyuu << " vv " << toyvv << " rho " << toyrho << endl; + return -1; + } + return 0; +} + +int main(int argc, char** argv) { + unsigned ntoy(20000), seed(124223); + int verbose(0); + int opt; + int long_index =0; + while ((opt = getopt_long_only(argc, argv,"", + long_options, &long_index )) != -1) { + switch (opt) { + case 'n' : ntoy = atoi(optarg); + break; + case 's' : seed = atoi(optarg); + break; + case 'v' : verbose = atoi(optarg); + break; + default: print_usage(); + exit(EXIT_FAILURE); + } + } + VEC3 bnom(0.0,0.0,1.0); + VEC4 pos(0.0,0.0,0.0,0.0); + MOM4 mom(40.0,30.0,60.0,0.511); + TimeRange trange(-10.0,100.0); + double tol(1.0e-6); + // surfaces: tilted plane, a small rectangle on that plane (so the intersection is out of bounds), and a cylinder + VEC3 norm = VEC3(0.3,0.2,1.0).Unit(); + VEC3 udir = norm.Cross(VEC3(0.0,1.0,0.0)).Unit(); + VEC3 pcent(5.0,-3.0,400.0); + Plane plane(norm,udir,pcent); + Rectangle rect(norm,udir,pcent,1.0,1.0); + Cylinder cyl(VEC3(0.0,0.0,1.0),VEC3(0.0,0.0,0.0),200.0,1000.0); + // trajectories with diagonal parameter covariance + LoopHelix lhelix(pos,mom,-1,bnom,trange); + setCovariance(lhelix,{0.5,0.5,0.5,0.5,0.002,0.05}); + CentralHelix chelix(pos,mom,-1,bnom,trange); + setCovariance(chelix,{0.3,0.002,1.0e-5,0.3,0.001,0.05}); + KinematicLine kline(pos,mom,-1,bnom,trange); + setCovariance(kline,{0.1,0.1,0.0005,0.0005,0.005,0.05}); + + auto inter = [&](auto const& ktraj, auto const& surf, TimeRange const& range) { return intersect(ktraj,surf,range,tol); }; + + int status(0); + status |= testCovariance("LoopHelix Plane",lhelix,plane,trange,inter,true,ntoy,seed,verbose); + status |= testCovariance("LoopHelix Rectangle (out of bounds)",lhelix,rect,trange,inter,false,ntoy,seed,verbose); + status |= testCovariance("LoopHelix Cylinder",lhelix,cyl,trange,inter,true,ntoy,seed,verbose); + status |= testCovariance("CentralHelix Plane",chelix,plane,trange,inter,true,ntoy,seed,verbose); + status |= testCovariance("CentralHelix Cylinder",chelix,cyl,trange,inter,true,ntoy,seed,verbose); + status |= testCovariance("KinematicLine Plane",kline,plane,trange,inter,true,ntoy,seed,verbose); + status |= testCovariance("KinematicLine Rectangle (out of bounds)",kline,rect,trange,inter,false,ntoy,seed,verbose); + status |= testCovariance("KinematicLine Cylinder",kline,cyl,trange,inter,true,ntoy,seed,verbose); + if(status == 0) + cout << "IntersectionCovariance test passed" << endl; + else + cout << "IntersectionCovariance test FAILED" << endl; + return status; +} diff --git a/Trajectory/CentralHelix.cc b/Trajectory/CentralHelix.cc index 12b02175..d4e86828 100644 --- a/Trajectory/CentralHelix.cc +++ b/Trajectory/CentralHelix.cc @@ -165,13 +165,19 @@ namespace KinKal { } PMAT CentralHelix::planeCovariance(double time,Plane const& plane) const { - // project covariance onto the U, V direction of the given plane - // particle direction cannot be orthogonal to the plane normal + // project the spatial covariance onto the U, V directions of the given plane. The projection is + // along the particle direction, so the result describes the covariance of the point where the trajectory + // crosses the plane. This includes the effect of the t0 (and other) errors on the position along the trajectory. + // The particle direction cannot lie in the plane auto momdir = direction(time); - if(fabs(plane.normal().Dot(momdir)) < 1.0e-10)throw invalid_argument("Momentum direction lies in the plane"); + double ndot = plane.normal().Dot(momdir); + if(fabs(ndot) < 1.0e-10)throw invalid_argument("Momentum direction lies in the plane"); + // a perturbation dx moves the crossing point by dx - momdir*(norm.dx)/(norm.momdir) + auto uproj = plane.uDirection() - plane.normal()*(plane.uDirection().Dot(momdir)/ndot); + auto vproj = plane.vDirection() - plane.normal()*(plane.vDirection().Dot(momdir)/ndot); auto dxdpvec = dXdPar(time); - SVEC3 uvec(plane.uDirection().X(),plane.uDirection().Y(),plane.uDirection().Z()); - SVEC3 vvec(plane.vDirection().X(),plane.vDirection().Y(),plane.vDirection().Z()); + SVEC3 uvec(uproj.X(),uproj.Y(),uproj.Z()); + SVEC3 vvec(vproj.X(),vproj.Y(),vproj.Z()); PPMAT dPlanedPar; dPlanedPar.Place_in_row(uvec*dxdpvec,0,0); dPlanedPar.Place_in_row(vvec*dxdpvec,1,0); @@ -488,6 +494,13 @@ namespace KinKal { return Ray(direction(time),position3(time)); } + Ray CentralHelix::axis(double time) const { + // direction is along Bnom, signed by the velocity component along it. Note Bnom is in global coordinates + VEC3 adir = bnom_.Unit(); + if(adir.Dot(velocity(time)) < 0.0) adir *= -1.0; + return Ray(adir,center(time)); + } + double CentralHelix::sagitta(double trange) const { double tlen = trange*transverseSpeed(); double brad = bendRadius(); diff --git a/Trajectory/CentralHelix.hh b/Trajectory/CentralHelix.hh index 7cd7fc15..26764483 100644 --- a/Trajectory/CentralHelix.hh +++ b/Trajectory/CentralHelix.hh @@ -150,6 +150,7 @@ namespace KinKal { // helix interface VEC3 center(double time) const; // helix center in global coordinates Ray tangent(double time) const; // tangent to the helix at a given time + Ray axis(double time) const; // helix axis in global coordinates, directed along the motion // linear approximation Ray linearize(double time) const { return tangent(time); } double bendRadius() const { return fabs(1.0/omega()); } diff --git a/Trajectory/KinematicLine.cc b/Trajectory/KinematicLine.cc index ae54ff96..1c055ebb 100644 --- a/Trajectory/KinematicLine.cc +++ b/Trajectory/KinematicLine.cc @@ -133,13 +133,19 @@ namespace KinKal { } PMAT KinematicLine::planeCovariance(double time,Plane const& plane) const { - // project covariance onto the U, V direction of the given plane - // particle direction cannot be orthogonal to the plane normal + // project the spatial covariance onto the U, V directions of the given plane. The projection is + // along the particle direction, so the result describes the covariance of the point where the trajectory + // crosses the plane. This includes the effect of the t0 (and other) errors on the position along the trajectory. + // The particle direction cannot lie in the plane auto momdir = direction(time); - if(fabs(plane.normal().Dot(momdir)) < 1.0e-10)throw invalid_argument("Momentum direction lies in the plane"); + double ndot = plane.normal().Dot(momdir); + if(fabs(ndot) < 1.0e-10)throw invalid_argument("Momentum direction lies in the plane"); + // a perturbation dx moves the crossing point by dx - momdir*(norm.dx)/(norm.momdir) + auto uproj = plane.uDirection() - plane.normal()*(plane.uDirection().Dot(momdir)/ndot); + auto vproj = plane.vDirection() - plane.normal()*(plane.vDirection().Dot(momdir)/ndot); auto dxdpvec = dXdPar(time); - SVEC3 uvec(plane.uDirection().X(),plane.uDirection().Y(),plane.uDirection().Z()); - SVEC3 vvec(plane.vDirection().X(),plane.vDirection().Y(),plane.vDirection().Z()); + SVEC3 uvec(uproj.X(),uproj.Y(),uproj.Z()); + SVEC3 vvec(vproj.X(),vproj.Y(),vproj.Z()); PPMAT dPlanedPar; dPlanedPar.Place_in_row(uvec*dxdpvec,0,0); dPlanedPar.Place_in_row(vvec*dxdpvec,1,0); diff --git a/Trajectory/LoopHelix.cc b/Trajectory/LoopHelix.cc index 8f119995..be95f784 100644 --- a/Trajectory/LoopHelix.cc +++ b/Trajectory/LoopHelix.cc @@ -134,13 +134,19 @@ namespace KinKal { } PMAT LoopHelix::planeCovariance(double time,Plane const& plane) const { - // project covariance onto the U, V direction of the given plane - // particle direction cannot be orthogonal to the plane normal + // project the spatial covariance onto the U, V directions of the given plane. The projection is + // along the particle direction, so the result describes the covariance of the point where the trajectory + // crosses the plane. This includes the effect of the t0 (and other) errors on the position along the trajectory. + // The particle direction cannot lie in the plane auto momdir = direction(time); - if(fabs(plane.normal().Dot(momdir)) < 1.0e-10)throw invalid_argument("Momentum direction lies in the plane"); + double ndot = plane.normal().Dot(momdir); + if(fabs(ndot) < 1.0e-10)throw invalid_argument("Momentum direction lies in the plane"); + // a perturbation dx moves the crossing point by dx - momdir*(norm.dx)/(norm.momdir) + auto uproj = plane.uDirection() - plane.normal()*(plane.uDirection().Dot(momdir)/ndot); + auto vproj = plane.vDirection() - plane.normal()*(plane.vDirection().Dot(momdir)/ndot); auto dxdpvec = dXdPar(time); - SVEC3 uvec(plane.uDirection().X(),plane.uDirection().Y(),plane.uDirection().Z()); - SVEC3 vvec(plane.vDirection().X(),plane.vDirection().Y(),plane.vDirection().Z()); + SVEC3 uvec(uproj.X(),uproj.Y(),uproj.Z()); + SVEC3 vvec(vproj.X(),vproj.Y(),vproj.Z()); PPMAT dPlanedPar; dPlanedPar.Place_in_row(uvec*dxdpvec,0,0); dPlanedPar.Place_in_row(vvec*dxdpvec,1,0); From bae8ab3a6e508f70ab85841a04ebab6954b17f88 Mon Sep 17 00:00:00 2001 From: David Nathan Brown Date: Fri, 20 Nov 2026 16:45:41 -0800 Subject: [PATCH 2/7] simplify canIntersect to catch glancing intersections with non-colinear helix and cylinder and frustrum axes. Add a unit test of this situation. Coded by Claude --- Geometry/Intersect.hh | 27 +++++-- Tests/CMakeLists.txt | 1 + Tests/IntersectTilt_unit.cc | 146 ++++++++++++++++++++++++++++++++++++ 3 files changed, 169 insertions(+), 5 deletions(-) create mode 100644 Tests/IntersectTilt_unit.cc diff --git a/Geometry/Intersect.hh b/Geometry/Intersect.hh index 23b45eb4..c96f0e93 100644 --- a/Geometry/Intersect.hh +++ b/Geometry/Intersect.hh @@ -129,21 +129,38 @@ namespace KinKal { auto hbeg = helix.center(trange.begin()); auto hend = helix.center(trange.end()); // if the circles are fully contained one in the other no intersection is possible + // The helix center moves linearly in time along bnom, so its distance from the cylinder axis is convex in time + // and is largest at one end of the range. A crossing requires the circles to not be nested at some time, so + // it is enough to test the larger end separation. double dbeg = ROOT::Math::VectorUtil::Perp(hbeg - cyl.center(),cyl.axis()); double dend = ROOT::Math::VectorUtil::Perp(hend - cyl.center(),cyl.axis()); - double drad = fabs(cyl.radius()-helix.bendRadius()); - return dbeg > drad -tol && dend > drad -tol; + // If bnom is tilted from the cylinder axis, the helix circle projects onto an ellipse whose minor axis is shorter by cos(tilt), + // so it can reach that much closer to the cylinder axis + double cost = fabs(helix.bnom().Unit().Dot(cyl.axis())); + double rbend = helix.bendRadius(); + double drad = cyl.radius() > rbend ? cyl.radius() - rbend : rbend*cost - cyl.radius(); + return std::max(dbeg,dend) > drad - tol; } template < class HELIX> bool canIntersect( HELIX const& helix, KinKal::Frustrum const& fru, TimeRange const& trange, double tol) { auto hbeg = helix.center(trange.begin()); auto hend = helix.center(trange.end()); // if the circles are fully contained one in the other no intersection is possible + // As for the cylinder, the helix center distance from the axis is convex in time. While the sign of (cone radius - bend radius) + // is unchanged the nesting cut is linear in time, so the separation beyond the cut is largest at one end of the range. double dbeg = ROOT::Math::VectorUtil::Perp(hbeg - fru.center(),fru.axis()); double dend = ROOT::Math::VectorUtil::Perp(hend - fru.center(),fru.axis()); - double dradbeg = fru.radius(hbeg)-helix.bendRadius(); - double dradend = fru.radius(hend)-helix.bendRadius(); - return dradbeg*dradend < 0.0 || (dbeg > fabs(dradbeg) -tol && dend > fabs(dradend) -tol); + double rbend = helix.bendRadius(); + double rfbeg = fru.radius(hbeg); + double rfend = fru.radius(hend); + if((rfbeg-rbend)*(rfend-rbend) < 0.0) return true; + // If bnom is tilted from the axis the helix circle projects onto an ellipse with minor axis rbend*cos(tilt), and it spans + // +-rbend*sin(tilt) along the axis, over which the cone radius changes by that times the cone slope + double cost = fabs(helix.bnom().Unit().Dot(fru.axis())); + double sint = sqrt(std::max(1.0-cost*cost,0.0)); + double slack = rbend*sint*fabs(fru.highRadius()-fru.lowRadius())/(2.0*fru.halfLength()); + auto drad = [rbend,cost](double rf) { return rf > rbend ? rf - rbend : rbend*cost - rf; }; + return std::max(dbeg - drad(rfbeg), dend - drad(rfend)) > -tol - slack; } template < class HELIX> Intersection hcIntersect( HELIX const& helix, KinKal::Cylinder const& cyl, TimeRange trange ,double tol,TimeDir tdir = TimeDir::forwards) { diff --git a/Tests/CMakeLists.txt b/Tests/CMakeLists.txt index 82023068..68ac678c 100644 --- a/Tests/CMakeLists.txt +++ b/Tests/CMakeLists.txt @@ -29,6 +29,7 @@ set( TEST_SOURCE_FILES Intersection_unit.cc IntersectReturn_unit.cc IntersectionCovariance_unit.cc + IntersectTilt_unit.cc MatEnv_unit.cc Truncate_unit.cc ) diff --git a/Tests/IntersectTilt_unit.cc b/Tests/IntersectTilt_unit.cc new file mode 100644 index 00000000..1273eb44 --- /dev/null +++ b/Tests/IntersectTilt_unit.cc @@ -0,0 +1,146 @@ +// +// Test helix intersections with cylinders and frustra when the nominal BField is tilted from the surface axis. +// Random queries are compared against a reference found by stepping over the whole time range; intersect must not +// miss a crossing the reference finds, nor return a later one. This exercises canIntersect (KFTrack/KinKal#238). +// original author: David Brown (LBNL) 2026 +// +#include "KinKal/Geometry/Intersection.hh" +#include "KinKal/Geometry/Intersect.hh" +#include "KinKal/Geometry/Cylinder.hh" +#include "KinKal/Geometry/Frustrum.hh" +#include +#include +#include +#include +#include + +using namespace KinKal; +using std::cout; +using std::endl; + +static struct option long_options[] = { + {"nquery", required_argument, 0, 'n' }, + {"seed", required_argument, 0, 's' }, + {"verbose", required_argument, 0, 'v' }, + {NULL, 0,0,0} +}; + +void print_usage() { + printf("Usage: IntersectTilt --nquery (number of random queries per configuration) --seed (random seed) --verbose (verbosity)\n"); +} + +enum SurfType {cylout=0, cylin, fruout, fruin}; +static const char* surfName[4] = {"Cylinder (helix circle inside)","Cylinder (helix circle around)","Frustrum (helix circle inside)","Frustrum (helix circle around)"}; + +// reference: the first in-bounds crossing found by stepping, restarting past any out-of-bounds crossings +template Intersection refIntersect(HELIX const& helix, SURF const& surf, TimeRange trange, double tol, TimeDir tdir){ + static const double eps(1.0e-4); // ns: restart offset + for(unsigned icross=0; icross < 100; ++icross){ + auto inter = stepIntersect(helix,surf,trange,tol,tdir); + if(!inter.onsurface_ || !inter.inrange_ || inter.inbounds_) return inter; + if(tdir == TimeDir::forwards){ + if(inter.time_+eps >= trange.end()) break; + trange = TimeRange(inter.time_+eps,trange.end()); + } else { + if(inter.time_-eps <= trange.begin()) break; + trange = TimeRange(trange.begin(),inter.time_-eps); + } + } + return Intersection(); +} + +template void compare(HELIX const& helix, SURF const& surf, TimeRange const& trange, double tol, TimeDir tdir, + unsigned& nref, unsigned& nmiss, unsigned& nlate, unsigned& nextra, int verbose) { + static const double dttol(1.0e-5); // ns + auto ref = refIntersect(helix,surf,trange,tol,tdir); + auto inter = intersect(helix,surf,trange,tol,tdir); + if(ref.good()){ + ++nref; + if(!inter.good()){ + ++nmiss; + if(verbose > 1) cout << "Missed crossing: reference " << ref << endl; + } else if((inter.time_-ref.time_)*timeDirSign(tdir) > dttol){ + ++nlate; + if(verbose > 1) cout << "Later crossing: reference " << ref << " intersect " << inter << endl; + } + } else if(inter.good()) { + ++nextra; // the reference stepping can miss grazing crossings; this is not a failure + } +} + +template int testTilt(std::string const& hname, SurfType stype, double maxtilt, unsigned nquery, unsigned seed, int verbose) { + static const double tol(1.0e-5); // mm + std::mt19937 gen(seed); + std::uniform_real_distribution uni(0.0,1.0); + unsigned nref(0), nmiss(0), nlate(0), nextra(0); + for(unsigned iquery=0; iquery < nquery; ++iquery){ + // bnom tilted from z, the surface axis + double tilt = maxtilt*uni(gen); + double tphi = 2*M_PI*uni(gen); + VEC3 bnom(sin(tilt)*cos(tphi),sin(tilt)*sin(tphi),cos(tilt)); + // low-momentum particle so that the helix loops within the query range + double mom = 30.0+120.0*uni(gen); + double cost = -0.9+1.8*uni(gen); + double sint = sqrt(1.0-cost*cost); + double phi = 2*M_PI*uni(gen); + MOM4 mom4(mom*sint*cos(phi),mom*sint*sin(phi),mom*cost,0.511); + VEC4 pos(-400.0+800.0*uni(gen),-400.0+800.0*uni(gen),-500.0+1000.0*uni(gen),0.0); + HELIX helix(pos,mom4,-1,bnom,TimeRange(-50.0,50.0)); + // surface radius near the helix extremes, so that crossings are marginal + double dcent = helix.center(0.0).Rho(); + double rbend = helix.bendRadius(); + double rsurf = (stype == cylin || stype == fruin) ? rbend - dcent : dcent + (uni(gen) < 0.5 ? 1.0 : -1.0)*rbend; + rsurf += -30.0 + 60.0*uni(gen); + double t0 = -10.0+10.0*uni(gen); + TimeRange trange(t0,t0+2.0+18.0*uni(gen)); + auto tdir = uni(gen) < 0.5 ? TimeDir::forwards : TimeDir::backwards; + bool isfru = stype == fruout || stype == fruin; + double dr = -200.0 + 400.0*uni(gen); // frustrum radius change + if(rsurf < 10.0 || (isfru && rsurf-fabs(dr) < 10.0)) continue; + VEC3 zdir(0.0,0.0,1.0), origin(0.0,0.0,0.0); + if(isfru){ + Frustrum fru(zdir,origin,rsurf-dr,rsurf+dr,2000.0); + compare(helix,fru,trange,tol,tdir,nref,nmiss,nlate,nextra,verbose); + } else { + Cylinder cyl(zdir,origin,rsurf,2000.0); + compare(helix,cyl,trange,tol,tdir,nref,nmiss,nlate,nextra,verbose); + } + } + bool fail = nmiss > 0 || nlate > 0; + if(verbose > 0 || fail) + cout << hname << " " << surfName[stype] << " tilt < " << maxtilt << " rad: " << nref << " reference crossings, " + << nmiss << " missed, " << nlate << " later, " << nextra << " extra" << (fail ? " FAILED" : "") << endl; + return fail ? -1 : 0; +} + +int main(int argc, char** argv) { + unsigned nquery(500), seed(238); + int verbose(0); + int opt; + int long_index =0; + while ((opt = getopt_long_only(argc, argv,"", + long_options, &long_index )) != -1) { + switch (opt) { + case 'n' : nquery = atoi(optarg); + break; + case 's' : seed = atoi(optarg); + break; + case 'v' : verbose = atoi(optarg); + break; + default: print_usage(); + exit(EXIT_FAILURE); + } + } + int status(0); + for(auto stype : {cylout, cylin, fruout, fruin}){ + for(double maxtilt : {0.0, 0.05, 0.45}){ + status |= testTilt("LoopHelix",stype,maxtilt,nquery,seed,verbose); + status |= testTilt("CentralHelix",stype,maxtilt,nquery,seed,verbose); + } + } + if(status == 0) + cout << "IntersectTilt test passed" << endl; + else + cout << "IntersectTilt test FAILED" << endl; + return status; +} From 085d1998f9c09f50ecd8641c07b5a7379ff13f82 Mon Sep 17 00:00:00 2001 From: David Nathan Brown Date: Fri, 20 Nov 2026 17:04:18 -0800 Subject: [PATCH 3/7] Address FP issues in unit test --- Tests/Truncate_unit.cc | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/Tests/Truncate_unit.cc b/Tests/Truncate_unit.cc index 942c6441..a4ca22a6 100644 --- a/Tests/Truncate_unit.cc +++ b/Tests/Truncate_unit.cc @@ -262,19 +262,35 @@ namespace { continue; } double cut = 0.5*(lastactive + *next); - size_t neff = trk.effects().size(); check(!trk.truncate(TimeDir::forwards,lastactive),elabel + " refuses a cut at the last active effect"); - check(trk.truncate(TimeDir::forwards,cut),elabel + " truncation before the inactive hits"); - check(ftraj.range().end() == cut,elabel + " trajectory ends at the cut"); - check(trk.effects().size() == neff,elabel + " effects kept"); + // with field correction the extrapolation step can end several domains past the cut: those domains and the DomainWalls + // into them are removed, and every other effect, including the inactive hits, must be kept + checkCut(trk,TimeDir::forwards,cut,elabel + " before the inactive hits"); + size_t nkept(0); for(auto const& eff : trk.effects()){ if(eff->active() || eff->time() <= cut) continue; auto meas = dynamic_cast const*>(eff.get()); + if(meas != nullptr) ++nkept; check(meas != nullptr && meas->hit()->refTrajPtr() && std::isfinite(meas->hit()->referenceTrajectory().momentum(eff->time())), elabel + " an inactive hit beyond the cut keeps a usable reference piece"); } - if(!trk.domains().empty()) check((*trk.domains().crbegin())->end() <= cut && contiguous(trk),elabel + " domains end at the cut"); + check(nkept == size_t(tinact.end()-next),elabel + " inactive hits beyond the cut kept"); check(trk.fitStatus().usable(),elabel + " fit status still usable"); + // Whether the long step above leaves a domain beyond the cut depends on floating-point details, so extrapolate again in + // short steps, which with field correction adds domains beyond the inactive hits, and cut again before the next one + ReachTime xshort{hits.back()->time() + 5.0, 1.0}; + check(trk.extrapolate(TimeDir::forwards,xshort),elabel + " short-step extrapolation past the inactive hits"); + double cut2 = 0.5*(cut + *next); + if(bfcorr){ + size_t nbeyond(0); + for(auto const& dom : trk.domains()) nbeyond += dom->begin() >= cut2; + check(nbeyond > 0,elabel + " domains beyond the second cut"); + } + checkCut(trk,TimeDir::forwards,cut2,elabel + " second cut before the inactive hits"); + nkept = 0; + for(auto const& eff : trk.effects()) + if(!eff->active() && eff->time() > cut2 && dynamic_cast const*>(eff.get()) != nullptr) ++nkept; + check(nkept == size_t(tinact.end()-next),elabel + " inactive hits beyond the second cut kept"); } check(ntested == 3,label + " has 3 usable fits in 10 events"); std::cout << label << ": " << ntested << " fits tested" << std::endl; From 33f4bbdef7b6e819b57180b386ac4f2506557039 Mon Sep 17 00:00:00 2001 From: David Nathan Brown Date: Fri, 20 Nov 2026 18:24:00 -0800 Subject: [PATCH 4/7] Fix longstanding bug in ToyMC which broke the gradient field unit test. Re-enable that test at Mu2e tracker gradient. Fixed by Claude. --- Tests/CentralHelixFit_unit.cc | 13 +++++-------- Tests/LoopHelixFit_unit.cc | 13 +++++-------- Tests/ToyMC.hh | 25 ++++++++++++++++--------- 3 files changed, 26 insertions(+), 25 deletions(-) diff --git a/Tests/CentralHelixFit_unit.cc b/Tests/CentralHelixFit_unit.cc index f1e451e3..acd6c61c 100644 --- a/Tests/CentralHelixFit_unit.cc +++ b/Tests/CentralHelixFit_unit.cc @@ -6,15 +6,12 @@ int main(int argc, char **argv) { cout << "Testing gradient field, correction 2" << endl; std::vector arguments; arguments.push_back(argv[0]); -// arguments.push_back("--Bgrad"); -// arguments.push_back("-0.036"); // mu2e-like field gradient + arguments.push_back("--Bgrad"); + arguments.push_back("-0.036"); // mu2e-like field gradient arguments.push_back("--Schedule"); - arguments.push_back("MCAmbigFixedField.txt"); -// arguments.push_back("seedfit.txt"); -// arguments.push_back("--extend"); -// arguments.push_back("driftextend.txt"); -// arguments.push_back("--ttree"); -// arguments.push_back("1"); + arguments.push_back("seedfit.txt"); + arguments.push_back("--extend"); + arguments.push_back("driftextend.txt"); std::vector myargv; for (const auto& arg : arguments) myargv.push_back((char*)arg.data()); diff --git a/Tests/LoopHelixFit_unit.cc b/Tests/LoopHelixFit_unit.cc index a63acd24..35b1f3c0 100644 --- a/Tests/LoopHelixFit_unit.cc +++ b/Tests/LoopHelixFit_unit.cc @@ -6,15 +6,12 @@ int main(int argc, char **argv) { cout << "Testing gradient field, correction 2" << endl; std::vector arguments; arguments.push_back(argv[0]); -// arguments.push_back("--Bgrad"); -// arguments.push_back("-0.036"); // mu2e-like field gradient + arguments.push_back("--Bgrad"); + arguments.push_back("-0.036"); // mu2e-like field gradient arguments.push_back("--Schedule"); - arguments.push_back("MCAmbigFixedField.txt"); -// arguments.push_back("seedfit.txt"); -// arguments.push_back("--extend"); -// arguments.push_back("driftextend.txt"); -// arguments.push_back("--ttree"); -// arguments.push_back("1"); + arguments.push_back("seedfit.txt"); + arguments.push_back("--extend"); + arguments.push_back("driftextend.txt"); std::vector myargv; for (const auto& arg : arguments) myargv.push_back((char*)arg.data()); diff --git a/Tests/ToyMC.hh b/Tests/ToyMC.hh index c3bab5a4..073527f0 100644 --- a/Tests/ToyMC.hh +++ b/Tests/ToyMC.hh @@ -60,7 +60,7 @@ namespace KKTest { // create a seed by randomizing the parameters void createSeed(KTRAJ& seed,DVEC const& sigmas, double seedsmear); void extendTraj(PTRAJ& ptraj,double htime); - void createTraj(PTRAJ& ptraj); + double createTraj(PTRAJ& ptraj); // create the initial piece; returns the end time of the full simulation range void createScintHit(PTRAJ& ptraj, HITCOL& thits); void simulateParticle(PTRAJ& ptraj,HITCOL& thits, EXINGCOL& dxings, bool addmat=true); double createStrawMaterial(PTRAJ& ptraj, EXING* sxing); @@ -133,15 +133,18 @@ namespace KKTest { template void ToyMC::simulateParticle(PTRAJ& ptraj,HITCOL& thits, EXINGCOL& dxings, bool addmat) { // create the seed first - createTraj(ptraj); + // the initial piece only covers the range where the field is within tolerance (the full range in a uniform field); + // the hits must span the full simulation range, extending the trajectory through the field as they are generated + double simend = createTraj(ptraj); + TimeRange simrange(ptraj.range().begin(),simend); double mom = ptraj.momentum(0.0); // divide time range double dt(0.0); - if(nhits_ > 0) dt = (ptraj.range().range())/(nhits_); + if(nhits_ > 0) dt = (simrange.range())/(nhits_); VEC3 bsim; // create the hits (and associated materials) for(size_t ihit=0; ihit double ToyMC::createStrawMaterial(PTRAJ& ptraj, EXING* sxing) { @@ -195,9 +198,12 @@ namespace KKTest { endmom.SetCoordinates(endmom.Px()+dmvec.X(), endmom.Py()+dmvec.Y(), endmom.Pz()+dmvec.Z(),endmom.M()); // generate a new piece with this momentumand append VEC3 bnom = bfield_.fieldVect(endpos.Vect()); - KTRAJ newend(endpos,endmom,endpiece.charge(),bnom,TimeRange(tstraw,ptraj.range().end())); + // in a non-uniform field the crossing can be at or past the end of the trajectory simulated so far: if so, cover one step within the field tolerance + double tend = ptraj.range().end(); + if(tend <= tstraw) tend = tstraw + bfield_.rangeInTolerance(endpiece,tstraw,tol_); + KTRAJ newend(endpos,endmom,endpiece.charge(),bnom,TimeRange(tstraw,tend)); // newend.print(cout,1); - ptraj.append(newend); + ptraj.append(newend,true); // replace any pieces past the crossing, which were simulated with the pre-crossing momentum return dm; } @@ -268,7 +274,7 @@ namespace KKTest { } } - template void ToyMC::createTraj(PTRAJ& ptraj) { + template double ToyMC::createTraj(PTRAJ& ptraj) { // randomize the position and momentum double tphi = tr_.Uniform(-M_PI,M_PI); double tcost = tr_.Uniform(ctmin_,ctmax_); @@ -281,8 +287,9 @@ namespace KKTest { KTRAJ ktraj(torigin,tmomv,icharge_,bsim,TimeRange(tbeg,tbeg+tmax)); // set initial range double tend = tbeg + bfield_.rangeInTolerance(ktraj,tbeg,tol_); - ktraj.setRange(TimeRange(tbeg,tend)); + ktraj.setRange(TimeRange(tbeg,std::min(tend,tbeg+tmax))); ptraj.append(ktraj); + return tbeg+tmax; } } #endif From 862cc6f76abbb27063eaf7746357555bb060269d Mon Sep 17 00:00:00 2001 From: David Nathan Brown Date: Fri, 20 Nov 2026 23:03:24 -0800 Subject: [PATCH 5/7] Make the covariance projection optional, default false --- Geometry/Intersect.hh | 85 ++++++++++++++++--------- Geometry/IntersectFlag.cc | 1 + Geometry/IntersectFlag.hh | 5 +- Geometry/Intersection.cc | 1 + Geometry/Intersection.hh | 3 +- Geometry/ParticleTrajectoryIntersect.hh | 8 ++- Tests/IntersectionCovariance_unit.cc | 23 +++++-- Tests/ParticleTrajectoryTest.hh | 14 ++++ 8 files changed, 98 insertions(+), 42 deletions(-) diff --git a/Geometry/Intersect.hh b/Geometry/Intersect.hh index c96f0e93..7e250a45 100644 --- a/Geometry/Intersect.hh +++ b/Geometry/Intersect.hh @@ -18,21 +18,32 @@ #include namespace KinKal { // - // fill the local plane UV system and the projection of the trajectory spatial covariance onto it. - // The projection (see KTRAJ::planeCovariance) is along the trajectory direction, so it describes the covariance of where the trajectory crosses the plane. - // If the trajectory is (nearly) parallel to the plane, the projection is singular and the covariance is left 0. + // fill the local plane (tangent to the surface at the intersection) UV system. This is cheap, and is done for every onsurface intersection // - template void fillPlaneCovariance(KTRAJ const& ktraj, Surface const& surf, Intersection& inter) { + inline void fillPlaneFrame(Surface const& surf, Intersection& inter) { auto plane = surf.tangentPlane(inter.pos_); inter.udir_ = plane.uDirection(); inter.vdir_ = plane.vDirection(); + } + // + // fill the projection of the trajectory spatial covariance onto the local plane of an onsurface intersection. + // The projection (see KTRAJ::planeCovariance) is along the trajectory direction, so it describes the covariance of where the trajectory crosses the plane. + // If the trajectory is (nearly) parallel to the plane the projection is singular: the covariance is left 0 and hascov_ false. + // This is optional as the projection is relatively expensive; intersect calls it only on request (pcov argument), and only on the final intersection. + // + template void fillPlaneCovariance(KTRAJ const& ktraj, Intersection& inter) { inter.pcov_ = PMAT(); + inter.hascov_ = false; + if(!inter.onsurface_) return; // the projection is singular if the trajectory lies in the plane - if(fabs(plane.normal().Dot(ktraj.direction(inter.time_))) < 1.0e-10) return; + if(fabs(inter.norm_.Dot(ktraj.direction(inter.time_))) < 1.0e-10) return; + Plane plane(inter.norm_,inter.udir_,inter.pos_); inter.pcov_ = ktraj.planeCovariance(inter.time_,plane); + inter.hascov_ = true; } // - // generic intersection implementation based on stepping across the surface within a given range in the given time direction + // generic intersection implementation based on stepping across the surface within a given range in the given time direction. + // This and the other internal implementations below don't project the covariance; that is done by the intersect functions on request // template Intersection stepIntersect( KTRAJ const& ktraj, SURF const& surf, TimeRange trange, double tol,TimeDir tdir = TimeDir::forwards) { Intersection retval; @@ -110,7 +121,7 @@ namespace KinKal { retval.pdir_ = ktraj.direction(retval.time_); retval.inbounds_ = surf.inBounds(retval.pos_,tol); retval.norm_ = surf.normal(retval.pos_); - fillPlaneCovariance(ktraj,surf,retval); + fillPlaneFrame(surf,retval); } } // check the final time to be in range @@ -306,30 +317,43 @@ namespace KinKal { return retval; } // - // Tie intersect to the explicit helix implementations + // Tie intersect to the explicit helix implementations. + // If pcov is true, the projected spatial covariance is filled in the returned intersection (see fillPlaneCovariance) // - Intersection intersect( LoopHelix const& lhelix, KinKal::Cylinder const& cyl, TimeRange trange ,double tol,TimeDir tdir = TimeDir::forwards) { - return hcIntersect(lhelix,cyl,trange,tol,tdir); + Intersection intersect( LoopHelix const& lhelix, KinKal::Cylinder const& cyl, TimeRange trange ,double tol,TimeDir tdir = TimeDir::forwards, bool pcov=false) { + auto retval = hcIntersect(lhelix,cyl,trange,tol,tdir); + if(pcov)fillPlaneCovariance(lhelix,retval); + return retval; } - Intersection intersect( CentralHelix const& chelix, KinKal::Cylinder const& cyl, TimeRange trange ,double tol,TimeDir tdir = TimeDir::forwards) { - return hcIntersect(chelix,cyl,trange,tol,tdir); + Intersection intersect( CentralHelix const& chelix, KinKal::Cylinder const& cyl, TimeRange trange ,double tol,TimeDir tdir = TimeDir::forwards, bool pcov=false) { + auto retval = hcIntersect(chelix,cyl,trange,tol,tdir); + if(pcov)fillPlaneCovariance(chelix,retval); + return retval; } - Intersection intersect( LoopHelix const& lhelix, KinKal::Plane const& plane, TimeRange trange ,double tol,TimeDir tdir = TimeDir::forwards) { - return hpIntersect(lhelix,plane,trange,tol,tdir); + Intersection intersect( LoopHelix const& lhelix, KinKal::Plane const& plane, TimeRange trange ,double tol,TimeDir tdir = TimeDir::forwards, bool pcov=false) { + auto retval = hpIntersect(lhelix,plane,trange,tol,tdir); + if(pcov)fillPlaneCovariance(lhelix,retval); + return retval; } - Intersection intersect( CentralHelix const& chelix, KinKal::Plane const& plane, TimeRange trange ,double tol,TimeDir tdir = TimeDir::forwards) { - return hpIntersect(chelix,plane,trange,tol,tdir); + Intersection intersect( CentralHelix const& chelix, KinKal::Plane const& plane, TimeRange trange ,double tol,TimeDir tdir = TimeDir::forwards, bool pcov=false) { + auto retval = hpIntersect(chelix,plane,trange,tol,tdir); + if(pcov)fillPlaneCovariance(chelix,retval); + return retval; } - Intersection intersect( LoopHelix const& lhelix, KinKal::Frustrum const& fru, TimeRange trange ,double tol,TimeDir tdir = TimeDir::forwards) { - return hfIntersect(lhelix,fru,trange,tol,tdir); + Intersection intersect( LoopHelix const& lhelix, KinKal::Frustrum const& fru, TimeRange trange ,double tol,TimeDir tdir = TimeDir::forwards, bool pcov=false) { + auto retval = hfIntersect(lhelix,fru,trange,tol,tdir); + if(pcov)fillPlaneCovariance(lhelix,retval); + return retval; } - Intersection intersect( CentralHelix const& chelix, KinKal::Frustrum const& fru, TimeRange trange ,double tol,TimeDir tdir = TimeDir::forwards) { - return hfIntersect(chelix,fru,trange,tol,tdir); + Intersection intersect( CentralHelix const& chelix, KinKal::Frustrum const& fru, TimeRange trange ,double tol,TimeDir tdir = TimeDir::forwards, bool pcov=false) { + auto retval = hfIntersect(chelix,fru,trange,tol,tdir); + if(pcov)fillPlaneCovariance(chelix,retval); + return retval; } // // Line trajectory with generic surfaces; no specialization needed since all surfaces provide a ray intersection implementation // - Intersection intersect(KinKal::KinematicLine const& kkline, KinKal::Surface const& surf, TimeRange trange,double tol,TimeDir tdir = TimeDir::forwards) { + Intersection intersect(KinKal::KinematicLine const& kkline, KinKal::Surface const& surf, TimeRange trange,double tol,TimeDir tdir = TimeDir::forwards, bool pcov=false) { Intersection retval; auto tstart = tdir == TimeDir::forwards ? trange.begin() : trange.end(); auto pos = kkline.position3(tstart); @@ -344,7 +368,8 @@ namespace KinKal { retval.norm_ = surf.normal(retval.pos_); retval.time_ = tstart + dist*timeDirSign(tdir)/kkline.speed(tstart); retval.pdir_ = kkline.direction(retval.time_); - fillPlaneCovariance(kkline,surf,retval); + fillPlaneFrame(surf,retval); + if(pcov)fillPlaneCovariance(kkline,retval); } // check the final time to be in range; retval.inrange_ = trange.inRange(retval.time_); @@ -352,25 +377,25 @@ namespace KinKal { } // generic surface intersection cast down till we find something that works. This will only be used for helices, as KinematicLine // is already complete - template Intersection hsIntersect(KTRAJ const& ktraj, Surface const& surf,TimeRange trange, double tol,TimeDir tdir = TimeDir::forwards) { + template Intersection hsIntersect(KTRAJ const& ktraj, Surface const& surf,TimeRange trange, double tol,TimeDir tdir = TimeDir::forwards, bool pcov=false) { // use pointers to cast to avoid avoid a throw const Surface* surfp = &surf; // go through the possibilities: I don't know of anything more elegant auto plane = dynamic_cast(surfp); - if(plane)return intersect(ktraj,*plane,trange,tol,tdir); + if(plane)return intersect(ktraj,*plane,trange,tol,tdir,pcov); auto cyl = dynamic_cast(surfp); - if(cyl)return intersect(ktraj,*cyl,trange,tol,tdir); + if(cyl)return intersect(ktraj,*cyl,trange,tol,tdir,pcov); auto fru = dynamic_cast(surfp); - if(fru)return intersect(ktraj,*fru,trange,tol,tdir); + if(fru)return intersect(ktraj,*fru,trange,tol,tdir,pcov); // unknown surface subclass; return failure return Intersection(); } // now provide the explicit generic interface - Intersection intersect( LoopHelix const& ploophelix, KinKal::Surface const& surf, TimeRange trange ,double tol,TimeDir tdir = TimeDir::forwards) { - return hsIntersect(ploophelix,surf,trange,tol,tdir); + Intersection intersect( LoopHelix const& ploophelix, KinKal::Surface const& surf, TimeRange trange ,double tol,TimeDir tdir = TimeDir::forwards, bool pcov=false) { + return hsIntersect(ploophelix,surf,trange,tol,tdir,pcov); } - Intersection intersect( CentralHelix const& pcentralhelix, KinKal::Surface const& surf, TimeRange trange ,double tol,TimeDir tdir = TimeDir::forwards) { - return hsIntersect(pcentralhelix,surf,trange,tol,tdir); + Intersection intersect( CentralHelix const& pcentralhelix, KinKal::Surface const& surf, TimeRange trange ,double tol,TimeDir tdir = TimeDir::forwards, bool pcov=false) { + return hsIntersect(pcentralhelix,surf,trange,tol,tdir,pcov); } } diff --git a/Geometry/IntersectFlag.cc b/Geometry/IntersectFlag.cc index 1e5dcff7..fe88c5c0 100644 --- a/Geometry/IntersectFlag.cc +++ b/Geometry/IntersectFlag.cc @@ -8,6 +8,7 @@ std::ostream& operator <<(std::ostream& ost, KinKal::IntersectFlag const& iflag) ost << "On surface "; if(iflag.inbounds_)ost << " in bounds "; if(iflag.inrange_)ost << " in range "; + if(iflag.hascov_)ost << " with covariance "; }else { ost << "No Intersection"; } diff --git a/Geometry/IntersectFlag.hh b/Geometry/IntersectFlag.hh index 2339dd1d..50c0aa73 100644 --- a/Geometry/IntersectFlag.hh +++ b/Geometry/IntersectFlag.hh @@ -13,8 +13,9 @@ namespace KinKal { bool onsurface_ = false; // intersection is on the surface bool inbounds_ = false; // intersection is inside the surface boundaries bool inrange_ = false; // intersection is inside the time range - bool operator ==(IntersectFlag const& other) const { return other.onsurface_ == onsurface_ && other.inbounds_ == inbounds_ && other.inrange_ == inrange_;} - bool operator !=(IntersectFlag const& other) const { return other.onsurface_ != onsurface_ || other.inbounds_ != inbounds_ || other.inrange_ != inrange_;} + bool hascov_ = false; // the projected spatial covariance (Intersection::pcov_) is filled. This is optional, and independent of good() + bool operator ==(IntersectFlag const& other) const { return other.onsurface_ == onsurface_ && other.inbounds_ == inbounds_ && other.inrange_ == inrange_ && other.hascov_ == hascov_;} + bool operator !=(IntersectFlag const& other) const { return other.onsurface_ != onsurface_ || other.inbounds_ != inbounds_ || other.inrange_ != inrange_ || other.hascov_ != hascov_;} bool good() const { return onsurface_ && inbounds_ && inrange_; } friend std::ostream& operator <<(std::ostream& ost, KinKal::IntersectFlag const& iflag); }; diff --git a/Geometry/Intersection.cc b/Geometry/Intersection.cc index af164138..df0bc696 100644 --- a/Geometry/Intersection.cc +++ b/Geometry/Intersection.cc @@ -8,6 +8,7 @@ namespace KinKal { ost << "Intersection on surface "; if(inter.inbounds_) ost << " in bounds "; if(inter.inrange_) ost << " in time range "; + if(inter.hascov_) ost << " with covariance "; } else { ost << "No Intersection"; } diff --git a/Geometry/Intersection.hh b/Geometry/Intersection.hh index 9f5744ee..5f75ae3a 100644 --- a/Geometry/Intersection.hh +++ b/Geometry/Intersection.hh @@ -22,7 +22,8 @@ namespace KinKal { VEC3 udir_; // local plane U direction VEC3 vdir_; // local plane V direction // projected spatial covariance of the trajectory at the intersection onto the local plane, in UV coordinates. - // This is filled for all onsurface intersections (in bounds or not), as long as the trajectory isn't parallel to the plane + // This is only computed on request (the pcov argument of intersect), and is then filled for onsurface intersections (in bounds or not) + // as long as the trajectory isn't parallel to the plane. hascov_ records if it was filled; otherwise it is 0. PMAT pcov_; Ray ray() const { return Ray(pdir_,pos_); } // linear particle trajectory at intersection friend std::ostream& operator << (std::ostream& ost, KinKal::Intersection const& inter); diff --git a/Geometry/ParticleTrajectoryIntersect.hh b/Geometry/ParticleTrajectoryIntersect.hh index 63fd4590..ffc12738 100644 --- a/Geometry/ParticleTrajectoryIntersect.hh +++ b/Geometry/ParticleTrajectoryIntersect.hh @@ -8,15 +8,16 @@ #include "KinKal/Geometry/Intersection.hh" #include "KinKal/Geometry/Intersect.hh" namespace KinKal { - // find intersection by stepping over pieces. This works when the pieces have small curvature - template Intersection intersect(ParticleTrajectory const& ptraj, SURF const& surf, TimeRange trange, double tol,TimeDir tdir = TimeDir::forwards) { + // find intersection by stepping over pieces. This works when the pieces have small curvature. + // If pcov is true the projected spatial covariance is filled, using the piece containing the final intersection only + template Intersection intersect(ParticleTrajectory const& ptraj, SURF const& surf, TimeRange trange, double tol,TimeDir tdir = TimeDir::forwards, bool pcov=false) { Intersection retval; double tstart = (tdir == TimeDir::forwards) ? trange.begin() : trange.end(); double tend = (tdir == TimeDir::forwards) ? trange.end() : trange.begin(); size_t istart = ptraj.nearestIndex(tstart); size_t iend = ptraj.nearestIndex(tend); if(istart == iend){ - retval = intersect(ptraj.piece(istart),surf,trange,tol,tdir); + retval = intersect(ptraj.piece(istart),surf,trange,tol,tdir,pcov); } else { int istep = (tdir == TimeDir::forwards) ? 1 : -1; do { @@ -46,6 +47,7 @@ namespace KinKal { auto tinter = intersect(*ttraj,surf,srange,tol,tdir); if(tinter.good()){ retval = tinter; + if(pcov)fillPlaneCovariance(*ttraj,retval); break; } } diff --git a/Tests/IntersectionCovariance_unit.cc b/Tests/IntersectionCovariance_unit.cc index 2876f523..16d69477 100644 --- a/Tests/IntersectionCovariance_unit.cc +++ b/Tests/IntersectionCovariance_unit.cc @@ -2,8 +2,8 @@ // Test the projected spatial covariance of a trajectory onto the local plane at an intersection (Intersection::pcov_) // by comparing it with a toy MC: the trajectory parameters are randomized according to their covariance, the // intersection is recomputed, and the spread of the intersection points in the local plane UV system is measured. -// Also tests consistency of pcov_ with KTRAJ::planeCovariance, and that the covariance is filled for -// intersections that are on the surface but out of bounds. +// Also tests consistency of pcov_ with KTRAJ::planeCovariance, that the covariance is filled for +// intersections that are on the surface but out of bounds, and that it is only filled on request. // original author: David Brown (LBNL) 2026 // #include "KinKal/Geometry/Intersection.hh" @@ -41,18 +41,29 @@ template void setCovariance(KTRAJ& ktraj, std::array con } } -// INTERF is a callable (KTRAJ const&, SURF const&, TimeRange const&) -> Intersection +// INTERF is a callable (KTRAJ const&, SURF const&, TimeRange const&, bool pcov) -> Intersection template int testCovariance(std::string const& name, KTRAJ const& ktraj, SURF const& surf, TimeRange const& trange, INTERF interf, bool expectinbounds, unsigned ntoy, unsigned seed, int verbose) { static const double vartol(0.05); // relative tolerance on toy variance (statistical precision ~1% for 20K toys) static const double rhotol(0.03); // absolute tolerance on the toy correlation coefficient static const double ctol(1.0e-9); // relative tolerance on consistency checks - auto inter = interf(ktraj,surf,trange); + auto inter = interf(ktraj,surf,trange,true); if(verbose > 0) cout << name << " " << inter << endl; if(!inter.onsurface_){ cout << name << ": intersection not on surface" << endl; return -1; } + if(!inter.hascov_){ + cout << name << ": plane covariance not filled" << endl; + return -1; + } + // by default the covariance is not projected; the intersection must otherwise be identical + auto nocov = interf(ktraj,surf,trange,false); + if(nocov.hascov_ || nocov.pcov_ != PMAT() || nocov.onsurface_ != inter.onsurface_ || nocov.inbounds_ != inter.inbounds_ || + nocov.inrange_ != inter.inrange_ || nocov.time_ != inter.time_ || nocov.udir_ != inter.udir_ || nocov.vdir_ != inter.vdir_){ + cout << name << ": default intersection inconsistent: " << nocov << " vs " << inter << endl; + return -1; + } if(inter.inbounds_ != expectinbounds){ cout << name << ": unexpected inbounds state " << inter.inbounds_ << endl; return -1; @@ -94,7 +105,7 @@ template int testCovariance(std::string for(size_t ipar=0;ipar < NParams(); ++ipar) pars.parameters()[ipar] += gauss(gen)*sqrt(ktraj.params().covariance()(ipar,ipar)); KTRAJ toytraj(pars,ktraj); - auto toyinter = interf(toytraj,surf,toyrange); + auto toyinter = interf(toytraj,surf,toyrange,false); // only the position is needed if(!toyinter.onsurface_) continue; auto dpos = toyinter.pos_ - inter.pos_; double du = dpos.Dot(inter.udir_); @@ -162,7 +173,7 @@ int main(int argc, char** argv) { KinematicLine kline(pos,mom,-1,bnom,trange); setCovariance(kline,{0.1,0.1,0.0005,0.0005,0.005,0.05}); - auto inter = [&](auto const& ktraj, auto const& surf, TimeRange const& range) { return intersect(ktraj,surf,range,tol); }; + auto inter = [&](auto const& ktraj, auto const& surf, TimeRange const& range, bool pcov) { return intersect(ktraj,surf,range,tol,TimeDir::forwards,pcov); }; int status(0); status |= testCovariance("LoopHelix Plane",lhelix,plane,trange,inter,true,ntoy,seed,verbose); diff --git a/Tests/ParticleTrajectoryTest.hh b/Tests/ParticleTrajectoryTest.hh index 85d89567..64a78ca2 100644 --- a/Tests/ParticleTrajectoryTest.hh +++ b/Tests/ParticleTrajectoryTest.hh @@ -271,6 +271,20 @@ int ParticleTrajectoryTest(int argc, char **argv) { KinKal::Surface const& csurf = static_cast(cyl); auto kc2_inter = intersect(ptraj,csurf, ptraj.range(), 1.0e-8); std::cout << "KinematicLine Surface (Cylinder) " << kc2_inter << std::endl; + // the plane covariance is only projected on request, using the piece at the final intersection + if(kc_inter.hascov_ || kc2_inter.hascov_){ + std::cout << "Plane covariance filled without request" << std::endl; + return -2; + } + if(kc_inter.good()){ + auto kc3_inter = intersect(ptraj,csurf, ptraj.range(), 1.0e-8,TimeDir::forwards,true); + Plane tplane(kc3_inter.norm_,kc3_inter.udir_,kc3_inter.pos_); + auto tcov = ptraj.nearestPiece(kc3_inter.time_).planeCovariance(kc3_inter.time_,tplane); + if(!kc3_inter.hascov_ || kc3_inter.time_ != kc_inter.time_ || kc3_inter.pcov_ != tcov){ + std::cout << "Plane covariance inconsistent " << kc3_inter << " " << kc3_inter.pcov_ << " " << tcov << std::endl; + return -2; + } + } // return 0; From d426035c5380ed16e9f7e5202c1e9862e4fe92b5 Mon Sep 17 00:00:00 2001 From: David Nathan Brown Date: Sat, 21 Nov 2026 10:44:06 -0800 Subject: [PATCH 6/7] Add a computation of the fraction of the covariance lying inside the surface bounds to the Intersection payload. Allow out-of-bounds cylinder and frustrum intersections. Ensure hand-built intersections produce the same plane intersections. Code by Claude. --- Geometry/Intersect.hh | 237 ++++++++++++++--------- Geometry/IntersectFlag.hh | 1 + Geometry/Intersection.hh | 4 +- Geometry/ParticleTrajectoryIntersect.hh | 2 +- Tests/CMakeLists.txt | 1 + Tests/IntersectionBounds_unit.cc | 243 ++++++++++++++++++++++++ 6 files changed, 398 insertions(+), 90 deletions(-) create mode 100644 Tests/IntersectionBounds_unit.cc diff --git a/Geometry/Intersect.hh b/Geometry/Intersect.hh index 7e250a45..544f3b50 100644 --- a/Geometry/Intersect.hh +++ b/Geometry/Intersect.hh @@ -16,6 +16,8 @@ #include "KinKal/General/TimeDir.hh" #include "Math/VectorUtil.h" #include +#include +#include namespace KinKal { // // fill the local plane (tangent to the surface at the intersection) UV system. This is cheap, and is done for every onsurface intersection @@ -26,20 +28,111 @@ namespace KinKal { inter.vdir_ = plane.vDirection(); } // + // Is the point at local plane coordinates (u,v) of an intersection within the surface boundaries? The point is projected onto the + // surface along the normal at the intersection; points that don't project onto the surface are out of bounds. + // + inline bool planePointInBounds(Surface const& surf, Intersection const& inter, double u, double v, double tol) { + VEC3 ppos = inter.pos_ + u*inter.udir_ + v*inter.vdir_; + double dist(0.0); + auto sinter = surf.intersect(Ray(inter.norm_,ppos),dist,false,tol); // closest projection in either direction + return sinter.onsurface_ && sinter.inbounds_; + } + // + // Fraction of the 2D Gaussian with covariance pcov_ centered on the intersection that lies within the surface boundaries. + // The integral is done in whitened coordinates (where the Gaussian is circular) as an angular integral over rays from the center. + // Along each ray the boundary crossings are found by stepping (in units of sigma) out to rmax and refining by bisection; the Gaussian + // mass in each inside segment [r1,r2] is exp(-r1^2/2)-exp(-r2^2/2). A ray that is inside at rmax is taken to be inside to infinity. + // The angular integral uses the trapezoid rule on nsector equal sectors. Sectors whose end rays differ by more than angtol (ie that + // contain a boundary corner, or where a boundary passes close to the center) are bisected, up to maxdepth times. + // This handles any number of edges (corners, holes) generically. Boundary features narrower than rstep sigma, or angular features + // narrower than a sector (2pi/nsector) that don't change the end rays, can be missed. + // + inline double boundsFraction(Surface const& surf, Intersection const& inter, double tol, + unsigned nsector=32, unsigned maxdepth=4, double angtol=0.02, double rmax=5.0, double rstep=0.25, double rtol=1.0e-3) { + auto const& cov = inter.pcov_; + // Cholesky decomposition cov = L L^T + double l00 = cov(0,0) > 0.0 ? sqrt(cov(0,0)) : 0.0; + double l10 = l00 > 0.0 ? cov(0,1)/l00 : 0.0; + double l11sq = cov(1,1) - l10*l10; + // degenerate covariance: the answer is the bounds state of the center + if(l00 <= 0.0 || l11sq <= 0.0) return inter.inbounds_ ? 1.0 : 0.0; + double l11 = sqrt(l11sq); + auto mass = [](double r) { return exp(-0.5*r*r); }; // Gaussian mass outside whitened radius r + bool cinside = planePointInBounds(surf,inter,0.0,0.0,tol); + // Gaussian mass inside the boundaries along the ray at whitened angle phi, normalized to 1 for a fully-inside ray + auto rayfrac = [&](double phi) { + double du = l00*cos(phi); // ray direction in UV for unit whitened radius + double dv = l10*cos(phi) + l11*sin(phi); + auto inb = [&](double r) { return planePointInBounds(surf,inter,r*du,r*dv,tol); }; + bool inside = cinside; + double rin = 0.0; // start of the current inside segment + double r0 = 0.0; + double retval(0.0); + while(r0 < rmax){ + double r1 = std::min(r0 + rstep,rmax); + bool in1 = inb(r1); + if(in1 != inside){ + // bisect to find the crossing + double ra(r0), rb(r1); + while(rb - ra > rtol){ + double rm = 0.5*(ra+rb); + if(inb(rm) == inside) ra = rm; else rb = rm; + } + double rc = 0.5*(ra+rb); + if(inside) retval += mass(rin) - mass(rc); // leaving + else rin = rc; // entering + inside = in1; + } + r0 = r1; + } + if(inside) retval += mass(rin); // inside to infinity + return retval; + }; + // adaptive trapezoid integration over a sector, given the ray fractions at its ends + std::function sector = [&](double phi0, double phi1, double f0, double f1, unsigned depth) { + if(depth < maxdepth && fabs(f0-f1) > angtol){ + double phim = 0.5*(phi0+phi1); + double fm = rayfrac(phim); + return sector(phi0,phim,f0,fm,depth+1) + sector(phim,phi1,fm,f1,depth+1); + } + return 0.5*(f0+f1)*(phi1-phi0); + }; + double frac(0.0); + double dsec = 2.0*M_PI/nsector; + double f0 = rayfrac(0.0); + double fprev = f0; + for(unsigned isec=0; isec < nsector; ++isec){ + double phi0 = isec*dsec; + double fnext = isec+1 < nsector ? rayfrac(phi0+dsec) : f0; // periodic + frac += sector(phi0,phi0+dsec,fprev,fnext,0); + fprev = fnext; + } + return std::clamp(frac/(2.0*M_PI),0.0,1.0); + } + // // fill the projection of the trajectory spatial covariance onto the local plane of an onsurface intersection. // The projection (see KTRAJ::planeCovariance) is along the trajectory direction, so it describes the covariance of where the trajectory crosses the plane. // If the trajectory is (nearly) parallel to the plane the projection is singular: the covariance is left 0 and hascov_ false. // This is optional as the projection is relatively expensive; intersect calls it only on request (pcov argument), and only on the final intersection. + // Only the position, time, and onsurface_ (and inbounds_, used if the covariance is degenerate) of the intersection are used as input: + // the local frame (norm_, udir_, vdir_) is (re)filled here from the surface tangent plane at the intersection position, so this can + // also be called on intersections constructed outside of the intersect functions. // - template void fillPlaneCovariance(KTRAJ const& ktraj, Intersection& inter) { + template void fillPlaneCovariance(KTRAJ const& ktraj, Surface const& surf, Intersection& inter, double tol) { inter.pcov_ = PMAT(); inter.hascov_ = false; + inter.inbfrac_ = 0.0; if(!inter.onsurface_) return; + auto tplane = surf.tangentPlane(inter.pos_); + inter.norm_ = tplane.normal(); + inter.udir_ = tplane.uDirection(); + inter.vdir_ = tplane.vDirection(); // the projection is singular if the trajectory lies in the plane if(fabs(inter.norm_.Dot(ktraj.direction(inter.time_))) < 1.0e-10) return; Plane plane(inter.norm_,inter.udir_,inter.pos_); inter.pcov_ = ktraj.planeCovariance(inter.time_,plane); inter.hascov_ = true; + inter.inbfrac_ = boundsFraction(surf,inter,tol); } // // generic intersection implementation based on stepping across the surface within a given range in the given time direction. @@ -174,50 +267,54 @@ namespace KinKal { return std::max(dbeg - drad(rfbeg), dend - drad(rfend)) > -tol - slack; } - template < class HELIX> Intersection hcIntersect( HELIX const& helix, KinKal::Cylinder const& cyl, TimeRange trange ,double tol,TimeDir tdir = TimeDir::forwards) { + // + // Helix and a bounded surface of revolution (cylinder or frustrum) whose axis is roughly co-linear with the helix axis. + // The search is first restricted to the time range where the helix is within the surface axial bounds, using the end disk crossings. + // If no in-bounds crossing is found there, the first crossing over the full range is returned, flagged as out-of-bounds. + // + template Intersection hbIntersect( HELIX const& helix, SURF const& surf, TimeRange trange ,double tol,TimeDir tdir) { Intersection retval; - // test if the range is lnger than the radius. If so, make an axial approximation - double rbend = fabs(helix.bendRadius()); - // compare directions and divide into cases - double ddot = fabs(helix.bnom().Unit().Dot(cyl.axis())); - if(rbend < trange.range()*helix.transverseSpeed() && ddot > 0.9) { // mostly co-linear - // the helix and cylinder are roughly co-linear, and the helix loops within this range - // first try to limit the range using disk-axis intersections - // see if the range is in bounds - auto binb = cyl.inBounds(helix.position3(trange.begin()),tol); - auto einb = cyl.inBounds(helix.position3(trange.end()),tol); - if(binb && einb) { - // both in bounds: use this range - if(canIntersect(helix,cyl,trange,tol)){ - retval = stepIntersect(helix,cyl,trange,tol,tdir); - } - } else { - // create a list of times to select the most restrictive range - std::vectortimes; - if(binb)times.push_back(trange.begin()); - if(einb)times.push_back(trange.end()); - // find the intersections with the front and back disks. Use those to refine the range - // note we don't know the orientation of the trajectory WRT the axis so we have to try both - auto frontdisk = cyl.frontDisk(); - auto backdisk = cyl.backDisk(); - auto frontinter = hpIntersect(helix,frontdisk,trange,tol,tdir); - auto backinter = hpIntersect(helix,backdisk,trange,tol,tdir); - if(trange.inRange(frontinter.time_))times.push_back(frontinter.time_); - if(trange.inRange(backinter.time_))times.push_back(backinter.time_); - if(times.size() >=2){ - TimeRange srange(*std::min_element(times.begin(),times.end()),*std::max_element(times.begin(),times.end())); - // intersection is possible: step within the restricted range - if(canIntersect(helix,cyl,srange,tol)){ - retval = stepIntersect(helix,cyl,srange,tol,tdir); - if(retval.onsurface_) retval.inrange_ = trange.inRange(retval.time_); // report against the caller's range, not the restricted one - } + // canIntersect is monotonic in the range: if it fails for the full range it fails for any sub-range + if(!canIntersect(helix,surf,trange,tol)) return retval; + auto binb = surf.inBounds(helix.position3(trange.begin()),tol); + auto einb = surf.inBounds(helix.position3(trange.end()),tol); + // both ends in bounds: use the full range + if(binb && einb) return stepIntersect(helix,surf,trange,tol,tdir); + // create a list of times to select the most restrictive range + std::vectortimes; + if(binb)times.push_back(trange.begin()); + if(einb)times.push_back(trange.end()); + // find the intersections with the front and back disks. Use those to refine the range + // note we don't know the orientation of the trajectory WRT the axis so we have to try both + auto frontinter = hpIntersect(helix,surf.frontDisk(),trange,tol,tdir); + auto backinter = hpIntersect(helix,surf.backDisk(),trange,tol,tdir); + if(trange.inRange(frontinter.time_))times.push_back(frontinter.time_); + if(trange.inRange(backinter.time_))times.push_back(backinter.time_); + if(times.size() >=2){ + TimeRange srange(*std::min_element(times.begin(),times.end()),*std::max_element(times.begin(),times.end())); + // intersection is possible: step within the restricted range + if(canIntersect(helix,surf,srange,tol)){ + retval = stepIntersect(helix,surf,srange,tol,tdir); + if(retval.onsurface_ && retval.inbounds_){ + retval.inrange_ = trange.inRange(retval.time_); // report against the caller's range, not the restricted one + return retval; } } - } else { - // intermediate case: use step intersection - retval = stepIntersect(helix,cyl,trange,tol,tdir); } - return retval; + // no in-bounds crossing: return the first crossing in the full range, which will be out-of-bounds (or none) + return stepIntersect(helix,surf,trange,tol,tdir); + } + // + // Helix and cylinder + // + template < class HELIX> Intersection hcIntersect( HELIX const& helix, KinKal::Cylinder const& cyl, TimeRange trange ,double tol,TimeDir tdir = TimeDir::forwards) { + double rbend = fabs(helix.bendRadius()); + double ddot = fabs(helix.bnom().Unit().Dot(cyl.axis())); + // the helix and cylinder are roughly co-linear, and the helix loops within this range + if(rbend < trange.range()*helix.transverseSpeed() && ddot > 0.9) + return hbIntersect(helix,cyl,trange,tol,tdir); + // intermediate case: use step intersection + return stepIntersect(helix,cyl,trange,tol,tdir); } // // Helix and planar surfaces @@ -273,48 +370,12 @@ namespace KinKal { // Helix and frustrum // template < class HELIX> Intersection hfIntersect( HELIX const& helix, KinKal::Frustrum const& fru, TimeRange trange ,double tol,TimeDir tdir = TimeDir::forwards) { - Intersection retval; double ddot = fabs(helix.bnom().Unit().Dot(fru.axis())); - if (ddot > 0.9) { // I need a more physical co-linear test TODO - // the helix and frustrum are roughly co-linear. - // see if the range is in bounds - auto binb = fru.inBounds(helix.position3(trange.begin()),tol); - auto einb = fru.inBounds(helix.position3(trange.end()),tol); - if(binb && einb) { - // both in bounds: use this range - if(canIntersect(helix,fru,trange,tol)) { - retval = stepIntersect(helix,fru,trange,tol,tdir); - } - } else { - // create a list of times to select the most restrictive range - std::vectortimes; - if(binb)times.push_back(trange.begin()); - if(einb)times.push_back(trange.end()); - // find the intersections with the front and back disks. Use those to refine the range - // note we don't know the orientation of the trajectory WRT the axis so we have to try both - auto frontdisk = fru.frontDisk(); - auto backdisk = fru.backDisk(); - auto frontinter = hpIntersect(helix,frontdisk,trange,tol); - auto backinter = hpIntersect(helix,backdisk,trange,tol); - if(trange.inRange(frontinter.time_))times.push_back(frontinter.time_); - if(trange.inRange(backinter.time_))times.push_back(backinter.time_); - if(times.size() >=2){ - TimeRange srange(*std::min_element(times.begin(),times.end()),*std::max_element(times.begin(),times.end())); - // intersection is possible: step within the restricted range - if(canIntersect(helix,fru,srange,tol) ) { - retval = stepIntersect(helix,fru,srange,tol,tdir); - if(retval.onsurface_) retval.inrange_ = trange.inRange(retval.time_); // report against the caller's range, not the restricted one - } - } - } - // } else if (ddot < 0.1) { - // // the helix and frustrum are mostly orthogonal, use POCA to the axis to find an initial estimate, then do a linear search - // // TODO. Construct a KinematicLine object from the helix axis, and a GeometricLine from the frustrum, then invoke POCA. - } else { + // the helix and frustrum are roughly co-linear. I need a more physical co-linear test TODO + // For the mostly orthogonal case (ddot < 0.1), POCA of the helix axis to the frustrum axis could provide an initial estimate TODO + if (ddot > 0.9) return hbIntersect(helix,fru,trange,tol,tdir); // intermediate case: use step intersection - retval = stepIntersect(helix,fru,trange,tol,tdir); - } - return retval; + return stepIntersect(helix,fru,trange,tol,tdir); } // // Tie intersect to the explicit helix implementations. @@ -322,32 +383,32 @@ namespace KinKal { // Intersection intersect( LoopHelix const& lhelix, KinKal::Cylinder const& cyl, TimeRange trange ,double tol,TimeDir tdir = TimeDir::forwards, bool pcov=false) { auto retval = hcIntersect(lhelix,cyl,trange,tol,tdir); - if(pcov)fillPlaneCovariance(lhelix,retval); + if(pcov)fillPlaneCovariance(lhelix,cyl,retval,tol); return retval; } Intersection intersect( CentralHelix const& chelix, KinKal::Cylinder const& cyl, TimeRange trange ,double tol,TimeDir tdir = TimeDir::forwards, bool pcov=false) { auto retval = hcIntersect(chelix,cyl,trange,tol,tdir); - if(pcov)fillPlaneCovariance(chelix,retval); + if(pcov)fillPlaneCovariance(chelix,cyl,retval,tol); return retval; } Intersection intersect( LoopHelix const& lhelix, KinKal::Plane const& plane, TimeRange trange ,double tol,TimeDir tdir = TimeDir::forwards, bool pcov=false) { auto retval = hpIntersect(lhelix,plane,trange,tol,tdir); - if(pcov)fillPlaneCovariance(lhelix,retval); + if(pcov)fillPlaneCovariance(lhelix,plane,retval,tol); return retval; } Intersection intersect( CentralHelix const& chelix, KinKal::Plane const& plane, TimeRange trange ,double tol,TimeDir tdir = TimeDir::forwards, bool pcov=false) { auto retval = hpIntersect(chelix,plane,trange,tol,tdir); - if(pcov)fillPlaneCovariance(chelix,retval); + if(pcov)fillPlaneCovariance(chelix,plane,retval,tol); return retval; } Intersection intersect( LoopHelix const& lhelix, KinKal::Frustrum const& fru, TimeRange trange ,double tol,TimeDir tdir = TimeDir::forwards, bool pcov=false) { auto retval = hfIntersect(lhelix,fru,trange,tol,tdir); - if(pcov)fillPlaneCovariance(lhelix,retval); + if(pcov)fillPlaneCovariance(lhelix,fru,retval,tol); return retval; } Intersection intersect( CentralHelix const& chelix, KinKal::Frustrum const& fru, TimeRange trange ,double tol,TimeDir tdir = TimeDir::forwards, bool pcov=false) { auto retval = hfIntersect(chelix,fru,trange,tol,tdir); - if(pcov)fillPlaneCovariance(chelix,retval); + if(pcov)fillPlaneCovariance(chelix,fru,retval,tol); return retval; } // @@ -369,7 +430,7 @@ namespace KinKal { retval.time_ = tstart + dist*timeDirSign(tdir)/kkline.speed(tstart); retval.pdir_ = kkline.direction(retval.time_); fillPlaneFrame(surf,retval); - if(pcov)fillPlaneCovariance(kkline,retval); + if(pcov)fillPlaneCovariance(kkline,surf,retval,tol); } // check the final time to be in range; retval.inrange_ = trange.inRange(retval.time_); diff --git a/Geometry/IntersectFlag.hh b/Geometry/IntersectFlag.hh index 50c0aa73..c795fec6 100644 --- a/Geometry/IntersectFlag.hh +++ b/Geometry/IntersectFlag.hh @@ -14,6 +14,7 @@ namespace KinKal { bool inbounds_ = false; // intersection is inside the surface boundaries bool inrange_ = false; // intersection is inside the time range bool hascov_ = false; // the projected spatial covariance (Intersection::pcov_) is filled. This is optional, and independent of good() + bool gap_ = false; // intersection is in a piecewise-trajectory gap bool operator ==(IntersectFlag const& other) const { return other.onsurface_ == onsurface_ && other.inbounds_ == inbounds_ && other.inrange_ == inrange_ && other.hascov_ == hascov_;} bool operator !=(IntersectFlag const& other) const { return other.onsurface_ != onsurface_ || other.inbounds_ != inbounds_ || other.inrange_ != inrange_ || other.hascov_ != hascov_;} bool good() const { return onsurface_ && inbounds_ && inrange_; } diff --git a/Geometry/Intersection.hh b/Geometry/Intersection.hh index 5f75ae3a..1e9d1b37 100644 --- a/Geometry/Intersection.hh +++ b/Geometry/Intersection.hh @@ -17,7 +17,6 @@ namespace KinKal { VEC3 norm_; // surface normal at intersection VEC3 pdir_; // particle direction at intersection double time_ = 0.0; // time at intersection (from particle) - bool gap_ = false; // intersection is in a piecewise-trajectory gap // local plane (tangent to the surface at the intersection) coordinate system; W = norm_ VEC3 udir_; // local plane U direction VEC3 vdir_; // local plane V direction @@ -25,6 +24,9 @@ namespace KinKal { // This is only computed on request (the pcov argument of intersect), and is then filled for onsurface intersections (in bounds or not) // as long as the trajectory isn't parallel to the plane. hascov_ records if it was filled; otherwise it is 0. PMAT pcov_; + // approximate (~1%) fraction of the 2D Gaussian described by pcov_ that lies within the surface boundaries. For curved surfaces + // the boundaries are projected onto the local plane along the surface normal. Only meaningful if hascov_ is true + double inbfrac_ = 0.0; Ray ray() const { return Ray(pdir_,pos_); } // linear particle trajectory at intersection friend std::ostream& operator << (std::ostream& ost, KinKal::Intersection const& inter); }; diff --git a/Geometry/ParticleTrajectoryIntersect.hh b/Geometry/ParticleTrajectoryIntersect.hh index ffc12738..9b9f774a 100644 --- a/Geometry/ParticleTrajectoryIntersect.hh +++ b/Geometry/ParticleTrajectoryIntersect.hh @@ -47,7 +47,7 @@ namespace KinKal { auto tinter = intersect(*ttraj,surf,srange,tol,tdir); if(tinter.good()){ retval = tinter; - if(pcov)fillPlaneCovariance(*ttraj,retval); + if(pcov)fillPlaneCovariance(*ttraj,surf,retval,tol); break; } } diff --git a/Tests/CMakeLists.txt b/Tests/CMakeLists.txt index 68ac678c..e80a4753 100644 --- a/Tests/CMakeLists.txt +++ b/Tests/CMakeLists.txt @@ -29,6 +29,7 @@ set( TEST_SOURCE_FILES Intersection_unit.cc IntersectReturn_unit.cc IntersectionCovariance_unit.cc + IntersectionBounds_unit.cc IntersectTilt_unit.cc MatEnv_unit.cc Truncate_unit.cc diff --git a/Tests/IntersectionBounds_unit.cc b/Tests/IntersectionBounds_unit.cc new file mode 100644 index 00000000..f7f0002b --- /dev/null +++ b/Tests/IntersectionBounds_unit.cc @@ -0,0 +1,243 @@ +// +// Test Intersection::inbfrac_, the fraction of the projected spatial covariance ellipse inside the surface boundaries. +// The fraction is compared with a toy MC in which the trajectory parameters are randomized according to their covariance, +// the intersection is recomputed, and the fraction of in-bounds intersections is counted. This tests the normal projection +// of curved surface boundaries as well as the integration. Simple configurations are also compared with analytic results. +// original author: David Brown (LBNL) 2026 +// +#include "KinKal/Geometry/Intersection.hh" +#include "KinKal/Geometry/Intersect.hh" +#include "KinKal/Geometry/Plane.hh" +#include "KinKal/Geometry/Rectangle.hh" +#include "KinKal/Geometry/Annulus.hh" +#include "KinKal/Geometry/Disk.hh" +#include "KinKal/Geometry/Cylinder.hh" +#include "KinKal/Geometry/Frustrum.hh" +#include +#include +#include +#include +#include + +using namespace KinKal; +using std::cout; +using std::endl; + +static struct option long_options[] = { + {"ntoy", required_argument, 0, 'n' }, + {"seed", required_argument, 0, 's' }, + {"verbose", required_argument, 0, 'v' }, + {NULL, 0,0,0} +}; + +void print_usage() { + printf("Usage: IntersectionBounds --ntoy (number of toy MC trials) --seed (random seed) --verbose (verbosity)\n"); +} + +template void setCovariance(KTRAJ& ktraj, std::array const& sigmas) { + for(size_t ipar=0;ipar < NParams(); ++ipar) + for(size_t jpar=0;jpar < NParams(); ++jpar) + ktraj.params().covariance()(ipar,jpar) = ipar == jpar ? sigmas[ipar]*sigmas[ipar] : 0.0; +} + +double normcdf(double x) { return 0.5*erfc(-x/sqrt(2.0)); } + +static const double tol(1.0e-6); +static const double fractol(0.01); // the target precision of inbfrac_ +static const double toytol(0.015); // tolerance on the toy MC comparison: target precision plus statistics + +// compare the bounds fraction with the toy MC fraction of in-bounds intersections, and optionally an analytic expectation (if >= 0). +template int testBounds(std::string const& name, KTRAJ const& ktraj, SURF const& surf, + TimeRange const& trange, double expect, unsigned ntoy, unsigned seed, int verbose) { + auto inter = intersect(ktraj,surf,trange,tol,TimeDir::forwards,true); + if(!inter.onsurface_ || !inter.hascov_){ + cout << name << ": no intersection covariance " << inter << endl; + return -1; + } + if(inter.inbfrac_ < 0.0 || inter.inbfrac_ > 1.0){ + cout << name << ": fraction out of range " << inter.inbfrac_ << endl; + return -1; + } + // an intersection constructed outside of intersect (only position, time and flags set) must give the same projection + Intersection hinter; + hinter.pos_ = inter.pos_; + hinter.time_ = inter.time_; + hinter.onsurface_ = inter.onsurface_; + hinter.inbounds_ = inter.inbounds_; + fillPlaneCovariance(ktraj,surf,hinter,tol); + if(!hinter.hascov_ || fabs(hinter.inbfrac_-inter.inbfrac_) > 1.0e-9 || (hinter.norm_-inter.norm_).R() > 1.0e-9 + || (hinter.udir_-inter.udir_).R() > 1.0e-9 || (hinter.vdir_-inter.vdir_).R() > 1.0e-9){ + cout << name << ": hand-built intersection inconsistent " << hinter << endl; + return -1; + } + for(size_t i=0;i<2;++i)for(size_t j=0;j<2;++j) + if(fabs(hinter.pcov_(i,j)-inter.pcov_(i,j)) > 1.0e-9*(inter.pcov_(0,0)+inter.pcov_(1,1))){ + cout << name << ": hand-built intersection covariance inconsistent" << endl; + return -1; + } + // toy MC; restrict the intersection search to a window around the nominal intersection + static const double dt(0.5); // ns + TimeRange toyrange(inter.time_-dt,inter.time_+dt); + std::mt19937 gen(seed); + std::normal_distribution gauss(0.0,1.0); + unsigned nsurf(0), ninb(0); + for(unsigned itoy=0; itoy < ntoy; ++itoy){ + auto pars = ktraj.params(); + for(size_t ipar=0;ipar < NParams(); ++ipar) + pars.parameters()[ipar] += gauss(gen)*sqrt(ktraj.params().covariance()(ipar,ipar)); + KTRAJ toytraj(pars,ktraj); + auto toyinter = intersect(toytraj,surf,toyrange,tol); + if(!toyinter.onsurface_) continue; + ++nsurf; + if(toyinter.inbounds_) ++ninb; + } + double toyfrac = nsurf > 0 ? double(ninb)/nsurf : -1.0; + int retval(0); + if(nsurf < 0.99*ntoy){ + cout << name << ": too many toy intersections failed " << nsurf << " of " << ntoy << endl; + retval = -1; + } + if(fabs(toyfrac-inter.inbfrac_) > toytol){ + cout << name << ": fraction " << inter.inbfrac_ << " disagrees with toy MC " << toyfrac << endl; + retval = -1; + } + if(expect >= 0.0 && fabs(expect-inter.inbfrac_) > fractol){ + cout << name << ": fraction " << inter.inbfrac_ << " disagrees with analytic " << expect << endl; + retval = -1; + } + if(verbose > 0 || retval != 0) + cout << name << " inbounds " << inter.inbounds_ << " fraction " << inter.inbfrac_ << " toy " << toyfrac + << (expect >= 0.0 ? " analytic " + std::to_string(expect) : std::string()) << (retval != 0 ? " FAILED" : "") << endl; + return retval; +} + +template int testTraj(std::string const& tname, KTRAJ const& ktraj, TimeRange const& trange, unsigned ntoy, unsigned seed, int verbose) { + int status(0); + // nominal intersection with an (unbounded) tilted plane defines the local frame and covariance + VEC3 norm = VEC3(0.3,0.2,1.0).Unit(); + VEC3 pudir = norm.Cross(VEC3(0.0,1.0,0.0)).Unit(); + Plane plane(norm,pudir,VEC3(5.0,-3.0,400.0)); + auto inter = intersect(ktraj,plane,trange,tol,TimeDir::forwards,true); + if(!inter.hascov_){ + cout << tname << ": no plane intersection" << endl; + return -1; + } + status |= testBounds(tname+" Plane",ktraj,plane,trange,1.0,ntoy,seed,verbose); + auto const& pos = inter.pos_; + auto const& udir = inter.udir_; + auto const& vdir = inter.vdir_; + double su = sqrt(inter.pcov_(0,0)); + double sv = sqrt(inter.pcov_(1,1)); + double rho = inter.pcov_(0,1)/(su*sv); + if(verbose > 0) cout << tname << " sigma u " << su << " v " << sv << " rho " << rho << endl; + static const double big(1.0e4); + // single edge: the +u edge of a rectangle at distance d from the intersection + for(double dsig : {-1.5, -0.5, 0.0, 0.7, 2.0}){ + double d = dsig*su; + Rectangle rect(norm,udir,pos+(d-big)*udir,big,big); + status |= testBounds(tname+" Rectangle edge at "+std::to_string(dsig)+" sigma",ktraj,rect,trange,normcdf(dsig),ntoy,seed,verbose); + } + // corner: the intersection is at the corner, (u,v) edges at 0. For a bivariate Gaussian the quadrant probability is 1/4 + asin(rho)/2pi + { + Rectangle rect(norm,udir,pos-big*udir-big*vdir,big,big); + status |= testBounds(tname+" Rectangle corner",ktraj,rect,trange,0.25+asin(rho)/(2*M_PI),ntoy,seed,verbose); + } + // corner offset from the intersection, and a narrow strip (2 parallel edges) + { + Rectangle rect(norm,udir,pos+(0.5*su-big)*udir+(-0.8*sv+big)*vdir,big,big); + status |= testBounds(tname+" Rectangle offset corner",ktraj,rect,trange,-1.0,ntoy,seed,verbose); + Rectangle strip(norm,udir,pos+0.3*su*udir,0.6*su,big); + status |= testBounds(tname+" Rectangle strip",ktraj,strip,trange,normcdf(0.9)-normcdf(-0.3),ntoy,seed,verbose); + Rectangle small(norm,udir,pos+0.2*su*udir-0.3*sv*vdir,0.8*su,0.6*sv); + status |= testBounds(tname+" Rectangle small (4 edges)",ktraj,small,trange,-1.0,ntoy,seed,verbose); + } + // intersection outside the boundary + { + Rectangle rect(norm,udir,pos+(-1.0*su-big)*udir,big,big); + status |= testBounds(tname+" Rectangle out of bounds",ktraj,rect,trange,normcdf(-1.0),ntoy,seed,verbose); + } + // disk edge, and an annulus with the intersection in the hole + { + double smax = std::max(su,sv); + Disk disk(norm,udir,pos+3.0*smax*udir,3.0*smax+0.5*su); + status |= testBounds(tname+" Disk",ktraj,disk,trange,-1.0,ntoy,seed,verbose); + Annulus ann(norm,udir,pos+0.5*smax*vdir,1.0*smax,10.0*smax); + status |= testBounds(tname+" Annulus (in hole)",ktraj,ann,trange,-1.0,ntoy,seed,verbose); + } + return status; +} + +// curved surfaces: the trajectory crosses a cylinder or frustrum near its end +template int testCurved(std::string const& tname, KTRAJ const& ktraj, TimeRange const& trange, unsigned ntoy, unsigned seed, int verbose) { + int status(0); + VEC3 zdir(0.0,0.0,1.0); + double rcyl(200.0), hlen(1000.0); + Cylinder cyl0(zdir,VEC3(0.0,0.0,0.0),rcyl,hlen); + auto inter = intersect(ktraj,cyl0,trange,tol,TimeDir::forwards,true); + if(!inter.hascov_){ + cout << tname << ": no cylinder intersection" << endl; + return -1; + } + // axial sigma of the projected covariance; the axial direction lies in the tangent plane + double sz = sqrt(ROOT::Math::Similarity(inter.pcov_,ROOT::Math::SVector(zdir.Dot(inter.udir_),zdir.Dot(inter.vdir_)))); + if(verbose > 0) cout << tname << " cylinder axial sigma " << sz << endl; + // restrict to a window around this crossing, so that the shifted surfaces below don't select a crossing on a different loop + TimeRange crange(inter.time_-0.5,inter.time_+0.5); + for(double dsig : {-1.0, 0.0, 0.5, 1.5}){ + // place the cylinder so its +z end is dsig sigma from the intersection + Cylinder cyl(zdir,VEC3(0.0,0.0,inter.pos_.Z()+dsig*sz-hlen),rcyl,hlen); + status |= testBounds(tname+" Cylinder end at "+std::to_string(dsig)+" sigma",ktraj,cyl,crange,normcdf(dsig),ntoy,seed,verbose); + } + // frustrum through the same point, with its +z end near the intersection. The boundary projection is not exactly axial here + double dr(100.0); + for(double dsig : {-0.5, 0.0, 1.0}){ + double zend = inter.pos_.Z()+dsig*sz; + // radius rcyl at the intersection z: r(z) = rlow + (rhigh-rlow)*(z-zlow)/(2 hlen) + double rhigh = rcyl + dr*(zend - inter.pos_.Z())/(2*hlen); + Frustrum fru(zdir,VEC3(0.0,0.0,zend-hlen),rhigh-dr,rhigh,hlen); + status |= testBounds(tname+" Frustrum end at "+std::to_string(dsig)+" sigma",ktraj,fru,crange,-1.0,ntoy,seed,verbose); + } + return status; +} + +int main(int argc, char** argv) { + unsigned ntoy(20000), seed(124223); + int verbose(0); + int opt; + int long_index =0; + while ((opt = getopt_long_only(argc, argv,"", + long_options, &long_index )) != -1) { + switch (opt) { + case 'n' : ntoy = atoi(optarg); + break; + case 's' : seed = atoi(optarg); + break; + case 'v' : verbose = atoi(optarg); + break; + default: print_usage(); + exit(EXIT_FAILURE); + } + } + VEC3 bnom(0.0,0.0,1.0); + VEC4 pos(0.0,0.0,0.0,0.0); + MOM4 mom(40.0,30.0,60.0,0.511); + TimeRange trange(-10.0,100.0); + LoopHelix lhelix(pos,mom,-1,bnom,trange); + setCovariance(lhelix,{0.5,0.5,0.5,0.5,0.002,0.05}); + CentralHelix chelix(pos,mom,-1,bnom,trange); + setCovariance(chelix,{0.3,0.002,1.0e-5,0.3,0.001,0.05}); + KinematicLine kline(pos,mom,-1,bnom,trange); + setCovariance(kline,{0.1,0.002,0.1,0.002,0.005,0.05}); // d0, phi0, z0, theta, t0, mom + int status(0); + status |= testTraj("LoopHelix",lhelix,trange,ntoy,seed,verbose); + status |= testTraj("CentralHelix",chelix,trange,ntoy,seed,verbose); + status |= testTraj("KinematicLine",kline,trange,ntoy,seed,verbose); + status |= testCurved("LoopHelix",lhelix,trange,ntoy,seed,verbose); + status |= testCurved("CentralHelix",chelix,trange,ntoy,seed,verbose); + status |= testCurved("KinematicLine",kline,trange,ntoy,seed,verbose); + if(status == 0) + cout << "IntersectionBounds test passed" << endl; + else + cout << "IntersectionBounds test FAILED" << endl; + return status; +} From cb8107dc3571abe8edc2cf06d142c87a0dff2f45 Mon Sep 17 00:00:00 2001 From: David Nathan Brown Date: Sat, 21 Nov 2026 14:20:52 -0800 Subject: [PATCH 7/7] Small fixes. --- Fit/Material.hh | 3 +++ Geometry/Intersect.hh | 14 ++++++++------ Tests/IntersectionBounds_unit.cc | 2 +- Tests/IntersectionCovariance_unit.cc | 4 ++-- Tests/ParticleTrajectoryTest.hh | 2 +- Tests/Trajectory.hh | 2 +- Trajectory/CentralHelix.cc | 9 +++++---- Trajectory/CentralHelix.hh | 2 +- Trajectory/KinematicLine.cc | 9 +++++---- Trajectory/KinematicLine.hh | 2 +- Trajectory/LoopHelix.cc | 9 +++++---- Trajectory/LoopHelix.hh | 2 +- 12 files changed, 34 insertions(+), 26 deletions(-) diff --git a/Fit/Material.hh b/Fit/Material.hh index 6bc87052..28b76b82 100644 --- a/Fit/Material.hh +++ b/Fit/Material.hh @@ -103,6 +103,9 @@ namespace KinKal { if((tdir == TimeDir::forwards && ptraj.back().range().begin() > time()) || (tdir == TimeDir::backwards && ptraj.front().range().end() < time()) ) throw std::invalid_argument("Material: Can't append piece"); + // an inactive xing (ie an out-of-bounds crossing) has no effect: don't split the trajectory. As with process and append, + // it is still kept as an effect, and will contribute if it becomes active when the track is refit + if(!exingptr_->active()) return; auto ktrajptr = ptraj.nearestTraj(time()); // convert parameters at this material to momentum space representation auto pstate = ktrajptr->stateEstimate(time()); diff --git a/Geometry/Intersect.hh b/Geometry/Intersect.hh index 544f3b50..d3780f02 100644 --- a/Geometry/Intersect.hh +++ b/Geometry/Intersect.hh @@ -112,13 +112,14 @@ namespace KinKal { // // fill the projection of the trajectory spatial covariance onto the local plane of an onsurface intersection. // The projection (see KTRAJ::planeCovariance) is along the trajectory direction, so it describes the covariance of where the trajectory crosses the plane. - // If the trajectory is (nearly) parallel to the plane the projection is singular: the covariance is left 0 and hascov_ false. + // If the trajectory is (nearly) parallel to the plane (|cos| of the angle between the trajectory direction and the plane normal below dirtol) + // the projection is singular: the covariance is left 0 and hascov_ false. // This is optional as the projection is relatively expensive; intersect calls it only on request (pcov argument), and only on the final intersection. // Only the position, time, and onsurface_ (and inbounds_, used if the covariance is degenerate) of the intersection are used as input: // the local frame (norm_, udir_, vdir_) is (re)filled here from the surface tangent plane at the intersection position, so this can // also be called on intersections constructed outside of the intersect functions. // - template void fillPlaneCovariance(KTRAJ const& ktraj, Surface const& surf, Intersection& inter, double tol) { + template void fillPlaneCovariance(KTRAJ const& ktraj, Surface const& surf, Intersection& inter, double tol, double dirtol=1.0e-10) { inter.pcov_ = PMAT(); inter.hascov_ = false; inter.inbfrac_ = 0.0; @@ -128,9 +129,9 @@ namespace KinKal { inter.udir_ = tplane.uDirection(); inter.vdir_ = tplane.vDirection(); // the projection is singular if the trajectory lies in the plane - if(fabs(inter.norm_.Dot(ktraj.direction(inter.time_))) < 1.0e-10) return; + if(fabs(inter.norm_.Dot(ktraj.direction(inter.time_))) < dirtol) return; Plane plane(inter.norm_,inter.udir_,inter.pos_); - inter.pcov_ = ktraj.planeCovariance(inter.time_,plane); + inter.pcov_ = ktraj.planeCovariance(inter.time_,plane,dirtol); inter.hascov_ = true; inter.inbfrac_ = boundsFraction(surf,inter,tol); } @@ -288,8 +289,9 @@ namespace KinKal { // note we don't know the orientation of the trajectory WRT the axis so we have to try both auto frontinter = hpIntersect(helix,surf.frontDisk(),trange,tol,tdir); auto backinter = hpIntersect(helix,surf.backDisk(),trange,tol,tdir); - if(trange.inRange(frontinter.time_))times.push_back(frontinter.time_); - if(trange.inRange(backinter.time_))times.push_back(backinter.time_); + // a failed disk search leaves time_ at 0, so require the disk intersection be on the surface + if(frontinter.onsurface_ && trange.inRange(frontinter.time_))times.push_back(frontinter.time_); + if(backinter.onsurface_ && trange.inRange(backinter.time_))times.push_back(backinter.time_); if(times.size() >=2){ TimeRange srange(*std::min_element(times.begin(),times.end()),*std::max_element(times.begin(),times.end())); // intersection is possible: step within the restricted range diff --git a/Tests/IntersectionBounds_unit.cc b/Tests/IntersectionBounds_unit.cc index f7f0002b..da798ab0 100644 --- a/Tests/IntersectionBounds_unit.cc +++ b/Tests/IntersectionBounds_unit.cc @@ -42,7 +42,7 @@ template void setCovariance(KTRAJ& ktraj, std::array con double normcdf(double x) { return 0.5*erfc(-x/sqrt(2.0)); } -static const double tol(1.0e-6); +static const double tol(1.0e-3); // intersection tolerance (mm): small compared to the projected errors (~1 mm), and keeps the toy MC fast static const double fractol(0.01); // the target precision of inbfrac_ static const double toytol(0.015); // tolerance on the toy MC comparison: target precision plus statistics diff --git a/Tests/IntersectionCovariance_unit.cc b/Tests/IntersectionCovariance_unit.cc index 16d69477..0d9ac3de 100644 --- a/Tests/IntersectionCovariance_unit.cc +++ b/Tests/IntersectionCovariance_unit.cc @@ -82,7 +82,7 @@ template int testCovariance(std::string } // consistency with the trajectory planeCovariance function, using the local tangent plane auto tplane = surf.tangentPlane(inter.pos_); - auto tcov = ktraj.planeCovariance(inter.time_,tplane); + auto tcov = ktraj.planeCovariance(inter.time_,tplane,1.0e-10); for(int irow=0;irow<2;++irow){ for(int icol=0;icol<2;++icol){ if(fabs(tcov(irow,icol)-pcov(irow,icol)) > ctol*sqrt(pcov(0,0)*pcov(1,1))){ @@ -171,7 +171,7 @@ int main(int argc, char** argv) { CentralHelix chelix(pos,mom,-1,bnom,trange); setCovariance(chelix,{0.3,0.002,1.0e-5,0.3,0.001,0.05}); KinematicLine kline(pos,mom,-1,bnom,trange); - setCovariance(kline,{0.1,0.1,0.0005,0.0005,0.005,0.05}); + setCovariance(kline,{0.1,0.002,0.1,0.002,0.005,0.05}); // d0, phi0, z0, theta, t0, mom auto inter = [&](auto const& ktraj, auto const& surf, TimeRange const& range, bool pcov) { return intersect(ktraj,surf,range,tol,TimeDir::forwards,pcov); }; diff --git a/Tests/ParticleTrajectoryTest.hh b/Tests/ParticleTrajectoryTest.hh index 64a78ca2..fe590d05 100644 --- a/Tests/ParticleTrajectoryTest.hh +++ b/Tests/ParticleTrajectoryTest.hh @@ -279,7 +279,7 @@ int ParticleTrajectoryTest(int argc, char **argv) { if(kc_inter.good()){ auto kc3_inter = intersect(ptraj,csurf, ptraj.range(), 1.0e-8,TimeDir::forwards,true); Plane tplane(kc3_inter.norm_,kc3_inter.udir_,kc3_inter.pos_); - auto tcov = ptraj.nearestPiece(kc3_inter.time_).planeCovariance(kc3_inter.time_,tplane); + auto tcov = ptraj.nearestPiece(kc3_inter.time_).planeCovariance(kc3_inter.time_,tplane,1.0e-10); if(!kc3_inter.hascov_ || kc3_inter.time_ != kc_inter.time_ || kc3_inter.pcov_ != tcov){ std::cout << "Plane covariance inconsistent " << kc3_inter << " " << kc3_inter.pcov_ << " " << tcov << std::endl; return -2; diff --git a/Tests/Trajectory.hh b/Tests/Trajectory.hh index 2f66f22a..ce3f4d43 100644 --- a/Tests/Trajectory.hh +++ b/Tests/Trajectory.hh @@ -329,7 +329,7 @@ int TrajectoryTest(int argc, char **argv,KinKal::DVEC sigmas) { auto momdir = ktraj.direction(ltime); auto udir = ktraj.direction(ltime,MomBasis::perpdir_); Plane plane(momdir,udir,ppos); - auto pcov = ktraj.planeCovariance(ltime,plane); + auto pcov = ktraj.planeCovariance(ltime,plane,1.0e-10); // cout << "Plane covariance " << pcov << endl; if(fabs(pcov(0,0) - pperpvar) > 1e-9 || diff --git a/Trajectory/CentralHelix.cc b/Trajectory/CentralHelix.cc index d4e86828..afe0f239 100644 --- a/Trajectory/CentralHelix.cc +++ b/Trajectory/CentralHelix.cc @@ -164,14 +164,15 @@ namespace KinKal { return ROOT::Math::Similarity(dxdp,params().covariance()); } - PMAT CentralHelix::planeCovariance(double time,Plane const& plane) const { + PMAT CentralHelix::planeCovariance(double time,Plane const& plane, double dirtol) const { // project the spatial covariance onto the U, V directions of the given plane. The projection is // along the particle direction, so the result describes the covariance of the point where the trajectory - // crosses the plane. This includes the effect of the t0 (and other) errors on the position along the trajectory. - // The particle direction cannot lie in the plane + // crosses the plane. Errors that displace the position along the particle direction (such as the t0 error) drop out of + // this linear projection. The particle direction cannot lie in the plane: |cos| of the angle between the direction and + // the plane normal must exceed dirtol auto momdir = direction(time); double ndot = plane.normal().Dot(momdir); - if(fabs(ndot) < 1.0e-10)throw invalid_argument("Momentum direction lies in the plane"); + if(fabs(ndot) < dirtol)throw invalid_argument("Momentum direction lies in the plane"); // a perturbation dx moves the crossing point by dx - momdir*(norm.dx)/(norm.momdir) auto uproj = plane.uDirection() - plane.normal()*(plane.uDirection().Dot(momdir)/ndot); auto vproj = plane.vDirection() - plane.normal()*(plane.vDirection().Dot(momdir)/ndot); diff --git a/Trajectory/CentralHelix.hh b/Trajectory/CentralHelix.hh index 26764483..bd2ac998 100644 --- a/Trajectory/CentralHelix.hh +++ b/Trajectory/CentralHelix.hh @@ -75,7 +75,7 @@ namespace KinKal { double momentum(double time=0) const { return fabs(mass_ * pbar() / mbar()); } double momentumVariance(double time=0) const; double positionVariance(double time,MomBasis::Direction dir) const; - PMAT planeCovariance(double time,Plane const& plane) const; + PMAT planeCovariance(double time,Plane const& plane, double dirtol) const; double energy(double time=0) const { return fabs(mass_ * ebar() / mbar()); } // local momentum direction basis void print(std::ostream& ost, int detail) const; diff --git a/Trajectory/KinematicLine.cc b/Trajectory/KinematicLine.cc index 1c055ebb..606cfb4e 100644 --- a/Trajectory/KinematicLine.cc +++ b/Trajectory/KinematicLine.cc @@ -132,14 +132,15 @@ namespace KinKal { return ROOT::Math::Similarity(dxdp,params().covariance()); } - PMAT KinematicLine::planeCovariance(double time,Plane const& plane) const { + PMAT KinematicLine::planeCovariance(double time,Plane const& plane, double dirtol) const { // project the spatial covariance onto the U, V directions of the given plane. The projection is // along the particle direction, so the result describes the covariance of the point where the trajectory - // crosses the plane. This includes the effect of the t0 (and other) errors on the position along the trajectory. - // The particle direction cannot lie in the plane + // crosses the plane. Errors that displace the position along the particle direction (such as the t0 error) drop out of + // this linear projection. The particle direction cannot lie in the plane: |cos| of the angle between the direction and + // the plane normal must exceed dirtol auto momdir = direction(time); double ndot = plane.normal().Dot(momdir); - if(fabs(ndot) < 1.0e-10)throw invalid_argument("Momentum direction lies in the plane"); + if(fabs(ndot) < dirtol)throw invalid_argument("Momentum direction lies in the plane"); // a perturbation dx moves the crossing point by dx - momdir*(norm.dx)/(norm.momdir) auto uproj = plane.uDirection() - plane.normal()*(plane.uDirection().Dot(momdir)/ndot); auto vproj = plane.vDirection() - plane.normal()*(plane.vDirection().Dot(momdir)/ndot); diff --git a/Trajectory/KinematicLine.hh b/Trajectory/KinematicLine.hh index 03e8a000..64263a5b 100644 --- a/Trajectory/KinematicLine.hh +++ b/Trajectory/KinematicLine.hh @@ -75,7 +75,7 @@ class KinematicLine { double momentumVariance(double time) const { return pars_.covariance()(mom_,mom_); } double positionVariance(double time,MomBasis::Direction dir) const; - PMAT planeCovariance(double time,Plane const& plane) const; + PMAT planeCovariance(double time,Plane const& plane, double dirtol) const; double energy() const { double momval = mom(); return sqrt(momval*momval+mass_*mass_); } double energy(double time) const { return energy(); } diff --git a/Trajectory/LoopHelix.cc b/Trajectory/LoopHelix.cc index be95f784..2571a663 100644 --- a/Trajectory/LoopHelix.cc +++ b/Trajectory/LoopHelix.cc @@ -133,14 +133,15 @@ namespace KinKal { return ROOT::Math::Similarity(dxdp,params().covariance()); } - PMAT LoopHelix::planeCovariance(double time,Plane const& plane) const { + PMAT LoopHelix::planeCovariance(double time,Plane const& plane, double dirtol) const { // project the spatial covariance onto the U, V directions of the given plane. The projection is // along the particle direction, so the result describes the covariance of the point where the trajectory - // crosses the plane. This includes the effect of the t0 (and other) errors on the position along the trajectory. - // The particle direction cannot lie in the plane + // crosses the plane. Errors that displace the position along the particle direction (such as the t0 error) drop out of + // this linear projection. The particle direction cannot lie in the plane: |cos| of the angle between the direction and + // the plane normal must exceed dirtol auto momdir = direction(time); double ndot = plane.normal().Dot(momdir); - if(fabs(ndot) < 1.0e-10)throw invalid_argument("Momentum direction lies in the plane"); + if(fabs(ndot) < dirtol)throw invalid_argument("Momentum direction lies in the plane"); // a perturbation dx moves the crossing point by dx - momdir*(norm.dx)/(norm.momdir) auto uproj = plane.uDirection() - plane.normal()*(plane.uDirection().Dot(momdir)/ndot); auto vproj = plane.vDirection() - plane.normal()*(plane.vDirection().Dot(momdir)/ndot); diff --git a/Trajectory/LoopHelix.hh b/Trajectory/LoopHelix.hh index dec5d56e..c8954abf 100644 --- a/Trajectory/LoopHelix.hh +++ b/Trajectory/LoopHelix.hh @@ -81,7 +81,7 @@ namespace KinKal { double momentum(double time=0) const { return mass_*betaGamma(); } double momentumVariance(double time=0) const; double positionVariance(double time,MomBasis::Direction dir) const; - PMAT planeCovariance(double time,Plane const& plane) const; + PMAT planeCovariance(double time,Plane const& plane, double dirtol) const; double energy(double time=0) const { return fabs(ebar()*Q()); } VEC3 direction(double time, MomBasis::Direction mdir= MomBasis::momdir_) const; double mass() const { return mass_;} // mass