Allow interpolating along singleton dimensions
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 4.2k
- Forks
- 1.4k
- Avg merge
- 2d 15h
- Merged PRs (30d)
- 14
Description
Is your feature request related to a problem?
Currently, interpolating along a singleton dimension will always yield nan values.
E.g.
import xarray as xr
da = xr.DataArray([[0, 1]], coords={'a': [1.], 'b': [2., 3.]}).interp(a=1., b=2.5)
raises a warning
***\site-packages\scipy\interpolate\_interpolate.py:479: RuntimeWarning: invalid value encountered in divide
slope = (y_hi - y_lo) / (x_hi - x_lo)[:, None]
and returns array with correct shape, but all values nan:
<xarray.DataArray ()> Size: 8B
array(nan)
Coordinates:
a float64 8B 1.0
b float64 8B 2.5
Having only a single coordinate, interpolation is not well defined, of course.
But giving the exact coordinate value in interp(), should simply do a sel() along this dimension before interpolation.
That seems unambiguous and would be what users may reasonably expect.
This is particularly used, when interpolating with coordinates determined by computed dicts, like:
kwargs = dict(a=1., b=2.5) # from external input
da.interp(**kwargs)
Describe the solution you'd like
import xarray as xr
da = xr.DataArray([[0, 1]], coords={'a': [1.], 'b': [2., 3.]}).interp(a=1., b=2.5)
should yield
<xarray.DataArray ()> Size: 8B
array(0.5)
Coordinates:
a float64 8B 1.0
b float64 8B 2.5
Describe alternatives you've considered
Of course, singleton dimensions can be detected and special-cases manually:
import xarray as xr
kwargs = dict(a=1., b=2.5) # from external input
da = xr.DataArray([[0, 1]], coords={'a': [1.], 'b': [2., 3.]})
sel_kwargs = {k: v for k, v in kwargs.items() if da.sizes[k] == 1}
interp_kwargs = {k: v for k, v in kwargs.items() if k not in sel_kwargs.keys()}
da.sel(**sel_kwargs).interp(**interp_kwargs)
This yields the desired behaviour, but feels very clumsy.
Additional context
No response
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start at the DataArray.interp entry point and reproduce the singleton-dimension example from the issue. Trace how interpolation handles the singleton coordinate, then verify that an exact coordinate value behaves like selection while interpolation continues along the other dimension and returns 0.5.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- data
- Issue type
- Feature
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 52/100