NetCDF and Python: finding the closest lon / lat index with actual lon / lat values

I would like to find the indices of the lon / lat coordinate of the closest location for the lon / lat tuple. It is already available in the Java API as GridCoordSystem.findXYindexFromLatLon (), but I did not find anything comparable in the Python API. What I hope to find in the API, or write myself and contribute to the API (if useful), looks something like this:

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

Maybe it's not as difficult as I suppose, and I can leave just by using the closest neighbor?

Thanks in advance for any comments or suggestions.

+4
source share
2 answers

, Scipy cdist. lat/lon (lat_value, lon_value) . lat_index lon_index ( Numpy argmin).

+4

, lat/lon :

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]
+4

Source: https://habr.com/ru/post/1616431/


All Articles