簡體   English   中英

使用python查找網格上的緯度點的索引

[英]find indices of lat lon point on a grid using python

我是python的新手,我不知道如何找到從給定緯​​度/經度點(不是從網格中給出,而是由我選擇)到找到緯度/經度的最接近索引的最小距離網格上的lon點。

基本上,我正在讀取包含2D坐標的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)

我想在上面的網格中找到與以下值最近的緯度的索引:

sel_lat=71.60556
sel_lon=-161.458611

我嘗試制作緯度/經度對以便使用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')

任何幫助或提示,將不勝感激

我想我找到了答案,但這是一種變通方法,可以避免計算所選緯度/經度和網格上緯度/經度之間的距離。 這似乎並不完全准確,因為我從不計算距離,而只是計算緯度/經度值本身之間最接近的差。

我使用了問題的答案來查找2D數組中最接近的(長,緯)值的(i,j)位置

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

然后,使用這些返回的索引i,j,我可以在網格上找到與所選的經度和經度值最接近的坐標:

>>> lats[i,j]
71.490295
>>> lons[i,j]
-161.65045

檢出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

還有一種簡便的方法可以直接獲取最近的網格點處的數據值:

data_swath = pyresample.kd_tree.resample_nearest(
    source_geo_def=grid, target_geo_def=swath, data=data_grid,
    radius_of_influence=50000)
print "Data at nearest grid points:", data_swath

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM