0
votes

I am trying to find the equivalent (if there exists one) of an NCL function that returns the indices of two-dimensional latitude/longitude arrays closest to a user-specified latitude/longitude coordinate pair.

This is the link to the NCL function that I am hoping there is an equivalent to in python. I'm suspecting at this point that there is not, so any tips on how to get indices from lat/lon coordinates is appreciated

https://www.ncl.ucar.edu/Document/Functions/Contributed/getind_latlon2d.shtml

Right now , I have my coordinate values saved into an .nc file and are read by:

coords='coords.nc'
fh = Dataset(coords, mode='r')
lons = fh.variables['g5_lon_1'][:,:]
lats = fh.variables['g5_lat_0'][:,:]
rot = fh.variables['g5_rot_2'][:,:]
fh.close()
2
I am wondering something very similar.CRogers

2 Answers

0
votes

I found scipy spatial.KDTree can perform similar task. Here is my code of finding the model grid that is closest to the observation location

from scipy import spatial
from netCDF4 import Dataset

# read in the one dimensional lat lon info from a dataset
fname = '0k_T_ann_clim.nc'  
fid   = Dataset(fname, 'r')

lat  = fid.variables['lat'][:] 
lon  = fid.variables['lon'][:]
# make them a meshgrid for later use KDTree
lon2d, lat2d = np.meshgrid(lon, lat)
# zip them together
model_grid = list( zip(np.ravel(lon2d), np.ravel(lat2d)) ) 

#target point location : 30.5N, 56.1E
target_pts = [30.5 56.1]   
distance, index = spatial.KDTree(model_grid).query(target_pts)
# the nearest model location (in lat and lon)
model_loc_coord = [coord for i, coord in enumerate(model_grid) if i==index]
0
votes

I'm not sure how lon/lat arrays are stored when read in python, so to use the following solution you may need to convert lon/lat to numpy arrays. You can just put the abs(array-target).argmin() in a function.

import numpy as np

# make a dummy longitude array, 0.5 degree resolution.
lon=np.linspace(0.5,360,720)

# find index of nearest longitude to 25.4 
ind=abs(lon-25.4).argmin()

# check it works!  this gives 25.5 
lon[ind]