-
Notifications
You must be signed in to change notification settings - Fork 3
Add NDPointIndex examples #25
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
Merged
Merged
Changes from 2 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
c18e601
add NDPointIndex examples (wip advanced example)
benbovy 260df50
advanced example: add indexing
benbovy e30e653
Merge branch 'main' into add-nd-point-index
benbovy 79508c1
explain with using sklearn.BallTree
benbovy ab2328d
Merge branch 'main' into add-nd-point-index
benbovy 94bdafe
edits
dcherian File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,181 @@ | ||
# Tree-based indexes with `NDPointIndex` | ||
--- | ||
jupytext: | ||
text_representation: | ||
format_name: myst | ||
kernelspec: | ||
display_name: Python 3 | ||
name: python | ||
--- | ||
|
||
# Nearest neighbors with `NDPointIndex` | ||
|
||
## Highlights | ||
|
||
1. {py:class}`xarray.indexes.NDPointIndex` is useful for dealing with | ||
n-dimensional coordinate variables representing irregular data. | ||
1. It enables point-wise (nearest-neighbors) data selection using Xarray's | ||
[advanced indexing](https://docs.xarray.dev/en/latest/user-guide/indexing.html#more-advanced-indexing) | ||
capabilities. | ||
1. By default, a {py:class}`scipy.spatial.KDTree` is used under the hood for | ||
fast lookup of point data. Although experimental, it is possible to plug in | ||
alternative structures to `NDPointIndex` (see the advanced example below). | ||
|
||
## Basic example | ||
|
||
Let's create a dataset with random points. | ||
|
||
```{code-cell} python | ||
import numpy as np | ||
import matplotlib.pyplot as plt | ||
import xarray as xr | ||
``` | ||
|
||
```{code-cell} python | ||
--- | ||
tags: [remove-cell] | ||
--- | ||
%xmode minimal | ||
xr.set_options( | ||
display_expand_indexes=True, | ||
display_expand_data=False, | ||
); | ||
``` | ||
|
||
```{code-cell} python | ||
shape = (5, 10) | ||
xx = xr.DataArray(np.random.uniform(0, 10, size=shape), dims=("y", "x")) | ||
yy = xr.DataArray(np.random.uniform(0, 5, size=shape), dims=("y", "x")) | ||
data = (xx - 5)**2 + (yy - 2.5)**2 | ||
|
||
ds = xr.Dataset(data_vars={"data": data}, coords={"xx": xx, "yy": yy}) | ||
ds | ||
``` | ||
|
||
```{code-cell} python | ||
ds.plot.scatter(x="xx", y="yy", hue="data"); | ||
``` | ||
|
||
### Assigning | ||
|
||
```{code-cell} python | ||
ds_index = ds.set_xindex(("xx", "yy"), xr.indexes.NDPointIndex) | ||
ds_index | ||
``` | ||
|
||
### Point-wise indexing | ||
|
||
Select one value. | ||
|
||
```{code-cell} python | ||
ds_index.sel(xx=3.4, yy=4.2, method="nearest") | ||
``` | ||
|
||
Select multiple points in the `x`/`y` dimension space, using | ||
{py:class}`xarray.DataArray` objects as input labels. | ||
|
||
```{code-cell} python | ||
# create a regular grid as query points | ||
ds_grid = xr.Dataset(coords={"x": range(10), "y": range(5)}) | ||
|
||
# selection supports broadcasting of the input labels | ||
ds_selection = ds_index.sel( | ||
xx=ds_grid.x, yy=ds_grid.y, method="nearest" | ||
) | ||
|
||
# assign selection results to the grid | ||
# -> nearest neighbor interpolation | ||
ds_grid["data"] = ds_selection.data.variable | ||
|
||
ds_grid | ||
``` | ||
|
||
```{code-cell} python | ||
ds_grid.data.plot(x="x", y="y") | ||
ds.plot.scatter(x="xx", y="yy", c="k") | ||
plt.show() | ||
``` | ||
|
||
## Advanced example | ||
|
||
This example is based on the Regional Ocean Modeling System (ROMS) [Xarray | ||
example](https://docs.xarray.dev/en/stable/examples/ROMS_ocean_model.html). | ||
|
||
```{note} | ||
An alternative solution to this example is to use | ||
{py:class}`xarray.indexes.CoordinateTransformIndex` (see {doc}`transform`) with the | ||
horizontal coordinate transformations defined in ROMS. | ||
``` | ||
|
||
```{code-cell} python | ||
ds_roms = xr.tutorial.open_dataset("ROMS_example") | ||
ds_roms | ||
``` | ||
|
||
The dataset above is represented on a curvilinear grid with 2-dimensional | ||
`lat_rho` and `lon_rho` coordinate variables (in degrees). The default kd-tree | ||
structure used by {py:class}`~xarray.indexes.NDPointIndex` isn't best suited for | ||
these latitude and longitude coordinates. Fortunately, there a way of using | ||
alternative structures. Here let's use {py:class}`sklearn.neighbors.BallTree` | ||
with the `haversine` distance metric. | ||
|
||
```{code-cell} python | ||
from sklearn.neighbors import BallTree | ||
from xarray.indexes.nd_point_index import TreeAdapter | ||
|
||
|
||
class SklearnGeoBallTreeAdapter(TreeAdapter): | ||
|
||
def __init__(self, points: np.ndarray, options: dict): | ||
options.update({'metric': 'haversine'}) | ||
self._balltree = BallTree(np.deg2rad(points), **options) | ||
|
||
def query(self, points: np.ndarray) -> tuple[np.ndarray, np.ndarray]: | ||
return self._balltree.query(np.deg2rad(points)) | ||
|
||
def equals(self, other: "SklearnGeoBallTreeAdapter") -> bool: | ||
return np.array_equal(self._balltree.data, other._kdtree.data) | ||
``` | ||
|
||
```{note} | ||
Using alternative structures via custom `TreeAdapter` subclasses is an | ||
experimental feature! | ||
|
||
The adapter above based on {py:class}`sklearn.neighbors.BallTree` will | ||
eventually be available in the [xoak](https://github.com/xarray-contrib/xoak) | ||
package along with other useful adapters. | ||
``` | ||
|
||
### Assigning | ||
|
||
```{code-cell} python | ||
ds_roms_index = ds_roms.set_xindex( | ||
("lat_rho", "lon_rho"), | ||
xr.indexes.NDPointIndex, | ||
tree_adapter_cls=SklearnGeoBallTreeAdapter, | ||
) | ||
ds_roms_index | ||
``` | ||
|
||
### Indexing | ||
|
||
```{code-cell} python | ||
ds_trajectory = xr.Dataset( | ||
coords={ | ||
"lat": ('trajectory', np.linspace(28, 30, 50)), | ||
"lon": ('trajectory', np.linspace(-93, -88, 50)), | ||
}, | ||
) | ||
|
||
ds_roms_selection = ds_roms_index.sel( | ||
lat_rho=ds_trajectory.lat, | ||
lon_rho=ds_trajectory.lon, | ||
method="nearest", | ||
) | ||
ds_roms_selection | ||
``` | ||
|
||
```{code-cell} python | ||
|
||
ds_roms_selection.plot.scatter(x="lat_rho", y="lat_rho", hue="zeta") | ||
plt.show() | ||
``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -22,3 +22,4 @@ git+https://github.com/dcherian/rolodex | |
pint-xarray | ||
cf_xarray | ||
git+https://github.com/pydata/xarray | ||
scikit-learn |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.