NetCDF和Python:在给定实际lon / lat值的情况下查找最接近的lon / lat索引

时间:2015-11-18 20:07:40

标签: python netcdf

我希望能够找到离lon / lat元组最近位置的lon / lat坐标索引。这已经在Java API中作为GridCoordSystem.findXYindexFromLatLon()提供,但我在Python API中找不到任何可比的东西。我希望在API中找到的,或者自己编写并为API做出贡献(如果有用的话)是这样的:

def get_indices(netcdf_dataset, lon_value, lat_value):
    '''
    :param netcdf_dataset an open NetCDF data set object
    :param lon_value a longitude value, in degrees (-180...180)
    :param lat_value a latitude value, in degrees (-90...90)
    :return indices into the lon and lat coordinate variables corresponding to the closest point to the lon/lat value arguments
    '''

    # some (trigonometry?) code here...

    return lon_index, lat_index

也许这并不像我想象的那样复杂,而且我可以逃脱使用最近的邻居?

提前感谢任何意见或建议。

2 个答案:

答案 0 :(得分:7)

这是我用于十进制度的常规纬度/经度网格:

def geo_idx(dd, dd_array):
   """
     search for nearest decimal degree in an array of decimal degrees and return the index.
     np.argmin returns the indices of minium value along an axis.
     so subtract dd from all values in dd_array, take absolute value and find index of minium.
    """
   geo_idx = (np.abs(dd_array - dd)).argmin()
   return geo_idx

叫做:

  in_lat = 44.67
  in_lon = -79.25
  nci = netCDF4.Dataset(infile)
  lats = nci.variables['lat'][:]
  lons = nci.variables['lon'][:]

  lat_idx = geo_idx(in_lat, lats)
  lon_idx = geo_idx(in_lon, lons)

测试:

  print lats[lat_idx]
  print lons[lon_idx]

答案 1 :(得分:5)

您可以使用Scipy's cdist function编写一个相当简单的算法。您只需计算从目标纬度/经度坐标(lat_valuelon_value)到数据集中坐标集的距离。找到最小距离并返回其关联的lat_indexlon_index(可能会对Numpy's argmin有所帮助)。