Repository navigation
Description
When using open_mfdataset on files which 'should' share a grid, there is often a small mismatch which results in the grid not aligning properly. This happens frequently when trying to read data from large climate models from multiple files of the same variable, same lon,lat grid and different time intervals. This silent behavior means that I always have to check the sizes of the lon,lat grids whenever I rely on mfdataset to concatenate the data in time.
Here is an example in which I create two 1d DataArrays which have slightly different coordinates:
import xarray as xr
import numpy as np
from glob import glob
tol=1e-14
x1 = np.arange(1,6)+ tol*np.random.rand(5)
da1 = xr.DataArray([9, 0, 2, 1, 0], dims=['x'], coords={'x': x1})
x2 = np.arange(1,6) + tol*np.random.rand(5)
da2 = da1.copy()
da2['x'] = x2
print(da1.x,'\n', da2.x)<xarray.DataArray 'x' (x: 5)>
array([1., 2., 3., 4., 5.])
Coordinates:
* x (x) float64 1.0 2.0 3.0 4.0 5.0
<xarray.DataArray 'x' (x: 5)>
array([1., 2., 3., 4., 5.])
Coordinates:
* x (x) float64 1.0 2.0 3.0 4.0 5.0
First I save both DataArrays as netcdf files and then use open_mfdataset to load them:
da1.to_netcdf('da1.nc',encoding={'x':{'dtype':'float64'}})
da2.to_netcdf('da2.nc',encoding={'x':{'dtype':'float64'}})
db = xr.open_mfdataset(glob('da?.nc'))
db
<xarray.Dataset>
Dimensions: (x: 10)
Coordinates:
* x (x) float64 1.0 2.0 3.0 4.0 5.0 1.0 2.0 ...
Data variables:
__xarray_dataarray_variable__ (x) int64 dask.array<shape=(10,), chunksize=(5,)>
So the x grid is now twice the size. This behavior is the same if I just use align with join='outer':
xr.align(da1,da2,join='outer')
(<xarray.DataArray (x: 10)>
array([nan, 9., nan, 0., 2., nan, nan, 1., 0., nan])
Coordinates:
* x (x) float64 1.0 1.0 2.0 2.0 3.0 3.0 4.0 4.0 5.0 5.0,
<xarray.DataArray (x: 10)>
array([ 9., nan, 0., nan, nan, 2., 1., nan, nan, 0.])
Coordinates:
* x (x) float64 1.0 1.0 2.0 2.0 3.0 3.0 4.0 4.0 5.0 5.0)
Request/ suggestion
What is needed is a user specified tolerance level to give to open_mfdataset and passed to
align which will accept these grids as the same
Possibly related to #2215
Details
xr.__version__ '0.10.4'thanks, Naomi
Activity
shoyer commentedon Jun 6, 2018
I agree that this would be useful.
One option that works currently would be to determine the proper grid (e.g., from one file) and then use the
preprocessargument ofopen_mfdatasettoreindex()each dataset to the desired grid.To do this systematically in xarray, we would want to update
xarray.alignto be capable of approximate alignment. This would in turn require approximate versions ofpandas.Index.union(forjoin='outer') andpandas.Index.intersection(forjoin='inner').Ideally, we would do this work upstream in pandas, and utilize it downstream in xarray. Either way, someone will need to figure out and implement the appropriate algorithm to take an approximate union of two sets of points. This could be somewhat tricky when you start to consider sets where some but not all points are within
toleranceof each other (e.g.,{0, 1, 2, 3, 4, 5}withtolerance=1.5).rabernat commentedon Jun 6, 2018
An alternative approach to fixing this issue would be the long-discussed idea of a "fast path" for open_mfdataset (#1823). In this case, @naomi-henderson knows a-priori that the coordinates for these files should be the same, numerical noise notwithstanding. There should be a way to just skip the alignment check completely and override the coordinates with the values from the first file.
For example
This would just check that the shapes of the different coordinates match and then replace
da2's coordinates with those fromda1.shoyer commentedon Jun 6, 2018
I like this idea! This would be certainly be much easier to implement than general purpose approximate alignment.
WeatherGod commentedon Jun 21, 2018
I was just pointed to this issue yesterday, and I have an immediate need for this feature in xarray for a work project. I'll take responsibility to implement this feature tomorrow.
WeatherGod commentedon Jun 21, 2018
To be clear, my use-case would not be solved by
join='override'(isn't that justjoin='left'?). I have moving nests of coordinates that can have some floating-point noise in them, but are otherwise identical.shoyer commentedon Jun 21, 2018
`join='left'' will reindex all arguments to match the coordinates of the first object. In practice, that means that if coordinates differ by floating point noise, the second object would end up converted to all NaNs.
join='override'would just relabel coordinates, assuming that the shapes match. The data wouldn't change at all.I guess another way to do this would be to include
methodandtolerancearguments fromreindexon align, and only allow them whenjoin='left'orjoin='right'. But this would be a little trickier to pass on through other functions likeopen_mfdataset().WeatherGod commentedon Jun 22, 2018
Well, I need this to work for join='outer', so, it is gonna happen one way or another...
One concept I was toying with today was a distinction between aligning coords (which is what it does now) and aligning bounding boxes.
WeatherGod commentedon Jun 22, 2018
@shoyer, I am thinking your original intuition was right about needing to introduce improve the Index classes to perhaps work with an optional epsilon argument to its constructor. How receptive do you think pandas would be to that? And even if they would accept such a feature, we probably would need to implement it a bit ourselves in situations where older pandas versions are used.
shoyer commentedon Jun 22, 2018
I think a tolerance argument for set-methods like
Index.unionwould be an easier sell than an epsilon argument for the Index construction. You'd still need to figure out the right algorithmic approach, though.shoyer commentedon Jun 22, 2018
See pandas-dev/pandas#9817 and pandas-dev/pandas#9530 for the relevant pandas issues.
WeatherGod commentedon Jun 22, 2018
Ok, I see how you implemented it for pandas's reindex. You essentially inserted an inexact filter within
.get_indexer(). And theintersection()andunion()uses these methods, so, in theory, one could pipe a tolerance argument through them (as well as for the other set operations). The work needs to be expanded a bit, though, asget_indexer_non_unique()needs the tolerance parameter, too, I think.For xarray, though, I think we can work around backwards compatibility by having Dataset hold specialized subclasses of Index for floating-point data types that would have the needed changes to the Index class. We can have this specialized class have some default tolerance (say 100*finfo(dtype).resolution?), and it would have its methods use the stored tolerance by default, so it should be completely transparent to the end-user (hopefully). This way,
xr.open_mfdataset()would "just work".shoyer commentedon Jun 22, 2018
WeatherGod commentedon Jun 22, 2018
Actually, I disagree. Pandas's set operations methods are mostly index-based. For union and intersection, they have an optimization that dives down into some c-code when the Indexes are monotonic, but everywhere else, it all works off of results from
get_indexer(). I have made a quick toy demo code that seems to work. Note, I didn't know how to properly make a constructor for a subclassed Index, so I added thetoleranceattribute after construction just for the purposes of this demo.Run this and get the following results:
This is mostly lifted from the
Indexbase class methods, just with me taking out the monotonic optimization path, and supplying the tolerance argument to the respective calls toget_indexer. The choice of tolerance for a given operation is that unless provided as a keyword argument, then use the larger tolerance of the two objects being compared (with a failback if the other isn't an ImpreciseIndex).shoyer commentedon Jun 22, 2018
@WeatherGod One problem with your definition of tolerance is that it isn't commutative, even if both indexes have the same tolerance:
If you try a little harder, you could even have cases where the result has a different size, e.g.,
Maybe these aren't really problems in practice, but it's at least a little strange/surprising.
WeatherGod commentedon Jun 22, 2018
shoyer commentedon Jun 23, 2018
WeatherGod commentedon Jun 25, 2018
Do we want to dive straight to that? Or, would it make more sense to first submit some PRs piping the support for a tolerance kwarg through more of the API? Or perhaps we should propose that a "tolerance" attribute should be an optional attribute that methods like
get_indexer()and such could always check for? Not being a pandas dev, I am not sure how piecemeal we should approach this.In addition, we are likely going to have to implement a decent chunk of code ourselves for compatibility's sake, I think.
shoyer commentedon Jun 25, 2018
WeatherGod commentedon Jul 24, 2018
I have created a PR for my work-in-progress: pandas-dev/pandas#22043
maschull commentedon Oct 10, 2019
any work around to this issue?
dcherian commentedon Oct 10, 2019
Yes on xarray>=0.13.0,
xr.open_mfdataset(..., join="override")assuming that all files are on the same coordinate system.maschull commentedon Oct 10, 2019
ah wonderful! I will update to 1.13.0
dcherian commentedon Nov 24, 2020
reopening since we have a PR to fix this properly.