diff --git a/test/grid/geometry/test_bounds.py b/test/grid/geometry/test_bounds.py index 34156827a..3afd744b8 100644 --- a/test/grid/geometry/test_bounds.py +++ b/test/grid/geometry/test_bounds.py @@ -71,6 +71,36 @@ def _get_lonlat_rad_face_edge_nodes_testcase_helper_latlon_bounds_gca(face_nodes return lonlat_coordinates +def _bounds_from_face_edges(face_edges_cart, face_edges_lonlat, **kwargs): + """Call _construct_face_bounds using face-edge arrays as input, + similar to the old _construct_face_bounds interface from before solving issue #1896. + Old tests use this function; newer tests should prefer the new interface instead. + + face_edges_cart : np.ndarray, shape (n_edges, 2, 3) + Cartesian (x, y, z) of each edge's (start, end) nodes. + face_edges_lonlat : np.ndarray, shape (n_edges, 2, 2) + (lon, lat) in radians of each edge's (start, end) nodes. + **kwargs + Passed to _construct_face_bounds (is_latlonface, is_GCA_list). + """ + # Edge i goes from node i to node i+1, so this helper passes + # node i = face_edges[i, 0] to _construct_face_bounds. + start_xyz = face_edges_cart[:, 0] + start_lonlat = face_edges_lonlat[:, 0] + # Column slices like start_xyz[:, 0] are strided (non-contiguous) views. Numba accepts these, + # but compiles a separate specialization of _construct_face_bounds for non-contiguous arrays. + # Making them contiguous ensures the tests exercise the same compiled code used in production. + return _construct_face_bounds( + np.arange(len(face_edges_cart)), + np.ascontiguousarray(start_xyz[:, 0]), + np.ascontiguousarray(start_xyz[:, 1]), + np.ascontiguousarray(start_xyz[:, 2]), + np.ascontiguousarray(start_lonlat[:, 0]), + np.ascontiguousarray(start_lonlat[:, 1]), + **kwargs, + ) + + def test_populate_bounds_normal_latlon_bounds_gca(): vertices_lonlat = [[10.0, 60.0], [10.0, 10.0], [50.0, 10.0], [50.0, 60.0]] vertices_lonlat = np.array(vertices_lonlat) @@ -95,7 +125,7 @@ def test_populate_bounds_normal_latlon_bounds_gca(): grid.edge_node_connectivity.values, grid.node_lon.values, grid.node_lat.values) expected_bounds = np.array([[lat_min, lat_max], [lon_min, lon_max]]) - bounds = _construct_face_bounds(face_edges_connectivity_cartesian, face_edges_connectivity_lonlat) + bounds = _bounds_from_face_edges(face_edges_connectivity_cartesian, face_edges_connectivity_lonlat) np.testing.assert_allclose(bounds, expected_bounds, atol=ERROR_TOLERANCE) @@ -123,7 +153,7 @@ def test_populate_bounds_antimeridian_latlon_bounds_gca(): grid.edge_node_connectivity.values, grid.node_lon.values, grid.node_lat.values) expected_bounds = np.array([[lat_min, lat_max], [lon_min, lon_max]]) - bounds = _construct_face_bounds(face_edges_connectivity_cartesian, face_edges_connectivity_lonlat) + bounds = _bounds_from_face_edges(face_edges_connectivity_cartesian, face_edges_connectivity_lonlat) np.testing.assert_allclose(bounds, expected_bounds, atol=ERROR_TOLERANCE) @@ -137,7 +167,7 @@ def test_populate_bounds_equator_latlon_bounds_gca(): face_edges_lonlat = np.array( [[_xyz_to_lonlat_rad(*edge[0]), _xyz_to_lonlat_rad(*edge[1])] for edge in face_edges_cart]) - bounds = _construct_face_bounds(face_edges_cart, face_edges_lonlat) + bounds = _bounds_from_face_edges(face_edges_cart, face_edges_lonlat) expected_bounds = np.array([[-0.05235988, 0], [6.23082543, 0]]) np.testing.assert_allclose(bounds, expected_bounds, atol=ERROR_TOLERANCE) @@ -153,7 +183,7 @@ def test_populate_bounds_south_sphere_latlon_bounds_gca(): face_edges_lonlat = np.array( [[_xyz_to_lonlat_rad(*edge[0]), _xyz_to_lonlat_rad(*edge[1])] for edge in face_edges_cart]) - bounds = _construct_face_bounds(face_edges_cart, face_edges_lonlat) + bounds = _bounds_from_face_edges(face_edges_cart, face_edges_lonlat) expected_bounds = np.array([[-1.51843645, -1.45388627], [3.14159265, 3.92699082]]) np.testing.assert_allclose(bounds, expected_bounds, atol=ERROR_TOLERANCE) @@ -169,7 +199,7 @@ def test_populate_bounds_near_pole_latlon_bounds_gca(): face_edges_lonlat = np.array( [[_xyz_to_lonlat_rad(*edge[0]), _xyz_to_lonlat_rad(*edge[1])] for edge in face_edges_cart]) - bounds = _construct_face_bounds(face_edges_cart, face_edges_lonlat) + bounds = _bounds_from_face_edges(face_edges_cart, face_edges_lonlat) expected_bounds = np.array([[-1.20427718, -1.14935491], [0, 0.13568803]]) np.testing.assert_allclose(bounds, expected_bounds, atol=ERROR_TOLERANCE) @@ -185,7 +215,7 @@ def test_populate_bounds_near_pole2_latlon_bounds_gca(): face_edges_lonlat = np.array( [[_xyz_to_lonlat_rad(*edge[0]), _xyz_to_lonlat_rad(*edge[1])] for edge in face_edges_cart]) - bounds = _construct_face_bounds(face_edges_cart, face_edges_lonlat) + bounds = _bounds_from_face_edges(face_edges_cart, face_edges_lonlat) expected_bounds = np.array([[-1.20427718, -1.14935491], [6.147497, 4.960524e-16]]) np.testing.assert_allclose(bounds, expected_bounds, atol=ERROR_TOLERANCE) @@ -209,7 +239,7 @@ def test_populate_bounds_long_face_latlon_bounds_gca(): face_edges_lonlat = np.array( [[_xyz_to_lonlat_rad(*edge[0]), _xyz_to_lonlat_rad(*edge[1])] for edge in face_edges_cart]) - bounds = _construct_face_bounds(face_edges_cart, face_edges_lonlat) + bounds = _bounds_from_face_edges(face_edges_cart, face_edges_lonlat) # The expected bounds should not contain the south pole [0,-0.5*np.pi] assert bounds[1][0] != 0.0 diff --git a/test/grid/geometry/test_bounds_advanced.py b/test/grid/geometry/test_bounds_advanced.py index 2051665bd..07b7a9ed1 100644 --- a/test/grid/geometry/test_bounds_advanced.py +++ b/test/grid/geometry/test_bounds_advanced.py @@ -165,6 +165,36 @@ def _get_lonlat_rad_face_edge_nodes_testcase_helper_latlon_bounds_latlonface(fac return lonlat_coordinates +def _bounds_from_face_edges(face_edges_cart, face_edges_lonlat, **kwargs): + """Call _construct_face_bounds using face-edge arrays as input, + similar to the old _construct_face_bounds interface from before solving issue #1896. + Old tests use this function; newer tests should prefer the new interface instead. + + face_edges_cart : np.ndarray, shape (n_edges, 2, 3) + Cartesian (x, y, z) of each edge's (start, end) nodes. + face_edges_lonlat : np.ndarray, shape (n_edges, 2, 2) + (lon, lat) in radians of each edge's (start, end) nodes. + **kwargs + Passed to _construct_face_bounds (is_latlonface, is_GCA_list). + """ + # Edge i goes from node i to node i+1, so this helper passes + # node i = face_edges[i, 0] to _construct_face_bounds. + start_xyz = face_edges_cart[:, 0] + start_lonlat = face_edges_lonlat[:, 0] + # Column slices like start_xyz[:, 0] are strided (non-contiguous) views. Numba accepts these, + # but compiles a separate specialization of _construct_face_bounds for non-contiguous arrays. + # Making them contiguous ensures the tests exercise the same compiled code used in production. + return _construct_face_bounds( + np.arange(len(face_edges_cart)), + np.ascontiguousarray(start_xyz[:, 0]), + np.ascontiguousarray(start_xyz[:, 1]), + np.ascontiguousarray(start_xyz[:, 2]), + np.ascontiguousarray(start_lonlat[:, 0]), + np.ascontiguousarray(start_lonlat[:, 1]), + **kwargs, + ) + + def test_populate_bounds_antimeridian_latlon_bounds_gca(): vertices_lonlat = [[350, 60.0], [350, 10.0], [50.0, 10.0], [50.0, 60.0]] vertices_lonlat = np.array(vertices_lonlat) @@ -189,7 +219,7 @@ def test_populate_bounds_antimeridian_latlon_bounds_gca(): grid.edge_node_connectivity.values, grid.node_lon.values, grid.node_lat.values) expected_bounds = np.array([[lat_min, lat_max], [lon_min, lon_max]]) - bounds = _construct_face_bounds(face_edges_connectivity_cartesian, face_edges_connectivity_lonlat) + bounds = _bounds_from_face_edges(face_edges_connectivity_cartesian, face_edges_connectivity_lonlat) np.testing.assert_allclose(bounds, expected_bounds, atol=ERROR_TOLERANCE) @@ -204,7 +234,7 @@ def test_populate_bounds_near_pole2_latlon_bounds_gca(): face_edges_lonlat = np.array( [[_xyz_to_lonlat_rad(*edge[0]), _xyz_to_lonlat_rad(*edge[1])] for edge in face_edges_cart]) - bounds = _construct_face_bounds(face_edges_cart, face_edges_lonlat) + bounds = _bounds_from_face_edges(face_edges_cart, face_edges_lonlat) expected_bounds = np.array([[-1.20427718, -1.14935491], [6.147497, 4.960524e-16]]) np.testing.assert_allclose(bounds, expected_bounds, atol=ERROR_TOLERANCE) @@ -232,7 +262,7 @@ def test_populate_bounds_node_on_pole_latlon_bounds_gca(): grid.edge_node_connectivity.values, grid.node_lon.values, grid.node_lat.values) expected_bounds = np.array([[lat_min, lat_max], [lon_min, lon_max]]) - bounds = _construct_face_bounds(face_edges_connectivity_cartesian, face_edges_connectivity_lonlat) + bounds = _bounds_from_face_edges(face_edges_connectivity_cartesian, face_edges_connectivity_lonlat) np.testing.assert_allclose(bounds, expected_bounds, atol=ERROR_TOLERANCE) @@ -259,7 +289,7 @@ def test_populate_bounds_edge_over_pole_latlon_bounds_gca(): grid.edge_node_connectivity.values, grid.node_lon.values, grid.node_lat.values) expected_bounds = np.array([[lat_min, lat_max], [lon_min, lon_max]]) - bounds = _construct_face_bounds(face_edges_connectivity_cartesian, face_edges_connectivity_lonlat) + bounds = _bounds_from_face_edges(face_edges_connectivity_cartesian, face_edges_connectivity_lonlat) np.testing.assert_allclose(bounds, expected_bounds, atol=ERROR_TOLERANCE) @@ -286,7 +316,7 @@ def test_populate_bounds_pole_inside_latlon_bounds_gca(): grid.edge_node_connectivity.values, grid.node_lon.values, grid.node_lat.values) expected_bounds = np.array([[lat_min, lat_max], [lon_min, lon_max]]) - bounds = _construct_face_bounds(face_edges_connectivity_cartesian, face_edges_connectivity_lonlat) + bounds = _bounds_from_face_edges(face_edges_connectivity_cartesian, face_edges_connectivity_lonlat) np.testing.assert_allclose(bounds, expected_bounds, atol=ERROR_TOLERANCE) @@ -311,8 +341,8 @@ def test_populate_bounds_node_on_pole_latlon_bounds_gca_list(): grid.edge_node_connectivity.values, grid.node_lon.values, grid.node_lat.values) expected_bounds = np.array([[lat_min, lat_max], [lon_min, lon_max]]) - bounds = _construct_face_bounds(face_edges_connectivity_cartesian, face_edges_connectivity_lonlat, - is_GCA_list=[True, False, True, False]) + bounds = _bounds_from_face_edges(face_edges_connectivity_cartesian, face_edges_connectivity_lonlat, + is_GCA_list=[True, False, True, False]) np.testing.assert_allclose(bounds, expected_bounds, atol=ERROR_TOLERANCE) @@ -336,8 +366,8 @@ def test_populate_bounds_node_on_pole_latlon_bounds_latlonface(): grid.edge_node_connectivity.values, grid.node_lon.values, grid.node_lat.values) expected_bounds = np.array([[lat_min, lat_max], [lon_min, lon_max]]) - bounds = _construct_face_bounds(face_edges_connectivity_cartesian, face_edges_connectivity_lonlat, - is_latlonface=True) + bounds = _bounds_from_face_edges(face_edges_connectivity_cartesian, face_edges_connectivity_lonlat, + is_latlonface=True) np.testing.assert_allclose(bounds, expected_bounds, atol=ERROR_TOLERANCE) @@ -362,8 +392,8 @@ def test_populate_bounds_edge_over_pole_latlon_bounds_gca_list(): grid.edge_node_connectivity.values, grid.node_lon.values, grid.node_lat.values) expected_bounds = np.array([[lat_min, lat_max], [lon_min, lon_max]]) - bounds = _construct_face_bounds(face_edges_connectivity_cartesian, face_edges_connectivity_lonlat, - is_GCA_list=[True, False, True, False]) + bounds = _bounds_from_face_edges(face_edges_connectivity_cartesian, face_edges_connectivity_lonlat, + is_GCA_list=[True, False, True, False]) np.testing.assert_allclose(bounds, expected_bounds, atol=ERROR_TOLERANCE) @@ -388,8 +418,8 @@ def test_populate_bounds_edge_over_pole_latlon_bounds_latlonface(): grid.edge_node_connectivity.values, grid.node_lon.values, grid.node_lat.values) expected_bounds = np.array([[lat_min, lat_max], [lon_min, lon_max]]) - bounds = _construct_face_bounds(face_edges_connectivity_cartesian, face_edges_connectivity_lonlat, - is_latlonface=True) + bounds = _bounds_from_face_edges(face_edges_connectivity_cartesian, face_edges_connectivity_lonlat, + is_latlonface=True) np.testing.assert_allclose(bounds, expected_bounds, atol=ERROR_TOLERANCE) @@ -413,8 +443,8 @@ def test_populate_bounds_pole_inside_latlon_bounds_gca_list(): grid.edge_node_connectivity.values, grid.node_lon.values, grid.node_lat.values) expected_bounds = np.array([[lat_min, lat_max], [lon_min, lon_max]]) - bounds = _construct_face_bounds(face_edges_connectivity_cartesian, face_edges_connectivity_lonlat, - is_GCA_list=[True, True, True, True]) + bounds = _bounds_from_face_edges(face_edges_connectivity_cartesian, face_edges_connectivity_lonlat, + is_GCA_list=[True, True, True, True]) np.testing.assert_allclose(bounds, expected_bounds, atol=ERROR_TOLERANCE) @@ -438,8 +468,8 @@ def test_populate_bounds_pole_inside_latlon_bounds_latlonface(): grid.edge_node_connectivity.values, grid.node_lon.values, grid.node_lat.values) expected_bounds = np.array([[lat_min, lat_max], [lon_min, lon_max]]) - bounds = _construct_face_bounds(face_edges_connectivity_cartesian, face_edges_connectivity_lonlat, - is_latlonface=True) + bounds = _bounds_from_face_edges(face_edges_connectivity_cartesian, face_edges_connectivity_lonlat, + is_latlonface=True) np.testing.assert_allclose(bounds, expected_bounds, atol=ERROR_TOLERANCE) from uxarray.grid.bounds import _populate_face_bounds diff --git a/test/grid/geometry/test_geometry_advanced.py b/test/grid/geometry/test_geometry_advanced.py index 46b3bb960..9985a1ae3 100644 --- a/test/grid/geometry/test_geometry_advanced.py +++ b/test/grid/geometry/test_geometry_advanced.py @@ -6,7 +6,7 @@ from uxarray.constants import ERROR_TOLERANCE, INT_FILL_VALUE from uxarray.grid.coordinates import _lonlat_rad_to_xyz, _normalize_xyz, _xyz_to_lonlat_rad from uxarray.grid.arcs import extreme_gca_z -from uxarray.grid.bounds import _get_latlonbox_width, insert_pt_in_latlonbox +from uxarray.grid.bounds import _get_lon_width, insert_pt_in_latlonbox from uxarray.grid.geometry import _pole_point_inside_polygon_cartesian @@ -230,13 +230,11 @@ def test_extreme_gca_latitude_min(): assert np.isclose(min_latitude, expected_min_latitude, atol=ERROR_TOLERANCE) -def test_get_latlonbox_width(): - gca_latlon = np.array([[0.0, 0.0], [0.0, 3.0]]) - width = _get_latlonbox_width(gca_latlon) +def test_get_lon_width(): + width = _get_lon_width(0.0, 3.0) assert width == 3.0 - gca_latlon = np.array([[0.0, 0.0], [2 * np.pi - 1.0, 1.0]]) - width = _get_latlonbox_width(gca_latlon) + width = _get_lon_width(2 * np.pi - 1.0, 1.0) assert width == 2.0 diff --git a/test/grid/geometry/test_point_in_face.py b/test/grid/geometry/test_point_in_face.py index 1829c7eeb..e5568c588 100644 --- a/test/grid/geometry/test_point_in_face.py +++ b/test/grid/geometry/test_point_in_face.py @@ -5,7 +5,7 @@ import uxarray as ux from uxarray.constants import INT_FILL_VALUE from uxarray.grid.coordinates import _lonlat_rad_to_xyz -from uxarray.grid.utils import _get_cartesian_face_edge_nodes_array, _get_cartesian_face_edge_nodes +from uxarray.grid.utils import _get_cartesian_face_edge_nodes_array from uxarray.grid.point_in_face import _point_in_face_from_grid diff --git a/uxarray/grid/arcs.py b/uxarray/grid/arcs.py index c8c283c51..435808129 100644 --- a/uxarray/grid/arcs.py +++ b/uxarray/grid/arcs.py @@ -201,9 +201,11 @@ def extreme_gca_latitude(gca_cart, gca_lonlat, extreme_type): raise ValueError("Invalid extreme_type. Expected 'max' or 'min'.") # (numba complains about f-strings, so don't put `extreme_type` value in message.) - # Extract the two points + # Extract the two points; upcast to float64 to ensure high-precision math. n1 = gca_cart[0] n2 = gca_cart[1] + n1 = np.float64(n1[0]), np.float64(n1[1]), np.float64(n1[2]) + n2 = np.float64(n2[0]), np.float64(n2[1]), np.float64(n2[2]) # Compute dot product dot_n1_n2 = _numba_dot3(n1, n2) diff --git a/uxarray/grid/bounds.py b/uxarray/grid/bounds.py index c34f8dc23..fba1e3ccb 100644 --- a/uxarray/grid/bounds.py +++ b/uxarray/grid/bounds.py @@ -9,11 +9,9 @@ point_within_gca, ) from uxarray.grid.geometry import pole_point_inside_polygon -from uxarray.grid.utils import ( - _get_cartesian_face_edge_nodes, - _get_spherical_face_edge_nodes, - all_elements_nan, - any_close_lat, +from uxarray.utils.numba_math import ( + _numba_abs3, + _numba_sub3, ) from uxarray.utils.parallel import parallel_njit @@ -147,7 +145,9 @@ def _construct_face_bounds_array( is_latlonface: bool = False, is_face_GCA_list=None, ): - """Computes an array of face bounds.""" + """Computes an array of face bounds. + Result has shape (n_face, 2, 2), representing (n_face, lat_lon, min_max). + """ n_face = face_node_connectivity.shape[0] bounds_array = np.empty((n_face, 2, 2), dtype=np.float64) @@ -156,14 +156,7 @@ def _construct_face_bounds_array( # Iterate over each face in parallel for face_idx in prange(n_face): - # 1) Create the Cartesian Face Edge Nodes for the current face - cur_face_edge_nodes_cartesian = _get_cartesian_face_edge_nodes( - face_idx, face_node_connectivity, n_nodes_per_face, node_x, node_y, node_z - ) - # 2) Create the Spherical Face Edge Nodes for the current face - cur_face_edge_nodes_spherical = _get_spherical_face_edge_nodes( - face_idx, face_node_connectivity, n_nodes_per_face, node_lon, node_lat - ) + nodes_idx = face_node_connectivity[face_idx][: n_nodes_per_face[face_idx]] # TODO: This isn't currently used for the user API, consider updating in the future if is_face_GCA_list is not None: @@ -172,67 +165,76 @@ def _construct_face_bounds_array( is_GCA_list = None # 3) Populate the bounds for the current face - bounds_array[face_idx] = _construct_face_bounds( - cur_face_edge_nodes_cartesian, - cur_face_edge_nodes_spherical, + (lat_min, lat_max), (lon_min, lon_max) = _construct_face_bounds( + nodes_idx, + node_x, + node_y, + node_z, + node_lon, + node_lat, is_latlonface=is_latlonface, is_GCA_list=is_GCA_list, ) + bounds_array[face_idx, 0, 0] = lat_min + bounds_array[face_idx, 0, 1] = lat_max + bounds_array[face_idx, 1, 0] = lon_min + bounds_array[face_idx, 1, 1] = lon_max return bounds_array @njit(cache=True) def _construct_face_bounds( - face_edges_xyz, - face_edges_lonlat, + nodes_idx, + node_x, + node_y, + node_z, + node_lon, + node_lat, is_latlonface=False, is_GCA_list=None, ): - """Compute the bounds of a single face.""" + """Compute the bounds of a single face, returning ((lat_min, lat_max), (lon_min, lon_max)). + + nodes_idx : np.ndarray, shape (n_nodes_in_this_face,) + Node indices (within node_x, ...) for precisely all nodes in this face. + Likely from `face_node_connectivity[fidx][:n_nodes_per_face[fidx]]`. + node_x, node_y, node_z : np.ndarray, shape (n_nodes_total,) + Cartesian coordinates of all nodes. + (This method only uses the values at indices indicated by nodes_idx.) + node_lon, node_lat : np.ndarray, shape (n_nodes_total,) + Spherical coordinates of all nodes in radians. + (This method only uses the values at indices indicated by nodes_idx.) + """ + n_nodes = len(nodes_idx) # number of nodes in this face + max_i_node = n_nodes - 1 + # Check if face_edges contains pole points - has_north_pole = pole_point_inside_polygon(1, face_edges_xyz, face_edges_lonlat) - has_south_pole = pole_point_inside_polygon(-1, face_edges_xyz, face_edges_lonlat) + has_north_pole = pole_point_inside_polygon(1, nodes_idx, node_x, node_y, node_z) + has_south_pole = pole_point_inside_polygon(-1, nodes_idx, node_x, node_y, node_z) - # Initialize face_latlon_array with INT_FILL_VALUE - face_latlon_array = np.full((2, 2), np.nan, dtype=np.float64) + # Initialize latlonbox result: ((lat_min, lat_max), (lon_min, lon_max)) + llb = ((np.nan, np.nan), (np.nan, np.nan)) if has_north_pole or has_south_pole: # Initial assumption that the pole point is inside the face is_center_pole = True - pole_point_xyz = np.zeros(3, dtype=np.float64) - pole_point_lonlat = np.zeros(2, dtype=np.float64) - new_pt_latlon = np.zeros(2, dtype=np.float64) - if has_north_pole: - pole_point_xyz[2] = 1.0 # [0.0, 0.0, 1.0] - pole_point_lonlat[1] = np.pi / 2 # [0.0, pi/2] - new_pt_latlon[0] = np.pi / 2 # [pi/2, nan] - new_pt_latlon[1] = np.nan + pole_point_xyz = (0.0, 0.0, 1.0) + new_pt_latlon = (np.pi / 2, np.nan) else: - pole_point_xyz[2] = -1.0 # [0.0, 0.0, -1.0] - pole_point_lonlat[1] = -np.pi / 2 # [0.0, -pi/2] - new_pt_latlon[0] = -np.pi / 2 # [-pi/2, nan] - new_pt_latlon[1] = np.nan - - for i in range(face_edges_xyz.shape[0]): - edge_xyz = face_edges_xyz[i] - edge_lonlat = face_edges_lonlat[i] - - # Skip processing if the edge is marked as a dummy with a fill value - if np.any(edge_xyz == INT_FILL_VALUE): - continue - - # Extract cartesian coordinates of the edge's endpoints - n1_cart = edge_xyz[0] - n2_cart = edge_xyz[1] - n1_lonlat = edge_lonlat[0] - n2_lonlat = edge_lonlat[1] - - # Extract latitudes and longitudes of the nodes - node1_lon_rad = n1_lonlat[0] - node1_lat_rad = n1_lonlat[1] + pole_point_xyz = (0.0, 0.0, -1.0) + new_pt_latlon = (-np.pi / 2, np.nan) + + for i in range(n_nodes): + # edge is formed by nodes at (i1, i2) + i1 = nodes_idx[i] + i2 = nodes_idx[i + 1] if i < max_i_node else nodes_idx[0] + n1_cart = (node_x[i1], node_y[i1], node_z[i1]) + n2_cart = (node_x[i2], node_y[i2], node_z[i2]) + n1_lon = node_lon[i1] + n1_lat = node_lat[i1] # Determine if the edge's extreme latitudes need to be considered if is_GCA_list is not None: @@ -241,24 +243,24 @@ def _construct_face_bounds( is_GCA = not is_latlonface or n1_cart[2] != n2_cart[2] # Check if the node matches the pole point or if the pole point is within the edge - max_abs_diff = np.max(np.abs(n1_cart - pole_point_xyz)) + max_abs_diff = max(_numba_abs3(_numba_sub3(n1_cart, pole_point_xyz))) if max_abs_diff <= ERROR_TOLERANCE or point_within_gca( pole_point_xyz, n1_cart, n2_cart, ): is_center_pole = False - face_latlon_array = insert_pt_in_latlonbox( - face_latlon_array, new_pt_latlon - ) + llb = insert_pt_in_latlonbox(llb, new_pt_latlon) # Insert the current node's lat/lon into the latlonbox - face_latlon_array = insert_pt_in_latlonbox( - face_latlon_array, np.array([node1_lat_rad, node1_lon_rad]) - ) + llb = insert_pt_in_latlonbox(llb, (n1_lat, n1_lon)) # Determine extreme latitudes for GCA edges if is_GCA: + n2_lon = node_lon[i2] + n2_lat = node_lat[i2] + n1_lonlat = (n1_lon, n1_lat) + n2_lonlat = (n2_lon, n2_lat) lat_max = extreme_gca_latitude( (n1_cart, n2_cart), (n1_lonlat, n2_lonlat), "max" ) @@ -266,47 +268,33 @@ def _construct_face_bounds( (n1_cart, n2_cart), (n1_lonlat, n2_lonlat), "min" ) else: - lat_max = node1_lat_rad - lat_min = node1_lat_rad + lat_max = n1_lat + lat_min = n1_lat # Insert latitudinal extremes based on pole presence if has_north_pole: - face_latlon_array = insert_pt_in_latlonbox( - face_latlon_array, np.array([lat_min, node1_lon_rad]) - ) - face_latlon_array[0, 1] = np.pi / 2 # Upper latitude bound + llb = insert_pt_in_latlonbox(llb, (lat_min, n1_lon)) + # Upper latitude bound = pi/2 (North Pole) + llb = ((llb[0][0], np.pi / 2), (llb[1][0], llb[1][1])) else: - face_latlon_array = insert_pt_in_latlonbox( - face_latlon_array, np.array([lat_max, node1_lon_rad]) - ) - face_latlon_array[0, 0] = -np.pi / 2 # Lower latitude bound + llb = insert_pt_in_latlonbox(llb, (lat_max, n1_lon)) + # Lower latitude bound = -pi/2 (South Pole) + llb = ((-np.pi / 2, llb[0][1]), (llb[1][0], llb[1][1])) # Adjust longitude bounds globally if the pole is centrally inside the polygon if is_center_pole: - face_latlon_array[1, 0] = 0.0 - face_latlon_array[1, 1] = 2 * np.pi + llb = ((llb[0][0], llb[0][1]), (0.0, 2 * np.pi)) else: # Normal Face - for i in range(face_edges_xyz.shape[0]): - edge_xyz = face_edges_xyz[i] - edge_lonlat = face_edges_lonlat[i] - - # Skip processing if the edge is marked as a dummy with a fill value - if np.any(edge_xyz == INT_FILL_VALUE): - continue - - # Extract cartesian coordinates of the edge's endpoints - n1_cart = edge_xyz[0] - n2_cart = edge_xyz[1] - n1_lonlat = edge_lonlat[0] - n2_lonlat = edge_lonlat[1] - - # Extract latitudes and longitudes of the nodes - node1_lon_rad = n1_lonlat[0] - node1_lat_rad = n1_lonlat[1] - # node2_lon_rad = n2_lonlat[0] - node2_lat_rad = n2_lonlat[1] + for i in range(n_nodes): + # edge is formed by nodes at (i1, i2) + i1 = nodes_idx[i] + i2 = nodes_idx[i + 1] if i < max_i_node else nodes_idx[0] + n1_cart = (node_x[i1], node_y[i1], node_z[i1]) + n2_cart = (node_x[i2], node_y[i2], node_z[i2]) + n1_lon = node_lon[i1] + n1_lat = node_lat[i1] # Determine if the edge's extreme latitudes need to be considered if is_GCA_list is not None: @@ -315,13 +303,15 @@ def _construct_face_bounds( is_GCA = not is_latlonface or n1_cart[2] != n2_cart[2] # The node itself is always inside the box. - face_latlon_array = insert_pt_in_latlonbox( - face_latlon_array, np.array([node1_lat_rad, node1_lon_rad]) - ) + llb = insert_pt_in_latlonbox(llb, (n1_lat, n1_lon)) # A great circle arc can reach a latitude beyond both of its # endpoints; that interior extreme widens the box. if is_GCA: + n2_lon = node_lon[i2] + n2_lat = node_lat[i2] + n1_lonlat = (n1_lon, n1_lat) + n2_lonlat = (n2_lon, n2_lat) lat_max = extreme_gca_latitude( (n1_cart, n2_cart), (n1_lonlat, n2_lonlat), "max" ) @@ -329,21 +319,17 @@ def _construct_face_bounds( (n1_cart, n2_cart), (n1_lonlat, n2_lonlat), "min" ) if ( - abs(node1_lat_rad - lat_max) > ERROR_TOLERANCE - and abs(node2_lat_rad - lat_max) > ERROR_TOLERANCE + abs(n1_lat - lat_max) > ERROR_TOLERANCE + and abs(n2_lat - lat_max) > ERROR_TOLERANCE ): - face_latlon_array = insert_pt_in_latlonbox( - face_latlon_array, np.array([lat_max, node1_lon_rad]) - ) + llb = insert_pt_in_latlonbox(llb, (lat_max, n1_lon)) if ( - abs(node1_lat_rad - lat_min) > ERROR_TOLERANCE - and abs(node2_lat_rad - lat_min) > ERROR_TOLERANCE + abs(n1_lat - lat_min) > ERROR_TOLERANCE + and abs(n2_lat - lat_min) > ERROR_TOLERANCE ): - face_latlon_array = insert_pt_in_latlonbox( - face_latlon_array, np.array([lat_min, node1_lon_rad]) - ) + llb = insert_pt_in_latlonbox(llb, (lat_min, n1_lon)) - return face_latlon_array + return llb def _face_bounds_lat_degrees(bounds): @@ -431,54 +417,50 @@ def insert_pt_in_latlonbox(old_box, new_pt, is_lon_periodic=True): Parameters ---------- - old_box : np.ndarray - The original latitude-longitude box in radians, a 2x2 array: - [[min_lat, max_lat], - [left_lon, right_lon]]. - new_pt : np.ndarray - The new latitude-longitude point in radians, an array: [lat, lon]. + old_box : np.ndarray or iterable of 2 length-2 iterables + The original latitude-longitude box in radians: ((lat_min, lat_max), (lon_min, lon_max)). + new_pt : np.ndarray or iterable of length 2 + The new latitude-longitude point in radians: (lat, lon). is_lon_periodic : bool, optional Flag indicating if the latitude-longitude box is periodic in longitude (default is True). Returns ------- - np.ndarray - Updated latitude-longitude box including the new point in radians. + tuple of 2 length-2 tuples + Updated latitude-longitude box including the new point in radians: + ((lat_min, lat_max), (lon_min, lon_max)). Raises ------ Exception If logic errors occur in the calculation process. """ - # Check if the new point is a fill value - all_fill = all_elements_nan(new_pt) - if all_fill: - return old_box - - # Create a copy of the old box - latlon_box = np.copy(old_box) - - # Extract latitude and longitude from the new point + lat_min, lat_max = old_box[0] + lon_min, lon_max = old_box[1] lat_pt = new_pt[0] lon_pt = new_pt[1] + # No changes needed if the new point is a fill value + if np.isnan(lat_pt) and np.isnan(lon_pt): + return ((lat_min, lat_max), (lon_min, lon_max)) + # Normalize the longitude if it's not a fill value if not np.isnan(lon_pt): lon_pt = lon_pt % (2.0 * np.pi) # Check if the latitude range is uninitialized and update it - if np.isnan(old_box[0, 0]) and np.isnan(old_box[0, 1]): - latlon_box[0, 0] = lat_pt - latlon_box[0, 1] = lat_pt + if np.isnan(lat_min) and np.isnan(lat_max): + lat_min = lat_pt + lat_max = lat_pt else: # Update latitude range - latlon_box[0, 0] = min(latlon_box[0, 0], lat_pt) - latlon_box[0, 1] = max(latlon_box[0, 1], lat_pt) + lat_min = min(lat_min, lat_pt) + lat_max = max(lat_max, lat_pt) # Check if the longitude range is uninitialized and update it - if np.isnan(old_box[1, 0]) and np.isnan(old_box[1, 1]): - latlon_box[1, 0] = lon_pt - latlon_box[1, 1] = lon_pt + if np.isnan(lon_min) and np.isnan(lon_max): + lon_min = lon_pt + lon_max = lon_pt else: # Validate longitude point if not np.isnan(lon_pt) and (lon_pt < 0.0 or lon_pt > 2.0 * np.pi): @@ -486,28 +468,33 @@ def insert_pt_in_latlonbox(old_box, new_pt, is_lon_periodic=True): # (numba complains about f-strings, so don't put `lon_pt` value in message.) # Check for pole points - is_pole_point = False - if np.isnan(lon_pt) and any_close_lat(lat_pt, ERROR_TOLERANCE): - is_pole_point = True - - if is_pole_point: - # Update latitude for pole points - if np.isclose(lat_pt, 0.5 * np.pi, ERROR_TOLERANCE): - latlon_box[0, 1] = 0.5 * np.pi # Update max_lat for North Pole - elif np.isclose(lat_pt, -0.5 * np.pi, ERROR_TOLERANCE): - latlon_box[0, 0] = -0.5 * np.pi # Update min_lat for South Pole + NORTH_POLE_LAT = 0.5 * np.pi + SOUTH_POLE_LAT = -0.5 * np.pi + is_north_pole = False + is_south_pole = False + if np.isnan(lon_pt): + is_north_pole = np.isclose(lat_pt, NORTH_POLE_LAT, ERROR_TOLERANCE) + if not is_north_pole: + is_south_pole = np.isclose(lat_pt, SOUTH_POLE_LAT, ERROR_TOLERANCE) + + if is_north_pole: + lat_max = NORTH_POLE_LAT + elif is_south_pole: + lat_min = SOUTH_POLE_LAT else: # Update longitude range based on periodicity if not is_lon_periodic: # Non-periodic: straightforward min and max updates - latlon_box[1, 0] = min(latlon_box[1, 0], lon_pt) - latlon_box[1, 1] = max(latlon_box[1, 1], lon_pt) + # latlon_box[1, 0] = min(latlon_box[1, 0], lon_pt) + # latlon_box[1, 1] = max(latlon_box[1, 1], lon_pt) + lon_min = min(lon_min, lon_pt) + lon_max = max(lon_max, lon_pt) else: # Periodic longitude handling # Determine if the new point extends the current longitude range # considering the periodic boundary at 2*pi - left_lon = latlon_box[1, 0] - right_lon = latlon_box[1, 1] + left_lon = lon_min + right_lon = lon_max # Check if the current box wraps around wraps_around = left_lon > right_lon @@ -518,63 +505,44 @@ def insert_pt_in_latlonbox(old_box, new_pt, is_lon_periodic=True): # Decide to extend either the left or the right # Calculate the new width for both possibilities # Option 1: Extend the left boundary to lon_pt - box_a = np.copy(latlon_box) - box_a[1, 0] = lon_pt - d_width_a = _get_latlonbox_width(box_a) - + d_width_a = _get_lon_width(lon_pt, right_lon) # Option 2: Extend the right boundary to lon_pt - box_b = np.copy(latlon_box) - box_b[1, 1] = lon_pt - d_width_b = _get_latlonbox_width(box_b) - + d_width_b = _get_lon_width(left_lon, lon_pt) # Ensure widths are non-negative if (d_width_a < 0.0) or (d_width_b < 0.0): raise AssertionError( "Logic error in longitude box width calculation: computed negative width" ) - # Choose the box with the smaller width if d_width_a < d_width_b: - latlon_box = box_a + lon_min = lon_pt else: - latlon_box = box_b + lon_max = lon_pt else: # If the box does not wrap around, simply update min or max longitude if lon_pt < left_lon or lon_pt > right_lon: # Calculate the new width for both possibilities # Option 1: Extend the left boundary to lon_pt - box_a = np.copy(latlon_box) - box_a[1, 0] = lon_pt - d_width_a = _get_latlonbox_width(box_a) - + d_width_a = _get_lon_width(lon_pt, right_lon) # Option 2: Extend the right boundary to lon_pt - box_b = np.copy(latlon_box) - box_b[1, 1] = lon_pt - d_width_b = _get_latlonbox_width(box_b) - + d_width_b = _get_lon_width(left_lon, lon_pt) # Ensure widths are non-negative if (d_width_a < 0.0) or (d_width_b < 0.0): raise AssertionError( "Logic error in longitude box width calculation: computed negative width" ) - # Choose the box with the smaller width if d_width_a < d_width_b: - latlon_box = box_a + lon_min = lon_pt else: - latlon_box = box_b + lon_max = lon_pt - return latlon_box + return ((lat_min, lat_max), (lon_min, lon_max)) @njit(cache=True) -def _get_latlonbox_width(latlonbox_rad): - """Calculate the width of a latitude-longitude box in radians. The box - should be represented by a 2x2 array in radians and lon0 represent the - "left" side of the box. while lon1 represent the "right" side of the box. - - This function computes the width of a given latitude-longitude box. It - accounts for periodicity in the longitude direction. +def _get_lon_width(lon0, lon1): + """Calculate the width of a longitude range in radians, accounting for periodicity. Non-Periodic Longitude: This is the usual case where longitude values are considered within a fixed range, typically between -180 and 180 degrees, or 0 and 360 degrees. @@ -587,10 +555,10 @@ def _get_latlonbox_width(latlonbox_rad): Parameters ---------- - latlonbox_rad : np.ndarray - A latitude-longitude box represented by a 2x2 array in radians and lon0 represent the "left" side of the box. - while lon1 represent the "right" side of the box: - [[lat_0, lat_1], [lon_0, lon_1]]. + lon0: float + The "left" side of the box, in radians + lon1: float + The "right" side of the box, in radians Returns ------- @@ -606,8 +574,6 @@ def _get_latlonbox_width(latlonbox_rad): If the input longitude range is flagged as periodic but in the form [lon0, lon1] where lon0 < lon1. The function will automatically use the is_lon_periodic=False instead. """ - lon0, lon1 = latlonbox_rad[1] - if lon0 != INT_FILL_VALUE: lon0 = np.mod(lon0, 2 * np.pi) if lon1 != INT_FILL_VALUE: diff --git a/uxarray/grid/geometry.py b/uxarray/grid/geometry.py index 9a989a820..739ad3dbf 100644 --- a/uxarray/grid/geometry.py +++ b/uxarray/grid/geometry.py @@ -9,12 +9,14 @@ INT_FILL_VALUE, MACHINE_EPSILON, ) -from uxarray.grid.coordinates import _xyz_to_lonlat_rad from uxarray.grid.intersections import ( gca_gca_intersection, ) from uxarray.grid.point_in_face import _point_in_face from uxarray.utils.imports import _raise_hint_if_optional_deps_missing +from uxarray.utils.numba_math import ( + _numba_allclose3, +) from uxarray.utils.parallel import parallel_njit POLE_POINTS_XYZ = { @@ -778,143 +780,70 @@ def _convert_shells_to_polygons(shells): def _pole_point_inside_polygon_cartesian(pole, face_edges_xyz): + """Determines if a pole point is inside a polygon. + This is mostly a thin wrapper around the njit-compiled `pole_point_inside_polygon`, + which expects face_edges_xyz inputs instead of nodes_idx, node_x, node_y, node_z. + """ if isinstance(pole, str): pole = POLE_NAME_TO_INT[pole] - - x = face_edges_xyz[:, :, 0] - y = face_edges_xyz[:, :, 1] - z = face_edges_xyz[:, :, 2] - - lon, lat = _xyz_to_lonlat_rad(x, y, z) - - face_edges_lonlat = np.stack((lon, lat), axis=2) - - return pole_point_inside_polygon(pole, face_edges_xyz, face_edges_lonlat) + # drop zero-length edges (e.g. padding rows, which may be fill values or + # fill values converted from lonlat to some arbitrary point) + keep = ~np.all(face_edges_xyz[:, 0] == face_edges_xyz[:, 1], axis=1) + face_edges_xyz = face_edges_xyz[keep] + # construct nodes_idx, node_x, node_y, node_z arrays from face_edges_xyz. + # (Just need the start node for each edge.) + nodes_idx = np.arange(face_edges_xyz.shape[0], dtype=INT_DTYPE) + node_x = face_edges_xyz[:, 0, 0] + node_y = face_edges_xyz[:, 0, 1] + node_z = face_edges_xyz[:, 0, 2] + return pole_point_inside_polygon(pole, nodes_idx, node_x, node_y, node_z) @njit(cache=True) -def pole_point_inside_polygon(pole, face_edges_xyz, face_edges_lonlat): - """Determines if a pole point is inside a polygon.""" +def pole_point_inside_polygon(pole, nodes_idx, node_x, node_y, node_z): + """Determines if a pole point is inside this polygon (the face formed by these nodes). + + pole : int + 1 for North pole, -1 for South pole + nodes_idx : np.ndarray, shape (n_nodes_in_this_face,) + Node indices (within node_x, node_y, node_z) for precisely all nodes in this face. + Likely from `face_node_connectivity[fidx][:n_nodes_per_face[fidx]]`. + node_x, node_y, node_z : np.ndarray, shape (n_nodes_total,) + Cartesian coordinates of all nodes. + (This method only uses the values at indices indicated by nodes_idx.) + """ + # The idea is to pick a point outside the polygon, draw an edge from there to `pole` + # and count the number of intersections between that edge and the polygon's edges. + # The `pole` is inside the polygon if and only if the number of intersections is odd. + # For fully-north-hemisphere faces and fully-south-hemisphere faces it is easy to pick + # such a point; just pick the opposite pole. + # For faces crossing the equator, split the test into two pieces, picking the opposite + # pole for each piece. (This is a hand-waving explanation but the geometry works out!) if pole != 1 and pole != -1: raise ValueError("Pole must be 1 (North) or -1 (South)") # (numba complains about f-strings, so don't put `pole` value in message.) - # Define constants within the function - pole_point_xyz = np.empty(3, dtype=np.float64) - pole_point_xyz[0] = 0.0 - pole_point_xyz[1] = 0.0 - pole_point_xyz[2] = 1.0 * pole - - pole_point_lonlat = np.empty(2, dtype=np.float64) - pole_point_lonlat[0] = 0.0 - pole_point_lonlat[1] = (math.pi / 2) * pole + pole_z = 1.0 * pole - REFERENCE_POINT_EQUATOR_XYZ = np.empty(3, dtype=np.float64) - REFERENCE_POINT_EQUATOR_XYZ[0] = 1.0 - REFERENCE_POINT_EQUATOR_XYZ[1] = 0.0 - REFERENCE_POINT_EQUATOR_XYZ[2] = 0.0 - - REFERENCE_POINT_EQUATOR_LONLAT = np.empty(2, dtype=np.float64) - REFERENCE_POINT_EQUATOR_LONLAT[0] = 0.0 - REFERENCE_POINT_EQUATOR_LONLAT[1] = 0.0 - - # Classify the polygon's location - location = _classify_polygon_location(face_edges_xyz) + # 1: fully in North hemisphere; -1: fully in South hemisphere; 0: polygon crosses equator + location = _classify_polygon_location(nodes_idx, node_z) if (location == 1 and pole == -1) or (location == -1 and pole == 1): return False elif location == -1 or location == 1: - # Initialize ref_edge_xyz - ref_edge_xyz = np.empty((2, 3), dtype=np.float64) - ref_edge_xyz[0, 0] = pole_point_xyz[0] - ref_edge_xyz[0, 1] = pole_point_xyz[1] - ref_edge_xyz[0, 2] = pole_point_xyz[2] - ref_edge_xyz[1, :] = REFERENCE_POINT_EQUATOR_XYZ - - # Initialize ref_edge_lonlat - ref_edge_lonlat = np.empty((2, 2), dtype=np.float64) - ref_edge_lonlat[0, 0] = pole_point_lonlat[0] - ref_edge_lonlat[0, 1] = pole_point_lonlat[1] - ref_edge_lonlat[1, :] = REFERENCE_POINT_EQUATOR_LONLAT - - intersection_count = _check_intersection(ref_edge_xyz, face_edges_xyz) + intersection_count = _check_pole_ref_edge_intersection( + pole_z, nodes_idx, node_x, node_y, node_z, hemisphere_filter=0 + ) return (intersection_count % 2) != 0 elif location == 0: # Equator - # Initialize ref_edge_north_xyz and ref_edge_north_lonlat - ref_edge_north_xyz = np.empty((2, 3), dtype=np.float64) - ref_edge_north_xyz[0, 0] = 0.0 - ref_edge_north_xyz[0, 1] = 0.0 - ref_edge_north_xyz[0, 2] = 1.0 - ref_edge_north_xyz[1, :] = REFERENCE_POINT_EQUATOR_XYZ - - ref_edge_north_lonlat = np.empty((2, 2), dtype=np.float64) - ref_edge_north_lonlat[0, 0] = 0.0 - ref_edge_north_lonlat[0, 1] = math.pi / 2 - ref_edge_north_lonlat[1, :] = REFERENCE_POINT_EQUATOR_LONLAT - - # Initialize ref_edge_south_xyz and ref_edge_south_lonlat - ref_edge_south_xyz = np.empty((2, 3), dtype=np.float64) - ref_edge_south_xyz[0, 0] = 0.0 - ref_edge_south_xyz[0, 1] = 0.0 - ref_edge_south_xyz[0, 2] = -1.0 - ref_edge_south_xyz[1, :] = REFERENCE_POINT_EQUATOR_XYZ - - ref_edge_south_lonlat = np.empty((2, 2), dtype=np.float64) - ref_edge_south_lonlat[0, 0] = 0.0 - ref_edge_south_lonlat[0, 1] = -math.pi / 2 - ref_edge_south_lonlat[1, :] = REFERENCE_POINT_EQUATOR_LONLAT - - # Classify edges based on z-coordinate - n_edges = face_edges_xyz.shape[0] - north_edges_xyz = np.empty((n_edges, 2, 3), dtype=np.float64) - north_edges_lonlat = np.empty((n_edges, 2, 2), dtype=np.float64) - south_edges_xyz = np.empty((n_edges, 2, 3), dtype=np.float64) - south_edges_lonlat = np.empty((n_edges, 2, 2), dtype=np.float64) - north_count = 0 - south_count = 0 - - for i in range(n_edges): - edge_xyz = face_edges_xyz[i] - edge_lonlat = face_edges_lonlat[i] - if edge_xyz[0, 2] > 0 or edge_xyz[1, 2] > 0: - north_edges_xyz[north_count] = edge_xyz - north_edges_lonlat[north_count] = edge_lonlat - north_count += 1 - elif edge_xyz[0, 2] < 0 or edge_xyz[1, 2] < 0: - south_edges_xyz[south_count] = edge_xyz - south_edges_lonlat[south_count] = edge_lonlat - south_count += 1 - else: - # skip edges exactly on the equator - continue - - if north_count > 0: - north_edges_xyz = north_edges_xyz[:north_count] - north_edges_lonlat = north_edges_lonlat[:north_count] - else: - north_edges_xyz = np.empty((0, 2, 3), dtype=np.float64) - north_edges_lonlat = np.empty((0, 2, 2), dtype=np.float64) - - if south_count > 0: - south_edges_xyz = south_edges_xyz[:south_count] - south_edges_lonlat = south_edges_lonlat[:south_count] - else: - south_edges_xyz = np.empty((0, 2, 3), dtype=np.float64) - south_edges_lonlat = np.empty((0, 2, 2), dtype=np.float64) - - # Count south intersections - north_intersections = _check_intersection( - ref_edge_north_xyz, - north_edges_xyz, + north_intersections = _check_pole_ref_edge_intersection( + 1.0, nodes_idx, node_x, node_y, node_z, hemisphere_filter=1 ) - - # Count south intersections - south_intersections = _check_intersection( - ref_edge_south_xyz, - south_edges_xyz, + south_intersections = _check_pole_ref_edge_intersection( + -1.0, nodes_idx, node_x, node_y, node_z, hemisphere_filter=-1 ) return ((north_intersections + south_intersections) % 2) != 0 @@ -928,68 +857,106 @@ def pole_point_inside_polygon(pole, face_edges_xyz, face_edges_lonlat): @njit(cache=True) -def _classify_polygon_location(face_edge_cart): - """Classify the location of the polygon relative to the hemisphere.""" - z_coords = face_edge_cart[:, :, 2] - if np.all(z_coords > 0): # Use strict inequality +def _classify_polygon_location(nodes_idx, node_z): + """Classify location of this polygon relative to the North and South hemispheres. + Returns 1 (-1) if fully in North (South) hemisphere, else 0 (crosses equator). + + nodes_idx : np.ndarray, shape (n_nodes_in_this_face,) + Node indices (within node_z) for precisely all nodes in this face. + node_z : np.ndarray, shape (n_nodes_total,) + Cartesian z-coordinates of all nodes. + """ + n_nodes = len(nodes_idx) + north = 0 + south = 0 + for idx in nodes_idx: + z = node_z[idx] + if z > 0: + north += 1 + elif z < 0: + south += 1 + if north == n_nodes: return 1 # North - elif np.all(z_coords < 0): # Use strict inequality + elif south == n_nodes: return -1 # South else: - return 0 # Equator + return 0 # Crosses equator @njit(cache=True) -def _check_intersection(ref_edge_xyz, edges_xyz): +def _check_pole_ref_edge_intersection( + pole_z, + nodes_idx, + node_x, + node_y, + node_z, + hemisphere_filter=0, +): """Check the number of intersections of the reference edge with the given edges. + The reference edge's first point MUST be the North or South pole. Parameters ---------- - ref_edge_xyz : np.ndarray - Reference edge to check intersections against. Shape: (2, 3) - ref_edge_lonlat : np.ndarray - Reference edge longitude and latitude. Shape: (2, 2) - edges_xyz : np.ndarray - Edges to check for intersections. Shape: (n_edges, 2, 3) - edges_lonlat : np.ndarray - Longitude and latitude of the edges. Shape: (n_edges, 2, 2) + pole_z : float + z-coordinate of the pole (1.0 for North, -1.0 for South) + nodes_idx : np.ndarray, shape (n_nodes_in_this_face,) + Node indices (within node_x, node_y, node_z) for precisely all nodes in this face. + node_x, node_y, node_z : np.ndarray, shape (n_nodes_total,) + Cartesian coordinates of all nodes. + hemisphere_filter : 0, 1, or -1 + Optional filter to include only some of the edges. + If 0, include all edges. This is the default. + If 1, only include edges which are at least partially in the North hemisphere. + If -1, only include edges which are fully in the South hemisphere. Returns ------- int - Count of intersections. + Count of intersections, or 1 if the pole lies on an edge of the polygon. """ - pole_point_xyz = ref_edge_xyz[0] - n_edges = edges_xyz.shape[0] + pole_point_xyz = (0.0, 0.0, pole_z) + REFERENCE_POINT_EQUATOR_XYZ = (1.0, 0.0, 0.0) + ref_edge_xyz = (pole_point_xyz, REFERENCE_POINT_EQUATOR_XYZ) + n_nodes = len(nodes_idx) # number of nodes in this face + max_i_node = n_nodes - 1 - # Assuming at most 2 intersections per edge - max_intersections = n_edges * 2 - intersection_points = np.empty((max_intersections, 3), dtype=np.float64) intersection_count = 0 - for i in range(n_edges): - edge_xyz = edges_xyz[i] + for i in range(n_nodes): + i1 = nodes_idx[i] + i2 = nodes_idx[i + 1] if i < max_i_node else nodes_idx[0] + if hemisphere_filter != 0 and not _edge_in_hemisphere( + (node_z[i1], node_z[i2]), hemisphere_filter + ): + continue + n1_xyz = (node_x[i1], node_y[i1], node_z[i1]) + n2_xyz = (node_x[i2], node_y[i2], node_z[i2]) + edge_xyz = (n1_xyz, n2_xyz) - # compute intersection intersections_i = gca_gca_intersection(ref_edge_xyz, edge_xyz) + # (Always 2 length-3 tuples; NaNs represent "no intersection point") - if math.isfinite(intersections_i[0][0]): # at least 1 intersection point - if not math.isfinite(intersections_i[1][0]): # only 1 intersection point - # Only one point - point = intersections_i[0] - if np.allclose(point, pole_point_xyz, atol=ERROR_TOLERANCE): - return True - intersection_points[intersection_count] = point + if math.isfinite(intersections_i[0][0]): + pointA = intersections_i[0] + if _numba_allclose3(pointA, pole_point_xyz, atol=ERROR_TOLERANCE): + return ( + 1 # the pole intersects with this edge! Exit early, for efficiency. + ) + if intersection_count == 0: + # allocate array to store intersection points (allocate inside + # the loop for efficiency; many faces will have zero intersections.) + max_intersections = n_nodes * 2 + intersection_points = np.empty((max_intersections, 3), dtype=np.float64) + intersection_points[intersection_count] = pointA + intersection_count += 1 + + if math.isfinite(intersections_i[1][0]): + # There's a 2nd intersection point! + pointB = intersections_i[1] + if _numba_allclose3(pointB, pole_point_xyz, atol=ERROR_TOLERANCE): + return 1 # the pole intersects with this edge! Exit early, for efficiency. + intersection_points[intersection_count] = pointB intersection_count += 1 - else: - # Exactly 2 points (gca_gca_intersection always gives 0, 1, or 2 intersections) - num_points = 2 - for j in range(num_points): - point = intersections_i[j] - if np.allclose(point, pole_point_xyz, atol=ERROR_TOLERANCE): - return True - intersection_points[intersection_count] = point - intersection_count += 1 if intersection_count == 0: return 0 @@ -1002,16 +969,47 @@ def _check_intersection(ref_edge_xyz, edges_xyz): # If there's only one unique intersection point, check if it matches any edge nodes if unique_count == 1: intersection_point = unique_intersection_points[0] - for i in range(n_edges): - edge_xyz = edges_xyz[i] - if np.allclose( - intersection_point, edge_xyz[0], atol=ERROR_TOLERANCE - ) or np.allclose(intersection_point, edge_xyz[1], atol=ERROR_TOLERANCE): + for i in range(n_nodes): + i1 = nodes_idx[i] + i2 = nodes_idx[i + 1] if i < max_i_node else nodes_idx[0] + if hemisphere_filter != 0 and not _edge_in_hemisphere( + (node_z[i1], node_z[i2]), hemisphere_filter + ): + continue + n1_xyz = (node_x[i1], node_y[i1], node_z[i1]) + n2_xyz = (node_x[i2], node_y[i2], node_z[i2]) + + if _numba_allclose3( + intersection_point, n1_xyz, atol=ERROR_TOLERANCE + ) or _numba_allclose3(intersection_point, n2_xyz, atol=ERROR_TOLERANCE): return 0 return unique_count +@njit(cache=True) +def _edge_in_hemisphere(edge_z, hemisphere): + """returns whether the edge with these z coords falls in the given hemisphere. + Convention: equator-crossing edges are treated as falling in the North hemisphere. + (This convention ensures such edges are not dropped entirely, during + _check_pole_ref_edge_intersection.) + Edges fully on the equator (z=0 for both nodes) fall in neither hemisphere. + + edge_z : iterable of 2 floats + z coordinates of the edge's two endpoints + hemisphere : -1 or 1 + -1 for South hemisphere, 1 for North hemisphere + """ + za, zb = edge_z + north = za > 0 or zb > 0 + if hemisphere == 1: + return north + elif hemisphere == -1: + return (not north) and (za < 0 or zb < 0) + else: + raise ValueError("hemisphere must be 1 (North) or -1 (South)") + + def _construct_boundary_edge_indices(edge_face_connectivity): """Index the missing edges on a partial grid with holes, that is a region of the grid that is not covered by any geometry.""" diff --git a/uxarray/grid/point_in_face.py b/uxarray/grid/point_in_face.py index 206ec9466..71660ca35 100644 --- a/uxarray/grid/point_in_face.py +++ b/uxarray/grid/point_in_face.py @@ -60,12 +60,12 @@ def _point_in_face( ---------- point : iterable of length 3 3D unit-vector of the query point on the unit sphere. - nodes_idx : np.ndarray, shape (n_nodes,) + nodes_idx : np.ndarray, shape (n_nodes_in_this_face,) Node indices (within node_x, node_y, node_z) for precisely all nodes in this face. Likely from `face_node_connectivity[fidx][:n_nodes_per_face[fidx]]`. - node_x, node_y, node_z : np.ndarray, shape (n_nodes,) + node_x, node_y, node_z : np.ndarray, shape (n_nodes_total,) Cartesian coordinates of all nodes. - (This method uses the values at indices indicated by nodes_idx.) + (This method only uses the values at indices indicated by nodes_idx.) Returns ------- @@ -79,7 +79,7 @@ def _point_in_face( # simply asking to provide a single array of x, y, z coordinates for all nodes; # the former avoids any need to create a tiny numpy array to store the coordinates. - n_nodes = len(nodes_idx) + n_nodes = len(nodes_idx) # number of nodes in this face max_i_node = n_nodes - 1 # Check for an exact hit with any of the corner nodes diff --git a/uxarray/grid/utils.py b/uxarray/grid/utils.py index f1b363866..97668eadd 100644 --- a/uxarray/grid/utils.py +++ b/uxarray/grid/utils.py @@ -456,117 +456,6 @@ def _get_lonlat_rad_face_edge_nodes_array( return face_edges_lonlat_rad.reshape(n_face, n_max_face_edges, 2, 2) -@njit(cache=True) -def _get_cartesian_face_edge_nodes( - face_idx, face_node_connectivity, n_edges_per_face, node_x, node_y, node_z -): - """Computes the Cartesian Coordinates of the edge nodes that make up a given face. - - Parameters - ---------- - face_idx : int - The index of the face to construct the edge nodes - face_node_connectivity : np.ndarray - Face Node Connectivity array - n_edges_per_face : np.ndarray - Number of non-fill-value edges for each face - node_x : np.ndarray - Cartesian x coordinates - node_y : np.ndarray - Cartesian y coordinates - node_z : np.ndarray - Cartesian z coordinates - - Returns - ------- - face_edge_nodes: np.ndarray - Cartesian coordinates of the edge nodes that make up a given face - """ - # Number non-fill-value edges - n_edges = n_edges_per_face[face_idx] - - # Allocate data for face_edge_nodes - face_edge_nodes = np.empty((n_edges, 2, 3), dtype=np.float64) - - start_nodes = face_node_connectivity[face_idx, 0:n_edges] - end_nodes = np.roll(start_nodes, -1) - - # Assign x coordinates of start and end nodes - face_edge_nodes[0:n_edges, 0, 0] = node_x[start_nodes] - face_edge_nodes[0:n_edges, 1, 0] = node_x[end_nodes] - - # Assign y coordinates of start and end nodes - face_edge_nodes[0:n_edges, 0, 1] = node_y[start_nodes] - face_edge_nodes[0:n_edges, 1, 1] = node_y[end_nodes] - - # Assign z coordinates of start and end nodes - face_edge_nodes[0:n_edges, 0, 2] = node_z[start_nodes] - face_edge_nodes[0:n_edges, 1, 2] = node_z[end_nodes] - - return face_edge_nodes - - -@njit(cache=True) -def _get_spherical_face_edge_nodes( - face_idx, face_node_connectivity, n_edges_per_face, node_lon, node_lat -): - """Computes the Spherical Coordinates of the edge nodes that make up a given face. - - Parameters - ---------- - face_idx : int - The index of the face to construct the edge nodes - face_node_connectivity : np.ndarray - Face Node Connectivity array - n_edges_per_face : np.ndarray - Number of non-fill-value edges for each face - node_lon : np.ndarray - Longitude coordinates - node_lat : np.ndarray - Latitude coordinates - - Returns - ------- - face_edge_nodes: np.ndarray - Spherical coordinates of the edge nodes that make up a given face - """ - # Number non-fill-value edges - n_edges = n_edges_per_face[face_idx] - - # Allocate data for face_edge_nodes - face_edge_nodes = np.empty((n_edges, 2, 2), dtype=np.float64) - - start_nodes = face_node_connectivity[face_idx, 0:n_edges] - end_nodes = np.roll(start_nodes, -1) - - # Assign longitude coordinates of start and end nodes - face_edge_nodes[0:n_edges, 0, 0] = node_lon[start_nodes] - face_edge_nodes[0:n_edges, 1, 0] = node_lon[end_nodes] - - # Assign latitude coordinates of start and end nodes - face_edge_nodes[0:n_edges, 0, 1] = node_lat[start_nodes] - face_edge_nodes[0:n_edges, 1, 1] = node_lat[end_nodes] - - return face_edge_nodes - - -@njit(cache=True) -def all_elements_nan(arr): - """Check if all elements in an array are np.nan.""" - for i in range(arr.shape[0]): - if not np.isnan(arr[i]): - return False - return True - - -@njit(cache=True) -def any_close_lat(lat_pt, atol): - """Check if the latitude point is close to either the North or South Pole.""" - return np.isclose(lat_pt, 0.5 * np.pi, atol) or np.isclose( - lat_pt, -0.5 * np.pi, atol - ) - - def make_setter(key: str): """Return a setter that assigns the value to self._ds[key] after type-checking.""" diff --git a/uxarray/utils/numba_math.py b/uxarray/utils/numba_math.py index 6fcafb656..50769ecf2 100644 --- a/uxarray/utils/numba_math.py +++ b/uxarray/utils/numba_math.py @@ -77,6 +77,12 @@ def _numba_sqrt3(u): return np.sqrt(u[0]), np.sqrt(u[1]), np.sqrt(u[2]) +@njit(cache=True) +def _numba_abs3(u): + """component-wise absolute value of 3-vector; returns (abs(u[0]), abs(u[1]), abs(u[2]))""" + return abs(u[0]), abs(u[1]), abs(u[2]) + + # ------- vector arithmetic ------- #