Skip to content

Merge coincident pole and antimeridian nodes in structured grids - #1690

Merged
cmdupuis3 merged 8 commits into
mainfrom
rajeeja/structured-coincident-nodes
Aug 28, 2026
Merged

cmdupuis3 merged 8 commits into
mainfrom
rajeeja/structured-coincident-nodes

Conversation

@rajeeja

@rajeeja rajeeja commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

Closes #1689

  • _read_structured_grid matched nodes in the lon/lat plane, so the nlon+1 nodes at each pole and the two sides of the antimeridian were never merged.
  • Now matches in Cartesian space, so nodes that are the same point on the sphere collapse: 899 nodes at 1 deg, 3599 at 0.25 deg.
  • Merging leaves each polar quad with a repeated corner, so those faces are now stored as triangles padded with the fill value.
  • Pole valence is nlon as expected (36 at 10 deg, 360 at 1 deg) and V - E + F == 2 confirms a closed sphere.
  • Regional grids that touch neither pole nor the seam are unchanged.
  • Two regression tests added; the global one fails on main.

Match nodes in Cartesian space rather than the lon/lat plane so pole and
antimeridian nodes are recognized as the same point, and store the resulting
polar faces as triangles instead of quads with a repeated corner.
@rajeeja rajeeja self-assigned this Aug 19, 2026
@rajeeja

rajeeja commented Aug 19, 2026

Copy link
Copy Markdown
Contributor Author

Checked the docs and user guide for behavior changes: both datasets in user-guide/structured.ipynb are unaffected (air_temperature is regional, ersstv5 spans 0-358 deg so the seam never closes), and neither collapses a single node. Also fixed tol to stay in degrees rather than silently becoming a chord length, so the documented parameter keeps its meaning. Only grids that actually touch a pole or the antimeridian change.

@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.

Thank you for your work on this! Requesting minor changes and clarifications. I will take a closer look at the tests after understanding things a bit better.

Can you clarify, what does this mean from your original comment?

  • Now matches in Cartesian space, so nodes that are the same point on the sphere collapse: 899 nodes at 1 deg, 3599 at 0.25 deg.

I was also confused about the following, but I left an inline comment about it, feel free to respond there if that is easier:

  • Merging leaves each polar quad with a repeated corner, so those faces are now stored as triangles padded with the fill value.

Comment thread uxarray/io/_structured.py Resolved
Comment thread uxarray/io/_structured.py Resolved
Comment thread uxarray/io/_structured.py Resolved
@Sevans711 Sevans711 added the bug Something isn't working label Aug 21, 2026

@erogluorhan erogluorhan left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Wow, it is great to see this fix! It's always been unsettling to see those lons unmerged at the pole with UXarray's structured grids.

float32 input (e.g. real climate datasets) silently ran the whole
xyz/tolerance pipeline at float32 precision, causing pole/antimeridian
merges to fail or merge only partially.
@rajeeja
rajeeja requested a review from Sevans711 August 21, 2026 16:01

@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.

Looks almost ready to merge now, thank you for the changes! Left inline comments with minor style request and noting one typo. Other than that I think it looks good!

Comment thread uxarray/io/_structured.py Resolved
Comment thread test/io/test_structured.py Resolved
Comment thread uxarray/io/_structured.py Resolved
Comment thread uxarray/io/_structured.py Resolved
Comment thread uxarray/io/_structured.py Resolved

@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.

Looks ready to merge, thank you for the implementation here and for the back and forth with addressing all of my comments!

@cmdupuis3
cmdupuis3 merged commit d013907 into main Aug 28, 2026
13 checks passed
rajeeja added a commit that referenced this pull request Sep 8, 2026
The notebook's cell sources are identical to main; only the outputs
differed, and those differences were an xarray coordinate-ordering repr
change and a stray OMP info line. Keeping the re-run added ~1700 lines of
diff with no content change.
@erogluorhan
erogluorhan deleted the rajeeja/structured-coincident-nodes branch November 13, 2026 23:43
cmdupuis3 added a commit that referenced this pull request Nov 15, 2026
* Merge coincident nodes in structured grids on the sphere

Match nodes in Cartesian space rather than the lon/lat plane so pole and
antimeridian nodes are recognized as the same point, and store the resulting
polar faces as triangles instead of quads with a repeated corner.

* Keep tol in degrees when matching nodes on the sphere

* Merge duplicate nodes when constructing the dual mesh

Canonicalize duplicate node indices in the face-node connectivity before
building the dual, so grids with repeated nodes produce a correct dual instead
of being rejected. Also vectorize the duplicate lookup and deprecate the now
redundant check_duplicate_nodes argument.

* Address review: derive tol from ERROR_TOLERANCE, reuse xyz helper, clarify comment

* Upcast lon/lat to float64 before coincidence detection

float32 input (e.g. real climate datasets) silently ran the whole
xyz/tolerance pipeline at float32 precision, causing pole/antimeridian
merges to fail or merge only partially.

* Merge coincident nodes in structured grids on the sphere

Match nodes in Cartesian space rather than the lon/lat plane so pole and
antimeridian nodes are recognized as the same point, and store the resulting
polar faces as triangles instead of quads with a repeated corner.

* Keep tol in degrees when matching nodes on the sphere

* Address review: derive tol from ERROR_TOLERANCE, reuse xyz helper, clarify comment

* Upcast lon/lat to float64 before coincidence detection

float32 input (e.g. real climate datasets) silently ran the whole
xyz/tolerance pipeline at float32 precision, causing pole/antimeridian
merges to fail or merge only partially.

* Merge coincident nodes generally at Grid construction time

Extend #865's fix beyond the dual mesh: canonicalize duplicate/coincident
node indices in connectivity for every Grid construction path, not just
construct_dual. Detection is now tolerance-based (unit-sphere chordal
distance) instead of exact lon/lat match, so pole-degenerate duplicates
are also caught. Node coordinate arrays are left untouched by design;
only connectivity is remapped to canonical indices, with any resulting
repeated face corners collapsed.

* Remove now-redundant duplicate-node handling from dual mesh path

construct_dual no longer needs its own per-call duplicate detection and
remap, and get_dual() no longer needs to hard-gate on duplicate node
indices, since Grid construction now canonicalizes them structurally
before any of this code runs.

* Exclude dead duplicate node indices from node search trees

Since duplicate node coordinates are intentionally left unreferenced by
connectivity, a node KDTree/BallTree built over the raw coordinate array
could select an index no face actually points to, silently returning
empty or wrong nearest-neighbor results. Build the "nodes" tree only
over live (referenced) indices and translate query results back to
original index space.

* Make SCRIP reader's unique-node dedup order deterministic

polars' unique() with maintain_order unset does not guarantee row order
across runs, so the node index assigned to a given corner coordinate
could vary between reads of the same file. This is normally harmless,
but it made canonical-node selection for coincident duplicates
(e.g. pole points with differing longitude) flaky from run to run.

* Update tests for construction-time node dedup behavior

test_dual_duplicate: validate() now succeeds since connectivity is fully
canonicalized (duplicate coordinates remain by design, but nothing
references a dead index anymore). test_grid_nn_subset: max valid k for a
node search is now bounded by the live node count, not raw node count.
test_to_geodataframe_preserves_antimeridian_faces: pole-coincident
corners with differing longitude are now also merged, shifting the
antimeridian face count.

* Exclude pole points from coincident-node merging

Merging pole-adjacent duplicate nodes was collapsing each face's own
locally-meaningful longitude at the pole into one arbitrary canonical
value, which corrupted lat/lon bounds and broke zonal weight
computation for cube-sphere grids near the poles.

* Use ERROR_TOLERANCE directly as the default node-matching radius

* Vectorize duplicate-index check and make dedup tests self-evident

* Rename _dedupe_grid_ds_nodes to _merge_coincident_grid_ds_nodes

"Coincident nodes" is the domain term used by TempestRemap, MOAB, and our own
validation module; "dedupe" reads like a dataframe operation. Also note in the
docstring that we keep the redundant coordinates and only remap connectivity,
where TempestRemap and MOAB delete and renumber.

* Make the pole carve-out a chord tolerance, not a raw |z| deviation

_coincident_node_canonical_indices exempts pole nodes from merging so each face
touching a pole keeps its own longitude. The mask used np.isclose(|z|, 1.0,
atol=tolerance), which is wrong twice: tolerance is a chord radius everywhere
else in the function, and np.isclose's default rtol=1e-5 swamped atol entirely.
The carve-out spanned 1 - |z| <= 1.001e-5, a chord of 4.5e-3 or ~28 km on Earth,
so any node within 28 km of a pole was silently exempt from merging.

