Skip to content

Spherical point-in-face and lat-lon face bounds (AccuSphGeom split from #1513) - #1627

Open
rajeeja wants to merge 77 commits into
mainfrom
rajeeja/point_in_face_bounds
Open

rajeeja wants to merge 77 commits into
mainfrom
rajeeja/point_in_face_bounds

Conversation

@rajeeja

@rajeeja rajeeja commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

Split out from #1513 per discussion there — point-in-face and lat-lon bounds work, based on the same AccuSphGeom EFT kernels that already landed in main.

Draft while I confirm mergeability against main and re-verify tests/pre-commit after the split.

rajeeja added 30 commits June 8, 2026 15:47
…rite intersections, add 241 baseline testsgit status! - most came from accusphere
- benchmarks/geometry_kernels.py: ASV micro-benchmarks for all three
  layers of the EFT intersection stack (_accux_gca, _try_gca_gca_intersection,
  gca_gca_intersection, _accux_constlat, _try_gca_const_lat_intersection,
  gca_const_lat_intersection) plus EFT primitives and point-in-polygon;
  all functions warmed before timing so results reflect steady-state cost
- test/test_plot.py: add test_to_raster_auto_extent verifying that the
  axis limits change and the raster contains finite data
…rectness fixes

Review comments addressed:
- Remove "near-double precision" / "sufficient" overclaims; say "roughly twice
  as accurate" and note the robustness tier boundary clearly
- Explain _lon_bounds_from_vertices is required for UXarray antimeridian
  encoding and cannot be removed
- Add block comment before _no_extreme functions clarifying they are
  pre-existing edge screeners unrelated to the EFT stack
- Document SoS as explicit future work in _point_in_polygon_sphere docstring
- L2 pos_fin/neg_fin: replace ternary with int(); exploit neg=-pos symmetry
- Label computation: drop dead local*0 term, use integer mask arithmetic
- Remove vertex-lat snap from bounds: _face_location_info already captures
  interior arc extrema accurately via the compensated kernel
- _ON_MINOR_ARC_TOL: document intentional 1e-10 vs C++ 1e-8 divergence

Bug fixes:
- on_minor_arc: add antipodal-endpoint guard; a x b = 0 for antipodal inputs
  so every point on the great circle passes the collinearity test (false pos)
- bounds.py: replace mask arithmetic use_ext*z_ext + (1-use_ext)*z_edge with
  plain if/else; 0*NaN = NaN propagates when norm=0, if/else does not
- _point_in_polygon_sphere: ray-nudge now restarts the loop from i=0 so all
  edges are counted with the same ray (mid-loop nudge corrupted crossing parity)

Cleanup:
- Remove _flip_sign, _SIGN_NEG, _SIGN_POS, _SIGN_ZERO dead code from
  point_in_face.py; inline literals in _counts_as_crossing
- Remove _SNAP_TOL_DEG constant and snap_tol_deg parameter throughout bounds.py
- Notebook: fix Grid.get_point_on_face -> get_faces_containing_point; remove
  incorrect geometry.py row from Section 4 table; add accucross_pair and
  acc_sqrt_re to Section 2 building-blocks table
…PI name

- ci/environment.yml: pin tornado<6.5.7 to avoid ssl.SSLError in panel 1.9.3
  on Python 3.11 Windows (conda-forge regression, 2026-06-10)
- intersections.py: remove _gca_gca_intersection_cartesian shim (dead code);
  add comment explaining _snap_const_lat_endpoint snap_sq constant
- test_intersections.py: update 4 call sites to use gca_gca_intersection directly
- spherical-geometry-accuracy.ipynb: fix stale Grid.get_point_on_face ->
  Grid.get_faces_containing_point (2 occurrences)
…rite intersections, add 241 baseline testsgit status! - most came from accusphere
Reconcile diverged accusphere branch. Resolutions:
- intersections.py: restore inline=always on L1 kernels (_accux_constlat,
  _accux_gca) for allocation scalar-replacement
- point_in_face.py: keep restart-loop ray casting (consistent parity),
  adopt named sign constants, drop unused _flip_sign
- arcs.py: keep antipodal-endpoint guard in on_minor_arc
- bounds.py: keep vertex-latitude snapping (snap_tol_deg) path
- computing.py: keep detailed docstring with SIAM/EGUsphere references
Add an LLVM fma intrinsic and route two_prod through a single fused
multiply-add for its error term on hardware that supports it, selected at
import time and validated to be bit-exact against the Veltkamp split. Falls
back to the portable Veltkamp form otherwise, so there is no hard FMA
dependency.

The FMA path is ~2x faster in the compensated geometry kernels (each
two_prod drops from ~17 flops to one FMADD) and is numerically identical:
all 241 AccuSphGeom baseline cases pass unchanged.
Add _accux_constlat_scalar, which takes the arc endpoints as six scalars and
returns the candidate coordinates as scalars instead of two np.empty(3)
arrays. _accux_constlat now wraps it so the array API is unchanged.

Returning scalars lets Numba keep the candidates in registers, so a batch
loop over many edges does no per-point heap allocation. On a 16M-point
const-lat sweep this is ~2.7x faster than the array-returning path and drops
the AccuX/FP64 cost ratio from ~19x to ~7x. Bit-identical results; all 241
AccuSphGeom baseline cases pass.
@review-notebook-app

Copy link
Copy Markdown

Check out this pull request on  ReviewNB

See visual diffs & provide feedback on Jupyter Notebooks.


Powered by ReviewNB

…_bounds

# Conflicts:
#	benchmarks/geometry_kernels.py
#	test/grid/geometry/test_accusphgeom_baseline.py
#	uxarray/grid/arcs.py
#	uxarray/grid/intersections.py
#	uxarray/utils/computing.py
@cmdupuis3 cmdupuis3 added the accuracy Related to mathematical accuracy of operations, such as numerical precision or rounding errors label Oct 27, 2026
@rajeeja
rajeeja marked this pull request as ready for review November 3, 2026 21:50
@rajeeja
rajeeja requested a review from Sevans711 November 3, 2026 21:50
@Sevans711 Sevans711 added the run-benchmark Run ASV benchmark workflow label Nov 4, 2026

@Sevans711 Sevans711 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you provide more focused context/details to help me get up to speed on this without needing to read and understand the 110+ messages in #1513 together with all the background details about the AccuSphGeom work? It would be especially helpful if you can open and link an issue report which more clearly defines the limited scope of just the issue being solved in this PR.

Additionally, at first glance I'm highly suspicious of some of the changes in point_in_face.py. My guess would be that they might mess up the performance improvements from #1796 due to introducing many tiny numpy arrays (see #1648). Could you do a read-through of your changes (in that file and in other files as well) with that performance optimization principle in mind, before I take a closer look?

After you address these two major points, please feel free to ping me and/or re-request review, and then I would be happy to take a closer look!

@github-actions

github-actions Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

ASV Benchmarking

Benchmark Comparison Results

Benchmarks that have improved:

Change Before [70e73b9] After [dbe79e4] Ratio Benchmark (Parameter)
- 1.78M 393k 0.22 face_bounds.FaceBounds.track_peakmem_face_bounds(PosixPath('/home/runner/work/uxarray/uxarray/test/meshfiles/mpas/QU/oQU480.231010.nc'))
- 1.76M 373k 0.21 face_bounds.FaceBounds.track_peakmem_face_bounds(PosixPath('/home/runner/work/uxarray/uxarray/test/meshfiles/scrip/outCSne8/outCSne8.nc'))
- 1.92M 535k 0.28 face_bounds.FaceBounds.track_peakmem_face_bounds(PosixPath('/home/runner/work/uxarray/uxarray/test/meshfiles/ugrid/geoflow-small/grid.nc'))
* failed 451±4ns n/a geometry_kernels.PointInPolygonSphere.time_point_inside
* failed 460±10ns n/a geometry_kernels.PointInPolygonSphere.time_point_outside
- 2.2M 923k 0.42 subset.BoundingBoxHealpix.track_peakmem_bounding_box(6)

Benchmarks that have stayed the same:

Change Before [70e73b9] After [dbe79e4] Ratio Benchmark (Parameter)
1.05±0.07ms 1.05±0.01ms 1.00 connectivity.Connectivity.time_edge_face('120km')
328±4μs 326±6μs 0.99 connectivity.Connectivity.time_edge_face('480km')
2.40±0.05ms 2.45±0.06ms 1.02 connectivity.Connectivity.time_edge_node('120km')
756±30μs 757±20μs 1.00 connectivity.Connectivity.time_edge_node('480km')
44.3±3μs 45.0±3μs 1.02 connectivity.Connectivity.time_face_edge('120km')
41.3±6μs 41.7±5μs 1.01 connectivity.Connectivity.time_face_edge('480km')
795±40μs 755±20μs 0.95 connectivity.Connectivity.time_face_face('120km')
302±9μs 317±10μs 1.05 connectivity.Connectivity.time_face_face('480km')
43.5±4μs 44.6±10μs 1.02 connectivity.Connectivity.time_face_node('120km')
38.1±2μs 40.3±3μs 1.06 connectivity.Connectivity.time_face_node('480km')
408±50μs 372±20μs 0.91 connectivity.Connectivity.time_n_nodes_per_face('120km')
271±10μs 278±10μs 1.03 connectivity.Connectivity.time_n_nodes_per_face('480km')
914±10μs 904±20μs 0.99 connectivity.Connectivity.time_node_edge('120km')
310±9μs 312±9μs 1.01 connectivity.Connectivity.time_node_edge('480km')
52.6±0.1ms 51.8±0.4ms 0.99 connectivity.Connectivity.time_node_face('120km')
3.40±0.01ms 3.41±0.02ms 1.00 connectivity.Connectivity.time_node_face('480km')
1.42M 1.42M 1.00 connectivity.ConnectivityTracemalloc.track_peakmem_edge_face('120km')
105k 105k 1.00 connectivity.ConnectivityTracemalloc.track_peakmem_edge_face('480km')
6.48M 6.48M 1.00 connectivity.ConnectivityTracemalloc.track_peakmem_edge_node('120km')
419k 419k 1.00 connectivity.ConnectivityTracemalloc.track_peakmem_edge_node('480km')
2.05k 2.05k 1.00 connectivity.ConnectivityTracemalloc.track_peakmem_face_edge('120km')
2.05k 2.05k 1.00 connectivity.ConnectivityTracemalloc.track_peakmem_face_edge('480km')
1.6M 1.6M 1.00 connectivity.ConnectivityTracemalloc.track_peakmem_face_face('120km')
101k 101k 1.00 connectivity.ConnectivityTracemalloc.track_peakmem_face_face('480km')
2.18k 2.18k 1.00 connectivity.ConnectivityTracemalloc.track_peakmem_face_node('120km')
2.18k 2.18k 1.00 connectivity.ConnectivityTracemalloc.track_peakmem_face_node('480km')
240k 240k 1.00 connectivity.ConnectivityTracemalloc.track_peakmem_n_nodes_per_face('120km')
26k 26k 1.00 connectivity.ConnectivityTracemalloc.track_peakmem_n_nodes_per_face('480km')
1.9M 1.9M 1.00 connectivity.ConnectivityTracemalloc.track_peakmem_node_edge('120km')
127k 127k 1.00 connectivity.ConnectivityTracemalloc.track_peakmem_node_edge('480km')
11.9M 11.9M 1.00 connectivity.ConnectivityTracemalloc.track_peakmem_node_face('120km')
747k 747k 1.00 connectivity.ConnectivityTracemalloc.track_peakmem_node_face('480km')
4.53±0.09ms 1.98±0.08ms ~0.44 face_bounds.FaceBounds.time_face_bounds(PosixPath('/home/runner/work/uxarray/uxarray/test/meshfiles/mpas/QU/oQU480.231010.nc'))
1.32±0.03ms 1.06±0.09ms ~0.80 face_bounds.FaceBounds.time_face_bounds(PosixPath('/home/runner/work/uxarray/uxarray/test/meshfiles/scrip/outCSne8/outCSne8.nc'))
5.46±0.09ms 1.80±0.04ms ~0.33 face_bounds.FaceBounds.time_face_bounds(PosixPath('/home/runner/work/uxarray/uxarray/test/meshfiles/ugrid/geoflow-small/grid.nc'))
723±20μs 635±30μs ~0.88 face_bounds.FaceBounds.time_face_bounds(PosixPath('/home/runner/work/uxarray/uxarray/test/meshfiles/ugrid/quad-hexagon/grid.nc'))
57.3k 57.3k 1.00 face_bounds.FaceBounds.track_nbytes_face_bounds(PosixPath('/home/runner/work/uxarray/uxarray/test/meshfiles/mpas/QU/oQU480.231010.nc'))
12.3k 12.3k 1.00 face_bounds.FaceBounds.track_nbytes_face_bounds(PosixPath('/home/runner/work/uxarray/uxarray/test/meshfiles/scrip/outCSne8/outCSne8.nc'))
123k 123k 1.00 face_bounds.FaceBounds.track_nbytes_face_bounds(PosixPath('/home/runner/work/uxarray/uxarray/test/meshfiles/ugrid/geoflow-small/grid.nc'))
128 128 1.00 face_bounds.FaceBounds.track_nbytes_face_bounds(PosixPath('/home/runner/work/uxarray/uxarray/test/meshfiles/ugrid/quad-hexagon/grid.nc'))
1.27M 1.27M 1.00 face_bounds.FaceBounds.track_nbytes_grid_with_bounds(PosixPath('/home/runner/work/uxarray/uxarray/test/meshfiles/mpas/QU/oQU480.231010.nc'))
50.1k 50.1k 1.00 face_bounds.FaceBounds.track_nbytes_grid_with_bounds(PosixPath('/home/runner/work/uxarray/uxarray/test/meshfiles/scrip/outCSne8/outCSne8.nc'))
516k 516k 1.00 face_bounds.FaceBounds.track_nbytes_grid_with_bounds(PosixPath('/home/runner/work/uxarray/uxarray/test/meshfiles/ugrid/geoflow-small/grid.nc'))
712 712 1.00 face_bounds.FaceBounds.track_nbytes_grid_with_bounds(PosixPath('/home/runner/work/uxarray/uxarray/test/meshfiles/ugrid/quad-hexagon/grid.nc'))
35.3k 36.5k 1.03 face_bounds.FaceBounds.track_peakmem_face_bounds(PosixPath('/home/runner/work/uxarray/uxarray/test/meshfiles/ugrid/quad-hexagon/grid.nc'))
1.04±0.05μs 1.02±0.05μs 0.98 geometry_kernels.AccucrossKernels.time_accucross
2.32±0.06μs 2.42±0.03μs 1.04 geometry_kernels.AccucrossKernels.time_accucross_pair
305±10ns 316±10ns 1.03 geometry_kernels.EFTPrimitives.time_acc_sqrt_re
296±20ns 301±9ns 1.02 geometry_kernels.EFTPrimitives.time_diff_of_products
260±10ns 251±6ns 0.96 geometry_kernels.EFTPrimitives.time_two_prod
251±9ns 261±10ns 1.04 geometry_kernels.EFTPrimitives.time_two_sum
420±5ns 426±20ns 1.01 geometry_kernels.GCAConstLatIntersection.time_accux_constlat_kernel
516±5ns 541±9ns 1.05 geometry_kernels.GCAConstLatIntersection.time_gca_const_lat_intersection
510±8ns 516±10ns 1.01 geometry_kernels.GCAConstLatIntersection.time_try_gca_const_lat_intersection
606±40ns 574±20ns 0.95 geometry_kernels.GCAGCAIntersection.time_accux_gca_kernel
810±40ns 807±30ns 1.00 geometry_kernels.GCAGCAIntersection.time_gca_gca_intersection
890±20ns 834±30ns 0.94 geometry_kernels.GCAGCAIntersection.time_try_gca_gca_intersection
24.3±0.3μs 24.8±0.4μs 1.02 geometry_kernels.OrientPredicates.time_on_minor_arc
24.5±0.4μs 25.6±0.9μs 1.04 geometry_kernels.OrientPredicates.time_orient3d_on_sphere
2.89±0.04ms 2.92±0ms 1.01 geometry_samebody.SameBodyConstLat.time_accux_dispatch
641±4μs 622±20μs 0.97 geometry_samebody.SameBodyConstLat.time_accux_kernel
2.84±0.02ms 2.80±0ms 0.99 geometry_samebody.SameBodyConstLat.time_fp64_dispatch
92.9±2μs 91.4±0.3μs 0.98 geometry_samebody.SameBodyConstLat.time_fp64_kernel
48.2±0.1ms 48.0±0.1ms 1.00 geometry_samebody_gcagca.SameBodyGcaGca.time_accux_dispatch
5.22±0.04ms 5.26±0.05ms 1.01 geometry_samebody_gcagca.SameBodyGcaGca.time_accux_kernel
44.2±0.2ms 44.2±0.1ms 1.00 geometry_samebody_gcagca.SameBodyGcaGca.time_fp64_dispatch
613±10μs 633±9μs 1.03 geometry_samebody_gcagca.SameBodyGcaGca.time_fp64_kernel
827±9ms 817±6ms 0.99 import.Imports.timeraw_import_uxarray
1 1 1.00 lazy_grid_construction.LazyGridConstruction.track_computes_isel
3 3 1.00 lazy_grid_construction.LazyGridConstruction.track_computes_open_grid_chunked
71.9±1ms 73.4±4ms 1.02 lazy_grid_construction.OpenGridChunked.time_open_grid('120km')
89.6±2ms 95.4±3ms 1.06 lazy_grid_construction.OpenGridChunked.time_open_grid('480km')
3.42M 3.21M 0.94 lazy_grid_construction.OpenGridChunked.track_peakmem_open_grid('120km')
2.43M 2.42M 0.99 lazy_grid_construction.OpenGridChunked.track_peakmem_open_grid('480km')
2.18±0.01ms 2.25±0.04ms 1.03 mpas_ocean.AzimuthalAverage.time_azimuthal_average('120km')
964±9μs 973±10μs 1.01 mpas_ocean.AzimuthalAverage.time_azimuthal_average('480km')
1.37±0.04ms 1.45±0.02ms 1.06 mpas_ocean.CheckNorm.time_check_norm('120km')
991±20μs 1.07±0.01ms 1.08 mpas_ocean.CheckNorm.time_check_norm('480km')
575±20μs 613±20μs 1.07 mpas_ocean.ConnectivityConstruction.time_face_face_connectivity('120km')
285±4μs 277±10μs 0.97 mpas_ocean.ConnectivityConstruction.time_face_face_connectivity('480km')
391±10μs 444±30μs ~1.14 mpas_ocean.ConnectivityConstruction.time_n_nodes_per_face('120km')
306±5μs 294±3μs 0.96 mpas_ocean.ConnectivityConstruction.time_n_nodes_per_face('480km')
4.17±0.05ms 4.14±0.01ms 0.99 mpas_ocean.ConstructFaceLatLon.time_cartesian_averaging('120km')
3.09±0.01ms 3.10±0.02ms 1.00 mpas_ocean.ConstructFaceLatLon.time_cartesian_averaging('480km')
111±0.6ms 112±0.8ms 1.00 mpas_ocean.ConstructFaceLatLon.time_welzl('120km')
9.73±0.07ms 9.80±0.1ms 1.01 mpas_ocean.ConstructFaceLatLon.time_welzl('480km')
9.75±0.06ms 9.69±0.02ms 0.99 mpas_ocean.ConstructTreeStructures.time_ball_tree('120km')
594±10μs 597±20μs 1.00 mpas_ocean.ConstructTreeStructures.time_ball_tree('480km')
6.99±0.08ms 6.83±0.01ms 0.98 mpas_ocean.ConstructTreeStructures.time_kd_tree('120km')
412±8μs 416±10μs 1.01 mpas_ocean.ConstructTreeStructures.time_kd_tree('480km')
322±5ms 332±10ms 1.03 mpas_ocean.CrossSections.time_const_lat('120km', 1)
165±2ms 174±10ms 1.05 mpas_ocean.CrossSections.time_const_lat('120km', 2)
83.9±1ms 90.5±1ms 1.08 mpas_ocean.CrossSections.time_const_lat('120km', 4)
281±6ms 288±3ms 1.02 mpas_ocean.CrossSections.time_const_lat('480km', 1)
138±2ms 140±0.8ms 1.01 mpas_ocean.CrossSections.time_const_lat('480km', 2)
73.2±6ms 74.5±2ms 1.02 mpas_ocean.CrossSections.time_const_lat('480km', 4)
28.7±0.2ms 28.5±0.1ms 0.99 mpas_ocean.DualMesh.time_dual_mesh_construction('120km')
3.28±0.02ms 3.25±0.06ms 0.99 mpas_ocean.DualMesh.time_dual_mesh_construction('480km')
9.90±0.2ms 10.2±0.5ms 1.03 mpas_ocean.FaceAreas.time_face_areas('120km')
3.36±0.07ms 3.38±0.1ms 1.01 mpas_ocean.FaceAreas.time_face_areas('480km')
229k 229k 1.00 mpas_ocean.FaceAreas.track_nbytes_face_areas('120km')
14.3k 14.3k 1.00 mpas_ocean.FaceAreas.track_nbytes_face_areas('480km')
2.12M 2.12M 1.00 mpas_ocean.FaceAreas.track_peakmem_face_areas('120km')
679k 679k 1.00 mpas_ocean.FaceAreas.track_peakmem_face_areas('480km')
33.9±0.7ms 37.2±0.6ms 1.10 mpas_ocean.GeoDataFrame.time_to_geodataframe('120km', 'exclude')
89.4±2ms 94.3±0.9ms 1.05 mpas_ocean.GeoDataFrame.time_to_geodataframe('120km', 'split')
3.71±0.1ms 4.30±0.6ms ~1.16 mpas_ocean.GeoDataFrame.time_to_geodataframe('480km', 'exclude')
16.3±0.3ms 17.9±0.3ms 1.10 mpas_ocean.GeoDataFrame.time_to_geodataframe('480km', 'split')
9.58±0.08ms 10.4±0.2ms 1.08 mpas_ocean.Gradient.time_gradient('120km')
1.55±0.02ms 1.58±0.02ms 1.02 mpas_ocean.Gradient.time_gradient('480km')
457k 457k 1.00 mpas_ocean.Gradient.track_nbytes_gradient('120km')
28.7k 28.7k 1.00 mpas_ocean.Gradient.track_nbytes_gradient('480km')
3.44M 3.44M 1.00 mpas_ocean.Gradient.track_peakmem_gradient('120km')
226k 226k 1.00 mpas_ocean.Gradient.track_peakmem_gradient('480km')
271±9μs 261±10μs 0.96 mpas_ocean.HoleEdgeIndices.time_construct_hole_edge_indices('120km')
115±4μs 113±2μs 0.98 mpas_ocean.HoleEdgeIndices.time_construct_hole_edge_indices('480km')
115±2μs 136±3μs ~1.19 mpas_ocean.Integrate.time_integrate('120km')
96.4±1μs 99.5±0.7μs 1.03 mpas_ocean.Integrate.time_integrate('480km')
18.4M 18.4M 1.00 mpas_ocean.Integrate.track_nbytes_integrate('120km')
1.2M 1.2M 1.00 mpas_ocean.Integrate.track_nbytes_integrate('480km')
108±2ms 111±4ms 1.03 mpas_ocean.MatplotlibConversion.time_dataarray_to_polycollection('120km', 'exclude')
106±1ms 106±0.9ms 1.01 mpas_ocean.MatplotlibConversion.time_dataarray_to_polycollection('120km', 'include')
105±1ms 108±0.8ms 1.03 mpas_ocean.MatplotlibConversion.time_dataarray_to_polycollection('120km', 'split')
7.88±0.09ms 8.24±0.6ms 1.05 mpas_ocean.MatplotlibConversion.time_dataarray_to_polycollection('480km', 'exclude')
7.69±0.08ms 7.82±0.1ms 1.02 mpas_ocean.MatplotlibConversion.time_dataarray_to_polycollection('480km', 'include')
7.91±0.2ms 7.80±0.1ms 0.99 mpas_ocean.MatplotlibConversion.time_dataarray_to_polycollection('480km', 'split')
166±2ms 164±3ms 0.99 mpas_ocean.NeighborhoodBuild.time_build('120km', 1.0)
343±3ms 350±6ms 1.02 mpas_ocean.NeighborhoodBuild.time_build('120km', 5.0)
9.02±0.05ms 9.13±0.2ms 1.01 mpas_ocean.NeighborhoodBuild.time_build('480km', 1.0)
11.1±0.2ms 11.0±0.3ms 0.99 mpas_ocean.NeighborhoodBuild.time_build('480km', 5.0)
163±4ms 162±0.9ms 1.00 mpas_ocean.NeighborhoodBuild.time_query_radius('120km', 1.0)
346±3ms 348±3ms 1.01 mpas_ocean.NeighborhoodBuild.time_query_radius('120km', 5.0)
8.48±0.08ms 8.56±0.08ms 1.01 mpas_ocean.NeighborhoodBuild.time_query_radius('480km', 1.0)
10.9±0.2ms 10.7±0.02ms 0.98 mpas_ocean.NeighborhoodBuild.time_query_radius('480km', 5.0)
612.76 612.76 1.00 mpas_ocean.NeighborhoodBuild.track_mean_neighbors('120km', 15.0)
74.17 74.17 1.00 mpas_ocean.NeighborhoodBuild.track_mean_neighbors('120km', 5.0)
37.29 37.29 1.00 mpas_ocean.NeighborhoodBuild.track_mean_neighbors('480km', 15.0)
6.57 6.57 1.00 mpas_ocean.NeighborhoodBuild.track_mean_neighbors('480km', 5.0)
141M 141M 1.00 mpas_ocean.NeighborhoodBuild.track_nbytes_neighbors('120km', 15.0)
17.4M 17.4M 1.00 mpas_ocean.NeighborhoodBuild.track_nbytes_neighbors('120km', 5.0)
563k 563k 1.00 mpas_ocean.NeighborhoodBuild.track_nbytes_neighbors('480km', 15.0)
123k 123k 1.00 mpas_ocean.NeighborhoodBuild.track_nbytes_neighbors('480km', 5.0)
145M 145M 1.00 mpas_ocean.NeighborhoodBuild.track_peakmem_build('120km', 15.0)
21.5M 21.5M 1.00 mpas_ocean.NeighborhoodBuild.track_peakmem_build('120km', 5.0)
824k 824k 1.00 mpas_ocean.NeighborhoodBuild.track_peakmem_build('480km', 15.0)
384k 384k 1.00 mpas_ocean.NeighborhoodBuild.track_peakmem_build('480km', 5.0)
26.7±0.4ms 26.6±1ms 1.00 mpas_ocean.NeighborhoodDask.time_mean('120km', 'grid_chunks')
10.7±0.3ms 11.2±0.2ms 1.05 mpas_ocean.NeighborhoodDask.time_mean('120km', 'numpy')
23.2±0.5ms 23.7±0.4ms 1.02 mpas_ocean.NeighborhoodDask.time_mean('120km', 'time_chunks')
5.45±0.09ms 5.52±0.05ms 1.01 mpas_ocean.NeighborhoodDask.time_mean('480km', 'grid_chunks')
338±40μs 318±7μs 0.94 mpas_ocean.NeighborhoodDask.time_mean('480km', 'numpy')
3.84±0.09ms 3.63±0.04ms 0.94 mpas_ocean.NeighborhoodDask.time_mean('480km', 'time_chunks')
5.75M 5.82M 1.01 mpas_ocean.NeighborhoodDask.track_peakmem_mean('120km', 'grid_chunks')
2.75M 2.75M 1.00 mpas_ocean.NeighborhoodDask.track_peakmem_mean('120km', 'numpy')
5.68M 5.67M 1.00 mpas_ocean.NeighborhoodDask.track_peakmem_mean('120km', 'time_chunks')
635k 676k 1.06 mpas_ocean.NeighborhoodDask.track_peakmem_mean('480km', 'grid_chunks')
177k 177k 1.00 mpas_ocean.NeighborhoodDask.track_peakmem_mean('480km', 'numpy')
528k 528k 1.00 mpas_ocean.NeighborhoodDask.track_peakmem_mean('480km', 'time_chunks')
3.13±0.06s 3.06±0.02s 0.98 mpas_ocean.NeighborhoodReduce.time_dataset_reduce('120km', 'mean')
3.21±0.02s 3.18±0.03s 0.99 mpas_ocean.NeighborhoodReduce.time_dataset_reduce('120km', 'median')
81.6±3ms 82.7±1ms 1.01 mpas_ocean.NeighborhoodReduce.time_dataset_reduce('480km', 'mean')
82.4±2ms 84.3±0.5ms 1.02 mpas_ocean.NeighborhoodReduce.time_dataset_reduce('480km', 'median')
351±7ms 343±2ms 0.98 mpas_ocean.NeighborhoodReduce.time_neighborhood_reduce('120km', 'mean')
369±5ms 367±0.8ms 1.00 mpas_ocean.NeighborhoodReduce.time_neighborhood_reduce('120km', 'median')
11.2±0.3ms 11.5±0.3ms 1.03 mpas_ocean.NeighborhoodReduce.time_neighborhood_reduce('480km', 'mean')
11.5±0.3ms 11.8±0.2ms 1.02 mpas_ocean.NeighborhoodReduce.time_neighborhood_reduce('480km', 'median')
2.39±0.03ms 2.46±0.02ms 1.03 mpas_ocean.NeighborhoodReduce.time_reduce('120km', 'mean')
26.9±0.6ms 26.5±0.3ms 0.98 mpas_ocean.NeighborhoodReduce.time_reduce('120km', 'median')
113±2μs 111±2μs 0.98 mpas_ocean.NeighborhoodReduce.time_reduce('480km', 'mean')
335±5μs 360±70μs 1.07 mpas_ocean.NeighborhoodReduce.time_reduce('480km', 'median')
234k 234k 1.00 mpas_ocean.NeighborhoodReduce.track_peakmem_reduce('120km', 'mean')
235k 235k 1.00 mpas_ocean.NeighborhoodReduce.track_peakmem_reduce('120km', 'median')
19.5k 19.5k 1.00 mpas_ocean.NeighborhoodReduce.track_peakmem_reduce('480km', 'mean')
19.6k 19.6k 1.00 mpas_ocean.NeighborhoodReduce.track_peakmem_reduce('480km', 'median')
363±10μs 356±7μs 0.98 mpas_ocean.PointInPolygon.time_face_search_lonlat('120km')
347±7μs 342±6μs 0.98 mpas_ocean.PointInPolygon.time_face_search_lonlat('480km')
341±9μs 337±5μs 0.99 mpas_ocean.PointInPolygon.time_face_search_xyz('120km')
310±30μs 321±9μs 1.04 mpas_ocean.PointInPolygon.time_face_search_xyz('480km')
59.0±0.5ms 59.9±0.2ms 1.01 mpas_ocean.RemapDownsample.time_bilinear_remapping
10.4±0.2ms 10.7±0.2ms 1.02 mpas_ocean.RemapDownsample.time_inverse_distance_weighted_remapping
9.61±0.2ms 9.73±0.2ms 1.01 mpas_ocean.RemapDownsample.time_nearest_neighbor_remapping
560±3ms 561±4ms 1.00 mpas_ocean.RemapUpsample.time_bilinear_remapping
19.1±0.5ms 18.2±0.1ms 0.95 mpas_ocean.RemapUpsample.time_inverse_distance_weighted_remapping
7.92±0.03ms 7.86±0.02ms 0.99 mpas_ocean.RemapUpsample.time_nearest_neighbor_remapping
4.48±0.09ms 4.65±0.1ms 1.04 mpas_ocean.ZonalAverage.time_zonal_average('120km')
2.59±0.02ms 2.72±0.03ms 1.05 mpas_ocean.ZonalAverage.time_zonal_average('480km')
0.9980828376804379 1.0320421165154754 1.03 nogil_scaling.GILScaling.track_gil_scaling
1.24±0.02ms 1.25±0.02ms 1.01 open_dataset.OpenDataset.time_open_dataset('dataset', 'dataset')
2.22±0.02ms 2.35±0.03ms 1.06 open_dataset.OpenDataset.time_open_dataset('dataset', 'file')
4.71±0.01ms 4.89±0.09ms 1.04 open_dataset.OpenDataset.time_open_dataset('file', 'dataset')
5.70±0.09ms 5.70±0.04ms 1.00 open_dataset.OpenDataset.time_open_dataset('file', 'file')
192±4μs 270±40μs ~1.41 open_dataset.OpenDataset.time_open_dataset('grid', 'dataset')
1.13±0.01ms 1.16±0.04ms 1.02 open_dataset.OpenDataset.time_open_dataset('grid', 'file')
1.22±0.01s 1.31±0.02s 1.07 plots.PlotContour.time_contour_projected
222±1ms 215±4ms 0.97 plots.PlotHealpix.time_default_plot(6)
2.07±0.01s 2.05±0.01s 0.99 plots.PlotHealpix.time_default_plot(8)
28M 28M 1.00 plots.PlotHealpix.track_peakmem_default_plot(6)
443M 443M 1.00 plots.PlotHealpix.track_peakmem_default_plot(8)
5.17±0.04ms 5.31±0.06ms 1.03 quad_hexagon.QuadHexagon.time_open_dataset
4.45±0.2ms 4.49±0.02ms 1.01 quad_hexagon.QuadHexagon.time_open_grid
408 408 1.00 quad_hexagon.QuadHexagon.track_nbytes_open_dataset
392 392 1.00 quad_hexagon.QuadHexagon.track_nbytes_open_grid
71.7k 71.8k 1.00 quad_hexagon.QuadHexagon.track_peakmem_open_dataset
71.5k 71.5k 1.00 quad_hexagon.QuadHexagon.track_peakmem_open_grid
6.07±0.2ms 6.38±0.4ms 1.05 subset.BoundingBox.time_bounding_box('120km')
3.61±0.2ms 3.44±0.1ms 0.95 subset.BoundingBox.time_bounding_box('480km')
2.38M 2.38M 1.00 subset.BoundingBox.track_peakmem_bounding_box('120km')
203k 203k 1.00 subset.BoundingBox.track_peakmem_bounding_box('480km')
2.74±0.05ms 2.54±0.03ms 0.93 subset.BoundingBoxHealpix.time_bounding_box(6)
11.5±0.2ms 10.0±0.2ms ~0.87 subset.BoundingBoxHealpix.time_bounding_box(8)
13.2M 13.1M 0.99 subset.BoundingBoxHealpix.track_peakmem_bounding_box(8)
638±5ms 629±2ms 0.99 to_raster.ToRaster.time_to_raster((10000.0, 10.0))
1.35±0.01s 1.31±0.01s 0.97 to_raster.ToRaster.time_to_raster((10000.0, 100.0))
1.58±0s 1.56±0.01s 0.99 to_raster.ToRaster.time_to_raster((100000.0, 100.0))
270M 270M 1.00 to_raster.ToRaster.track_peakmem((10000.0, 10.0))
680M 680M 1.00 to_raster.ToRaster.track_peakmem((10000.0, 100.0))
765M 765M 1.00 to_raster.ToRaster.track_peakmem((100000.0, 100.0))
56.1±4μs 60.3±1μs 1.07 to_xarray.UxDataArrayToXarray.time_to_xarray(10)
190±6μs 192±4μs 1.01 to_xarray.UxDatasetToXarray.time_to_xarray((100, 10))
1.75±0.01ms 1.77±0.05ms 1.01 to_xarray.UxDatasetToXarray.time_to_xarray((1000, 100))
436±8μs 431±20μs 0.99 to_xarray.UxDatasetToXarray.time_to_xarray_healpix((100, 10))
3.90±0.04ms 3.93±0.04ms 1.01 to_xarray.UxDatasetToXarray.time_to_xarray_healpix((1000, 100))

Benchmarks that have got worse:

Change Before [70e73b9] After [dbe79e4] Ratio Benchmark (Parameter)
+ 305M 401M 1.31 face_bounds.FaceBoundsColdStartRss.track_peakmem_open_and_bounds(PosixPath('/home/runner/work/uxarray/uxarray/test/meshfiles/mpas/QU/oQU480.231010.nc'))
+ 307M 401M 1.31 face_bounds.FaceBoundsColdStartRss.track_peakmem_open_and_bounds(PosixPath('/home/runner/work/uxarray/uxarray/test/meshfiles/scrip/outCSne8/outCSne8.nc'))
+ 309M 401M 1.3 face_bounds.FaceBoundsColdStartRss.track_peakmem_open_and_bounds(PosixPath('/home/runner/work/uxarray/uxarray/test/meshfiles/ugrid/geoflow-small/grid.nc'))
+ 306M 401M 1.31 face_bounds.FaceBoundsColdStartRss.track_peakmem_open_and_bounds(PosixPath('/home/runner/work/uxarray/uxarray/test/meshfiles/ugrid/quad-hexagon/grid.nc'))
+ 1.70±0.03ms 1.94±0.03ms 1.14 geometry_kernels.PointInFaceNodes.time_repeated_queries
+ 280M 399M 1.43 import.Imports.track_peakmem_import_uxarray
+ 326M 399M 1.22 mpas_ocean.CrossSectionsPeakMem.track_peakmem_const_lat('120km', 1)
+ 326M 399M 1.22 mpas_ocean.CrossSectionsPeakMem.track_peakmem_const_lat('120km', 2)
+ 326M 399M 1.22 mpas_ocean.CrossSectionsPeakMem.track_peakmem_const_lat('120km', 4)
+ 308M 399M 1.3 mpas_ocean.CrossSectionsPeakMem.track_peakmem_const_lat('480km', 1)
+ 308M 399M 1.3 mpas_ocean.CrossSectionsPeakMem.track_peakmem_const_lat('480km', 2)
+ 307M 399M 1.3 mpas_ocean.CrossSectionsPeakMem.track_peakmem_const_lat('480km', 4)
+ 324M 401M 1.24 mpas_ocean.GradientColdStartRss.track_peakmem_gradient('120km')
+ 301M 401M 1.33 mpas_ocean.GradientColdStartRss.track_peakmem_gradient('480km')
+ 328M 401M 1.22 mpas_ocean.ZonalAveragePeakMem.track_peakmem_zonal_average('120km')
+ 310M 401M 1.29 mpas_ocean.ZonalAveragePeakMem.track_peakmem_zonal_average('480km')

@rajeeja
rajeeja requested a review from Sevans711 November 5, 2026 19:38
@Sevans711

Copy link
Copy Markdown
Collaborator

@rajeeja (replying now because you clicked the button to re-request my review) please provide this context and then I would be happy to review:

Could you provide more focused context/details to help me get up to speed on this without needing to read and understand the 110+ messages in # 1513 together with all the background details about the AccuSphGeom work? It would be especially helpful if you can open and link an issue report which more clearly defines the limited scope of just the issue being solved in this PR.

@cmdupuis3 cmdupuis3 left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm breaking my review down into batches, because there are some issues with the original C++ code. This batch of issues only appears in the ported code, so they mostly refer to things that are correct in the C++ (one issue is wrong in different ways). Suggestion snippets are included, but you probably have a better idea of what to do.

1, 2) Edge tolerance and winding denominator: on_minor_arc is called with an absolute tolerance of 1e-10, but the quantities it compares scale with sin L for an edge of length L. Points within 1e-10 / sin L radians of an edge, or that far past its endpoints, therefore count as on the edge: 6.4 m on 640 m edges, 64 m on 64 m edges. On an edge shorter than 1e-10 rad (0.6 mm, e.g. between near-duplicate nodes), every point on the sphere counts as on the edge: all 3,000 random test points, up to 178° away. The C++ edge test is exact. On 111 m triangles, a point 25 m inside one triangle is returned in 3 faces. On a 0.001° quad grid, 2,111 of 3,000 random points land in 2 or more faces. Scaling the tolerance by |a×b| is not enough on its own. First, on_minor_arc computes q·b − (a·b)(q·a) and q·a − (a·b)(q·b) in plain float, where they cancel to a few ulp, so a scaled tolerance needs an absolute floor f, and that floor is again a band of f / sin L: with f = 16 eps, 0.2° on a 1e-12 rad edge and up to 178° on a 1e-14 rad edge. Second, it exposes the plain-float winding denominator a·b − (q·a)(q·b): it cancels near vertices (170 of 24,000 wrong against exact arithmetic), and its sign depends on |q| (|q| = 1−1e-8 puts most interior points of a 1 km face outside). Fix: replace on_minor_arc with its three tests computed from the compensated accucross products the loop already has: (a×b)·q, −(q×a)·(a×b) = q·b − (a·b)(q·a), and (q×b)·(a×b) = q·a − (a·b)(q·b). Each is |a×b| times the sine of an angle, so comparing them with 1e-12·|a×b| gives a band of 1e-12 rad (6 µm) at every edge length, with no floor. Use the denominator (q×a)·(q×b) from the same products. Result: 0 wrong out of 192,000 near-boundary cases checked against exact arithmetic, no false on-edge hits for edges of 1e-16 to 1e-8 rad, every on-edge point of outCSne30, ICON, oQU480 and fesom still found, and queries opposite a vertex no longer return inside (555 of 4,000 before). Cost: none; the kernel is 3–10% faster than the PR's, because on_minor_arc is no longer called.

