-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Pointwise indexing -- something like sel_points #214
Comments
This operation is actually sort of like reindexing. So perhaps this should be spelled |
Unless I am missing something about xray, that selection operation could only work if |
@WeatherGod You are totally correct. The last dataset on which I have needed to do this was an unprojected grid with a constant increment of 0.5 degrees between points, so finding nearest neighbors was easy. If you have a lot of points to select at, finding nearest neighbor points could be done efficiently with a tree, e.g., |
Just managed to implement this using your suggestion for my data:
Not entirely certain why I needed to reverse y and x in that last part, but, oh well... |
@WeatherGod Very nice! I'm not entirely sure why you have to reverse y and x at the end, either -- what is the order of the dimensions on |
Starting using the above snippet for more datasets, some with interdependent coordinates and some without (so the coordinates would be 1-d). I think I have generalized it significantly...
I can still imagine some situations where this won't work, such as a requested set of dimensions that are a mix of dependent and independent variables. Currently, if the dimensions are independent, then the number of dimensions of each one is assumed to be 1 and np.newaxis is used for the others. Meanwhile, if the dimensions are dependent, then the number of dimensions for each one is assumed to be the same as the number of dependent variables and is merely flattened (the broadcast is essentially no-op). I should also note that this is technically not restricted to spatial coordinates even though the code says so. Just anything that can be represented in euclidean space. |
Oh, and it does take advantage of a bunch of python2.7 features such as dictionary comprehensions and generator statements, so... |
And, I think I just realized how I could generalize it even more. Right now, |
And, actually, the example I gave above has a bug in the dependent dimension case. This one should be much better (not fully tested yet, though):
|
The only part that wouldn't work for a Dataset is Also, you probably want to use |
The main logic there -- it looks like this is a routine for broadcasting data arrays? I have something similar, but not exactly the same, in |
oooh, didn't realize that |
to/from_dateframe just ate up all my memory. I think I am going to stick with my broadcasting approach... |
Hmmm, limitation that I just encountered. When there are dependent coordinates, the variables representing those coordinates are not the index arrays (and thus, are not "dimensions" either), so my solution is completely broken for dependent coordinates. |
What do you mean by "dependent coordinates"? |
Consider the following Dataset:
The latitude and longitude variables are both dependent upon xgrid_0 and ygrid_0. Meanwhile...
the latitude and longitude variables are independent of each other (they are 1-D). The variable in the first one can not be accessed directly by lat/lon values, while the MaxGust variable in the second one can. This poses some difficulties. |
Ok, I think I got it (for reals this time...)
Needs a lot more tests and comments and such, but I think this works. Best part is that it seems to do a very decent job of keeping memory usage low, and only operates upon the coordinates that I specify. Everything else is left alone. So, I have used this on 4-D data, picking out grid points at specified lat/lon positions, and get back a 3D result (time, level, station). And I have used this on just 2D data, getting back just a 1D result (dimension='station'). |
+1 for this proposal. I made a slight modification to @WeatherGod's code so that I could use string indices for the "station" coordinate, though I'm sure there is a better way to implement this. Also note the addition of a few def grid_to_points2(grid, points, coord_names):
if not coord_names:
raise ValueError("No coordinate names provided")
spat_dims = {d for n in coord_names for d in grid[n].dims}
not_spatial = set(grid.dims) - spat_dims
spatial_selection = {n:0 for n in not_spatial}
spat_only = grid.isel(**spatial_selection)
coords = bcast(spat_only, coord_names)
kd = KDTree(list(zip(*[c.ravel() for c in coords])))
_, indx = kd.query(list(zip(*[points[n].values for n in coord_names])))
indx = np.unravel_index(indx, coords[0].shape)
station_da = xray.DataArray(name='station', dims='station', data=stations.index.values)
return xray.concat(
(grid.isel(**{n:j for n, j in zip(spat_only.dims, i)})
for i in zip(*indx)),
dim=station_da)
In [97]:
stations = pd.DataFrame({'XLAT':[32.13, 32.43], 'XLONG':[-110.95, -112.02]}, index=['KTUS', 'KPHX'])
stations
Out[97]:
XLAT XLONG
KTUS 32.13 -110.95
KPHX 32.43 -112.02
In [98]:
station_ds = grid_to_points2(ds, stations, ('XLAT', 'XLONG'))
station_ds
Out[98]:
<xray.Dataset>
Dimensions: (Times: 1681, station: 2)
Coordinates:
* Times (Times) datetime64[ns] 2015-07-02T06:00:00 ...
XLAT (station) float32 32.1239 32.4337
* station (station) object 'KTUS' 'KPHX'
west_east (station) int64 220 164
XLONG (station) float32 -110.947 -112.012
south_north (station) int64 116 134
Data variables:
SWDNBRH (station, Times) float32 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ...
V10 (station, Times) float32 -2.09897 -1.94047 -1.55494 ...
V80 (station, Times) float32 0.0 -1.95921 -1.87583 -1.86289 ...
SWDNB (station, Times) float32 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ...
U10 (station, Times) float32 2.22951 1.89406 1.39955 1.04277 ...
SWDDNI (station, Times) float32 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ...
SWDNBC (station, Times) float32 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ...
T2 (station, Times) float32 301.419 303.905 304.155 304.296 ...
SWDDNIRH (station, Times) float32 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ...
U80 (station, Times) float32 0.0 1.93936 1.7901 1.63011 1.69481 ...
In [100]:
station_ds.sel(station='KTUS')[['U10','V10']]
Out[100]:
<xray.Dataset>
Dimensions: (Times: 1681)
Coordinates:
west_east int64 220
south_north int64 116
XLONG float32 -110.947
* Times (Times) datetime64[ns] 2015-07-02T06:00:00 ...
station object 'KTUS'
XLAT float32 32.1239
Data variables:
U10 (Times) float32 2.22951 1.89406 1.39955 1.04277 1.16338 ...
V10 (Times) float32 -2.09897 -1.94047 -1.55494 -1.34216 ... |
Fixed by #507 |
* update requirements and envs * whatsnew * added classifier for 3.11
@hdail suggested that it would be useful to be able to index points in addition to indexing dimensions separately. Right now, you can do this via something like:
xray.concat([ds.sel(x=x, y=y) for x, y in pts], dim='station')
This would be handy for sampling particular points out of multiple dimensions, e.g., to compare gridded and station data.
It's also probably worth implementing in xray because it can be done quickly using numpy's fancy indexing (I think) which would be more efficient than a loop, though I suspect the implementation is probably somewhat complex.
The text was updated successfully, but these errors were encountered: