From 9c36012ceea48e2f6e286112793e889104a47099 Mon Sep 17 00:00:00 2001 From: Rob Mina Date: Thu, 12 Nov 2026 14:48:41 -0600 Subject: [PATCH 1/2] Fix for helix-plane intersect outside time range. --- Geometry/Intersect.hh | 81 ++++++++++--------- Tests/CMakeLists.txt | 1 + Tests/IntersectReturn_unit.cc | 145 ++++++++++++++++++++++++++++++++++ 3 files changed, 189 insertions(+), 38 deletions(-) create mode 100644 Tests/IntersectReturn_unit.cc diff --git a/Geometry/Intersect.hh b/Geometry/Intersect.hh index dad26a7a..87a28864 100644 --- a/Geometry/Intersect.hh +++ b/Geometry/Intersect.hh @@ -37,7 +37,6 @@ namespace KinKal { tstep *= timeDirSign(tdir); bool startinside = surf.isInside(pos); bool stepinside; - unsigned niter(0); // step until we cross the surface or the time is out of range do { ttest += tstep; @@ -45,44 +44,49 @@ namespace KinKal { stepinside = surf.isInside(pos); } while (startinside == stepinside && trange.inRange(ttest)); if(startinside != stepinside){ - // we crossed the surface: backup and do a linear search. - ttest -= tstep; - double dist = std::numeric_limits::max(); - IntersectFlag rayinter; - static const unsigned nconv(5); // when to start worrying about non-convergence - double sumdist[2] = {0.0,0.0}; // sum of absolute distance for convergence testing - do { - retval.pos_ = ktraj.position3(ttest); - retval.pdir_ = ktraj.direction(ttest); - auto ray = retval.ray(); - rayinter = surf.intersect(ray,dist,false,tol); - if(rayinter.onsurface_){ - ttest += dist/speed; - } else { - break; + // we crossed the surface in the last step: refine inside that step with a safeguarded linear (Newton) search. + // The bracket [tstart, tcross] keeps one end on each side of the surface, so the search cannot leave it + double tstart = ttest - tstep; // on the starting side + double tcross = ttest; // on the other side + ttest = tstart; + double dtprev = std::numeric_limits::max(); // size of the previous step + static const unsigned maxiter(100); // bisection alone converges in far fewer iterations + bool converged(false); + for(unsigned niter=0; niter < maxiter; ++niter){ + pos = ktraj.position3(ttest); + // shrink the bracket using the side of the current point + if(niter > 0){ + if(surf.isInside(pos) == startinside) + tstart = ttest; + else + tcross = ttest; } - ++niter; - unsigned iconv = niter/nconv; // count convergence cycles - if(iconv > 0){ // start testing for non-convergence - unsigned icur = iconv % 2; // current cycle average indicator (0 or 1) - int irem = niter - iconv*nconv; - if( irem == 0){ - // new cycle - if(iconv > 2){ //if we're past the 3rd cycle, test - unsigned iprev = (iconv + 1) % 2; // previous cycle (that we just finished) - if(sumdist[iprev]/sumdist[icur] > 0.5) { - // claim non-convergence if the sum distance hasn't decreased by at least a factor of 2 between cycles - // std::cout << "Non-converged step intersection ray inter dist " << dist << " avg " << sumdist[iprev] << " prev avg " << sumdist[icur] << std::endl; - return retval; // failed - } - } - sumdist[icur] = 0.0; // reset the average counter + Ray ray(ktraj.direction(ttest),pos); + double dist(0.0); + auto rayinter = surf.intersect(ray,dist,false,tol); + double tnext = ttest + dist/speed; + // accept the linear step if it lands inside the bracket and at least halves the previous step + bool linear = rayinter.onsurface_ && (tnext-tstart)*(tnext-tcross) <= 0.0 && fabs(tnext-ttest) < 0.5*dtprev; + if(linear){ + if(fabs(dist) < tol){ + ttest = tnext; + converged = true; + break; + } + } else { + // otherwise bisect, and stop once the bracket is within tolerance + tnext = 0.5*(tstart+tcross); + if(fabs(tcross-tstart)*speed < tol){ + ttest = tnext; + converged = true; + break; } - sumdist[icur] += fabs(dist); // increatement the sum } - } while (fabs(dist) > tol); - if(rayinter.onsurface_){ - retval.onsurface_ = rayinter.onsurface_; + dtprev = fabs(tnext-ttest); + ttest = tnext; + } + if(converged){ + retval.onsurface_ = true; retval.time_ = ttest; retval.pos_ = ktraj.position3(retval.time_); retval.pdir_ = ktraj.direction(retval.time_); @@ -187,9 +191,10 @@ namespace KinKal { double ddot = fabs(ray.direction().Dot(plane.normal())); double zrange = fabs(vax*trange.range()); if(zrange > tol && ddot > tol/zrange ){ - // Find the intersection time of the helix ray (along bnom) with the plane to reduce the range + // Find the intersection time of the helix ray (along bnom) with the plane to reduce the range. + // The ray crossing can be behind the start even when the helix crosses the plane after it, so accept either direction double dist(0.0); - auto pinter = plane.intersect(ray,dist,true,tol); + auto pinter = plane.intersect(ray,dist,false,tol); if(pinter.onsurface_){ // translate the ray intersection distance to a time double tmid = tstart + dist/vax; diff --git a/Tests/CMakeLists.txt b/Tests/CMakeLists.txt index 030631eb..6c7073a3 100644 --- a/Tests/CMakeLists.txt +++ b/Tests/CMakeLists.txt @@ -27,6 +27,7 @@ set( TEST_SOURCE_FILES LoopHelix_unit.cc Geometry_unit.cc Intersection_unit.cc + IntersectReturn_unit.cc MatEnv_unit.cc Truncate_unit.cc ) diff --git a/Tests/IntersectReturn_unit.cc b/Tests/IntersectReturn_unit.cc new file mode 100644 index 00000000..b87623cb --- /dev/null +++ b/Tests/IntersectReturn_unit.cc @@ -0,0 +1,145 @@ +// +// Test helix intersections with a surface the helix crosses, overshoots slightly and crosses back (KFTrack/KinKal#233). +// The query starts on the outgoing leg (outside the tolerance slab, or at the turning point) and ends after the +// return crossing, so intersect must return the return crossing, which is the only root inside the query. +// The first sign-change step straddles the turning point; the refinement must stay inside that step. +// Surfaces: a plane (Rectangle) and a cylinder parallel to the field; LoopHelix and CentralHelix, both time directions. +// Second part: a helix whose axis is tilted from the plane normal starts just in front of the plane, so the point on +// the helix axis at the query start can already be past the plane; the crossing just after the start must be found. +// +#include "KinKal/General/ParticleState.hh" +#include "KinKal/General/TimeRange.hh" +#include "KinKal/General/TimeDir.hh" +#include "KinKal/Trajectory/LoopHelix.hh" +#include "KinKal/Trajectory/CentralHelix.hh" +#include "KinKal/Geometry/Rectangle.hh" +#include "KinKal/Geometry/Cylinder.hh" +#include "KinKal/Geometry/Intersection.hh" +#include "KinKal/Geometry/Intersect.hh" +#include +#include +#include +#include +#include + +using namespace KinKal; + +enum class SurfType { plane, cylinder }; + +// startfrac: query start in half-widths before the turning point (0 = at it; > 1 = before the first crossing) +// expect the first crossing when the query starts before it, otherwise the return crossing +template int surfaceReturn(SurfType stype, TimeDir tdir, double excursion, double tol, double startfrac, std::string const& name) { + double sign = tdir == TimeDir::forwards ? 1.0 : -1.0; + // 100 MeV/c transverse, 20 MeV/c along a 1 T field, muon mass; R = 333.6 mm + ParticleState state(VEC3(0.0,0.0,0.0),VEC3(100.0,0.0,20.0),0.0,105.658,1); + HELIX helix(state,VEC3(0.0,0.0,1.0),TimeRange(-100.0,100.0)); + double rbend = helix.bendRadius(); + double omega = helix.transverseSpeed()/rbend; // |dphi/dt| + double tmax = sign*0.5*M_PI/omega; // the turning point: a quarter turn from the start + std::unique_ptr surf; + double halfwidth(0.0); // time from a root to the turning point + std::string sname; + if(stype == SurfType::plane){ + // plane normal to the helix radius at tmax, excursion inside the helix circle + double radius = std::fabs(helix.position3(tmax).X()); + halfwidth = std::acos(1.0-excursion/radius)/omega; + surf = std::make_unique(VEC3(1.0,0.0,0.0),VEC3(0.0,1.0,0.0),helix.position3(tmax-sign*halfwidth),2000.0,2000.0); + sname = "Plane"; + } else { + // cylinder along the field whose axis is offset from the helix axis by ecc towards the helix position at tmax: + // the distance from the cylinder axis is smallest (rbend-ecc) at tmax, and the helix dips excursion inside it + double ecc = 0.5*rbend; // the same half-width as the plane to second order + auto rdir = helix.position3(tmax) - helix.center(tmax); + rdir.SetZ(0.0); + auto cpos = helix.center(tmax) + ecc*rdir.Unit(); + cpos.SetZ(0.0); + double crad = rbend - ecc + excursion; + halfwidth = std::acos((rbend*rbend + ecc*ecc - crad*crad)/(2.0*rbend*ecc))/omega; + surf = std::make_unique(VEC3(0.0,0.0,1.0),cpos,crad,2000.0); + sname = "Cylinder"; + } + double first = tmax - sign*halfwidth; // the crossing into the excursion + double ret = tmax + sign*halfwidth; // the return crossing + double expected = startfrac > 1.0 ? first : ret; + double qstart = tmax - sign*startfrac*halfwidth; + double qend = tmax + sign*1.5*halfwidth; + TimeRange query = tdir == TimeDir::forwards ? TimeRange(qstart,qend) : TimeRange(qend,qstart); + auto inter = KinKal::intersect(helix,*surf,query,tol,tdir); + bool ok = inter.good() && std::fabs(inter.time_-expected)*helix.speed(expected) < tol; + std::cout << std::setprecision(12) << name << " " << sname << (tdir == TimeDir::forwards ? " forwards" : " backwards") + << " start " << startfrac << " half-widths before the turn, excursion " << excursion << " mm tol " << tol << " mm\n" + << " query [" << query.begin() << ", " << query.end() << "] ns, start " + << surf->distance(helix.position3(qstart)) << " mm from the surface\n" + << " roots: first " << first << ", return " << ret << ", expected " << expected << "\n" + << " intersect: time " << inter.time_ << " onsurface " << inter.onsurface_ << " inbounds " + << inter.inbounds_ << " inrange " << inter.inrange_ << " -> " << (ok ? "OK" : "FAIL") << "\n"; + return ok ? 0 : 1; +} + +// a 35.5 MeV/c electron in a 2 T field tilted by alpha from the plane normal (z) starts dist0 in front of the plane, +// moving towards it with cos = -0.53 to the normal; the helix loops within the query; beta is the momentum azimuth +template int axisTilt(TimeDir tdir, double alpha, double beta, std::string const& name) { + double sign = tdir == TimeDir::forwards ? 1.0 : -1.0; + double tol(0.1), dist0(0.48), cost(-0.53), pmom(35.5), qlen(0.25); + double sint = std::sqrt(1.0-cost*cost); + // in the search direction the particle moves towards the plane: reverse the momentum when searching backwards + VEC3 mom = sign*pmom*VEC3(sint*std::cos(beta),sint*std::sin(beta),cost); + ParticleState state(VEC3(0.0,0.0,0.0),mom,0.0,0.511,-1); + VEC3 bnom(2.0*std::sin(alpha),0.0,2.0*std::cos(alpha)); + HELIX helix(state,bnom,TimeRange(-100.0,100.0)); + Rectangle plane(VEC3(0.0,0.0,1.0),VEC3(1.0,0.0,0.0),VEC3(0.0,0.0,-dist0),2000.0,2000.0); + TimeRange query = tdir == TimeDir::forwards ? TimeRange(0.0,qlen) : TimeRange(-qlen,0.0); + // the expected crossing, by bisection over the query (the plane distance is monotonic over it) + double ta(0.0), tb(sign*qlen); + double fa = plane.distance(helix.position3(ta)); + if(fa*plane.distance(helix.position3(tb)) >= 0.0){ + std::cout << name << " axis tilt: no crossing in the query, bad test geometry" << std::endl; + return 1; + } + for(unsigned i=0; i < 100; ++i){ + double tm = 0.5*(ta+tb); + if(plane.distance(helix.position3(tm))*fa > 0.0) ta = tm; else tb = tm; + } + double expected = 0.5*(ta+tb); + auto inter = KinKal::intersect(helix,plane,query,tol,tdir); + bool ok = inter.good() && std::fabs(inter.time_-expected)*helix.speed(expected) < tol; + auto ray = helix.linearize(0.0); + std::cout << std::setprecision(12) << name << " axis tilt " << alpha << " azimuth " << beta + << (tdir == TimeDir::forwards ? " forwards" : " backwards") << " query [" << query.begin() << ", " << query.end() + << "] ns, radius " << helix.bendRadius() << " mm, linearized ray start " << plane.distance(ray.start()) + << " mm from the plane\n expected " << expected << ", intersect: time " << inter.time_ << " onsurface " + << inter.onsurface_ << " inbounds " << inter.inbounds_ << " inrange " << inter.inrange_ << " -> " << (ok ? "OK" : "FAIL") << "\n"; + return ok ? 0 : 1; +} + +int main() { + int nfail(0), ncase(0); + for(auto stype : {SurfType::plane, SurfType::cylinder}){ + for(auto tdir : {TimeDir::forwards, TimeDir::backwards}){ + // tol = 0.1 mm: the first sign-change step straddles the turning point + // startfrac 0.5: the query starts outside the slab on the outgoing leg; 0.0: at the turning point + for(double startfrac : {0.5, 0.0}){ + nfail += surfaceReturn(stype,tdir,0.15,0.1,startfrac,"LoopHelix"); ++ncase; + nfail += surfaceReturn(stype,tdir,0.15,0.1,startfrac,"CentralHelix"); ++ncase; + } + // controls: tol = 0.05 mm (the sign-change step starts past the turn), and a query that contains both roots + nfail += surfaceReturn(stype,tdir,0.15,0.05,0.5,"control LoopHelix"); ++ncase; + nfail += surfaceReturn(stype,tdir,0.15,0.05,0.5,"control CentralHelix"); ++ncase; + nfail += surfaceReturn(stype,tdir,0.15,0.1,1.5,"control LoopHelix"); ++ncase; + nfail += surfaceReturn(stype,tdir,0.15,0.1,1.5,"control CentralHelix"); ++ncase; + } + } + int nfailaxis(0), ncaseaxis(0); + for(auto tdir : {TimeDir::forwards, TimeDir::backwards}){ + for(double alpha : {0.0, 0.05}){ // alpha = 0: the axis point and the particle are at the same distance from the plane + for(unsigned ibeta=0; ibeta < 8; ++ibeta){ + double beta = ibeta*M_PI/4.0; + nfailaxis += axisTilt(tdir,alpha,beta,"LoopHelix"); ++ncaseaxis; + nfailaxis += axisTilt(tdir,alpha,beta,"CentralHelix"); ++ncaseaxis; + } + } + } + std::cout << nfail << " of " << ncase << " return-crossing cases fail; " << nfailaxis << " of " << ncaseaxis << " axis-tilt cases fail" << std::endl; + nfail += nfailaxis; + return nfail == 0 ? 0 : 1; +} From d1b19c87b0af7ec1f7990a0617a1e3a10d94aef6 Mon Sep 17 00:00:00 2001 From: Rob Mina Date: Tue, 17 Nov 2026 06:57:00 -0600 Subject: [PATCH 2/2] Improve readability. --- Geometry/Intersect.hh | 18 +++++++++++++----- Tests/IntersectReturn_unit.cc | 12 +++++++----- 2 files changed, 20 insertions(+), 10 deletions(-) diff --git a/Geometry/Intersect.hh b/Geometry/Intersect.hh index 87a28864..954e6073 100644 --- a/Geometry/Intersect.hh +++ b/Geometry/Intersect.hh @@ -66,7 +66,11 @@ namespace KinKal { auto rayinter = surf.intersect(ray,dist,false,tol); double tnext = ttest + dist/speed; // accept the linear step if it lands inside the bracket and at least halves the previous step - bool linear = rayinter.onsurface_ && (tnext-tstart)*(tnext-tcross) <= 0.0 && fabs(tnext-ttest) < 0.5*dtprev; + TimeRange bracket(tstart,tcross,false); // unordered: tcross is before tstart when stepping backwards + // closed test: once a step has converged the next one is null, landing exactly on the bracket end it starts from, + // which TimeRange::inRange excludes + bool inbracket = tnext >= bracket.begin() && tnext <= bracket.end(); + bool linear = rayinter.onsurface_ && inbracket && fabs(tnext-ttest) < 0.5*dtprev; if(linear){ if(fabs(dist) < tol){ ttest = tnext; @@ -75,8 +79,8 @@ namespace KinKal { } } else { // otherwise bisect, and stop once the bracket is within tolerance - tnext = 0.5*(tstart+tcross); - if(fabs(tcross-tstart)*speed < tol){ + tnext = bracket.mid(); + if(bracket.range()*speed < tol){ ttest = tnext; converged = true; break; @@ -162,6 +166,7 @@ namespace KinKal { // 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 } } } @@ -191,8 +196,9 @@ namespace KinKal { double ddot = fabs(ray.direction().Dot(plane.normal())); double zrange = fabs(vax*trange.range()); if(zrange > tol && ddot > tol/zrange ){ - // Find the intersection time of the helix ray (along bnom) with the plane to reduce the range. - // The ray crossing can be behind the start even when the helix crosses the plane after it, so accept either direction + // 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 + // plane after it, so accept either direction double dist(0.0); auto pinter = plane.intersect(ray,dist,false,tol); if(pinter.onsurface_){ @@ -210,6 +216,7 @@ namespace KinKal { // step to the intersection in the restricted range. Use a separate intersection object as the // range is different retval = stepIntersect(helix,plane,srange,tol,tdir); + if(retval.onsurface_) retval.inrange_ = trange.inRange(retval.time_); // report against the caller's range, not the restricted one } } } else { @@ -253,6 +260,7 @@ namespace KinKal { // 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 } } } diff --git a/Tests/IntersectReturn_unit.cc b/Tests/IntersectReturn_unit.cc index b87623cb..4c96f04a 100644 --- a/Tests/IntersectReturn_unit.cc +++ b/Tests/IntersectReturn_unit.cc @@ -122,11 +122,13 @@ int main() { nfail += surfaceReturn(stype,tdir,0.15,0.1,startfrac,"LoopHelix"); ++ncase; nfail += surfaceReturn(stype,tdir,0.15,0.1,startfrac,"CentralHelix"); ++ncase; } - // controls: tol = 0.05 mm (the sign-change step starts past the turn), and a query that contains both roots - nfail += surfaceReturn(stype,tdir,0.15,0.05,0.5,"control LoopHelix"); ++ncase; - nfail += surfaceReturn(stype,tdir,0.15,0.05,0.5,"control CentralHelix"); ++ncase; - nfail += surfaceReturn(stype,tdir,0.15,0.1,1.5,"control LoopHelix"); ++ncase; - nfail += surfaceReturn(stype,tdir,0.15,0.1,1.5,"control CentralHelix"); ++ncase; + // smaller tolerance: with tol = 0.05 mm the sign-change step starts past the turn + nfail += surfaceReturn(stype,tdir,0.15,0.05,0.5,"small-tol LoopHelix"); ++ncase; + nfail += surfaceReturn(stype,tdir,0.15,0.05,0.5,"small-tol CentralHelix"); ++ncase; + // the query starts before the first crossing and contains both roots: the first crossing is expected. + // Before #233 was fixed the cylinder cases also failed, because the tangent ray misses the cylinder + nfail += surfaceReturn(stype,tdir,0.15,0.1,1.5,"first-crossing LoopHelix"); ++ncase; + nfail += surfaceReturn(stype,tdir,0.15,0.1,1.5,"first-crossing CentralHelix"); ++ncase; } } int nfailaxis(0), ncaseaxis(0);