_EDGE_TOL_RAD = 1e-12                                # band half-width in radians, at any edge length

@njit(cache=True, inline="always")
def _dot_hilo(ax, ay, az, alx, aly, alz, bx, by, bz, blx, bly, blz):
    """(a_hi + a_lo) . (b_hi + b_lo) for two accucross results; a_lo . b_lo is O(eps^2) and dropped."""
    return _normal_dot_value(ax, ay, az, alx, aly, alz, bx, by, bz) + (ax * blx + ay * bly + az * blz)

@njit(cache=True, inline="always")
def _on_edge(orient, nx, ny, nz, lx, ly, lz, ux, uy, uz, ulx, uly, ulz, vx, vy, vz, vlx, vly, vlz):
    """q within _EDGE_TOL_RAD of the minor arc a -> b, given n = a x b, u = q x a, v = q x b, orient = n . q.
    Each test is |n| * sin(angle), so one tolerance scaled by |n| is an angle at every edge length."""
    norm = math.sqrt(nx * nx + ny * ny + nz * nz)
    if not norm > 0.0:                               # repeated nodes: no great circle
        return False
    tol = _EDGE_TOL_RAD * norm
    if abs(orient) > tol:                            # off the great circle
        return False
    if -_dot_hilo(ux, uy, uz, ulx, uly, ulz, nx, ny, nz, lx, ly, lz) < -tol:    # q.b - (a.b)(q.a) < 0: before a
        return False
    return _dot_hilo(vx, vy, vz, vlx, vly, vlz, nx, ny, nz, lx, ly, lz) >= -tol  # q.a - (a.b)(q.b) >= 0: not past b

