Repository navigation
Conversation
…rite intersections, add 241 baseline testsgit status! - most came from accusphere
…us/mask, dispatcher
- 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
…us/mask, dispatcher
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.
|
Check out this pull request on 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
Sevans711
left a comment
There was a problem hiding this comment.
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!
ASV BenchmarkingBenchmark Comparison ResultsBenchmarks that have improved:
Benchmarks that have stayed the same:
Benchmarks that have got worse:
|
|
@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:
|
There was a problem hiding this comment.
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- 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)- 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 exactface_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- 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- 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:
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.