For a point at colatitude t, 1 - |z| = 1 - cos(t) = chord**2 / 2, so the correct
cap is tolerance**2 / 2 with rtol pinned to zero.

* Restore the duplicate-node guard on get_dual

construct_dual reads node_face_connectivity with no duplicate handling, so a
face still referencing a coincident duplicate index yields a degenerate dual
face instead of an error. Merging at construction makes that unreachable today,
so the guard is a no-op safety net; check_duplicate_nodes is now deprecated and
ignored, since the check always runs.

* Re-run structured.ipynb against the rewritten structured reader

The pole/seam merge in _read_structured_grid changes the ersstv5 grid (16290
nodes to 16200) and turns pole quads into triangles, so the near-pole plots were
stale. Outputs re-executed; the stray OMP stderr line is dropped.

* Drop the structured.ipynb re-execution now that #1690 is on main

The notebook's cell sources are identical to main; only the outputs
differed, and those differences were an xarray coordinate-ordering repr
change and a stray OMP info line. Keeping the re-run added ~1700 lines of
diff with no content change.

* Prescreen coincident-node detection on sorted x before building a KDTree

Coincident-node merging now runs on every Grid construction, so the cost
is paid by grids that have no duplicates at all. Two points within a
chord of ERROR_TOLERANCE differ by at most that in x, so in x-sorted
order every consecutive gap between them is also within tolerance; a
point whose sorted neighbours are both further away cannot be coincident
with anything. Filtering on that is exact and drops the tree build
entirely for a clean grid: 1.23s -> 0.28s over 2M nodes.

* Clarify duplicate node test comments and diagram

* Test that near-coincident nodes merge within tolerance

* Warn when node locations are unknown and the merge is skipped

* Explain why only face rings need corner collapsing

* Note the merge tolerance is a chord, not degrees

* Cache the duplicate node map on the grid

* Skip the coincident merge when building the dual grid

get_dual constructs a new Grid from this grid's face centers, which re-ran
the coincident node search on every call and made dual mesh construction
~1.6x slower. The dual's connectivity is already canonical, so the merge is
skipped there via a new internal Grid flag.

* Strengthen tolerance test, cover the unknown-location warning, and reason through corner collapsing

* Say plainly that the no-duplicate path returns grid_ds untouched

* Skip the coincident search for formats that index a unique vertex list

MPAS and HEALPix faces index into an already-unique set of vertices, so the
search cannot find anything to merge. It was still the dominant cost of
opening a large grid of those formats: an argsort over every node, paid for
a guaranteed no-op. On a 1.4M-vertex MPAS grid open_grid went 0.085s on main
to 0.393s here; skipping brings it back to 0.097s.

Formats storing per-face corners (SCRIP, Exodus, GEOS-CS) repeat shared
corners and are still searched. UGRID is deliberately not skipped: it permits
either layout, and geoflow-small has 2150 duplicate nodes. An unknown spec
falls back to searching.

* Read central longitude from pm as well as lon_0

Cartopy 0.26.0 changed PlateCarree from proj=eqc to proj=latlong, which
carries the prime meridian as pm and has no lon_0. Every plotting call that
defaulted to PlateCarree then died on KeyError: 'lon_0', failing test_topology
across all platforms once 0.26 reached conda-forge.

Check both keys and fall back to 0.0, so the lookup works on either cartopy
version rather than pinning away from 0.26.

* Address coincident-node review findings

* Ravel unique inverse for pole duplicate indexing

* Preserve unused nonfinite nodes during coincidence matching

* Canonicalize deferred lazy topology for grid dual construction

* Unify dual construction and canonicalize coincident face centers

* Treat decoded missing SCRIP corners as connectivity padding

* Forward coincidence merge opt-out through dataset and file readers

* Preserve coincidence merge opt-out during deferred dual preparation

---------

Co-authored-by: Rajeev Jain <[email protected]>
Co-authored-by: Sam Evans <[email protected]>
Co-authored-by: Christopher Dupuis <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Grid.from_structured does not merge coincident pole and antimeridian nodes

4 participants