i0 = 0 if nodes_idx is None else nodes_idx[0]
ux, uy, uz, ulx, uly, ulz = accucross(q[0], q[1], q[2], node_x[i0], node_y[i0], node_z[i0])
winding = 0.0
for i in range(n):
    ...
    nx, ny, nz, lx, ly, lz = accucross(a[0], a[1], a[2], b[0], b[1], b[2])
    numerator = _normal_dot_value(nx, ny, nz, lx, ly, lz, q[0], q[1], q[2])
    vx, vy, vz, vlx, vly, vlz = accucross(q[0], q[1], q[2], b[0], b[1], b[2])
    if _on_edge(numerator, nx, ny, nz, lx, ly, lz, ux, uy, uz, ulx, uly, ulz, vx, vy, vz, vlx, vly, vlz):
        return _LOC_ON_EDGE                          # replaces on_minor_arc(q, a, b, 1e-10)
    denominator = _dot_hilo(ux, uy, uz, ulx, uly, ulz, vx, vy, vz, vlx, vly, vlz)   # (q x a) . (q x b)
    winding += math.atan2(numerator, denominator)
    ux, uy, uz, ulx, uly, ulz = vx, vy, vz, vlx, vly, vlz
  1. Unnormalized query points: get_faces_containing_point passes Cartesian input through as given, but the k-d tree radius and the tolerances assume unit vectors. With scaled input (×0.5, ×2, or metres), 0 of 500 face centres on oQU480 are found. Main also fails gross scaling; the PR adds sensitivity to |q| at the 1e-8 level. Fix: normalize each row in _point_in_face_query, leaving zero and NaN rows as they are. Result: 500/500 found. Cost: about 3 ms per 200k points.
