Find the nearest neighbors in a grid of latitude and longitude coordinates.
This function takes in a target set of latitude and longitude coordinates, an input set of latitude and longitude coordinates, and a set of values associated with the input coordinates. It uses a BallTree to efficiently find the nearest neighbor in the input set for each point in the target set. The function returns an array of values corresponding to the nearest neighbors.
| Parameters: |
-
latlon_target
(tuple of arrays)
–
The target set of latitude and longitude coordinates.
-
latlon_input
(tuple of arrays)
–
The input set of latitude and longitude coordinates.
-
values
(array - like)
–
The set of values associated with the input coordinates.
-
leaf_size
(int, default:
30
)
–
The number of points to group together in the BallTree. Defaults to 30.
|
| Returns: |
-
values_out( array - like
) –
An array of values corresponding to the nearest neighbors.
|
Source code in wmsan/wmsan_to_noisi.py
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127 | def geo_nearest_neighbour(latlon_target, latlon_input, values, leaf_size=30):
"""Find the nearest neighbors in a grid of latitude and longitude coordinates.
This function takes in a target set of latitude and longitude coordinates, an input set of latitude and longitude coordinates, and a set of values associated with the input coordinates. It uses a BallTree to efficiently find the nearest neighbor in the input set for each point in the target set. The function returns an array of values corresponding to the nearest neighbors.
Args:
latlon_target (tuple of arrays): The target set of latitude and longitude coordinates.
latlon_input (tuple of arrays): The input set of latitude and longitude coordinates.
values (array-like): The set of values associated with the input coordinates.
leaf_size (int, optional): The number of points to group together in the BallTree. Defaults to 30.
Returns:
values_out (array-like): An array of values corresponding to the nearest neighbors.
"""
lat_in = latlon_input[0]
lon_in = latlon_input[1]
# transform into convenient array
# Create a meshgrid for x and y coordinates
latlat, lonlon = np.meshgrid(lat_in, lon_in, indexing='ij')
# Flatten the arrays
lat_flat = latlat.flatten()
lon_flat = lonlon.flatten()
data_flat = values.flatten()
lat = np.radians(lat_flat)
lon = np.radians(lon_flat)
grid_in = np.array([lat, lon]).T
# construct a ball tree with haversine distance as the metric
tree = BallTree(grid_in, leaf_size=leaf_size, metric='haversine')
values_out = np.zeros(latlon_target[0].shape)
for ix, query_point in enumerate(np.array(latlon_target).T):
pt = np.radians(query_point)
distance, index = tree.query([pt], k=1)
value_nearest = data_flat[index[0][0]]
values_out[ix] = value_nearest
return(values_out)
|