Skip to content

fix: compute theta and deltaangle with arctan2 for small angle precision - #760

Open
robinbishtt wants to merge 17 commits into
scikit-hep:mainfrom
robinbishtt:main
Open

robinbishtt wants to merge 17 commits into
scikit-hep:mainfrom
robinbishtt:main

Conversation

@robinbishtt

@robinbishtt robinbishtt commented Nov 4, 2026 •

Copy link
Copy Markdown

Description

Fixes #759.

theta was computed as arccos(z / mag) and deltaangle as arccos(dot / (|v1| |v2|)). Both lose precision for small angles. Below about 1e-8 rad the result is exactly 0, and theta(1e-6) is already off by 4e-5 relative. The same vector in xytheta and in rhophiz also gave a deltaangle of 1.5e-8 instead of 0. The reproducer is in #759.

This PR switches both to arctan2:

  • theta = arctan2(rho, z)
  • deltaangle = arctan2(|v1 x v2|, v1 . v2)

deltaangle.py gets much shorter. Like cross.py, it now implements only the Cartesian case and builds the other 35 coordinate combinations by converting to x, y, z (710 lines down to 146).

Two behaviour changes, also raised in #759:

  • deltaangle with a zero-length vector returns 0.0 instead of nan.
  • theta of (0, 0, -0.0) returns pi instead of 0.

If you prefer preserving the old behavior for either edge case, I can add an explicit guard.

Tests:

  • Added unit tests in tests/compute/spatial/test_theta.py and tests/compute/spatial/test_deltaangle.py covering small angles down to 1e-12 rad across object and NumPy backends, forward-momentum kinematics (pt = 0.01, pz = 6800.0), origin and pole vectors, antiparallel and perpendicular vectors, and identical vectors converted across all 36 coordinate-system pairs (13 of these cases fail on current main).
  • Updated 9 symbolic assertions across tests/backends/test_sympy.py, tests/compute/sympy/test_conversions.py, tests/compute/sympy/spatial/test_theta.py, and tests/compute/sympy/spatial/test_deltaangle.py where the previous sympy.acos expression was pinned directly.

Checklist

  • Have you followed the guidelines in our Contributing document?
  • Have you checked to ensure there aren't any other open Pull Requests for the required change?
  • Does your submission pass pre-commit? (ruff formatting and lint checks are clean across all 8 changed files)
  • Does your submission pass tests? (pytest: 4960 passed, 17 skipped, including the new small-angle and coordinate-pair precision tests)
  • Does the documentation build with your changes? (no documentation files modified; existing docstrings unchanged)
  • Does your submission pass the doctests? (pytest --doctest-plus src/vector/ passes)

Before Merging

  • Summarize the commit messages into a brief review of the Pull request.

Summary of commits (12 commits across 8 files, ready to squash on merge):

  • src/vector/_compute/spatial/theta.py: Switched xy_z and rhophi_z from arccos(costheta) to arctan2(rho, z) using vector._compute.planar.rho.
  • src/vector/_compute/spatial/deltaangle.py: Replaced the 36-combination arccos dispatch table with arctan2(|v1 x v2|, v1 . v2) routed through Cartesian coordinates.
  • tests/backends/test_sympy.py, tests/compute/sympy/test_conversions.py, tests/compute/sympy/spatial/test_theta.py, and tests/compute/sympy/spatial/test_deltaangle.py: Updated symbolic test expectations from sympy.acos to sympy.atan2 and cleaned up indentation/whitespace.
  • tests/compute/spatial/test_theta.py and tests/compute/spatial/test_deltaangle.py: Added numerical regression tests for small angles, forward scattering, poles/origin, antiparallel vectors, and cross-coordinate consistency.
  • AI Tool Use: AI assistance was used only to structure and format the PR description text. The bug discovery, patch, and test cases are my own work.

@Sinkleberg

Copy link
Copy Markdown

The small-angle case improves, but scaling both vectors can now change a 45° angle. With s = 1e100, the example below gives π/2 on this branch. With s = 1e-100, it gives 0. Both give π/4 on the base branch.

a = vector.obj(x=s, y=0.0, z=0.0)
b = vector.obj(x=s, y=s, z=0.0)
a.deltaangle(b)

The cross product is still representable at both scales, but squaring it overflows or underflows. Could we compute its norm with a scaled norm or hypot and keep these as regression cases?

@robinbishtt

Copy link
Copy Markdown
Author

@Sinkleberg Thanks, you're right. Squaring the cross product components overflows or underflows for vectors above about 1e77 or below 1e-77 so a 45 degree angle came out as pi/2 or 0.

I replaced the norm with a nested hypot so deltaangle is accurate over the whole range again and added your s = 1e100 and 1e-100 cases plus 1e-150, 1e-77, 1e77 and 1e150 as regression tests. SymPy's lib had no hypot so I added one there as well. I checked it against a 600 case random sweep from 1e-150 to 1e150 the worst error was 4e-16. The range is still about 1e154 because mag and rho overflow there too.

@robinbishtt

robinbishtt commented Nov 9, 2026 •

Copy link
Copy Markdown
Author

Ping @jpivarski @Saransh-cpp

@codecov

codecov Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 88.78%. Comparing base (caf34cd) to head (e3218cf).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #760      +/-   ##
==========================================
- Coverage   88.88%   88.78%   -0.11%     
==========================================
  Files          96       96              
  Lines       10783    10691      -92     
==========================================
- Hits         9585     9492      -93     
- Misses       1198     1199       +1     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Saransh-cpp

Copy link
Copy Markdown
Member

Hi @robinbishtt, thanks for opening the PR. Jim has moved on from Scikit-HEP. Sorry, I will not get any time in the couple of months to review this. We will finalize an AI_POLICY (#761) soon. Could you please add AI usage to the PR description. Another maintainer will take a look before me if they have spare time :)

@robinbishtt

Copy link
Copy Markdown
Author

Thanks for letting me know @Saransh-cpp! I just updated the PR description to include the AI usage disclosure at the bottom and synced the branch with main.

cc @henryiii @ikrommyd whenever someone has a moment to take a look or re trigger the CI workflow. Thanks!

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

theta and deltaangle lose precision for small angles

3 participants