norms = np.linalg.norm(pts, axis=1, keepdims=True)
pts = np.divide(pts, norms, out=pts.copy(), where=norms > 0)
  1. Batch result overflow: The result array has n_max_face_nodes columns per point, but a node can have more faces than that (6 on triangle meshes, with 3 columns). The kernel writes past the row without a bounds check, overwriting the next point's results. This is pre-existing for queries exactly on nodes: on ICON, 0 of 205 node queries come back correct. The wide edge band (1 + 2) makes it hit ordinary points: on a 0.001° triangle grid, 8,818 of 20,000 rows overflow and 8 come back with faces 27 cells away. Fix: skip the write once the row is full but keep counting, then re-run only the overflowing rows with enough columns. Result: 205/205 correct. Cost: about 40% extra only when queries are all at nodes.
if _point_in_face(point, nodes_idx, node_x, node_y, node_z):
    if count < width:          # numba doesn't check bounds: never write past the row
        result[i, count] = fidx
    count += 1                 # the count stays exact
face_indices, counts = _batch_point_in_face(pts, flat_cands, offs, *grid_arrays, width)
over = np.flatnonzero(counts > width)
if over.size:                  # re-run only the rows that overflowed, wide enough to hold every hit
    wide = int(counts[over].max())
    ...
    sub_indices, _ = _batch_point_in_face(pts[over], sub_cands, sub_offs, *grid_arrays, wide)
    padded = np.full((counts.size, wide), INT_FILL_VALUE, dtype=INT_DTYPE)
    padded[:, :width] = face_indices
    padded[over] = sub_indices
    face_indices = padded
  1. Only one pole checked per face: A face reaching both 80° caps is labelled north only, so the south pole is never tested; the C++ tests both. For a face past 80°N that wraps the south pole, the PR gives latitude [−82.4°, 85°] and longitude [240°, 120°] instead of [−90°, 85°] and the full circle. Fix: make the labels bit flags and test each pole the face reaches. This is safe in the port because its winding test handles antipodes. In the C++, testing both poles wrongly gives every south-polar face a latitude range ending at 90°, which is worth reporting upstream. Bounds are unchanged on all 22 test meshes.
