使用python在网格上查找lat lon点的索引

2024-04-29 12:51:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,我不知道如何找到从给定的lat/lon点(不是从网格中给定的,而是由我选择的)到一个在网格上找到一个lat/lon点最近的索引的最小距离。在

基本上,我正在读取包含二维坐标的ncfile:

coords = 'coords.nc'
fh = dataset(coords,mode='r')
lons = fh.variables['latitudes'][:,:]
lats = fh.variables['longitudes'][:,:]
fh.close()

>>> lons.shape
(94, 83)
>>> lats.shape
(94, 83)

我想在上面的网格中找到最接近以下值的纬度的指数:

^{pr2}$

我试着做横向/纵向配对,以便使用scipy.spatial.distance公司函数,但我仍然有问题,因为我没有将输入数组设置为它想要的格式,但我不知道如何做到:

latLon_pairsGrid = np.vstack(([lats.T],[lons.T])).T

>>> latLon_pairsGrid.shape
(94, 83, 2)

distance.cdist([sel_lat,sel_lon],latLon_pairsGrid,'euclidean')

任何帮助或提示将不胜感激


Tags: 网格距离coordsvariableslatlondistancelonlat
2条回答

签出pyresample包。它使用快速kdtree方法提供空间最近邻搜索:

import pyresample
import numpy as np

# Define lat-lon grid
lon = np.linspace(30, 40, 100)
lat = np.linspace(10, 20, 100)
lon_grid, lat_grid = np.meshgrid(lon, lat)
grid = pyresample.geometry.GridDefinition(lats=lat_grid, lons=lon_grid)

# Generate some random data on the grid
data_grid = np.random.rand(lon_grid.shape[0], lon_grid.shape[1])

# Define some sample points
my_lons = np.array([34.5, 36.5, 38.5])
my_lats = np.array([12.0, 14.0, 16.0])
swath = pyresample.geometry.SwathDefinition(lons=my_lons, lats=my_lats)

# Determine nearest (w.r.t. great circle distance) neighbour in the grid.
_, _, index_array, distance_array = pyresample.kd_tree.get_neighbour_info(
    source_geo_def=grid, target_geo_def=swath, radius_of_influence=50000,
    neighbours=1)

# get_neighbour_info() returns indices in the flattened lat/lon grid. Compute
# the 2D grid indices:
index_array_2d = np.unravel_index(index_array, grid.shape)

print "Indices of nearest neighbours:", index_array_2d
print "Longitude of nearest neighbours:", lon_grid[index_array_2d]
print "Latitude of nearest neighbours:", lat_grid[index_array_2d]
print "Great Circle Distance:", distance_array

还有一种在最近的网格点直接获取数据值的速记方法:

^{pr2}$

我想我找到了一个答案,但这是一个解决办法,可以避免计算所选lat/lon和网格上lat/lon之间的距离。这似乎并不完全准确,因为我从来没有计算过距离,只是lat/lon值之间最接近的差值。在

我用了这个问题的答案find (i,j) location of closest (long,lat) values in a 2D array

a = abs(lats-sel_lat)+abs(lons-sel_lon)
i,j = np.unravel_index(a.argmin(),a.shape)

使用这些返回的索引i,j,我可以在网格上找到与我选择的lat,lon值最接近的坐标:

^{pr2}$

相关问题 更多 >