Converting between curvilinear and lon/lat

Hey everyone :slight_smile:

I have a rectilinear xarray file (180 x 360) one of the attributes tells me the outflow point (to the ocean) of each watershed.

I have a curvilinear grid (coarser res x = 149 by y =182) with another variable I want to use.

I am looking for a way to “map” my output points from my rectilinear grid onto my curvilinear grid to find the values of the cells.

I have tried using interp with method=‘nearest’ (linear misses tons of values only 20 basins out of 2600) but this still misses roughly half of my exit points.

I wondered if there is an “easy” way to see which cell(s) a given long / lat falls in in a curvilinear grid? The annoying things is using geoviews I can superpose these datasets!!

Would Spatial pandas help out here?

I have come across this thread: Does interp() work on curvilinear grids (2D coordinates) ? · Issue #2281 · pydata/xarray · GitHub but this talks about interpolating.

xESMF has the ability to interpolate to curvilinear grids. Would that work?

1 Like

Thanks for the link @rsignell, I’ve got the example working quickly with ignore_degenerate=True else I was getting some errors :confused:

For reference in the mean time I got this pseudo code working:

  1. Extract the locations from curvilinear coordinates
  2. Use xarray.sel with method=‘nearest’ to find out which cell each point falls into
  3. Extract the Lons and Lats
  4. Use numpy.unique with return_index=True, return_inverse=True, return_counts=True
  5. Calculate the averages: `average = numpy.bincount(idx_reverse, weights=data) / counts
  6. Create an empty array and use search sorted to find locations and fill in with averaged data values
  7. Assign to xarray

Seems a hell of a work around :confused: This also means that my values are continuous now as they are with the xESMF regridding but it will work in my case.

Thanks again

1 Like

I agree xesmf is the ideal tool for this, particularly if you care about things like conservative interpolation schemes.

If you’re interested in indexing curvilinear data, you might also look into @benbovy’s xoak package: