Skip to content
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

Picking up #1118: Do not convert subclasses of ndarray unless required #2956

Closed
wants to merge 42 commits into from
Closed
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
dcc4bfe
import the unittest test suite for quantities
keewis May 12, 2019
f6925be
make sure no divide by zero occurs
keewis May 12, 2019
ef13531
use asanyarray instead of asarray in as_compatible_data
keewis May 12, 2019
b373ecf
preserve ndarray subclasses with the data accessor
keewis May 12, 2019
a2aced1
now the sel test passes, too, so don't xfail it
keewis May 12, 2019
97683a4
remove the last divide-by-zero possibility
keewis May 12, 2019
2ece12b
add quantities to some of the requirements files
keewis May 12, 2019
7a25fb6
rename the test file to match the name of the original test file
keewis May 12, 2019
4348e0b
remove trailing whitespace
keewis May 12, 2019
dbeaed8
fix a typo
keewis May 13, 2019
f792478
replace the single data fixture with multiple smaller ones
keewis May 13, 2019
b2e3ae2
add a test for combining data arrays
keewis May 13, 2019
453c693
replace the requires_quantities decorator with skipif on module level
keewis May 13, 2019
0d4b543
convert the test methods from the namespace class to functions
keewis May 13, 2019
8beaf76
also check that units on the data itself survive
keewis May 13, 2019
b4d4288
fix the order of imports
keewis May 19, 2019
1ad1d6d
assert in the comparison function instead of asserting the result
keewis May 20, 2019
2b654a5
use data creation helpers instead of data fixtures
keewis May 20, 2019
c52bdf4
add an option to switch on the support for subclasses
keewis May 20, 2019
92e62b3
modify duck_array_ops.asarray to work like asanyarray if enabled
keewis May 20, 2019
280abf3
add a function that uses asanyarray instead of asarray if the option …
keewis May 20, 2019
24d2771
use the new asarray function instead of using options directly
keewis May 20, 2019
2ea846e
explicitly convert matrix objects to ndarrays
keewis May 20, 2019
5a4db0c
wrap the option name and validator lines
keewis May 20, 2019
9809596
add tests to ensure the matrix and MaskedArray classes get converted
keewis May 20, 2019
b4cab61
fix the indentation of a parenthesis
keewis May 20, 2019
6f398e5
fix the line length of a decorator call
keewis May 20, 2019
54522e3
Merge commit 'f172c673' into member-arrays-with-units
keewis Aug 19, 2019
ee15176
black
keewis Aug 19, 2019
3bc5c5c
black2
keewis Aug 19, 2019
c1e513a
Merge commit 'd089df38' into member-arrays-with-units
keewis Aug 19, 2019
5477bca
Merge branch 'master' into member-arrays-with-units
keewis Aug 19, 2019
c787809
move the function deciding between asarray and asanyarray to npcompat
keewis Aug 19, 2019
c653eaa
make sure the original arrays are used as comparison
keewis Aug 19, 2019
5aee870
isort
keewis Aug 19, 2019
c2944c5
allow passing custom arrays to the helper functions
keewis Aug 20, 2019
8e7d7ce
create the test data in the tests to increase the readability
keewis Aug 20, 2019
25f5800
Merge branch 'master' into member-arrays-with-units
keewis Aug 20, 2019
e13e273
black
keewis Aug 21, 2019
a89a1e5
reuse the coordinate dict
keewis Aug 21, 2019
fe6a799
ignore the missing type annotations for quantities
keewis Aug 22, 2019
c4d8512
Merge branch 'master' into member-arrays-with-units
keewis Aug 26, 2019
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions ci/requirements-py36.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ dependencies:
- iris>=1.10
- pydap
- lxml
- quantities
- pip:
- cfgrib>=0.9.2
- mypy==0.660
1 change: 1 addition & 0 deletions ci/requirements-py37.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ dependencies:
- lxml
- eccodes
- pydap
- quantities
- pip:
- cfgrib>=0.9.2
- mypy==0.650
19 changes: 17 additions & 2 deletions xarray/core/variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ def as_compatible_data(data, fastpath=False):
data = np.asarray(data)

# validate whether the data is valid data types
data = np.asarray(data)
data = np.asanyarray(data)

if isinstance(data, np.ndarray):
if data.dtype.kind == 'O':
Expand Down Expand Up @@ -219,6 +219,21 @@ def _as_array_or_item(data):
return data


def _as_any_array_or_item(data):
""" Return the given values as a numpy array subclass instance, or
individual item if it's a 0d datetime64 or timedelta64 array.

The same caveats as for ``_as_array_or_item`` apply.
"""
data = np.asanyarray(data)
if data.ndim == 0:
if data.dtype.kind == 'M':
data = np.datetime64(data, 'ns')
elif data.dtype.kind == 'm':
data = np.timedelta64(data, 'ns')
return data


class Variable(common.AbstractArray, arithmetic.SupportsArithmetic,
utils.NdimSizeLenMixin):
"""A netcdf-like variable consisting of dimensions, data and attributes
Expand Down Expand Up @@ -294,7 +309,7 @@ def data(self):
if isinstance(self._data, dask_array_type):
return self._data
else:
return self.values
return _as_any_array_or_item(self._data)

@data.setter
def data(self, data):
Expand Down
121 changes: 121 additions & 0 deletions xarray/tests/test_quantities.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import numpy as np
import pytest

from xarray import DataArray

try:
import quantities as pq
has_quantities = True
except ImportError:
has_quantities = False

pytestmark = pytest.mark.skipif(
not has_quantities,
reason="requires python-quantities",
)


def equal_with_units(a, b):
a = a if not isinstance(a, DataArray) else a.data
b = b if not isinstance(b, DataArray) else b.data

return (
(hasattr(a, "units") and hasattr(b, "units"))
and a.units == b.units
and np.allclose(a.magnitude, b.magnitude)
)


@pytest.fixture
def data():
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a minor point, but I would recommend against using pytest fixtures for test data. (Though we do use this style currently in xarray in a few places.)

Fixtures are great for setup/teardown (e.g., cleaning up temporary files), but when you test depends on data values, it's best if the data values can be found in the test itself. Otherwise, the logic in a test is not self-contained, which means you have to understand a much bigger context of code.

All this is true for even helper functions, but pytest's fixtures are even more magical:

So in summary:

  • Prefer creating test data in a test itself, if your test relies on any aspect of the data values.
  • If you do want to re-use constructors, prefer using normal helper functions to fixtures. These are easier to understand.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

right, so I used helper functions instead

return (np.arange(10 * 20).reshape(10, 20) + 1) * pq.V


@pytest.fixture
def coords():
return {
'x': (np.arange(10) + 1) * pq.A,
'y': np.arange(20) + 1,
'xp': (np.arange(10) + 1) * pq.J,
}


@pytest.fixture
def data_array(data, coords):
coords['xp'] = (['x'], coords['xp'])
return DataArray(
data,
dims=('x', 'y'),
coords=coords,
)


def with_keys(mapping, keys):
return {
key: value
for key, value in mapping.items()
if key in keys
}


def test_units_in_data_and_coords(data_array):
assert equal_with_units(data_array.data, data_array)
assert equal_with_units(data_array.xp.data, data_array.xp)


def test_arithmetics(data_array, data, coords):
v = data
da = data_array

f = np.arange(10 * 20).reshape(10, 20) * pq.A
g = DataArray(f, dims=['x', 'y'], coords=with_keys(coords, ['x', 'y']))
assert equal_with_units(da * g, v * f)

# swapped dimension order
f = np.arange(20 * 10).reshape(20, 10) * pq.V
g = DataArray(f, dims=['y', 'x'], coords=with_keys(coords, ['x', 'y']))
assert equal_with_units(da + g, v + f.T)

# broadcasting
f = (np.arange(10) + 1) * pq.m
g = DataArray(f, dims=['x'], coords=with_keys(coords, ['x']))
assert equal_with_units(da / g, v / f[:, None])


@pytest.mark.xfail(reason="units don't survive through combining yet")
def test_combine(data_array):
from xarray import concat

a = data_array[:, :10]
b = data_array[:, 10:]

assert equal_with_units(concat([a, b], dim='y'), data_array)


def test_unit_checking(data_array, coords):
da = data_array

f = np.arange(10 * 20).reshape(10, 20) * pq.A
g = DataArray(f, dims=['x', 'y'], coords=with_keys(coords, ['x', 'y']))
with pytest.raises(ValueError,
match="Unable to convert between units"):
da + g


@pytest.mark.xfail(reason="units in indexes not supported")
def test_units_in_indexes(data_array, coords):
""" Test if units survive through xarray indexes.
Indexes are borrowed from Pandas, and Pandas does not support
units. Therefore, we currently don't intend to support units on
indexes either.
"""
assert equal_with_units(data_array.x, coords['x'])


def test_sel(data_array, coords, data):
assert equal_with_units(data_array.sel(y=coords['y'][0]), data[:, 0])


@pytest.mark.xfail
def test_mean(data_array, data):
assert equal_with_units(data_array.mean('x'), data.mean(0))