-
Notifications
You must be signed in to change notification settings - Fork 168
2119 spatial hashing #2132
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
2119 spatial hashing #2132
Changes from 6 commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
ef757f9
Add spatialhash class
fluidnumerics-joe ffe3fc2
[#2199] Add get_spatial_hash method to xgrid class
fluidnumerics-joe 7756dba
[#2119] Add spatial hash init test and resolve init bugs
fluidnumerics-joe 83fdf5f
Fix units to degrees for spatialhash grid
fluidnumerics-joe 37b7210
Switch to spatialhash query for initial guess
fluidnumerics-joe df788b4
Resolve correctness bug
fluidnumerics-joe fe54538
Remove global_grid option; hashgrid bounds taken from parent grid bou…
fluidnumerics-joe ca6e266
Remove unneccesary commented out imports
fluidnumerics-joe 1c3958c
Remove old comments/debug statements
fluidnumerics-joe 27b16ee
Remove global_grid arg to spatialhash
fluidnumerics-joe 88e416b
Remove debug statement
fluidnumerics-joe 9622349
Prefer barycentric_coordinates implementation in parcels.spatialhash
fluidnumerics-joe 3e2d18e
Move xbound,ybound calculation to spatialhash.__init__
fluidnumerics-joe 3956f07
Add note on circular import for delay in asserting grid is Xgrid
fluidnumerics-joe 8e12611
Change arg ordering to (y,x), consistent with the rest of parcels
fluidnumerics-joe ed9244b
Merge branch 'v4-dev' into 2119-spatial-hashing
fluidnumerics-joe 120efff
Remove commented out code
fluidnumerics-joe eddb351
Update function name to be consistent with (j,i) ordering
fluidnumerics-joe 723cb47
Prefix all internal api functions with "_"
fluidnumerics-joe 4a01f43
Fix docstring for _hash_cell_size
fluidnumerics-joe 7a77039
Conditionally wrap coordinates if mesh is spherical
fluidnumerics-joe dddeefe
Adjust docstring for _hash_index2d to something a bit more accurate
fluidnumerics-joe File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fluidnumerics-joe marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,326 @@ | ||
| # from __future__ import annotations | ||
|
|
||
| # from typing import Literal | ||
|
|
||
| # import numpy as np | ||
| # import uxarray as ux | ||
| # from uxarray.grid.coordinates import _lonlat_rad_to_xyz | ||
|
|
||
| # from parcels.field import FieldOutOfBoundError # Adjust import as necessary | ||
| # from parcels.xgrid import _search_1d_array | ||
|
|
||
| # from .basegrid import BaseGrid | ||
fluidnumerics-joe marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| import numpy as np | ||
|
|
||
|
|
||
| class SpatialHash: | ||
| """Custom data structure that is used for performing grid searches using Spatial Hashing. This class constructs an overlying | ||
| uniformly spaced rectilinear grid, called the "hash grid" on top parcels.xgrid.XGrid. It is particularly useful for grid searching | ||
| on curvilinear grids. Faces in the Xgrid are related to the cells in the hash grid by determining the hash cells the bounding box | ||
| of the unstructured face cells overlap with. | ||
| Parameters | ||
| ---------- | ||
| grid : parcels.xgrid.XGrid | ||
| Source grid used to construct the hash grid and hash table | ||
| global_grid : bool, default=False | ||
| If true, the hash grid is constructed using the domain [-pi,pi] x [-pi,pi] | ||
fluidnumerics-joe marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| reconstruct : bool, default=False | ||
| If true, reconstructs the spatial hash | ||
fluidnumerics-joe marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| Note | ||
| ---- | ||
| Does not currently support queries on periodic elements. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| grid, | ||
| global_grid=False, | ||
fluidnumerics-joe marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| reconstruct=False, | ||
| ): | ||
| # TODO : Enforce grid to be an instance of parcels.xgrid.XGrid and curvilinear. | ||
erikvansebille marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| self._source_grid = grid | ||
| self.reconstruct = reconstruct | ||
|
|
||
| # Hash grid size | ||
| self._dh = self._hash_cell_size() | ||
|
|
||
| if global_grid: | ||
| # Set the hash grid to be a global grid | ||
| self._xmin = -180.0 | ||
| self._ymin = -90.0 | ||
| self._xmax = 180.0 | ||
| self._ymax = 90.0 | ||
| else: | ||
| # Lower left corner of the hash grid | ||
| lon_min = self._source_grid.lon.min() | ||
| lat_min = self._source_grid.lat.min() | ||
| lon_max = self._source_grid.lon.max() | ||
| lat_max = self._source_grid.lat.max() | ||
|
|
||
| self._xmin = lon_min - self._dh | ||
| self._ymin = lat_min - self._dh | ||
| self._xmax = lon_max + self._dh | ||
| self._ymax = lat_max + self._dh | ||
fluidnumerics-joe marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| # Number of x points in the hash grid; used for | ||
| # array flattening | ||
| Lx = self._xmax - self._xmin | ||
| Ly = self._ymax - self._ymin | ||
| self._nx = int(np.ceil(Lx / self._dh)) | ||
| self._ny = int(np.ceil(Ly / self._dh)) | ||
|
|
||
| # Generate the mapping from the hash indices to unstructured grid elements | ||
| self._face_hash_table = None | ||
| self._face_hash_table = self._initialize_face_hash_table() | ||
|
|
||
| def _hash_cell_size(self): | ||
| """Computes the size of the hash cells from the source grid. | ||
| The hash cell size is set to 1/2 of the square root of the curvilinear cell area | ||
fluidnumerics-joe marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| """ | ||
| return np.sqrt(np.median(planar_quad_area(self._source_grid.lon, self._source_grid.lat))) * 0.5 | ||
|
|
||
| def _hash_index2d(self, coords): | ||
| """Computes the 2-d hash index (i,j) for the location (x,y), where x and y are given in spherical | ||
| coordinates (in degrees) | ||
| """ | ||
| # Wrap longitude to [-180, 180] | ||
| lon = (coords[:, 0] + 180.0) % (360.0) - 180.0 | ||
fluidnumerics-joe marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| i = ((lon - self._xmin) / self._dh).astype(np.int32) | ||
| j = ((coords[:, 1] - self._ymin) / self._dh).astype(np.int32) | ||
| return i, j | ||
fluidnumerics-joe marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| def _hash_index(self, coords): | ||
| """Computes the flattened hash index for the location (x,y), where x and y are given in spherical | ||
fluidnumerics-joe marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| coordinates (in degrees). The single dimensioned hash index orders the flat index with all of the | ||
fluidnumerics-joe marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| i-points first and then all the j-points. | ||
| """ | ||
| i, j = self._hash_index2d(coords) | ||
fluidnumerics-joe marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| return i + self._nx * j | ||
|
|
||
| def _grid_ij_for_eid(self, eid): | ||
| """Returns the (i,j) grid coordinates for the given element id (eid)""" | ||
| j = eid // (self._source_grid.xdim) | ||
| i = eid - j * (self._source_grid.xdim) | ||
| return i, j | ||
fluidnumerics-joe marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| def _initialize_face_hash_table(self): | ||
| """Create a mapping that relates unstructured grid faces to hash indices by determining | ||
| which faces overlap with which hash cells | ||
| """ | ||
| if self._face_hash_table is None or self.reconstruct: | ||
| index_to_face = [[] for i in range(self._nx * self._ny)] | ||
| # Get the bounds of each curvilinear faces | ||
| lon_bounds, lat_bounds = curvilinear_grid_facebounds( | ||
| self._source_grid.lon, | ||
| self._source_grid.lat, | ||
| ) | ||
| coords = np.stack( | ||
| ( | ||
| lon_bounds[:, :, 0].flatten(), | ||
| lat_bounds[:, :, 0].flatten(), | ||
| ), | ||
| axis=-1, | ||
| ) | ||
| xi1, yi1 = self._hash_index2d(coords) | ||
| coords = np.stack( | ||
| ( | ||
| lon_bounds[:, :, 1].flatten(), | ||
| lat_bounds[:, :, 1].flatten(), | ||
| ), | ||
| axis=-1, | ||
| ) | ||
| xi2, yi2 = self._hash_index2d(coords) | ||
| nface = (self._source_grid.xdim) * (self._source_grid.ydim) | ||
| for eid in range(nface): | ||
| for j in range(yi1[eid], yi2[eid] + 1): | ||
| if xi1[eid] <= xi2[eid]: | ||
| # Normal case, no wrap | ||
| for i in range(xi1[eid], xi2[eid] + 1): | ||
| index_to_face[(i % self._nx) + self._nx * j].append(eid) | ||
| else: | ||
| # Wrap-around case | ||
| for i in range(xi1[eid], self._nx): | ||
| index_to_face[(i % self._nx) + self._nx * j].append(eid) | ||
| for i in range(0, xi2[eid] + 1): | ||
| index_to_face[(i % self._nx) + self._nx * j].append(eid) | ||
erikvansebille marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| return index_to_face | ||
|
|
||
| def query( | ||
fluidnumerics-joe marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| self, | ||
| coords, | ||
| tol=1e-6, | ||
| ): | ||
| """Queries the hash table. | ||
| Parameters | ||
| ---------- | ||
| coords : array_like | ||
| coordinate pairs in degrees (lon, lat) to query. | ||
| Returns | ||
| ------- | ||
| faces : ndarray of shape (coords.shape[0]), dtype=np.int32 | ||
| Face id's in the self._source_grid where each coords element is found. When a coords element is not found, the | ||
| corresponding array entry in faces is set to -1. | ||
| """ | ||
| num_coords = coords.shape[0] | ||
|
|
||
| # Preallocate results | ||
| # bcoords = np.zeros((num_coords, 4), dtype=np.double) | ||
fluidnumerics-joe marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| faces = np.full((num_coords, 2), -1, dtype=np.int32) | ||
|
|
||
| # Get the list of candidate faces for each coordinate | ||
| candidate_faces = [self._face_hash_table[pid] for pid in self._hash_index(coords)] | ||
|
|
||
| # Get corner vertices of each face | ||
| xbound = np.stack( | ||
| ( | ||
| self._source_grid.lon[:-1, :-1], | ||
| self._source_grid.lon[:-1, 1:], | ||
| self._source_grid.lon[1:, 1:], | ||
| self._source_grid.lon[1:, :-1], | ||
| ), | ||
| axis=-1, | ||
| ) | ||
| ybound = np.stack( | ||
| ( | ||
| self._source_grid.lat[:-1, :-1], | ||
| self._source_grid.lat[:-1, 1:], | ||
| self._source_grid.lat[1:, 1:], | ||
| self._source_grid.lat[1:, :-1], | ||
| ), | ||
| axis=-1, | ||
| ) | ||
|
|
||
| for i, (coord, candidates) in enumerate(zip(coords, candidate_faces, strict=False)): | ||
| for face_id in candidates: | ||
| xi, yi = self._grid_ij_for_eid(face_id) | ||
| nodes = np.stack( | ||
| ( | ||
| xbound[yi, xi, :], | ||
| ybound[yi, xi, :], | ||
| ), | ||
| axis=-1, | ||
| ) | ||
|
|
||
| bcoord = np.asarray(_barycentric_coordinates(nodes, coord)) | ||
| err = abs(np.dot(bcoord, nodes[:, 0]) - coord[0]) + abs(np.dot(bcoord, nodes[:, 1]) - coord[1]) | ||
| if (bcoord >= 0).all() and err < tol: | ||
| faces[i, :] = [yi, xi] | ||
| # bcoords[i, :] = bcoord | ||
fluidnumerics-joe marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| break | ||
|
|
||
| return faces # , bcoords | ||
erikvansebille marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
|
|
||
| def _triangle_area(A, B, C): | ||
| """Compute the area of a triangle given by three points.""" | ||
| d1 = B - A | ||
| d2 = C - A | ||
| d3 = np.cross(d1, d2) | ||
| return 0.5 * np.linalg.norm(d3) | ||
|
|
||
|
|
||
| def _barycentric_coordinates(nodes, point, min_area=1e-8): | ||
| """ | ||
| Compute the barycentric coordinates of a point P inside a convex polygon using area-based weights. | ||
| So that this method generalizes to n-sided polygons, we use the Waschpress points as the generalized | ||
| barycentric coordinates, which is only valid for convex polygons. | ||
| Parameters | ||
| ---------- | ||
| nodes : numpy.ndarray | ||
| Spherical coordinates (lon,lat) of each corner node of a face | ||
| point : numpy.ndarray | ||
| Spherical coordinates (lon,lat) of the point | ||
| Returns | ||
| ------- | ||
| numpy.ndarray | ||
| Barycentric coordinates corresponding to each vertex. | ||
| """ | ||
| n = len(nodes) | ||
| sum_wi = 0 | ||
| w = [] | ||
|
|
||
| for i in range(0, n): | ||
| vim1 = nodes[i - 1] | ||
| vi = nodes[i] | ||
| vi1 = nodes[(i + 1) % n] | ||
| a0 = _triangle_area(vim1, vi, vi1) | ||
| a1 = max(_triangle_area(point, vim1, vi), min_area) | ||
| a2 = max(_triangle_area(point, vi, vi1), min_area) | ||
| sum_wi += a0 / (a1 * a2) | ||
| w.append(a0 / (a1 * a2)) | ||
| barycentric_coords = [w_i / sum_wi for w_i in w] | ||
|
|
||
| return barycentric_coords | ||
|
|
||
|
|
||
| def planar_quad_area(lon, lat): | ||
| """Computes the area of each quadrilateral face in a curvilinear grid. | ||
| The lon and lat arrays are assumed to be 2D arrays of points with dimensions (n_y, n_x). | ||
| The area is computed using the Shoelace formula. | ||
| Parameters | ||
| ---------- | ||
| lon : np.ndarray | ||
| 2D array of shape (n_y, n_x) containing the longitude of each corner node of the curvilinear grid. | ||
| lat : np.ndarray | ||
| 2D array of shape (n_y, n_x) containing the latitude of each corner node of the curvilinear grid. | ||
| Returns | ||
| ------- | ||
| area : np.ndarray | ||
| 2D array of shape (n_y-1, n_x-1) containing the area of each quadrilateral face in the curvilinear grid. | ||
| """ | ||
| x0 = lon[:-1, :-1] | ||
| x1 = lon[:-1, 1:] | ||
| x2 = lon[1:, 1:] | ||
| x3 = lon[1:, :-1] | ||
|
|
||
| y0 = lat[:-1, :-1] | ||
| y1 = lat[:-1, 1:] | ||
| y2 = lat[1:, 1:] | ||
| y3 = lat[1:, :-1] | ||
|
|
||
| # Shoelace formula: 0.5 * |sum(x_i*y_{i+1} - x_{i+1}*y_i)| | ||
| area = 0.5 * np.abs(x0 * y1 + x1 * y2 + x2 * y3 + x3 * y0 - y0 * x1 - y1 * x2 - y2 * x3 - y3 * x0) | ||
| return area | ||
|
|
||
|
|
||
| def curvilinear_grid_facebounds(lon, lat): | ||
fluidnumerics-joe marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| """Computes the bounds of each curvilinear face in the grid. | ||
| The lon and lat arrays are assumed to be 2D arrays of points with dimensions (n_y, n_x). | ||
| The bounds are for faces whose corner node vertices are defined by lon,lat. | ||
| Face(yi,xi) is surrounding by points (yi,xi), (yi,xi+1), (yi+1,xi+1), (yi+1,xi). | ||
| Parameters | ||
| ---------- | ||
| lon : np.ndarray | ||
| 2D array of shape (n_y, n_x) containing the longitude of each corner node of the curvilinear grid. | ||
| lat : np.ndarray | ||
| 2D array of shape (n_y, n_x) containing the latitude of each corner node of the curvilinear grid. | ||
| Returns | ||
| ------- | ||
| xbounds : np.ndarray | ||
| Array of shape (n_y-1, n_x-1, 2) containing the bounds of each face in the x-direction. | ||
| ybounds : np.ndarray | ||
| Array of shape (n_y-1, n_x-1, 2) containing the bounds of each face in the y-direction. | ||
| """ | ||
| xf = np.stack((lon[:-1, :-1], lon[:-1, 1:], lon[1:, 1:], lon[1:, :-1]), axis=-1) | ||
| xf_low = xf.min(axis=-1) | ||
| xf_high = xf.max(axis=-1) | ||
| xbounds = np.stack([xf_low, xf_high], axis=-1) | ||
|
|
||
| yf = np.stack((lat[:-1, :-1], lat[:-1, 1:], lat[1:, 1:], lat[1:, :-1]), axis=-1) | ||
| yf_low = yf.min(axis=-1) | ||
| yf_high = yf.max(axis=-1) | ||
| ybounds = np.stack([yf_low, yf_high], axis=-1) | ||
|
|
||
| return xbounds, ybounds | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.