Closed
Labels
new featureNew user-facing functionality
Description
Proposed new feature or change:
This would have the same shape as face_node_connectivity: for every face, for every node in that face, this tells the angle at that node.
Computing angles is necessary for computing one common measure of grid skewness. Related: #1305.
There are a few different possible ways to get the result, so I'm not sure if this should be a cached property or a function with a few optional flags:
- should the result be in radians or degrees?
- should the computation use 'euclidean' / flat geometry (sum of angles of a triangle is always 180 degrees) or respect the 'spherical' geometry (sum of angles of a triangle is always larger than 180 degrees)?
What are the best defaults for those flags?
Also, perhaps grid.face_node_angles(geometry=...) should dispatch to face_node_angles_flat or face_node_angles_spherical properties (whose results should be cached)?
Metadata
Metadata
Assignees
Labels
new featureNew user-facing functionality
Type
Fields
Priority
None yet
Projects
- StatusShow more project fields✅ Done
Activity
Sevans711 commentedon Jul 14, 2026
Pinging @rajeeja in case you have thoughts or advice on this!
rajeeja commentedon Jul 14, 2026
Hi @Sevans711 — looked into this. Answers to your questions first, then a numerics point and a question for @hongyuchen1030.
Your questions
arcs.py/coordinates.py), with adegrees=Trueflag for convenience.geometry="spherical", degrees=False.grid.face_node_angles(geometry=..., degrees=...)dispatching to cached_face_node_angles_spherical/_face_node_angles_euclideaninternals. Your instinct is right — a bare property cannot take flags, and the dispatch-to-cached-variant pattern gives both flexibility and caching.Compute lazily, never eagerly. These angles are a derived, optional quantity most workflows never need, and computing them is a per-face/per-node pass over the whole mesh. Follow the
face_areaspattern: compute on first request, cache, and never touch it at grid construction. Cache per geometry variant; keep the cache in radians and convert to degrees on return (cheap post-scale, no need to cache separately).Geometry, so you don't compute the wrong thing. The angle at a node is the interior angle between the two edges meeting there, not the angle between node position vectors. At node B with face-neighbors A and C: euclidean is the angle between chords (A−B) and (C−B); spherical is the angle between the great-circle arcs BA and BC, from the tangent directions at B (project A and C onto the tangent plane at B, i.e. remove the component along B, then take the angle between the tangents) — equivalently the angle between the edge-plane normals n1 = B×A and n2 = B×C.
Reuse existing primitives:
uxarray/grid/utils.py::_small_angle_of_2_vectorsuses the stable2*atan2(|u−v|,|u+v|)form — prefer it over anythingarccos-based, since skewed / near-degenerate cells (your regime) are wherearccosloses precision.node_x/y/z,face_node_connectivity, andn_nodes_per_faceare cached and ready; maskINT_FILL_VALUEin the connectivity for variable-sided faces or the padding slots produce junk angles.Free validation: for a spherical triangle, sum(interior angles) − π equals the spherical excess, which equals the face area — so you can cross-check against
grid.face_areasin tests (generalizes to (n−2)π + area for n-gons; flat sum is exactly (n−2)π).On accuracy / #1513. The spherical angle is built from cross products of the edge vectors (n1 = B×A, n2 = B×C). Naive cross products are difference-of-products and lose precision to cancellation exactly when edges are short or nearly collinear — which is the skewed-cell regime skewness analysis cares about most. The compensated cross-product kernels in the AccuSphGeom port (#1513) are built for precisely that, so I would structure the cross-product step so it can use those kernels once #1513 merges, rather than blocking on it now. #1513 is still open (not yet merged).
@hongyuchen1030 — a question for you, referencing this issue (#1566): AccuSphGeom's EFT is aimed at robust predicates (sign / orientation). Computing a node angle is a magnitude problem — accurate normals via
accucross, thenatan2(|n1×n2|, n1·n2). Does the compensated cross product meaningfully improve the accuracy of the resulting angle magnitude in the near-degenerate regime, or is the final error there dominated by theatan2conditioning near 0/π? Trying to gauge whether wiring the #1513 kernels into this buys real angle accuracy or mainly helps the orientation/sign side.Happy to review once you have a draft.
Sevans711 commentedon Jul 14, 2026
@rajeeja Thank you for your detailed response! My thoughts below:
Sounds good.
Agreed.
I think that all makes sense. I might realize I have questions once I start the implementation; I'll follow up if I get stuck.
Thank you for pointing me to this! This helped me discover
_angle_of_2_vectors, which is probably what I will end up using, to account for the possibility of non-convex faces where an internal angle can be >180 degrees. Unless… do uxarray grids actually require all faces to be convex?I agree (and also, Claude happened to mention that idea as well when I initially asked about computing skewness). I found #1567 and #1571 while looking into face_areas because of this.
This makes sense, and I will keep in mind that we might replace with more accurate cross products, or maybe a flag to swap between modes, in the near future.
Thank you! I will request you as a reviewer once the PR is ready to go.
erogluorhan commentedon Jul 15, 2026
Some thoughts:
Sevans711 commentedon Jul 15, 2026
@erogluorhan thank you for sharing these thoughts as well. I'll focus on spherical geometry first, and disable caching by default. I might still add a flag like
grid.face_node_angles(..., cache=False)to enable the user to opt-in to caching, in case they know ahead of time that they will be doing multiple computations related to angles, if that sounds reasonable?erogluorhan commentedon Jul 15, 2026
Great; thank you!
This is worth running some large data tests to see the performance and memory usage on NCAR's HPC clusters, maybe using 3.75 km data. Memory usage associated with the caching of it could be roughly calculated actually. Assuming you'll use float, it would (for our sample 3.75 km MPAS grid) be around (~42M faces * 6 nodes * 8 bytes) = ~2GB of extra memory usage.
The rest should be:
Sevans711 commentedon Jul 15, 2026
Small update: I managed to finish an initial implementation (see commit ecba4f1). Still need to add tests and examples before opening a PR.
The non-spherical geometry seems simple to support (it doesn't add any operations, it just skips the "project onto the tangent plane" step) so I included it as an option for now; it only took a few extra minutes to implement, to document the relevant kwarg and add "if geometry=..." checks inside the code.
I definitely agree that caching should be disabled by default, unless the calculation actually becomes a bottleneck. I did still include the caching option though, because it only took a few extra minutes to add it. This should help us later test in real workflows whether it saves non-negligible amounts of time:
cachekwarg. This will avoid caching entirely.grid.face_node_angles(..., cache=True)once at the top. This will lead to all calls using the cached value.If tests show there's never any point in supporting caching and we want to remove that option to avoid the overhead of slightly longer code / more for users to read about and consider, it should be easy enough to remove the relevant pieces of the code.
erogluorhan commentedon Jul 16, 2026
Re caching: Please see my previous comment and complete the tests accordingly and let us know the results before introducing functionality into API. (Once introduced into user API, even if it is disabled by default, removing it later would break user workflows if it gets some usage)
Re flat vs sphere: @rajeeja @hongyuchen1030 do you think it is worth to introduce any flat geometry calculations or should we focus only on spherical geometry?
erogluorhan commentedon Jul 16, 2026
Oh, I just had a look into the code now, and I believe it could be and has to be vectorized (instead of nested for loops) to run it in virtually "no time" for varying grid sizes. That way, I believe we'd have negligible execution times with it.
Sevans711 commentedon Jul 16, 2026
Ah, this really helped clarify for me, thank you. Now I understand your concern about including it in the API in the first place. I will make sure to run some initial tests so we can decide whether to remove the caching option before merging into main. I will reach out to you separately about getting HPC access if I have questions!
Similarly, I now understand it might make more sense to exclude the "geometry" option entirely. I am happy to follow whatever guidance people provide on that. Since it is in my initial implementation already, I will wait for others to chime in before removing it, and will also make sure we've come to a decision on this before merging into main.
My understanding is that numba speeds are comparable to (or better than) vectorized numpy computations. I believe vectorizing here is also not particularly elegant, because n_nodes_per_face varies from face to face. Am I misunderstanding something?
I didn't want to spend too much time on premature optimizations, but it did seem worthwhile to get some initial tests, so I asked claude for an initial/naive vectorized implementation without numba. I skimmed it for correctness and tested that the results are consistent with the numba results for all the uxarray tutorial grids and the grids below. I pushed it to a new branch for now (
face_node_angles_nonumba; see 0feade2).Now we can compare the timing (tests run locally on my machine, in Python 3.14):
This prints:
(Well, actually, the first time it is run, it takes closer to 1.8 seconds for the very first numba computation, because numba takes time to compile relevant functions. This is what it looked like the second time.)
I also ran similar code for some larger grids I happen to have downloaded on my machine, and got:
Conclusions: numba seems maybe faster, and at least comparable, to a numpy vectorized approach. Or, maybe there is some huge inefficiency that needs to be solved in the numpy implementation (see 0feade2)?
Sevans711 commentedon Jul 16, 2026
Actually, I also have a few more quick follow-up questions:
For 2, my initial thought is to compare to face_areas computation time, since uxarray already supports caching for face_areas. On
mainright now, face_areas takes much longer than face_node_angles. But, on the face_areas API cleanup and speedup branch (see #1571), the timing is actually quite similar:This, and similar code for the other two grid files tested above, produces:
Of course, these tests aren't as helpful as large data tests on HPC clusters, but hopefully they provide a bit more context in the meantime before I am set up on HPC.
7 remaining items
hongyuchen1030 commentedon Jul 20, 2026
I don't think we need the "convex" check. Given how hard it is to determine a face is actually "convex" on the sphere and the fact that most of our face are not very ill-conditioned. Our algorithms should cover all convex cases and mildly concave faces as well.
But I think it might be useful to have a mask to indicate if the given grids are triangles or not, if possible. Triangulated faces sometimes have tailored algorithms for better performance.
Sevans711 commentedon Aug 4, 2026
Finally got set up to use HPC and was able to test the timing. Here's what the timing looks like for large MPAS grids:
ux.open_grid()(See previous comment about timing for more details on the code being run: #1566 (comment))
The last column shows how long it took to run
ux.open_grid(gridfile)for each grid file, for reference.I used
numba.set_num_threads()to adjust the number of threads. Getting a job with 4 threads through the HPC job submission queues was very fast on Casper. I think it is reasonable to expect machines to be capable of handling at least 4 threads if they are also able to handle data processing on a 20 GB grid (~MPAS 3.75km). I included the 1 thread case for reference, to showcase the importance of usingprangeand@njit(..., parallel=True)in the implementation.I believe both the numba and numpy implementations could probably be further refined to improve efficiency, but I think we should save that for future PRs? These tests feel sufficient to answer the two primary questions we've been asking in this thread:
cacheoption?ux.open_grid()already uses roughly 20GB, and that doesn't factor in any of the memory of actual data variables living on the grid itself. So, while 2 GB sounds large, relatively it's not actually that huge. These numbers make me think "cache=True should be an option but not the default."Sevans711 commentedon Aug 4, 2026
With those tests completed, and considering the other comments in this thread, I would propose the following plan for implementation:
geometryoption. Always assume spherical geometry.assume_convexflag. Always assume convex faces.degreesoption as-is, with degrees=False by default. (Technically people could just convert afterwards, but it's a simple and convenient option to keep, and it helps to clarify the result is in radians, just by glancing at the function signature.)cacheoption untouched, with caching disabled by default.Grid.compute_face_node_angles(), and add a propertyGrid.face_node_angleswhich returns the result of this method. Clarify in theGrid.face_node_anglesproperty docstring that results are recomputed each time by default, but user can callGrid.compute_face_node_angles(cache=True)once to cache the results.erogluorhan commentedon Aug 4, 2026
Will look into this and review your suggestions soon
erogluorhan commentedon Aug 4, 2026
AI Disclosure: I had an instinct that an optimized numpy vectorization could have outperformed
numbaand played with Claude but it optimized numba as well as numpy and further opened the gap between the two in favor of numba :)@Sevans711 — happy to share the full benchmark script if useful.
@cmdupuis3 - These might be of interest to you
The following is from Claude:
Followed up on the numba-vs-numpy benchmarking question above — wrote a vectorized numpy implementation and compared it against the current numba kernel (ecba4f1, branch
face_node_angles) and the rough numpy version already tried (0feade2, branchface_node_angles_nonumba_option).Setup:
mpas-QU-480(real, 1,791 faces) plus the same grid tiled to ~500K and ~2M faces as a stand-in for the 3.75km/42M-face HPC test above (didn't have that grid file available; relative trends below should still hold). All outputs agree to float64 precision (max|diff| ~ 1e-15) across every implementation.New numpy implementation — groups faces by node-count (most grids have only 1–3 distinct arities: MPAS is pentagons+hexagons, cubed-sphere is all-quads) and vectorizes each group with
np.rollfor prev/next-node lookup instead of a global modulo +take_along_axisgather, so there's no wasted work on padded slots:So: single-threaded, the current numba kernel is ~4x slower than plain numpy, and only edges past numpy once given several threads.
Why: the current kernel builds a fresh
np.array([...])forv1,v2, and the surface normal on every loop iteration — a well-known numba anti-pattern that blocks scalar/register optimization.Same math, rewritten with plain scalars and no array literals in the hot loop:
Once written idiomatically, numba is ~6x faster than the best numpy vectorization even single-threaded, and 20–40x faster with threads — numpy has to materialize a full intermediate array in memory for every op (
v1,v2, projected normal, dotproducts, norms...), while the scalar loop fuses all of that per-face-node with no intermediate allocation. This is the expected shape for numba vs numpy: ragged data with tiny, fixed-size per-element math is numba's sweet spot.
Suggestion: keep numba, just fix the array-allocation pattern in the kernel — it's a small, mechanical change with a large payoff, not a rewrite.
(Benchmarking and both implementations above worked out with Claude's help.)
Sevans711 commentedon Aug 5, 2026
Thank you for looking into this in detail!
Can you re-run the benchmarks without using fastmath=True? I think uxarray cares a lot about numerical precision, and my understanding is that that flag is happy to silently mess up your accuracy in strange edge cases where you wouldn't expect any issues (even if no such edge cases appeared in the cases you tried here).
I also suspected the numba implementation was sub-optimal for constructing so many np.arrays internally; I have the intuition that constructing a numpy array is "expensive". But, I wanted to use the
_small_angle_of_2_vectorsprimitive, which also uses numpy functions internally already. Using_small_angle_of_2_vectorsinside_compute_face_node_angles_convexfeels more idiomatic for this PR, rather than in-lining all of its logic.Seeing that we care enough to optimize efficiency like this on the first implementation of this feature, I would maybe add to the plan: rewrite
_small_angle_of_2_vectorsto avoid building numpy arrays unnecessarily (when the inputs aren't numpy arrays yet).I also suspected the numpy implementation was sub-optimal but didn't know how much to focus on efficiency here. I appreciate your (and Claude's) efforts to optimize both and compare.
hongyuchen1030 commentedon Aug 5, 2026
I agree with diabling
fastmath = True. The concern includes both FMA contraction and the broader set of LLVM fast-math assumptions enabled by Numba (like assumption fornnanandninf). UXarray is also not computationally expensive enough forfastmath=Trueto be necessary by default. If disabling it causes a significant performance regression, that likely indicates a real performance issue in one of the kernels that should be investigated separately.I also agree that we should use
_small_angle_of_2_vectorsconsistently whenever calculating the angle between two vectors, rather than inlining the same logic in multiple places. It should not introduce meaningful overhead if it is implemented in the same plain-scalar, Numba-friendly style as the surrounding kernel. If it does, then the helper itself should be rewritten in that style.The updated implementation appears to mainly replace the original code with a more branch-free, SIMD-friendly formulation. That is generally the right direction for this type of Numba kernel. We are effectively writing C++-style SIMD code in Python, which gives us more direct control over branching, vectorization, and intermediate allocations than relying on higher-level NumPy operations.
In my experience these LLM models still have fairly limited depth on this kind of low-level vectorization work, they can silently drop important edge cases or introduce things like
fastmath=Truewithout flagging the tradeoff (exactly what happened here). Worth treating their output as a first draft to reviewerogluorhan commentedon Aug 5, 2026
@Sevans711 @hongyuchen1030 all great points that I 100% agree with. We should do our own assessment and finalize the implementation ourselves.
Sam, dropping
fastmathand doing small_angle_of_two_vecors, there didn't seem to be meaningful differences on execution times with Claude, but as we discussed offline with you, I think from this point it really needs you to do further tests on real data and see it from there.Sevans711 commentedon Aug 11, 2026
I added an optimized implementation on the
face_node_anglesbranch. The diff from main looks like: 5ef66d8...09bafd7Also it looks like the "constructing many tiny numpy arrays inside numba methods" performance hit is occurring throughout more areas of uxarray; I opened #1648 to address that. I think that issue should be a relatively high priority in terms of speeding up uxarray methods. For example, it occurs inside
_face_area_from_quadraturewhich gets called by allface_areascomputations. This suggests to me thatface_areascomputations could be sped up dramatically.Updating the table from before to include the optimized numba methods:
ux.open_grid()This order-of-magnitude improvement bringing MPAS 3.75 km down to roughly 3 seconds makes me think caching is no longer necessary to consider for now. I would rather wait 3 seconds than use an extra 2 GB of memory. It would be easy enough to add caching later if this ever becomes part of a hot path, but these speeds are now fast enough that it probably makes sense to ship
compute_face_node_anglesinitially without a cache option.Additionally, let's keep the
compute_face_node_angles()syntax for now, and not introduce aface_node_anglesproperty unless it becomes clearly necessary or helpful. Other properties (e.g.face_areas) tend to be cached, so it might cause some confusion if a non-cached property gets introduced.erogluorhan commentedon Aug 11, 2026
Looks great! No caching for now makes complete sense to me. When are you planning a PR on this?
Sevans711 commentedon Aug 12, 2026
Just made it, see #1672! I was hoping to get to it yesterday but had to head out before I could finish setting up tests and writing up the PR overview / description.
Implements `Grid.compute_face_node_angles()` (#1672)