label = _FACE_LOC_LOCAL
if z_max >= polar_cap_z:
    label |= _FACE_LOC_NORTH_POLAR
if z_min <= -polar_cap_z:
    label |= _FACE_LOC_SOUTH_POLAR
...
north_loc = _point_in_polygon_sphere(_NORTH_POLE, face_vertices) if label & _FACE_LOC_NORTH_POLAR else _LOC_OUTSIDE
south_loc = _point_in_polygon_sphere(_SOUTH_POLE, face_vertices) if label & _FACE_LOC_SOUTH_POLAR else _LOC_OUTSIDE
  1. Normalization check: The new bounds path reads z as sin(latitude), so node coordinates must be unit vectors. _check_normalization takes abs(max(...)) instead of max(abs(...)), so a grid whose vectors are all too short passes and is never normalized. On mixed.exo (vector lengths 0.967–1.0), 81 faces get latitude bounds that exclude their own nodes, by up to 4.99°; main has none. Fix: take the absolute value before the max, and set the tolerance to max(1e-8, 8 × machine epsilon of the coordinate dtype). Without the second part, float32 grids such as quad-hexagon fail the check, get renormalized partway through, and break test_face_node_angles_hexagons_and_pentagons. Bounds on the other 21 test meshes are unchanged.
max_dev = abs(x**2 + y**2 + z**2 - 1.0).max().compute()    # abs before max
tol = max(ERROR_TOLERANCE, 8.0 * np.finfo(x.dtype).eps)    # judge against the stored precision
if max_dev > tol:

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

Labels

accuracy Related to mathematical accuracy of operations, such as numerical precision or rounding errors run-benchmark Run ASV benchmark workflow

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants