-
-
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
xarray.map #4484
Closed
Closed
xarray.map #4484
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
8000575
Fixing deepcopy for Dataset.attrs + adjusting testcase
kefirbandi 73a2cab
removing extra newlines
kefirbandi 6926f5b
Updating whats-new
kefirbandi 5114beb
PEP8
kefirbandi 81aae2e
Adding attrs-test to the shallow copy testcase
kefirbandi 68455ca
Rename _attrs -> attrs
shoyer 7c983e0
Merge branch 'master' into master
shoyer 0dabcac
Merge remote-tracking branch 'upstream/master'
kefirbandi 2e711b3
Adding the xarray.map function as a multi-variable generalization of …
kefirbandi 5d17336
Some formatting changes
kefirbandi ed286b8
Docs fixes
kefirbandi 53b96f4
Pep8, doctest
kefirbandi 8d59089
attempt to fix imports in __init__.py
kefirbandi d99b0d8
fixing doctest
kefirbandi 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 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 |
---|---|---|
|
@@ -33,6 +33,7 @@ Top-level functions | |
corr | ||
dot | ||
polyval | ||
map | ||
map_blocks | ||
show_versions | ||
set_options | ||
|
This file contains 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 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 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 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 |
---|---|---|
@@ -0,0 +1,107 @@ | ||
from typing import ( | ||
Any, | ||
Callable, | ||
Dict, | ||
Iterable, | ||
Optional, | ||
) | ||
|
||
from .options import _get_keep_attrs | ||
from .utils import ( | ||
maybe_wrap_array, | ||
) | ||
from .. import Dataset | ||
|
||
|
||
def map( | ||
datasets: Iterable[Any], | ||
func: Callable, | ||
keep_attrs: Optional[int] = None, | ||
args: Iterable[Any] = (), | ||
kwargs: Dict = None, | ||
) -> "Dataset": | ||
"""Apply a function to each variable in the provided dataset(s). | ||
|
||
The function may take several DataArrays as inputs. The number of DataArrays | ||
passed to the function will be equal to the length of the datasets variable. | ||
|
||
It is assumed that the Datasets in the datasets variable share common data variable names. | ||
If the same variable name is present in all Datasets, then the function will be performed on | ||
those DataArrays | ||
|
||
Parameters | ||
---------- | ||
datasets : sequence of Datasets | ||
The Dataset whose variables will be the input DataArrays of the function | ||
func : callable | ||
Function which can be called in the form `func(x,y,z, ..., *args, **kwargs)` | ||
to transform each sequence of DataArrays `x`, `y`, `z` in the datasets into another | ||
DataArray. | ||
keep_attrs : int or bool, optional | ||
If False, the new object will be returned without attributes. | ||
If is an integer between 0 and len(datasets-1), it will give the index of the Dataset in | ||
datasets parameter whose attributes needs to be copied | ||
args : tuple, optional | ||
Positional arguments passed on to `func`. | ||
kwargs : dict, optional | ||
Keyword arguments passed on to `func`. | ||
|
||
Returns | ||
------- | ||
applied : Dataset | ||
Resulting dataset from applying ``func`` to each tuple of data variables. | ||
|
||
Examples | ||
-------- | ||
>>> da = xr.DataArray([[1.1, 2.2, 3.3], [4.4, 5.5, 6.6]]) | ||
>>> ds1 = xr.Dataset({"foo": da, "bar": ("x", [-1, 2])}) | ||
>>> ds2 = xr.Dataset({"foo": da+1, "bar": ("x", [-1, 2])}) | ||
>>> ds1 | ||
<xarray.Dataset> | ||
Dimensions: (dim_0: 2, dim_1: 3, x: 2) | ||
Dimensions without coordinates: dim_0, dim_1, x | ||
Data variables: | ||
foo (dim_0, dim_1) float64 1.1 2.2 3.3 4.4 5.5 6.6 | ||
bar (x) int64 -1 2 | ||
>>> ds2 | ||
<xarray.Dataset> | ||
Dimensions: (dim_0: 2, dim_1: 3, x: 2) | ||
Dimensions without coordinates: dim_0, dim_1, x | ||
Data variables: | ||
foo (dim_0, dim_1) float64 2.1 3.2 4.3 5.4 6.5 7.6 | ||
bar (x) int64 -1 2 | ||
>>> f = lambda a, b: b-a | ||
>>> map([ds1, ds2], f) | ||
<xarray.Dataset> | ||
Dimensions: (dim_0: 2, dim_1: 3, x: 2) | ||
Dimensions without coordinates: dim_0, dim_1, x | ||
Data variables: | ||
foo (dim_0, dim_1) float64 1.0 1.0 1.0 1.0 1.0 1.0 | ||
bar (x) int64 0 0 | ||
|
||
|
||
See Also | ||
-------- | ||
Dataset.map | ||
""" | ||
if kwargs is None: | ||
kwargs = {} | ||
variables = {} | ||
if len(datasets): | ||
shared_variable_names = set.intersection(*(set(ds.data_vars) for ds in datasets)) | ||
for k in shared_variable_names: | ||
data_arrays = [d[k] for d in datasets] | ||
v = maybe_wrap_array(datasets[0][k], func(*(data_arrays + list(args)), **kwargs)) | ||
variables[k] = v | ||
|
||
if keep_attrs is None: | ||
keep_attrs = _get_keep_attrs(default=False) | ||
if keep_attrs: | ||
keep_attrs = 0 | ||
|
||
if keep_attrs is not False: | ||
attrs = datasets[keep_attrs].attrs | ||
else: | ||
attrs = None | ||
|
||
return Dataset(variables, attrs=attrs) |
This file contains 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 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 |
---|---|---|
@@ -0,0 +1,63 @@ | ||
import numpy as np | ||
|
||
import xarray as xr | ||
from xarray.testing import assert_identical, assert_allclose | ||
|
||
|
||
class TestMap: | ||
def test_2_dim(self): | ||
da = xr.DataArray(np.random.randn(2, 3)) | ||
ds1 = xr.Dataset({"foo": da, "bar": ("x", [-1, 2])}) | ||
ds2 = xr.Dataset({"foo": da + 1, "bar": ("x", [0, 3])}) | ||
print(ds1) | ||
print(ds2) | ||
|
||
f = lambda a, b: b - a | ||
r = xr.map([ds1, ds2], f) | ||
assert_allclose(r, xr.ones_like(ds1)) | ||
|
||
def test_different_variables_with_overlap(self): | ||
ds1 = xr.Dataset({"foo": ("x", [1, 2]), "bar": ("x", [-1, 2]), | ||
"oof" : ("x", [3, 4])}) | ||
ds2 = xr.Dataset({"foo": ("x", [11, 22]), "oof": ("x", [-1, 3])}) | ||
ds3 = xr.Dataset({"bar": ("x", [11, 22]), "oof": ("x", [-1, 2])}) | ||
|
||
ds_out = xr.Dataset({"oof": ("x", [3, 5])}) | ||
f = lambda x, y, z: x + y - z | ||
r = xr.map([ds1, ds2, ds3], f) | ||
assert_identical(r, ds_out) | ||
|
||
def test_no_variable_overlap(self): | ||
ds1 = xr.Dataset({"foo": ("x", [1, 2]), "oof": ("x", [3, 4])}) | ||
ds2 = xr.Dataset({"bar": ("x", [11, 22]), "rab": ("x", [-1, 3])}) | ||
|
||
ds_out = xr.Dataset() | ||
f = lambda x, y: x + y | ||
r = xr.map([ds1, ds2], f) | ||
assert_identical(r, ds_out) | ||
|
||
def test_with_args_and_kwargs(self): | ||
ds1 = xr.Dataset({"foo": ("x", [1, 1]), "oof": ("x", [3, 3])}) | ||
ds2 = xr.Dataset({"foo": ("x", [2, 2]), "oof": ("x", [4, 4])}) | ||
|
||
ds_out = xr.Dataset({"foo": ("x", [8, 8]), "oof": ("x", [18, 18])}) | ||
|
||
def f(da1, da2, multiplier_1, multiplier_2): | ||
return multiplier_1 * da1 + multiplier_2 * da2 | ||
|
||
r = xr.map([ds1, ds2], f, args=[2], kwargs={'multiplier_2' : 3}) | ||
assert_identical(r, ds_out) | ||
|
||
def test_keep_attrs(self): | ||
ds1 = xr.Dataset({"foo": ("x", [1, 1]), "oof": ("x", [3, 3])}, attrs={'value': 1}) | ||
ds2 = xr.Dataset({"foo": ("x", [2, 2]), "oof": ("x", [4, 4])}, attrs={'value': 2}) | ||
ds3 = xr.Dataset({"foo": ("x", [3, 3]), "oof": ("x", [5, 5])}, attrs={'value': 3}) | ||
|
||
def f(da1, da2, da3, selector): | ||
return [da1, da2, da3][selector] | ||
|
||
r = xr.map([ds1, ds2, ds3], f, args=[2], keep_attrs=0) | ||
assert r.attrs['value'] == 1 | ||
|
||
r = xr.map([ds1, ds2, ds3], f, args=[0], keep_attrs=1) | ||
assert r.attrs['value'] == 2 |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I would prefer not use
maybe_wrap_array
in new functions. It exists inmap
only for legacy reasons, but we'd really like to put that sort of functionality into a separate dedicated function (e.g., see the proposal forapply_raw
in #1618).There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
No problem for me. I copied the existing behavior without actually really paying attention as to what it is doing an why.