diff --git a/.gitignore b/.gitignore index 68f548b..f53aca4 100644 --- a/.gitignore +++ b/.gitignore @@ -32,6 +32,7 @@ pip-log.txt .tox nosetests.xml .cache +.ropeproject/ # Translations *.mo @@ -51,4 +52,7 @@ doc/_build doc/generated xarray/version.py +# Sync tools +Icon* + .ipynb_checkpoints diff --git a/.travis.yml b/.travis.yml index d797e98..068ea3c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -13,7 +13,7 @@ matrix: - python: 2.7 env: CONDA_ENV=py27-min - python: 2.7 - env: CONDA_ENV=py27-cdat+pynio + env: CONDA_ENV=py27-cdat+iris+pynio - python: 3.4 env: CONDA_ENV=py34 - python: 3.5 @@ -43,6 +43,8 @@ matrix: env: CONDA_ENV=py36-pynio-dev - python: 3.6 env: CONDA_ENV=py36-rasterio1.0alpha + - python: 3.6 + env: CONDA_ENV=py36-zarr-dev allow_failures: - python: 3.6 env: @@ -67,6 +69,8 @@ matrix: env: CONDA_ENV=py36-pynio-dev - python: 3.6 env: CONDA_ENV=py36-rasterio1.0alpha + - python: 3.6 + env: CONDA_ENV=py36-zarr-dev before_install: - if [[ "$TRAVIS_PYTHON_VERSION" == "2.7" ]]; then @@ -89,9 +93,9 @@ install: - python xarray/util/print_versions.py script: + - flake8 -j auto xarray - python -OO -c "import xarray" - py.test xarray --cov=xarray --cov-config ci/.coveragerc --cov-report term-missing --verbose $EXTRA_FLAGS - - git diff upstream/master **/*py | flake8 --diff --exit-zero || true after_success: - coveralls diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..d457a9e --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,46 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at xarray-core-team@googlegroups.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/asv_bench/benchmarks/dataarray_missing.py b/asv_bench/benchmarks/dataarray_missing.py new file mode 100644 index 0000000..c6aa8f4 --- /dev/null +++ b/asv_bench/benchmarks/dataarray_missing.py @@ -0,0 +1,73 @@ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import pandas as pd + +try: + import dask +except ImportError: + pass + +import xarray as xr + +from . import randn, requires_dask + + +def make_bench_data(shape, frac_nan, chunks): + vals = randn(shape, frac_nan) + coords = {'time': pd.date_range('2000-01-01', freq='D', + periods=shape[0])} + da = xr.DataArray(vals, dims=('time', 'x', 'y'), coords=coords) + + if chunks is not None: + da = da.chunk(chunks) + + return da + + +def time_interpolate_na(shape, chunks, method, limit): + if chunks is not None: + requires_dask() + da = make_bench_data(shape, 0.1, chunks=chunks) + actual = da.interpolate_na(dim='time', method='linear', limit=limit) + + if chunks is not None: + actual = actual.compute() + + +time_interpolate_na.param_names = ['shape', 'chunks', 'method', 'limit'] +time_interpolate_na.params = ([(3650, 200, 400), (100, 25, 25)], + [None, {'x': 25, 'y': 25}], + ['linear', 'spline', 'quadratic', 'cubic'], + [None, 3]) + + +def time_ffill(shape, chunks, limit): + + da = make_bench_data(shape, 0.1, chunks=chunks) + actual = da.ffill(dim='time', limit=limit) + + if chunks is not None: + actual = actual.compute() + + +time_ffill.param_names = ['shape', 'chunks', 'limit'] +time_ffill.params = ([(3650, 200, 400), (100, 25, 25)], + [None, {'x': 25, 'y': 25}], + [None, 3]) + + +def time_bfill(shape, chunks, limit): + + da = make_bench_data(shape, 0.1, chunks=chunks) + actual = da.bfill(dim='time', limit=limit) + + if chunks is not None: + actual = actual.compute() + + +time_bfill.param_names = ['shape', 'chunks', 'limit'] +time_bfill.params = ([(3650, 200, 400), (100, 25, 25)], + [None, {'x': 25, 'y': 25}], + [None, 3]) diff --git a/ci/requirements-py27-cdat+pynio.yml b/ci/requirements-py27-cdat+iris+pynio.yml similarity index 93% rename from ci/requirements-py27-cdat+pynio.yml rename to ci/requirements-py27-cdat+iris+pynio.yml index 126dd41..6c7e3b8 100644 --- a/ci/requirements-py27-cdat+pynio.yml +++ b/ci/requirements-py27-cdat+iris+pynio.yml @@ -22,6 +22,8 @@ dependencies: - seaborn - toolz - rasterio + - iris>=1.10 + - zarr - pip: - coveralls - pytest-cov diff --git a/ci/requirements-py27-windows.yml b/ci/requirements-py27-windows.yml index bb76afd..a39b24b 100644 --- a/ci/requirements-py27-windows.yml +++ b/ci/requirements-py27-windows.yml @@ -19,3 +19,4 @@ dependencies: - seaborn - toolz - rasterio + - zarr diff --git a/ci/requirements-py34.yml b/ci/requirements-py34.yml index 0b0d409..ba79e00 100644 --- a/ci/requirements-py34.yml +++ b/ci/requirements-py34.yml @@ -2,9 +2,9 @@ name: test_env dependencies: - python=3.4 - bottleneck - - pytest - flake8 - pandas - pip: - coveralls - pytest-cov + - pytest diff --git a/ci/requirements-py35.yml b/ci/requirements-py35.yml index 8c5ca99..6f9ae24 100644 --- a/ci/requirements-py35.yml +++ b/ci/requirements-py35.yml @@ -17,6 +17,7 @@ dependencies: - seaborn - toolz - rasterio + - zarr - pip: - coveralls - pytest-cov diff --git a/ci/requirements-py36-windows.yml b/ci/requirements-py36-windows.yml index 70ff3e5..ea366bd 100644 --- a/ci/requirements-py36-windows.yml +++ b/ci/requirements-py36-windows.yml @@ -16,3 +16,4 @@ dependencies: - seaborn - toolz - rasterio + - zarr diff --git a/ci/requirements-py36-zarr-dev.yml b/ci/requirements-py36-zarr-dev.yml new file mode 100644 index 0000000..9be5228 --- /dev/null +++ b/ci/requirements-py36-zarr-dev.yml @@ -0,0 +1,20 @@ +name: test_env +channels: + - conda-forge +dependencies: + - python=3.6 + - dask + - distributed + - matplotlib + - pytest + - flake8 + - numpy + - pandas + - scipy + - seaborn + - toolz + - bottleneck + - pip: + - coveralls + - pytest-cov + - git+https://github.com/alimanfoo/zarr.git diff --git a/ci/requirements-py36.yml b/ci/requirements-py36.yml index d679c83..cc02d6e 100644 --- a/ci/requirements-py36.yml +++ b/ci/requirements-py36.yml @@ -18,7 +18,9 @@ dependencies: - toolz - rasterio - bottleneck + - zarr - pip: - coveralls - pytest-cov - pydap + - lxml diff --git a/doc/api-hidden.rst b/doc/api-hidden.rst index c27db1e..b8fbfbc 100644 --- a/doc/api-hidden.rst +++ b/doc/api-hidden.rst @@ -46,6 +46,7 @@ Dataset.T Dataset.cumsum Dataset.cumprod + Dataset.rank DataArray.ndim DataArray.shape @@ -91,6 +92,7 @@ DataArray.T DataArray.cumsum DataArray.cumprod + DataArray.rank ufuncs.angle ufuncs.arccos diff --git a/doc/api.rst b/doc/api.rst index 7bcb844..10386fe 100644 --- a/doc/api.rst +++ b/doc/api.rst @@ -148,6 +148,9 @@ Computation :py:attr:`~Dataset.count` :py:attr:`~Dataset.dropna` :py:attr:`~Dataset.fillna` +:py:attr:`~Dataset.ffill` +:py:attr:`~Dataset.bfill` +:py:attr:`~Dataset.interpolate_na` :py:attr:`~Dataset.where` **ndarray methods**: @@ -160,6 +163,7 @@ Computation :py:attr:`~Dataset.real` :py:attr:`~Dataset.cumsum` :py:attr:`~Dataset.cumprod` +:py:attr:`~Dataset.rank` **Grouped operations**: :py:attr:`~core.groupby.DatasetGroupBy.assign` @@ -298,6 +302,9 @@ Computation :py:attr:`~DataArray.count` :py:attr:`~DataArray.dropna` :py:attr:`~DataArray.fillna` +:py:attr:`~DataArray.ffill` +:py:attr:`~DataArray.bfill` +:py:attr:`~DataArray.interpolate_na` :py:attr:`~DataArray.where` **ndarray methods**: @@ -312,6 +319,7 @@ Computation :py:attr:`~DataArray.T` :py:attr:`~DataArray.cumsum` :py:attr:`~DataArray.cumprod` +:py:attr:`~DataArray.rank` **Grouped operations**: :py:attr:`~core.groupby.DataArrayGroupBy.assign_coords` @@ -415,7 +423,9 @@ Dataset methods open_dataset open_mfdataset open_rasterio + open_zarr Dataset.to_netcdf + Dataset.to_zarr save_mfdataset Dataset.to_array Dataset.to_dataframe @@ -446,6 +456,8 @@ DataArray methods DataArray.to_index DataArray.to_masked_array DataArray.to_cdms2 + DataArray.to_iris + DataArray.from_iris DataArray.to_dict DataArray.from_series DataArray.from_cdms2 diff --git a/doc/computation.rst b/doc/computation.rst index 087cca6..420b979 100644 --- a/doc/computation.rst +++ b/doc/computation.rst @@ -59,8 +59,9 @@ Missing values xarray objects borrow the :py:meth:`~xarray.DataArray.isnull`, :py:meth:`~xarray.DataArray.notnull`, :py:meth:`~xarray.DataArray.count`, -:py:meth:`~xarray.DataArray.dropna` and :py:meth:`~xarray.DataArray.fillna` methods -for working with missing data from pandas: +:py:meth:`~xarray.DataArray.dropna`, :py:meth:`~xarray.DataArray.fillna`, +:py:meth:`~xarray.DataArray.ffill`, and :py:meth:`~xarray.DataArray.bfill` +methods for working with missing data from pandas: .. ipython:: python @@ -70,10 +71,25 @@ for working with missing data from pandas: x.count() x.dropna(dim='x') x.fillna(-1) + x.ffill() + x.bfill() Like pandas, xarray uses the float value ``np.nan`` (not-a-number) to represent missing values. +xarray objects also have an :py:meth:`~xarray.DataArray.interpolate_na` method +for filling missing values via 1D interpolation. + +.. ipython:: python + + x = xr.DataArray([0, 1, np.nan, np.nan, 2], dims=['x'], + coords={'xx': xr.Variable('x', [0, 1, 1.1, 1.9, 3])}) + x.interpolate_na(dim='x', method='linear', use_coordinate='xx') + +Note that xarray slightly diverges from the pandas ``interpolate`` syntax by +providing the ``use_coordinate`` keyword which facilitates a clear specification +of which values to use as the index in the interpolation. + Aggregation =========== diff --git a/doc/conf.py b/doc/conf.py index 5a62cb5..eb71c92 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -23,7 +23,7 @@ print("python exec:", sys.executable) print("sys.path:", sys.path) for name in ('numpy scipy pandas matplotlib dask IPython seaborn ' - 'cartopy netCDF4 rasterio').split(): + 'cartopy netCDF4 rasterio zarr').split(): try: module = importlib.import_module(name) if name == 'matplotlib': @@ -323,4 +323,5 @@ 'iris': ('http://scitools.org.uk/iris/docs/latest/', None), 'numpy': ('https://docs.scipy.org/doc/numpy/', None), 'numba': ('https://numba.pydata.org/numba-doc/latest/', None), + 'matplotlib': ('https://matplotlib.org/', None), } diff --git a/doc/environment.yml b/doc/environment.yml index ae3ddb8..b14fba3 100644 --- a/doc/environment.yml +++ b/doc/environment.yml @@ -16,3 +16,5 @@ dependencies: - cartopy=0.15.1 - rasterio=0.36.0 - sphinx-gallery + - zarr + - iris diff --git a/doc/faq.rst b/doc/faq.rst index 55fe933..68670d0 100644 --- a/doc/faq.rst +++ b/doc/faq.rst @@ -1,6 +1,14 @@ Frequently Asked Questions ========================== +.. ipython:: python + :suppress: + + import numpy as np + import pandas as pd + import xarray as xr + np.random.seed(123456) + Why is pandas not enough? ------------------------- @@ -58,6 +66,38 @@ fundamentally multi-dimensional. If your data is unstructured or one-dimensional, stick with pandas. +Why don't aggregations return Python scalars? +--------------------------------------------- + +xarray tries hard to be self-consistent: operations on a ``DataArray`` (resp. +``Dataset``) return another ``DataArray`` (resp. ``Dataset``) object. In +particular, operations returning scalar values (e.g. indexing or aggregations +like ``mean`` or ``sum`` applied to all axes) will also return xarray objects. + +Unfortunately, this means we sometimes have to explicitly cast our results from +xarray when using them in other libraries. As an illustration, the following +code fragment + +.. ipython:: python + + arr = xr.DataArray([1, 2, 3]) + pd.Series({'x': arr[0], 'mean': arr.mean(), 'std': arr.std()}) + +does not yield the pandas DataFrame we expected. We need to specify the type +conversion ourselves: + +.. ipython:: python + + pd.Series({'x': arr[0], 'mean': arr.mean(), 'std': arr.std()}, dtype=float) + +Alternatively, we could use the ``item`` method or the ``float`` constructor to +convert values one at a time + +.. ipython:: python + + pd.Series({'x': arr[0].item(), 'mean': float(arr.mean())}) + + .. _approach to metadata: What is your approach to metadata? diff --git a/doc/gallery/plot_lines_from_2d.py b/doc/gallery/plot_lines_from_2d.py new file mode 100644 index 0000000..1e5875e --- /dev/null +++ b/doc/gallery/plot_lines_from_2d.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +""" +================================== +Multiple lines from a 2d DataArray +================================== + + +Use :py:func:`xarray.plot.line` on a 2d DataArray to plot selections as +multiple lines. + +See :ref:`plotting.multiplelines` for more details. + +""" + +import xarray as xr +import matplotlib.pyplot as plt + +# Load the data +ds = xr.tutorial.load_dataset('air_temperature') +air = ds.air - 273.15 # to celsius + +# Prepare the figure +f, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4), sharey=True) + +# Selected latitude indices +isel_lats = [10, 15, 20] + +# Temperature vs longitude plot - illustrates the "hue" kwarg +air.isel(time=0, lat=isel_lats).plot.line(ax=ax1, hue='lat') +ax1.set_ylabel('°C') + +# Temperature vs time plot - illustrates the "x" and "add_legend" kwargs +air.isel(lon=30, lat=isel_lats).plot.line(ax=ax2, x='time', add_legend=False) +ax2.set_ylabel('') + +# Show +plt.tight_layout() +plt.show() diff --git a/doc/gallery/plot_rasterio.py b/doc/gallery/plot_rasterio.py index b42970d..2ec58b8 100644 --- a/doc/gallery/plot_rasterio.py +++ b/doc/gallery/plot_rasterio.py @@ -44,13 +44,10 @@ da.coords['lon'] = (('y', 'x'), lon) da.coords['lat'] = (('y', 'x'), lat) -# Compute a greyscale out of the rgb image -greyscale = da.mean(dim='band') - # Plot on a map ax = plt.subplot(projection=ccrs.PlateCarree()) -greyscale.plot(ax=ax, x='lon', y='lat', transform=ccrs.PlateCarree(), - cmap='Greys_r', add_colorbar=False) +da.plot.imshow(ax=ax, x='lon', y='lat', rgb='band', + transform=ccrs.PlateCarree()) ax.coastlines('10m', color='r') plt.show() diff --git a/doc/indexing.rst b/doc/indexing.rst index 74aef45..6b01471 100644 --- a/doc/indexing.rst +++ b/doc/indexing.rst @@ -277,7 +277,7 @@ Like numpy and pandas, xarray supports indexing many array elements at once in a If you only provide integers, slices, or unlabeled arrays (array without dimension names, such as ``np.ndarray``, ``list``, but not :py:meth:`~xarray.DataArray` or :py:meth:`~xarray.Variable`) indexing can be -understand as orthogonally. Each indexer component selects independently along +understood as orthogonally. Each indexer component selects independently along the corresponding dimension, similar to how vector indexing works in Fortran or MATLAB, or after using the :py:func:`numpy.ix_` helper: @@ -357,6 +357,14 @@ These methods may and also be applied to ``Dataset`` objects ``isel_points`` and ``sel_points`` are now deprecated. See :ref:`more_advanced_indexing` for their alternative. +.. note:: + + If an indexer is a :py:meth:`~xarray.DataArray`, its coordinates should not + conflict with the selected subpart of the target array (except for the + explicitly indexed dimensions with ``.loc``/``.sel``). + Otherwise, ``IndexError`` will be raised. + + .. _assigning_values: Assigning values with indexing @@ -401,6 +409,11 @@ __ https://docs.scipy.org/doc/numpy/user/basics.indexing.html#assigning-values-t Dask array does not support value assignment (see :ref:`dask` for the details). +.. note:: + + Coordinates in both the left- and right-hand-side arrays should not + conflict with each other. + Otherwise, ``IndexError`` will be raised. .. warning:: @@ -457,6 +470,7 @@ method: arr.sel(space=xr.DataArray(['IA', 'IL', 'IN'], dims=['new_time']), time=times) + .. _align and reindex: Align and reindex diff --git a/doc/installing.rst b/doc/installing.rst index 62d2a67..3af330f 100644 --- a/doc/installing.rst +++ b/doc/installing.rst @@ -24,6 +24,7 @@ For netCDF and IO reading and writing netCDF4 files that does not use the netCDF-C libraries - `pynio `__: for reading GRIB and other geoscience specific file formats +- `zarr `__: for chunked, compressed, N-dimensional arrays. For accelerating xarray ~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/doc/io.rst b/doc/io.rst index 9e17ffc..eac941b 100644 --- a/doc/io.rst +++ b/doc/io.rst @@ -295,7 +295,7 @@ string encoding for character arrays in netCDF files was Technically, you can use `any string encoding recognized by Python `_ if you feel the need to deviate from UTF-8, by setting the ``_Encoding`` field in ``encoding``. But -`we don't recommend it`_. +`we don't recommend it `_. .. warning:: @@ -338,6 +338,38 @@ supported by netCDF4-python: 'standard', 'gregorian', 'proleptic_gregorian' 'nol By default, xarray uses the 'proleptic_gregorian' calendar and units of the smallest time difference between values, with a reference time of the first time value. +.. _io.iris: + +Iris +---- + +The Iris_ tool allows easy reading of common meteorological and climate model formats +(including GRIB and UK MetOffice PP files) into ``Cube`` objects which are in many ways very +similar to ``DataArray`` objects, while enforcing a CF-compliant data model. If iris is +installed xarray can convert a ``DataArray`` into a ``Cube`` using +:py:meth:`~xarray.DataArray.to_iris`: + +.. ipython:: python + + da = xr.DataArray(np.random.rand(4, 5), dims=['x', 'y'], + coords=dict(x=[10, 20, 30, 40], + y=pd.date_range('2000-01-01', periods=5))) + + cube = da.to_iris() + cube + +Conversely, we can create a new ``DataArray`` object from a ``Cube`` using +:py:meth:`~xarray.DataArray.from_iris`: + +.. ipython:: python + + da_cube = xr.DataArray.from_iris(cube) + da_cube + + +.. _Iris: http://scitools.org.uk/iris + + OPeNDAP ------- @@ -502,6 +534,103 @@ longitudes and latitudes. .. _test files: https://github.com/mapbox/rasterio/blob/master/tests/data/RGB.byte.tif .. _pyproj: https://github.com/jswhit/pyproj +.. _io.zarr: + +Zarr +---- + +`Zarr`_ is a Python package providing an implementation of chunked, compressed, +N-dimensional arrays. +Zarr has the ability to store arrays in a range of ways, including in memory, +in files, and in cloud-based object storage such as `Amazon S3`_ and +`Google Cloud Storage`_. +Xarray's Zarr backend allows xarray to leverage these capabilities. + +.. warning:: + + Zarr support is still an experimental feature. Please report any bugs or + unexepected behavior via github issues. + +Xarray can't open just any zarr dataset, because xarray requires special +metadata (attributes) describing the dataset dimensions and coordinates. +At this time, xarray can only open zarr datasets that have been written by +xarray. To write a dataset with zarr, we use the +:py:attr:`Dataset.to_zarr ` method. +To write to a local directory, we pass a path to a directory + +.. ipython:: python + :suppress: + + ! rm -rf path/to/directory.zarr + +.. ipython:: python + + ds = xr.Dataset({'foo': (('x', 'y'), np.random.rand(4, 5))}, + coords={'x': [10, 20, 30, 40], + 'y': pd.date_range('2000-01-01', periods=5), + 'z': ('x', list('abcd'))}) + ds.to_zarr('path/to/directory.zarr') + +(The suffix ``.zarr`` is optional--just a reminder that a zarr store lives +there.) If the directory does not exist, it will be created. If a zarr +store is already present at that path, an error will be raised, preventing it +from being overwritten. To override this behavior and overwrite an existing +store, add ``mode='w'`` when invoking ``to_zarr``. + +To read back a zarr dataset that has been created this way, we use the +:py:func:`~xarray.open_zarr` method: + +.. ipython:: python + + ds_zarr = xr.open_zarr('path/to/directory.zarr') + ds_zarr + +Cloud Storage Buckets +~~~~~~~~~~~~~~~~~~~~~ + +It is possible to read and write xarray datasets directly from / to cloud +storage buckets using zarr. This example uses the `gcsfs`_ package to provide +a ``MutableMapping`` interface to `Google Cloud Storage`_, which we can then +pass to xarray:: + + import gcsfs + fs = gcsfs.GCSFileSystem(project='', token=None) + gcsmap = gcsfs.mapping.GCSMap('', gcs=fs, check=True, create=False) + # write to the bucket + ds.to_zarr(store=gcsmap) + # read it back + ds_gcs = xr.open_zarr(gcsmap, mode='r') + +.. _Zarr: http://zarr.readthedocs.io/ +.. _Amazon S3: https://aws.amazon.com/s3/ +.. _Google Cloud Storage: https://cloud.google.com/storage/ +.. _gcsfs: https://github.com/dask/gcsfs + +Zarr Compressors and Filters +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +There are many different options for compression and filtering possible with +zarr. These are described in the +`zarr documentation `_. +These options can be passed to the ``to_zarr`` method as variable encoding. +For example: + +.. ipython:: python + :suppress: + + ! rm -rf foo.zarr + +.. ipython:: python + + import zarr + compressor = zarr.Blosc(cname='zstd', clevel=3, shuffle=2) + ds.to_zarr('foo.zarr', encoding={'foo': {'compressor': compressor}}) + +.. note:: + + Not all native zarr compression and filtering options have been tested with + xarray. + .. _io.pynio: Formats supported by PyNIO @@ -529,6 +658,7 @@ exporting your objects to pandas and using its broad range of `IO tools`_. .. _IO tools: http://pandas.pydata.org/pandas-docs/stable/io.html + Combining multiple files ------------------------ diff --git a/doc/plotting.rst b/doc/plotting.rst index 5cfa2b6..2b816a2 100644 --- a/doc/plotting.rst +++ b/doc/plotting.rst @@ -174,14 +174,36 @@ entire figure (as for matplotlib's ``figsize`` argument). .. _not equivalent to matplotlib's: https://github.com/mwaskom/seaborn/issues/746 + +.. _plotting.multiplelines: + +Multiple lines showing variation along a dimension +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +It is possible to make line plots of two-dimensional data by calling :py:func:`xarray.plot.line` +with appropriate arguments. Consider the 3D variable ``air`` defined above. We can use line +plots to check the variation of air temperature at three different latitudes along a longitude line: + +.. ipython:: python + + @savefig plotting_example_multiple_lines_x_kwarg.png + air.isel(lon=10, lat=[19,21,22]).plot.line(x='time') + +It is required to explicitly specify either + +1. ``x``: the dimension to be used for the x-axis, or +2. ``hue``: the dimension you want to represent by multiple lines. + +Thus, we could have made the previous plot by specifying ``hue='lat'`` instead of ``x='time'``. +If required, the automatic legend can be turned off using ``add_legend=False``. + Two Dimensions -------------- Simple Example ~~~~~~~~~~~~~~ -The default method :py:meth:`xarray.DataArray.plot` sees that the data is -2 dimensional and calls :py:func:`xarray.plot.pcolormesh`. +The default method :py:meth:`xarray.DataArray.plot` calls :py:func:`xarray.plot.pcolormesh` by default when the data is two-dimensional. .. ipython:: python @@ -283,6 +305,8 @@ example, consider the original data in Kelvins rather than Celsius: The Celsius data contain 0, so a diverging color map was used. The Kelvins do not have 0, so the default color map was used. +.. _robust-plotting: + Robust ~~~~~~ diff --git a/doc/whats-new.rst b/doc/whats-new.rst index 899175a..0c6a590 100644 --- a/doc/whats-new.rst +++ b/doc/whats-new.rst @@ -18,15 +18,89 @@ What's New v0.10.1 (unreleased) -------------------- +Documentation +~~~~~~~~~~~~~ + +- New entry `Why don’t aggregations return Python scalars?` in the + :doc:`faq` (:issue:`1726`). + By `0x0L `_. + Enhancements ~~~~~~~~~~~~ - -- :py:func:`~plot.contourf()` learned to contour 2D variables that have both a 1D co-ordinate (e.g. time) and a 2D co-ordinate (e.g. depth as a function of time). +- reduce methods such as :py:func:`DataArray.sum()` now accepts ``dtype`` + arguments. (:issue:`1838`) + By `Keisuke Fujii `_. +- Added nodatavals attribute to DataArray when using :py:func:`~xarray.open_rasterio`. (:issue:`1736`). + By `Alan Snow `_. +- :py:func:`~plot.contourf()` learned to contour 2D variables that have both a + 1D co-ordinate (e.g. time) and a 2D co-ordinate (e.g. depth as a function of + time) (:issue:`1737`). + By `Deepak Cherian `_. +- Added :py:meth:`DataArray.to_iris ` and :py:meth:`DataArray.from_iris ` for + converting data arrays to and from Iris_ Cubes with the same data and coordinates (:issue:`621` and :issue:`37`). + By `Neil Parley `_ and `Duncan Watson-Parris `_. +- Use ``pandas.Grouper`` class in xarray resample methods rather than the + deprecated ``pandas.TimeGrouper`` class (:issue:`1766`). + By `Joe Hamman `_. +- Support for using `Zarr`_ as storage layer for xarray. + By `Ryan Abernathey `_. +- :func:`xarray.plot.imshow` now handles RGB and RGBA images. + Saturation can be adjusted with ``vmin`` and ``vmax``, or with ``robust=True``. + By `Zac Hatfield-Dodds `_. +- Experimental support for parsing ENVI metadata to coordinates and attributes + in :py:func:`xarray.open_rasterio`. + By `Matti Eskelinen `_. +- :py:func:`~plot()` learned to rotate x-axis ticks if x-axis is time. + By `Deepak Cherian `_. +- :py:func:`~plot.line()` learned to draw multiple lines if provided with a + 2D variable. By `Deepak Cherian `_. +.. _Zarr: http://zarr.readthedocs.io/ + +.. _Iris: http://scitools.org.uk/iris + +**New functions/methods** + +- New :py:meth:`~xarray.DataArray.rank` on arrays and datasets. Requires + bottleneck (:issue:`1731`). + By `0x0L `_. Bug fixes ~~~~~~~~~ +- Added warning in api.py of a netCDF4 bug that occurs when + the filepath has 88 characters (:issue:`1745`). + By `Liam Brannigan ` _. +- Fixed encoding of multi-dimensional coordinates in + :py:meth:`~Dataset.to_netcdf` (:issue:`1763`). + By `Mike Neish `_. + +- Bug fix in open_dataset(engine='pydap') (:issue:`1775`) + By `Keisuke Fujii `_. + +- Bug fix in vectorized assignment (:issue:`1743`, `1744`). + Now item assignment to :py:meth:`~DataArray.__setitem__` checks +- Bug fix in vectorized assignment (:issue:`1743`, :issue:`1744`). + Now item assignment to :py:meth:`DataArray.__setitem__` checks + coordinates of target, destination and keys. If there are any conflict among + these coordinates, ``IndexError`` will be raised. + By `Keisuke Fujii `_. +- Properly point :py:meth:`DataArray.__dask_scheduler__` to + ``dask.threaded.get``. By `Matthew Rocklin `_. +- Bug fixes in :py:meth:`DataArray.plot.imshow`: all-NaN arrays and arrays + with size one in some dimension can now be plotted, which is good for + exploring satellite imagery (:issue:`1780`). + By `Zac Hatfield-Dodds `_. +- Fixed ``UnboundLocalError`` when opening netCDF file `` (:issue:`1781`). + By `Stephan Hoyer `_. +- The ``variables``, ``attrs``, and ``dimensions`` properties have been + deprecated as part of a bug fix addressing an issue where backends were + unintentionally loading the datastores data and attributes repeatedly during + writes (:issue:`1798`). + By `Joe Hamman `_. +- Compatibility fixes to plotting module for Numpy 1.14 and Pandas 0.22 + (:issue:`1813`). + By `Joe Hamman `_. .. _whats-new.0.10.0: diff --git a/setup.py b/setup.py index db4399b..ccffc63 100644 --- a/setup.py +++ b/setup.py @@ -105,11 +105,14 @@ # partial clone, manually construct version string # this is the format before we started using git-describe # to get an ordering on dev version strings. - rev = "v%s.dev-%s" % (VERSION, rev) + rev = "v%s+dev.%s" % (VERSION, rev) # Strip leading v from tags format "vx.y.z" to get th version string FULLVERSION = rev.lstrip('v') + # make sure we respect PEP 440 + FULLVERSION = FULLVERSION.replace("-", "+dev", 1).replace("-", ".") + else: FULLVERSION += QUALIFIER diff --git a/xarray/__init__.py b/xarray/__init__.py index 1b34425..3e80acd 100644 --- a/xarray/__init__.py +++ b/xarray/__init__.py @@ -18,6 +18,7 @@ from .backends.api import (open_dataset, open_dataarray, open_mfdataset, save_mfdataset) from .backends.rasterio_ import open_rasterio +from .backends.zarr import open_zarr from .conventions import decode_cf, SerializationWarning diff --git a/xarray/backends/__init__.py b/xarray/backends/__init__.py index a082bd5..d85893a 100644 --- a/xarray/backends/__init__.py +++ b/xarray/backends/__init__.py @@ -10,3 +10,15 @@ from .pynio_ import NioDataStore from .scipy_ import ScipyDataStore from .h5netcdf_ import H5NetCDFStore +from .zarr import ZarrStore + +__all__ = [ + 'AbstractDataStore', + 'InMemoryDataStore', + 'NetCDF4DataStore', + 'PydapDataStore', + 'NioDataStore', + 'ScipyDataStore', + 'H5NetCDFStore', + 'ZarrStore', +] diff --git a/xarray/backends/api.py b/xarray/backends/api.py index 36c686e..4359868 100644 --- a/xarray/backends/api.py +++ b/xarray/backends/api.py @@ -27,18 +27,18 @@ def _get_default_engine(path, allow_remote=False): engine = 'netcdf4' except ImportError: try: - import pydap + import pydap # flake8: noqa engine = 'pydap' except ImportError: raise ValueError('netCDF4 or pydap is required for accessing ' 'remote datasets via OPeNDAP') else: try: - import netCDF4 + import netCDF4 # flake8: noqa engine = 'netcdf4' except ImportError: # pragma: no cover try: - import scipy.io.netcdf + import scipy.io.netcdf # flake8: noqa engine = 'scipy' except ImportError: raise ValueError('cannot read or write netCDF files without ' @@ -313,7 +313,10 @@ def maybe_decode_store(store, lock=False): return maybe_decode_store(store) -def open_dataarray(*args, **kwargs): +def open_dataarray(filename_or_obj, group=None, decode_cf=True, + mask_and_scale=True, decode_times=True, autoclose=False, + concat_characters=True, decode_coords=True, engine=None, + chunks=None, lock=None, cache=None, drop_variables=None): """Open an DataArray from a netCDF file containing a single data variable. This is designed to read netCDF files with only one data variable. If @@ -394,7 +397,13 @@ def open_dataarray(*args, **kwargs): -------- open_dataset """ - dataset = open_dataset(*args, **kwargs) + dataset = open_dataset(filename_or_obj, group=group, decode_cf=decode_cf, + mask_and_scale=mask_and_scale, + decode_times=decode_times, autoclose=autoclose, + concat_characters=concat_characters, + decode_coords=decode_coords, engine=engine, + chunks=chunks, lock=lock, cache=cache, + drop_variables=drop_variables) if len(dataset.data_vars) != 1: raise ValueError('Given file dataset contains more than one data ' @@ -713,3 +722,29 @@ def save_mfdataset(datasets, paths, mode='w', format=None, groups=None, finally: for store in stores: store.close() + + +def to_zarr(dataset, store=None, mode='w-', synchronizer=None, group=None, + encoding=None): + """This function creates an appropriate datastore for writing a dataset to + a zarr ztore + + See `Dataset.to_zarr` for full API docs. + """ + if isinstance(store, path_type): + store = str(store) + if encoding is None: + encoding = {} + + # validate Dataset keys, DataArray names, and attr keys/values + _validate_dataset_names(dataset) + _validate_attrs(dataset) + + store = backends.ZarrStore.open_group(store=store, mode=mode, + synchronizer=synchronizer, + group=group, writer=None) + + # I think zarr stores should always be sync'd immediately + # TODO: figure out how to properly handle unlimited_dims + dataset.dump_to_store(store, sync=True, encoding=encoding) + return store diff --git a/xarray/backends/common.py b/xarray/backends/common.py index d33bffb..83753ce 100644 --- a/xarray/backends/common.py +++ b/xarray/backends/common.py @@ -7,7 +7,7 @@ import traceback import contextlib from collections import Mapping -from distutils.version import LooseVersion +import warnings from ..conventions import cf_encoder from ..core import indexing @@ -133,24 +133,25 @@ def load(self): @property def variables(self): - # Because encoding/decoding might happen which may require both the - # attributes and the variables, and because a store may be updated - # we need to load both the attributes and variables - # anytime either one is requested. + warnings.warn('The ``variables`` property has been deprecated and ' + 'will be removed in xarray v0.11.', + FutureWarning, stacklevel=2) variables, _ = self.load() return variables @property def attrs(self): - # Because encoding/decoding might happen which may require both the - # attributes and the variables, and because a store may be updated - # we need to load both the attributes and variables - # anytime either one is requested. - _, attributes = self.load() - return attributes + warnings.warn('The ``attrs`` property has been deprecated and ' + 'will be removed in xarray v0.11.', + FutureWarning, stacklevel=2) + _, attrs = self.load() + return attrs @property def dimensions(self): + warnings.warn('The ``dimensions`` property has been deprecated and ' + 'will be removed in xarray v0.11.', + FutureWarning, stacklevel=2) return self.get_dimensions() def close(self): @@ -164,9 +165,10 @@ def __exit__(self, exception_type, exception_value, traceback): class ArrayWriter(object): - def __init__(self): + def __init__(self, lock=GLOBAL_LOCK): self.sources = [] self.targets = [] + self.lock = lock def add(self, source, target): if isinstance(source, dask_array_type): @@ -182,11 +184,7 @@ def add(self, source, target): def sync(self): if self.sources: import dask.array as da - import dask - if LooseVersion(dask.__version__) > LooseVersion('0.8.1'): - da.store(self.sources, self.targets, lock=GLOBAL_LOCK) - else: - da.store(self.sources, self.targets) + da.store(self.sources, self.targets, lock=self.lock) self.sources = [] self.targets = [] @@ -231,19 +229,17 @@ def set_variables(self, variables, check_encoding_set, for vn, v in iteritems(variables): name = _encode_variable_name(vn) check = vn in check_encoding_set - if vn not in self.variables: - target, source = self.prepare_variable( - name, v, check, unlimited_dims=unlimited_dims) - else: - target, source = self.ds.variables[name], v.data + target, source = self.prepare_variable( + name, v, check, unlimited_dims=unlimited_dims) self.writer.add(source, target) def set_necessary_dimensions(self, variable, unlimited_dims=None): if unlimited_dims is None: unlimited_dims = set() + dims = self.get_dimensions() for d, l in zip(variable.dims, variable.shape): - if d not in self.dimensions: + if d not in dims: is_unlimited = d in unlimited_dims self.set_dimension(d, l, is_unlimited) diff --git a/xarray/backends/h5netcdf_.py b/xarray/backends/h5netcdf_.py index b4d2dc7..1cd7b65 100644 --- a/xarray/backends/h5netcdf_.py +++ b/xarray/backends/h5netcdf_.py @@ -55,6 +55,7 @@ def _open_h5netcdf_group(filename, mode, group): class H5NetCDFStore(WritableCFDataStore, DataStorePickleMixin): """Store for reading and writing data via h5netcdf """ + def __init__(self, filename, mode='r', format=None, group=None, writer=None, autoclose=False): if format not in [None, 'NETCDF4']: @@ -156,8 +157,11 @@ def prepare_variable(self, name, variable, check_encoding=False, 'chunksizes', 'fletcher32']: if key in encoding: kwargs[key] = encoding[key] - nc4_var = self.ds.createVariable(name, dtype, variable.dims, - fill_value=fill_value, **kwargs) + if name not in self.ds.variables: + nc4_var = self.ds.createVariable(name, dtype, variable.dims, + fill_value=fill_value, **kwargs) + else: + nc4_var = self.ds.variables[name] for k, v in iteritems(attrs): nc4_var.setncattr(k, v) diff --git a/xarray/backends/memory.py b/xarray/backends/memory.py index f79e924..4cecf1e 100644 --- a/xarray/backends/memory.py +++ b/xarray/backends/memory.py @@ -18,6 +18,7 @@ class InMemoryDataStore(AbstractWritableDataStore): This store exists purely for internal testing purposes. """ + def __init__(self, variables=None, attributes=None, writer=None): self._variables = OrderedDict() if variables is None else variables self._attributes = OrderedDict() if attributes is None else attributes diff --git a/xarray/backends/netCDF4_.py b/xarray/backends/netCDF4_.py index 59e195b..a22416a 100644 --- a/xarray/backends/netCDF4_.py +++ b/xarray/backends/netCDF4_.py @@ -3,6 +3,8 @@ from __future__ import print_function import functools import operator +import warnings +from distutils.version import LooseVersion import numpy as np @@ -218,6 +220,7 @@ class NetCDF4DataStore(WritableCFDataStore, DataStorePickleMixin): This store supports NetCDF3, NetCDF4 and OpenDAP datasets. """ + def __init__(self, netcdf4_dataset, mode='r', writer=None, opener=None, autoclose=False): @@ -243,6 +246,17 @@ def __init__(self, netcdf4_dataset, mode='r', writer=None, opener=None, def open(cls, filename, mode='r', format='NETCDF4', group=None, writer=None, clobber=True, diskless=False, persist=False, autoclose=False): + import netCDF4 as nc4 + if (len(filename) == 88 and + LooseVersion(nc4.__version__) < "1.3.1"): + warnings.warn( + '\nA segmentation fault may occur when the\n' + 'file path has exactly 88 characters as it does.\n' + 'in this case. The issue is known to occur with\n' + 'version 1.2.4 of netCDF4 and can be addressed by\n' + 'upgrading netCDF4 to at least version 1.3.1.\n' + 'More details can be found here:\n' + 'https://github.com/pydata/xarray/issues/1745 \n') if format is None: format = 'NETCDF4' opener = functools.partial(_open_netcdf4_group, filename, mode=mode, @@ -352,20 +366,24 @@ def prepare_variable(self, name, variable, check_encoding=False, encoding = _extract_nc4_variable_encoding( variable, raise_on_invalid=check_encoding, unlimited_dims=unlimited_dims) - nc4_var = self.ds.createVariable( - varname=name, - datatype=datatype, - dimensions=variable.dims, - zlib=encoding.get('zlib', False), - complevel=encoding.get('complevel', 4), - shuffle=encoding.get('shuffle', True), - fletcher32=encoding.get('fletcher32', False), - contiguous=encoding.get('contiguous', False), - chunksizes=encoding.get('chunksizes'), - endian='native', - least_significant_digit=encoding.get('least_significant_digit'), - fill_value=fill_value) - _disable_auto_decode_variable(nc4_var) + if name in self.ds.variables: + nc4_var = self.ds.variables[name] + else: + nc4_var = self.ds.createVariable( + varname=name, + datatype=datatype, + dimensions=variable.dims, + zlib=encoding.get('zlib', False), + complevel=encoding.get('complevel', 4), + shuffle=encoding.get('shuffle', True), + fletcher32=encoding.get('fletcher32', False), + contiguous=encoding.get('contiguous', False), + chunksizes=encoding.get('chunksizes'), + endian='native', + least_significant_digit=encoding.get( + 'least_significant_digit'), + fill_value=fill_value) + _disable_auto_decode_variable(nc4_var) for k, v in iteritems(attrs): # set attributes one-by-one since netCDF4<1.0.10 can't handle diff --git a/xarray/backends/netcdf3.py b/xarray/backends/netcdf3.py index 7194e06..7aa054b 100644 --- a/xarray/backends/netcdf3.py +++ b/xarray/backends/netcdf3.py @@ -6,7 +6,6 @@ import numpy as np from .. import conventions, Variable -from ..core import duck_array_ops from ..core.pycompat import basestring, unicode_type, OrderedDict diff --git a/xarray/backends/pydap_.py b/xarray/backends/pydap_.py index 044dcc2..297d96e 100644 --- a/xarray/backends/pydap_.py +++ b/xarray/backends/pydap_.py @@ -4,7 +4,7 @@ import numpy as np from .. import Variable -from ..core.utils import FrozenOrderedDict, Frozen +from ..core.utils import FrozenOrderedDict, Frozen, is_dict_like from ..core import indexing from ..core.pycompat import integer_types @@ -15,16 +15,13 @@ class PydapArrayWrapper(BackendArray): def __init__(self, array): self.array = array + @property + def shape(self): + return self.array.shape + @property def dtype(self): - t = self.array.type - if t.size is None and t.typecode == 'S': - # return object dtype because that's the only way in numpy to - # represent variable length strings; it also prevents automatic - # string concatenation via conventions.decode_cf_variable - return np.dtype('O') - else: - return np.dtype(t.typecode + str(t.size)) + return self.array.dtype def __getitem__(self, key): key = indexing.unwrap_explicit_indexer( @@ -37,17 +34,23 @@ def __getitem__(self, key): # pydap doesn't squeeze axes automatically like numpy axis = tuple(n for n, k in enumerate(key) if isinstance(k, integer_types)) - result = np.squeeze(result, axis) + if len(axis) > 0: + result = np.squeeze(result, axis) return result -def _fix_global_attributes(attributes): +def _fix_attributes(attributes): attributes = dict(attributes) for k in list(attributes): if k.lower() == 'global' or k.lower().endswith('_global'): # move global attributes to the top level, like the netcdf-C # DAP client attributes.update(attributes.pop(k)) + elif is_dict_like(attributes[k]): + # Make Hierarchical attributes to a single level with a + # dot-separated key + attributes.update({'{}.{}'.format(k, k_child): v_child for + k_child, v_child in attributes.pop(k).items()}) return attributes @@ -57,6 +60,7 @@ class PydapDataStore(AbstractDataStore): This store provides an alternative way to access OpenDAP datasets that may be useful if the netCDF4 library is not available. """ + def __init__(self, ds): """ Parameters @@ -73,14 +77,15 @@ def open(cls, url, session=None): def open_store_variable(self, var): data = indexing.LazilyIndexedArray(PydapArrayWrapper(var)) - return Variable(var.dimensions, data, var.attributes) + return Variable(var.dimensions, data, + _fix_attributes(var.attributes)) def get_variables(self): return FrozenOrderedDict((k, self.open_store_variable(self.ds[k])) for k in self.ds.keys()) def get_attrs(self): - return Frozen(_fix_global_attributes(self.ds.attributes)) + return Frozen(_fix_attributes(self.ds.attributes)) def get_dimensions(self): return Frozen(self.ds.dimensions) diff --git a/xarray/backends/pynio_.py b/xarray/backends/pynio_.py index ffa936c..37f1db1 100644 --- a/xarray/backends/pynio_.py +++ b/xarray/backends/pynio_.py @@ -40,6 +40,7 @@ def __getitem__(self, key): class NioDataStore(AbstractDataStore, DataStorePickleMixin): """Store for accessing datasets via PyNIO """ + def __init__(self, filename, mode='r', autoclose=False): import Nio opener = functools.partial(Nio.open_file, filename, mode=mode) diff --git a/xarray/backends/rasterio_.py b/xarray/backends/rasterio_.py index 13f9c0a..d94bf01 100644 --- a/xarray/backends/rasterio_.py +++ b/xarray/backends/rasterio_.py @@ -20,6 +20,7 @@ class RasterioArrayWrapper(BackendArray): """A wrapper around rasterio dataset objects""" + def __init__(self, rasterio_ds): self.rasterio_ds = rasterio_ds self._shape = (rasterio_ds.count, rasterio_ds.height, @@ -63,9 +64,9 @@ def __getitem__(self, key): elif is_scalar(k): # windowed operations will always return an array # we will have to squeeze it later - squeeze_axis.append(i+1) + squeeze_axis.append(i + 1) start = k - stop = k+1 + stop = k + 1 else: k = np.asarray(k) start = k[0] @@ -81,6 +82,37 @@ def __getitem__(self, key): return out +def _parse_envi(meta): + """Parse ENVI metadata into Python data structures. + + See the link for information on the ENVI header file format: + http://www.harrisgeospatial.com/docs/enviheaderfiles.html + + Parameters + ---------- + meta : dict + Dictionary of keys and str values to parse, as returned by the rasterio + tags(ns='ENVI') call. + + Returns + ------- + parsed_meta : dict + Dictionary containing the original keys and the parsed values + + """ + + def parsevec(s): + return np.fromstring(s.strip('{}'), dtype='float', sep=',') + + def default(s): + return s.strip('{}') + + parse = {'wavelength': parsevec, + 'fwhm': parsevec} + parsed_meta = {k: parse.get(k, default)(v) for k, v in meta.items()} + return parsed_meta + + def open_rasterio(filename, chunks=None, cache=None, lock=None): """Open a file with rasterio (experimental). @@ -134,10 +166,10 @@ def open_rasterio(filename, chunks=None, cache=None, lock=None): dx, dy = riods.res[0], -riods.res[1] x0 = riods.bounds.right if dx < 0 else riods.bounds.left y0 = riods.bounds.top if dy < 0 else riods.bounds.bottom - coords['y'] = np.linspace(start=y0 + dy/2, num=ny, - stop=(y0 + (ny - 1) * dy) + dy/2) - coords['x'] = np.linspace(start=x0 + dx/2, num=nx, - stop=(x0 + (nx - 1) * dx) + dx/2) + coords['y'] = np.linspace(start=y0 + dy / 2, num=ny, + stop=(y0 + (ny - 1) * dy) + dy / 2) + coords['x'] = np.linspace(start=x0 + dx / 2, num=nx, + stop=(x0 + (nx - 1) * dx) + dx / 2) # Attributes attrs = {} @@ -157,6 +189,25 @@ def open_rasterio(filename, chunks=None, cache=None, lock=None): # Affine transformation matrix (tuple of floats) # Describes coefficients mapping pixel coordinates to CRS attrs['transform'] = tuple(riods.transform) + if hasattr(riods, 'nodatavals'): + # The nodata values for the raster bands + attrs['nodatavals'] = tuple([np.nan if nodataval is None else nodataval + for nodataval in riods.nodatavals]) + + # Parse extra metadata from tags, if supported + parsers = {'ENVI': _parse_envi} + + driver = riods.driver + if driver in parsers: + meta = parsers[driver](riods.tags(ns=driver)) + + for k, v in meta.items(): + # Add values as coordinates if they match the band count, + # as attributes otherwise + if isinstance(v, (list, np.ndarray)) and len(v) == riods.count: + coords[k] = ('band', np.asarray(v)) + else: + attrs[k] = v data = indexing.LazilyIndexedArray(RasterioArrayWrapper(riods)) diff --git a/xarray/backends/scipy_.py b/xarray/backends/scipy_.py index 240b8f2..0994d85 100644 --- a/xarray/backends/scipy_.py +++ b/xarray/backends/scipy_.py @@ -165,7 +165,7 @@ def get_encoding(self): def set_dimension(self, name, length, is_unlimited=False): with self.ensure_open(autoclose=False): - if name in self.dimensions: + if name in self.ds.dimensions: raise ValueError('%s does not support modifying dimensions' % type(self).__name__) dim_length = length if not is_unlimited else None @@ -196,7 +196,8 @@ def prepare_variable(self, name, variable, check_encoding=False, # nb. this still creates a numpy array in all memory, even though we # don't write the data yet; scipy.io.netcdf does not not support # incremental writes. - self.ds.createVariable(name, data.dtype, variable.dims) + if name not in self.ds.variables: + self.ds.createVariable(name, data.dtype, variable.dims) scipy_var = self.ds.variables[name] for k, v in iteritems(variable.attrs): self._validate_attr_key(k) diff --git a/xarray/backends/zarr.py b/xarray/backends/zarr.py new file mode 100644 index 0000000..5305121 --- /dev/null +++ b/xarray/backends/zarr.py @@ -0,0 +1,546 @@ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +from itertools import product +from base64 import b64encode + +import numpy as np + +from .. import coding +from .. import Variable +from ..core import indexing +from ..core.utils import FrozenOrderedDict, HiddenKeyDict +from ..core.pycompat import iteritems, OrderedDict, integer_types +from .common import AbstractWritableDataStore, BackendArray, ArrayWriter +from .. import conventions + +# need some special secret attributes to tell us the dimensions +_DIMENSION_KEY = '_ARRAY_DIMENSIONS' + + +# zarr attributes have to be serializable as json +# many xarray datasets / variables have numpy arrays and values +# these functions handle encoding / decoding of such items +def _encode_zarr_attr_value(value): + if isinstance(value, np.ndarray): + encoded = value.tolist() + # this checks if it's a scalar number + elif isinstance(value, np.generic): + encoded = value.item() + # np.string_('X').item() returns a type `bytes` + # zarr still doesn't like that + if type(encoded) is bytes: + encoded = b64encode(encoded) + else: + encoded = value + return encoded + + +def _ensure_valid_fill_value(value, dtype): + if dtype.type == np.string_ and type(value) == bytes: + valid = b64encode(value) + else: + valid = value + return _encode_zarr_attr_value(valid) + + +def _decode_zarr_attr_value(value): + return value + + +def _decode_zarr_attrs(attrs): + return OrderedDict([(k, _decode_zarr_attr_value(v)) + for k, v in attrs.items()]) + + +def _replace_slices_with_arrays(key, shape): + """Replace slice objects in vindex with equivalent ndarray objects.""" + num_slices = sum(1 for k in key if isinstance(k, slice)) + ndims = [k.ndim for k in key if isinstance(k, np.ndarray)] + array_subspace_size = max(ndims) if ndims else 0 + assert len(key) == len(shape) + new_key = [] + slice_count = 0 + for k, size in zip(key, shape): + if isinstance(k, slice): + # the slice subspace always appears after the ndarray subspace + array = np.arange(*k.indices(size)) + sl = [np.newaxis] * len(shape) + sl[array_subspace_size + slice_count] = slice(None) + k = array[tuple(sl)] + slice_count += 1 + else: + assert isinstance(k, np.ndarray) + k = k[(slice(None),) * array_subspace_size + + (np.newaxis,) * num_slices] + new_key.append(k) + return tuple(new_key) + + +class ZarrArrayWrapper(BackendArray): + def __init__(self, variable_name, datastore): + self.datastore = datastore + self.variable_name = variable_name + + array = self.get_array() + self.shape = array.shape + + dtype = array.dtype + self.dtype = dtype + + def get_array(self): + return self.datastore.ds[self.variable_name] + + def __getitem__(self, key): + array = self.get_array() + if isinstance(key, indexing.BasicIndexer): + return array[key.tuple] + elif isinstance(key, indexing.VectorizedIndexer): + return array.vindex[_replace_slices_with_arrays(key.tuple, + self.shape)] + else: + assert isinstance(key, indexing.OuterIndexer) + return array.oindex[key.tuple] + # if self.ndim == 0: + # could possibly have a work-around for 0d data here + + +def _determine_zarr_chunks(enc_chunks, var_chunks, ndim): + """ + Given encoding chunks (possibly None) and variable chunks (possibly None) + """ + + # zarr chunk spec: + # chunks : int or tuple of ints, optional + # Chunk shape. If not provided, will be guessed from shape and dtype. + + # if there are no chunks in encoding and the variable data is a numpy + # array, then we let zarr use its own heuristics to pick the chunks + if var_chunks is None and enc_chunks is None: + return None + + # if there are no chunks in encoding but there are dask chunks, we try to + # use the same chunks in zarr + # However, zarr chunks needs to be uniform for each array + # http://zarr.readthedocs.io/en/latest/spec/v1.html#chunks + # while dask chunks can be variable sized + # http://dask.pydata.org/en/latest/array-design.html#chunks + if var_chunks and enc_chunks is None: + all_var_chunks = list(product(*var_chunks)) + first_var_chunk = all_var_chunks[0] + # all but the last chunk have to match exactly + for this_chunk in all_var_chunks[:-1]: + if this_chunk != first_var_chunk: + raise ValueError( + "Zarr requires uniform chunk sizes excpet for final chunk." + " Variable %r has incompatible chunks. Consider " + "rechunking using `chunk()`." % (var_chunks,)) + # last chunk is allowed to be smaller + last_var_chunk = all_var_chunks[-1] + for len_first, len_last in zip(first_var_chunk, last_var_chunk): + if len_last > len_first: + raise ValueError( + "Final chunk of Zarr array must be smaller than first. " + "Variable %r has incompatible chunks. Consider rechunking " + "using `chunk()`." % var_chunks) + return first_var_chunk + + # from here on, we are dealing with user-specified chunks in encoding + # zarr allows chunks to be an integer, in which case it uses the same chunk + # size on each dimension. + # Here we re-implement this expansion ourselves. That makes the logic of + # checking chunk compatibility easier + + if isinstance(enc_chunks, integer_types): + enc_chunks_tuple = ndim * (enc_chunks,) + else: + enc_chunks_tuple = tuple(enc_chunks) + + if len(enc_chunks_tuple) != ndim: + raise ValueError("zarr chunks tuple %r must have same length as " + "variable.ndim %g" % + (enc_chunks_tuple, ndim)) + + for x in enc_chunks_tuple: + if not isinstance(x, int): + raise TypeError("zarr chunks must be an int or a tuple of ints. " + "Instead found %r" % (enc_chunks_tuple,)) + + # if there are chunks in encoding and the variable data is a numpy array, + # we use the specified chunks + if var_chunks is None: + return enc_chunks_tuple + + # the hard case + # DESIGN CHOICE: do not allow multiple dask chunks on a single zarr chunk + # this avoids the need to get involved in zarr synchronization / locking + # From zarr docs: + # "If each worker in a parallel computation is writing to a separate + # region of the array, and if region boundaries are perfectly aligned + # with chunk boundaries, then no synchronization is required." + # TODO: incorporate synchronizer to allow writes from multiple dask + # threads + if var_chunks and enc_chunks_tuple: + for zchunk, dchunks in zip(enc_chunks_tuple, var_chunks): + for dchunk in dchunks: + if dchunk % zchunk: + raise NotImplementedError( + "Specified zarr chunks %r would overlap multiple dask " + "chunks %r. This is not implemented in xarray yet. " + " Consider rechunking the data using " + "`chunk()` or specifying different chunks in encoding." + % (enc_chunks_tuple, var_chunks)) + return enc_chunks_tuple + + raise AssertionError( + "We should never get here. Function logic must be wrong.") + + +def _get_zarr_dims_and_attrs(zarr_obj, dimension_key): + # Zarr arrays do not have dimenions. To get around this problem, we add + # an attribute that specifies the dimension. We have to hide this attribute + # when we send the attributes to the user. + # zarr_obj can be either a zarr group or zarr array + try: + dimensions = zarr_obj.attrs[dimension_key] + except KeyError: + raise KeyError("Zarr object is missing the attribute `%s`, which is " + "required for xarray to determine variable dimensions." + % (dimension_key)) + attributes = HiddenKeyDict(zarr_obj.attrs, [dimension_key]) + return dimensions, attributes + + +def _extract_zarr_variable_encoding(variable, raise_on_invalid=False): + encoding = variable.encoding.copy() + + valid_encodings = set(['chunks', 'compressor', 'filters', + 'cache_metadata']) + + if raise_on_invalid: + invalid = [k for k in encoding if k not in valid_encodings] + if invalid: + raise ValueError('unexpected encoding parameters for zarr ' + 'backend: %r' % invalid) + else: + for k in list(encoding): + if k not in valid_encodings: + del encoding[k] + + chunks = _determine_zarr_chunks(encoding.get('chunks'), variable.chunks, + variable.ndim) + encoding['chunks'] = chunks + return encoding + + +# Function below is copied from conventions.encode_cf_variable. +# The only change is to raise an error for object dtypes. +def encode_zarr_variable(var, needs_copy=True, name=None): + """ + Converts an Variable into an Variable which follows some + of the CF conventions: + + - Nans are masked using _FillValue (or the deprecated missing_value) + - Rescaling via: scale_factor and add_offset + - datetimes are converted to the CF 'units since time' format + - dtype encodings are enforced. + + Parameters + ---------- + var : xarray.Variable + A variable holding un-encoded data. + + Returns + ------- + out : xarray.Variable + A variable which has been encoded as described above. + """ + + if var.dtype.kind == 'O': + raise NotImplementedError("Variable `%s` is an object. Zarr " + "store can't yet encode objects." % name) + + for coder in [coding.times.CFDatetimeCoder(), + coding.times.CFTimedeltaCoder(), + coding.variables.CFScaleOffsetCoder(), + coding.variables.CFMaskCoder(), + coding.variables.UnsignedIntegerCoder()]: + var = coder.encode(var, name=name) + + var = conventions.maybe_encode_nonstring_dtype(var, name=name) + var = conventions.maybe_default_fill_value(var) + var = conventions.maybe_encode_bools(var) + var = conventions.ensure_dtype_not_object(var, name=name) + var = conventions.maybe_encode_string_dtype(var, name=name) + return var + + +class ZarrStore(AbstractWritableDataStore): + """Store for reading and writing data via zarr + """ + + @classmethod + def open_group(cls, store, mode='r', synchronizer=None, group=None, + writer=None): + import zarr + zarr_group = zarr.open_group(store=store, mode=mode, + synchronizer=synchronizer, path=group) + return cls(zarr_group, writer=writer) + + def __init__(self, zarr_group, writer=None): + self.ds = zarr_group + self._read_only = self.ds.read_only + self._synchronizer = self.ds.synchronizer + self._group = self.ds.path + + if _DIMENSION_KEY not in self.ds.attrs: + if self._read_only: + raise KeyError("Zarr group can't be read by xarray because " + "it is missing the `%s` attribute." % + _DIMENSION_KEY) + else: + # initialize hidden dimension attribute + self.ds.attrs[_DIMENSION_KEY] = {} + + if writer is None: + # by default, we should not need a lock for writing zarr because + # we do not (yet) allow overlapping chunks during write + zarr_writer = ArrayWriter(lock=False) + else: + zarr_writer = writer + + # do we need to define attributes for all of the opener keyword args? + super(ZarrStore, self).__init__(zarr_writer) + + def open_store_variable(self, name, zarr_array): + data = indexing.LazilyIndexedArray(ZarrArrayWrapper(name, self)) + dimensions, attributes = _get_zarr_dims_and_attrs(zarr_array, + _DIMENSION_KEY) + attributes = _decode_zarr_attrs(attributes) + encoding = {'chunks': zarr_array.chunks, + 'compressor': zarr_array.compressor, + 'filters': zarr_array.filters} + # _FillValue needs to be in attributes, not encoding, so it will get + # picked up by decode_cf + if getattr(zarr_array, 'fill_value') is not None: + attributes['_FillValue'] = zarr_array.fill_value + + return Variable(dimensions, data, attributes, encoding) + + def get_variables(self): + return FrozenOrderedDict((k, self.open_store_variable(k, v)) + for k, v in self.ds.arrays()) + + def get_attrs(self): + _, attributes = _get_zarr_dims_and_attrs(self.ds, _DIMENSION_KEY) + return _decode_zarr_attrs(attributes) + + def get_dimensions(self): + dimensions, _ = _get_zarr_dims_and_attrs(self.ds, _DIMENSION_KEY) + return dimensions + + def set_dimension(self, name, length, is_unlimited=False): + if is_unlimited: + raise NotImplementedError( + "Zarr backend doesn't know how to handle unlimited dimensions") + # consistency check + if name in self.ds.attrs[_DIMENSION_KEY]: + if self.ds.attrs[_DIMENSION_KEY][name] != length: + raise ValueError("Pre-existing array dimensions %r " + "encoded in Zarr attributes are incompatible " + "with newly specified dimension `%s`: %g" % + (self.ds.attrs[_DIMENSION_KEY], name, length)) + self.ds.attrs[_DIMENSION_KEY][name] = length + + def set_attribute(self, key, value): + _, attributes = _get_zarr_dims_and_attrs(self.ds, _DIMENSION_KEY) + attributes[key] = _encode_zarr_attr_value(value) + + def prepare_variable(self, name, variable, check_encoding=False, + unlimited_dims=None): + + attrs = variable.attrs.copy() + dims = variable.dims + dtype = variable.dtype + shape = variable.shape + + # TODO: figure out how zarr should deal with unlimited dimensions + self.set_necessary_dimensions(variable, unlimited_dims=unlimited_dims) + + fill_value = _ensure_valid_fill_value(attrs.pop('_FillValue', None), + dtype) + + # TODO: figure out what encoding is needed for zarr + encoding = _extract_zarr_variable_encoding( + variable, raise_on_invalid=check_encoding) + + # arguments for zarr.create: + # zarr.creation.create(shape, chunks=None, dtype=None, + # compressor='default', fill_value=0, order='C', store=None, + # synchronizer=None, overwrite=False, path=None, chunk_store=None, + # filters=None, cache_metadata=True, **kwargs) + if name in self.ds: + zarr_array = self.ds[name] + else: + zarr_array = self.ds.create(name, shape=shape, dtype=dtype, + fill_value=fill_value, **encoding) + # decided not to explicity enumerate encoding options because we + # risk overriding zarr's defaults (e.g. if we specificy + # cache_metadata=None instead of True). Alternative is to have lots of + # logic in _extract_zarr_variable encoding to duplicate zarr defaults. + # chunks=encoding.get('chunks'), + # compressor=encoding.get('compressor'), + # filters=encodings.get('filters'), + # cache_metadata=encoding.get('cache_metadata')) + + # the magic for storing the hidden dimension data + zarr_array.attrs[_DIMENSION_KEY] = dims + _, attributes = _get_zarr_dims_and_attrs(zarr_array, _DIMENSION_KEY) + + for k, v in iteritems(attrs): + attributes[k] = _encode_zarr_attr_value(v) + + return zarr_array, variable.data + + def store(self, variables, attributes, *args, **kwargs): + new_vars = OrderedDict((k, encode_zarr_variable(v, name=k)) + for k, v in iteritems(variables)) + AbstractWritableDataStore.store(self, new_vars, attributes, + *args, **kwargs) + # sync() and close() methods should not be needed with zarr + + +# from zarr docs + +# Zarr arrays can be used as either the source or sink for data in parallel +# computations. Both multi-threaded and multi-process parallelism are +# supported. The Python global interpreter lock (GIL) is released for both +# compression and decompression operations, so Zarr will not block other Python +# threads from running. +# +# A Zarr array can be read concurrently by multiple threads or processes. No +# synchronization (i.e., locking) is required for concurrent reads. +# +# A Zarr array can also be written to concurrently by multiple threads or +# processes. Some synchronization may be required, depending on the way the +# data is being written. + +# If each worker in a parallel computation is writing to a separate region of +# the array, and if region boundaries are perfectly aligned with chunk +# boundaries, then no synchronization is required. However, if region and chunk +# boundaries are not perfectly aligned, then synchronization is required to +# avoid two workers attempting to modify the same chunk at the same time. + + +def open_zarr(store, group=None, synchronizer=None, auto_chunk=True, + decode_cf=True, mask_and_scale=True, decode_times=True, + concat_characters=True, decode_coords=True, + drop_variables=None): + """Load and decode a dataset from a Zarr store. + + .. note:: Experimental + The Zarr backend is new and experimental. Please report any + unexpected behavior via github issues. + + The `store` object should be a valid store for a Zarr group. `store` + variables must contain dimension metadata encoded in the + `_ARRAY_DIMENSIONS` attribute. + + Parameters + ---------- + store : MutableMapping or str + A MutableMapping where a Zarr Group has been stored or a path to a + directory in file system where a Zarr DirectoryStore has been stored. + synchronizer : object, optional + Array synchronizer provided to zarr + group : str, obtional + Group path. (a.k.a. `path` in zarr terminology.) + auto_chunk : bool, optional + Whether to automatically create dask chunks corresponding to each + variable's zarr chunks. If False, zarr array data will lazily convert + to numpy arrays upon access. + decode_cf : bool, optional + Whether to decode these variables, assuming they were saved according + to CF conventions. + mask_and_scale : bool, optional + If True, replace array values equal to `_FillValue` with NA and scale + values according to the formula `original_values * scale_factor + + add_offset`, where `_FillValue`, `scale_factor` and `add_offset` are + taken from variable attributes (if they exist). If the `_FillValue` or + `missing_value` attribute contains multiple values a warning will be + issued and all array values matching one of the multiple values will + be replaced by NA. + decode_times : bool, optional + If True, decode times encoded in the standard NetCDF datetime format + into datetime objects. Otherwise, leave them encoded as numbers. + concat_characters : bool, optional + If True, concatenate along the last dimension of character arrays to + form string arrays. Dimensions will only be concatenated over (and + removed) if they have no corresponding variable and if they are only + used as the last dimension of character arrays. + decode_coords : bool, optional + If True, decode the 'coordinates' attribute to identify coordinates in + the resulting dataset. + drop_variables: string or iterable, optional + A variable or list of variables to exclude from being parsed from the + dataset. This may be useful to drop variables with problems or + inconsistent values. + + Returns + ------- + dataset : Dataset + The newly created dataset. + + See Also + -------- + open_dataset + + References + ---------- + http://zarr.readthedocs.io/ + """ + + if not decode_cf: + mask_and_scale = False + decode_times = False + concat_characters = False + decode_coords = False + + def maybe_decode_store(store, lock=False): + ds = conventions.decode_cf( + store, mask_and_scale=mask_and_scale, decode_times=decode_times, + concat_characters=concat_characters, decode_coords=decode_coords, + drop_variables=drop_variables) + + # TODO: this is where we would apply caching + + return ds + + # Zarr supports a wide range of access modes, but for now xarray either + # reads or writes from a store, never both. For open_zarr, we only read + mode = 'r' + zarr_store = ZarrStore.open_group(store, mode=mode, + synchronizer=synchronizer, + group=group) + ds = maybe_decode_store(zarr_store) + + # auto chunking needs to be here and not in ZarrStore because variable + # chunks do not survive decode_cf + if auto_chunk: + # adapted from Dataset.Chunk() + def maybe_chunk(name, var): + from dask.base import tokenize + chunks = var.encoding.get('chunks') + if (var.ndim > 0) and (chunks is not None): + # does this cause any data to be read? + token2 = tokenize(name, var._data) + name2 = 'zarr-%s-%s' % (name, token2) + return var.chunk(chunks, name=name2, lock=None) + else: + return var + + variables = OrderedDict([(k, maybe_chunk(k, v)) + for k, v in ds.variables.items()]) + return ds._replace_vars_and_dims(variables) + else: + return ds diff --git a/xarray/coding/__init__.py b/xarray/coding/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/xarray/coding/times.py b/xarray/coding/times.py new file mode 100644 index 0000000..e00769a --- /dev/null +++ b/xarray/coding/times.py @@ -0,0 +1,363 @@ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import re +import traceback +import warnings +from datetime import datetime +from functools import partial + +import numpy as np + +import pandas as pd +try: + from pandas.errors import OutOfBoundsDatetime +except ImportError: + # pandas < 0.20 + from pandas.tslib import OutOfBoundsDatetime + +from .variables import (SerializationWarning, VariableCoder, + lazy_elemwise_func, pop_to, safe_setitem, + unpack_for_decoding, unpack_for_encoding) +from ..core import indexing +from ..core.formatting import first_n_items, format_timestamp, last_item +from ..core.pycompat import PY3 +from ..core.variable import Variable + + +# standard calendars recognized by netcdftime +_STANDARD_CALENDARS = set(['standard', 'gregorian', 'proleptic_gregorian']) + +_NS_PER_TIME_DELTA = {'us': int(1e3), + 'ms': int(1e6), + 's': int(1e9), + 'm': int(1e9) * 60, + 'h': int(1e9) * 60 * 60, + 'D': int(1e9) * 60 * 60 * 24} + +TIME_UNITS = frozenset(['days', 'hours', 'minutes', 'seconds', + 'milliseconds', 'microseconds']) + + +def _netcdf_to_numpy_timeunit(units): + units = units.lower() + if not units.endswith('s'): + units = '%ss' % units + return {'microseconds': 'us', 'milliseconds': 'ms', 'seconds': 's', + 'minutes': 'm', 'hours': 'h', 'days': 'D'}[units] + + +def _unpack_netcdf_time_units(units): + # CF datetime units follow the format: "UNIT since DATE" + # this parses out the unit and date allowing for extraneous + # whitespace. + matches = re.match('(.+) since (.+)', units) + if not matches: + raise ValueError('invalid time units: %s' % units) + delta_units, ref_date = [s.strip() for s in matches.groups()] + return delta_units, ref_date + + +def _decode_datetime_with_netcdf4(num_dates, units, calendar): + import netCDF4 as nc4 + + dates = np.asarray(nc4.num2date(num_dates, units, calendar)) + if (dates[np.nanargmin(num_dates)].year < 1678 or + dates[np.nanargmax(num_dates)].year >= 2262): + warnings.warn('Unable to decode time axis into full ' + 'numpy.datetime64 objects, continuing using dummy ' + 'netCDF4.datetime objects instead, reason: dates out' + ' of range', SerializationWarning, stacklevel=3) + else: + try: + dates = nctime_to_nptime(dates) + except ValueError as e: + warnings.warn('Unable to decode time axis into full ' + 'numpy.datetime64 objects, continuing using ' + 'dummy netCDF4.datetime objects instead, reason:' + '{0}'.format(e), SerializationWarning, stacklevel=3) + return dates + + +def _decode_cf_datetime_dtype(data, units, calendar): + # Verify that at least the first and last date can be decoded + # successfully. Otherwise, tracebacks end up swallowed by + # Dataset.__repr__ when users try to view their lazily decoded array. + values = indexing.ImplicitToExplicitIndexingAdapter( + indexing.as_indexable(data)) + example_value = np.concatenate([first_n_items(values, 1) or [0], + last_item(values) or [0]]) + + try: + result = decode_cf_datetime(example_value, units, calendar) + except Exception: + calendar_msg = ('the default calendar' if calendar is None + else 'calendar %r' % calendar) + msg = ('unable to decode time units %r with %s. Try ' + 'opening your dataset with decode_times=False.' + % (units, calendar_msg)) + if not PY3: + msg += ' Full traceback:\n' + traceback.format_exc() + raise ValueError(msg) + else: + dtype = getattr(result, 'dtype', np.dtype('object')) + + return dtype + + +def decode_cf_datetime(num_dates, units, calendar=None): + """Given an array of numeric dates in netCDF format, convert it into a + numpy array of date time objects. + + For standard (Gregorian) calendars, this function uses vectorized + operations, which makes it much faster than netCDF4.num2date. In such a + case, the returned array will be of type np.datetime64. + + Note that time unit in `units` must not be smaller than microseconds and + not larger than days. + + See also + -------- + netCDF4.num2date + """ + num_dates = np.asarray(num_dates) + flat_num_dates = num_dates.ravel() + if calendar is None: + calendar = 'standard' + + delta, ref_date = _unpack_netcdf_time_units(units) + + try: + if calendar not in _STANDARD_CALENDARS: + raise OutOfBoundsDatetime + + delta = _netcdf_to_numpy_timeunit(delta) + try: + ref_date = pd.Timestamp(ref_date) + except ValueError: + # ValueError is raised by pd.Timestamp for non-ISO timestamp + # strings, in which case we fall back to using netCDF4 + raise OutOfBoundsDatetime + + # fixes: https://github.com/pydata/pandas/issues/14068 + # these lines check if the the lowest or the highest value in dates + # cause an OutOfBoundsDatetime (Overflow) error + pd.to_timedelta(flat_num_dates.min(), delta) + ref_date + pd.to_timedelta(flat_num_dates.max(), delta) + ref_date + + # Cast input dates to integers of nanoseconds because `pd.to_datetime` + # works much faster when dealing with integers + flat_num_dates_ns_int = (flat_num_dates * + _NS_PER_TIME_DELTA[delta]).astype(np.int64) + + dates = (pd.to_timedelta(flat_num_dates_ns_int, 'ns') + + ref_date).values + + except (OutOfBoundsDatetime, OverflowError): + dates = _decode_datetime_with_netcdf4(flat_num_dates.astype(np.float), + units, + calendar) + + return dates.reshape(num_dates.shape) + + +def decode_cf_timedelta(num_timedeltas, units): + """Given an array of numeric timedeltas in netCDF format, convert it into a + numpy timedelta64[ns] array. + """ + num_timedeltas = np.asarray(num_timedeltas) + units = _netcdf_to_numpy_timeunit(units) + + shape = num_timedeltas.shape + num_timedeltas = num_timedeltas.ravel() + + result = pd.to_timedelta(num_timedeltas, unit=units, box=False) + # NaT is returned unboxed with wrong units; this should be fixed in pandas + if result.dtype != 'timedelta64[ns]': + result = result.astype('timedelta64[ns]') + return result.reshape(shape) + + +def _infer_time_units_from_diff(unique_timedeltas): + for time_unit in ['days', 'hours', 'minutes', 'seconds']: + delta_ns = _NS_PER_TIME_DELTA[_netcdf_to_numpy_timeunit(time_unit)] + unit_delta = np.timedelta64(delta_ns, 'ns') + diffs = unique_timedeltas / unit_delta + if np.all(diffs == diffs.astype(int)): + return time_unit + return 'seconds' + + +def infer_datetime_units(dates): + """Given an array of datetimes, returns a CF compatible time-unit string of + the form "{time_unit} since {date[0]}", where `time_unit` is 'days', + 'hours', 'minutes' or 'seconds' (the first one that can evenly divide all + unique time deltas in `dates`) + """ + dates = pd.to_datetime(np.asarray(dates).ravel(), box=False) + dates = dates[pd.notnull(dates)] + unique_timedeltas = np.unique(np.diff(dates)) + units = _infer_time_units_from_diff(unique_timedeltas) + reference_date = dates[0] if len(dates) > 0 else '1970-01-01' + return '%s since %s' % (units, pd.Timestamp(reference_date)) + + +def infer_timedelta_units(deltas): + """Given an array of timedeltas, returns a CF compatible time-unit from + {'days', 'hours', 'minutes' 'seconds'} (the first one that can evenly + divide all unique time deltas in `deltas`) + """ + deltas = pd.to_timedelta(np.asarray(deltas).ravel(), box=False) + unique_timedeltas = np.unique(deltas[pd.notnull(deltas)]) + units = _infer_time_units_from_diff(unique_timedeltas) + return units + + +def nctime_to_nptime(times): + """Given an array of netCDF4.datetime objects, return an array of + numpy.datetime64 objects of the same size""" + times = np.asarray(times) + new = np.empty(times.shape, dtype='M8[ns]') + for i, t in np.ndenumerate(times): + dt = datetime(t.year, t.month, t.day, t.hour, t.minute, t.second) + new[i] = np.datetime64(dt) + return new + + +def _cleanup_netcdf_time_units(units): + delta, ref_date = _unpack_netcdf_time_units(units) + try: + units = '%s since %s' % (delta, format_timestamp(ref_date)) + except OutOfBoundsDatetime: + # don't worry about reifying the units if they're out of bounds + pass + return units + + +def _encode_datetime_with_netcdf4(dates, units, calendar): + """Fallback method for encoding dates using netCDF4-python. + + This method is more flexible than xarray's parsing using datetime64[ns] + arrays but also slower because it loops over each element. + """ + import netCDF4 as nc4 + + if np.issubdtype(dates.dtype, np.datetime64): + # numpy's broken datetime conversion only works for us precision + dates = dates.astype('M8[us]').astype(datetime) + + def encode_datetime(d): + return np.nan if d is None else nc4.date2num(d, units, calendar) + + return np.vectorize(encode_datetime)(dates) + + +def cast_to_int_if_safe(num): + int_num = np.array(num, dtype=np.int64) + if (num == int_num).all(): + num = int_num + return num + + +def encode_cf_datetime(dates, units=None, calendar=None): + """Given an array of datetime objects, returns the tuple `(num, units, + calendar)` suitable for a CF compliant time variable. + + Unlike `date2num`, this function can handle datetime64 arrays. + + See also + -------- + netCDF4.date2num + """ + dates = np.asarray(dates) + + if units is None: + units = infer_datetime_units(dates) + else: + units = _cleanup_netcdf_time_units(units) + + if calendar is None: + calendar = 'proleptic_gregorian' + + delta, ref_date = _unpack_netcdf_time_units(units) + try: + if calendar not in _STANDARD_CALENDARS or dates.dtype.kind == 'O': + # parse with netCDF4 instead + raise OutOfBoundsDatetime + assert dates.dtype == 'datetime64[ns]' + + delta_units = _netcdf_to_numpy_timeunit(delta) + time_delta = np.timedelta64(1, delta_units).astype('timedelta64[ns]') + ref_date = np.datetime64(pd.Timestamp(ref_date)) + num = (dates - ref_date) / time_delta + + except (OutOfBoundsDatetime, OverflowError): + num = _encode_datetime_with_netcdf4(dates, units, calendar) + + num = cast_to_int_if_safe(num) + return (num, units, calendar) + + +def encode_cf_timedelta(timedeltas, units=None): + if units is None: + units = infer_timedelta_units(timedeltas) + + np_unit = _netcdf_to_numpy_timeunit(units) + num = 1.0 * timedeltas / np.timedelta64(1, np_unit) + num = np.where(pd.isnull(timedeltas), np.nan, num) + num = cast_to_int_if_safe(num) + return (num, units) + + +class CFDatetimeCoder(VariableCoder): + + def encode(self, variable, name=None): + dims, data, attrs, encoding = unpack_for_encoding(variable) + + if np.issubdtype(data.dtype, np.datetime64): + (data, units, calendar) = encode_cf_datetime( + data, + encoding.pop('units', None), + encoding.pop('calendar', None)) + safe_setitem(attrs, 'units', units, name=name) + safe_setitem(attrs, 'calendar', calendar, name=name) + + return Variable(dims, data, attrs, encoding) + + def decode(self, variable, name=None): + dims, data, attrs, encoding = unpack_for_decoding(variable) + + if 'units' in attrs and 'since' in attrs['units']: + units = pop_to(attrs, encoding, 'units') + calendar = pop_to(attrs, encoding, 'calendar') + dtype = _decode_cf_datetime_dtype(data, units, calendar) + transform = partial( + decode_cf_datetime, units=units, calendar=calendar) + data = lazy_elemwise_func(data, transform, dtype) + + return Variable(dims, data, attrs, encoding) + + +class CFTimedeltaCoder(VariableCoder): + + def encode(self, variable, name=None): + dims, data, attrs, encoding = unpack_for_encoding(variable) + + if np.issubdtype(data.dtype, np.timedelta64): + data, units = encode_cf_timedelta( + data, encoding.pop('units', None)) + safe_setitem(attrs, 'units', units, name=name) + + return Variable(dims, data, attrs, encoding) + + def decode(self, variable, name=None): + dims, data, attrs, encoding = unpack_for_decoding(variable) + + if 'units' in attrs and attrs['units'] in TIME_UNITS: + units = pop_to(attrs, encoding, 'units') + transform = partial(decode_cf_timedelta, units=units) + dtype = np.dtype('timedelta64[ns]') + data = lazy_elemwise_func(data, transform, dtype=dtype) + + return Variable(dims, data, attrs, encoding) diff --git a/xarray/coding/variables.py b/xarray/coding/variables.py new file mode 100644 index 0000000..bf2ded8 --- /dev/null +++ b/xarray/coding/variables.py @@ -0,0 +1,277 @@ +"""Coders for individual Variable objects.""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from functools import partial +import warnings + +import numpy as np +import pandas as pd + +from ..core import dtypes +from ..core import duck_array_ops +from ..core import indexing +from ..core import utils +from ..core.pycompat import dask_array_type +from ..core.variable import Variable + + +class SerializationWarning(RuntimeWarning): + """Warnings about encoding/decoding issues in serialization.""" + + +class VariableCoder(object): + """Base class for encoding and decoding transformations on variables. + + We use coders for transforming variables between xarray's data model and + a format suitable for serialization. For example, coders apply CF + conventions for how data should be represented in netCDF files. + + Subclasses should implement encode() and decode(), which should satisfy + the identity ``coder.decode(coder.encode(variable)) == variable``. If any + options are necessary, they should be implemented as arguments to the + __init__ method. + + The optional name argument to encode() and decode() exists solely for the + sake of better error messages, and should correspond to the name of + variables in the underlying store. + """ + + def encode(self, variable, name=None): + # type: (Variable, Any) -> Variable + """Convert an encoded variable to a decoded variable.""" + raise NotImplementedError + + def decode(self, variable, name=None): + # type: (Variable, Any) -> Variable + """Convert an decoded variable to a encoded variable.""" + raise NotImplementedError + + +class _ElementwiseFunctionArray(indexing.ExplicitlyIndexedNDArrayMixin): + """Lazily computed array holding values of elemwise-function. + + Do not construct this object directly: call lazy_elemwise_func instead. + + Values are computed upon indexing or coercion to a NumPy array. + """ + + def __init__(self, array, func, dtype): + assert not isinstance(array, dask_array_type) + self.array = indexing.as_indexable(array) + self.func = func + self._dtype = dtype + + @property + def dtype(self): + return np.dtype(self._dtype) + + def __getitem__(self, key): + return self.func(self.array[key]) + + def __repr__(self): + return ("%s(%r, func=%r, dtype=%r)" % + (type(self).__name__, self.array, self.func, self.dtype)) + + +def lazy_elemwise_func(array, func, dtype): + """Lazily apply an element-wise function to an array. + + Parameters + ---------- + array : any valid value of Variable._data + func : callable + Function to apply to indexed slices of an array. For use with dask, + this should be a pickle-able object. + dtype : coercible to np.dtype + Dtype for the result of this function. + + Returns + ------- + Either a dask.array.Array or _ElementwiseFunctionArray. + """ + if isinstance(array, dask_array_type): + return array.map_blocks(func, dtype=dtype) + else: + return _ElementwiseFunctionArray(array, func, dtype) + + +def unpack_for_encoding(var): + return var.dims, var.data, var.attrs.copy(), var.encoding.copy() + + +def unpack_for_decoding(var): + return var.dims, var._data, var.attrs.copy(), var.encoding.copy() + + +def safe_setitem(dest, key, value, name=None): + if key in dest: + var_str = ' on variable {!r}'.format(name) if name else '' + raise ValueError( + 'failed to prevent overwriting existing key {} in attrs{}. ' + 'This is probably an encoding field used by xarray to describe ' + 'how a variable is serialized. To proceed, remove this key from ' + "the variable's attributes manually.".format(key, var_str)) + dest[key] = value + + +def pop_to(source, dest, key, name=None): + """ + A convenience function which pops a key k from source to dest. + None values are not passed on. If k already exists in dest an + error is raised. + """ + value = source.pop(key, None) + if value is not None: + safe_setitem(dest, key, value, name=name) + return value + + +def _apply_mask(data, # type: np.ndarray + encoded_fill_values, # type: list + decoded_fill_value, # type: Any + dtype, # type: Any + ): # type: np.ndarray + """Mask all matching values in a NumPy arrays.""" + condition = False + for fv in encoded_fill_values: + condition |= data == fv + data = np.asarray(data, dtype=dtype) + return np.where(condition, decoded_fill_value, data) + + +class CFMaskCoder(VariableCoder): + """Mask or unmask fill values according to CF conventions.""" + + def encode(self, variable, name=None): + dims, data, attrs, encoding = unpack_for_encoding(variable) + + if encoding.get('_FillValue') is not None: + fill_value = pop_to(encoding, attrs, '_FillValue', name=name) + if not pd.isnull(fill_value): + data = duck_array_ops.fillna(data, fill_value) + + return Variable(dims, data, attrs, encoding) + + def decode(self, variable, name=None): + dims, data, attrs, encoding = unpack_for_decoding(variable) + + if 'missing_value' in attrs: + # missing_value is deprecated, but we still want to support it as + # an alias for _FillValue. + if ('_FillValue' in attrs and + not utils.equivalent(attrs['_FillValue'], + attrs['missing_value'])): + raise ValueError("Conflicting _FillValue and missing_value " + "attrs on a variable {!r}: {} vs. {}\n\n" + "Consider opening the offending dataset " + "using decode_cf=False, correcting the " + "attrs and decoding explicitly using " + "xarray.decode_cf()." + .format(name, attrs['_FillValue'], + attrs['missing_value'])) + attrs['_FillValue'] = attrs.pop('missing_value') + + if '_FillValue' in attrs: + raw_fill_value = pop_to(attrs, encoding, '_FillValue', name=name) + encoded_fill_values = [ + fv for fv in np.ravel(raw_fill_value) if not pd.isnull(fv)] + + if len(encoded_fill_values) > 1: + warnings.warn("variable {!r} has multiple fill values {}, " + "decoding all values to NaN." + .format(name, encoded_fill_values), + SerializationWarning, stacklevel=3) + + dtype, decoded_fill_value = dtypes.maybe_promote(data.dtype) + + if encoded_fill_values: + transform = partial(_apply_mask, + encoded_fill_values=encoded_fill_values, + decoded_fill_value=decoded_fill_value, + dtype=dtype) + data = lazy_elemwise_func(data, transform, dtype) + + return Variable(dims, data, attrs, encoding) + + +def _scale_offset_decoding(data, scale_factor, add_offset, dtype): + data = np.array(data, dtype=dtype, copy=True) + if scale_factor is not None: + data *= scale_factor + if add_offset is not None: + data += add_offset + return data + + +class CFScaleOffsetCoder(VariableCoder): + """Scale and offset variables according to CF conventions. + + Follows the formula: + decode_values = encoded_values * scale_factor + add_offset + """ + + def encode(self, variable, name=None): + dims, data, attrs, encoding = unpack_for_encoding(variable) + + if 'scale_factor' in encoding or 'add_offset' in encoding: + data = data.astype(dtype=np.float64, copy=True) + if 'add_offset' in encoding: + data -= pop_to(encoding, attrs, 'add_offset', name=name) + if 'scale_factor' in encoding: + data /= pop_to(encoding, attrs, 'scale_factor', name=name) + + return Variable(dims, data, attrs, encoding) + + def decode(self, variable, name=None): + dims, data, attrs, encoding = unpack_for_decoding(variable) + + if 'scale_factor' in attrs or 'add_offset' in attrs: + scale_factor = pop_to(attrs, encoding, 'scale_factor', name=name) + add_offset = pop_to(attrs, encoding, 'add_offset', name=name) + dtype = np.float64 + transform = partial(_scale_offset_decoding, + scale_factor=scale_factor, + add_offset=add_offset, + dtype=dtype) + data = lazy_elemwise_func(data, transform, dtype) + + return Variable(dims, data, attrs, encoding) + + +class UnsignedIntegerCoder(VariableCoder): + + def encode(self, variable, name=None): + dims, data, attrs, encoding = unpack_for_encoding(variable) + + if encoding.get('_Unsigned', False): + pop_to(encoding, attrs, '_Unsigned') + signed_dtype = np.dtype('i%s' % data.dtype.itemsize) + if '_FillValue' in attrs: + new_fill = signed_dtype.type(attrs['_FillValue']) + attrs['_FillValue'] = new_fill + data = duck_array_ops.around(data).astype(signed_dtype) + + return Variable(dims, data, attrs, encoding) + + def decode(self, variable, name=None): + dims, data, attrs, encoding = unpack_for_decoding(variable) + + if '_Unsigned' in attrs: + unsigned = pop_to(attrs, encoding, '_Unsigned') + + if data.dtype.kind == 'i': + if unsigned: + unsigned_dtype = np.dtype('u%s' % data.dtype.itemsize) + transform = partial(np.asarray, dtype=unsigned_dtype) + data = lazy_elemwise_func(data, transform, unsigned_dtype) + if '_FillValue' in attrs: + new_fill = unsigned_dtype.type(attrs['_FillValue']) + attrs['_FillValue'] = new_fill + else: + warnings.warn("variable %r has _Unsigned attribute but is not " + "of integer type. Ignoring attribute." % name, + SerializationWarning, stacklevel=3) + + return Variable(dims, data, attrs, encoding) diff --git a/xarray/conventions.py b/xarray/conventions.py index 5b951ff..fe75d9e 100644 --- a/xarray/conventions.py +++ b/xarray/conventions.py @@ -1,455 +1,20 @@ from __future__ import absolute_import from __future__ import division from __future__ import print_function -from datetime import datetime -import re -import traceback -import warnings -import numpy as np -import pandas as pd +import warnings from collections import defaultdict -try: - from pandas.errors import OutOfBoundsDatetime -except ImportError: - # pandas < 0.20 - from pandas.tslib import OutOfBoundsDatetime - -from .core import duck_array_ops, indexing, ops, utils -from .core.formatting import format_timestamp, first_n_items, last_item -from .core.variable import as_variable, IndexVariable, Variable -from .core.pycompat import iteritems, OrderedDict, PY3, basestring - - -# standard calendars recognized by netcdftime -_STANDARD_CALENDARS = set(['standard', 'gregorian', 'proleptic_gregorian']) - -_NS_PER_TIME_DELTA = {'us': 1e3, - 'ms': 1e6, - 's': 1e9, - 'm': 1e9 * 60, - 'h': 1e9 * 60 * 60, - 'D': 1e9 * 60 * 60 * 24} - - -class SerializationWarning(RuntimeWarning): - """Warnings about encoding/decoding issues in serialization.""" - - -def mask_and_scale(array, fill_value=None, scale_factor=None, add_offset=None, - dtype=float): - """Scale and mask array values according to CF conventions for packed and - missing values - - First, values equal to the fill_value are replaced by NaN. Then, new values - are given by the formula: - - original_values * scale_factor + add_offset - - Parameters - ---------- - array : array-like - Original array of values to wrap - fill_value : number, optional - All values equal to fill_value in the original array are replaced - by NaN. If an array of multiple values is provided a warning will be - issued and all array elements matching an value in the fill_value array - will be replaced by NaN. - scale_factor : number, optional - Multiply entries in the original array by this number. - add_offset : number, optional - After applying scale_factor, add this number to entries in the - original array. - - Returns - ------- - scaled : np.ndarray - Array of masked and scaled values. - - References - ---------- - http://www.unidata.ucar.edu/software/netcdf/docs/BestPractices.html - """ - # by default, cast to float to ensure NaN is meaningful - values = np.array(array, dtype=dtype, copy=True) - if fill_value is not None and not np.all(pd.isnull(fill_value)): - if getattr(fill_value, 'size', 1) > 1: - fill_values = fill_value # multiple fill values - else: - fill_values = [fill_value] - for f_value in fill_values: - if values.ndim > 0: - values[values == f_value] = np.nan - elif values == f_value: - values = np.array(np.nan) - if scale_factor is not None: - values *= scale_factor - if add_offset is not None: - values += add_offset - return values - - -def _netcdf_to_numpy_timeunit(units): - units = units.lower() - if not units.endswith('s'): - units = '%ss' % units - return {'microseconds': 'us', 'milliseconds': 'ms', 'seconds': 's', - 'minutes': 'm', 'hours': 'h', 'days': 'D'}[units] - - -def _unpack_netcdf_time_units(units): - # CF datetime units follow the format: "UNIT since DATE" - # this parses out the unit and date allowing for extraneous - # whitespace. - matches = re.match('(.+) since (.+)', units) - if not matches: - raise ValueError('invalid time units: %s' % units) - delta_units, ref_date = [s.strip() for s in matches.groups()] - return delta_units, ref_date - - -def _decode_datetime_with_netcdf4(num_dates, units, calendar): - import netCDF4 as nc4 - - dates = np.asarray(nc4.num2date(num_dates, units, calendar)) - if (dates[np.nanargmin(num_dates)].year < 1678 or - dates[np.nanargmax(num_dates)].year >= 2262): - warnings.warn('Unable to decode time axis into full ' - 'numpy.datetime64 objects, continuing using dummy ' - 'netCDF4.datetime objects instead, reason: dates out' - ' of range', SerializationWarning, stacklevel=3) - else: - try: - dates = nctime_to_nptime(dates) - except ValueError as e: - warnings.warn('Unable to decode time axis into full ' - 'numpy.datetime64 objects, continuing using ' - 'dummy netCDF4.datetime objects instead, reason:' - '{0}'.format(e), SerializationWarning, stacklevel=3) - return dates - - -def decode_cf_datetime(num_dates, units, calendar=None): - """Given an array of numeric dates in netCDF format, convert it into a - numpy array of date time objects. - - For standard (Gregorian) calendars, this function uses vectorized - operations, which makes it much faster than netCDF4.num2date. In such a - case, the returned array will be of type np.datetime64. - - Note that time unit in `units` must not be smaller than microseconds and - not larger than days. - - See also - -------- - netCDF4.num2date - """ - num_dates = np.asarray(num_dates) - flat_num_dates = num_dates.ravel() - if calendar is None: - calendar = 'standard' - - delta, ref_date = _unpack_netcdf_time_units(units) - - try: - if calendar not in _STANDARD_CALENDARS: - raise OutOfBoundsDatetime - - delta = _netcdf_to_numpy_timeunit(delta) - try: - ref_date = pd.Timestamp(ref_date) - except ValueError: - # ValueError is raised by pd.Timestamp for non-ISO timestamp - # strings, in which case we fall back to using netCDF4 - raise OutOfBoundsDatetime - - # fixes: https://github.com/pydata/pandas/issues/14068 - # these lines check if the the lowest or the highest value in dates - # cause an OutOfBoundsDatetime (Overflow) error - pd.to_timedelta(flat_num_dates.min(), delta) + ref_date - pd.to_timedelta(flat_num_dates.max(), delta) + ref_date - - # Cast input dates to integers of nanoseconds because `pd.to_datetime` - # works much faster when dealing with integers - flat_num_dates_ns_int = (flat_num_dates * - _NS_PER_TIME_DELTA[delta]).astype(np.int64) - - dates = (pd.to_timedelta(flat_num_dates_ns_int, 'ns') + - ref_date).values - - except (OutOfBoundsDatetime, OverflowError): - dates = _decode_datetime_with_netcdf4(flat_num_dates.astype(np.float), - units, - calendar) - - return dates.reshape(num_dates.shape) - - -def decode_cf_timedelta(num_timedeltas, units): - """Given an array of numeric timedeltas in netCDF format, convert it into a - numpy timedelta64[ns] array. - """ - num_timedeltas = np.asarray(num_timedeltas) - units = _netcdf_to_numpy_timeunit(units) - - shape = num_timedeltas.shape - num_timedeltas = num_timedeltas.ravel() - - result = pd.to_timedelta(num_timedeltas, unit=units, box=False) - # NaT is returned unboxed with wrong units; this should be fixed in pandas - if result.dtype != 'timedelta64[ns]': - result = result.astype('timedelta64[ns]') - return result.reshape(shape) - - -TIME_UNITS = frozenset(['days', 'hours', 'minutes', 'seconds', - 'milliseconds', 'microseconds']) - - -def _infer_time_units_from_diff(unique_timedeltas): - for time_unit, delta in [('days', 86400), ('hours', 3600), - ('minutes', 60), ('seconds', 1)]: - unit_delta = np.timedelta64(10 ** 9 * delta, 'ns') - diffs = unique_timedeltas / unit_delta - if np.all(diffs == diffs.astype(int)): - return time_unit - return 'seconds' - - -def infer_datetime_units(dates): - """Given an array of datetimes, returns a CF compatible time-unit string of - the form "{time_unit} since {date[0]}", where `time_unit` is 'days', - 'hours', 'minutes' or 'seconds' (the first one that can evenly divide all - unique time deltas in `dates`) - """ - dates = pd.to_datetime(np.asarray(dates).ravel(), box=False) - dates = dates[pd.notnull(dates)] - unique_timedeltas = np.unique(np.diff(dates)) - units = _infer_time_units_from_diff(unique_timedeltas) - reference_date = dates[0] if len(dates) > 0 else '1970-01-01' - return '%s since %s' % (units, pd.Timestamp(reference_date)) - - -def infer_timedelta_units(deltas): - """Given an array of timedeltas, returns a CF compatible time-unit from - {'days', 'hours', 'minutes' 'seconds'} (the first one that can evenly - divide all unique time deltas in `deltas`) - """ - deltas = pd.to_timedelta(np.asarray(deltas).ravel(), box=False) - unique_timedeltas = np.unique(deltas[pd.notnull(deltas)]) - units = _infer_time_units_from_diff(unique_timedeltas) - return units - - -def nctime_to_nptime(times): - """Given an array of netCDF4.datetime objects, return an array of - numpy.datetime64 objects of the same size""" - times = np.asarray(times) - new = np.empty(times.shape, dtype='M8[ns]') - for i, t in np.ndenumerate(times): - dt = datetime(t.year, t.month, t.day, t.hour, t.minute, t.second) - new[i] = np.datetime64(dt) - return new - - -def _cleanup_netcdf_time_units(units): - delta, ref_date = _unpack_netcdf_time_units(units) - try: - units = '%s since %s' % (delta, format_timestamp(ref_date)) - except OutOfBoundsDatetime: - # don't worry about reifying the units if they're out of bounds - pass - return units - - -def _encode_datetime_with_netcdf4(dates, units, calendar): - """Fallback method for encoding dates using netCDF4-python. - - This method is more flexible than xarray's parsing using datetime64[ns] - arrays but also slower because it loops over each element. - """ - import netCDF4 as nc4 - - if np.issubdtype(dates.dtype, np.datetime64): - # numpy's broken datetime conversion only works for us precision - dates = dates.astype('M8[us]').astype(datetime) - - def encode_datetime(d): - return np.nan if d is None else nc4.date2num(d, units, calendar) - - return np.vectorize(encode_datetime)(dates) - - -def cast_to_int_if_safe(num): - int_num = np.array(num, dtype=np.int64) - if (num == int_num).all(): - num = int_num - return num - - -def encode_cf_datetime(dates, units=None, calendar=None): - """Given an array of datetime objects, returns the tuple `(num, units, - calendar)` suitable for a CF compliant time variable. - - Unlike `date2num`, this function can handle datetime64 arrays. - - See also - -------- - netCDF4.date2num - """ - dates = np.asarray(dates) - - if units is None: - units = infer_datetime_units(dates) - else: - units = _cleanup_netcdf_time_units(units) - - if calendar is None: - calendar = 'proleptic_gregorian' - - delta, ref_date = _unpack_netcdf_time_units(units) - try: - if calendar not in _STANDARD_CALENDARS or dates.dtype.kind == 'O': - # parse with netCDF4 instead - raise OutOfBoundsDatetime - assert dates.dtype == 'datetime64[ns]' - - delta_units = _netcdf_to_numpy_timeunit(delta) - time_delta = np.timedelta64(1, delta_units).astype('timedelta64[ns]') - ref_date = np.datetime64(pd.Timestamp(ref_date)) - num = (dates - ref_date) / time_delta - - except (OutOfBoundsDatetime, OverflowError): - num = _encode_datetime_with_netcdf4(dates, units, calendar) - - num = cast_to_int_if_safe(num) - return (num, units, calendar) - - -def encode_cf_timedelta(timedeltas, units=None): - if units is None: - units = infer_timedelta_units(timedeltas) - - np_unit = _netcdf_to_numpy_timeunit(units) - num = 1.0 * timedeltas / np.timedelta64(1, np_unit) - num = np.where(pd.isnull(timedeltas), np.nan, num) - num = cast_to_int_if_safe(num) - return (num, units) - - -class MaskedAndScaledArray(indexing.ExplicitlyIndexedNDArrayMixin): - """Wrapper around array-like objects to create a new indexable object where - values, when accessed, are automatically scaled and masked according to - CF conventions for packed and missing data values. - - New values are given by the formula: - original_values * scale_factor + add_offset - - Values can only be accessed via `__getitem__`: - - >>> x = MaskedAndScaledArray(np.array([-99, -1, 0, 1, 2]), -99, 0.01, 1) - >>> x - MaskedAndScaledArray(array([-99, -1, 0, 1, 2]), fill_value=-99, - scale_factor=0.01, add_offset=1) - >>> x[:] - array([ nan, 0.99, 1. , 1.01, 1.02] - - References - ---------- - http://www.unidata.ucar.edu/software/netcdf/docs/BestPractices.html - """ - def __init__(self, array, fill_value=None, scale_factor=None, - add_offset=None, dtype=float): - """ - Parameters - ---------- - array : array-like - Original array of values to wrap - fill_value : number, optional - All values equal to fill_value in the original array are replaced - by NaN. - scale_factor : number, optional - Multiply entries in the original array by this number. - add_offset : number, optional - After applying scale_factor, add this number to entries in the - original array. - """ - self.array = indexing.as_indexable(array) - self.fill_value = fill_value - self.scale_factor = scale_factor - self.add_offset = add_offset - self._dtype = dtype - @property - def dtype(self): - return np.dtype(self._dtype) - - def __getitem__(self, key): - return mask_and_scale(self.array[key], self.fill_value, - self.scale_factor, self.add_offset, self._dtype) - - def __repr__(self): - return ("%s(%r, fill_value=%r, scale_factor=%r, add_offset=%r, " - "dtype=%r)" % - (type(self).__name__, self.array, self.fill_value, - self.scale_factor, self.add_offset, self._dtype)) - - -class DecodedCFDatetimeArray(indexing.ExplicitlyIndexedNDArrayMixin): - """Wrapper around array-like objects to create a new indexable object where - values, when accessed, are automatically converted into datetime objects - using decode_cf_datetime. - """ - def __init__(self, array, units, calendar=None): - self.array = indexing.as_indexable(array) - self.units = units - self.calendar = calendar - - # Verify that at least the first and last date can be decoded - # successfully. Otherwise, tracebacks end up swallowed by - # Dataset.__repr__ when users try to view their lazily decoded array. - values = indexing.ImplicitToExplicitIndexingAdapter(self.array) - example_value = np.concatenate([first_n_items(values, 1) or [0], - last_item(values) or [0]]) - - try: - result = decode_cf_datetime(example_value, units, calendar) - except Exception: - calendar_msg = ('the default calendar' if calendar is None - else 'calendar %r' % calendar) - msg = ('unable to decode time units %r with %s. Try ' - 'opening your dataset with decode_times=False.' - % (units, calendar_msg)) - if not PY3: - msg += ' Full traceback:\n' + traceback.format_exc() - raise ValueError(msg) - else: - self._dtype = getattr(result, 'dtype', np.dtype('object')) - - @property - def dtype(self): - return self._dtype - - def __getitem__(self, key): - return decode_cf_datetime(self.array[key], units=self.units, - calendar=self.calendar) - - -class DecodedCFTimedeltaArray(indexing.ExplicitlyIndexedNDArrayMixin): - """Wrapper around array-like objects to create a new indexable object where - values, when accessed, are automatically converted into timedelta objects - using decode_cf_timedelta. - """ - def __init__(self, array, units): - self.array = indexing.as_indexable(array) - self.units = units +import numpy as np - @property - def dtype(self): - return np.dtype('timedelta64[ns]') +import pandas as pd - def __getitem__(self, key): - return decode_cf_timedelta(self.array[key], units=self.units) +from .coding import times +from .coding import variables +from .coding.variables import SerializationWarning +from .core import duck_array_ops, indexing +from .core.pycompat import OrderedDict, basestring, iteritems +from .core.variable import IndexVariable, Variable, as_variable class StackedBytesArray(indexing.ExplicitlyIndexedNDArrayMixin): @@ -460,6 +25,7 @@ class StackedBytesArray(indexing.ExplicitlyIndexedNDArrayMixin): array('abc', dtype='|S3') """ + def __init__(self, array): """ Parameters @@ -505,6 +71,7 @@ class BytesToStringArray(indexing.ExplicitlyIndexedNDArrayMixin): array(['abc'], dtype=object) """ + def __init__(self, array, encoding='utf-8'): """ Parameters @@ -555,6 +122,7 @@ class NativeEndiannessArray(indexing.ExplicitlyIndexedNDArrayMixin): >>> NativeEndianArray(x)[:].dtype dtype('int16') """ + def __init__(self, array): self.array = indexing.as_indexable(array) @@ -583,40 +151,13 @@ class BoolTypeArray(indexing.ExplicitlyIndexedNDArrayMixin): >>> BoolTypeArray(x)[:].dtype dtype('bool') """ - def __init__(self, array): - self.array = indexing.as_indexable(array) - - @property - def dtype(self): - return np.dtype('bool') - def __getitem__(self, key): - return np.asarray(self.array[key], dtype=self.dtype) - - -class UnsignedIntTypeArray(indexing.ExplicitlyIndexedNDArrayMixin): - """Decode arrays on the fly from signed integer to unsigned - integer. Typically used when _Unsigned is set at as a netCDF - attribute on a signed integer variable. - - >>> sb = np.asarray([0, 1, 127, -128, -1], dtype='i1') - - >>> sb.dtype - dtype('int8') - - >>> UnsignedIntTypeArray(sb).dtype - dtype('uint8') - - >>> UnsignedIntTypeArray(sb)[:] - array([ 0, 1, 127, 128, 255], dtype=uint8) - """ def __init__(self, array): self.array = indexing.as_indexable(array) - self.unsigned_dtype = np.dtype('u%s' % array.dtype.itemsize) @property def dtype(self): - return self.unsigned_dtype + return np.dtype('bool') def __getitem__(self, key): return np.asarray(self.array[key], dtype=self.dtype) @@ -696,56 +237,17 @@ def _var_as_tuple(var): return var.dims, var.data, var.attrs.copy(), var.encoding.copy() -def maybe_encode_datetime(var, name=None): - if np.issubdtype(var.dtype, np.datetime64): - dims, data, attrs, encoding = _var_as_tuple(var) - (data, units, calendar) = encode_cf_datetime( - data, encoding.pop('units', None), encoding.pop('calendar', None)) - safe_setitem(attrs, 'units', units, name=name) - safe_setitem(attrs, 'calendar', calendar, name=name) - var = Variable(dims, data, attrs, encoding) - return var - - -def maybe_encode_timedelta(var, name=None): - if np.issubdtype(var.dtype, np.timedelta64): - dims, data, attrs, encoding = _var_as_tuple(var) - data, units = encode_cf_timedelta( - data, encoding.pop('units', None)) - safe_setitem(attrs, 'units', units, name=name) - var = Variable(dims, data, attrs, encoding) - return var - - -def maybe_encode_offset_and_scale(var, needs_copy=True, name=None): - if any(k in var.encoding for k in ['add_offset', 'scale_factor']): - dims, data, attrs, encoding = _var_as_tuple(var) - data = data.astype(dtype=float, copy=needs_copy) - needs_copy = False - if 'add_offset' in encoding: - data -= pop_to(encoding, attrs, 'add_offset', name=name) - if 'scale_factor' in encoding: - data /= pop_to(encoding, attrs, 'scale_factor', name=name) - var = Variable(dims, data, attrs, encoding) - return var, needs_copy - - -def maybe_encode_fill_value(var, needs_copy=True, name=None): - # replace NaN with the fill value - if var.encoding.get('_FillValue') is not None: - dims, data, attrs, encoding = _var_as_tuple(var) - fill_value = pop_to(encoding, attrs, '_FillValue', name=name) - if not pd.isnull(fill_value): - data = ops.fillna(data, fill_value) - needs_copy = False - var = Variable(dims, data, attrs, encoding) - return var, needs_copy - - def maybe_encode_as_char_array(var, name=None): if var.dtype.kind in {'S', 'U'}: dims, data, attrs, encoding = _var_as_tuple(var) if data.dtype.kind == 'U': + if '_FillValue' in attrs: + raise NotImplementedError( + 'variable {!r} has a _FillValue specified, but ' + '_FillValue is yet supported on unicode strings: ' + 'https://github.com/pydata/xarray/issues/1647' + .format(name)) + string_encoding = encoding.pop('_Encoding', 'utf-8') safe_setitem(attrs, '_Encoding', string_encoding, name=name) data = encode_string_array(data, string_encoding) @@ -780,13 +282,6 @@ def maybe_encode_nonstring_dtype(var, name=None): 'any _FillValue to use for NaNs' % name, SerializationWarning, stacklevel=3) data = duck_array_ops.around(data)[...] - if encoding.get('_Unsigned', False): - signed_dtype = np.dtype('i%s' % dtype.itemsize) - if '_FillValue' in var.attrs: - new_fill = signed_dtype.type(attrs['_FillValue']) - attrs['_FillValue'] = new_fill - data = data.astype(signed_dtype) - pop_to(encoding, attrs, '_Unsigned') data = data.astype(dtype=dtype) var = Variable(dims, data, attrs, encoding) return var @@ -830,18 +325,20 @@ def _infer_dtype(array, name=None): return dtype +def ensure_not_multiindex(var, name=None): + if (isinstance(var, IndexVariable) and + isinstance(var.to_index(), pd.MultiIndex)): + raise NotImplementedError( + 'variable {!r} is a MultiIndex, which cannot yet be ' + 'serialized to netCDF files ' + '(https://github.com/pydata/xarray/issues/1077). Use ' + 'reset_index() to convert MultiIndex levels into coordinate ' + 'variables instead.'.format(name)) + + def ensure_dtype_not_object(var, name=None): # TODO: move this from conventions to backends? (it's not CF related) if var.dtype.kind == 'O': - if (isinstance(var, IndexVariable) and - isinstance(var.to_index(), pd.MultiIndex)): - raise NotImplementedError( - 'variable {!r} is a MultiIndex, which cannot yet be ' - 'serialized to netCDF files ' - '(https://github.com/pydata/xarray/issues/1077). Use ' - 'reset_index() to convert MultiIndex levels into coordinate ' - 'variables instead.'.format(name)) - dims, data, attrs, encoding = _var_as_tuple(var) missing = pd.isnull(data) if missing.any(): @@ -858,7 +355,7 @@ def ensure_dtype_not_object(var, name=None): fill_value = u'' else: # insist on using float for numeric values - if not np.issubdtype(inferred_dtype, float): + if not np.issubdtype(inferred_dtype, np.floating): inferred_dtype = np.dtype(float) fill_value = inferred_dtype.type(np.nan) @@ -890,10 +387,16 @@ def encode_cf_variable(var, needs_copy=True, name=None): out : xarray.Variable A variable which has been encoded as described above. """ - var = maybe_encode_datetime(var, name=name) - var = maybe_encode_timedelta(var, name=name) - var, needs_copy = maybe_encode_offset_and_scale(var, needs_copy, name=name) - var, needs_copy = maybe_encode_fill_value(var, needs_copy, name=name) + ensure_not_multiindex(var, name=name) + + for coder in [times.CFDatetimeCoder(), + times.CFTimedeltaCoder(), + variables.CFScaleOffsetCoder(), + variables.CFMaskCoder(), + variables.UnsignedIntegerCoder()]: + var = coder.encode(var, name=name) + + # TODO(shoyer): convert all of these to use coders, too: var = maybe_encode_nonstring_dtype(var, name=name) var = maybe_default_fill_value(var) var = maybe_encode_bools(var) @@ -958,73 +461,22 @@ def decode_cf_variable(name, var, concat_characters=True, mask_and_scale=True, if string_encoding is not None: data = BytesToStringArray(data, string_encoding) - unsigned = pop_to(attributes, encoding, '_Unsigned') - if unsigned and mask_and_scale: - if data.dtype.kind == 'i': - data = UnsignedIntTypeArray(data) - else: - warnings.warn("variable %r has _Unsigned attribute but is not " - "of integer type. Ignoring attribute." % name, - SerializationWarning, stacklevel=3) + # TODO(shoyer): convert everything above to use coders + var = Variable(dimensions, data, attributes, encoding) if mask_and_scale: - if 'missing_value' in attributes: - # missing_value is deprecated, but we still want to support it as - # an alias for _FillValue. - if ('_FillValue' in attributes and - not utils.equivalent(attributes['_FillValue'], - attributes['missing_value'])): - raise ValueError("Conflicting _FillValue and missing_value " - "attributes on a variable {!r}: {} vs. {}\n\n" - "Consider opening the offending dataset " - "using decode_cf=False, correcting the " - "attributes and decoding explicitly using " - "xarray.decode_cf()." - .format(name, attributes['_FillValue'], - attributes['missing_value'])) - attributes['_FillValue'] = attributes.pop('missing_value') - - fill_value = pop_to(attributes, encoding, '_FillValue') - if isinstance(fill_value, np.ndarray) and fill_value.size > 1: - warnings.warn("variable {!r} has multiple fill values {}, " - "decoding all values to NaN." - .format(name, fill_value), - SerializationWarning, stacklevel=3) - - scale_factor = pop_to(attributes, encoding, 'scale_factor') - add_offset = pop_to(attributes, encoding, 'add_offset') - has_fill = (fill_value is not None and - not np.any(pd.isnull(fill_value))) - if (has_fill or scale_factor is not None or add_offset is not None): - if has_fill and np.array(fill_value).dtype.kind in ['U', 'S', 'O']: - if string_encoding is not None: - raise NotImplementedError( - 'variable %r has a _FillValue specified, but ' - '_FillValue is yet supported on unicode strings: ' - 'https://github.com/pydata/xarray/issues/1647') - dtype = object - else: - # According to the CF spec, the fill value is of the same - # type as its variable, i.e. its storage format on disk. - # This handles the case where the fill_value also needs to be - # converted to its unsigned value. - if has_fill: - fill_value = data.dtype.type(fill_value) - dtype = float - - data = MaskedAndScaledArray(data, fill_value, scale_factor, - add_offset, dtype) - - if decode_times and 'units' in attributes: - if 'since' in attributes['units']: - # datetime - units = pop_to(attributes, encoding, 'units') - calendar = pop_to(attributes, encoding, 'calendar') - data = DecodedCFDatetimeArray(data, units, calendar) - elif attributes['units'] in TIME_UNITS: - # timedelta - units = pop_to(attributes, encoding, 'units') - data = DecodedCFTimedeltaArray(data, units) + for coder in [variables.UnsignedIntegerCoder(), + variables.CFMaskCoder(), + variables.CFScaleOffsetCoder()]: + var = coder.decode(var, name=name) + if decode_times: + for coder in [times.CFTimedeltaCoder(), + times.CFDatetimeCoder()]: + var = coder.decode(var, name=name) + + dimensions, data, attributes, encoding = ( + variables.unpack_for_decoding(var)) + # TODO(shoyer): convert everything below to use coders if decode_endianness and not data.dtype.isnative: # do this last, so it's only done if we didn't already unmask/scale @@ -1215,7 +667,7 @@ def _encode_coordinates(variables, attributes, non_dim_coord_names): target_dims = variables[coord_name].dims for k, v in variables.items(): if (k not in non_dim_coord_names and k not in v.dims and - any(d in target_dims for d in v.dims)): + set(target_dims) <= set(v.dims)): variable_coordinates[k].add(coord_name) global_coordinates.discard(coord_name) diff --git a/xarray/convert.py b/xarray/convert.py index 26822ea..caf665b 100644 --- a/xarray/convert.py +++ b/xarray/convert.py @@ -6,25 +6,43 @@ import numpy as np +from .coding.times import CFDatetimeCoder, CFTimedeltaCoder from .core.dataarray import DataArray -from .conventions import ( - maybe_encode_timedelta, maybe_encode_datetime, decode_cf) +from .core.pycompat import OrderedDict, range +from .core.dtypes import get_fill_value +from .conventions import decode_cf -ignored_attrs = set(['name', 'tileIndex']) +cdms2_ignored_attrs = {'name', 'tileIndex'} +iris_forbidden_keys = {'standard_name', 'long_name', 'units', 'bounds', 'axis', + 'calendar', 'leap_month', 'leap_year', 'month_lengths', + 'coordinates', 'grid_mapping', 'climatology', + 'cell_methods', 'formula_terms', 'compress', + 'missing_value', 'add_offset', 'scale_factor', + 'valid_max', 'valid_min', 'valid_range', '_FillValue'} +cell_methods_strings = {'point', 'sum', 'maximum', 'median', 'mid_range', + 'minimum', 'mean', 'mode', 'standard_deviation', + 'variance'} + + +def encode(var): + return CFTimedeltaCoder().encode(CFDatetimeCoder().encode(var.variable)) + + +def _filter_attrs(attrs, ignored_attrs): + """ Return attrs that are not in ignored_attrs + """ + return dict((k, v) for k, v in attrs.items() if k not in ignored_attrs) def from_cdms2(variable): """Convert a cdms2 variable into an DataArray """ - def get_cdms2_attrs(var): - return dict((k, v) for k, v in var.attributes.items() - if k not in ignored_attrs) - values = np.asarray(variable) name = variable.id - coords = [(v.id, np.asarray(v), get_cdms2_attrs(v)) + coords = [(v.id, np.asarray(v), + _filter_attrs(v.attributes, cdms2_ignored_attrs)) for v in variable.getAxisList()] - attrs = get_cdms2_attrs(variable) + attrs = _filter_attrs(variable.attributes, cdms2_ignored_attrs) dataarray = DataArray(values, coords=coords, name=name, attrs=attrs) return decode_cf(dataarray.to_dataset())[dataarray.name] @@ -35,9 +53,6 @@ def to_cdms2(dataarray): # we don't want cdms2 to be a hard dependency import cdms2 - def encode(var): - return maybe_encode_timedelta(maybe_encode_datetime(var.variable)) - def set_cdms2_attrs(var, attrs): for k, v in attrs.items(): setattr(var, k, v) @@ -53,3 +68,150 @@ def set_cdms2_attrs(var, attrs): cdms2_var = cdms2.createVariable(var.values, axes=axes, id=dataarray.name) set_cdms2_attrs(cdms2_var, var.attrs) return cdms2_var + + +def _pick_attrs(attrs, keys): + """ Return attrs with keys in keys list + """ + return dict((k, v) for k, v in attrs.items() if k in keys) + + +def _get_iris_args(attrs): + """ Converts the xarray attrs into args that can be passed into Iris + """ + # iris.unit is deprecated in Iris v1.9 + import cf_units + args = {'attributes': _filter_attrs(attrs, iris_forbidden_keys)} + args.update(_pick_attrs(attrs, ('standard_name', 'long_name',))) + unit_args = _pick_attrs(attrs, ('calendar',)) + if 'units' in attrs: + args['units'] = cf_units.Unit(attrs['units'], **unit_args) + return args + + +# TODO: Add converting bounds from xarray to Iris and back +def to_iris(dataarray): + """ Convert a DataArray into a Iris Cube + """ + # Iris not a hard dependency + import iris + from iris.fileformats.netcdf import parse_cell_methods + from xarray.core.pycompat import dask_array_type + + dim_coords = [] + aux_coords = [] + + for coord_name in dataarray.coords: + coord = encode(dataarray.coords[coord_name]) + coord_args = _get_iris_args(coord.attrs) + coord_args['var_name'] = coord_name + axis = None + if coord.dims: + axis = dataarray.get_axis_num(coord.dims) + if coord_name in dataarray.dims: + iris_coord = iris.coords.DimCoord(coord.values, **coord_args) + dim_coords.append((iris_coord, axis)) + else: + iris_coord = iris.coords.AuxCoord(coord.values, **coord_args) + aux_coords.append((iris_coord, axis)) + + args = _get_iris_args(dataarray.attrs) + args['var_name'] = dataarray.name + args['dim_coords_and_dims'] = dim_coords + args['aux_coords_and_dims'] = aux_coords + if 'cell_methods' in dataarray.attrs: + args['cell_methods'] = \ + parse_cell_methods(dataarray.attrs['cell_methods']) + + # Create the right type of masked array (should be easier after #1769) + if isinstance(dataarray.data, dask_array_type): + from dask.array import ma as dask_ma + masked_data = dask_ma.masked_invalid(dataarray) + else: + masked_data = np.ma.masked_invalid(dataarray) + + cube = iris.cube.Cube(masked_data, **args) + + return cube + + +def _iris_obj_to_attrs(obj): + """ Return a dictionary of attrs when given a Iris object + """ + attrs = {'standard_name': obj.standard_name, + 'long_name': obj.long_name} + if obj.units.calendar: + attrs['calendar'] = obj.units.calendar + if obj.units.origin != '1': + attrs['units'] = obj.units.origin + attrs.update(obj.attributes) + return dict((k, v) for k, v in attrs.items() if v is not None) + + +def _iris_cell_methods_to_str(cell_methods_obj): + """ Converts a Iris cell methods into a string + """ + cell_methods = [] + for cell_method in cell_methods_obj: + names = ''.join(['{}: '.format(n) for n in cell_method.coord_names]) + intervals = ' '.join(['interval: {}'.format(interval) + for interval in cell_method.intervals]) + comments = ' '.join(['comment: {}'.format(comment) + for comment in cell_method.comments]) + extra = ' '.join([intervals, comments]).strip() + if extra: + extra = ' ({})'.format(extra) + cell_methods.append(names + cell_method.method + extra) + return ' '.join(cell_methods) + + +def from_iris(cube): + """ Convert a Iris cube into an DataArray + """ + import iris.exceptions + from xarray.core.pycompat import dask_array_type + + name = cube.var_name + dims = [] + for i in range(cube.ndim): + try: + dim_coord = cube.coord(dim_coords=True, dimensions=(i,)) + dims.append(dim_coord.var_name) + except iris.exceptions.CoordinateNotFoundError: + dims.append("dim_{}".format(i)) + + coords = OrderedDict() + + for coord in cube.coords(): + coord_attrs = _iris_obj_to_attrs(coord) + coord_dims = [dims[i] for i in cube.coord_dims(coord)] + if not coord.var_name: + raise ValueError("Coordinate '{}' has no " + "var_name attribute".format(coord.name())) + if coord_dims: + coords[coord.var_name] = (coord_dims, coord.points, coord_attrs) + else: + coords[coord.var_name] = ((), + np.asscalar(coord.points), coord_attrs) + + array_attrs = _iris_obj_to_attrs(cube) + cell_methods = _iris_cell_methods_to_str(cube.cell_methods) + if cell_methods: + array_attrs['cell_methods'] = cell_methods + + # Deal with iris 1.* and 2.* + cube_data = cube.core_data() if hasattr(cube, 'core_data') else cube.data + + # Deal with dask and numpy masked arrays + if isinstance(cube_data, dask_array_type): + from dask.array import ma as dask_ma + filled_data = dask_ma.filled(cube_data, get_fill_value(cube.dtype)) + elif isinstance(cube_data, np.ma.MaskedArray): + filled_data = np.ma.filled(cube_data, get_fill_value(cube.dtype)) + else: + filled_data = cube_data + + dataarray = DataArray(filled_data, coords=coords, name=name, + attrs=array_attrs, dims=dims) + decoded_ds = decode_cf(dataarray._to_temp_dataset()) + return dataarray._from_temp_dataset(decoded_ds) diff --git a/xarray/core/accessors.py b/xarray/core/accessors.py index 59aca6b..5052b55 100644 --- a/xarray/core/accessors.py +++ b/xarray/core/accessors.py @@ -80,6 +80,7 @@ class DatetimeAccessor(object): `dayofyear` may not be accurate. """ + def __init__(self, xarray_obj): if not is_datetime_like(xarray_obj.dtype): raise TypeError("'dt' accessor only available for " diff --git a/xarray/core/alignment.py b/xarray/core/alignment.py index 24b7da8..8762453 100644 --- a/xarray/core/alignment.py +++ b/xarray/core/alignment.py @@ -363,7 +363,7 @@ def var_indexers(var, indexers): "Indexer has dimensions {0:s} that are different " "from that to be indexed along {1:s}. " "This will behave differently in the future.".format( - str(indexer.dims), dim), + str(indexer.dims), dim), FutureWarning, stacklevel=3) if dim in variables: diff --git a/xarray/core/combine.py b/xarray/core/combine.py index 97c36c8..b14d085 100644 --- a/xarray/core/combine.py +++ b/xarray/core/combine.py @@ -9,7 +9,8 @@ from .alignment import align from .merge import merge from .pycompat import iteritems, OrderedDict, basestring -from .variable import Variable, as_variable, IndexVariable, concat as concat_vars +from .variable import Variable, as_variable, IndexVariable, \ + concat as concat_vars def concat(objs, dim=None, data_vars='all', coords='different', @@ -103,12 +104,12 @@ def concat(objs, dim=None, data_vars='all', coords='different', if mode is not None: raise ValueError('`mode` is no longer a valid argument to ' - 'xarray.concat; it has been split into the `data_vars` ' - 'and `coords` arguments') + 'xarray.concat; it has been split into the ' + '`data_vars` and `coords` arguments') if concat_over is not None: raise ValueError('`concat_over` is no longer a valid argument to ' - 'xarray.concat; it has been split into the `data_vars` ' - 'and `coords` arguments') + 'xarray.concat; it has been split into the ' + '`data_vars` and `coords` arguments') if isinstance(first_obj, DataArray): f = _dataarray_concat @@ -166,8 +167,8 @@ def process_subset_opt(opt, subset): if k not in concat_over: # Compare the variable of all datasets vs. the one # of the first dataset. Perform the minimum amount of - # loads in order to avoid multiple loads from disk while - # keeping the RAM footprint low. + # loads in order to avoid multiple loads from disk + # while keeping the RAM footprint low. v_lhs = datasets[0].variables[k].load() # We'll need to know later on if variables are equal. computed = [] @@ -199,11 +200,11 @@ def process_subset_opt(opt, subset): if subset == 'coords': raise ValueError( 'some variables in coords are not coordinates on ' - 'the first dataset: %s' % invalid_vars) + 'the first dataset: %s' % (invalid_vars,)) else: raise ValueError( - 'some variables in data_vars are not data variables on ' - 'the first dataset: %s' % invalid_vars) + 'some variables in data_vars are not data variables ' + 'on the first dataset: %s' % (invalid_vars,)) concat_over.update(opt) process_subset_opt(data_vars, 'data_vars') @@ -275,7 +276,6 @@ def insert_result_variable(k, v): raise ValueError( 'variable %s not equal across datasets' % k) - # we've already verified everything is consistent; now, calculate # shared dimension sizes so we can expand the necessary variables dim_lengths = [ds.dims.get(dim, 1) for ds in datasets] @@ -377,8 +377,8 @@ def auto_combine(datasets, This method attempts to combine a list of datasets into a single entity by inspecting metadata and using a combination of concat and merge. - It does not concatenate along more than one dimension or sort data under any - circumstances. It does align coordinates, but different variables on + It does not concatenate along more than one dimension or sort data under + any circumstances. It does align coordinates, but different variables on datasets can cause it to fail under some scenarios. In complex cases, you may need to clean up your data and use ``concat``/``merge`` explicitly. @@ -392,9 +392,9 @@ def auto_combine(datasets, Dataset objects to merge. concat_dim : str or DataArray or Index, optional Dimension along which to concatenate variables, as used by - :py:func:`xarray.concat`. You only need to provide this argument if the - dimension along which you want to concatenate is not a dimension in - the original datasets, e.g., if you want to stack a collection of + :py:func:`xarray.concat`. You only need to provide this argument if + the dimension along which you want to concatenate is not a dimension + in the original datasets, e.g., if you want to stack a collection of 2D arrays along a third dimension. By default, xarray attempts to infer this argument by examining component files. Set ``concat_dim=None`` explicitly to disable diff --git a/xarray/core/common.py b/xarray/core/common.py index 2986301..1366d0f 100644 --- a/xarray/core/common.py +++ b/xarray/core/common.py @@ -91,7 +91,7 @@ def __complex__(self): return complex(self.values) def __long__(self): - return long(self.values) + return long(self.values) # flake8: noqa def __array__(self, dtype=None): return np.asarray(self.values, dtype=dtype) @@ -590,10 +590,9 @@ def resample(self, freq=None, dim=None, how=None, skipna=None, raise TypeError("Dimension name should be a string; " "was passed %r" % dim) group = DataArray(dim, [(dim.dims, dim)], name=RESAMPLE_DIM) - time_grouper = pd.TimeGrouper(freq=freq, closed=closed, - label=label, base=base) + grouper = pd.Grouper(freq=freq, closed=closed, label=label, base=base) resampler = self._resample_cls(self, group=group, dim=dim_name, - grouper=time_grouper, + grouper=grouper, resample_dim=RESAMPLE_DIM) return resampler @@ -609,15 +608,15 @@ def _resample_immediately(self, freq, dim, how, skipna, "calculations. Instead of passing 'dim' and " "'how=\"{how}\", instead consider using " ".resample({dim}=\"{freq}\").{how}() ".format( - dim=dim, freq=freq, how=how + dim=dim, freq=freq, how=how ), DeprecationWarning, stacklevel=3) if isinstance(dim, basestring): dim = self[dim] group = DataArray(dim, [(dim.dims, dim)], name=RESAMPLE_DIM) - time_grouper = pd.TimeGrouper(freq=freq, how=how, closed=closed, - label=label, base=base) - gb = self._groupby_cls(self, group, grouper=time_grouper) + grouper = pd.Grouper(freq=freq, how=how, closed=closed, label=label, + base=base) + gb = self._groupby_cls(self, group, grouper=grouper) if isinstance(how, basestring): f = getattr(gb, how) if how in ['first', 'last']: diff --git a/xarray/core/computation.py b/xarray/core/computation.py index e58b072..f151902 100644 --- a/xarray/core/computation.py +++ b/xarray/core/computation.py @@ -1,12 +1,11 @@ -"""Functions for applying functions that act on arrays to xarray's labeled data. +""" +Functions for applying functions that act on arrays to xarray's labeled data. NOT PUBLIC API. """ -import collections import functools import itertools import operator -import re import numpy as np @@ -36,6 +35,7 @@ class _UFuncSignature(object): output_core_dims : tuple[tuple] Core dimension names on each output variable. """ + def __init__(self, input_core_dims, output_core_dims=((),)): self.input_core_dims = tuple(tuple(a) for a in input_core_dims) self.output_core_dims = tuple(tuple(a) for a in output_core_dims) @@ -248,8 +248,8 @@ def assert_and_return_exact_match(all_keys): for keys in all_keys[1:]: if keys != first_keys: raise ValueError( - 'exact match required for all data variable names, but %r != %r' - % (keys, first_keys)) + 'exact match required for all data variable names, ' + 'but %r != %r' % (keys, first_keys)) return first_keys @@ -483,9 +483,10 @@ def broadcast_compat_data(variable, broadcast_dims, core_dims): set_old_dims = set(old_dims) missing_core_dims = [d for d in core_dims if d not in set_old_dims] if missing_core_dims: - raise ValueError('operand to apply_ufunc has required core dimensions ' - '%r, but some of these are missing on the input ' - 'variable: %r' % (list(core_dims), missing_core_dims)) + raise ValueError( + 'operand to apply_ufunc has required core dimensions %r, but ' + 'some of these are missing on the input variable: %r' + % (list(core_dims), missing_core_dims)) set_new_dims = set(new_dims) unexpected_dims = [d for d in old_dims if d not in set_new_dims] @@ -552,9 +553,11 @@ def apply_variable_ufunc(func, *args, **kwargs): input_dims = [broadcast_dims + dims for dims in signature.input_core_dims] numpy_func = func - func = lambda *arrays: _apply_with_dask_atop( - numpy_func, arrays, input_dims, output_dims, signature, - output_dtypes, output_sizes) + + def func(*arrays): + return _apply_with_dask_atop( + numpy_func, arrays, input_dims, output_dims, + signature, output_dtypes, output_sizes) elif dask == 'allowed': pass else: @@ -598,8 +601,8 @@ def _apply_with_dask_atop(func, args, input_dims, output_dims, signature, new_dims = signature.all_output_core_dims - signature.all_input_core_dims if any(dim not in output_sizes for dim in new_dims): raise ValueError("when using dask='parallelized' with apply_ufunc, " - 'output core dimensions not found on inputs must have ' - 'explicitly set sizes with ``output_sizes``: {}' + 'output core dimensions not found on inputs must ' + 'have explicitly set sizes with ``output_sizes``: {}' .format(new_dims)) for n, (data, core_dims) in enumerate( @@ -763,9 +766,9 @@ def apply_ufunc(func, *args, **kwargs): output_dtypes : list of dtypes, optional Optional list of output dtypes. Only used if dask='parallelized'. output_sizes : dict, optional - Optional mapping from dimension names to sizes for outputs. Only used if - dask='parallelized' and new dimensions (not found on inputs) appear on - outputs. + Optional mapping from dimension names to sizes for outputs. Only used + if dask='parallelized' and new dimensions (not found on inputs) appear + on outputs. Returns ------- @@ -845,7 +848,7 @@ def earth_mover_distance(first_samples, ---------- .. [1] http://docs.scipy.org/doc/numpy/reference/ufuncs.html .. [2] http://docs.scipy.org/doc/numpy/reference/c-api.generalized-ufuncs.html - """ + """ # noqa: E501 # don't error on that URL one line up from .groupby import GroupBy from .dataarray import DataArray from .variable import Variable diff --git a/xarray/core/coordinates.py b/xarray/core/coordinates.py index 4736118..60c01e8 100644 --- a/xarray/core/coordinates.py +++ b/xarray/core/coordinates.py @@ -5,11 +5,12 @@ from contextlib import contextmanager import pandas as pd -from . import formatting +from . import formatting, indexing from .utils import Frozen from .merge import ( merge_coords, expand_and_merge_variables, merge_coords_for_inplace_math) from .pycompat import OrderedDict +from .variable import Variable class AbstractCoordinates(Mapping, formatting.ReprMixin): @@ -106,7 +107,7 @@ def _merge_inplace(self, other): # don't include indexes in priority_vars, because we didn't align # first priority_vars = OrderedDict( - (k, v) for k, v in self.variables.items() if k not in self.dims) + kv for kv in self.variables.items() if kv[0] not in self.dims) variables = merge_coords_for_inplace_math( [self.variables, other.variables], priority_vars=priority_vars) yield @@ -151,6 +152,7 @@ class DatasetCoordinates(AbstractCoordinates): dimensions and the values given by the corresponding xarray.Coordinate objects. """ + def __init__(self, dataset): self._data = dataset @@ -209,6 +211,7 @@ class DataArrayCoordinates(AbstractCoordinates): Essentially an OrderedDict with keys given by the array's dimensions and the values given by corresponding DataArray objects. """ + def __init__(self, dataarray): self._data = dataarray @@ -255,6 +258,7 @@ class LevelCoordinatesSource(object): Used for attribute style lookup with AttrAccessMixin. Not returned directly by any public methods. """ + def __init__(self, data_object): self._data = data_object @@ -269,6 +273,7 @@ def __iter__(self): class Indexes(Mapping, formatting.ReprMixin): """Ordered Mapping[str, pandas.Index] for xarray objects. """ + def __init__(self, variables, sizes): """Not for public consumption. @@ -301,3 +306,54 @@ def __getitem__(self, key): def __unicode__(self): return formatting.indexes_repr(self) + + +def assert_coordinate_consistent(obj, coords): + """ Maeke sure the dimension coordinate of obj is + consistent with coords. + + obj: DataArray or Dataset + coords: Dict-like of variables + """ + for k in obj.dims: + # make sure there are no conflict in dimension coordinates + if k in coords and k in obj.coords: + if not coords[k].equals(obj[k].variable): + raise IndexError( + 'dimension coordinate {!r} conflicts between ' + 'indexed and indexing objects:\n{}\nvs.\n{}' + .format(k, obj[k], coords[k])) + + +def remap_label_indexers(obj, method=None, tolerance=None, **indexers): + """ + Remap **indexers from obj.coords. + If indexer is an instance of DataArray and it has coordinate, then this + coordinate will be attached to pos_indexers. + + Returns + ------- + pos_indexers: Same type of indexers. + np.ndarray or Variable or DataArra + new_indexes: mapping of new dimensional-coordinate. + """ + from .dataarray import DataArray + + v_indexers = {k: v.variable.data if isinstance(v, DataArray) else v + for k, v in indexers.items()} + + pos_indexers, new_indexes = indexing.remap_label_indexers( + obj, v_indexers, method=method, tolerance=tolerance + ) + # attach indexer's coordinate to pos_indexers + for k, v in indexers.items(): + if isinstance(v, Variable): + pos_indexers[k] = Variable(v.dims, pos_indexers[k]) + elif isinstance(v, DataArray): + # drop coordinates found in indexers since .sel() already + # ensures alignments + coords = OrderedDict((k, v) for k, v in v._coords.items() + if k not in indexers) + pos_indexers[k] = DataArray(pos_indexers[k], + coords=coords, dims=v.dims) + return pos_indexers, new_indexes diff --git a/xarray/core/dataarray.py b/xarray/core/dataarray.py index 0516b47..8e1ec8a 100644 --- a/xarray/core/dataarray.py +++ b/xarray/core/dataarray.py @@ -20,7 +20,8 @@ from .alignment import align, reindex_like_indexers from .common import AbstractArray, BaseDataObject from .coordinates import (DataArrayCoordinates, LevelCoordinatesSource, - Indexes) + Indexes, assert_coordinate_consistent, + remap_label_indexers) from .dataset import Dataset, merge_indexes, split_indexes from .pycompat import iteritems, basestring, OrderedDict, zip, range from .variable import (as_variable, Variable, as_compatible_data, @@ -102,22 +103,20 @@ class _LocIndexer(object): def __init__(self, data_array): self.data_array = data_array - def _remap_key(self, key): + def __getitem__(self, key): if not utils.is_dict_like(key): # expand the indexer so we can handle Ellipsis labels = indexing.expanded_indexer(key, self.data_array.ndim) key = dict(zip(self.data_array.dims, labels)) - return indexing.remap_label_indexers(self.data_array, key) + return self.data_array.sel(**key) - def __getitem__(self, key): + def __setitem__(self, key, value): if not utils.is_dict_like(key): # expand the indexer so we can handle Ellipsis labels = indexing.expanded_indexer(key, self.data_array.ndim) key = dict(zip(self.data_array.dims, labels)) - return self.data_array.sel(**key) - def __setitem__(self, key, value): - pos_indexers, _ = self._remap_key(key) + pos_indexers, _ = remap_label_indexers(self.data_array, **key) self.data_array[pos_indexers] = value @@ -317,7 +316,7 @@ def _to_dataset_whole(self, name=None, shallow_copy=True): if name in self.coords: raise ValueError('cannot create a Dataset from a DataArray with ' 'the same name as one of its coordinates') - # use private APIs here for speed: this is called by _to_temp_dataset(), + # use private APIs for speed: this is called by _to_temp_dataset(), # which is used in the guts of a lot of operations (e.g., reindex) variables = self._coords.copy() variables[name] = self.variable @@ -429,9 +428,9 @@ def to_index(self): def dims(self): """Tuple of dimension names associated with this array. - Note that the type of this property is inconsistent with `Dataset.dims`. - See `Dataset.sizes` and `DataArray.sizes` for consistently named - properties. + Note that the type of this property is inconsistent with + `Dataset.dims`. See `Dataset.sizes` and `DataArray.sizes` for + consistently named properties. """ return self.variable.dims @@ -484,7 +483,15 @@ def __setitem__(self, key, value): if isinstance(key, basestring): self.coords[key] = value else: - # xarray-style array indexing + # Coordinates in key, value and self[key] should be consistent. + # TODO Coordinate consistency in key is checked here, but it + # causes unnecessary indexing. It should be optimized. + obj = self[key] + if isinstance(value, DataArray): + assert_coordinate_consistent(value, obj.coords.variables) + # DataArray key -> Variable key + key = {k: v.variable if isinstance(v, DataArray) else v + for k, v in self._item_key_to_dict(key).items()} self.variable[key] = value def __delitem__(self, key): @@ -594,7 +601,7 @@ def __dask_optimize__(self): @property def __dask_scheduler__(self): - return self._to_temp_dataset().__dask_optimize__ + return self._to_temp_dataset().__dask_scheduler__ def __dask_postcompute__(self): func, args = self._to_temp_dataset().__dask_postcompute__() @@ -861,12 +868,11 @@ def reindex(self, method=None, tolerance=None, copy=True, **indexers): Maximum distance between original and new labels for inexact matches. The values of the index at the matching locations most satisfy the equation ``abs(index[indexer] - target) <= tolerance``. - Requires pandas>=0.17. **indexers : dict Dictionary with keys given by dimension names and values given by - arrays of coordinates tick labels. Any mis-matched coordinate values - will be filled in with NaN, and any mis-matched dimension names will - simply be ignored. + arrays of coordinates tick labels. Any mis-matched coordinate + values will be filled in with NaN, and any mis-matched dimension + names will simply be ignored. Returns ------- @@ -936,8 +942,8 @@ def swap_dims(self, dims_dict): return self._from_temp_dataset(ds) def expand_dims(self, dim, axis=None): - """Return a new object with an additional axis (or axes) inserted at the - corresponding position in the array shape. + """Return a new object with an additional axis (or axes) inserted at + the corresponding position in the array shape. If dim is already a scalar coordinate, it will be promoted to a 1D coordinate consisting of a single value. @@ -963,7 +969,8 @@ def expand_dims(self, dim, axis=None): return self._from_temp_dataset(ds) def set_index(self, append=False, inplace=False, **indexes): - """Set DataArray (multi-)indexes using one or more existing coordinates. + """Set DataArray (multi-)indexes using one or more existing + coordinates. Parameters ---------- @@ -971,8 +978,8 @@ def set_index(self, append=False, inplace=False, **indexes): If True, append the supplied index(es) to the existing index(es). Otherwise replace the existing index(es) (default). inplace : bool, optional - If True, set new index(es) in-place. Otherwise, return a new DataArray - object. + If True, set new index(es) in-place. Otherwise, return a new + DataArray object. **indexes : {dim: index, ...} Keyword arguments with names matching dimensions and values given by (lists of) the names of existing coordinates or variables to set @@ -981,7 +988,7 @@ def set_index(self, append=False, inplace=False, **indexes): Returns ------- obj : DataArray - Another dataarray, with this dataarray's data but replaced coordinates. + Another dataarray, with this data but replaced coordinates. See Also -------- @@ -1220,6 +1227,97 @@ def fillna(self, value): out = ops.fillna(self, value) return out + def interpolate_na(self, dim=None, method='linear', limit=None, + use_coordinate=True, + **kwargs): + """Interpolate values according to different methods. + + Parameters + ---------- + dim : str + Specifies the dimension along which to interpolate. + method : {'linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic', + 'polynomial', 'barycentric', 'krog', 'pchip', + 'spline', 'akima'}, optional + String indicating which method to use for interpolation: + + - 'linear': linear interpolation (Default). Additional keyword + arguments are passed to ``numpy.interp`` + - 'nearest', 'zero', 'slinear', 'quadratic', 'cubic', + 'polynomial': are passed to ``scipy.interpolate.interp1d``. If + method=='polynomial', the ``order`` keyword argument must also be + provided. + - 'barycentric', 'krog', 'pchip', 'spline', and `akima`: use their + respective``scipy.interpolate`` classes. + use_coordinate : boolean or str, default True + Specifies which index to use as the x values in the interpolation + formulated as `y = f(x)`. If False, values are treated as if + eqaully-spaced along `dim`. If True, the IndexVariable `dim` is + used. If use_coordinate is a string, it specifies the name of a + coordinate variariable to use as the index. + limit : int, default None + Maximum number of consecutive NaNs to fill. Must be greater than 0 + or None for no limit. + + Returns + ------- + DataArray + + See also + -------- + numpy.interp + scipy.interpolate + """ + from .missing import interp_na + return interp_na(self, dim=dim, method=method, limit=limit, + use_coordinate=use_coordinate, **kwargs) + + def ffill(self, dim, limit=None): + '''Fill NaN values by propogating values forward + + *Requires bottleneck.* + + Parameters + ---------- + dim : str + Specifies the dimension along which to propagate values when + filling. + limit : int, default None + The maximum number of consecutive NaN values to forward fill. In + other words, if there is a gap with more than this number of + consecutive NaNs, it will only be partially filled. Must be greater + than 0 or None for no limit. + + Returns + ------- + DataArray + ''' + from .missing import ffill + return ffill(self, dim, limit=limit) + + def bfill(self, dim, limit=None): + '''Fill NaN values by propogating values backward + + *Requires bottleneck.* + + Parameters + ---------- + dim : str + Specifies the dimension along which to propagate values when + filling. + limit : int, default None + The maximum number of consecutive NaN values to backward fill. In + other words, if there is a gap with more than this number of + consecutive NaNs, it will only be partially filled. Must be greater + than 0 or None for no limit. + + Returns + ------- + DataArray + ''' + from .missing import bfill + return bfill(self, dim, limit=limit) + def combine_first(self, other): """Combine two DataArray objects, with union of coordinates. @@ -1509,9 +1607,9 @@ def from_series(cls, series): """Convert a pandas.Series into an xarray.DataArray. If the series's index is a MultiIndex, it will be expanded into a - tensor product of one-dimensional coordinates (filling in missing values - with NaN). Thus this operation should be the inverse of the `to_series` - method. + tensor product of one-dimensional coordinates (filling in missing + values with NaN). Thus this operation should be the inverse of the + `to_series` method. """ # TODO: add a 'name' parameter name = series.name @@ -1532,6 +1630,19 @@ def from_cdms2(cls, variable): from ..convert import from_cdms2 return from_cdms2(variable) + def to_iris(self): + """Convert this array into a iris.cube.Cube + """ + from ..convert import to_iris + return to_iris(self) + + @classmethod + def from_iris(cls, cube): + """Convert a iris.cube.Cube into an xarray.DataArray + """ + from ..convert import from_iris + return from_iris(cube) + def _all_compat(self, other, compat_str): """Helper function for equals and identical""" @@ -1914,6 +2025,24 @@ def sortby(self, variables, ascending=True): sorted: DataArray A new dataarray where all the specified dims are sorted by dim labels. + + Examples + -------- + + >>> da = xr.DataArray(np.random.rand(5), + ... coords=[pd.date_range('1/1/2000', periods=5)], + ... dims='time') + >>> da + + array([ 0.965471, 0.615637, 0.26532 , 0.270962, 0.552878]) + Coordinates: + * time (time) datetime64[ns] 2000-01-01 2000-01-02 2000-01-03 ... + + >>> da.sortby(da) + + array([ 0.26532 , 0.270962, 0.552878, 0.615637, 0.965471]) + Coordinates: + * time (time) datetime64[ns] 2000-01-03 2000-01-04 2000-01-05 ... """ ds = self._to_temp_dataset().sortby(variables, ascending=ascending) return self._from_temp_dataset(ds) @@ -1960,8 +2089,47 @@ def quantile(self, q, dim=None, interpolation='linear', keep_attrs=False): numpy.nanpercentile, pandas.Series.quantile, Dataset.quantile """ - ds = self._to_temp_dataset().quantile(q, dim=dim, keep_attrs=keep_attrs, - interpolation=interpolation) + ds = self._to_temp_dataset().quantile( + q, dim=dim, keep_attrs=keep_attrs, interpolation=interpolation) + return self._from_temp_dataset(ds) + + def rank(self, dim, pct=False, keep_attrs=False): + """Ranks the data. + + Equal values are assigned a rank that is the average of the ranks that + would have been otherwise assigned to all of the values within that + set. Ranks begin at 1, not 0. If pct, computes percentage ranks. + + NaNs in the input array are returned as NaNs. + + The `bottleneck` library is required. + + Parameters + ---------- + dim : str + Dimension over which to compute rank. + pct : bool, optional + If True, compute percentage ranks, otherwise compute integer ranks. + keep_attrs : bool, optional + If True, the dataset's attributes (`attrs`) will be copied from + the original object to the new one. If False (default), the new + object will be returned without attributes. + + Returns + ------- + ranked : DataArray + DataArray with the same coordinates and dtype 'float64'. + + Examples + -------- + + >>> arr = xr.DataArray([5, 6, 7], dims='x') + >>> arr.rank('x') + + array([ 1., 2., 3.]) + Dimensions without coordinates: x + """ + ds = self._to_temp_dataset().rank(dim, pct=pct, keep_attrs=keep_attrs) return self._from_temp_dataset(ds) diff --git a/xarray/core/dataset.py b/xarray/core/dataset.py index 9c99213..62ad2b9 100644 --- a/xarray/core/dataset.py +++ b/xarray/core/dataset.py @@ -23,7 +23,8 @@ from . import duck_array_ops from .. import conventions from .alignment import align -from .coordinates import DatasetCoordinates, LevelCoordinatesSource, Indexes +from .coordinates import (DatasetCoordinates, LevelCoordinatesSource, Indexes, + assert_coordinate_consistent, remap_label_indexers) from .common import ImplementsDatasetReduce, BaseDataObject from .dtypes import is_datetime_like from .merge import (dataset_update_method, dataset_merge_method, @@ -1086,7 +1087,7 @@ def to_netcdf(self, path=None, mode='w', format=None, group=None, Write ('w') or append ('a') mode. If mode='w', any existing file at this location will be overwritten. If mode='a', existing variables will be overwritten. - format : {'NETCDF4', 'NETCDF4_CLASSIC', 'NETCDF3_64BIT', 'NETCDF3_CLASSIC'}, optional + format : {'NETCDF4', 'NETCDF4_CLASSIC', 'NETCDF3_64BIT','NETCDF3_CLASSIC'}, optional File format for the resulting netCDF file: * NETCDF4: Data is stored in an HDF5 file, using netCDF4 API @@ -1131,6 +1132,40 @@ def to_netcdf(self, path=None, mode='w', format=None, group=None, engine=engine, encoding=encoding, unlimited_dims=unlimited_dims) + def to_zarr(self, store=None, mode='w-', synchronizer=None, group=None, + encoding=None): + """Write dataset contents to a zarr group. + + .. note:: Experimental + The Zarr backend is new and experimental. Please report any + unexpected behavior via github issues. + + Parameters + ---------- + store : MutableMapping or str, optional + Store or path to directory in file system. + mode : {'w', 'w-'} + Persistence mode: 'w' means create (overwrite if exists); + 'w-' means create (fail if exists). + synchronizer : object, optional + Array synchronizer + group : str, obtional + Group path. (a.k.a. `path` in zarr terminology.) + encoding : dict, optional + Nested dictionary with variable names as keys and dictionaries of + variable specific encodings as values, e.g., + ``{'my_variable': {'dtype': 'int16', 'scale_factor': 0.1,}, ...}`` + """ + if encoding is None: + encoding = {} + if mode not in ['w', 'w-']: + # TODO: figure out how to handle 'r+' and 'a' + raise ValueError("The only supported options for mode are 'w' " + "and 'w-'.") + from ..backends.api import to_zarr + return to_zarr(self, store=store, mode=mode, synchronizer=synchronizer, + group=group, encoding=encoding) + def __unicode__(self): return formatting.dataset_repr(self) @@ -1217,7 +1252,7 @@ def chunk(self, chunks=None, name_prefix='xarray-', token=None, try: from dask.base import tokenize except ImportError: - import dask # raise the usual error if dask is entirely missing + import dask # raise the usual error if dask is entirely missing # flake8: noqa raise ImportError('xarray requires dask version 0.6 or newer') if isinstance(chunks, Number): @@ -1305,15 +1340,7 @@ def _get_indexers_coordinates(self, indexers): # we don't need to call align() explicitly, because merge_variables # already checks for exact alignment between dimension coordinates coords = merge_variables(coord_list) - - for k in self.dims: - # make sure there are not conflict in dimension coordinates - if (k in coords and k in self._variables and - not coords[k].equals(self._variables[k])): - raise IndexError( - 'dimension coordinate {!r} conflicts between ' - 'indexed and indexing objects:\n{}\nvs.\n{}' - .format(k, self._variables[k], coords[k])) + assert_coordinate_consistent(self, coords) attached_coords = OrderedDict() for k, v in coords.items(): # silently drop the conflicted variables. @@ -1437,25 +1464,8 @@ def sel(self, method=None, tolerance=None, drop=False, **indexers): Dataset.isel DataArray.sel """ - from .dataarray import DataArray - - v_indexers = {k: v.variable.data if isinstance(v, DataArray) else v - for k, v in indexers.items()} - - pos_indexers, new_indexes = indexing.remap_label_indexers( - self, v_indexers, method=method, tolerance=tolerance - ) - # attach indexer's coordinate to pos_indexers - for k, v in indexers.items(): - if isinstance(v, Variable): - pos_indexers[k] = Variable(v.dims, pos_indexers[k]) - elif isinstance(v, DataArray): - # drop coordinates found in indexers since .sel() already - # ensures alignments - coords = OrderedDict((k, v) for k, v in v._coords.items() - if k not in indexers) - pos_indexers[k] = DataArray(pos_indexers[k], - coords=coords, dims=v.dims) + pos_indexers, new_indexes = remap_label_indexers(self, method, + tolerance, **indexers) result = self.isel(drop=drop, **pos_indexers) return result._replace_indexes(new_indexes) @@ -1563,7 +1573,8 @@ def relevant_keys(mapping): dim_name = dim dim_coord = None - reordered = self.transpose(*(list(indexer_dims) + list(non_indexed_dims))) + reordered = self.transpose( + *(list(indexer_dims) + list(non_indexed_dims))) variables = OrderedDict() @@ -2400,6 +2411,105 @@ def fillna(self, value): out = ops.fillna(self, value) return out + def interpolate_na(self, dim=None, method='linear', limit=None, + use_coordinate=True, + **kwargs): + """Interpolate values according to different methods. + + Parameters + ---------- + dim : str + Specifies the dimension along which to interpolate. + method : {'linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic', + 'polynomial', 'barycentric', 'krog', 'pchip', + 'spline'}, optional + String indicating which method to use for interpolation: + + - 'linear': linear interpolation (Default). Additional keyword + arguments are passed to ``numpy.interp`` + - 'nearest', 'zero', 'slinear', 'quadratic', 'cubic', + 'polynomial': are passed to ``scipy.interpolate.interp1d``. If + method=='polynomial', the ``order`` keyword argument must also be + provided. + - 'barycentric', 'krog', 'pchip', 'spline': use their respective + ``scipy.interpolate`` classes. + use_coordinate : boolean or str, default True + Specifies which index to use as the x values in the interpolation + formulated as `y = f(x)`. If False, values are treated as if + eqaully-spaced along `dim`. If True, the IndexVariable `dim` is + used. If use_coordinate is a string, it specifies the name of a + coordinate variariable to use as the index. + limit : int, default None + Maximum number of consecutive NaNs to fill. Must be greater than 0 + or None for no limit. + + Returns + ------- + Dataset + + See also + -------- + numpy.interp + scipy.interpolate + """ + from .missing import interp_na, _apply_over_vars_with_dim + + new = _apply_over_vars_with_dim(interp_na, self, dim=dim, + method=method, limit=limit, + use_coordinate=use_coordinate, + **kwargs) + return new + + def ffill(self, dim, limit=None): + '''Fill NaN values by propogating values forward + + *Requires bottleneck.* + + Parameters + ---------- + dim : str + Specifies the dimension along which to propagate values when + filling. + limit : int, default None + The maximum number of consecutive NaN values to forward fill. In + other words, if there is a gap with more than this number of + consecutive NaNs, it will only be partially filled. Must be greater + than 0 or None for no limit. + + Returns + ------- + Dataset + ''' + from .missing import ffill, _apply_over_vars_with_dim + + new = _apply_over_vars_with_dim(ffill, self, dim=dim, limit=limit) + return new + + def bfill(self, dim, limit=None): + '''Fill NaN values by propogating values backward + + *Requires bottleneck.* + + Parameters + ---------- + dim : str + Specifies the dimension along which to propagate values when + filling. + limit : int, default None + The maximum number of consecutive NaN values to backward fill. In + other words, if there is a gap with more than this number of + consecutive NaNs, it will only be partially filled. Must be greater + than 0 or None for no limit. + + Returns + ------- + Dataset + ''' + from .missing import bfill, _apply_over_vars_with_dim + + new = _apply_over_vars_with_dim(bfill, self, dim=dim, limit=limit) + return new + def combine_first(self, other): """Combine two Datasets, default to data_vars of self. @@ -3246,6 +3356,49 @@ def quantile(self, q, dim=None, interpolation='linear', new.coords['quantile'] = q return new + def rank(self, dim, pct=False, keep_attrs=False): + """Ranks the data. + + Equal values are assigned a rank that is the average of the ranks that + would have been otherwise assigned to all of the values within that set. + Ranks begin at 1, not 0. If pct is True, computes percentage ranks. + + NaNs in the input array are returned as NaNs. + + The `bottleneck` library is required. + + Parameters + ---------- + dim : str + Dimension over which to compute rank. + pct : bool, optional + If True, compute percentage ranks, otherwise compute integer ranks. + keep_attrs : bool, optional + If True, the dataset's attributes (`attrs`) will be copied from + the original object to the new one. If False (default), the new + object will be returned without attributes. + + Returns + ------- + ranked : Dataset + Variables that do not depend on `dim` are dropped. + """ + if dim not in self.dims: + raise ValueError( + 'Dataset does not contain the dimension: %s' % dim) + + variables = OrderedDict() + for name, var in iteritems(self.variables): + if name in self.data_vars: + if dim in var.dims: + variables[name] = var.rank(dim, pct=pct) + else: + variables[name] = var + + coord_names = set(self.coords) + attrs = self.attrs if keep_attrs else None + return self._replace_vars_and_dims(variables, coord_names, attrs=attrs) + @property def real(self): return self._unary_op(lambda x: x.real, keep_attrs=True)(self) diff --git a/xarray/core/dtypes.py b/xarray/core/dtypes.py index 0578611..ccbe48e 100644 --- a/xarray/core/dtypes.py +++ b/xarray/core/dtypes.py @@ -20,13 +20,15 @@ def maybe_promote(dtype): fill_value : Valid missing value for the promoted dtype. """ # N.B. these casting rules should match pandas - if np.issubdtype(dtype, float): + if np.issubdtype(dtype, np.floating): fill_value = np.nan - elif np.issubdtype(dtype, int): - # convert to floating point so NaN is valid - dtype = float + elif np.issubdtype(dtype, np.integer): + if dtype.itemsize <= 2: + dtype = np.float32 + else: + dtype = np.float64 fill_value = np.nan - elif np.issubdtype(dtype, complex): + elif np.issubdtype(dtype, np.complexfloating): fill_value = np.nan + np.nan * 1j elif np.issubdtype(dtype, np.datetime64): fill_value = np.datetime64('NaT') diff --git a/xarray/core/duck_array_ops.py b/xarray/core/duck_array_ops.py index 2f97de4..2058ce8 100644 --- a/xarray/core/duck_array_ops.py +++ b/xarray/core/duck_array_ops.py @@ -175,11 +175,11 @@ def _create_nan_agg_method(name, numeric_only=False, np_compat=False, no_bottleneck=False, coerce_strings=False, keep_dims=False): def f(values, axis=None, skipna=None, **kwargs): - # ignore keyword args inserted by np.mean and other numpy aggregators - # automatically: - kwargs.pop('dtype', None) - kwargs.pop('out', None) + if kwargs.pop('out', None) is not None: + raise TypeError('`out` is not valid for {}'.format(name)) + # If dtype is supplied, we use numpy's method. + dtype = kwargs.get('dtype', None) values = asarray(values) if coerce_strings and values.dtype.kind in 'SU': @@ -192,7 +192,8 @@ def f(values, axis=None, skipna=None, **kwargs): % (name, values.dtype)) nanname = 'nan' + name if (isinstance(axis, tuple) or not values.dtype.isnative or - no_bottleneck): + no_bottleneck or + (dtype is not None and np.dtype(dtype) != values.dtype)): # bottleneck can't handle multiple axis arguments or non-native # endianness if np_compat: @@ -200,6 +201,7 @@ def f(values, axis=None, skipna=None, **kwargs): else: eager_module = np else: + kwargs.pop('dtype', None) eager_module = bn func = _dask_or_eager_func(nanname, eager_module) using_numpy_nan_func = (eager_module is np or diff --git a/xarray/core/extensions.py b/xarray/core/extensions.py index affb55b..90639e4 100644 --- a/xarray/core/extensions.py +++ b/xarray/core/extensions.py @@ -15,6 +15,7 @@ class AccessorRegistrationWarning(Warning): class _CachedAccessor(object): """Custom property-like object (descriptor) for caching accessors.""" + def __init__(self, name, accessor): self._name = name self._accessor = accessor @@ -26,9 +27,9 @@ def __get__(self, obj, cls): try: accessor_obj = self._accessor(obj) except AttributeError: - # __getattr__ on data object will swallow any AttributeErrors raised - # when initializing the accessor, so we need to raise as something - # else (GH933): + # __getattr__ on data object will swallow any AttributeErrors + # raised when initializing the accessor, so we need to raise as + # something else (GH933): msg = 'error initializing %r accessor.' % self._name if PY2: msg += ' Full traceback:\n' + traceback.format_exc() diff --git a/xarray/core/formatting.py b/xarray/core/formatting.py index 6f91f73..83f8e27 100644 --- a/xarray/core/formatting.py +++ b/xarray/core/formatting.py @@ -21,7 +21,6 @@ from .options import OPTIONS from .pycompat import PY2, unicode_type, bytes_type, dask_array_type -from .indexing import BasicIndexer def pretty_print(x, numchars): @@ -60,6 +59,7 @@ def ensure_valid_repr(string): class ReprMixin(object): """Mixin that defines __repr__ for a class that already has __unicode__.""" + def __repr__(self): return ensure_valid_repr(self.__unicode__()) diff --git a/xarray/core/groupby.py b/xarray/core/groupby.py index b299380..c4b2574 100644 --- a/xarray/core/groupby.py +++ b/xarray/core/groupby.py @@ -80,9 +80,9 @@ def _consolidate_slices(slices): for slice_ in slices: if not isinstance(slice_, slice): raise ValueError('list element is not a slice: %r' % slice_) - if (result and last_slice.stop == slice_.start - and _is_one_or_none(last_slice.step) - and _is_one_or_none(slice_.step)): + if (result and last_slice.stop == slice_.start and + _is_one_or_none(last_slice.step) and + _is_one_or_none(slice_.step)): last_slice = slice(last_slice.start, slice_.stop, slice_.step) result[-1] = last_slice else: @@ -172,6 +172,7 @@ class GroupBy(object): Dataset.groupby DataArray.groupby """ + def __init__(self, obj, group, squeeze=False, grouper=None, bins=None, cut_kwargs={}): """Create a GroupBy object @@ -441,6 +442,7 @@ def _maybe_reorder(xarray_obj, dim, positions): class DataArrayGroupBy(GroupBy, ImplementsArrayReduce): """GroupBy object specialized to grouping DataArray objects """ + def _iter_grouped_shortcut(self): """Fast version of `_iter_grouped` that yields Variables without metadata @@ -548,8 +550,8 @@ def reduce(self, func, dim=None, axis=None, keep_attrs=False, ---------- func : function Function which can be called in the form - `func(x, axis=axis, **kwargs)` to return the result of collapsing an - np.ndarray over an integer valued axis. + `func(x, axis=axis, **kwargs)` to return the result of collapsing + an np.ndarray over an integer valued axis. dim : str or sequence of str, optional Dimension(s) over which to apply `func`. axis : int or sequence of int, optional @@ -573,6 +575,7 @@ def reduce_array(ar): return ar.reduce(func, dim, axis, keep_attrs=keep_attrs, **kwargs) return self.apply(reduce_array, shortcut=shortcut) + ops.inject_reduce_methods(DataArrayGroupBy) ops.inject_binary_ops(DataArrayGroupBy) @@ -629,8 +632,8 @@ def reduce(self, func, dim=None, keep_attrs=False, **kwargs): ---------- func : function Function which can be called in the form - `func(x, axis=axis, **kwargs)` to return the result of collapsing an - np.ndarray over an integer valued axis. + `func(x, axis=axis, **kwargs)` to return the result of collapsing + an np.ndarray over an integer valued axis. dim : str or sequence of str, optional Dimension(s) over which to apply `func`. axis : int or sequence of int, optional @@ -663,5 +666,6 @@ def assign(self, **kwargs): """ return self.apply(lambda ds: ds.assign(**kwargs)) + ops.inject_reduce_methods(DatasetGroupBy) ops.inject_binary_ops(DatasetGroupBy) diff --git a/xarray/core/indexing.py b/xarray/core/indexing.py index 3aea8ca..e06b045 100644 --- a/xarray/core/indexing.py +++ b/xarray/core/indexing.py @@ -3,12 +3,14 @@ from __future__ import print_function from datetime import timedelta from collections import defaultdict, Hashable +import functools import operator import numpy as np import pandas as pd from . import nputils from . import utils +from . import duck_array_ops from .pycompat import (iteritems, range, integer_types, dask_array_type, suppress) from .utils import is_dict_like @@ -74,9 +76,9 @@ def _asarray_tuplesafe(values): def _is_nested_tuple(possible_tuple): - return (isinstance(possible_tuple, tuple) - and any(isinstance(value, (tuple, list, slice)) - for value in possible_tuple)) + return (isinstance(possible_tuple, tuple) and + any(isinstance(value, (tuple, list, slice)) + for value in possible_tuple)) def _index_method_kwargs(method, tolerance): @@ -123,8 +125,8 @@ def convert_label_indexer(index, label, index_name='', method=None, _try_get_item(label.stop), _try_get_item(label.step)) if not isinstance(indexer, slice): - # unlike pandas, in xarray we never want to silently convert a slice - # indexer into an array indexer + # unlike pandas, in xarray we never want to silently convert a + # slice indexer into an array indexer raise KeyError('cannot represent labeled-based slice indexer for ' 'dimension %r with a slice over integer positions; ' 'the index is unsorted or non-unique' % index_name) @@ -132,8 +134,8 @@ def convert_label_indexer(index, label, index_name='', method=None, elif is_dict_like(label): is_nested_vals = _is_nested_tuple(tuple(label.values())) if not isinstance(index, pd.MultiIndex): - raise ValueError('cannot use a dict-like object for selection on a ' - 'dimension that does not have a MultiIndex') + raise ValueError('cannot use a dict-like object for selection on ' + 'a dimension that does not have a MultiIndex') elif len(label) == index.nlevels and not is_nested_vals: indexer = index.get_loc(tuple((label[k] for k in index.names))) else: @@ -143,7 +145,7 @@ def convert_label_indexer(index, label, index_name='', method=None, raise ValueError('Vectorized selection is not ' 'available along level variable: ' + k) indexer, new_index = index.get_loc_level( - tuple(label.values()), level=tuple(label.keys())) + tuple(label.values()), level=tuple(label.keys())) elif isinstance(label, tuple) and isinstance(index, pd.MultiIndex): if _is_nested_tuple(label): @@ -288,6 +290,7 @@ class ExplicitIndexer(object): Do not instantiate BaseIndexer objects directly: instead, use one of the sub-classes BasicIndexer, OuterIndexer or VectorizedIndexer. """ + def __init__(self, key): if type(self) is ExplicitIndexer: raise TypeError('cannot instantiate base ExplicitIndexer objects') @@ -319,6 +322,7 @@ class BasicIndexer(ExplicitIndexer): rules for basic indexing: each axis is independently sliced and axes indexed with an integer are dropped from the result. """ + def __init__(self, key): if not isinstance(key, tuple): raise TypeError('key must be a tuple: {!r}'.format(key)) @@ -345,6 +349,7 @@ class OuterIndexer(ExplicitIndexer): axes indexed with an integer are dropped from the result. This type of indexing works like MATLAB/Fortran. """ + def __init__(self, key): if not isinstance(key, tuple): raise TypeError('key must be a tuple: {!r}'.format(key)) @@ -376,16 +381,18 @@ class VectorizedIndexer(ExplicitIndexer): """Tuple for vectorized indexing. All elements should be slice or N-dimensional np.ndarray objects with an - integer dtype. Indexing follows proposed rules for np.ndarray.vindex, which - matches NumPy's advanced indexing rules (including broadcasting) except - sliced axes are always moved to the end: + integer dtype and the same number of dimensions. Indexing follows proposed + rules for np.ndarray.vindex, which matches NumPy's advanced indexing rules + (including broadcasting) except sliced axes are always moved to the end: https://github.com/numpy/numpy/pull/6256 """ + def __init__(self, key): if not isinstance(key, tuple): raise TypeError('key must be a tuple: {!r}'.format(key)) new_key = [] + ndim = None for k in key: if isinstance(k, slice): k = as_integer_slice(k) @@ -393,6 +400,13 @@ def __init__(self, key): if not np.issubdtype(k.dtype, np.integer): raise TypeError('invalid indexer array, does not have ' 'integer dtype: {!r}'.format(k)) + if ndim is None: + ndim = k.ndim + elif ndim != k.ndim: + ndims = [k.ndim for k in key if isinstance(k, np.ndarray)] + raise ValueError('invalid indexer key: ndarray arguments ' + 'have different numbers of dimensions: {}' + .format(ndims)) k = np.asarray(k, dtype=np.int64) else: raise TypeError('unexpected indexer type for {}: {!r}' @@ -448,6 +462,7 @@ def __getitem__(self, key): class LazilyIndexedArray(ExplicitlyIndexedNDArrayMixin): """Wrap an array to make basic and orthogonal indexing lazy. """ + def __init__(self, array, key=None): """ Parameters @@ -581,27 +596,23 @@ def as_indexable(array): raise TypeError('Invalid array type: {}'.format(type(array))) -def _outer_to_numpy_indexer(key, shape): - """Convert an OuterIndexer into an indexer for NumPy. +def _outer_to_vectorized_indexer(key, shape): + """Convert an OuterIndexer into an vectorized indexer. Parameters ---------- key : tuple - Outer indexing tuple to convert. + Tuple from an OuterIndexer to convert. shape : tuple Shape of the array subject to the indexing. Returns ------- tuple - Base tuple suitable for use to index a NumPy array. + Tuple suitable for use to index a NumPy array with vectorized indexing. + Each element is an integer or array: broadcasting them together gives + the shape of the result. """ - if len([k for k in key if not isinstance(k, slice)]) <= 1: - # If there is only one vector and all others are slice, - # it can be safely used in mixed basic/advanced indexing. - # Boolean index should already be converted to integer array. - return tuple(key) - n_dim = len([k for k in key if not isinstance(k, integer_types)]) i_dim = 0 new_key = [] @@ -619,6 +630,149 @@ def _outer_to_numpy_indexer(key, shape): return tuple(new_key) +def _outer_to_numpy_indexer(key, shape): + """Convert an OuterIndexer into an indexer for NumPy. + + Parameters + ---------- + key : tuple + Tuple from an OuterIndexer to convert. + shape : tuple + Shape of the array subject to the indexing. + + Returns + ------- + tuple + Tuple suitable for use to index a NumPy array. + """ + if len([k for k in key if not isinstance(k, slice)]) <= 1: + # If there is only one vector and all others are slice, + # it can be safely used in mixed basic/advanced indexing. + # Boolean index should already be converted to integer array. + return tuple(key) + else: + return _outer_to_vectorized_indexer(key, shape) + + +def _dask_array_with_chunks_hint(array, chunks): + """Create a dask array using the chunks hint for dimensions of size > 1.""" + import dask.array as da + if len(chunks) < array.ndim: + raise ValueError('not enough chunks in hint') + new_chunks = [] + for chunk, size in zip(chunks, array.shape): + new_chunks.append(chunk if size > 1 else (1,)) + return da.from_array(array, new_chunks) + + +def _logical_any(args): + return functools.reduce(operator.or_, args) + + +def _masked_result_drop_slice(key, chunks_hint=None): + key = (k for k in key if not isinstance(k, slice)) + if chunks_hint is not None: + key = [_dask_array_with_chunks_hint(k, chunks_hint) + if isinstance(k, np.ndarray) else k + for k in key] + return _logical_any(k == -1 for k in key) + + +def create_mask(indexer, shape, chunks_hint=None): + """Create a mask for indexing with a fill-value. + + Parameters + ---------- + indexer : ExplicitIndexer + Indexer with -1 in integer or ndarray value to indicate locations in + the result that should be masked. + shape : tuple + Shape of the array being indexed. + chunks_hint : tuple, optional + Optional tuple indicating desired chunks for the result. If provided, + used as a hint for chunks on the resulting dask. Must have a hint for + each dimension on the result array. + + Returns + ------- + mask : bool, np.ndarray or dask.array.Array with dtype=bool + Dask array if chunks_hint is provided, otherwise a NumPy array. Has the + same shape as the indexing result. + """ + if isinstance(indexer, OuterIndexer): + key = _outer_to_vectorized_indexer(indexer.tuple, shape) + assert not any(isinstance(k, slice) for k in key) + mask = _masked_result_drop_slice(key, chunks_hint) + + elif isinstance(indexer, VectorizedIndexer): + key = indexer.tuple + base_mask = _masked_result_drop_slice(key, chunks_hint) + slice_shape = tuple(np.arange(*k.indices(size)).size + for k, size in zip(key, shape) + if isinstance(k, slice)) + expanded_mask = base_mask[ + (Ellipsis,) + (np.newaxis,) * len(slice_shape)] + mask = duck_array_ops.broadcast_to( + expanded_mask, base_mask.shape + slice_shape) + + elif isinstance(indexer, BasicIndexer): + mask = any(k == -1 for k in indexer.tuple) + + else: + raise TypeError('unexpected key type: {}'.format(type(indexer))) + + return mask + + +def _posify_mask_subindexer(index): + """Convert masked indices in a flat array to the nearest unmasked index. + + Parameters + ---------- + index : np.ndarray + One dimensional ndarray with dtype=int. + + Returns + ------- + np.ndarray + One dimensional ndarray with all values equal to -1 replaced by an + adjacent non-masked element. + """ + masked = index == -1 + unmasked_locs = np.flatnonzero(~masked) + if not unmasked_locs.size: + # indexing unmasked_locs is invalid + return np.zeros_like(index) + masked_locs = np.flatnonzero(masked) + prev_value = np.maximum(0, np.searchsorted(unmasked_locs, masked_locs) - 1) + new_index = index.copy() + new_index[masked_locs] = index[unmasked_locs[prev_value]] + return new_index + + +def posify_mask_indexer(indexer): + """Convert masked values (-1) in an indexer to nearest unmasked values. + + This routine is useful for dask, where it can be much faster to index + adjacent points than arbitrary points from the end of an array. + + Parameters + ---------- + indexer : ExplicitIndexer + Input indexer. + + Returns + ------- + ExplicitIndexer + Same type of input, with all values in ndarray keys equal to -1 + replaced by an adjacent non-masked element. + """ + key = tuple(_posify_mask_subindexer(k.ravel()).reshape(k.shape) + if isinstance(k, np.ndarray) else k + for k in indexer.tuple) + return type(indexer)(key) + + class NumpyIndexingAdapter(ExplicitlyIndexedNDArrayMixin): """Wrap a NumPy array to use explicit indexing.""" @@ -725,7 +879,7 @@ def __array__(self, dtype=None): if isinstance(array, pd.PeriodIndex): with suppress(AttributeError): # this might not be public API - array = array.asobject + array = array.astype('object') return np.asarray(array.values, dtype=dtype) @property diff --git a/xarray/core/merge.py b/xarray/core/merge.py index be11be2..c5e643a 100644 --- a/xarray/core/merge.py +++ b/xarray/core/merge.py @@ -507,8 +507,9 @@ def merge(objects, compat='no_conflicts', join='outer'): from .dataarray import DataArray from .dataset import Dataset - dict_like_objects = [obj.to_dataset() if isinstance(obj, DataArray) else obj - for obj in objects] + dict_like_objects = [ + obj.to_dataset() if isinstance(obj, DataArray) else obj + for obj in objects] variables, coord_names, dims = merge_core(dict_like_objects, compat, join) merged = Dataset._construct_direct(variables, coord_names, dims) @@ -549,4 +550,5 @@ def dataset_merge_method(dataset, other, overwrite_vars, compat, join): def dataset_update_method(dataset, other): """Guts of the Dataset.update method""" - return merge_core([dataset, other], priority_arg=1, indexes=dataset.indexes) + return merge_core([dataset, other], priority_arg=1, + indexes=dataset.indexes) diff --git a/xarray/core/missing.py b/xarray/core/missing.py new file mode 100644 index 0000000..e26e976 --- /dev/null +++ b/xarray/core/missing.py @@ -0,0 +1,332 @@ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from collections import Iterable +from functools import partial + +import numpy as np +import pandas as pd + + +from .pycompat import iteritems +from .computation import apply_ufunc +from .utils import is_scalar +from .npcompat import flip + + +class BaseInterpolator(object): + '''gerneric interpolator class for normalizing interpolation methods''' + cons_kwargs = {} + call_kwargs = {} + f = None + method = None + + def __init__(self, xi, yi, method=None, **kwargs): + self.method = method + self.call_kwargs = kwargs + + def __call__(self, x): + return self.f(x, **self.call_kwargs) + + def __repr__(self): + return "{type}: method={method}".format(type=self.__class__.__name__, + method=self.method) + + +class NumpyInterpolator(BaseInterpolator): + '''One-dimensional linear interpolation. + + See Also + -------- + numpy.interp + ''' + + def __init__(self, xi, yi, method='linear', fill_value=None, **kwargs): + + if method != 'linear': + raise ValueError( + 'only method `linear` is valid for the NumpyInterpolator') + + self.method = method + self.f = np.interp + self.cons_kwargs = kwargs + self.call_kwargs = {'period': self.cons_kwargs.pop('period', None)} + + self._xi = xi + self._yi = yi + + if self.cons_kwargs: + raise ValueError( + 'recieved invalid kwargs: %r' % self.cons_kwargs.keys()) + + if fill_value is None: + self._left = np.nan + self._right = np.nan + elif isinstance(fill_value, Iterable) and len(fill_value) == 2: + self._left = fill_value[0] + self._right = fill_value[1] + elif is_scalar(fill_value): + self._left = fill_value + self._right = fill_value + else: + raise ValueError('%s is not a valid fill_value' % fill_value) + + def __call__(self, x): + return self.f(x, self._xi, self._yi, left=self._left, + right=self._right, **self.call_kwargs) + + +class ScipyInterpolator(BaseInterpolator): + '''Interpolate a 1-D function using Scipy interp1d + + See Also + -------- + scipy.interpolate.interp1d + ''' + + def __init__(self, xi, yi, method=None, fill_value=None, + assume_sorted=True, copy=False, bounds_error=False, **kwargs): + from scipy.interpolate import interp1d + + if method is None: + raise ValueError('method is a required argument, please supply a ' + 'valid scipy.inter1d method (kind)') + + if method == 'polynomial': + method = kwargs.pop('order', None) + if method is None: + raise ValueError('order is required when method=polynomial') + + self.method = method + + self.cons_kwargs = kwargs + self.call_kwargs = {} + + if fill_value is None and method == 'linear': + fill_value = kwargs.pop('fill_value', (np.nan, np.nan)) + elif fill_value is None: + fill_value = np.nan + + self.f = interp1d(xi, yi, kind=self.method, fill_value=fill_value, + bounds_error=False, assume_sorted=assume_sorted, + copy=copy, **self.cons_kwargs) + + +class SplineInterpolator(BaseInterpolator): + '''One-dimensional smoothing spline fit to a given set of data points. + + See Also + -------- + scipy.interpolate.UnivariateSpline + ''' + + def __init__(self, xi, yi, method='spline', fill_value=None, order=3, + **kwargs): + from scipy.interpolate import UnivariateSpline + + if method != 'spline': + raise ValueError( + 'only method `spline` is valid for the SplineInterpolator') + + self.method = method + self.cons_kwargs = kwargs + self.call_kwargs['nu'] = kwargs.pop('nu', 0) + self.call_kwargs['ext'] = kwargs.pop('ext', None) + + if fill_value is not None: + raise ValueError('SplineInterpolator does not support fill_value') + + self.f = UnivariateSpline(xi, yi, k=order, **self.cons_kwargs) + + +def _apply_over_vars_with_dim(func, self, dim=None, **kwargs): + '''wrapper for datasets''' + + ds = type(self)(coords=self.coords, attrs=self.attrs) + + for name, var in iteritems(self.data_vars): + if dim in var.dims: + ds[name] = func(var, dim=dim, **kwargs) + else: + ds[name] = var + + return ds + + +def get_clean_interp_index(arr, dim, use_coordinate=True, **kwargs): + '''get index to use for x values in interpolation. + + If use_coordinate is True, the coordinate that shares the name of the + dimension along which interpolation is being performed will be used as the + x values. + + If use_coordinate is False, the x values are set as an equally spaced + sequence. + ''' + if use_coordinate: + if use_coordinate is True: + index = arr.get_index(dim) + else: + index = arr.coords[use_coordinate] + if index.ndim != 1: + raise ValueError( + 'Coordinates used for interpolation must be 1D, ' + '%s is %dD.' % (use_coordinate, index.ndim)) + + # raise if index cannot be cast to a float (e.g. MultiIndex) + try: + index = index.values.astype(np.float64) + except (TypeError, ValueError): + # pandas raises a TypeError + # xarray/nuppy raise a ValueError + raise TypeError('Index must be castable to float64 to support' + 'interpolation, got: %s' % type(index)) + # check index sorting now so we can skip it later + if not (np.diff(index) > 0).all(): + raise ValueError("Index must be monotonicly increasing") + else: + axis = arr.get_axis_num(dim) + index = np.arange(arr.shape[axis], dtype=np.float64) + + return index + + +def interp_na(self, dim=None, use_coordinate=True, method='linear', limit=None, + **kwargs): + '''Interpolate values according to different methods.''' + + if dim is None: + raise NotImplementedError('dim is a required argument') + + if limit is not None: + valids = _get_valid_fill_mask(self, dim, limit) + + # method + index = get_clean_interp_index(self, dim, use_coordinate=use_coordinate, + **kwargs) + interpolator = _get_interpolator(method, **kwargs) + + arr = apply_ufunc(interpolator, index, self, + input_core_dims=[[dim], [dim]], + output_core_dims=[[dim]], + output_dtypes=[self.dtype], + dask='parallelized', + vectorize=True, + keep_attrs=True).transpose(*self.dims) + + if limit is not None: + arr = arr.where(valids) + + return arr + + +def wrap_interpolator(interpolator, x, y, **kwargs): + '''helper function to apply interpolation along 1 dimension''' + # it would be nice if this wasn't necessary, works around: + # "ValueError: assignment destination is read-only" in assignment below + out = y.copy() + + nans = pd.isnull(y) + nonans = ~nans + + # fast track for no-nans and all-nans cases + n_nans = nans.sum() + if n_nans == 0 or n_nans == len(y): + return y + + f = interpolator(x[nonans], y[nonans], **kwargs) + out[nans] = f(x[nans]) + return out + + +def _bfill(arr, n=None, axis=-1): + '''inverse of ffill''' + import bottleneck as bn + + arr = flip(arr, axis=axis) + + # fill + arr = bn.push(arr, axis=axis, n=n) + + # reverse back to original + return flip(arr, axis=axis) + + +def ffill(arr, dim=None, limit=None): + '''forward fill missing values''' + import bottleneck as bn + + axis = arr.get_axis_num(dim) + + # work around for bottleneck 178 + _limit = limit if limit is not None else arr.shape[axis] + + return apply_ufunc(bn.push, arr, + dask='parallelized', + keep_attrs=True, + output_dtypes=[arr.dtype], + kwargs=dict(n=_limit, axis=axis)).transpose(*arr.dims) + + +def bfill(arr, dim=None, limit=None): + '''backfill missing values''' + axis = arr.get_axis_num(dim) + + # work around for bottleneck 178 + _limit = limit if limit is not None else arr.shape[axis] + + return apply_ufunc(_bfill, arr, + dask='parallelized', + keep_attrs=True, + output_dtypes=[arr.dtype], + kwargs=dict(n=_limit, axis=axis)).transpose(*arr.dims) + + +def _get_interpolator(method, **kwargs): + '''helper function to select the appropriate interpolator class + + returns a partial of wrap_interpolator + ''' + interp1d_methods = ['linear', 'nearest', 'zero', 'slinear', 'quadratic', + 'cubic', 'polynomial'] + valid_methods = interp1d_methods + ['barycentric', 'krog', 'pchip', + 'spline', 'akima'] + + if (method == 'linear' and not + kwargs.get('fill_value', None) == 'extrapolate'): + kwargs.update(method=method) + interp_class = NumpyInterpolator + elif method in valid_methods: + try: + from scipy import interpolate + except ImportError: + raise ImportError( + 'Interpolation with method `%s` requires scipy' % method) + if method in interp1d_methods: + kwargs.update(method=method) + interp_class = ScipyInterpolator + elif method == 'barycentric': + interp_class = interpolate.BarycentricInterpolator + elif method == 'krog': + interp_class = interpolate.KroghInterpolator + elif method == 'pchip': + interp_class = interpolate.PchipInterpolator + elif method == 'spline': + kwargs.update(method=method) + interp_class = SplineInterpolator + elif method == 'akima': + interp_class = interpolate.Akima1DInterpolator + else: + raise ValueError('%s is not a valid scipy interpolator' % method) + else: + raise ValueError('%s is not a valid interpolator' % method) + + return partial(wrap_interpolator, interp_class, **kwargs) + + +def _get_valid_fill_mask(arr, dim, limit): + '''helper function to determine values that can be filled when limit is not + None''' + kw = {dim: limit + 1} + return arr.isnull().rolling(min_periods=1, **kw).sum() <= limit diff --git a/xarray/core/npcompat.py b/xarray/core/npcompat.py index fc080c6..bbe7b74 100644 --- a/xarray/core/npcompat.py +++ b/xarray/core/npcompat.py @@ -4,7 +4,7 @@ import numpy as np try: - from numpy import nancumsum, nancumprod + from numpy import nancumsum, nancumprod, flip except ImportError: # pragma: no cover # Code copied from newer versions of NumPy (v1.12). # Used under the terms of NumPy's license, see licenses/NUMPY_LICENSE. @@ -33,8 +33,8 @@ def _replace_nan(a, val): If `a` is of inexact type, return a copy of `a` with the NaNs replaced by the fill value, otherwise return `a`. mask: {bool, None} - If `a` is of inexact type, return a boolean mask marking locations of - NaNs, otherwise return None. + If `a` is of inexact type, return a boolean mask marking locations + of NaNs, otherwise return None. """ is_new = not isinstance(a, np.ndarray) @@ -174,3 +174,74 @@ def nancumprod(a, axis=None, dtype=None, out=None): """ a, mask = _replace_nan(a, 1) return np.cumprod(a, axis=axis, dtype=dtype, out=out) + + def flip(m, axis): + """ + Reverse the order of elements in an array along the given axis. + + The shape of the array is preserved, but the elements are reordered. + + .. versionadded:: 1.12.0 + + Parameters + ---------- + m : array_like + Input array. + axis : integer + Axis in array, which entries are reversed. + + + Returns + ------- + out : array_like + A view of `m` with the entries of axis reversed. Since a view is + returned, this operation is done in constant time. + + See Also + -------- + flipud : Flip an array vertically (axis=0). + fliplr : Flip an array horizontally (axis=1). + + Notes + ----- + flip(m, 0) is equivalent to flipud(m). + flip(m, 1) is equivalent to fliplr(m). + flip(m, n) corresponds to ``m[...,::-1,...]`` with ``::-1`` at index n. + + Examples + -------- + >>> A = np.arange(8).reshape((2,2,2)) + >>> A + array([[[0, 1], + [2, 3]], + + [[4, 5], + [6, 7]]]) + + >>> flip(A, 0) + array([[[4, 5], + [6, 7]], + + [[0, 1], + [2, 3]]]) + + >>> flip(A, 1) + array([[[2, 3], + [0, 1]], + + [[6, 7], + [4, 5]]]) + + >>> A = np.random.randn(3,4,5) + >>> np.all(flip(A,2) == A[:,:,::-1,...]) + True + """ + if not hasattr(m, 'ndim'): + m = np.asarray(m) + indexer = [slice(None)] * m.ndim + try: + indexer[axis] = slice(None, None, -1) + except IndexError: + raise ValueError("axis=%i is invalid for the %i-dimensional " + "input array" % (axis, m.ndim)) + return m[tuple(indexer)] diff --git a/xarray/core/nputils.py b/xarray/core/nputils.py index a721425..8ac0475 100644 --- a/xarray/core/nputils.py +++ b/xarray/core/nputils.py @@ -120,6 +120,7 @@ class NumpyVIndexAdapter(object): This is a pure Python implementation of (some of) the logic in this NumPy proposal: https://github.com/numpy/numpy/pull/6256 """ + def __init__(self, array): self._array = array diff --git a/xarray/core/ops.py b/xarray/core/ops.py index 2ed3f81..d02b8fa 100644 --- a/xarray/core/ops.py +++ b/xarray/core/ops.py @@ -262,7 +262,7 @@ def inject_reduce_methods(cls): def inject_cum_methods(cls): methods = ([(name, getattr(duck_array_ops, name), True) - for name in NAN_CUM_METHODS]) + for name in NAN_CUM_METHODS]) for name, f, include_skipna in methods: numeric_only = getattr(f, 'numeric_only', False) func = cls._reduce_method(f, include_skipna, numeric_only) diff --git a/xarray/core/options.py b/xarray/core/options.py index abae742..9f06f8d 100644 --- a/xarray/core/options.py +++ b/xarray/core/options.py @@ -35,6 +35,7 @@ class set_options(object): >>> xr.set_options(display_width=80) """ + def __init__(self, **kwargs): invalid_options = {k for k in kwargs if k not in OPTIONS} if invalid_options: diff --git a/xarray/core/pycompat.py b/xarray/core/pycompat.py index a73a27f..4b83df9 100644 --- a/xarray/core/pycompat.py +++ b/xarray/core/pycompat.py @@ -1,3 +1,5 @@ +# flake8: noqa + from __future__ import absolute_import from __future__ import division from __future__ import print_function @@ -126,6 +128,7 @@ class ExitStack(object): # in the list raise an exception """ + def __init__(self): self._exit_callbacks = deque() @@ -161,7 +164,7 @@ def push(self, exit): self._exit_callbacks.append(exit) else: self._push_cm_exit(exit, exit_method) - return exit # Allow use as a decorator + return exit # Allow use as a decorator def callback(self, callback, *args, **kwds): """Registers an arbitrary callback and arguments. @@ -174,7 +177,7 @@ def _exit_wrapper(exc_type, exc, tb): # setting __wrapped__ may still help with introspection _exit_wrapper.__wrapped__ = callback self.push(_exit_wrapper) - return callback # Allow use as a decorator + return callback # Allow use as a decorator def enter_context(self, cm): """Enters the supplied context manager diff --git a/xarray/core/rolling.py b/xarray/core/rolling.py index 6ac668f..8209e70 100644 --- a/xarray/core/rolling.py +++ b/xarray/core/rolling.py @@ -87,7 +87,8 @@ def __repr__(self): """provide a nice str repr of our rolling object""" attrs = ["{k}->{v}".format(k=k, v=getattr(self, k)) - for k in self._attributes if getattr(self, k, None) is not None] + for k in self._attributes + if getattr(self, k, None) is not None] return "{klass} [{attrs}]".format(klass=self.__class__.__name__, attrs=','.join(attrs)) @@ -122,6 +123,7 @@ class DataArrayRolling(Rolling): + rolling.DataArrayRolling + ops.inject_bottleneck_rolling_methods """ + def __init__(self, obj, min_periods=None, center=False, **windows): super(DataArrayRolling, self).__init__(obj, min_periods=min_periods, center=center, **windows) @@ -228,6 +230,7 @@ def _reduce_method(cls, func): Methods to return a wrapped function for any function `func` for numpy methods. """ + def wrapped_func(self, **kwargs): return self.reduce(func, **kwargs) return wrapped_func @@ -238,6 +241,7 @@ def _bottleneck_reduce(cls, func): Methods to return a wrapped function for any function `func` for bottoleneck method, except for `median`. """ + def wrapped_func(self, **kwargs): from .dataarray import DataArray @@ -285,6 +289,7 @@ class DatasetRolling(Rolling): Dataset.rolling DataArray.rolling """ + def __init__(self, obj, min_periods=None, center=False, **windows): """ Moving window object for Dataset. @@ -355,6 +360,7 @@ def _reduce_method(cls, func): Return a wrapped function for injecting numpy and bottoleneck methods. see ops.inject_datasetrolling_methods """ + def wrapped_func(self, **kwargs): from .dataset import Dataset reduced = OrderedDict() @@ -367,5 +373,6 @@ def wrapped_func(self, **kwargs): return Dataset(reduced, coords=self.obj.coords) return wrapped_func + inject_bottleneck_rolling_methods(DataArrayRolling) inject_datasetrolling_methods(DatasetRolling) diff --git a/xarray/core/utils.py b/xarray/core/utils.py index ac70d7f..de6b582 100644 --- a/xarray/core/utils.py +++ b/xarray/core/utils.py @@ -271,6 +271,7 @@ class SingleSlotPickleMixin(object): """Mixin class to add the ability to pickle objects whose state is defined by a single __slots__ attribute. Only necessary under Python 2. """ + def __getstate__(self): return getattr(self, self.__slots__[0]) @@ -386,6 +387,7 @@ class OrderedSet(MutableSet): The API matches the builtin set, but it preserves insertion order of elements, like an OrderedDict. """ + def __init__(self, values=None): self._ordered_dict = OrderedDict() if values is not None: @@ -533,3 +535,42 @@ def ensure_us_time_resolution(val): elif np.issubdtype(val.dtype, np.timedelta64): val = val.astype('timedelta64[us]') return val + + +class HiddenKeyDict(MutableMapping): + ''' + Acts like a normal dictionary, but hides certain keys. + ''' + # ``__init__`` method required to create instance from class. + + def __init__(self, data, hidden_keys): + self._data = data + if type(hidden_keys) not in (list, tuple): + raise TypeError("hidden_keys must be a list or tuple") + self._hidden_keys = hidden_keys + + def _raise_if_hidden(self, key): + if key in self._hidden_keys: + raise KeyError('Key `%r` is hidden.' % key) + + # The next five methods are requirements of the ABC. + def __setitem__(self, key, value): + self._raise_if_hidden(key) + self._data[key] = value + + def __getitem__(self, key): + self._raise_if_hidden(key) + return self._data[key] + + def __delitem__(self, key): + self._raise_if_hidden(key) + del self._data[key] + + def __iter__(self): + for k in self._data: + if k not in self._hidden_keys: + yield k + + def __len__(self): + num_hidden = sum([k in self._hidden_keys for k in self._data]) + return len(self._data) - num_hidden diff --git a/xarray/core/variable.py b/xarray/core/variable.py index 53b4bf6..d486301 100644 --- a/xarray/core/variable.py +++ b/xarray/core/variable.py @@ -5,7 +5,6 @@ from collections import defaultdict import functools import itertools -from distutils.version import LooseVersion import numpy as np import pandas as pd @@ -288,7 +287,8 @@ def nbytes(self): @property def _in_memory(self): - return (isinstance(self._data, (np.ndarray, np.number, PandasIndexAdapter)) or + return (isinstance(self._data, (np.ndarray, np.number, + PandasIndexAdapter)) or (isinstance(self._data, indexing.MemoryCachedArray) and isinstance(self._data.array, indexing.NumpyIndexingAdapter))) @@ -307,10 +307,6 @@ def data(self, data): "replacement data must match the Variable's shape") self._data = data - @property - def _indexable_data(self): - return as_indexable(self._data) - def load(self, **kwargs): """Manually trigger loading of this variable's data from disk or a remote source into memory and return this variable. @@ -386,7 +382,7 @@ def __dask_postpersist__(self): def _dask_finalize(results, array_func, array_args, dims, attrs, encoding): if isinstance(results, dict): # persist case name = array_args[0] - results = {k: v for k, v in results.items() if k[0] == name} # cull + results = {k: v for k, v in results.items() if k[0] == name} data = array_func(results, *array_args) return Variable(dims, data, attrs=attrs, encoding=encoding) @@ -622,13 +618,56 @@ def __getitem__(self, key): If you really want to do indexing like `x[x > 0]`, manipulate the numpy array `x.values` directly. """ - dims, index_tuple, new_order = self._broadcast_indexes(key) - data = self._indexable_data[index_tuple] + dims, indexer, new_order = self._broadcast_indexes(key) + data = as_indexable(self._data)[indexer] if new_order: data = np.moveaxis(data, range(len(new_order)), new_order) + return self._finalize_indexing_result(dims, data) + + def _finalize_indexing_result(self, dims, data): + """Used by IndexVariable to return IndexVariable objects when possible. + """ return type(self)(dims, data, self._attrs, self._encoding, fastpath=True) + def _getitem_with_mask(self, key, fill_value=dtypes.NA): + """Index this Variable with -1 remapped to fill_value.""" + # TODO(shoyer): expose this method in public API somewhere (isel?) and + # use it for reindex. + # TODO(shoyer): add a sanity check that all other integers are + # non-negative + # TODO(shoyer): add an optimization, remapping -1 to an adjacent value + # that is actually indexed rather than mapping it to the last value + # along each axis. + + if fill_value is dtypes.NA: + fill_value = dtypes.get_fill_value(self.dtype) + + dims, indexer, new_order = self._broadcast_indexes(key) + + if self.size: + if isinstance(self._data, dask_array_type): + # dask's indexing is faster this way; also vindex does not + # support negative indices yet: + # https://github.com/dask/dask/pull/2967 + actual_indexer = indexing.posify_mask_indexer(indexer) + else: + actual_indexer = indexer + + data = as_indexable(self._data)[actual_indexer] + chunks_hint = getattr(data, 'chunks', None) + mask = indexing.create_mask(indexer, self.shape, chunks_hint) + data = duck_array_ops.where(mask, fill_value, data) + else: + # array cannot be indexed along dimensions of size 0, so just + # build the mask directly instead. + mask = indexing.create_mask(indexer, self.shape) + data = np.broadcast_to(fill_value, getattr(mask, 'shape', ())) + + if new_order: + data = np.moveaxis(data, range(len(new_order)), new_order) + return self._finalize_indexing_result(dims, data) + def __setitem__(self, key, value): """__setitem__ is overloaded to access the underlying numpy values with orthogonal indexing. @@ -637,22 +676,28 @@ def __setitem__(self, key, value): """ dims, index_tuple, new_order = self._broadcast_indexes(key) - if isinstance(value, Variable): - value = value.set_dims(dims).data - - if new_order: - value = duck_array_ops.asarray(value) + if not isinstance(value, Variable): + value = as_compatible_data(value) if value.ndim > len(dims): raise ValueError( 'shape mismatch: value array of shape %s could not be' 'broadcast to indexing result with %s dimensions' % (value.shape, len(dims))) + if value.ndim == 0: + value = Variable((), value) + else: + value = Variable(dims[-value.ndim:], value) + # broadcast to become assignable + value = value.set_dims(dims).data + if new_order: + value = duck_array_ops.asarray(value) value = value[(len(dims) - value.ndim) * (np.newaxis,) + (Ellipsis,)] value = np.moveaxis(value, new_order, range(len(new_order))) - self._indexable_data[index_tuple] = value + indexable = as_indexable(self._data) + indexable[index_tuple] = value @property def attrs(self): @@ -1108,8 +1153,8 @@ def unstack(self, **dimensions): Parameters ---------- **dimensions : keyword arguments of the form old_dim={dim1: size1, ...} - Names of existing dimensions, and the new dimensions and sizes that they - map to. + Names of existing dimensions, and the new dimensions and sizes + that they map to. Returns ------- @@ -1204,9 +1249,9 @@ def concat(cls, variables, dim='concat_dim', positions=None, dimension is unchanged. Where to insert the new dimension is determined by the first variable. positions : None or list of integer arrays, optional - List of integer arrays which specifies the integer positions to which - to assign each dataset along the concatenated dimension. If not - supplied, objects are concatenated in the provided order. + List of integer arrays which specifies the integer positions to + which to assign each dataset along the concatenated dimension. + If not supplied, objects are concatenated in the provided order. shortcut : bool, optional This option is used internally to speed-up groupby operations. If `shortcut` is True, some checks of internal consistency between @@ -1343,14 +1388,10 @@ def quantile(self, q, dim=None, interpolation='linear'): numpy.nanpercentile, pandas.Series.quantile, Dataset.quantile, DataArray.quantile """ - if isinstance(self.data, dask_array_type): raise TypeError("quantile does not work for arrays stored as dask " "arrays. Load the data via .compute() or .load() " "prior to calling this method.") - if LooseVersion(np.__version__) < LooseVersion('1.10.0'): - raise NotImplementedError( - 'quantile requres numpy version 1.10.0 or later') q = np.asarray(q, dtype=np.float64) @@ -1374,6 +1415,47 @@ def quantile(self, q, dim=None, interpolation='linear'): interpolation=interpolation) return Variable(new_dims, qs) + def rank(self, dim, pct=False): + """Ranks the data. + + Equal values are assigned a rank that is the average of the ranks that + would have been otherwise assigned to all of the values within that + set. Ranks begin at 1, not 0. If `pct`, computes percentage ranks. + + NaNs in the input array are returned as NaNs. + + The `bottleneck` library is required. + + Parameters + ---------- + dim : str + Dimension over which to compute rank. + pct : bool, optional + If True, compute percentage ranks, otherwise compute integer ranks. + + Returns + ------- + ranked : Variable + + See Also + -------- + Dataset.rank, DataArray.rank + """ + import bottleneck as bn + + if isinstance(self.data, dask_array_type): + raise TypeError("rank does not work for arrays stored as dask " + "arrays. Load the data via .compute() or .load() " + "prior to calling this method.") + + axis = self.get_axis_num(dim) + func = bn.nanrankdata if self.dtype.kind is 'f' else bn.rankdata + ranked = func(self.data, axis=axis) + if pct: + count = np.sum(~np.isnan(self.data), axis=axis, keepdims=True) + ranked /= count + return Variable(self.dims, ranked) + @property def real(self): return type(self)(self.dims, self.data.real, self._attrs) @@ -1463,14 +1545,12 @@ def chunk(self, chunks=None, name=None, lock=False): # Dummy - do not chunk. This method is invoked e.g. by Dataset.chunk() return self.copy(deep=False) - def __getitem__(self, key): - dims, index_tuple, new_order = self._broadcast_indexes(key) - values = self._indexable_data[index_tuple] - if getattr(values, 'ndim', 0) != 1: + def _finalize_indexing_result(self, dims, data): + if getattr(data, 'ndim', 0) != 1: # returns Variable rather than IndexVariable if multi-dimensional - return Variable(dims, values, self._attrs, self._encoding) + return Variable(dims, data, self._attrs, self._encoding) else: - return type(self)(dims, values, self._attrs, + return type(self)(dims, data, self._attrs, self._encoding, fastpath=True) def __setitem__(self, key, value): @@ -1613,6 +1693,11 @@ def _unified_dims(variables): def _broadcast_compat_variables(*variables): + """Create broadcast compatible variables, with the same dimensions. + + Unlike the result of broadcast_variables(), some variables may have + dimensions of size 1 instead of the the size of the broadcast dimension. + """ dims = tuple(_unified_dims(variables)) return tuple(var.set_dims(dims) if var.dims != dims else var for var in variables) diff --git a/xarray/plot/__init__.py b/xarray/plot/__init__.py index cb0cca4..fe2c604 100644 --- a/xarray/plot/__init__.py +++ b/xarray/plot/__init__.py @@ -5,3 +5,14 @@ hist, imshow, pcolormesh) from .facetgrid import FacetGrid + +__all__ = [ + 'plot', + 'line', + 'contour', + 'contourf', + 'hist', + 'imshow', + 'pcolormesh', + 'FacetGrid', +] diff --git a/xarray/plot/facetgrid.py b/xarray/plot/facetgrid.py index 8e5ec80..badd44b 100644 --- a/xarray/plot/facetgrid.py +++ b/xarray/plot/facetgrid.py @@ -239,8 +239,9 @@ def map_dataarray(self, func, x, y, **kwargs): func_kwargs.update({'add_colorbar': False, 'add_labels': False}) # Get x, y labels for the first subplot - x, y = _infer_xy_labels(darray=self.data.loc[self.name_dicts.flat[0]], - x=x, y=y) + x, y = _infer_xy_labels( + darray=self.data.loc[self.name_dicts.flat[0]], x=x, y=y, + imshow=func.__name__ == 'imshow', rgb=kwargs.get('rgb', None)) for d, ax in zip(self.name_dicts.flat, self.axes.flat): # None is the sentinel value diff --git a/xarray/plot/plot.py b/xarray/plot/plot.py index 4dd1b12..d17ceb8 100644 --- a/xarray/plot/plot.py +++ b/xarray/plot/plot.py @@ -15,8 +15,8 @@ import pandas as pd from datetime import datetime -from .utils import (_determine_cmap_params, _infer_xy_labels, get_axis, - import_matplotlib_pyplot) +from .utils import (ROBUST_PERCENTILE, _determine_cmap_params, + _infer_xy_labels, get_axis, import_matplotlib_pyplot) from .facetgrid import FacetGrid from xarray.core.pycompat import basestring @@ -37,10 +37,7 @@ def _valid_other_type(x, types): """ Do all elements of x have a type from types? """ - if not np.issubdtype(np.generic, x.dtype): - return False - else: - return all(any(isinstance(el, t) for t in types) for el in np.ravel(x)) + return all(any(isinstance(el, t) for t in types) for el in np.ravel(x)) def _ensure_plottable(*args): @@ -52,11 +49,12 @@ def _ensure_plottable(*args): other_types = [datetime] for x in args: - if not (_valid_numpy_subdtype(np.array(x), numpy_types) - or _valid_other_type(np.array(x), other_types)): + if not (_valid_numpy_subdtype(np.array(x), numpy_types) or + _valid_other_type(np.array(x), other_types)): raise TypeError('Plotting requires coordinates to be numeric ' 'or dates.') + def _easy_facetgrid(darray, plotfunc, x, y, row=None, col=None, col_wrap=None, sharex=True, sharey=True, aspect=None, size=None, subplot_kws=None, **kwargs): @@ -156,9 +154,9 @@ def plot(darray, row=None, col=None, col_wrap=None, ax=None, rtol=0.01, # matplotlib format strings def line(darray, *args, **kwargs): """ - Line plot of 1 dimensional DataArray index against values + Line plot of DataArray index against values - Wraps matplotlib.pyplot.plot + Wraps :func:`matplotlib:matplotlib.pyplot.plot` Parameters ---------- @@ -176,15 +174,20 @@ def line(darray, *args, **kwargs): ax : matplotlib axes object, optional Axis on which to plot this figure. By default, use the current axis. Mutually exclusive with ``size`` and ``figsize``. + hue : string, optional + Coordinate for which you want multiple lines plotted (2D inputs only). + x : string, optional + Coordinate for x axis. + add_legend : boolean, optional + Add legend with y axis coordinates (2D inputs only). *args, **kwargs : optional Additional arguments to matplotlib.pyplot.plot """ - plt = import_matplotlib_pyplot() ndims = len(darray.dims) - if ndims != 1: - raise ValueError('Line plots are for 1 dimensional DataArrays. ' + if ndims > 2: + raise ValueError('Line plots are for 1- or 2-dimensional DataArrays. ' 'Passed DataArray has {ndims} ' 'dimensions'.format(ndims=ndims)) @@ -193,11 +196,27 @@ def line(darray, *args, **kwargs): aspect = kwargs.pop('aspect', None) size = kwargs.pop('size', None) ax = kwargs.pop('ax', None) + hue = kwargs.pop('hue', None) + x = kwargs.pop('x', None) + add_legend = kwargs.pop('add_legend', True) ax = get_axis(figsize, size, aspect, ax) - xlabel, = darray.dims - x = darray.coords[xlabel] + if ndims == 1: + xlabel, = darray.dims + if x is not None and xlabel != x: + raise ValueError('Input does not have specified dimension' + ' {!r}'.format(x)) + + x = darray.coords[xlabel] + + else: + if x is None and hue is None: + raise ValueError('For 2D inputs, please specify either hue or x.') + + xlabel, huelabel = _infer_xy_labels(darray=darray, x=x, y=hue) + x = darray.coords[xlabel] + darray = darray.transpose(xlabel, huelabel) _ensure_plottable(x) @@ -209,9 +228,14 @@ def line(darray, *args, **kwargs): if darray.name is not None: ax.set_ylabel(darray.name) + if darray.ndim == 2 and add_legend: + ax.legend(handles=primitive, + labels=list(darray.coords[huelabel].values), + title=huelabel) + # Rotate dates on xlabels if np.issubdtype(x.dtype, np.datetime64): - plt.gcf().autofmt_xdate() + ax.get_figure().autofmt_xdate() return primitive @@ -220,7 +244,7 @@ def hist(darray, figsize=None, size=None, aspect=None, ax=None, **kwargs): """ Histogram of DataArray - Wraps matplotlib.pyplot.hist + Wraps :func:`matplotlib:matplotlib.pyplot.hist` Plots N dimensional arrays by first flattening the array. @@ -302,6 +326,39 @@ def line(self, *args, **kwargs): return line(self._da, *args, **kwargs) +def _rescale_imshow_rgb(darray, vmin, vmax, robust): + assert robust or vmin is not None or vmax is not None + # There's a cyclic dependency via DataArray, so we can't import from + # xarray.ufuncs in global scope. + from xarray.ufuncs import maximum, minimum + # Calculate vmin and vmax automatically for `robust=True` + if robust: + if vmax is None: + vmax = np.nanpercentile(darray, 100 - ROBUST_PERCENTILE) + if vmin is None: + vmin = np.nanpercentile(darray, ROBUST_PERCENTILE) + # If not robust and one bound is None, calculate the default other bound + # and check that an interval between them exists. + elif vmax is None: + vmax = 255 if np.issubdtype(darray.dtype, np.integer) else 1 + if vmax < vmin: + raise ValueError( + 'vmin=%r is less than the default vmax (%r) - you must supply ' + 'a vmax > vmin in this case.' % (vmin, vmax)) + elif vmin is None: + vmin = 0 + if vmin > vmax: + raise ValueError( + 'vmax=%r is less than the default vmin (0) - you must supply ' + 'a vmin < vmax in this case.' % vmax) + # Scale interval [vmin .. vmax] to [0 .. 1], with darray as 64-bit float + # to avoid precision loss, integer over/underflow, etc with extreme inputs. + # After scaling, downcast to 32-bit float. This substantially reduces + # memory usage after we hand `darray` off to matplotlib. + darray = ((darray.astype('f8') - vmin) / (vmax - vmin)).astype('f4') + return minimum(maximum(darray, 0), 1) + + def _plot2d(plotfunc): """ Decorator for common 2d plotting logic @@ -419,10 +476,22 @@ def newplotfunc(darray, x=None, y=None, figsize=None, size=None, # Decide on a default for the colorbar before facetgrids if add_colorbar is None: add_colorbar = plotfunc.__name__ != 'contour' + imshow_rgb = ( + plotfunc.__name__ == 'imshow' and + darray.ndim == (3 + (row is not None) + (col is not None))) + if imshow_rgb: + # Don't add a colorbar when showing an image with explicit colors + add_colorbar = False + # Matplotlib does not support normalising RGB data, so do it here. + # See eg. https://github.com/matplotlib/matplotlib/pull/10220 + if robust or vmax is not None or vmin is not None: + darray = _rescale_imshow_rgb(darray, vmin, vmax, robust) + vmin, vmax, robust = None, None, False # Handle facetgrids first if row or col: allargs = locals().copy() + allargs.pop('imshow_rgb') allargs.update(allargs.pop('kwargs')) # Need the decorated plotting function @@ -446,12 +515,19 @@ def newplotfunc(darray, x=None, y=None, figsize=None, size=None, "Use colors keyword instead.", DeprecationWarning, stacklevel=3) - xlab, ylab = _infer_xy_labels(darray=darray, x=x, y=y) + rgb = kwargs.pop('rgb', None) + xlab, ylab = _infer_xy_labels( + darray=darray, x=x, y=y, imshow=imshow_rgb, rgb=rgb) + + if rgb is not None and plotfunc.__name__ != 'imshow': + raise ValueError('The "rgb" keyword is only valid for imshow()') + elif rgb is not None and not imshow_rgb: + raise ValueError('The "rgb" keyword is only valid for imshow()' + 'with a three-dimensional array (per facet)') # better to pass the ndarrays directly to plotting functions xval = darray[xlab].values yval = darray[ylab].values - zval = darray.to_masked_array(copy=False) # check if we need to broadcast one dimension if xval.ndim < yval.ndim: @@ -462,8 +538,19 @@ def newplotfunc(darray, x=None, y=None, figsize=None, size=None, # May need to transpose for correct x, y labels # xlab may be the name of a coord, we have to check for dim names - if darray[xlab].dims[-1] == darray.dims[0]: - zval = zval.T + if imshow_rgb: + # For RGB[A] images, matplotlib requires the color dimension + # to be last. In Xarray the order should be unimportant, so + # we transpose to (y, x, color) to make this work. + yx_dims = (ylab, xlab) + dims = yx_dims + tuple(d for d in darray.dims if d not in yx_dims) + if dims != darray.dims: + darray = darray.transpose(*dims) + elif darray[xlab].dims[-1] == darray.dims[0]: + darray = darray.transpose() + + # Pass the data as a masked ndarray too + zval = darray.to_masked_array(copy=False) _ensure_plottable(xval, yval) @@ -530,6 +617,10 @@ def newplotfunc(darray, x=None, y=None, figsize=None, size=None, _update_axes_limits(ax, xincrease, yincrease) + # Rotate dates on xlabels + if np.issubdtype(xval.dtype, np.datetime64): + ax.get_figure().autofmt_xdate() + return primitive # For use as DataArray.plot.plotmethod @@ -565,10 +656,19 @@ def imshow(x, y, z, ax, **kwargs): """ Image plot of 2d DataArray using matplotlib.pyplot - Wraps matplotlib.pyplot.imshow + Wraps :func:`matplotlib:matplotlib.pyplot.imshow` - ..note:: + While other plot methods require the DataArray to be strictly + two-dimensional, ``imshow`` also accepts a 3D array where some + dimension can be interpreted as RGB or RGBA color channels and + allows this dimension to be specified via the kwarg ``rgb=``. + Unlike matplotlib, Xarray can apply ``vmin`` and ``vmax`` to RGB or RGBA + data, by applying a single scaling factor and offset to all bands. + Passing ``robust=True`` infers ``vmin`` and ``vmax`` + :ref:`in the usual way `. + + .. note:: This function needs uniformly spaced coordinates to properly label the axes. Call DataArray.plot() to check. @@ -581,8 +681,15 @@ def imshow(x, y, z, ax, **kwargs): 'pcolormesh or contour(f)') # Centering the pixels- Assumes uniform spacing - xstep = (x[1] - x[0]) / 2.0 - ystep = (y[1] - y[0]) / 2.0 + try: + xstep = (x[1] - x[0]) / 2.0 + except IndexError: + # Arbitrary default value, similar to matplotlib behaviour + xstep = .1 + try: + ystep = (y[1] - y[0]) / 2.0 + except IndexError: + ystep = .1 left, right = x[0] - xstep, x[-1] + xstep bottom, top = y[-1] + ystep, y[0] - ystep @@ -598,6 +705,15 @@ def imshow(x, y, z, ax, **kwargs): # Allow user to override these defaults defaults.update(kwargs) + if z.ndim == 3: + # matplotlib imshow uses black for missing data, but Xarray makes + # missing data transparent. We therefore add an alpha channel if + # there isn't one, and set it to transparent where data is masked. + if z.shape[-1] == 3: + z = np.ma.concatenate((z, np.ma.ones(z.shape[:2] + (1,))), 2) + z = z.copy() + z[np.any(z.mask, axis=-1), -1] = 0 + primitive = ax.imshow(z, **defaults) return primitive @@ -608,7 +724,7 @@ def contour(x, y, z, ax, **kwargs): """ Contour plot of 2d DataArray - Wraps matplotlib.pyplot.contour + Wraps :func:`matplotlib:matplotlib.pyplot.contour` """ primitive = ax.contour(x, y, z, **kwargs) return primitive @@ -619,7 +735,7 @@ def contourf(x, y, z, ax, **kwargs): """ Filled contour plot of 2d DataArray - Wraps matplotlib.pyplot.contourf + Wraps :func:`matplotlib:matplotlib.pyplot.contourf` """ primitive = ax.contourf(x, y, z, **kwargs) return primitive @@ -635,6 +751,8 @@ def _infer_interval_breaks(coord, axis=0): """ coord = np.asarray(coord) deltas = 0.5 * np.diff(coord, axis=axis) + if deltas.size == 0: + deltas = np.array(0.0) first = np.take(coord, [0], axis=axis) - np.take(deltas, [0], axis=axis) last = np.take(coord, [-1], axis=axis) + np.take(deltas, [-1], axis=axis) trim_last = tuple(slice(None, -1) if n == axis else slice(None) @@ -647,7 +765,7 @@ def pcolormesh(x, y, z, ax, infer_intervals=None, **kwargs): """ Pseudocolor plot of 2d DataArray - Wraps matplotlib.pyplot.pcolormesh + Wraps :func:`matplotlib:matplotlib.pyplot.pcolormesh` """ # decide on a default for infer_intervals (GH781) diff --git a/xarray/plot/utils.py b/xarray/plot/utils.py index 169aa12..c194b9d 100644 --- a/xarray/plot/utils.py +++ b/xarray/plot/utils.py @@ -11,6 +11,9 @@ from ..core.utils import is_scalar +ROBUST_PERCENTILE = 2.0 + + def _load_default_cmap(fname='default_colormap.csv'): """ Returns viridis color map @@ -47,8 +50,13 @@ def register_pandas_datetime_converter_if_needed(): # based on https://github.com/pandas-dev/pandas/pull/17710 global _registered if not _registered: - from pandas.tseries import converter - converter.register() + try: + from pandas.plotting import register_matplotlib_converters + register_matplotlib_converters() + except ImportError: + # register_matplotlib_converters new in pandas 0.22 + from pandas.tseries import converter + converter.register() _registered = True @@ -160,11 +168,15 @@ def _determine_cmap_params(plot_data, vmin=None, vmax=None, cmap=None, cmap_params : dict Use depends on the type of the plotting function """ - ROBUST_PERCENTILE = 2.0 import matplotlib as mpl calc_data = np.ravel(plot_data[~pd.isnull(plot_data)]) + # Handle all-NaN input data gracefully + if calc_data.size == 0: + # Arbitrary default for when all values are NaN + calc_data = np.array(0.0) + # Setting center=False prevents a divergent cmap possibly_divergent = center is not False @@ -234,7 +246,7 @@ def _determine_cmap_params(plot_data, vmin=None, vmax=None, cmap=None, levels = np.linspace(vmin, vmax, levels) else: # N in MaxNLocator refers to bins, not ticks - ticker = mpl.ticker.MaxNLocator(levels-1) + ticker = mpl.ticker.MaxNLocator(levels - 1) levels = ticker.tick_values(vmin, vmax) vmin, vmax = levels[0], levels[-1] @@ -248,12 +260,65 @@ def _determine_cmap_params(plot_data, vmin=None, vmax=None, cmap=None, levels=levels, norm=norm) -def _infer_xy_labels(darray, x, y): +def _infer_xy_labels_3d(darray, x, y, rgb): + """ + Determine x and y labels for showing RGB images. + + Attempts to infer which dimension is RGB/RGBA by size and order of dims. + + """ + assert rgb is None or rgb != x + assert rgb is None or rgb != y + # Start by detecting and reporting invalid combinations of arguments + assert darray.ndim == 3 + not_none = [a for a in (x, y, rgb) if a is not None] + if len(set(not_none)) < len(not_none): + raise ValueError( + 'Dimension names must be None or unique strings, but imshow was ' + 'passed x=%r, y=%r, and rgb=%r.' % (x, y, rgb)) + for label in not_none: + if label not in darray.dims: + raise ValueError('%r is not a dimension' % (label,)) + + # Then calculate rgb dimension if certain and check validity + could_be_color = [label for label in darray.dims + if darray[label].size in (3, 4) and label not in (x, y)] + if rgb is None and not could_be_color: + raise ValueError( + 'A 3-dimensional array was passed to imshow(), but there is no ' + 'dimension that could be color. At least one dimension must be ' + 'of size 3 (RGB) or 4 (RGBA), and not given as x or y.') + if rgb is None and len(could_be_color) == 1: + rgb = could_be_color[0] + if rgb is not None and darray[rgb].size not in (3, 4): + raise ValueError('Cannot interpret dim %r of size %s as RGB or RGBA.' + % (rgb, darray[rgb].size)) + + # If rgb dimension is still unknown, there must be two or three dimensions + # in could_be_color. We therefore warn, and use a heuristic to break ties. + if rgb is None: + assert len(could_be_color) in (2, 3) + rgb = could_be_color[-1] + warnings.warn( + 'Several dimensions of this array could be colors. Xarray ' + 'will use the last possible dimension (%r) to match ' + 'matplotlib.pyplot.imshow. You can pass names of x, y, ' + 'and/or rgb dimensions to override this guess.' % rgb) + assert rgb is not None + + # Finally, we pick out the red slice and delegate to the 2D version: + return _infer_xy_labels(darray.isel(**{rgb: 0}).squeeze(), x, y) + + +def _infer_xy_labels(darray, x, y, imshow=False, rgb=None): """ Determine x and y labels. For use in _plot2d - darray must be a 2 dimensional data array. + darray must be a 2 dimensional data array, or 3d for imshow only. """ + assert x is None or x != y + if imshow and darray.ndim == 3: + return _infer_xy_labels_3d(darray, x, y, rgb) if x is None and y is None: if darray.ndim != 2: diff --git a/xarray/tests/__init__.py b/xarray/tests/__init__.py index 1716c3e..f373d20 100644 --- a/xarray/tests/__init__.py +++ b/xarray/tests/__init__.py @@ -8,21 +8,22 @@ import importlib import numpy as np -from numpy.testing import assert_array_equal +from numpy.testing import assert_array_equal # noqa: F401 from xarray.core.duck_array_ops import allclose_or_equiv import pytest from xarray.core import utils from xarray.core.pycompat import PY3 from xarray.core.indexing import ExplicitlyIndexed -from xarray.testing import assert_equal, assert_identical, assert_allclose +from xarray.testing import (assert_equal, assert_identical, # noqa: F401 + assert_allclose) from xarray.plot.utils import import_seaborn try: from pandas.testing import assert_frame_equal except ImportError: # old location, for pandas < 0.20 - from pandas.util.testing import assert_frame_equal + from pandas.util.testing import assert_frame_equal # noqa: F401 try: import unittest2 as unittest @@ -32,7 +33,7 @@ try: from unittest import mock except ImportError: - import mock + import mock # noqa: F401 # import mpl and change the backend before other mpl imports try: @@ -71,6 +72,8 @@ def _importorskip(modname, minversion=None): has_bottleneck, requires_bottleneck = _importorskip('bottleneck') has_rasterio, requires_rasterio = _importorskip('rasterio') has_pathlib, requires_pathlib = _importorskip('pathlib') +has_zarr, requires_zarr = _importorskip('zarr', minversion='2.2.0') +has_np112, requires_np112 = _importorskip('numpy', minversion='1.12.0') # some special cases has_scipy_or_netCDF4 = has_scipy or has_netCDF4 @@ -84,7 +87,7 @@ def _importorskip(modname, minversion=None): try: import_seaborn() has_seaborn = True -except: +except ImportError: has_seaborn = False requires_seaborn = unittest.skipUnless(has_seaborn, reason='requires seaborn') @@ -107,6 +110,9 @@ def _importorskip(modname, minversion=None): class TestCase(unittest.TestCase): + """ + These functions are all deprecated. Instead, use functions in xr.testing + """ if PY3: # Python 3 assertCountEqual is roughly equivalent to Python 2 # assertItemsEqual @@ -123,26 +129,10 @@ def assertWarns(self, message): assert len(w) > 0 assert any(message in str(wi.message) for wi in w) - def assertVariableEqual(self, v1, v2): - __tracebackhide__ = True # noqa: F841 - assert_equal(v1, v2) - - def assertVariableIdentical(self, v1, v2): - __tracebackhide__ = True # noqa: F841 - assert_identical(v1, v2) - - def assertVariableAllClose(self, v1, v2, rtol=1e-05, atol=1e-08): - __tracebackhide__ = True # noqa: F841 - assert_allclose(v1, v2, rtol=rtol, atol=atol) - def assertVariableNotEqual(self, v1, v2): __tracebackhide__ = True # noqa: F841 assert not v1.equals(v2) - def assertArrayEqual(self, a1, a2): - __tracebackhide__ = True # noqa: F841 - assert_array_equal(a1, a2) - def assertEqual(self, a1, a2): __tracebackhide__ = True # noqa: F841 assert a1 == a2 or (a1 != a1 and a2 != a2) @@ -151,38 +141,6 @@ def assertAllClose(self, a1, a2, rtol=1e-05, atol=1e-8): __tracebackhide__ = True # noqa: F841 assert allclose_or_equiv(a1, a2, rtol=rtol, atol=atol) - def assertDatasetEqual(self, d1, d2): - __tracebackhide__ = True # noqa: F841 - assert_equal(d1, d2) - - def assertDatasetIdentical(self, d1, d2): - __tracebackhide__ = True # noqa: F841 - assert_identical(d1, d2) - - def assertDatasetAllClose(self, d1, d2, rtol=1e-05, atol=1e-08, - decode_bytes=True): - __tracebackhide__ = True # noqa: F841 - assert_allclose(d1, d2, rtol=rtol, atol=atol, - decode_bytes=decode_bytes) - - def assertCoordinatesEqual(self, d1, d2): - __tracebackhide__ = True # noqa: F841 - assert_equal(d1, d2) - - def assertDataArrayEqual(self, ar1, ar2): - __tracebackhide__ = True # noqa: F841 - assert_equal(ar1, ar2) - - def assertDataArrayIdentical(self, ar1, ar2): - __tracebackhide__ = True # noqa: F841 - assert_identical(ar1, ar2) - - def assertDataArrayAllClose(self, ar1, ar2, rtol=1e-05, atol=1e-08, - decode_bytes=True): - __tracebackhide__ = True # noqa: F841 - assert_allclose(ar1, ar2, rtol=rtol, atol=atol, - decode_bytes=decode_bytes) - @contextmanager def raises_regex(error, pattern): diff --git a/xarray/tests/data/bears.nc b/xarray/tests/data/bears.nc index d65c20f..2f1a063 100644 Binary files a/xarray/tests/data/bears.nc and b/xarray/tests/data/bears.nc differ diff --git a/xarray/tests/test_accessors.py b/xarray/tests/test_accessors.py index 5233dea..30ea1a8 100644 --- a/xarray/tests/test_accessors.py +++ b/xarray/tests/test_accessors.py @@ -6,7 +6,8 @@ import numpy as np import pandas as pd -from . import TestCase, requires_dask, raises_regex +from . import (TestCase, requires_dask, raises_regex, assert_equal, + assert_array_equal) class TestDatetimeAccessor(TestCase): @@ -36,10 +37,10 @@ def test_field_access(self): hours = xr.DataArray(self.times.hour, name='hour', coords=[self.times, ], dims=['time', ]) - self.assertDataArrayEqual(years, self.data.time.dt.year) - self.assertDataArrayEqual(months, self.data.time.dt.month) - self.assertDataArrayEqual(days, self.data.time.dt.day) - self.assertDataArrayEqual(hours, self.data.time.dt.hour) + assert_equal(years, self.data.time.dt.year) + assert_equal(months, self.data.time.dt.month) + assert_equal(days, self.data.time.dt.day) + assert_equal(hours, self.data.time.dt.hour) def test_not_datetime_type(self): nontime_data = self.data.copy() @@ -75,16 +76,16 @@ def test_dask_field_access(self): # Double check that outcome chunksize is unchanged dask_chunks = dask_times_2d.chunks - self.assertEqual(dask_year.data.chunks, dask_chunks) - self.assertEqual(dask_month.data.chunks, dask_chunks) - self.assertEqual(dask_day.data.chunks, dask_chunks) - self.assertEqual(dask_hour.data.chunks, dask_chunks) + assert dask_year.data.chunks == dask_chunks + assert dask_month.data.chunks == dask_chunks + assert dask_day.data.chunks == dask_chunks + assert dask_hour.data.chunks == dask_chunks # Check the actual output from the accessors - self.assertDataArrayEqual(years, dask_year.compute()) - self.assertDataArrayEqual(months, dask_month.compute()) - self.assertDataArrayEqual(days, dask_day.compute()) - self.assertDataArrayEqual(hours, dask_hour.compute()) + assert_equal(years, dask_year.compute()) + assert_equal(months, dask_month.compute()) + assert_equal(days, dask_day.compute()) + assert_equal(hours, dask_hour.compute()) def test_seasons(self): dates = pd.date_range(start="2000/01/01", freq="M", periods=12) @@ -93,4 +94,4 @@ def test_seasons(self): "SON", "SON", "SON", "DJF"] seasons = xr.DataArray(seasons) - self.assertArrayEqual(seasons.values, dates.dt.season.values) + assert_array_equal(seasons.values, dates.dt.season.values) diff --git a/xarray/tests/test_backends.py b/xarray/tests/test_backends.py index 017e290..65bf0b5 100644 --- a/xarray/tests/test_backends.py +++ b/xarray/tests/test_backends.py @@ -2,7 +2,6 @@ from __future__ import division from __future__ import print_function from io import BytesIO -from threading import Lock import contextlib import itertools import os.path @@ -11,6 +10,7 @@ import tempfile import unittest import sys +import warnings import numpy as np import pandas as pd @@ -21,18 +21,21 @@ open_mfdataset, backends, save_mfdataset) from xarray.backends.common import robust_getitem from xarray.backends.netCDF4_ import _extract_nc4_variable_encoding +from xarray.backends.pydap_ import PydapDataStore from xarray.core import indexing from xarray.core.pycompat import (iteritems, PY2, ExitStack, basestring, dask_array_type) from . import (TestCase, requires_scipy, requires_netCDF4, requires_pydap, requires_scipy_or_netCDF4, requires_dask, requires_h5netcdf, - requires_pynio, requires_pathlib, has_netCDF4, has_scipy, - assert_allclose, flaky, network, requires_rasterio, - assert_identical, raises_regex) + requires_pynio, requires_pathlib, requires_zarr, + requires_rasterio, has_netCDF4, has_scipy, assert_allclose, + flaky, network, assert_identical, raises_regex, assert_equal, + assert_array_equal) + from .test_dataset import create_test_data -from xarray.tests import mock, assert_identical +from xarray.tests import mock try: import netCDF4 as nc4 @@ -172,7 +175,7 @@ def test_zero_dimensional_variable(self): expected['bytes_var'] = ([], b'foobar') expected['string_var'] = ([], u'foobar') with self.roundtrip(expected) as actual: - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_write_store(self): expected = create_test_data() @@ -181,7 +184,7 @@ def test_write_store(self): # we need to cf decode the store because it has time and # non-dimension coordinates with xr.decode_cf(store) as actual: - self.assertDatasetAllClose(expected, actual) + assert_allclose(expected, actual) def check_dtypes_roundtripped(self, expected, actual): for k in expected.variables: @@ -200,7 +203,7 @@ def test_roundtrip_test_data(self): expected = create_test_data() with self.roundtrip(expected) as actual: self.check_dtypes_roundtripped(expected, actual) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_load(self): expected = create_test_data() @@ -217,7 +220,7 @@ def assert_loads(vars=None): for k, v in actual.variables.items(): if k in vars: self.assertTrue(v._in_memory) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) with pytest.raises(AssertionError): # make sure the contextmanager works! @@ -233,7 +236,7 @@ def assert_loads(vars=None): # verify we can read data even after closing the file with self.roundtrip(expected) as ds: actual = ds.load() - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_dataset_compute(self): expected = create_test_data() @@ -251,8 +254,8 @@ def test_dataset_compute(self): for v in computed.variables.values(): self.assertTrue(v._in_memory) - self.assertDatasetIdentical(expected, actual) - self.assertDatasetIdentical(expected, computed) + assert_identical(expected, actual) + assert_identical(expected, computed) def test_pickle(self): expected = Dataset({'foo': ('x', [42])}) @@ -262,14 +265,14 @@ def test_pickle(self): # windows doesn't like opening the same file twice roundtripped.close() unpickled_ds = pickle.loads(raw_pickle) - self.assertDatasetIdentical(expected, unpickled_ds) + assert_identical(expected, unpickled_ds) def test_pickle_dataarray(self): expected = Dataset({'foo': ('x', [42])}) with self.roundtrip( expected, allow_cleanup_failure=ON_WINDOWS) as roundtripped: unpickled_array = pickle.loads(pickle.dumps(roundtripped['foo'])) - self.assertDatasetIdentical(expected['foo'], unpickled_array) + assert_identical(expected['foo'], unpickled_array) def test_dataset_caching(self): expected = Dataset({'foo': ('x', [5, 6, 7])}) @@ -290,7 +293,7 @@ def test_dataset_caching(self): def test_roundtrip_None_variable(self): expected = Dataset({None: (('x', 'y'), [[0, 1], [2, 3]])}) with self.roundtrip(expected) as actual: - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_roundtrip_object_dtype(self): floats = np.array([0.0, 0.0, 1.0, 2.0, 3.0], dtype=object) @@ -311,7 +314,7 @@ def test_roundtrip_object_dtype(self): expected = original.copy(deep=True) with self.roundtrip(original) as actual: try: - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) except AssertionError: # Most stores use '' for nans in strings, but some don't. # First try the ideal case (where the store returns exactly) @@ -321,23 +324,23 @@ def test_roundtrip_object_dtype(self): # https://github.com/pydata/xarray/issues/1647 expected['bytes_nans'][-1] = b'' expected['strings_nans'][-1] = u'' - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_roundtrip_string_data(self): expected = Dataset({'x': ('t', ['ab', 'cdef'])}) with self.roundtrip(expected) as actual: - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_roundtrip_string_encoded_characters(self): expected = Dataset({'x': ('t', [u'ab', u'cdef'])}) expected['x'].encoding['dtype'] = 'S1' with self.roundtrip(expected) as actual: - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) self.assertEqual(actual['x'].encoding['_Encoding'], 'utf-8') expected['x'].encoding['_Encoding'] = 'ascii' with self.roundtrip(expected) as actual: - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) self.assertEqual(actual['x'].encoding['_Encoding'], 'ascii') def test_roundtrip_datetime_data(self): @@ -345,20 +348,20 @@ def test_roundtrip_datetime_data(self): expected = Dataset({'t': ('t', times), 't0': times[0]}) kwds = {'encoding': {'t0': {'units': 'days since 1950-01-01'}}} with self.roundtrip(expected, save_kwargs=kwds) as actual: - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) assert actual.t0.encoding['units'] == 'days since 1950-01-01' def test_roundtrip_timedelta_data(self): time_deltas = pd.to_timedelta(['1h', '2h', 'NaT']) expected = Dataset({'td': ('td', time_deltas), 'td0': time_deltas[0]}) with self.roundtrip(expected) as actual: - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_roundtrip_float64_data(self): expected = Dataset({'x': ('y', np.array([1.0, 2.0, np.pi], dtype='float64'))}) with self.roundtrip(expected) as actual: - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_roundtrip_example_1_netcdf(self): expected = open_example_dataset('example_1.nc') @@ -367,32 +370,32 @@ def test_roundtrip_example_1_netcdf(self): # will depend on the encoding used. For example, # without CF encoding 'actual' will end up with # a dtype attribute. - self.assertDatasetEqual(expected, actual) + assert_equal(expected, actual) def test_roundtrip_coordinates(self): original = Dataset({'foo': ('x', [0, 1])}, {'x': [2, 3], 'y': ('a', [42]), 'z': ('x', [4, 5])}) with self.roundtrip(original) as actual: - self.assertDatasetIdentical(original, actual) + assert_identical(original, actual) def test_roundtrip_global_coordinates(self): original = Dataset({'x': [2, 3], 'y': ('a', [42]), 'z': ('x', [4, 5])}) with self.roundtrip(original) as actual: - self.assertDatasetIdentical(original, actual) + assert_identical(original, actual) def test_roundtrip_coordinates_with_space(self): original = Dataset(coords={'x': 0, 'y z': 1}) expected = Dataset({'y z': 1}, {'x': 0}) with pytest.warns(xr.SerializationWarning): with self.roundtrip(original) as actual: - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_roundtrip_boolean_dtype(self): original = create_boolean_data() self.assertEqual(original['x'].dtype, 'bool') with self.roundtrip(original) as actual: - self.assertDatasetIdentical(original, actual) + assert_identical(original, actual) self.assertEqual(actual['x'].dtype, 'bool') def test_orthogonal_indexing(self): @@ -437,7 +440,7 @@ def test_isel_dataarray(self): with self.roundtrip(in_memory) as on_disk: expected = in_memory.isel(dim2=in_memory['dim2'] < 3) actual = on_disk.isel(dim2=on_disk['dim2'] < 3) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def validate_array_type(self, ds): # Make sure that only NumpyIndexingAdapter stores a bare np.ndarray. @@ -455,7 +458,7 @@ def find_and_validate_array(obj): assert isinstance(obj, indexing.PandasIndexAdapter) else: raise TypeError('{} is wrapped by {}'.format( - type(obj.array), type(obj))) + type(obj.array), type(obj))) for k, v in ds.variables.items(): find_and_validate_array(v._data) @@ -507,12 +510,13 @@ def test_roundtrip_bytes_with_fill_value(self): encoding = {'_FillValue': b'X', 'dtype': 'S1'} original = Dataset({'x': ('t', values, {}, encoding)}) expected = original.copy(deep=True) + print(original) with self.roundtrip(original) as actual: - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) original = Dataset({'x': ('t', values, {}, {'_FillValue': b''})}) with self.roundtrip(original) as actual: - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_roundtrip_string_with_fill_value_nchar(self): values = np.array([u'ab', u'cdef', np.nan], dtype=object) @@ -523,7 +527,7 @@ def test_roundtrip_string_with_fill_value_nchar(self): # Not supported yet. with pytest.raises(NotImplementedError): with self.roundtrip(original) as actual: - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_unsigned_roundtrip_mask_and_scale(self): decoded = create_unsigned_masked_scaled_data() @@ -532,58 +536,58 @@ def test_unsigned_roundtrip_mask_and_scale(self): for k in decoded.variables: self.assertEqual(decoded.variables[k].dtype, actual.variables[k].dtype) - self.assertDatasetAllClose(decoded, actual, decode_bytes=False) + assert_allclose(decoded, actual, decode_bytes=False) with self.roundtrip(decoded, open_kwargs=dict(decode_cf=False)) as actual: for k in encoded.variables: self.assertEqual(encoded.variables[k].dtype, actual.variables[k].dtype) - self.assertDatasetAllClose(encoded, actual, decode_bytes=False) + assert_allclose(encoded, actual, decode_bytes=False) with self.roundtrip(encoded, open_kwargs=dict(decode_cf=False)) as actual: for k in encoded.variables: self.assertEqual(encoded.variables[k].dtype, actual.variables[k].dtype) - self.assertDatasetAllClose(encoded, actual, decode_bytes=False) + assert_allclose(encoded, actual, decode_bytes=False) # make sure roundtrip encoding didn't change the # original dataset. - self.assertDatasetAllClose( + assert_allclose( encoded, create_encoded_unsigned_masked_scaled_data()) with self.roundtrip(encoded) as actual: for k in decoded.variables: self.assertEqual(decoded.variables[k].dtype, actual.variables[k].dtype) - self.assertDatasetAllClose(decoded, actual, decode_bytes=False) + assert_allclose(decoded, actual, decode_bytes=False) with self.roundtrip(encoded, open_kwargs=dict(decode_cf=False)) as actual: for k in encoded.variables: self.assertEqual(encoded.variables[k].dtype, actual.variables[k].dtype) - self.assertDatasetAllClose(encoded, actual, decode_bytes=False) + assert_allclose(encoded, actual, decode_bytes=False) def test_roundtrip_mask_and_scale(self): decoded = create_masked_and_scaled_data() encoded = create_encoded_masked_and_scaled_data() with self.roundtrip(decoded) as actual: - self.assertDatasetAllClose(decoded, actual, decode_bytes=False) + assert_allclose(decoded, actual, decode_bytes=False) with self.roundtrip(decoded, open_kwargs=dict(decode_cf=False)) as actual: # TODO: this assumes that all roundtrips will first # encode. Is that something we want to test for? - self.assertDatasetAllClose(encoded, actual, decode_bytes=False) + assert_allclose(encoded, actual, decode_bytes=False) with self.roundtrip(encoded, open_kwargs=dict(decode_cf=False)) as actual: - self.assertDatasetAllClose(encoded, actual, decode_bytes=False) + assert_allclose(encoded, actual, decode_bytes=False) # make sure roundtrip encoding didn't change the # original dataset. - self.assertDatasetAllClose(encoded, - create_encoded_masked_and_scaled_data(), - decode_bytes=False) + assert_allclose(encoded, + create_encoded_masked_and_scaled_data(), + decode_bytes=False) with self.roundtrip(encoded) as actual: - self.assertDatasetAllClose(decoded, actual, decode_bytes=False) + assert_allclose(decoded, actual, decode_bytes=False) with self.roundtrip(encoded, open_kwargs=dict(decode_cf=False)) as actual: - self.assertDatasetAllClose(encoded, actual, decode_bytes=False) + assert_allclose(encoded, actual, decode_bytes=False) def test_coordinates_encoding(self): def equals_latlon(obj): @@ -592,19 +596,20 @@ def equals_latlon(obj): original = Dataset({'temp': ('x', [0, 1]), 'precip': ('x', [0, -1])}, {'lat': ('x', [2, 3]), 'lon': ('x', [4, 5])}) with self.roundtrip(original) as actual: - self.assertDatasetIdentical(actual, original) + assert_identical(actual, original) with create_tmp_file() as tmp_file: original.to_netcdf(tmp_file) with open_dataset(tmp_file, decode_coords=False) as ds: self.assertTrue(equals_latlon(ds['temp'].attrs['coordinates'])) - self.assertTrue(equals_latlon(ds['precip'].attrs['coordinates'])) + self.assertTrue( + equals_latlon(ds['precip'].attrs['coordinates'])) self.assertNotIn('coordinates', ds.attrs) self.assertNotIn('coordinates', ds['lat'].attrs) self.assertNotIn('coordinates', ds['lon'].attrs) modified = original.drop(['temp', 'precip']) with self.roundtrip(modified) as actual: - self.assertDatasetIdentical(actual, modified) + assert_identical(actual, modified) with create_tmp_file() as tmp_file: modified.to_netcdf(tmp_file) with open_dataset(tmp_file, decode_coords=False) as ds: @@ -623,7 +628,7 @@ def test_roundtrip_endian(self): # one hold mixed endian data (ds) the other should be # all big endian (actual). assertDatasetIdentical # should still pass though. - self.assertDatasetIdentical(ds, actual) + assert_identical(ds, actual) if type(self) is NetCDF4DataTest: ds['z'].encoding['endian'] = 'big' @@ -639,7 +644,7 @@ def test_invalid_dataarray_names_raise(self): for name, e in zip([0, (4, 5), True, ''], [te, te, te, ve]): ds = Dataset({name: da}) with raises_regex(*e): - with self.roundtrip(ds) as actual: + with self.roundtrip(ds): pass def test_encoding_kwarg(self): @@ -669,7 +674,7 @@ def test_encoding_kwarg(self): kwargs = dict(encoding={'t': {'units': units}}) with self.roundtrip(ds, save_kwargs=kwargs) as actual: self.assertEqual(actual.t.encoding['units'], units) - self.assertDatasetIdentical(actual, ds) + assert_identical(actual, ds) def test_default_fill_value(self): # Test default encoding for float: @@ -710,7 +715,7 @@ def test_append_write(self): # regression for GH1215 data = create_test_data() with self.roundtrip_append(data) as actual: - self.assertDatasetIdentical(data, actual) + assert_identical(data, actual) def test_append_overwrite_values(self): # regression for GH1215 @@ -721,7 +726,7 @@ def test_append_overwrite_values(self): data['var9'] = data['var2'] * 3 self.save(data[['var2', 'var9']], tmp_file, mode='a') with self.open(tmp_file) as actual: - self.assertDatasetIdentical(data, actual) + assert_identical(data, actual) def test_vectorized_indexing(self): self._test_vectorized_indexing(vindex_support=False) @@ -782,7 +787,7 @@ def test_open_group(self): # check equivalent ways to specify group for group in 'foo', '/foo', 'foo/', '/foo/': with open_dataset(tmp_file, group=group) as actual: - self.assertVariableEqual(actual['x'], expected['x']) + assert_equal(actual['x'], expected['x']) # check that missing group raises appropriate exception with pytest.raises(IOError): @@ -791,7 +796,7 @@ def test_open_group(self): open_dataset(tmp_file, group=(1, 2, 3)) def test_open_subgroup(self): - # Create a netCDF file with a dataset stored within a group within a group + # Create a netCDF file with a dataset within a group within a group with create_tmp_file() as tmp_file: rootgrp = nc4.Dataset(tmp_file, 'w') foogrp = rootgrp.createGroup('foo') @@ -809,7 +814,7 @@ def test_open_subgroup(self): # check equivalent ways to specify group for group in 'foo/bar', '/foo/bar', 'foo/bar/', '/foo/bar/': with open_dataset(tmp_file, group=group) as actual: - self.assertVariableEqual(actual['x'], expected['x']) + assert_equal(actual['x'], expected['x']) def test_write_groups(self): data1 = create_test_data() @@ -818,9 +823,9 @@ def test_write_groups(self): data1.to_netcdf(tmp_file, group='data/1') data2.to_netcdf(tmp_file, group='data/2', mode='a') with open_dataset(tmp_file, group='data/1') as actual1: - self.assertDatasetIdentical(data1, actual1) + assert_identical(data1, actual1) with open_dataset(tmp_file, group='data/2') as actual2: - self.assertDatasetIdentical(data2, actual2) + assert_identical(data2, actual2) def test_roundtrip_string_with_fill_value_vlen(self): values = np.array([u'ab', u'cdef', np.nan], dtype=object) @@ -833,12 +838,12 @@ def test_roundtrip_string_with_fill_value_vlen(self): original = Dataset({'x': ('t', values, {}, {'_FillValue': u'XXX'})}) with pytest.raises(NotImplementedError): with self.roundtrip(original) as actual: - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) original = Dataset({'x': ('t', values, {}, {'_FillValue': u''})}) with pytest.raises(NotImplementedError): with self.roundtrip(original) as actual: - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_roundtrip_character_array(self): with create_tmp_file() as tmp_file: @@ -853,15 +858,15 @@ def test_roundtrip_character_array(self): values = np.array(['abc', 'def'], dtype='S') expected = Dataset({'x': ('x', values)}) with open_dataset(tmp_file) as actual: - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) # regression test for #157 with self.roundtrip(actual) as roundtripped: - self.assertDatasetIdentical(expected, roundtripped) + assert_identical(expected, roundtripped) def test_default_to_char_arrays(self): data = Dataset({'x': np.array(['foo', 'zzzz'], dtype='S')}) with self.roundtrip(data) as actual: - self.assertDatasetIdentical(data, actual) + assert_identical(data, actual) self.assertEqual(actual['x'].dtype, np.dtype('S4')) def test_open_encodings(self): @@ -883,11 +888,12 @@ def test_open_encodings(self): expected['time'] = ('time', time, {}, encoding) with open_dataset(tmp_file) as actual: - self.assertVariableEqual(actual['time'], expected['time']) + assert_equal(actual['time'], expected['time']) actual_encoding = dict((k, v) for k, v in iteritems(actual['time'].encoding) if k in expected['time'].encoding) - self.assertDictEqual(actual_encoding, expected['time'].encoding) + self.assertDictEqual(actual_encoding, + expected['time'].encoding) def test_dump_encodings(self): # regression test for #709 @@ -912,8 +918,10 @@ def test_dump_and_open_encodings(self): with create_tmp_file() as tmp_file2: xarray_dataset.to_netcdf(tmp_file2) with nc4.Dataset(tmp_file2, 'r') as ds: - self.assertEqual(ds.variables['time'].getncattr('units'), units) - self.assertArrayEqual(ds.variables['time'], np.arange(10) + 4) + self.assertEqual( + ds.variables['time'].getncattr('units'), units) + assert_array_equal( + ds.variables['time'], np.arange(10) + 4) def test_compression_encoding(self): data = create_test_data() @@ -929,7 +937,7 @@ def test_compression_encoding(self): # regression test for #156 expected = data.isel(dim1=0) with self.roundtrip(expected) as actual: - self.assertDatasetEqual(expected, actual) + assert_equal(expected, actual) def test_encoding_chunksizes_unlimited(self): # regression test for GH1225 @@ -944,7 +952,7 @@ def test_encoding_chunksizes_unlimited(self): 'original_shape': (3,), } with self.roundtrip(ds) as actual: - self.assertDatasetEqual(ds, actual) + assert_equal(ds, actual) def test_mask_and_scale(self): with create_tmp_file() as tmp_file: @@ -963,12 +971,12 @@ def test_mask_and_scale(self): expected = np.ma.array([-1, -1, 10, 10.1, 10.2], mask=[True, True, False, False, False]) actual = nc.variables['x'][:] - self.assertArrayEqual(expected, actual) + assert_array_equal(expected, actual) # now check xarray with open_dataset(tmp_file) as ds: expected = create_masked_and_scaled_data() - self.assertDatasetIdentical(expected, ds) + assert_identical(expected, ds) def test_0dimensional_variable(self): # This fix verifies our work-around to this netCDF4-python bug: @@ -980,7 +988,7 @@ def test_0dimensional_variable(self): with open_dataset(tmp_file) as ds: expected = Dataset({'x': ((), 123)}) - self.assertDatasetIdentical(expected, ds) + assert_identical(expected, ds) def test_already_open_dataset(self): with create_tmp_file() as tmp_file: @@ -992,7 +1000,7 @@ def test_already_open_dataset(self): with backends.NetCDF4DataStore(nc, autoclose=False) as store: with open_dataset(store) as ds: expected = Dataset({'x': ((), 42)}) - self.assertDatasetIdentical(expected, ds) + assert_identical(expected, ds) def test_variable_len_strings(self): with create_tmp_file() as tmp_file: @@ -1006,7 +1014,7 @@ def test_variable_len_strings(self): expected = Dataset({'x': ('x', values)}) for kwargs in [{}, {'decode_cf': True}]: with open_dataset(tmp_file, **kwargs) as actual: - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) @requires_netCDF4 @@ -1042,11 +1050,22 @@ def test_unsorted_index_raises(self): with self.roundtrip(ds) as ondisk: inds = np.argsort(dim1) ds2 = ondisk.isel(dim1=inds) + # Older versions of NetCDF4 raise an exception here, and if so we + # want to ensure we improve (that is, replace) the error message try: - print(ds2.randovar.values) # should raise IndexError in netCDF4 + ds2.randovar.values except IndexError as err: self.assertIn('first by calling .load', str(err)) + def test_88_character_filename_segmentation_fault(self): + # should be fixed in netcdf4 v1.3.1 + with mock.patch('netCDF4.__version__', '1.2.4'): + with warnings.catch_warnings(): + warnings.simplefilter("error") + with raises_regex(Warning, 'segmentation fault'): + # Need to construct 88 character filepath + xr.Dataset().to_netcdf('a' * (88 - len(os.getcwd()) - 1)) + class NetCDF4DataStoreAutocloseTrue(NetCDF4DataTest): autoclose = True @@ -1080,6 +1099,249 @@ class NetCDF4ViaDaskDataTestAutocloseTrue(NetCDF4ViaDaskDataTest): autoclose = True +@requires_zarr +class BaseZarrTest(CFEncodedDataTest): + + DIMENSION_KEY = '_ARRAY_DIMENSIONS' + + @contextlib.contextmanager + def create_store(self): + with self.create_zarr_target() as store_target: + yield backends.ZarrStore.open_group(store_target, mode='w') + + @contextlib.contextmanager + def roundtrip(self, data, save_kwargs={}, open_kwargs={}, + allow_cleanup_failure=False): + with self.create_zarr_target() as store_target: + data.to_zarr(store=store_target, **save_kwargs) + yield xr.open_zarr(store_target, **open_kwargs) + + def test_auto_chunk(self): + original = create_test_data().chunk() + + with self.roundtrip( + original, open_kwargs={'auto_chunk': False}) as actual: + for k, v in actual.variables.items(): + # only index variables should be in memory + self.assertEqual(v._in_memory, k in actual.dims) + # there should be no chunks + self.assertEqual(v.chunks, None) + + with self.roundtrip( + original, open_kwargs={'auto_chunk': True}) as actual: + for k, v in actual.variables.items(): + # only index variables should be in memory + self.assertEqual(v._in_memory, k in actual.dims) + # chunk size should be the same as original + self.assertEqual(v.chunks, original[k].chunks) + + def test_chunk_encoding(self): + # These datasets have no dask chunks. All chunking specified in + # encoding + data = create_test_data() + chunks = (5, 5) + data['var2'].encoding.update({'chunks': chunks}) + + with self.roundtrip(data) as actual: + self.assertEqual(chunks, actual['var2'].encoding['chunks']) + + # expect an error with non-integer chunks + data['var2'].encoding.update({'chunks': (5, 4.5)}) + with pytest.raises(TypeError): + with self.roundtrip(data) as actual: + pass + + def test_chunk_encoding_with_dask(self): + # These datasets DO have dask chunks. Need to check for various + # interactions between dask and zarr chunks + ds = xr.DataArray((np.arange(12)), dims='x', name='var1').to_dataset() + + # - no encoding specified - + # zarr automatically gets chunk information from dask chunks + ds_chunk4 = ds.chunk({'x': 4}) + with self.roundtrip(ds_chunk4) as actual: + self.assertEqual((4,), actual['var1'].encoding['chunks']) + + # should fail if dask_chunks are irregular... + ds_chunk_irreg = ds.chunk({'x': (5, 4, 3)}) + with pytest.raises(ValueError) as e_info: + with self.roundtrip(ds_chunk_irreg) as actual: + pass + # make sure this error message is correct and not some other error + assert e_info.match('chunks') + + # ... except if the last chunk is smaller than the first + ds_chunk_irreg = ds.chunk({'x': (5, 5, 2)}) + with self.roundtrip(ds_chunk_irreg) as actual: + self.assertEqual((5,), actual['var1'].encoding['chunks']) + + # - encoding specified - + # specify compatible encodings + for chunk_enc in 4, (4, ): + ds_chunk4['var1'].encoding.update({'chunks': chunk_enc}) + with self.roundtrip(ds_chunk4) as actual: + self.assertEqual((4,), actual['var1'].encoding['chunks']) + + # specify incompatible encoding + ds_chunk4['var1'].encoding.update({'chunks': (5, 5)}) + with pytest.raises(ValueError) as e_info: + with self.roundtrip(ds_chunk4) as actual: + pass + assert e_info.match('chunks') + + # TODO: remove this failure once syncronized overlapping writes are + # supported by xarray + ds_chunk4['var1'].encoding.update({'chunks': 5}) + with pytest.raises(NotImplementedError): + with self.roundtrip(ds_chunk4) as actual: + pass + + def test_vectorized_indexing(self): + self._test_vectorized_indexing(vindex_support=True) + + def test_hidden_zarr_keys(self): + expected = create_test_data() + with self.create_store() as store: + expected.dump_to_store(store) + zarr_group = store.ds + + # check that the global hidden attribute is present + assert self.DIMENSION_KEY in zarr_group.attrs + + # check that a variable hidden attribute is present and correct + # JSON only has a single array type, which maps to list in Python. + # In contrast, dims in xarray is always a tuple. + for var in expected.variables.keys(): + assert (zarr_group[var].attrs[self.DIMENSION_KEY] == + list(expected[var].dims)) + + with xr.decode_cf(store) as actual: + # make sure it is hidden + assert self.DIMENSION_KEY not in actual.attrs + for var in expected.variables.keys(): + assert self.DIMENSION_KEY not in expected[var].attrs + + # verify that the dataset fails to open if dimension key is missing + del zarr_group.attrs[self.DIMENSION_KEY] + with pytest.raises(KeyError): + with xr.decode_cf(store) as actual: + pass + + # put it back and try removing from a variable + zarr_group.attrs[self.DIMENSION_KEY] = {} + del zarr_group.var2.attrs[self.DIMENSION_KEY] + with pytest.raises(KeyError): + with xr.decode_cf(store) as actual: + pass + + def test_write_persistence_modes(self): + original = create_test_data() + + # overwrite mode + with self.roundtrip(original, save_kwargs={'mode': 'w'}) as actual: + assert_identical(original, actual) + + # don't overwrite mode + with self.roundtrip(original, save_kwargs={'mode': 'w-'}) as actual: + assert_identical(original, actual) + + # make sure overwriting works as expected + with self.create_zarr_target() as store: + original.to_zarr(store) + # should overwrite with no error + original.to_zarr(store, mode='w') + actual = xr.open_zarr(store) + assert_identical(original, actual) + with pytest.raises(ValueError): + original.to_zarr(store, mode='w-') + + # check that we can't use other persistence modes + # TODO: reconsider whether other persistence modes should be supported + with pytest.raises(ValueError): + with self.roundtrip(original, save_kwargs={'mode': 'a'}) as actual: + pass + + def test_compressor_encoding(self): + original = create_test_data() + # specify a custom compressor + import zarr + blosc_comp = zarr.Blosc(cname='zstd', clevel=3, shuffle=2) + save_kwargs = dict(encoding={'var1': {'compressor': blosc_comp}}) + with self.roundtrip(original, save_kwargs=save_kwargs) as actual: + assert actual.var1.encoding['compressor'] == blosc_comp + + def test_group(self): + original = create_test_data() + group = 'some/random/path' + with self.roundtrip(original, save_kwargs={'group': group}, + open_kwargs={'group': group}) as actual: + assert_identical(original, actual) + with pytest.raises(KeyError): + with self.roundtrip(original, + save_kwargs={'group': group}) as actual: + assert_identical(original, actual) + + # TODO: implement zarr object encoding and make these tests pass + @pytest.mark.xfail(reason="Zarr object encoding not implemented") + def test_multiindex_not_implemented(self): + super(CFEncodedDataTest, self).test_multiindex_not_implemented() + + @pytest.mark.xfail(reason="Zarr object encoding not implemented") + def test_roundtrip_bytes_with_fill_value(self): + super(CFEncodedDataTest, self).test_roundtrip_bytes_with_fill_value() + + @pytest.mark.xfail(reason="Zarr object encoding not implemented") + def test_roundtrip_object_dtype(self): + super(CFEncodedDataTest, self).test_roundtrip_object_dtype() + + @pytest.mark.xfail(reason="Zarr object encoding not implemented") + def test_roundtrip_string_encoded_characters(self): + super(CFEncodedDataTest, + self).test_roundtrip_string_encoded_characters() + + # TODO: someone who understand caching figure out whether chaching + # makes sense for Zarr backend + @pytest.mark.xfail(reason="Zarr caching not implemented") + def test_dataset_caching(self): + super(CFEncodedDataTest, self).test_dataset_caching() + + +@requires_zarr +class ZarrDictStoreTest(BaseZarrTest, TestCase): + @contextlib.contextmanager + def create_zarr_target(self): + yield {} + + +@requires_zarr +class ZarrDirectoryStoreTest(BaseZarrTest, TestCase): + @contextlib.contextmanager + def create_zarr_target(self): + with create_tmp_file(suffix='.zarr') as tmp: + yield tmp + + +def test_replace_slices_with_arrays(): + (actual,) = xr.backends.zarr._replace_slices_with_arrays( + key=(slice(None),), shape=(5,)) + np.testing.assert_array_equal(actual, np.arange(5)) + + actual = xr.backends.zarr._replace_slices_with_arrays( + key=(np.arange(5),) * 3, shape=(8, 10, 12)) + expected = np.stack([np.arange(5)] * 3) + np.testing.assert_array_equal(np.stack(actual), expected) + + a, b = xr.backends.zarr._replace_slices_with_arrays( + key=(np.arange(5), slice(None)), shape=(8, 10)) + np.testing.assert_array_equal(a, np.arange(5)[:, np.newaxis]) + np.testing.assert_array_equal(b, np.arange(10)[np.newaxis, :]) + + a, b = xr.backends.zarr._replace_slices_with_arrays( + key=(slice(None), np.arange(5)), shape=(8, 10)) + np.testing.assert_array_equal(a, np.arange(8)[np.newaxis, :]) + np.testing.assert_array_equal(b, np.arange(5)[:, np.newaxis]) + + @requires_scipy class ScipyInMemoryDataTest(CFEncodedDataTest, NetCDF3Only, TestCase): engine = 'scipy' @@ -1099,7 +1361,7 @@ def test_bytesio_pickle(self): fobj = BytesIO(data.to_netcdf()) with open_dataset(fobj, autoclose=self.autoclose) as ds: unpickled = pickle.loads(pickle.dumps(ds)) - self.assertDatasetIdentical(unpickled, data) + assert_identical(unpickled, data) class ScipyInMemoryDataTestAutocloseTrue(ScipyInMemoryDataTest): @@ -1147,13 +1409,13 @@ def create_store(self): def test_array_attrs(self): ds = Dataset(attrs={'foo': [[1, 2], [3, 4]]}) with raises_regex(ValueError, 'must be 1-dimensional'): - with self.roundtrip(ds) as roundtripped: + with self.roundtrip(ds): pass def test_roundtrip_example_1_netcdf_gz(self): with open_example_dataset('example_1.nc.gz') as expected: with open_example_dataset('example_1.nc') as actual: - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_netcdf3_endianness(self): # regression test for GH416 @@ -1266,12 +1528,12 @@ def test_encoding_unlimited_dims(self): with self.roundtrip(ds, save_kwargs=dict(unlimited_dims=['y'])) as actual: self.assertEqual(actual.encoding['unlimited_dims'], set('y')) - self.assertDatasetEqual(ds, actual) + assert_equal(ds, actual) ds.encoding = {'unlimited_dims': ['y']} with self.roundtrip(ds) as actual: self.assertEqual(actual.encoding['unlimited_dims'], set('y')) - self.assertDatasetEqual(ds, actual) + assert_equal(ds, actual) class GenericNetCDFDataTestAutocloseTrue(GenericNetCDFDataTest): @@ -1299,7 +1561,7 @@ def test_array_type_after_indexing(self): def test_complex(self): expected = Dataset({'x': ('y', np.ones(5) + 1j * np.ones(5))}) with self.roundtrip(expected) as actual: - self.assertDatasetEqual(expected, actual) + assert_equal(expected, actual) @pytest.mark.xfail(reason='https://github.com/pydata/xarray/issues/535') def test_cross_engine_read_write_netcdf4(self): @@ -1314,7 +1576,7 @@ def test_cross_engine_read_write_netcdf4(self): data.to_netcdf(tmp_file, engine=write_engine) for read_engine in valid_engines: with open_dataset(tmp_file, engine=read_engine) as actual: - self.assertDatasetIdentical(data, actual) + assert_identical(data, actual) def test_read_byte_attrs_as_unicode(self): with create_tmp_file() as tmp_file: @@ -1322,18 +1584,18 @@ def test_read_byte_attrs_as_unicode(self): nc.foo = b'bar' with open_dataset(tmp_file) as actual: expected = Dataset(attrs={'foo': 'bar'}) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_encoding_unlimited_dims(self): ds = Dataset({'x': ('y', np.arange(10.0))}) with self.roundtrip(ds, save_kwargs=dict(unlimited_dims=['y'])) as actual: self.assertEqual(actual.encoding['unlimited_dims'], set('y')) - self.assertDatasetEqual(ds, actual) + assert_equal(ds, actual) ds.encoding = {'unlimited_dims': ['y']} with self.roundtrip(ds) as actual: self.assertEqual(actual.encoding['unlimited_dims'], set('y')) - self.assertDatasetEqual(ds, actual) + assert_equal(ds, actual) # tests pending h5netcdf fix @@ -1353,13 +1615,14 @@ def validate_open_mfdataset_autoclose(self, engine, nfiles=10): else 'netcdf4') # split into multiple sets of temp files for ii in original.x.values: - subds = original.isel(x=slice(ii, ii+1)) + subds = original.isel(x=slice(ii, ii + 1)) subds.to_netcdf(tmpfiles[ii], engine=writeengine) # check that calculation on opened datasets works properly ds = open_mfdataset(tmpfiles, engine=readengine, autoclose=True) - self.assertAllClose(ds.x.sum().values, (nfiles*(nfiles-1))/2) + self.assertAllClose(ds.x.sum().values, + (nfiles * (nfiles - 1)) / 2) self.assertAllClose(ds.foo.sum().values, np.sum(randdata)) self.assertAllClose(ds.sum().foo.values, np.sum(randdata)) ds.close() @@ -1458,14 +1721,14 @@ def gen_datasets_with_common_coord_and_time(self): coords={ 't': (['t', ], t1), 'x': (['x', ], x) - }) + }) ds2 = Dataset(data_vars={self.var_name: (['t', 'x'], v2), self.coord_name: ('x', 2 * x)}, coords={ 't': (['t', ], t2), 'x': (['x', ], x) - }) + }) return ds1, ds2 @@ -1477,12 +1740,12 @@ def test_open_mfdataset_does_same_as_concat(self): with open_mfdataset(files, data_vars=opt) as ds: kwargs = dict(data_vars=opt, dim='t') ds_expect = xr.concat([ds1, ds2], **kwargs) - self.assertDatasetIdentical(ds, ds_expect) + assert_identical(ds, ds_expect) with open_mfdataset(files, coords=opt) as ds: kwargs = dict(coords=opt, dim='t') ds_expect = xr.concat([ds1, ds2], **kwargs) - self.assertDatasetIdentical(ds, ds_expect) + assert_identical(ds, ds_expect) def test_common_coord_when_datavars_all(self): opt = 'all' @@ -1557,7 +1820,7 @@ def test_roundtrip_datetime_data(self): times = pd.to_datetime(['2000-01-01', '2000-01-02', 'NaT']) expected = Dataset({'t': ('t', times), 't0': times[0]}) with self.roundtrip(expected) as actual: - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_write_store(self): # Override method in DatasetIOTestCases - not applicable to dask @@ -1581,7 +1844,7 @@ def test_open_mfdataset(self): self.assertIsInstance(actual.foo.variable.data, da.Array) self.assertEqual(actual.foo.variable.data.chunks, ((5, 5),)) - self.assertDatasetIdentical(original, actual) + assert_identical(original, actual) with open_mfdataset([tmp1, tmp2], chunks={'x': 3}, autoclose=self.autoclose) as actual: self.assertEqual(actual.foo.variable.data.chunks, @@ -1601,7 +1864,7 @@ def test_open_mfdataset_pathlib(self): original.isel(x=slice(5, 10)).to_netcdf(tmp2) with open_mfdataset([tmp1, tmp2], autoclose=self.autoclose) as actual: - self.assertDatasetIdentical(original, actual) + assert_identical(original, actual) def test_attrs_mfdataset(self): original = Dataset({'foo': ('x', np.random.randn(10))}) @@ -1619,7 +1882,7 @@ def test_attrs_mfdataset(self): self.assertEqual(actual.test1, ds1.test1) # attributes from ds2 are not retained, e.g., with raises_regex(AttributeError, - 'no attribute'): + 'no attribute'): actual.test2 def test_preprocess_mfdataset(self): @@ -1633,7 +1896,7 @@ def preprocess(ds): expected = preprocess(original) with open_mfdataset(tmp, preprocess=preprocess, autoclose=self.autoclose) as actual: - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_save_mfdataset_roundtrip(self): original = Dataset({'foo': ('x', np.random.randn(10))}) @@ -1644,7 +1907,7 @@ def test_save_mfdataset_roundtrip(self): save_mfdataset(datasets, [tmp1, tmp2]) with open_mfdataset([tmp1, tmp2], autoclose=self.autoclose) as actual: - self.assertDatasetIdentical(actual, original) + assert_identical(actual, original) def test_save_mfdataset_invalid(self): ds = Dataset() @@ -1671,7 +1934,7 @@ def test_save_mfdataset_pathlib_roundtrip(self): save_mfdataset(datasets, [tmp1, tmp2]) with open_mfdataset([tmp1, tmp2], autoclose=self.autoclose) as actual: - self.assertDatasetIdentical(actual, original) + assert_identical(actual, original) def test_open_and_do_math(self): original = Dataset({'foo': ('x', np.random.randn(10))}) @@ -1679,8 +1942,7 @@ def test_open_and_do_math(self): original.to_netcdf(tmp) with open_mfdataset(tmp, autoclose=self.autoclose) as ds: actual = 1.0 * ds - self.assertDatasetAllClose(original, actual, - decode_bytes=False) + assert_allclose(original, actual, decode_bytes=False) def test_open_mfdataset_concat_dim_none(self): with create_tmp_file() as tmp1: @@ -1690,7 +1952,7 @@ def test_open_mfdataset_concat_dim_none(self): Dataset({'x': np.nan}).to_netcdf(tmp2) with open_mfdataset([tmp1, tmp2], concat_dim=None, autoclose=self.autoclose) as actual: - self.assertDatasetIdentical(data, actual) + assert_identical(data, actual) def test_open_dataset(self): original = Dataset({'foo': ('x', np.random.randn(10))}) @@ -1699,12 +1961,12 @@ def test_open_dataset(self): with open_dataset(tmp, chunks={'x': 5}) as actual: self.assertIsInstance(actual.foo.variable.data, da.Array) self.assertEqual(actual.foo.variable.data.chunks, ((5, 5),)) - self.assertDatasetIdentical(original, actual) + assert_identical(original, actual) with open_dataset(tmp, chunks=5) as actual: - self.assertDatasetIdentical(original, actual) + assert_identical(original, actual) with open_dataset(tmp) as actual: self.assertIsInstance(actual.foo.variable.data, np.ndarray) - self.assertDatasetIdentical(original, actual) + assert_identical(original, actual) def test_dask_roundtrip(self): with create_tmp_file() as tmp: @@ -1712,11 +1974,11 @@ def test_dask_roundtrip(self): data.to_netcdf(tmp) chunks = {'dim1': 4, 'dim2': 4, 'dim3': 4, 'time': 10} with open_dataset(tmp, chunks=chunks) as dask_ds: - self.assertDatasetIdentical(data, dask_ds) + assert_identical(data, dask_ds) with create_tmp_file() as tmp2: dask_ds.to_netcdf(tmp2) with open_dataset(tmp2) as on_disk: - self.assertDatasetIdentical(data, on_disk) + assert_identical(data, on_disk) def test_deterministic_names(self): with create_tmp_file() as tmp: @@ -1737,11 +1999,11 @@ def test_dataarray_compute(self): # Test DataArray.compute() on dask backend. # The test for Dataset.compute() is already in DatasetIOTestCases; # however dask is the only tested backend which supports DataArrays - actual = DataArray([1,2]).chunk() + actual = DataArray([1, 2]).chunk() computed = actual.compute() self.assertFalse(actual._in_memory) self.assertTrue(computed._in_memory) - self.assertDataArrayAllClose(actual, computed, decode_bytes=False) + assert_allclose(actual, computed, decode_bytes=False) def test_vectorized_indexing(self): self._test_vectorized_indexing(vindex_support=True) @@ -1751,40 +2013,87 @@ class DaskTestAutocloseTrue(DaskTest): autoclose = True -@network @requires_scipy_or_netCDF4 @requires_pydap class PydapTest(TestCase): + def convert_to_pydap_dataset(self, original): + from pydap.model import GridType, BaseType, DatasetType + ds = DatasetType('bears', **original.attrs) + for key, var in original.data_vars.items(): + v = GridType(key) + v[key] = BaseType(key, var.values, dimensions=var.dims, + **var.attrs) + for d in var.dims: + v[d] = BaseType(d, var[d].values) + ds[key] = v + # check all dims are stored in ds + for d in original.coords: + ds[d] = BaseType(d, original[d].values, dimensions=(d, ), + **original[d].attrs) + return ds + @contextlib.contextmanager def create_datasets(self, **kwargs): - url = 'http://test.opendap.org/opendap/hyrax/data/nc/bears.nc' - actual = open_dataset(url, engine='pydap', **kwargs) with open_example_dataset('bears.nc') as expected: - # don't check attributes since pydap doesn't serialize them - # correctly also skip the "bears" variable since the test DAP - # server incorrectly concatenates it. - actual = actual.drop('bears') - expected = expected.drop('bears') + pydap_ds = self.convert_to_pydap_dataset(expected) + actual = open_dataset(PydapDataStore(pydap_ds)) + # TODO solve this workaround: + # netcdf converts string to byte not unicode + expected['bears'] = expected['bears'].astype(str) yield actual, expected def test_cmp_local_file(self): with self.create_datasets() as (actual, expected): - self.assertDatasetEqual(actual, expected) + assert_equal(actual, expected) # global attributes should be global attributes on the dataset self.assertNotIn('NC_GLOBAL', actual.attrs) self.assertIn('history', actual.attrs) + # we don't check attributes exactly with assertDatasetIdentical() + # because the test DAP server seems to insert some extra + # attributes not found in the netCDF file. + assert actual.attrs.keys() == expected.attrs.keys() + with self.create_datasets() as (actual, expected): - self.assertDatasetEqual(actual.isel(l=2), expected.isel(l=2)) + assert_equal( + actual.isel(l=2), expected.isel(l=2)) # noqa: E741 with self.create_datasets() as (actual, expected): - self.assertDatasetEqual(actual.isel(i=0, j=-1), - expected.isel(i=0, j=-1)) + assert_equal(actual.isel(i=0, j=-1), + expected.isel(i=0, j=-1)) with self.create_datasets() as (actual, expected): - self.assertDatasetEqual(actual.isel(j=slice(1, 2)), - expected.isel(j=slice(1, 2))) + assert_equal(actual.isel(j=slice(1, 2)), + expected.isel(j=slice(1, 2))) + + def test_compatible_to_netcdf(self): + # make sure it can be saved as a netcdf + with self.create_datasets() as (actual, expected): + with create_tmp_file() as tmp_file: + actual.to_netcdf(tmp_file) + actual = open_dataset(tmp_file) + actual['bears'] = actual['bears'].astype(str) + assert_equal(actual, expected) + + @requires_dask + def test_dask(self): + with self.create_datasets(chunks={'j': 2}) as (actual, expected): + assert_equal(actual, expected) + + +@network +@requires_scipy_or_netCDF4 +@requires_pydap +class PydapOnlineTest(PydapTest): + @contextlib.contextmanager + def create_datasets(self, **kwargs): + url = 'http://test.opendap.org/opendap/hyrax/data/nc/bears.nc' + actual = open_dataset(url, engine='pydap', **kwargs) + with open_example_dataset('bears.nc') as expected: + # workaround to restore string which is converted to byte + expected['bears'] = expected['bears'].astype(str) + yield actual, expected def test_session(self): from pydap.cas.urs import setup_session @@ -1794,11 +2103,6 @@ def test_session(self): xr.backends.PydapDataStore.open('http://test.url', session=session) mock_func.assert_called_with('http://test.url', session=session) - @requires_dask - def test_dask(self): - with self.create_datasets(chunks={'j': 2}) as (actual, expected): - self.assertDatasetEqual(actual, expected) - @requires_scipy @requires_pynio @@ -1838,7 +2142,7 @@ def test_weakrefs(self): on_disk = open_dataset(tmp_file, engine='pynio') actual = on_disk.rename({'foo': 'bar', 'x': 'y'}) del on_disk # trigger garbage collection - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) class TestPyNioAutocloseTrue(TestPyNio): @@ -1857,7 +2161,7 @@ def test_serialization(self): with create_tmp_file(suffix='.tif') as tmp_file: # data nx, ny, nz = 4, 3, 3 - data = np.arange(nx*ny*nz, + data = np.arange(nx * ny * nz, dtype=rasterio.float32).reshape(nz, ny, nx) transform = from_origin(5000, 80000, 1000, 2000.) with rasterio.open( @@ -1876,7 +2180,39 @@ def test_serialization(self): with xr.open_dataarray(tmp_nc_file) as ncds: assert_identical(rioda, ncds) - def test_utm(self): + @requires_scipy_or_netCDF4 + def test_nodata(self): + import rasterio + from rasterio.transform import from_origin + + # Create a geotiff file in utm proj + with create_tmp_file(suffix='.tif') as tmp_file: + # data + nx, ny, nz = 4, 3, 3 + data = np.arange(nx*ny*nz, + dtype=rasterio.float32).reshape(nz, ny, nx) + transform = from_origin(5000, 80000, 1000, 2000.) + with rasterio.open( + tmp_file, 'w', + driver='GTiff', height=ny, width=nx, count=nz, + crs={'units': 'm', 'no_defs': True, 'ellps': 'WGS84', + 'proj': 'utm', 'zone': 18}, + transform=transform, + nodata=-9765, + dtype=rasterio.float32) as s: + s.write(data) + expected_nodatavals = [-9765, -9765, -9765] + with xr.open_rasterio(tmp_file) as rioda: + np.testing.assert_array_equal(rioda.attrs['nodatavals'], + expected_nodatavals) + with create_tmp_file(suffix='.nc') as tmp_nc_file: + rioda.to_netcdf(tmp_nc_file) + with xr.open_dataarray(tmp_nc_file) as ncds: + np.testing.assert_array_equal(ncds.attrs['nodatavals'], + expected_nodatavals) + + @requires_scipy_or_netCDF4 + def test_nodata_missing(self): import rasterio from rasterio.transform import from_origin @@ -1887,6 +2223,36 @@ def test_utm(self): data = np.arange(nx*ny*nz, dtype=rasterio.float32).reshape(nz, ny, nx) transform = from_origin(5000, 80000, 1000, 2000.) + with rasterio.open( + tmp_file, 'w', + driver='GTiff', height=ny, width=nx, count=nz, + crs={'units': 'm', 'no_defs': True, 'ellps': 'WGS84', + 'proj': 'utm', 'zone': 18}, + transform=transform, + dtype=rasterio.float32) as s: + s.write(data) + + expected_nodatavals = [np.nan, np.nan, np.nan] + with xr.open_rasterio(tmp_file) as rioda: + np.testing.assert_array_equal(rioda.attrs['nodatavals'], + expected_nodatavals) + with create_tmp_file(suffix='.nc') as tmp_nc_file: + rioda.to_netcdf(tmp_nc_file) + with xr.open_dataarray(tmp_nc_file) as ncds: + np.testing.assert_array_equal(ncds.attrs['nodatavals'], + expected_nodatavals) + + def test_utm(self): + import rasterio + from rasterio.transform import from_origin + + # Create a geotiff file in utm proj + with create_tmp_file(suffix='.tif') as tmp_file: + # data + nx, ny, nz = 4, 3, 3 + data = np.arange(nx * ny * nz, + dtype=rasterio.float32).reshape(nz, ny, nx) + transform = from_origin(5000, 80000, 1000, 2000.) with rasterio.open( tmp_file, 'w', driver='GTiff', height=ny, width=nx, count=nz, @@ -1898,12 +2264,11 @@ def test_utm(self): dx, dy = s.res[0], -s.res[1] # Tests - expected = DataArray(data, dims=('band', 'y', 'x'), - coords={ - 'band': [1, 2, 3], - 'y': -np.arange(ny) * 2000 + 80000 + dy/2, - 'x': np.arange(nx) * 1000 + 5000 + dx/2, - }) + expected = DataArray(data, dims=('band', 'y', 'x'), coords={ + 'band': [1, 2, 3], + 'y': -np.arange(ny) * 2000 + 80000 + dy / 2, + 'x': np.arange(nx) * 1000 + 5000 + dx / 2, + }) with xr.open_rasterio(tmp_file) as rioda: assert_allclose(rioda, expected) assert 'crs' in rioda.attrs @@ -1939,8 +2304,8 @@ def test_platecarree(self): expected = DataArray(data[np.newaxis, ...], dims=('band', 'y', 'x'), coords={'band': [1], - 'y': -np.arange(ny)*2 + 2 + dy/2, - 'x': np.arange(nx)*0.5 + 1 + dx/2, + 'y': -np.arange(ny) * 2 + 2 + dy / 2, + 'x': np.arange(nx) * 0.5 + 1 + dx / 2, }) with xr.open_rasterio(tmp_file) as rioda: assert_allclose(rioda, expected) @@ -1962,7 +2327,7 @@ def test_indexing(self): with create_tmp_file(suffix='.tif') as tmp_file: # data nx, ny, nz = 8, 10, 3 - data = np.arange(nx*ny*nz, + data = np.arange(nx * ny * nz, dtype=rasterio.float32).reshape(nz, ny, nx) transform = from_origin(1, 2, 0.5, 2.) with rasterio.open( @@ -1975,10 +2340,10 @@ def test_indexing(self): dx, dy = s.res[0], -s.res[1] # ref - expected = DataArray(data, dims=('band', 'y', 'x'), - coords={'x': (np.arange(nx)*0.5 + 1) + dx/2, - 'y': (-np.arange(ny)*2 + 2) + dy/2, - 'band': [1, 2, 3]}) + expected = DataArray(data, dims=('band', 'y', 'x'), coords={ + 'x': (np.arange(nx) * 0.5 + 1) + dx / 2, + 'y': (-np.arange(ny) * 2 + 2) + dy / 2, + 'band': [1, 2, 3]}) with xr.open_rasterio(tmp_file, cache=False) as actual: @@ -2054,7 +2419,7 @@ def test_caching(self): with create_tmp_file(suffix='.tif') as tmp_file: # data nx, ny, nz = 8, 10, 3 - data = np.arange(nx*ny*nz, + data = np.arange(nx * ny * nz, dtype=rasterio.float32).reshape(nz, ny, nx) transform = from_origin(1, 2, 0.5, 2.) with rasterio.open( @@ -2067,10 +2432,11 @@ def test_caching(self): dx, dy = s.res[0], -s.res[1] # ref - expected = DataArray(data, dims=('band', 'y', 'x'), - coords={'x': (np.arange(nx)*0.5 + 1) + dx/2, - 'y': (-np.arange(ny)*2 + 2) + dy/2, - 'band': [1, 2, 3]}) + expected = DataArray( + data, dims=('band', 'y', 'x'), coords={ + 'x': (np.arange(nx) * 0.5 + 1) + dx / 2, + 'y': (-np.arange(ny) * 2 + 2) + dy / 2, + 'band': [1, 2, 3]}) # Cache is the default with xr.open_rasterio(tmp_file) as actual: @@ -2098,7 +2464,7 @@ def test_chunks(self): with create_tmp_file(suffix='.tif') as tmp_file: # data nx, ny, nz = 8, 10, 3 - data = np.arange(nx*ny*nz, + data = np.arange(nx * ny * nz, dtype=rasterio.float32).reshape(nz, ny, nx) transform = from_origin(1, 2, 0.5, 2.) with rasterio.open( @@ -2118,10 +2484,10 @@ def test_chunks(self): assert 'open_rasterio' in actual.data.name # ref - expected = DataArray(data, dims=('band', 'y', 'x'), - coords={'x': np.arange(nx)*0.5 + 1 + dx/2, - 'y': -np.arange(ny)*2 + 2 + dy/2, - 'band': [1, 2, 3]}) + expected = DataArray(data, dims=('band', 'y', 'x'), coords={ + 'x': np.arange(nx) * 0.5 + 1 + dx / 2, + 'y': -np.arange(ny) * 2 + 2 + dy / 2, + 'band': [1, 2, 3]}) # do some arithmetic ac = actual.mean() @@ -2132,6 +2498,53 @@ def test_chunks(self): ex = expected.sel(band=1).mean(dim='x') assert_allclose(ac, ex) + def test_ENVI_tags(self): + rasterio = pytest.importorskip('rasterio', minversion='1.0a') + from rasterio.transform import from_origin + + # Create an ENVI file with some tags in the ENVI namespace + with create_tmp_file(suffix='.dat') as tmp_file: + # data + nx, ny, nz = 4, 3, 3 + data = np.arange(nx * ny * nz, + dtype=rasterio.float32).reshape(nz, ny, nx) + transform = from_origin(5000, 80000, 1000, 2000.) + with rasterio.open( + tmp_file, 'w', + driver='ENVI', height=ny, width=nx, count=nz, + crs={'units': 'm', 'no_defs': True, 'ellps': 'WGS84', + 'proj': 'utm', 'zone': 18}, + transform=transform, + dtype=rasterio.float32) as s: + s.update_tags( + ns='ENVI', + description='{Tagged file}', + wavelength='{123.000000, 234.234000, 345.345678}', + fwhm='{1.000000, 0.234000, 0.000345}') + s.write(data) + dx, dy = s.res[0], -s.res[1] + + # Tests + coords = { + 'band': [1, 2, 3], + 'y': -np.arange(ny) * 2000 + 80000 + dy / 2, + 'x': np.arange(nx) * 1000 + 5000 + dx / 2, + 'wavelength': ('band', np.array([123, 234.234, 345.345678])), + 'fwhm': ('band', np.array([1, 0.234, 0.000345])), + } + expected = DataArray(data, dims=('band', 'y', 'x'), coords=coords) + + with xr.open_rasterio(tmp_file) as rioda: + assert_allclose(rioda, expected) + assert isinstance(rioda.attrs['crs'], basestring) + assert isinstance(rioda.attrs['res'], tuple) + assert isinstance(rioda.attrs['is_tiled'], np.uint8) + assert isinstance(rioda.attrs['transform'], tuple) + # from ENVI tags + assert isinstance(rioda.attrs['description'], basestring) + assert isinstance(rioda.attrs['map_info'], basestring) + assert isinstance(rioda.attrs['samples'], basestring) + class TestEncodingInvalid(TestCase): @@ -2271,7 +2684,7 @@ def test_dataarray_to_netcdf_no_name(self): original_da.to_netcdf(tmp) with open_dataarray(tmp) as loaded_da: - self.assertDataArrayIdentical(original_da, loaded_da) + assert_identical(original_da, loaded_da) def test_dataarray_to_netcdf_with_name(self): original_da = DataArray(np.arange(12).reshape((3, 4)), @@ -2281,7 +2694,7 @@ def test_dataarray_to_netcdf_with_name(self): original_da.to_netcdf(tmp) with open_dataarray(tmp) as loaded_da: - self.assertDataArrayIdentical(original_da, loaded_da) + assert_identical(original_da, loaded_da) def test_dataarray_to_netcdf_coord_name_clash(self): original_da = DataArray(np.arange(12).reshape((3, 4)), @@ -2292,7 +2705,7 @@ def test_dataarray_to_netcdf_coord_name_clash(self): original_da.to_netcdf(tmp) with open_dataarray(tmp) as loaded_da: - self.assertDataArrayIdentical(original_da, loaded_da) + assert_identical(original_da, loaded_da) def test_open_dataarray_options(self): data = DataArray( @@ -2303,7 +2716,7 @@ def test_open_dataarray_options(self): expected = data.drop('y') with open_dataarray(tmp, drop_variables=['y']) as loaded: - self.assertDataArrayIdentical(expected, loaded) + assert_identical(expected, loaded) def test_dataarray_to_netcdf_return_bytes(self): # regression test for GH1410 @@ -2320,4 +2733,4 @@ def test_dataarray_to_netcdf_no_name_pathlib(self): original_da.to_netcdf(tmp) with open_dataarray(tmp) as loaded_da: - self.assertDataArrayIdentical(original_da, loaded_da) + assert_identical(original_da, loaded_da) diff --git a/xarray/tests/test_coding.py b/xarray/tests/test_coding.py new file mode 100644 index 0000000..d1b54fc --- /dev/null +++ b/xarray/tests/test_coding.py @@ -0,0 +1,38 @@ +import numpy as np + +import xarray as xr +from xarray.core.pycompat import suppress +from xarray.coding import variables + +from . import requires_dask, assert_identical + +with suppress(ImportError): + import dask.array as da + + +def test_CFMaskCoder_decode(): + original = xr.Variable(('x',), [0, -1, 1], {'_FillValue': -1}) + expected = xr.Variable(('x',), [0, np.nan, 1]) + coder = variables.CFMaskCoder() + encoded = coder.decode(original) + assert_identical(expected, encoded) + + +@requires_dask +def test_CFMaskCoder_decode_dask(): + original = xr.Variable(('x',), [0, -1, 1], {'_FillValue': -1}).chunk() + expected = xr.Variable(('x',), [0, np.nan, 1]) + coder = variables.CFMaskCoder() + encoded = coder.decode(original) + assert isinstance(encoded.data, da.Array) + assert_identical(expected, encoded) + +# TODO(shoyer): port other fill-value tests + + +# TODO(shoyer): parameterize when we have more coders +def test_coder_roundtrip(): + original = xr.Variable(('x',), [0.0, np.nan, 1.0]) + coder = variables.CFMaskCoder() + roundtripped = coder.decode(coder.encode(original)) + assert_identical(original, roundtripped) diff --git a/xarray/tests/test_coding_times.py b/xarray/tests/test_coding_times.py new file mode 100644 index 0000000..f8ac3d3 --- /dev/null +++ b/xarray/tests/test_coding_times.py @@ -0,0 +1,323 @@ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import warnings + +import numpy as np +import pandas as pd + +from xarray import Variable, coding +from . import ( + TestCase, requires_netCDF4, assert_array_equal) +import pytest + + +@np.vectorize +def _ensure_naive_tz(dt): + if hasattr(dt, 'tzinfo'): + return dt.replace(tzinfo=None) + else: + return dt + + +class TestDatetime(TestCase): + @requires_netCDF4 + def test_cf_datetime(self): + import netCDF4 as nc4 + for num_dates, units in [ + (np.arange(10), 'days since 2000-01-01'), + (np.arange(10).reshape(2, 5), 'days since 2000-01-01'), + (12300 + np.arange(5), 'hours since 1680-01-01 00:00:00'), + # here we add a couple minor formatting errors to test + # the robustness of the parsing algorithm. + (12300 + np.arange(5), 'hour since 1680-01-01 00:00:00'), + (12300 + np.arange(5), u'Hour since 1680-01-01 00:00:00'), + (12300 + np.arange(5), ' Hour since 1680-01-01 00:00:00 '), + (10, 'days since 2000-01-01'), + ([10], 'daYs since 2000-01-01'), + ([[10]], 'days since 2000-01-01'), + ([10, 10], 'days since 2000-01-01'), + (np.array(10), 'days since 2000-01-01'), + (0, 'days since 1000-01-01'), + ([0], 'days since 1000-01-01'), + ([[0]], 'days since 1000-01-01'), + (np.arange(2), 'days since 1000-01-01'), + (np.arange(0, 100000, 20000), 'days since 1900-01-01'), + (17093352.0, 'hours since 1-1-1 00:00:0.0'), + ([0.5, 1.5], 'hours since 1900-01-01T00:00:00'), + (0, 'milliseconds since 2000-01-01T00:00:00'), + (0, 'microseconds since 2000-01-01T00:00:00'), + ]: + for calendar in ['standard', 'gregorian', 'proleptic_gregorian']: + expected = _ensure_naive_tz( + nc4.num2date(num_dates, units, calendar)) + print(num_dates, units, calendar) + with warnings.catch_warnings(): + warnings.filterwarnings('ignore', + 'Unable to decode time axis') + actual = coding.times.decode_cf_datetime(num_dates, units, + calendar) + if (isinstance(actual, np.ndarray) and + np.issubdtype(actual.dtype, np.datetime64)): + # self.assertEqual(actual.dtype.kind, 'M') + # For some reason, numpy 1.8 does not compare ns precision + # datetime64 arrays as equal to arrays of datetime objects, + # but it works for us precision. Thus, convert to us + # precision for the actual array equal comparison... + actual_cmp = actual.astype('M8[us]') + else: + actual_cmp = actual + assert_array_equal(expected, actual_cmp) + encoded, _, _ = coding.times.encode_cf_datetime(actual, units, + calendar) + if '1-1-1' not in units: + # pandas parses this date very strangely, so the original + # units/encoding cannot be preserved in this case: + # (Pdb) pd.to_datetime('1-1-1 00:00:0.0') + # Timestamp('2001-01-01 00:00:00') + assert_array_equal(num_dates, np.around(encoded, 1)) + if (hasattr(num_dates, 'ndim') and num_dates.ndim == 1 and + '1000' not in units): + # verify that wrapping with a pandas.Index works + # note that it *does not* currently work to even put + # non-datetime64 compatible dates into a pandas.Index + encoded, _, _ = coding.times.encode_cf_datetime( + pd.Index(actual), units, calendar) + assert_array_equal(num_dates, np.around(encoded, 1)) + + @requires_netCDF4 + def test_decode_cf_datetime_overflow(self): + # checks for + # https://github.com/pydata/pandas/issues/14068 + # https://github.com/pydata/xarray/issues/975 + + from datetime import datetime + units = 'days since 2000-01-01 00:00:00' + + # date after 2262 and before 1678 + days = (-117608, 95795) + expected = (datetime(1677, 12, 31), datetime(2262, 4, 12)) + + for i, day in enumerate(days): + result = coding.times.decode_cf_datetime(day, units) + assert result == expected[i] + + def test_decode_cf_datetime_non_standard_units(self): + expected = pd.date_range(periods=100, start='1970-01-01', freq='h') + # netCDFs from madis.noaa.gov use this format for their time units + # they cannot be parsed by netcdftime, but pd.Timestamp works + units = 'hours since 1-1-1970' + actual = coding.times.decode_cf_datetime(np.arange(100), units) + assert_array_equal(actual, expected) + + @requires_netCDF4 + def test_decode_cf_datetime_non_iso_strings(self): + # datetime strings that are _almost_ ISO compliant but not quite, + # but which netCDF4.num2date can still parse correctly + expected = pd.date_range(periods=100, start='2000-01-01', freq='h') + cases = [(np.arange(100), 'hours since 2000-01-01 0'), + (np.arange(100), 'hours since 2000-1-1 0'), + (np.arange(100), 'hours since 2000-01-01 0:00')] + for num_dates, units in cases: + actual = coding.times.decode_cf_datetime(num_dates, units) + assert_array_equal(actual, expected) + + @requires_netCDF4 + def test_decode_non_standard_calendar(self): + import netCDF4 as nc4 + + for calendar in ['noleap', '365_day', '360_day', 'julian', 'all_leap', + '366_day']: + units = 'days since 0001-01-01' + times = pd.date_range('2001-04-01-00', end='2001-04-30-23', + freq='H') + noleap_time = nc4.date2num(times.to_pydatetime(), units, + calendar=calendar) + expected = times.values + with warnings.catch_warnings(): + warnings.filterwarnings('ignore', 'Unable to decode time axis') + actual = coding.times.decode_cf_datetime(noleap_time, units, + calendar=calendar) + assert actual.dtype == np.dtype('M8[ns]') + abs_diff = abs(actual - expected) + # once we no longer support versions of netCDF4 older than 1.1.5, + # we could do this check with near microsecond accuracy: + # https://github.com/Unidata/netcdf4-python/issues/355 + assert (abs_diff <= np.timedelta64(1, 's')).all() + + @requires_netCDF4 + def test_decode_non_standard_calendar_single_element(self): + units = 'days since 0001-01-01' + for calendar in ['noleap', '365_day', '360_day', 'julian', 'all_leap', + '366_day']: + for num_time in [735368, [735368], [[735368]]]: + with warnings.catch_warnings(): + warnings.filterwarnings('ignore', + 'Unable to decode time axis') + actual = coding.times.decode_cf_datetime(num_time, units, + calendar=calendar) + assert actual.dtype == np.dtype('M8[ns]') + + @requires_netCDF4 + def test_decode_non_standard_calendar_single_element_fallback(self): + import netCDF4 as nc4 + + units = 'days since 0001-01-01' + dt = nc4.netcdftime.datetime(2001, 2, 29) + for calendar in ['360_day', 'all_leap', '366_day']: + num_time = nc4.date2num(dt, units, calendar) + with pytest.warns(Warning, match='Unable to decode time axis'): + actual = coding.times.decode_cf_datetime(num_time, units, + calendar=calendar) + expected = np.asarray(nc4.num2date(num_time, units, calendar)) + print(num_time, calendar, actual, expected) + assert actual.dtype == np.dtype('O') + assert expected == actual + + @requires_netCDF4 + def test_decode_non_standard_calendar_multidim_time(self): + import netCDF4 as nc4 + + calendar = 'noleap' + units = 'days since 0001-01-01' + times1 = pd.date_range('2001-04-01', end='2001-04-05', freq='D') + times2 = pd.date_range('2001-05-01', end='2001-05-05', freq='D') + noleap_time1 = nc4.date2num(times1.to_pydatetime(), units, + calendar=calendar) + noleap_time2 = nc4.date2num(times2.to_pydatetime(), units, + calendar=calendar) + mdim_time = np.empty((len(noleap_time1), 2), ) + mdim_time[:, 0] = noleap_time1 + mdim_time[:, 1] = noleap_time2 + + expected1 = times1.values + expected2 = times2.values + with warnings.catch_warnings(): + warnings.filterwarnings('ignore', 'Unable to decode time axis') + actual = coding.times.decode_cf_datetime(mdim_time, units, + calendar=calendar) + assert actual.dtype == np.dtype('M8[ns]') + assert_array_equal(actual[:, 0], expected1) + assert_array_equal(actual[:, 1], expected2) + + @requires_netCDF4 + def test_decode_non_standard_calendar_fallback(self): + import netCDF4 as nc4 + # ensure leap year doesn't matter + for year in [2010, 2011, 2012, 2013, 2014]: + for calendar in ['360_day', '366_day', 'all_leap']: + calendar = '360_day' + units = 'days since {0}-01-01'.format(year) + num_times = np.arange(100) + expected = nc4.num2date(num_times, units, calendar) + + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always') + actual = coding.times.decode_cf_datetime(num_times, units, + calendar=calendar) + assert len(w) == 1 + assert 'Unable to decode time axis' in \ + str(w[0].message) + + assert actual.dtype == np.dtype('O') + assert_array_equal(actual, expected) + + @requires_netCDF4 + def test_cf_datetime_nan(self): + for num_dates, units, expected_list in [ + ([np.nan], 'days since 2000-01-01', ['NaT']), + ([np.nan, 0], 'days since 2000-01-01', + ['NaT', '2000-01-01T00:00:00Z']), + ([np.nan, 0, 1], 'days since 2000-01-01', + ['NaT', '2000-01-01T00:00:00Z', '2000-01-02T00:00:00Z']), + ]: + with warnings.catch_warnings(): + warnings.filterwarnings('ignore', 'All-NaN') + actual = coding.times.decode_cf_datetime(num_dates, units) + expected = np.array(expected_list, dtype='datetime64[ns]') + assert_array_equal(expected, actual) + + @requires_netCDF4 + def test_decoded_cf_datetime_array_2d(self): + # regression test for GH1229 + variable = Variable(('x', 'y'), np.array([[0, 1], [2, 3]]), + {'units': 'days since 2000-01-01'}) + result = coding.times.CFDatetimeCoder().decode(variable) + assert result.dtype == 'datetime64[ns]' + expected = pd.date_range('2000-01-01', periods=4).values.reshape(2, 2) + assert_array_equal(np.asarray(result), expected) + + def test_infer_datetime_units(self): + for dates, expected in [(pd.date_range('1900-01-01', periods=5), + 'days since 1900-01-01 00:00:00'), + (pd.date_range('1900-01-01 12:00:00', freq='H', + periods=2), + 'hours since 1900-01-01 12:00:00'), + (['1900-01-01', '1900-01-02', + '1900-01-02 00:00:01'], + 'seconds since 1900-01-01 00:00:00'), + (pd.to_datetime( + ['1900-01-01', '1900-01-02', 'NaT']), + 'days since 1900-01-01 00:00:00'), + (pd.to_datetime(['1900-01-01', + '1900-01-02T00:00:00.005']), + 'seconds since 1900-01-01 00:00:00'), + (pd.to_datetime(['NaT', '1900-01-01']), + 'days since 1900-01-01 00:00:00'), + (pd.to_datetime(['NaT']), + 'days since 1970-01-01 00:00:00'), + ]: + assert expected == coding.times.infer_datetime_units(dates) + + def test_cf_timedelta(self): + examples = [ + ('1D', 'days', np.int64(1)), + (['1D', '2D', '3D'], 'days', np.array([1, 2, 3], 'int64')), + ('1h', 'hours', np.int64(1)), + ('1ms', 'milliseconds', np.int64(1)), + ('1us', 'microseconds', np.int64(1)), + (['NaT', '0s', '1s'], None, [np.nan, 0, 1]), + (['30m', '60m'], 'hours', [0.5, 1.0]), + (np.timedelta64('NaT', 'ns'), 'days', np.nan), + (['NaT', 'NaT'], 'days', [np.nan, np.nan]), + ] + + for timedeltas, units, numbers in examples: + timedeltas = pd.to_timedelta(timedeltas, box=False) + numbers = np.array(numbers) + + expected = numbers + actual, _ = coding.times.encode_cf_timedelta(timedeltas, units) + assert_array_equal(expected, actual) + assert expected.dtype == actual.dtype + + if units is not None: + expected = timedeltas + actual = coding.times.decode_cf_timedelta(numbers, units) + assert_array_equal(expected, actual) + assert expected.dtype == actual.dtype + + expected = np.timedelta64('NaT', 'ns') + actual = coding.times.decode_cf_timedelta(np.array(np.nan), 'days') + assert_array_equal(expected, actual) + + def test_cf_timedelta_2d(self): + timedeltas = ['1D', '2D', '3D'] + units = 'days' + numbers = np.atleast_2d([1, 2, 3]) + + timedeltas = np.atleast_2d(pd.to_timedelta(timedeltas, box=False)) + expected = timedeltas + + actual = coding.times.decode_cf_timedelta(numbers, units) + assert_array_equal(expected, actual) + assert expected.dtype == actual.dtype + + def test_infer_timedelta_units(self): + for deltas, expected in [ + (pd.to_timedelta(['1 day', '2 days']), 'days'), + (pd.to_timedelta(['1h', '1 day 1 hour']), 'hours'), + (pd.to_timedelta(['1m', '2m', np.nan]), 'minutes'), + (pd.to_timedelta(['1m3s', '1m4s']), 'seconds')]: + assert expected == coding.times.infer_timedelta_units(deltas) diff --git a/xarray/tests/test_combine.py b/xarray/tests/test_combine.py index b2bbba3..365e274 100644 --- a/xarray/tests/test_combine.py +++ b/xarray/tests/test_combine.py @@ -11,7 +11,8 @@ from xarray import Dataset, DataArray, auto_combine, concat, Variable from xarray.core.pycompat import iteritems, OrderedDict -from . import TestCase, InaccessibleArray, requires_dask, raises_regex +from . import (TestCase, InaccessibleArray, requires_dask, raises_regex, + assert_equal, assert_identical, assert_array_equal) from .test_dataset import create_test_data @@ -27,7 +28,7 @@ def test_concat(self): split_data = [data.isel(dim1=slice(3)), data.isel(dim1=slice(3, None))] - self.assertDatasetIdentical(data, concat(split_data, 'dim1')) + assert_identical(data, concat(split_data, 'dim1')) def rectify_dim_order(dataset): # return a new dataset with all variable dimensions transposed into @@ -38,22 +39,22 @@ def rectify_dim_order(dataset): for dim in ['dim1', 'dim2']: datasets = [g for _, g in data.groupby(dim, squeeze=False)] - self.assertDatasetIdentical(data, concat(datasets, dim)) + assert_identical(data, concat(datasets, dim)) dim = 'dim2' - self.assertDatasetIdentical( + assert_identical( data, concat(datasets, data[dim])) - self.assertDatasetIdentical( + assert_identical( data, concat(datasets, data[dim], coords='minimal')) datasets = [g for _, g in data.groupby(dim, squeeze=True)] concat_over = [k for k, v in iteritems(data.coords) if dim in v.dims and k != dim] actual = concat(datasets, data[dim], coords=concat_over) - self.assertDatasetIdentical(data, rectify_dim_order(actual)) + assert_identical(data, rectify_dim_order(actual)) actual = concat(datasets, data[dim], coords='different') - self.assertDatasetIdentical(data, rectify_dim_order(actual)) + assert_identical(data, rectify_dim_order(actual)) # make sure the coords argument behaves as expected data.coords['extra'] = ('dim4', np.arange(3)) @@ -62,12 +63,12 @@ def rectify_dim_order(dataset): actual = concat(datasets, data[dim], coords='all') expected = np.array([data['extra'].values for _ in range(data.dims[dim])]) - self.assertArrayEqual(actual['extra'].values, expected) + assert_array_equal(actual['extra'].values, expected) actual = concat(datasets, data[dim], coords='different') - self.assertDataArrayEqual(data['extra'], actual['extra']) + assert_equal(data['extra'], actual['extra']) actual = concat(datasets, data[dim], coords='minimal') - self.assertDataArrayEqual(data['extra'], actual['extra']) + assert_equal(data['extra'], actual['extra']) # verify that the dim argument takes precedence over # concatenating dataset variables of the same name @@ -75,14 +76,14 @@ def rectify_dim_order(dataset): datasets = [g for _, g in data.groupby('dim1', squeeze=False)] expected = data.copy() expected['dim1'] = dim - self.assertDatasetIdentical(expected, concat(datasets, dim)) + assert_identical(expected, concat(datasets, dim)) def test_concat_data_vars(self): data = Dataset({'foo': ('x', np.random.randn(10))}) objs = [data.isel(x=slice(5)), data.isel(x=slice(5, None))] for data_vars in ['minimal', 'different', 'all', [], ['foo']]: actual = concat(objs, dim='x', data_vars=data_vars) - self.assertDatasetIdentical(data, actual) + assert_identical(data, actual) def test_concat_coords(self): data = Dataset({'foo': ('x', np.random.randn(10))}) @@ -91,7 +92,7 @@ def test_concat_coords(self): data.isel(x=slice(5, None)).assign_coords(c=1)] for coords in ['different', 'all', ['c']]: actual = concat(objs, dim='x', coords=coords) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) for coords in ['minimal', []]: with raises_regex(ValueError, 'not equal across'): concat(objs, dim='x', coords=coords) @@ -103,7 +104,7 @@ def test_concat_constant_index(self): expected = Dataset({'foo': ('y', [1.5, 2.5]), 'y': [1, 1]}) for mode in ['different', 'all', ['foo']]: actual = concat([ds1, ds2], 'y', data_vars=mode) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) with raises_regex(ValueError, 'not equal across datasets'): concat([ds1, ds2], 'y', data_vars='minimal') @@ -111,10 +112,10 @@ def test_concat_size0(self): data = create_test_data() split_data = [data.isel(dim1=slice(0, 0)), data] actual = concat(split_data, 'dim1') - self.assertDatasetIdentical(data, actual) + assert_identical(data, actual) actual = concat(split_data[::-1], 'dim1') - self.assertDatasetIdentical(data, actual) + assert_identical(data, actual) def test_concat_autoalign(self): ds1 = Dataset({'foo': DataArray([1, 2], coords=[('x', [1, 2])])}) @@ -123,7 +124,7 @@ def test_concat_autoalign(self): expected = Dataset({'foo': DataArray([[1, 2, np.nan], [1, np.nan, 2]], dims=['y', 'x'], coords={'x': [1, 2, 3]})}) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_concat_errors(self): data = create_test_data() @@ -140,7 +141,7 @@ def test_concat_errors(self): data0, data1 = deepcopy(split_data) data1.attrs['foo'] = 'bar' concat([data0, data1], 'dim1', compat='identical') - self.assertDatasetIdentical( + assert_identical( data, concat([data0, data1], 'dim1', compat='equals')) with raises_regex(ValueError, 'encountered unexpected'): @@ -172,31 +173,31 @@ def test_concat_promote_shape(self): objs = [Dataset({}, {'x': 0}), Dataset({'x': [1]})] actual = concat(objs, 'x') expected = Dataset({'x': [0, 1]}) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) objs = [Dataset({'x': [0]}), Dataset({}, {'x': 1})] actual = concat(objs, 'x') - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) # mixed dims between variables objs = [Dataset({'x': [2], 'y': 3}), Dataset({'x': [4], 'y': 5})] actual = concat(objs, 'x') expected = Dataset({'x': [2, 4], 'y': ('x', [3, 5])}) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) # mixed dims in coord variable objs = [Dataset({'x': [0]}, {'y': -1}), Dataset({'x': [1]}, {'y': ('x', [-2])})] actual = concat(objs, 'x') expected = Dataset({'x': [0, 1]}, {'y': ('x', [-1, -2])}) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) # scalars with mixed lengths along concat dim -- values should repeat objs = [Dataset({'x': [0]}, {'y': -1}), Dataset({'x': [1, 2]}, {'y': -2})] actual = concat(objs, 'x') expected = Dataset({'x': [0, 1, 2]}, {'y': ('x', [-1, -2, -2])}) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) # broadcast 1d x 1d -> 2d objs = [Dataset({'z': ('x', [-1])}, {'x': [0], 'y': [0]}), @@ -204,7 +205,7 @@ def test_concat_promote_shape(self): actual = concat(objs, 'x') expected = Dataset({'z': (('x', 'y'), [[-1], [1]])}, {'x': [0, 1], 'y': [0]}) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) def test_concat_do_not_promote(self): # GH438 @@ -212,7 +213,7 @@ def test_concat_do_not_promote(self): Dataset({'y': ('t', [2])}, {'x': 1, 't': [0]})] expected = Dataset({'y': ('t', [1, 2])}, {'x': 1, 't': [0, 0]}) actual = concat(objs, 't') - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) objs = [Dataset({'y': ('t', [1])}, {'x': 1, 't': [0]}), Dataset({'y': ('t', [2])}, {'x': 2, 't': [0]})] @@ -224,7 +225,7 @@ def test_concat_dim_is_variable(self): coord = Variable('y', [3, 4]) expected = Dataset({'x': ('y', [0, 1]), 'y': [3, 4]}) actual = concat(objs, coord) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) def test_concat_multiindex(self): x = pd.MultiIndex.from_product([[1, 2, 3], ['a', 'b']]) @@ -247,22 +248,23 @@ def test_concat(self): expected = DataArray(np.array([foo.values, bar.values]), dims=['w', 'x', 'y'], coords={'x': [0, 1]}) actual = concat([foo, bar], 'w') - self.assertDataArrayEqual(expected, actual) + assert_equal(expected, actual) # from iteration: grouped = [g for _, g in foo.groupby('x')] stacked = concat(grouped, ds['x']) - self.assertDataArrayIdentical(foo, stacked) + assert_identical(foo, stacked) # with an index as the 'dim' argument stacked = concat(grouped, ds.indexes['x']) - self.assertDataArrayIdentical(foo, stacked) + assert_identical(foo, stacked) - actual = concat([foo[0], foo[1]], pd.Index([0, 1])).reset_coords(drop=True) + actual = concat([foo[0], foo[1]], pd.Index([0, 1]) + ).reset_coords(drop=True) expected = foo[:2].rename({'x': 'concat_dim'}) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = concat([foo[0], foo[1]], [0, 1]).reset_coords(drop=True) expected = foo[:2].rename({'x': 'concat_dim'}) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) with raises_regex(ValueError, 'not identical'): concat([foo, bar], dim='w', compat='identical') @@ -290,8 +292,8 @@ def test_concat_lazy(self): dims=['x', 'y']) for _ in range(2)] # should not raise combined = concat(arrays, dim='z') - self.assertEqual(combined.shape, (2, 3, 3)) - self.assertEqual(combined.dims, ('z', 'x', 'y')) + assert combined.shape == (2, 3, 3) + assert combined.dims == ('z', 'x', 'y') class TestAutoCombine(TestCase): @@ -301,22 +303,22 @@ def test_auto_combine(self): objs = [Dataset({'x': [0]}), Dataset({'x': [1]})] actual = auto_combine(objs) expected = Dataset({'x': [0, 1]}) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) actual = auto_combine([actual]) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) objs = [Dataset({'x': [0, 1]}), Dataset({'x': [2]})] actual = auto_combine(objs) expected = Dataset({'x': [0, 1, 2]}) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) # ensure auto_combine handles non-sorted variables objs = [Dataset(OrderedDict([('x', ('a', [0])), ('y', ('a', [0]))])), Dataset(OrderedDict([('y', ('a', [1])), ('x', ('a', [1]))]))] actual = auto_combine(objs) expected = Dataset({'x': ('a', [0, 1]), 'y': ('a', [0, 1])}) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) objs = [Dataset({'x': [0], 'y': [0]}), Dataset({'y': [1], 'x': [1]})] with raises_regex(ValueError, 'too many .* dimensions'): @@ -340,7 +342,7 @@ def test_auto_combine_previously_failed(self): expected = Dataset({'a': ('x', [0, 1]), 'b': ('x', [0, np.nan])}, {'x': [0, 1]}) actual = auto_combine(datasets) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) # Your data includes "time" and "station" dimensions, and each year's # data has a different set of stations. @@ -350,7 +352,7 @@ def test_auto_combine_previously_failed(self): [[np.nan, 2, 3], [1, 2, np.nan]])}, {'x': [0, 1, 2]}) actual = auto_combine(datasets, concat_dim='t') - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) @requires_dask # only for toolz def test_auto_combine_still_fails(self): @@ -366,13 +368,13 @@ def test_auto_combine_no_concat(self): objs = [Dataset({'x': 0}), Dataset({'y': 1})] actual = auto_combine(objs) expected = Dataset({'x': 0, 'y': 1}) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) objs = [Dataset({'x': 0, 'y': 1}), Dataset({'y': np.nan, 'z': 2})] actual = auto_combine(objs) expected = Dataset({'x': 0, 'y': 1, 'z': 2}) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) data = Dataset({'x': 0}) actual = auto_combine([data, data, data], concat_dim=None) - self.assertDatasetIdentical(data, actual) + assert_identical(data, actual) diff --git a/xarray/tests/test_computation.py b/xarray/tests/test_computation.py index 430a1a0..23e77b8 100644 --- a/xarray/tests/test_computation.py +++ b/xarray/tests/test_computation.py @@ -488,10 +488,10 @@ def add(a, b, keep_attrs): actual = add(a, b, keep_attrs=True) assert_identical(actual.attrs, a.attrs) - a = xr.Dataset({'x': ('x', [1, 2]), 'x': [0, 1]}) + a = xr.Dataset({'x': [0, 1]}) a.attrs['attr'] = 'ds' a.x.attrs['attr'] = 'da' - b = xr.Dataset({'x': ('x', [1, 1]), 'x': [0, 1]}) + b = xr.Dataset({'x': [0, 1]}) actual = add(a, b, keep_attrs=False) assert not actual.attrs @@ -666,8 +666,8 @@ def test_apply_dask_multiple_inputs(): import dask.array as da def covariance(x, y): - return ((x - x.mean(axis=-1, keepdims=True)) - * (y - y.mean(axis=-1, keepdims=True))).mean(axis=-1) + return ((x - x.mean(axis=-1, keepdims=True)) * + (y - y.mean(axis=-1, keepdims=True))).mean(axis=-1) rs = np.random.RandomState(42) array1 = da.from_array(rs.randn(4, 4), chunks=(2, 4)) diff --git a/xarray/tests/test_conventions.py b/xarray/tests/test_conventions.py index ca88ea6..6a50936 100644 --- a/xarray/tests/test_conventions.py +++ b/xarray/tests/test_conventions.py @@ -2,17 +2,19 @@ from __future__ import absolute_import from __future__ import division from __future__ import print_function + import contextlib +import warnings import numpy as np import pandas as pd -import pytest -import warnings - import pytest from xarray import conventions, Variable, Dataset, open_dataset from xarray.core import utils, indexing -from . import TestCase, requires_netCDF4, unittest, raises_regex, IndexerMaker +from xarray.testing import assert_identical +from . import ( + TestCase, requires_netCDF4, unittest, raises_regex, IndexerMaker, + assert_array_equal) from .test_backends import CFEncodedDataTest from xarray.core.pycompat import iteritems from xarray.backends.memory import InMemoryDataStore @@ -21,62 +23,21 @@ B = IndexerMaker(indexing.BasicIndexer) -O = IndexerMaker(indexing.OuterIndexer) V = IndexerMaker(indexing.VectorizedIndexer) -class TestMaskedAndScaledArray(TestCase): - def test(self): - x = conventions.MaskedAndScaledArray(np.arange(3), fill_value=0) - self.assertEqual(x.dtype, np.dtype('float')) - self.assertEqual(x.shape, (3,)) - self.assertEqual(x.size, 3) - self.assertEqual(x.ndim, 1) - self.assertEqual(len(x), 3) - self.assertArrayEqual([np.nan, 1, 2], x) - - x = conventions.MaskedAndScaledArray(np.arange(3), add_offset=1) - self.assertArrayEqual(np.arange(3) + 1, x) - - x = conventions.MaskedAndScaledArray(np.arange(3), scale_factor=2) - self.assertArrayEqual(2 * np.arange(3), x) - - x = conventions.MaskedAndScaledArray(np.array([-99, -1, 0, 1, 2]), - -99, 0.01, 1) - expected = np.array([np.nan, 0.99, 1, 1.01, 1.02]) - self.assertArrayEqual(expected, x) - - def test_0d(self): - x = conventions.MaskedAndScaledArray(np.array(0), fill_value=0) - self.assertTrue(np.isnan(x)) - self.assertTrue(np.isnan(x[B[()]])) - - x = conventions.MaskedAndScaledArray(np.array(0), fill_value=10) - self.assertEqual(0, x[B[()]]) - - def test_multiple_fill_value(self): - x = conventions.MaskedAndScaledArray( - np.arange(4), fill_value=np.array([0, 1])) - self.assertArrayEqual([np.nan, np.nan, 2, 3], x) - - x = conventions.MaskedAndScaledArray( - np.array(0), fill_value=np.array([0, 1])) - self.assertTrue(np.isnan(x)) - self.assertTrue(np.isnan(x[B[()]])) - - class TestStackedBytesArray(TestCase): def test_wrapper_class(self): array = np.array([[b'a', b'b', b'c'], [b'd', b'e', b'f']], dtype='S') actual = conventions.StackedBytesArray(array) expected = np.array([b'abc', b'def'], dtype='S') - self.assertEqual(actual.dtype, expected.dtype) - self.assertEqual(actual.shape, expected.shape) - self.assertEqual(actual.size, expected.size) - self.assertEqual(actual.ndim, expected.ndim) - self.assertEqual(len(actual), len(expected)) - self.assertArrayEqual(expected, actual) - self.assertArrayEqual(expected[:1], actual[B[:1]]) + assert actual.dtype == expected.dtype + assert actual.shape == expected.shape + assert actual.size == expected.size + assert actual.ndim == expected.ndim + assert len(actual) == len(expected) + assert_array_equal(expected, actual) + assert_array_equal(expected[:1], actual[B[:1]]) with pytest.raises(IndexError): actual[B[:, :2]] @@ -100,34 +61,34 @@ def test_char_to_bytes(self): array = np.array([['a', 'b', 'c'], ['d', 'e', 'f']]) expected = np.array(['abc', 'def']) actual = conventions.char_to_bytes(array) - self.assertArrayEqual(actual, expected) + assert_array_equal(actual, expected) expected = np.array(['ad', 'be', 'cf']) actual = conventions.char_to_bytes(array.T) # non-contiguous - self.assertArrayEqual(actual, expected) + assert_array_equal(actual, expected) def test_char_to_bytes_ndim_zero(self): expected = np.array('a') actual = conventions.char_to_bytes(expected) - self.assertArrayEqual(actual, expected) + assert_array_equal(actual, expected) def test_char_to_bytes_size_zero(self): array = np.zeros((3, 0), dtype='S1') expected = np.array([b'', b'', b'']) actual = conventions.char_to_bytes(array) - self.assertArrayEqual(actual, expected) + assert_array_equal(actual, expected) def test_bytes_to_char(self): array = np.array([['ab', 'cd'], ['ef', 'gh']]) expected = np.array([[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]]) actual = conventions.bytes_to_char(array) - self.assertArrayEqual(actual, expected) + assert_array_equal(actual, expected) expected = np.array([[['a', 'b'], ['e', 'f']], [['c', 'd'], ['g', 'h']]]) actual = conventions.bytes_to_char(array.T) - self.assertArrayEqual(actual, expected) + assert_array_equal(actual, expected) def test_vectorized_indexing(self): array = np.array([[b'a', b'b', b'c'], [b'd', b'e', b'f']], dtype='S') @@ -135,7 +96,7 @@ def test_vectorized_indexing(self): expected = np.array([[b'abc', b'def'], [b'def', b'abc']]) indexer = V[np.array([[0, 1], [1, 0]])] actual = stacked[indexer] - self.assertArrayEqual(actual, expected) + assert_array_equal(actual, expected) class TestBytesToStringArray(TestCase): @@ -146,12 +107,12 @@ def test_encoding(self): actual = conventions.BytesToStringArray(raw_array, encoding=encoding) expected = np.array([u'abc', u'ß∂µ∆'], dtype=object) - self.assertEqual(actual.dtype, expected.dtype) - self.assertEqual(actual.shape, expected.shape) - self.assertEqual(actual.size, expected.size) - self.assertEqual(actual.ndim, expected.ndim) - self.assertArrayEqual(expected, actual) - self.assertArrayEqual(expected[0], actual[B[0]]) + assert actual.dtype == expected.dtype + assert actual.shape == expected.shape + assert actual.size == expected.size + assert actual.ndim == expected.ndim + assert_array_equal(expected, actual) + assert_array_equal(expected[0], actual[B[0]]) def test_scalar(self): expected = np.array(u'abc', dtype=object) @@ -176,413 +137,13 @@ def test_decode_bytes_array(self): np.testing.assert_array_equal(actual, expected) -class TestUnsignedIntTypeArray(TestCase): - def test_unsignedinttype_array(self): - sb = np.asarray([0, 1, 127, -128, -1], dtype='i1') - ub = conventions.UnsignedIntTypeArray(sb) - self.assertEqual(ub.dtype, np.dtype('u1')) - self.assertArrayEqual(ub, np.array([0, 1, 127, 128, 255], - dtype=np.dtype('u1'))) - - class TestBoolTypeArray(TestCase): def test_booltype_array(self): x = np.array([1, 0, 1, 1, 0], dtype='i1') bx = conventions.BoolTypeArray(x) - self.assertEqual(bx.dtype, np.bool) - self.assertArrayEqual(bx, np.array([True, False, True, True, False], - dtype=np.bool)) - - -@np.vectorize -def _ensure_naive_tz(dt): - if hasattr(dt, 'tzinfo'): - return dt.replace(tzinfo=None) - else: - return dt - - -class TestDatetime(TestCase): - @requires_netCDF4 - def test_cf_datetime(self): - import netCDF4 as nc4 - for num_dates, units in [ - (np.arange(10), 'days since 2000-01-01'), - (np.arange(10).reshape(2, 5), 'days since 2000-01-01'), - (12300 + np.arange(5), 'hours since 1680-01-01 00:00:00'), - # here we add a couple minor formatting errors to test - # the robustness of the parsing algorithm. - (12300 + np.arange(5), 'hour since 1680-01-01 00:00:00'), - (12300 + np.arange(5), u'Hour since 1680-01-01 00:00:00'), - (12300 + np.arange(5), ' Hour since 1680-01-01 00:00:00 '), - (10, 'days since 2000-01-01'), - ([10], 'daYs since 2000-01-01'), - ([[10]], 'days since 2000-01-01'), - ([10, 10], 'days since 2000-01-01'), - (np.array(10), 'days since 2000-01-01'), - (0, 'days since 1000-01-01'), - ([0], 'days since 1000-01-01'), - ([[0]], 'days since 1000-01-01'), - (np.arange(2), 'days since 1000-01-01'), - (np.arange(0, 100000, 20000), 'days since 1900-01-01'), - (17093352.0, 'hours since 1-1-1 00:00:0.0'), - ([0.5, 1.5], 'hours since 1900-01-01T00:00:00'), - (0, 'milliseconds since 2000-01-01T00:00:00'), - (0, 'microseconds since 2000-01-01T00:00:00'), - ]: - for calendar in ['standard', 'gregorian', 'proleptic_gregorian']: - expected = _ensure_naive_tz(nc4.num2date(num_dates, units, calendar)) - print(num_dates, units, calendar) - with warnings.catch_warnings(): - warnings.filterwarnings('ignore', - 'Unable to decode time axis') - actual = conventions.decode_cf_datetime(num_dates, units, - calendar) - if (isinstance(actual, np.ndarray) and - np.issubdtype(actual.dtype, np.datetime64)): - # self.assertEqual(actual.dtype.kind, 'M') - # For some reason, numpy 1.8 does not compare ns precision - # datetime64 arrays as equal to arrays of datetime objects, - # but it works for us precision. Thus, convert to us - # precision for the actual array equal comparison... - actual_cmp = actual.astype('M8[us]') - else: - actual_cmp = actual - self.assertArrayEqual(expected, actual_cmp) - encoded, _, _ = conventions.encode_cf_datetime(actual, units, - calendar) - if '1-1-1' not in units: - # pandas parses this date very strangely, so the original - # units/encoding cannot be preserved in this case: - # (Pdb) pd.to_datetime('1-1-1 00:00:0.0') - # Timestamp('2001-01-01 00:00:00') - self.assertArrayEqual(num_dates, np.around(encoded, 1)) - if (hasattr(num_dates, 'ndim') and num_dates.ndim == 1 and - '1000' not in units): - # verify that wrapping with a pandas.Index works - # note that it *does not* currently work to even put - # non-datetime64 compatible dates into a pandas.Index :( - encoded, _, _ = conventions.encode_cf_datetime( - pd.Index(actual), units, calendar) - self.assertArrayEqual(num_dates, np.around(encoded, 1)) - - @requires_netCDF4 - def test_decode_cf_datetime_overflow(self): - # checks for - # https://github.com/pydata/pandas/issues/14068 - # https://github.com/pydata/xarray/issues/975 - - from datetime import datetime - units = 'days since 2000-01-01 00:00:00' - - # date after 2262 and before 1678 - days = (-117608, 95795) - expected = (datetime(1677, 12, 31), datetime(2262, 4, 12)) - - for i, day in enumerate(days): - result = conventions.decode_cf_datetime(day, units) - self.assertEqual(result, expected[i]) - - @requires_netCDF4 - def test_decode_cf_datetime_transition_to_invalid(self): - # manually create dataset with not-decoded date - from datetime import datetime - ds = Dataset(coords={'time': [0, 266 * 365]}) - units = 'days since 2000-01-01 00:00:00' - ds.time.attrs = dict(units=units) - ds_decoded = conventions.decode_cf(ds) - - expected = [datetime(2000, 1, 1, 0, 0), - datetime(2265, 10, 28, 0, 0)] - - self.assertArrayEqual(ds_decoded.time.values, expected) - - def test_decoded_cf_datetime_array(self): - actual = conventions.DecodedCFDatetimeArray( - np.array([0, 1, 2]), 'days since 1900-01-01', 'standard') - expected = pd.date_range('1900-01-01', periods=3).values - self.assertEqual(actual.dtype, np.dtype('datetime64[ns]')) - self.assertArrayEqual(actual, expected) - - # default calendar - actual = conventions.DecodedCFDatetimeArray( - np.array([0, 1, 2]), 'days since 1900-01-01') - self.assertEqual(actual.dtype, np.dtype('datetime64[ns]')) - self.assertArrayEqual(actual, expected) - - def test_slice_decoded_cf_datetime_array(self): - actual = conventions.DecodedCFDatetimeArray( - np.array([0, 1, 2]), 'days since 1900-01-01', 'standard') - expected = pd.date_range('1900-01-01', periods=3).values - self.assertEqual(actual.dtype, np.dtype('datetime64[ns]')) - self.assertArrayEqual(actual[B[0:2]], expected[slice(0, 2)]) - - actual = conventions.DecodedCFDatetimeArray( - np.array([0, 1, 2]), 'days since 1900-01-01', 'standard') - expected = pd.date_range('1900-01-01', periods=3).values - self.assertEqual(actual.dtype, np.dtype('datetime64[ns]')) - self.assertArrayEqual(actual[O[np.array([0, 2])]], expected[[0, 2]]) - - def test_decode_cf_datetime_non_standard_units(self): - expected = pd.date_range(periods=100, start='1970-01-01', freq='h') - # netCDFs from madis.noaa.gov use this format for their time units - # they cannot be parsed by netcdftime, but pd.Timestamp works - units = 'hours since 1-1-1970' - actual = conventions.decode_cf_datetime(np.arange(100), units) - self.assertArrayEqual(actual, expected) - - def test_decode_cf_with_conflicting_fill_missing_value(self): - var = Variable(['t'], np.arange(10), - {'units': 'foobar', - 'missing_value': 0, - '_FillValue': 1}) - with raises_regex(ValueError, "_FillValue and missing_value"): - conventions.decode_cf_variable('t', var) - - var = Variable(['t'], np.arange(10), - {'units': 'foobar', - 'missing_value': np.nan, - '_FillValue': np.nan}) - var = conventions.decode_cf_variable('t', var) - self.assertIsNotNone(var) - - var = Variable(['t'], np.arange(10), - {'units': 'foobar', - 'missing_value': np.float32(np.nan), - '_FillValue': np.float32(np.nan)}) - var = conventions.decode_cf_variable('t', var) - self.assertIsNotNone(var) - - @requires_netCDF4 - def test_decode_cf_datetime_non_iso_strings(self): - # datetime strings that are _almost_ ISO compliant but not quite, - # but which netCDF4.num2date can still parse correctly - expected = pd.date_range(periods=100, start='2000-01-01', freq='h') - cases = [(np.arange(100), 'hours since 2000-01-01 0'), - (np.arange(100), 'hours since 2000-1-1 0'), - (np.arange(100), 'hours since 2000-01-01 0:00')] - for num_dates, units in cases: - actual = conventions.decode_cf_datetime(num_dates, units) - self.assertArrayEqual(actual, expected) - - @requires_netCDF4 - def test_decode_non_standard_calendar(self): - import netCDF4 as nc4 - - for calendar in ['noleap', '365_day', '360_day', 'julian', 'all_leap', - '366_day']: - units = 'days since 0001-01-01' - times = pd.date_range('2001-04-01-00', end='2001-04-30-23', - freq='H') - noleap_time = nc4.date2num(times.to_pydatetime(), units, - calendar=calendar) - expected = times.values - with warnings.catch_warnings(): - warnings.filterwarnings('ignore', 'Unable to decode time axis') - actual = conventions.decode_cf_datetime(noleap_time, units, - calendar=calendar) - self.assertEqual(actual.dtype, np.dtype('M8[ns]')) - abs_diff = abs(actual - expected) - # once we no longer support versions of netCDF4 older than 1.1.5, - # we could do this check with near microsecond accuracy: - # https://github.com/Unidata/netcdf4-python/issues/355 - self.assertTrue((abs_diff <= np.timedelta64(1, 's')).all()) - - @requires_netCDF4 - def test_decode_non_standard_calendar_single_element(self): - units = 'days since 0001-01-01' - for calendar in ['noleap', '365_day', '360_day', 'julian', 'all_leap', - '366_day']: - for num_time in [735368, [735368], [[735368]]]: - with warnings.catch_warnings(): - warnings.filterwarnings('ignore', - 'Unable to decode time axis') - actual = conventions.decode_cf_datetime(num_time, units, - calendar=calendar) - self.assertEqual(actual.dtype, np.dtype('M8[ns]')) - - @requires_netCDF4 - def test_decode_non_standard_calendar_single_element_fallback(self): - import netCDF4 as nc4 - - units = 'days since 0001-01-01' - dt = nc4.netcdftime.datetime(2001, 2, 29) - for calendar in ['360_day', 'all_leap', '366_day']: - num_time = nc4.date2num(dt, units, calendar) - with self.assertWarns('Unable to decode time axis'): - actual = conventions.decode_cf_datetime(num_time, units, - calendar=calendar) - expected = np.asarray(nc4.num2date(num_time, units, calendar)) - print(num_time, calendar, actual, expected) - self.assertEqual(actual.dtype, np.dtype('O')) - self.assertEqual(expected, actual) - - @requires_netCDF4 - def test_decode_non_standard_calendar_multidim_time(self): - import netCDF4 as nc4 - - calendar = 'noleap' - units = 'days since 0001-01-01' - times1 = pd.date_range('2001-04-01', end='2001-04-05', freq='D') - times2 = pd.date_range('2001-05-01', end='2001-05-05', freq='D') - noleap_time1 = nc4.date2num(times1.to_pydatetime(), units, - calendar=calendar) - noleap_time2 = nc4.date2num(times2.to_pydatetime(), units, - calendar=calendar) - mdim_time = np.empty((len(noleap_time1), 2), ) - mdim_time[:, 0] = noleap_time1 - mdim_time[:, 1] = noleap_time2 - - expected1 = times1.values - expected2 = times2.values - with warnings.catch_warnings(): - warnings.filterwarnings('ignore', 'Unable to decode time axis') - actual = conventions.decode_cf_datetime(mdim_time, units, - calendar=calendar) - self.assertEqual(actual.dtype, np.dtype('M8[ns]')) - self.assertArrayEqual(actual[:, 0], expected1) - self.assertArrayEqual(actual[:, 1], expected2) - - @requires_netCDF4 - def test_decode_non_standard_calendar_fallback(self): - import netCDF4 as nc4 - # ensure leap year doesn't matter - for year in [2010, 2011, 2012, 2013, 2014]: - for calendar in ['360_day', '366_day', 'all_leap']: - calendar = '360_day' - units = 'days since {0}-01-01'.format(year) - num_times = np.arange(100) - expected = nc4.num2date(num_times, units, calendar) - - with warnings.catch_warnings(record=True) as w: - warnings.simplefilter('always') - actual = conventions.decode_cf_datetime(num_times, units, - calendar=calendar) - self.assertEqual(len(w), 1) - self.assertIn('Unable to decode time axis', - str(w[0].message)) - - self.assertEqual(actual.dtype, np.dtype('O')) - self.assertArrayEqual(actual, expected) - - @requires_netCDF4 - def test_cf_datetime_nan(self): - for num_dates, units, expected_list in [ - ([np.nan], 'days since 2000-01-01', ['NaT']), - ([np.nan, 0], 'days since 2000-01-01', - ['NaT', '2000-01-01T00:00:00Z']), - ([np.nan, 0, 1], 'days since 2000-01-01', - ['NaT', '2000-01-01T00:00:00Z', '2000-01-02T00:00:00Z']), - ]: - with warnings.catch_warnings(): - warnings.filterwarnings('ignore', 'All-NaN') - actual = conventions.decode_cf_datetime(num_dates, units) - expected = np.array(expected_list, dtype='datetime64[ns]') - self.assertArrayEqual(expected, actual) - - @requires_netCDF4 - def test_decoded_cf_datetime_array_2d(self): - # regression test for GH1229 - array = conventions.DecodedCFDatetimeArray(np.array([[0, 1], [2, 3]]), - 'days since 2000-01-01') - assert array.dtype == 'datetime64[ns]' - expected = pd.date_range('2000-01-01', periods=4).values.reshape(2, 2) - self.assertArrayEqual(np.asarray(array), expected) - - def test_infer_datetime_units(self): - for dates, expected in [(pd.date_range('1900-01-01', periods=5), - 'days since 1900-01-01 00:00:00'), - (pd.date_range('1900-01-01 12:00:00', freq='H', - periods=2), - 'hours since 1900-01-01 12:00:00'), - (['1900-01-01', '1900-01-02', - '1900-01-02 00:00:01'], - 'seconds since 1900-01-01 00:00:00'), - (pd.to_datetime(['1900-01-01', '1900-01-02', 'NaT']), - 'days since 1900-01-01 00:00:00'), - (pd.to_datetime(['1900-01-01', - '1900-01-02T00:00:00.005']), - 'seconds since 1900-01-01 00:00:00'), - (pd.to_datetime(['NaT', '1900-01-01']), - 'days since 1900-01-01 00:00:00'), - (pd.to_datetime(['NaT']), - 'days since 1970-01-01 00:00:00'), - ]: - self.assertEqual(expected, conventions.infer_datetime_units(dates)) - - def test_cf_timedelta(self): - examples = [ - ('1D', 'days', np.int64(1)), - (['1D', '2D', '3D'], 'days', np.array([1, 2, 3], 'int64')), - ('1h', 'hours', np.int64(1)), - ('1ms', 'milliseconds', np.int64(1)), - ('1us', 'microseconds', np.int64(1)), - (['NaT', '0s', '1s'], None, [np.nan, 0, 1]), - (['30m', '60m'], 'hours', [0.5, 1.0]), - (np.timedelta64('NaT', 'ns'), 'days', np.nan), - (['NaT', 'NaT'], 'days', [np.nan, np.nan]), - ] - - for timedeltas, units, numbers in examples: - timedeltas = pd.to_timedelta(timedeltas, box=False) - numbers = np.array(numbers) - - expected = numbers - actual, _ = conventions.encode_cf_timedelta(timedeltas, units) - self.assertArrayEqual(expected, actual) - self.assertEqual(expected.dtype, actual.dtype) - - if units is not None: - expected = timedeltas - actual = conventions.decode_cf_timedelta(numbers, units) - self.assertArrayEqual(expected, actual) - self.assertEqual(expected.dtype, actual.dtype) - - expected = np.timedelta64('NaT', 'ns') - actual = conventions.decode_cf_timedelta(np.array(np.nan), 'days') - self.assertArrayEqual(expected, actual) - - def test_cf_timedelta_2d(self): - timedeltas, units, numbers = ['1D', '2D', '3D'], 'days', np.atleast_2d([1, 2, 3]) - - timedeltas = np.atleast_2d(pd.to_timedelta(timedeltas, box=False)) - expected = timedeltas - - actual = conventions.decode_cf_timedelta(numbers, units) - self.assertArrayEqual(expected, actual) - self.assertEqual(expected.dtype, actual.dtype) - - def test_infer_timedelta_units(self): - for deltas, expected in [ - (pd.to_timedelta(['1 day', '2 days']), 'days'), - (pd.to_timedelta(['1h', '1 day 1 hour']), 'hours'), - (pd.to_timedelta(['1m', '2m', np.nan]), 'minutes'), - (pd.to_timedelta(['1m3s', '1m4s']), 'seconds')]: - self.assertEqual(expected, conventions.infer_timedelta_units(deltas)) - - def test_invalid_units_raises_eagerly(self): - ds = Dataset({'time': ('time', [0, 1], {'units': 'foobar since 123'})}) - with raises_regex(ValueError, 'unable to decode time'): - decode_cf(ds) - - @requires_netCDF4 - def test_dataset_repr_with_netcdf4_datetimes(self): - # regression test for #347 - attrs = {'units': 'days since 0001-01-01', 'calendar': 'noleap'} - with warnings.catch_warnings(): - warnings.filterwarnings('ignore', 'unable to decode time') - ds = decode_cf(Dataset({'time': ('time', [0, 1], attrs)})) - self.assertIn('(time) object', repr(ds)) - - attrs = {'units': 'days since 1900-01-01'} - ds = decode_cf(Dataset({'time': ('time', [0, 1], attrs)})) - self.assertIn('(time) datetime64[ns]', repr(ds)) - - # this should not throw a warning (GH1111) - with warnings.catch_warnings(): - warnings.filterwarnings('error') - conventions.DecodedCFDatetimeArray(np.asarray([722624]), - "days since 0001-01-01") + assert bx.dtype == np.bool + assert_array_equal(bx, np.array([True, False, True, True, False], + dtype=np.bool)) class TestNativeEndiannessArray(TestCase): @@ -592,7 +153,32 @@ def test(self): a = conventions.NativeEndiannessArray(x) assert a.dtype == expected.dtype assert a.dtype == expected[:].dtype - self.assertArrayEqual(a, expected) + assert_array_equal(a, expected) + + +def test_decode_cf_with_conflicting_fill_missing_value(): + var = Variable(['t'], np.arange(10), + {'units': 'foobar', + 'missing_value': 0, + '_FillValue': 1}) + with raises_regex(ValueError, "_FillValue and missing_value"): + conventions.decode_cf_variable('t', var) + + expected = Variable(['t'], np.arange(10), {'units': 'foobar'}) + + var = Variable(['t'], np.arange(10), + {'units': 'foobar', + 'missing_value': np.nan, + '_FillValue': np.nan}) + actual = conventions.decode_cf_variable('t', var) + assert_identical(actual, expected) + + var = Variable(['t'], np.arange(10), + {'units': 'foobar', + 'missing_value': np.float32(np.nan), + '_FillValue': np.float32(np.nan)}) + actual = conventions.decode_cf_variable('t', var) + assert_identical(actual, expected) @requires_netCDF4 @@ -604,7 +190,7 @@ def test_incompatible_attributes(self): Variable(['t'], pd.to_timedelta(['1 day']), {'units': 'foobar'}), Variable(['t'], [0, 1, 2], {'add_offset': 0}, {'add_offset': 2}), Variable(['t'], [0, 1, 2], {'_FillValue': 0}, {'_FillValue': 2}), - ] + ] for var in invalid_vars: with pytest.raises(ValueError): conventions.encode_cf_variable(var) @@ -612,9 +198,44 @@ def test_incompatible_attributes(self): def test_missing_fillvalue(self): v = Variable(['x'], np.array([np.nan, 1, 2, 3])) v.encoding = {'dtype': 'int16'} - with self.assertWarns('floating point data as an integer'): + with pytest.warns(Warning, match='floating point data as an integer'): conventions.encode_cf_variable(v) + def test_multidimensional_coordinates(self): + # regression test for GH1763 + # Set up test case with coordinates that have overlapping (but not + # identical) dimensions. + zeros1 = np.zeros((1, 5, 3)) + zeros2 = np.zeros((1, 6, 3)) + zeros3 = np.zeros((1, 5, 4)) + orig = Dataset({ + 'lon1': (['x1', 'y1'], zeros1.squeeze(0), {}), + 'lon2': (['x2', 'y1'], zeros2.squeeze(0), {}), + 'lon3': (['x1', 'y2'], zeros3.squeeze(0), {}), + 'lat1': (['x1', 'y1'], zeros1.squeeze(0), {}), + 'lat2': (['x2', 'y1'], zeros2.squeeze(0), {}), + 'lat3': (['x1', 'y2'], zeros3.squeeze(0), {}), + 'foo1': (['time', 'x1', 'y1'], zeros1, + {'coordinates': 'lon1 lat1'}), + 'foo2': (['time', 'x2', 'y1'], zeros2, + {'coordinates': 'lon2 lat2'}), + 'foo3': (['time', 'x1', 'y2'], zeros3, + {'coordinates': 'lon3 lat3'}), + 'time': ('time', [0.], {'units': 'hours since 2017-01-01'}), + }) + orig = conventions.decode_cf(orig) + # Encode the coordinates, as they would be in a netCDF output file. + enc, attrs = conventions.encode_dataset_coordinates(orig) + # Make sure we have the right coordinates for each variable. + foo1_coords = enc['foo1'].attrs.get('coordinates', '') + foo2_coords = enc['foo2'].attrs.get('coordinates', '') + foo3_coords = enc['foo3'].attrs.get('coordinates', '') + assert set(foo1_coords.split()) == set(['lat1', 'lon1']) + assert set(foo2_coords.split()) == set(['lat2', 'lon2']) + assert set(foo3_coords.split()) == set(['lat3', 'lon3']) + # Should not have any global coordinates. + assert 'coordinates' not in attrs + @requires_netCDF4 class TestDecodeCF(TestCase): @@ -628,26 +249,26 @@ def test_dataset(self): {'t': pd.date_range('2000-01-01', periods=3), 'y': ('t', [5.0, 10.0, np.nan])}) actual = conventions.decode_cf(original) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_invalid_coordinates(self): # regression test for GH308 original = Dataset({'foo': ('t', [1, 2], {'coordinates': 'invalid'})}) actual = conventions.decode_cf(original) - self.assertDatasetIdentical(original, actual) + assert_identical(original, actual) def test_decode_coordinates(self): # regression test for GH610 original = Dataset({'foo': ('t', [1, 2], {'coordinates': 'x'}), 'x': ('t', [4, 5])}) actual = conventions.decode_cf(original) - self.assertEqual(actual.foo.encoding['coordinates'], 'x') + assert actual.foo.encoding['coordinates'] == 'x' def test_0d_int32_encoding(self): original = Variable((), np.int32(0), encoding={'dtype': 'int64'}) expected = Variable((), np.int64(0)) actual = conventions.maybe_encode_nonstring_dtype(original) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_decode_cf_with_multiple_missing_values(self): original = Variable(['t'], [0, 1, 2], @@ -655,25 +276,59 @@ def test_decode_cf_with_multiple_missing_values(self): expected = Variable(['t'], [np.nan, np.nan, 2], {}) with warnings.catch_warnings(record=True) as w: actual = conventions.decode_cf_variable('t', original) - self.assertDatasetIdentical(expected, actual) - self.assertIn('has multiple fill', str(w[0].message)) + assert_identical(expected, actual) + assert 'has multiple fill' in str(w[0].message) def test_decode_cf_with_drop_variables(self): original = Dataset({ 't': ('t', [0, 1, 2], {'units': 'days since 2000-01-01'}), 'x': ("x", [9, 8, 7], {'units': 'km'}), - 'foo': (('t', 'x'), [[0, 0, 0], [1, 1, 1], [2, 2, 2]], {'units': 'bar'}), + 'foo': (('t', 'x'), [[0, 0, 0], [1, 1, 1], [2, 2, 2]], + {'units': 'bar'}), 'y': ('t', [5, 10, -999], {'_FillValue': -999}) }) expected = Dataset({ 't': pd.date_range('2000-01-01', periods=3), - 'foo': (('t', 'x'), [[0, 0, 0], [1, 1, 1], [2, 2, 2]], {'units': 'bar'}), + 'foo': (('t', 'x'), [[0, 0, 0], [1, 1, 1], [2, 2, 2]], + {'units': 'bar'}), 'y': ('t', [5, 10, np.nan]) }) actual = conventions.decode_cf(original, drop_variables=("x",)) actual2 = conventions.decode_cf(original, drop_variables="x") - self.assertDatasetIdentical(expected, actual) - self.assertDatasetIdentical(expected, actual2) + assert_identical(expected, actual) + assert_identical(expected, actual2) + + def test_invalid_time_units_raises_eagerly(self): + ds = Dataset({'time': ('time', [0, 1], {'units': 'foobar since 123'})}) + with raises_regex(ValueError, 'unable to decode time'): + decode_cf(ds) + + @requires_netCDF4 + def test_dataset_repr_with_netcdf4_datetimes(self): + # regression test for #347 + attrs = {'units': 'days since 0001-01-01', 'calendar': 'noleap'} + with warnings.catch_warnings(): + warnings.filterwarnings('ignore', 'unable to decode time') + ds = decode_cf(Dataset({'time': ('time', [0, 1], attrs)})) + assert '(time) object' in repr(ds) + + attrs = {'units': 'days since 1900-01-01'} + ds = decode_cf(Dataset({'time': ('time', [0, 1], attrs)})) + assert '(time) datetime64[ns]' in repr(ds) + + @requires_netCDF4 + def test_decode_cf_datetime_transition_to_invalid(self): + # manually create dataset with not-decoded date + from datetime import datetime + ds = Dataset(coords={'time': [0, 266 * 365]}) + units = 'days since 2000-01-01 00:00:00' + ds.time.attrs = dict(units=units) + ds_decoded = conventions.decode_cf(ds) + + expected = [datetime(2000, 1, 1, 0, 0), + datetime(2265, 10, 28, 0, 0)] + + assert_array_equal(ds_decoded.time.values, expected) class CFEncodedInMemoryStore(WritableCFDataStore, InMemoryDataStore): @@ -685,6 +340,7 @@ class NullWrapper(utils.NDArrayMixin): Just for testing, this lets us create a numpy array directly but make it look like its not in memory yet. """ + def __init__(self, array): self.array = array diff --git a/xarray/tests/test_dask.py b/xarray/tests/test_dask.py index 4e9b025..7833a43 100644 --- a/xarray/tests/test_dask.py +++ b/xarray/tests/test_dask.py @@ -14,13 +14,15 @@ from xarray import Variable, DataArray, Dataset import xarray.ufuncs as xu from xarray.core.pycompat import suppress, OrderedDict -from . import TestCase, assert_frame_equal, raises_regex +from . import ( + TestCase, assert_frame_equal, raises_regex, assert_equal, assert_identical, + assert_array_equal, assert_allclose) from xarray.tests import mock dask = pytest.importorskip('dask') -import dask.array as da -import dask.dataframe as dd +import dask.array as da # noqa: E402 # allow importorskip call above this +import dask.dataframe as dd # noqa: E402 class DaskTestCase(TestCase): @@ -30,28 +32,28 @@ def assertLazyAnd(self, expected, actual, test): if isinstance(actual, Dataset): for k, v in actual.variables.items(): if k in actual.dims: - self.assertIsInstance(v.data, np.ndarray) + assert isinstance(v.data, np.ndarray) else: - self.assertIsInstance(v.data, da.Array) + assert isinstance(v.data, da.Array) elif isinstance(actual, DataArray): - self.assertIsInstance(actual.data, da.Array) + assert isinstance(actual.data, da.Array) for k, v in actual.coords.items(): if k in actual.dims: - self.assertIsInstance(v.data, np.ndarray) + assert isinstance(v.data, np.ndarray) else: - self.assertIsInstance(v.data, da.Array) + assert isinstance(v.data, da.Array) elif isinstance(actual, Variable): - self.assertIsInstance(actual.data, da.Array) + assert isinstance(actual.data, da.Array) else: assert False class TestVariable(DaskTestCase): def assertLazyAndIdentical(self, expected, actual): - self.assertLazyAnd(expected, actual, self.assertVariableIdentical) + self.assertLazyAnd(expected, actual, assert_identical) def assertLazyAndAllClose(self, expected, actual): - self.assertLazyAnd(expected, actual, self.assertVariableAllClose) + self.assertLazyAnd(expected, actual, assert_allclose) def setUp(self): self.values = np.random.RandomState(0).randn(4, 6) @@ -62,9 +64,9 @@ def setUp(self): def test_basics(self): v = self.lazy_var - self.assertIs(self.data, v.data) - self.assertEqual(self.data.chunks, v.chunks) - self.assertArrayEqual(self.values, v) + assert self.data is v.data + assert self.data.chunks == v.chunks + assert_array_equal(self.values, v) def test_copy(self): self.assertLazyAndIdentical(self.eager_var, self.lazy_var.copy()) @@ -78,7 +80,7 @@ def test_chunk(self): ({'x': 3}, ((3, 1), (2, 2, 2))), ({'x': (3, 1)}, ((3, 1), (2, 2, 2)))]: rechunked = self.lazy_var.chunk(chunks) - self.assertEqual(rechunked.chunks, expected) + assert rechunked.chunks == expected self.assertLazyAndIdentical(self.eager_var, rechunked) def test_indexing(self): @@ -97,10 +99,10 @@ def test_squeeze(self): def test_equals(self): v = self.lazy_var - self.assertTrue(v.equals(v)) - self.assertIsInstance(v.data, da.Array) - self.assertTrue(v.identical(v)) - self.assertIsInstance(v.data, da.Array) + assert v.equals(v) + assert isinstance(v.data, da.Array) + assert v.identical(v) + assert isinstance(v.data, da.Array) def test_transpose(self): u = self.eager_var @@ -112,13 +114,13 @@ def test_shift(self): v = self.lazy_var self.assertLazyAndIdentical(u.shift(x=2), v.shift(x=2)) self.assertLazyAndIdentical(u.shift(x=-2), v.shift(x=-2)) - self.assertEqual(v.data.chunks, v.shift(x=1).data.chunks) + assert v.data.chunks == v.shift(x=1).data.chunks def test_roll(self): u = self.eager_var v = self.lazy_var self.assertLazyAndIdentical(u.roll(x=2), v.roll(x=2)) - self.assertEqual(v.data.chunks, v.roll(x=1).data.chunks) + assert v.data.chunks == v.roll(x=1).data.chunks def test_unary_op(self): u = self.eager_var @@ -138,20 +140,20 @@ def test_repr(self): expected = dedent("""\ dask.array""") - self.assertEqual(expected, repr(self.lazy_var)) + assert expected == repr(self.lazy_var) def test_pickle(self): # Test that pickling/unpickling does not convert the dask # backend to numpy a1 = Variable(['x'], build_dask_array('x')) a1.compute() - self.assertFalse(a1._in_memory) + assert not a1._in_memory assert kernel_call_count == 1 a2 = pickle.loads(pickle.dumps(a1)) assert kernel_call_count == 1 - self.assertVariableIdentical(a1, a2) - self.assertFalse(a1._in_memory) - self.assertFalse(a2._in_memory) + assert_identical(a1, a2) + assert not a1._in_memory + assert not a2._in_memory def test_reduce(self): u = self.eager_var @@ -171,7 +173,8 @@ def test_missing_values(self): eager_var = Variable('x', values) lazy_var = Variable('x', data) self.assertLazyAndIdentical(eager_var, lazy_var.fillna(lazy_var)) - self.assertLazyAndIdentical(Variable('x', range(4)), lazy_var.fillna(2)) + self.assertLazyAndIdentical(Variable('x', range(4)), + lazy_var.fillna(2)) self.assertLazyAndIdentical(eager_var.count(), lazy_var.count()) def test_concat(self): @@ -182,18 +185,19 @@ def test_concat(self): self.assertLazyAndIdentical(u[:2], Variable.concat([u[0], v[1]], 'x')) self.assertLazyAndIdentical(u[:2], Variable.concat([v[0], u[1]], 'x')) self.assertLazyAndIdentical( - u[:3], Variable.concat([v[[0, 2]], v[[1]]], 'x', positions=[[0, 2], [1]])) + u[:3], + Variable.concat([v[[0, 2]], v[[1]]], 'x', positions=[[0, 2], [1]])) def test_missing_methods(self): v = self.lazy_var try: v.argsort() except NotImplementedError as err: - self.assertIn('dask', str(err)) + assert 'dask' in str(err) try: v[0].item() except NotImplementedError as err: - self.assertIn('dask', str(err)) + assert 'dask' in str(err) def test_univariate_ufunc(self): u = self.eager_var @@ -237,13 +241,13 @@ def test_persist(self): class TestDataArrayAndDataset(DaskTestCase): def assertLazyAndIdentical(self, expected, actual): - self.assertLazyAnd(expected, actual, self.assertDataArrayIdentical) + self.assertLazyAnd(expected, actual, assert_identical) def assertLazyAndAllClose(self, expected, actual): - self.assertLazyAnd(expected, actual, self.assertDataArrayAllClose) + self.assertLazyAnd(expected, actual, assert_allclose) def assertLazyAndEqual(self, expected, actual): - self.assertLazyAnd(expected, actual, self.assertDataArrayEqual) + self.assertLazyAnd(expected, actual, assert_equal) def setUp(self): self.values = np.random.randn(4, 6) @@ -255,16 +259,16 @@ def setUp(self): def test_rechunk(self): chunked = self.eager_array.chunk({'x': 2}).chunk({'y': 2}) - self.assertEqual(chunked.chunks, ((2,) * 2, (2,) * 3)) + assert chunked.chunks == ((2,) * 2, (2,) * 3) self.assertLazyAndIdentical(self.lazy_array, chunked) def test_new_chunk(self): chunked = self.eager_array.chunk() - self.assertTrue(chunked.data.name.startswith('xarray-')) + assert chunked.data.name.startswith('xarray-') def test_lazy_dataset(self): lazy_ds = Dataset({'foo': (('x', 'y'), self.data)}) - self.assertIsInstance(lazy_ds.foo.variable.data, da.Array) + assert isinstance(lazy_ds.foo.variable.data, da.Array) def test_lazy_array(self): u = self.eager_array @@ -331,13 +335,15 @@ def test_concat_loads_variables(self): assert isinstance(out['d'].data, np.ndarray) assert isinstance(out['c'].data, np.ndarray) - out = xr.concat([ds1, ds2, ds3], dim='n', data_vars='all', coords='all') + out = xr.concat( + [ds1, ds2, ds3], dim='n', data_vars='all', coords='all') # no extra kernel calls assert kernel_call_count == 6 assert isinstance(out['d'].data, dask.array.Array) assert isinstance(out['c'].data, dask.array.Array) - out = xr.concat([ds1, ds2, ds3], dim='n', data_vars=['d'], coords=['c']) + out = xr.concat( + [ds1, ds2, ds3], dim='n', data_vars=['d'], coords=['c']) # no extra kernel calls assert kernel_call_count == 6 assert isinstance(out['d'].data, dask.array.Array) @@ -358,7 +364,8 @@ def test_concat_loads_variables(self): # When the test for different turns true halfway through, # stop computing variables as it would not have any benefit - ds4 = Dataset(data_vars={'d': ('x', [2.0])}, coords={'c': ('x', [2.0])}) + ds4 = Dataset(data_vars={'d': ('x', [2.0])}, + coords={'c': ('x', [2.0])}) out = xr.concat([ds1, ds2, ds4, ds3], dim='n', data_vars='different', coords='different') # the variables of ds1 and ds2 were computed, but those of ds3 didn't @@ -456,7 +463,7 @@ def counting_get(*args, **kwargs): with dask.set_options(get=counting_get): ds.load() - self.assertEqual(count[0], 1) + assert count[0] == 1 def test_stack(self): data = da.random.normal(size=(2, 3, 4), chunks=(1, 3, 4)) @@ -485,7 +492,7 @@ def test_dataarray_repr(self): Coordinates: y (x) int64 dask.array Dimensions without coordinates: x""") - self.assertEqual(expected, repr(a)) + assert expected == repr(a) assert kernel_call_count == 0 def test_dataset_repr(self): @@ -503,7 +510,7 @@ def test_dataset_repr(self): Dimensions without coordinates: x Data variables: a (x) int64 dask.array""") - self.assertEqual(expected, repr(ds)) + assert expected == repr(ds) assert kernel_call_count == 0 def test_dataarray_pickle(self): @@ -513,16 +520,16 @@ def test_dataarray_pickle(self): nonindex_coord = build_dask_array('coord') a1 = DataArray(data, dims=['x'], coords={'y': ('x', nonindex_coord)}) a1.compute() - self.assertFalse(a1._in_memory) - self.assertFalse(a1.coords['y']._in_memory) + assert not a1._in_memory + assert not a1.coords['y']._in_memory assert kernel_call_count == 2 a2 = pickle.loads(pickle.dumps(a1)) assert kernel_call_count == 2 - self.assertDataArrayIdentical(a1, a2) - self.assertFalse(a1._in_memory) - self.assertFalse(a2._in_memory) - self.assertFalse(a1.coords['y']._in_memory) - self.assertFalse(a2.coords['y']._in_memory) + assert_identical(a1, a2) + assert not a1._in_memory + assert not a2._in_memory + assert not a1.coords['y']._in_memory + assert not a2.coords['y']._in_memory def test_dataset_pickle(self): # Test that pickling/unpickling converts the dask backend @@ -532,16 +539,16 @@ def test_dataset_pickle(self): ds1 = Dataset(data_vars={'a': ('x', data)}, coords={'y': ('x', nonindex_coord)}) ds1.compute() - self.assertFalse(ds1['a']._in_memory) - self.assertFalse(ds1['y']._in_memory) + assert not ds1['a']._in_memory + assert not ds1['y']._in_memory assert kernel_call_count == 2 ds2 = pickle.loads(pickle.dumps(ds1)) assert kernel_call_count == 2 - self.assertDatasetIdentical(ds1, ds2) - self.assertFalse(ds1['a']._in_memory) - self.assertFalse(ds2['a']._in_memory) - self.assertFalse(ds1['y']._in_memory) - self.assertFalse(ds2['y']._in_memory) + assert_identical(ds1, ds2) + assert not ds1['a']._in_memory + assert not ds2['a']._in_memory + assert not ds1['y']._in_memory + assert not ds2['y']._in_memory def test_dataarray_getattr(self): # ipython/jupyter does a long list of getattr() calls to when trying to @@ -570,9 +577,9 @@ def test_values(self): # Test that invoking the values property does not convert the dask # backend to numpy a = DataArray([1, 2]).chunk() - self.assertFalse(a._in_memory) + assert not a._in_memory assert a.values.tolist() == [1, 2] - self.assertFalse(a._in_memory) + assert not a._in_memory def test_from_dask_variable(self): # Test array creation from Variable with dask backend. @@ -602,7 +609,7 @@ def test_to_dask_dataframe(self): expected = dd.from_pandas(expected_pd, chunksize=4) actual = ds.to_dask_dataframe(set_index=True) # test if we have dask dataframes - self.assertIsInstance(actual, dd.DataFrame) + assert isinstance(actual, dd.DataFrame) # use the .equals from pandas to check dataframes are equivalent assert_frame_equal(expected.compute(), actual.compute()) @@ -613,7 +620,7 @@ def test_to_dask_dataframe(self): actual = ds.to_dask_dataframe(set_index=False) - self.assertIsInstance(actual, dd.DataFrame) + assert isinstance(actual, dd.DataFrame) assert_frame_equal(expected.compute(), actual.compute()) def test_to_dask_dataframe_2D(self): @@ -634,7 +641,7 @@ def test_to_dask_dataframe_2D(self): expected = expected.reset_index(drop=False) actual = ds.to_dask_dataframe(set_index=False) - self.assertIsInstance(actual, dd.DataFrame) + assert isinstance(actual, dd.DataFrame) assert_frame_equal(expected, actual.compute()) @pytest.mark.xfail(raises=NotImplementedError) @@ -647,13 +654,13 @@ def test_to_dask_dataframe_2D_set_index(self): expected = ds.compute().to_dataframe() actual = ds.to_dask_dataframe(set_index=True) - self.assertIsInstance(actual, dd.DataFrame) + assert isinstance(actual, dd.DataFrame) assert_frame_equal(expected, actual.compute()) def test_to_dask_dataframe_coordinates(self): # Test if coordinate is also a dask array x = da.from_array(np.random.randn(10), chunks=4) - t = da.from_array(np.arange(10)*2, chunks=4) + t = da.from_array(np.arange(10) * 2, chunks=4) ds = Dataset(OrderedDict([('a', ('t', x)), ('t', ('t', t))])) @@ -662,7 +669,7 @@ def test_to_dask_dataframe_coordinates(self): index=pd.Index(t, name='t')) expected = dd.from_pandas(expected_pd, chunksize=4) actual = ds.to_dask_dataframe(set_index=True) - self.assertIsInstance(actual, dd.DataFrame) + assert isinstance(actual, dd.DataFrame) assert_frame_equal(expected.compute(), actual.compute()) def test_to_dask_dataframe_not_daskarray(self): @@ -679,7 +686,7 @@ def test_to_dask_dataframe_not_daskarray(self): index=pd.Index(t, name='t')) actual = ds.to_dask_dataframe(set_index=True) - self.assertIsInstance(actual, dd.DataFrame) + assert isinstance(actual, dd.DataFrame) assert_frame_equal(expected, actual.compute()) def test_to_dask_dataframe_no_coordinate(self): @@ -688,12 +695,12 @@ def test_to_dask_dataframe_no_coordinate(self): expected = ds.compute().to_dataframe().reset_index() actual = ds.to_dask_dataframe() - self.assertIsInstance(actual, dd.DataFrame) + assert isinstance(actual, dd.DataFrame) assert_frame_equal(expected, actual.compute()) expected = ds.compute().to_dataframe() actual = ds.to_dask_dataframe(set_index=True) - self.assertIsInstance(actual, dd.DataFrame) + assert isinstance(actual, dd.DataFrame) assert_frame_equal(expected, actual.compute()) def test_to_dask_dataframe_dim_order(self): @@ -702,12 +709,12 @@ def test_to_dask_dataframe_dim_order(self): expected = ds['w'].to_series().reset_index() actual = ds.to_dask_dataframe(dim_order=['x', 'y']) - self.assertIsInstance(actual, dd.DataFrame) + assert isinstance(actual, dd.DataFrame) assert_frame_equal(expected, actual.compute()) expected = ds['w'].T.to_series().reset_index() actual = ds.to_dask_dataframe(dim_order=['y', 'x']) - self.assertIsInstance(actual, dd.DataFrame) + assert isinstance(actual, dd.DataFrame) assert_frame_equal(expected, actual.compute()) with raises_regex(ValueError, 'does not match the set of dimensions'): @@ -829,4 +836,18 @@ def test_dataarray_with_dask_coords(): (array2,) = dask.compute(array) assert not dask.is_dask_collection(array2) - assert all(isinstance(v._variable.data, np.ndarray) for v in array2.coords.values()) + assert all(isinstance(v._variable.data, np.ndarray) + for v in array2.coords.values()) + + +def test_basic_compute(): + ds = Dataset({'foo': ('x', range(5)), + 'bar': ('x', range(5))}).chunk({'x': 2}) + for get in [dask.threaded.get, + dask.multiprocessing.get, + dask.local.get_sync, + None]: + with dask.set_options(get=get): + ds.compute() + ds.foo.compute() + ds.foo.variable.compute() diff --git a/xarray/tests/test_dataarray.py b/xarray/tests/test_dataarray.py index c86f706..39b3109 100644 --- a/xarray/tests/test_dataarray.py +++ b/xarray/tests/test_dataarray.py @@ -13,13 +13,13 @@ from xarray import (align, broadcast, Dataset, DataArray, IndexVariable, Variable) +from xarray.coding.times import CFDatetimeCoder from xarray.core.pycompat import iteritems, OrderedDict from xarray.core.common import full_like - from xarray.tests import ( TestCase, ReturnItem, source_ndarray, unittest, requires_dask, assert_identical, assert_equal, assert_allclose, assert_array_equal, - raises_regex, requires_scipy) + raises_regex, requires_scipy, requires_bottleneck) class TestDataArray(TestCase): @@ -50,7 +50,7 @@ def test_repr(self): Dimensions without coordinates: time Attributes: foo: bar""") - self.assertEqual(expected, repr(data_array)) + assert expected == repr(data_array) def test_repr_multiindex(self): expected = dedent("""\ @@ -60,22 +60,22 @@ def test_repr_multiindex(self): * x (x) MultiIndex - level_1 (x) object 'a' 'a' 'b' 'b' - level_2 (x) int64 1 2 1 2""") - self.assertEqual(expected, repr(self.mda)) + assert expected == repr(self.mda) def test_properties(self): - self.assertVariableEqual(self.dv.variable, self.v) - self.assertArrayEqual(self.dv.values, self.v.values) + assert_equal(self.dv.variable, self.v) + assert_array_equal(self.dv.values, self.v.values) for attr in ['dims', 'dtype', 'shape', 'size', 'nbytes', 'ndim', 'attrs']: - self.assertEqual(getattr(self.dv, attr), getattr(self.v, attr)) - self.assertEqual(len(self.dv), len(self.v)) - self.assertVariableEqual(self.dv.variable, self.v) - self.assertItemsEqual(list(self.dv.coords), list(self.ds.coords)) + assert getattr(self.dv, attr) == getattr(self.v, attr) + assert len(self.dv) == len(self.v) + assert_equal(self.dv.variable, self.v) + assert set(self.dv.coords) == set(self.ds.coords) for k, v in iteritems(self.dv.coords): - self.assertArrayEqual(v, self.ds.coords[k]) + assert_array_equal(v, self.ds.coords[k]) with pytest.raises(AttributeError): self.dv.dataset - self.assertIsInstance(self.ds['x'].to_index(), pd.Index) + assert isinstance(self.ds['x'].to_index(), pd.Index) with raises_regex(ValueError, 'must be 1-dimensional'): self.ds['foo'].to_index() with pytest.raises(AttributeError): @@ -85,10 +85,10 @@ def test_data_property(self): array = DataArray(np.zeros((3, 4))) actual = array.copy() actual.values = np.ones((3, 4)) - self.assertArrayEqual(np.ones((3, 4)), actual.values) + assert_array_equal(np.ones((3, 4)), actual.values) actual.data = 2 * np.ones((3, 4)) - self.assertArrayEqual(2 * np.ones((3, 4)), actual.data) - self.assertArrayEqual(actual.data, actual.values) + assert_array_equal(2 * np.ones((3, 4)), actual.data) + assert_array_equal(actual.data, actual.values) def test_indexes(self): array = DataArray(np.zeros((2, 3)), @@ -141,7 +141,7 @@ def test_struct_array_dims(self): expected = DataArray([1, -4, -5], dims=['participant'], coords={'participant': p_data}) - self.assertDataArrayIdentical(actual, expected) + assert_identical(actual, expected) # checking array subraction when dims are not the same p_data_1 = np.array([('John', 180), ('Stacy', 151), ('Dick', 200)], @@ -155,7 +155,7 @@ def test_struct_array_dims(self): expected = DataArray([1, -5], dims=['participant'], coords={'participant': p_data_2}) - self.assertDataArrayIdentical(actual, expected) + assert_identical(actual, expected) # checking array subraction when dims are not the same and one # is np.nan @@ -170,107 +170,107 @@ def test_struct_array_dims(self): expected = DataArray([1, -5], dims=['participant'], coords={'participant': p_data_2}) - self.assertDataArrayIdentical(actual, expected) + assert_identical(actual, expected) def test_name(self): arr = self.dv - self.assertEqual(arr.name, 'foo') + assert arr.name == 'foo' copied = arr.copy() arr.name = 'bar' - self.assertEqual(arr.name, 'bar') - self.assertDataArrayEqual(copied, arr) + assert arr.name == 'bar' + assert_equal(copied, arr) actual = DataArray(IndexVariable('x', [3])) actual.name = 'y' expected = DataArray([3], [('x', [3])], name='y') - self.assertDataArrayIdentical(actual, expected) + assert_identical(actual, expected) def test_dims(self): arr = self.dv - self.assertEqual(arr.dims, ('x', 'y')) + assert arr.dims == ('x', 'y') with raises_regex(AttributeError, 'you cannot assign'): arr.dims = ('w', 'z') def test_sizes(self): array = DataArray(np.zeros((3, 4)), dims=['x', 'y']) - self.assertEqual(array.sizes, {'x': 3, 'y': 4}) - self.assertEqual(tuple(array.sizes), array.dims) + assert array.sizes == {'x': 3, 'y': 4} + assert tuple(array.sizes) == array.dims with pytest.raises(TypeError): array.sizes['foo'] = 5 def test_encoding(self): expected = {'foo': 'bar'} self.dv.encoding['foo'] = 'bar' - assert expected, self.d == encoding + assert expected == self.dv.encoding expected = {'baz': 0} self.dv.encoding = expected - assert expected, self.d == encoding - self.assertIsNot(expected, self.dv.encoding) + + assert expected is not self.dv.encoding def test_constructor(self): data = np.random.random((2, 3)) actual = DataArray(data) expected = Dataset({None: (['dim_0', 'dim_1'], data)})[None] - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = DataArray(data, [['a', 'b'], [-1, -2, -3]]) expected = Dataset({None: (['dim_0', 'dim_1'], data), 'dim_0': ('dim_0', ['a', 'b']), 'dim_1': ('dim_1', [-1, -2, -3])})[None] - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = DataArray(data, [pd.Index(['a', 'b'], name='x'), pd.Index([-1, -2, -3], name='y')]) expected = Dataset({None: (['x', 'y'], data), 'x': ('x', ['a', 'b']), 'y': ('y', [-1, -2, -3])})[None] - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) coords = [['a', 'b'], [-1, -2, -3]] actual = DataArray(data, coords, ['x', 'y']) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) coords = [pd.Index(['a', 'b'], name='A'), pd.Index([-1, -2, -3], name='B')] actual = DataArray(data, coords, ['x', 'y']) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) coords = {'x': ['a', 'b'], 'y': [-1, -2, -3]} actual = DataArray(data, coords, ['x', 'y']) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) coords = [('x', ['a', 'b']), ('y', [-1, -2, -3])] actual = DataArray(data, coords) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) expected = Dataset({None: (['x', 'y'], data), 'x': ('x', ['a', 'b'])})[None] actual = DataArray(data, {'x': ['a', 'b']}, ['x', 'y']) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = DataArray(data, dims=['x', 'y']) expected = Dataset({None: (['x', 'y'], data)})[None] - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = DataArray(data, dims=['x', 'y'], name='foo') expected = Dataset({'foo': (['x', 'y'], data)})['foo'] - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = DataArray(data, name='foo') expected = Dataset({'foo': (['dim_0', 'dim_1'], data)})['foo'] - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = DataArray(data, dims=['x', 'y'], attrs={'bar': 2}) expected = Dataset({None: (['x', 'y'], data, {'bar': 2})})[None] - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = DataArray(data, dims=['x', 'y'], encoding={'bar': 2}) expected = Dataset({None: (['x', 'y'], data, {}, {'bar': 2})})[None] - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) def test_constructor_invalid(self): data = np.random.randn(3, 2) @@ -308,48 +308,47 @@ def test_constructor_from_self_described(self): dims=['x', 'y'], name='foobar', attrs={'bar': 2}, encoding={'foo': 3}) actual = DataArray(expected) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = DataArray(expected.values, actual.coords) - self.assertDataArrayEqual(expected, actual) + assert_equal(expected, actual) frame = pd.DataFrame(data, index=pd.Index(['a', 'b'], name='x'), columns=pd.Index([-1, -2], name='y')) actual = DataArray(frame) - self.assertDataArrayEqual(expected, actual) + assert_equal(expected, actual) series = pd.Series(data[0], index=pd.Index([-1, -2], name='y')) actual = DataArray(series) - self.assertDataArrayEqual(expected[0].reset_coords('x', drop=True), - actual) + assert_equal(expected[0].reset_coords('x', drop=True), actual) panel = pd.Panel({0: frame}) actual = DataArray(panel) expected = DataArray([data], expected.coords, ['dim_0', 'x', 'y']) expected['dim_0'] = [0] - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) expected = DataArray(data, coords={'x': ['a', 'b'], 'y': [-1, -2], 'a': 0, 'z': ('x', [-0.5, 0.5])}, dims=['x', 'y']) actual = DataArray(expected) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = DataArray(expected.values, expected.coords) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) expected = Dataset({'foo': ('foo', ['a', 'b'])})['foo'] actual = DataArray(pd.Index(['a', 'b'], name='foo')) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = DataArray(IndexVariable('foo', ['a', 'b'])) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) def test_constructor_from_0d(self): expected = Dataset({None: ([], 0)})[None] actual = DataArray(0) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) @requires_dask def test_constructor_dask_coords(self): @@ -371,77 +370,77 @@ def test_equals_and_identical(self): expected = orig actual = orig.copy() - self.assertTrue(expected.equals(actual)) - self.assertTrue(expected.identical(actual)) + assert expected.equals(actual) + assert expected.identical(actual) actual = expected.rename('baz') - self.assertTrue(expected.equals(actual)) - self.assertFalse(expected.identical(actual)) + assert expected.equals(actual) + assert not expected.identical(actual) actual = expected.rename({'x': 'xxx'}) - self.assertFalse(expected.equals(actual)) - self.assertFalse(expected.identical(actual)) + assert not expected.equals(actual) + assert not expected.identical(actual) actual = expected.copy() actual.attrs['foo'] = 'bar' - self.assertTrue(expected.equals(actual)) - self.assertFalse(expected.identical(actual)) + assert expected.equals(actual) + assert not expected.identical(actual) actual = expected.copy() actual['x'] = ('x', -np.arange(5)) - self.assertFalse(expected.equals(actual)) - self.assertFalse(expected.identical(actual)) + assert not expected.equals(actual) + assert not expected.identical(actual) actual = expected.reset_coords(drop=True) - self.assertFalse(expected.equals(actual)) - self.assertFalse(expected.identical(actual)) + assert not expected.equals(actual) + assert not expected.identical(actual) actual = orig.copy() actual[0] = np.nan expected = actual.copy() - self.assertTrue(expected.equals(actual)) - self.assertTrue(expected.identical(actual)) + assert expected.equals(actual) + assert expected.identical(actual) actual[:] = np.nan - self.assertFalse(expected.equals(actual)) - self.assertFalse(expected.identical(actual)) + assert not expected.equals(actual) + assert not expected.identical(actual) actual = expected.copy() actual['a'] = 100000 - self.assertFalse(expected.equals(actual)) - self.assertFalse(expected.identical(actual)) + assert not expected.equals(actual) + assert not expected.identical(actual) def test_equals_failures(self): orig = DataArray(np.arange(5.0), {'a': 42}, dims='x') - self.assertFalse(orig.equals(np.arange(5))) - self.assertFalse(orig.identical(123)) - self.assertFalse(orig.broadcast_equals({1: 2})) + assert not orig.equals(np.arange(5)) + assert not orig.identical(123) + assert not orig.broadcast_equals({1: 2}) def test_broadcast_equals(self): a = DataArray([0, 0], {'y': 0}, dims='x') b = DataArray([0, 0], {'y': ('x', [0, 0])}, dims='x') - self.assertTrue(a.broadcast_equals(b)) - self.assertTrue(b.broadcast_equals(a)) - self.assertFalse(a.equals(b)) - self.assertFalse(a.identical(b)) + assert a.broadcast_equals(b) + assert b.broadcast_equals(a) + assert not a.equals(b) + assert not a.identical(b) c = DataArray([0], coords={'x': 0}, dims='y') - self.assertFalse(a.broadcast_equals(c)) - self.assertFalse(c.broadcast_equals(a)) + assert not a.broadcast_equals(c) + assert not c.broadcast_equals(a) def test_getitem(self): # strings pull out dataarrays - self.assertDataArrayIdentical(self.dv, self.ds['foo']) + assert_identical(self.dv, self.ds['foo']) x = self.dv['x'] y = self.dv['y'] - self.assertDataArrayIdentical(self.ds['x'], x) - self.assertDataArrayIdentical(self.ds['y'], y) + assert_identical(self.ds['x'], x) + assert_identical(self.ds['y'], y) - I = ReturnItem() + I = ReturnItem() # noqa: E741 # allow ambiguous name for i in [I[:], I[...], I[x.values], I[x.variable], I[x], I[x, y], I[x.values > -1], I[x.variable > -1], I[x > -1], I[x > -1, y > -1]]: - self.assertVariableEqual(self.dv, self.dv[i]) + assert_equal(self.dv, self.dv[i]) for i in [I[0], I[:, 0], I[:3, :2], I[x.values[:3]], I[x.variable[:3]], I[x[:3]], I[x[:3], y[:4]], @@ -452,7 +451,7 @@ def test_getitem(self): def test_getitem_dict(self): actual = self.dv[{'x': slice(3), 'y': 0}] expected = self.dv.isel(x=slice(3), y=0) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) def test_getitem_coords(self): orig = DataArray([[10], [20]], @@ -462,51 +461,51 @@ def test_getitem_coords(self): 'xy': (['y', 'x'], [['d', 'e']])}, dims=['x', 'y']) - self.assertDataArrayIdentical(orig, orig[:]) - self.assertDataArrayIdentical(orig, orig[:, :]) - self.assertDataArrayIdentical(orig, orig[...]) - self.assertDataArrayIdentical(orig, orig[:2, :1]) - self.assertDataArrayIdentical(orig, orig[[0, 1], [0]]) + assert_identical(orig, orig[:]) + assert_identical(orig, orig[:, :]) + assert_identical(orig, orig[...]) + assert_identical(orig, orig[:2, :1]) + assert_identical(orig, orig[[0, 1], [0]]) actual = orig[0, 0] expected = DataArray( 10, {'x': 1, 'y': 3, 'z': 4, 'x2': 'a', 'y2': 'c', 'xy': 'd'}) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = orig[0, :] expected = DataArray( [10], {'x': 1, 'y': [3], 'z': 4, 'x2': 'a', 'y2': ('y', ['c']), 'xy': ('y', ['d'])}, dims='y') - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = orig[:, 0] expected = DataArray( [10, 20], {'x': [1, 2], 'y': 3, 'z': 4, 'x2': ('x', ['a', 'b']), 'y2': 'c', 'xy': ('x', ['d', 'e'])}, dims='x') - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) def test_getitem_dataarray(self): # It should not conflict da = DataArray(np.arange(12).reshape((3, 4)), dims=['x', 'y']) ind = DataArray([[0, 1], [0, 1]], dims=['x', 'z']) actual = da[ind] - self.assertArrayEqual(actual, da.values[[[0, 1], [0, 1]], :]) + assert_array_equal(actual, da.values[[[0, 1], [0, 1]], :]) da = DataArray(np.arange(12).reshape((3, 4)), dims=['x', 'y'], coords={'x': [0, 1, 2], 'y': ['a', 'b', 'c', 'd']}) ind = xr.DataArray([[0, 1], [0, 1]], dims=['X', 'Y']) actual = da[ind] expected = da.values[[[0, 1], [0, 1]], :] - self.assertArrayEqual(actual, expected) + assert_array_equal(actual, expected) assert actual.dims == ('X', 'Y', 'y') # boolean indexing ind = xr.DataArray([True, True, False], dims=['x']) - self.assertDataArrayEqual(da[ind], da[[0, 1], :]) - self.assertDataArrayEqual(da[ind], da[[0, 1]]) - self.assertDataArrayEqual(da[ind], da[ind.values]) + assert_equal(da[ind], da[[0, 1], :]) + assert_equal(da[ind], da[[0, 1]]) + assert_equal(da[ind], da[ind.values]) def test_setitem(self): # basic indexing should work as numpy's indexing @@ -524,7 +523,94 @@ def test_setitem(self): dims=['x', 'y']) orig[t] = 1 expected[t] = 1 - self.assertArrayEqual(orig.values, expected) + assert_array_equal(orig.values, expected) + + def test_setitem_fancy(self): + # vectorized indexing + da = DataArray(np.ones((3, 2)), dims=['x', 'y']) + ind = Variable(['a'], [0, 1]) + da[dict(x=ind, y=ind)] = 0 + expected = DataArray([[0, 1], [1, 0], [1, 1]], dims=['x', 'y']) + assert_identical(expected, da) + # assign another 0d-variable + da[dict(x=ind, y=ind)] = Variable((), 0) + expected = DataArray([[0, 1], [1, 0], [1, 1]], dims=['x', 'y']) + assert_identical(expected, da) + # assign another 1d-variable + da[dict(x=ind, y=ind)] = Variable(['a'], [2, 3]) + expected = DataArray([[2, 1], [1, 3], [1, 1]], dims=['x', 'y']) + assert_identical(expected, da) + + # 2d-vectorized indexing + da = DataArray(np.ones((3, 2)), dims=['x', 'y']) + ind_x = DataArray([[0, 1]], dims=['a', 'b']) + ind_y = DataArray([[1, 0]], dims=['a', 'b']) + da[dict(x=ind_x, y=ind_y)] = 0 + expected = DataArray([[1, 0], [0, 1], [1, 1]], dims=['x', 'y']) + assert_identical(expected, da) + + da = DataArray(np.ones((3, 2)), dims=['x', 'y']) + ind = Variable(['a'], [0, 1]) + da[ind] = 0 + expected = DataArray([[0, 0], [0, 0], [1, 1]], dims=['x', 'y']) + assert_identical(expected, da) + + def test_setitem_dataarray(self): + def get_data(): + return DataArray(np.ones((4, 3, 2)), dims=['x', 'y', 'z'], + coords={'x': np.arange(4), 'y': ['a', 'b', 'c'], + 'non-dim': ('x', [1, 3, 4, 2])}) + + da = get_data() + # indexer with inconsistent coordinates. + ind = DataArray(np.arange(1, 4), dims=['x'], + coords={'x': np.random.randn(3)}) + with raises_regex(IndexError, "dimension coordinate 'x'"): + da[dict(x=ind)] = 0 + + # indexer with consistent coordinates. + ind = DataArray(np.arange(1, 4), dims=['x'], + coords={'x': np.arange(1, 4)}) + da[dict(x=ind)] = 0 # should not raise + assert np.allclose(da[dict(x=ind)].values, 0) + assert_identical(da['x'], get_data()['x']) + assert_identical(da['non-dim'], get_data()['non-dim']) + + da = get_data() + # conflict in the assigning values + value = xr.DataArray(np.zeros((3, 3, 2)), dims=['x', 'y', 'z'], + coords={'x': [0, 1, 2], + 'non-dim': ('x', [0, 2, 4])}) + with raises_regex(IndexError, "dimension coordinate 'x'"): + da[dict(x=ind)] = value + + # consistent coordinate in the assigning values + value = xr.DataArray(np.zeros((3, 3, 2)), dims=['x', 'y', 'z'], + coords={'x': [1, 2, 3], + 'non-dim': ('x', [0, 2, 4])}) + da[dict(x=ind)] = value + assert np.allclose(da[dict(x=ind)].values, 0) + assert_identical(da['x'], get_data()['x']) + assert_identical(da['non-dim'], get_data()['non-dim']) + + # Conflict in the non-dimension coordinate + value = xr.DataArray(np.zeros((3, 3, 2)), dims=['x', 'y', 'z'], + coords={'x': [1, 2, 3], + 'non-dim': ('x', [0, 2, 4])}) + da[dict(x=ind)] = value # should not raise + + # conflict in the assigning values + value = xr.DataArray(np.zeros((3, 3, 2)), dims=['x', 'y', 'z'], + coords={'x': [0, 1, 2], + 'non-dim': ('x', [0, 2, 4])}) + with raises_regex(IndexError, "dimension coordinate 'x'"): + da[dict(x=ind)] = value + + # consistent coordinate in the assigning values + value = xr.DataArray(np.zeros((3, 3, 2)), dims=['x', 'y', 'z'], + coords={'x': [1, 2, 3], + 'non-dim': ('x', [0, 2, 4])}) + da[dict(x=ind)] = value # should not raise def test_contains(self): data_array = DataArray(1, coords={'x': 2}) @@ -534,54 +620,53 @@ def test_contains(self): def test_attr_sources_multiindex(self): # make sure attr-style access for multi-index levels # returns DataArray objects - self.assertIsInstance(self.mda.level_1, DataArray) + assert isinstance(self.mda.level_1, DataArray) def test_pickle(self): data = DataArray(np.random.random((3, 3)), dims=('id', 'time')) roundtripped = pickle.loads(pickle.dumps(data)) - self.assertDataArrayIdentical(data, roundtripped) + assert_identical(data, roundtripped) @requires_dask def test_chunk(self): unblocked = DataArray(np.ones((3, 4))) - self.assertIsNone(unblocked.chunks) + assert unblocked.chunks is None blocked = unblocked.chunk() - self.assertEqual(blocked.chunks, ((3,), (4,))) + assert blocked.chunks == ((3,), (4,)) blocked = unblocked.chunk(chunks=((2, 1), (2, 2))) - self.assertEqual(blocked.chunks, ((2, 1), (2, 2))) + assert blocked.chunks == ((2, 1), (2, 2)) blocked = unblocked.chunk(chunks=(3, 3)) - self.assertEqual(blocked.chunks, ((3,), (3, 1))) + assert blocked.chunks == ((3,), (3, 1)) - self.assertIsNone(blocked.load().chunks) + assert blocked.load().chunks is None # Check that kwargs are passed import dask.array as da blocked = unblocked.chunk(name_prefix='testname_') - self.assertIsInstance(blocked.data, da.Array) + assert isinstance(blocked.data, da.Array) assert 'testname_' in blocked.data.name def test_isel(self): - self.assertDataArrayIdentical(self.dv[0], self.dv.isel(x=0)) - self.assertDataArrayIdentical(self.dv, self.dv.isel(x=slice(None))) - self.assertDataArrayIdentical(self.dv[:3], self.dv.isel(x=slice(3))) - self.assertDataArrayIdentical(self.dv[:3, :5], - self.dv.isel(x=slice(3), y=slice(5))) + assert_identical(self.dv[0], self.dv.isel(x=0)) + assert_identical(self.dv, self.dv.isel(x=slice(None))) + assert_identical(self.dv[:3], self.dv.isel(x=slice(3))) + assert_identical(self.dv[:3, :5], self.dv.isel(x=slice(3), y=slice(5))) def test_isel_types(self): # regression test for #1405 da = DataArray([1, 2, 3], dims='x') # uint64 - self.assertDataArrayIdentical(da.isel(x=np.array([0], dtype="uint64")), - da.isel(x=np.array([0]))) + assert_identical(da.isel(x=np.array([0], dtype="uint64")), + da.isel(x=np.array([0]))) # uint32 - self.assertDataArrayIdentical(da.isel(x=np.array([0], dtype="uint32")), - da.isel(x=np.array([0]))) + assert_identical(da.isel(x=np.array([0], dtype="uint32")), + da.isel(x=np.array([0]))) # int64 - self.assertDataArrayIdentical(da.isel(x=np.array([0], dtype="int64")), - da.isel(x=np.array([0]))) + assert_identical(da.isel(x=np.array([0], dtype="int64")), + da.isel(x=np.array([0]))) def test_isel_fancy(self): shape = (10, 7, 6) @@ -614,13 +699,13 @@ def test_isel_fancy(self): np.testing.assert_equal(actual, expected) # test that the order of the indexers doesn't matter - self.assertDataArrayIdentical( + assert_identical( da.isel(y=(('points', ), y), x=(('points', ), x)), da.isel(x=(('points', ), x), y=(('points', ), y))) # make sure we're raising errors in the right places with raises_regex(IndexError, - 'Dimensions of indexers mismatch'): + 'Dimensions of indexers mismatch'): da.isel(y=(('points', ), [1, 2]), x=(('points', ), [1, 2, 3])) # tests using index or DataArray as indexers @@ -632,7 +717,7 @@ def test_isel_fancy(self): actual = da.isel(x=stations['dim1s'], y=stations['dim2s']) assert 'station' in actual.coords assert 'station' in actual.dims - self.assertDataArrayIdentical(actual['station'], stations['station']) + assert_identical(actual['station'], stations['station']) with raises_regex(ValueError, 'conflicting values for '): da.isel(x=DataArray([0, 1, 2], dims='station', @@ -652,24 +737,24 @@ def test_isel_fancy(self): assert 'a' in actual.dims assert 'b' in actual.coords assert 'b' in actual.dims - self.assertDataArrayIdentical(actual['a'], stations['a']) - self.assertDataArrayIdentical(actual['b'], stations['b']) + assert_identical(actual['a'], stations['a']) + assert_identical(actual['b'], stations['b']) expected = da.variable[:, stations['dim2s'].variable, stations['dim1s'].variable] - self.assertArrayEqual(actual, expected) + assert_array_equal(actual, expected) def test_sel(self): self.ds['x'] = ('x', np.array(list('abcdefghij'))) da = self.ds['foo'] - self.assertDataArrayIdentical(da, da.sel(x=slice(None))) - self.assertDataArrayIdentical(da[1], da.sel(x='b')) - self.assertDataArrayIdentical(da[:3], da.sel(x=slice('c'))) - self.assertDataArrayIdentical(da[:3], da.sel(x=['a', 'b', 'c'])) - self.assertDataArrayIdentical(da[:, :4], da.sel(y=(self.ds['y'] < 4))) + assert_identical(da, da.sel(x=slice(None))) + assert_identical(da[1], da.sel(x='b')) + assert_identical(da[:3], da.sel(x=slice('c'))) + assert_identical(da[:3], da.sel(x=['a', 'b', 'c'])) + assert_identical(da[:, :4], da.sel(y=(self.ds['y'] < 4))) # verify that indexing with a dataarray works b = DataArray('b') - self.assertDataArrayIdentical(da[1], da.sel(x=b)) - self.assertDataArrayIdentical(da[[1]], da.sel(x=slice(b, b))) + assert_identical(da[1], da.sel(x=b)) + assert_identical(da[[1]], da.sel(x=slice(b, b))) def test_sel_dataarray(self): # indexing with DataArray @@ -678,30 +763,29 @@ def test_sel_dataarray(self): ind = DataArray(['a', 'b', 'c'], dims=['x']) actual = da.sel(x=ind) - self.assertDataArrayIdentical(actual, da.isel(x=[0, 1, 2])) + assert_identical(actual, da.isel(x=[0, 1, 2])) # along new dimension ind = DataArray(['a', 'b', 'c'], dims=['new_dim']) actual = da.sel(x=ind) - self.assertArrayEqual(actual, da.isel(x=[0, 1, 2])) + assert_array_equal(actual, da.isel(x=[0, 1, 2])) assert 'new_dim' in actual.dims # with coordinate ind = DataArray(['a', 'b', 'c'], dims=['new_dim'], coords={'new_dim': [0, 1, 2]}) actual = da.sel(x=ind) - self.assertArrayEqual(actual, da.isel(x=[0, 1, 2])) + assert_array_equal(actual, da.isel(x=[0, 1, 2])) assert 'new_dim' in actual.dims assert 'new_dim' in actual.coords - self.assertDataArrayEqual(actual['new_dim'].drop('x'), - ind['new_dim']) + assert_equal(actual['new_dim'].drop('x'), ind['new_dim']) def test_sel_no_index(self): array = DataArray(np.arange(10), dims='x') - self.assertDataArrayIdentical(array[0], array.sel(x=0)) - self.assertDataArrayIdentical(array[:5], array.sel(x=slice(5))) - self.assertDataArrayIdentical(array[[0, -1]], array.sel(x=[0, -1])) - self.assertDataArrayIdentical( + assert_identical(array[0], array.sel(x=0)) + assert_identical(array[:5], array.sel(x=slice(5))) + assert_identical(array[[0, -1]], array.sel(x=[0, -1])) + assert_identical( array[array < 5], array.sel(x=(array < 5))) def test_sel_method(self): @@ -710,36 +794,36 @@ def test_sel_method(self): expected = data.sel(y=['a', 'b']) actual = data.sel(y=['ab', 'ba'], method='pad') - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) expected = data.sel(x=[1, 2]) actual = data.sel(x=[0.9, 1.9], method='backfill', tolerance=1) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) def test_sel_drop(self): data = DataArray([1, 2, 3], [('x', [0, 1, 2])]) expected = DataArray(1) selected = data.sel(x=0, drop=True) - self.assertDataArrayIdentical(expected, selected) + assert_identical(expected, selected) expected = DataArray(1, {'x': 0}) selected = data.sel(x=0, drop=False) - self.assertDataArrayIdentical(expected, selected) + assert_identical(expected, selected) data = DataArray([1, 2, 3], dims=['x']) expected = DataArray(1) selected = data.sel(x=0, drop=True) - self.assertDataArrayIdentical(expected, selected) + assert_identical(expected, selected) def test_isel_drop(self): data = DataArray([1, 2, 3], [('x', [0, 1, 2])]) expected = DataArray(1) selected = data.isel(x=0, drop=True) - self.assertDataArrayIdentical(expected, selected) + assert_identical(expected, selected) expected = DataArray(1, {'x': 0}) selected = data.isel(x=0, drop=False) - self.assertDataArrayIdentical(expected, selected) + assert_identical(expected, selected) def test_isel_points(self): shape = (10, 5, 6) @@ -776,26 +860,26 @@ def test_isel_points(self): np.testing.assert_equal(actual.T, expected) # test that the order of the indexers doesn't matter - self.assertDataArrayIdentical( + assert_identical( da.isel_points(y=y, x=x), da.isel_points(x=x, y=y)) # make sure we're raising errors in the right places with raises_regex(ValueError, - 'All indexers must be the same length'): + 'All indexers must be the same length'): da.isel_points(y=[1, 2], x=[1, 2, 3]) with raises_regex(ValueError, - 'dimension bad_key does not exist'): + 'dimension bad_key does not exist'): da.isel_points(bad_key=[1, 2]) with raises_regex(TypeError, 'Indexers must be integers'): da.isel_points(y=[1.5, 2.2]) with raises_regex(TypeError, 'Indexers must be integers'): da.isel_points(x=[1, 2, 3], y=slice(3)) with raises_regex(ValueError, - 'Indexers must be 1 dimensional'): + 'Indexers must be 1 dimensional'): da.isel_points(y=1, x=2) with raises_regex(ValueError, - 'Existing dimension names are not'): + 'Existing dimension names are not'): da.isel_points(y=[1, 2], x=[1, 2], dim='x') # using non string dims @@ -805,26 +889,25 @@ def test_isel_points(self): def test_loc(self): self.ds['x'] = ('x', np.array(list('abcdefghij'))) da = self.ds['foo'] - self.assertDataArrayIdentical(da[:3], da.loc[:'c']) - self.assertDataArrayIdentical(da[1], da.loc['b']) - self.assertDataArrayIdentical(da[1], da.loc[{'x': 'b'}]) - self.assertDataArrayIdentical(da[1], da.loc['b', ...]) - self.assertDataArrayIdentical(da[:3], da.loc[['a', 'b', 'c']]) - self.assertDataArrayIdentical(da[:3, :4], - da.loc[['a', 'b', 'c'], np.arange(4)]) - self.assertDataArrayIdentical(da[:, :4], da.loc[:, self.ds['y'] < 4]) + assert_identical(da[:3], da.loc[:'c']) + assert_identical(da[1], da.loc['b']) + assert_identical(da[1], da.loc[{'x': 'b'}]) + assert_identical(da[1], da.loc['b', ...]) + assert_identical(da[:3], da.loc[['a', 'b', 'c']]) + assert_identical(da[:3, :4], da.loc[['a', 'b', 'c'], np.arange(4)]) + assert_identical(da[:, :4], da.loc[:, self.ds['y'] < 4]) def test_loc_assign(self): self.ds['x'] = ('x', np.array(list('abcdefghij'))) da = self.ds['foo'] # assignment da.loc['a':'j'] = 0 - self.assertTrue(np.all(da.values == 0)) + assert np.all(da.values == 0) da.loc[{'x': slice('a', 'j')}] = 2 - self.assertTrue(np.all(da.values == 2)) + assert np.all(da.values == 2) da.loc[{'x': slice('a', 'j')}] = 2 - self.assertTrue(np.all(da.values == 2)) + assert np.all(da.values == 2) # Multi dimensional case da = DataArray(np.arange(12).reshape(3, 4), dims=['x', 'y']) @@ -834,13 +917,51 @@ def test_loc_assign(self): da = DataArray(np.arange(12).reshape(3, 4), dims=['x', 'y']) da.loc[0] = 0 - self.assertTrue(np.all(da.values[0] == np.zeros(4))) + assert np.all(da.values[0] == np.zeros(4)) assert da.values[1, 0] != 0 + def test_loc_assign_dataarray(self): + def get_data(): + return DataArray(np.ones((4, 3, 2)), dims=['x', 'y', 'z'], + coords={'x': np.arange(4), 'y': ['a', 'b', 'c'], + 'non-dim': ('x', [1, 3, 4, 2])}) + + da = get_data() + # indexer with inconsistent coordinates. + ind = DataArray(np.arange(1, 4), dims=['y'], + coords={'y': np.random.randn(3)}) + with raises_regex(IndexError, "dimension coordinate 'y'"): + da.loc[dict(x=ind)] = 0 + + # indexer with consistent coordinates. + ind = DataArray(np.arange(1, 4), dims=['x'], + coords={'x': np.arange(1, 4)}) + da.loc[dict(x=ind)] = 0 # should not raise + assert np.allclose(da[dict(x=ind)].values, 0) + assert_identical(da['x'], get_data()['x']) + assert_identical(da['non-dim'], get_data()['non-dim']) + + da = get_data() + # conflict in the assigning values + value = xr.DataArray(np.zeros((3, 3, 2)), dims=['x', 'y', 'z'], + coords={'x': [0, 1, 2], + 'non-dim': ('x', [0, 2, 4])}) + with raises_regex(IndexError, "dimension coordinate 'x'"): + da.loc[dict(x=ind)] = value + + # consistent coordinate in the assigning values + value = xr.DataArray(np.zeros((3, 3, 2)), dims=['x', 'y', 'z'], + coords={'x': [1, 2, 3], + 'non-dim': ('x', [0, 2, 4])}) + da.loc[dict(x=ind)] = value + assert np.allclose(da[dict(x=ind)].values, 0) + assert_identical(da['x'], get_data()['x']) + assert_identical(da['non-dim'], get_data()['non-dim']) + def test_loc_single_boolean(self): data = DataArray([0, 1], coords=[[True, False]]) - self.assertEqual(data.loc[True], 0) - self.assertEqual(data.loc[False], 1) + assert data.loc[True] == 0 + assert data.loc[False] == 1 def test_selection_multiindex(self): mindex = pd.MultiIndex.from_product([['a', 'b'], [1, 2], [-1, -2]], @@ -852,12 +973,12 @@ def test_sel(lab_indexer, pos_indexer, replaced_idx=False, da = mdata.sel(x=lab_indexer) expected_da = mdata.isel(x=pos_indexer) if not replaced_idx: - self.assertDataArrayIdentical(da, expected_da) + assert_identical(da, expected_da) else: if renamed_dim: - self.assertEqual(da.dims[0], renamed_dim) + assert da.dims[0] == renamed_dim da = da.rename({renamed_dim: 'x'}) - self.assertVariableIdentical(da.variable, expected_da.variable) + assert_identical(da.variable, expected_da.variable) self.assertVariableNotEqual(da['x'], expected_da['x']) test_sel(('a', 1, -1), 0) @@ -873,29 +994,28 @@ def test_sel(lab_indexer, pos_indexer, replaced_idx=False, renamed_dim='three') test_sel({'one': 'a'}, range(4), replaced_idx=True) - self.assertDataArrayIdentical(mdata.loc['a'], mdata.sel(x='a')) - self.assertDataArrayIdentical(mdata.loc[('a', 1), ...], - mdata.sel(x=('a', 1))) - self.assertDataArrayIdentical(mdata.loc[{'one': 'a'}, ...], - mdata.sel(x={'one': 'a'})) + assert_identical(mdata.loc['a'], mdata.sel(x='a')) + assert_identical(mdata.loc[('a', 1), ...], mdata.sel(x=('a', 1))) + assert_identical(mdata.loc[{'one': 'a'}, ...], + mdata.sel(x={'one': 'a'})) with pytest.raises(IndexError): mdata.loc[('a', 1)] - self.assertDataArrayIdentical(mdata.sel(x={'one': 'a', 'two': 1}), - mdata.sel(one='a', two=1)) + assert_identical(mdata.sel(x={'one': 'a', 'two': 1}), + mdata.sel(one='a', two=1)) def test_virtual_default_coords(self): array = DataArray(np.zeros((5,)), dims='x') expected = DataArray(range(5), dims='x', name='x') - self.assertDataArrayIdentical(expected, array['x']) - self.assertDataArrayIdentical(expected, array.coords['x']) + assert_identical(expected, array['x']) + assert_identical(expected, array.coords['x']) def test_virtual_time_components(self): dates = pd.date_range('2000-01-01', periods=10) da = DataArray(np.arange(1, 11), [('time', dates)]) - self.assertArrayEqual(da['time.dayofyear'], da.values) - self.assertArrayEqual(da.coords['time.dayofyear'], da.values) + assert_array_equal(da['time.dayofyear'], da.values) + assert_array_equal(da.coords['time.dayofyear'], da.values) def test_coords(self): # use int64 to ensure repr() consistency on windows @@ -905,14 +1025,14 @@ def test_coords(self): assert 2 == len(da.coords) - self.assertEqual(['x', 'y'], list(da.coords)) + assert ['x', 'y'] == list(da.coords) - self.assertTrue(coords[0].identical(da.coords['x'])) - self.assertTrue(coords[1].identical(da.coords['y'])) + assert coords[0].identical(da.coords['x']) + assert coords[1].identical(da.coords['y']) - self.assertIn('x', da.coords) - self.assertNotIn(0, da.coords) - self.assertNotIn('foo', da.coords) + assert 'x' in da.coords + assert 0 not in da.coords + assert 'foo' not in da.coords with pytest.raises(KeyError): da.coords[0] @@ -929,7 +1049,7 @@ def test_coords(self): del da.coords['x'] expected = DataArray(da.values, {'y': [0, 1, 2]}, dims=['x', 'y'], name='foo') - self.assertDataArrayIdentical(da, expected) + assert_identical(da, expected) with raises_regex(ValueError, 'conflicting MultiIndex'): self.mda['level_1'] = np.arange(4) @@ -967,17 +1087,17 @@ def test_coord_coords(self): expected = DataArray([1, 2], {'z': 4, 'x2': ('x', ['a', 'b']), 'x': [1, 2]}, dims='x', name='x') - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) del actual.coords['x2'] - self.assertDataArrayIdentical( + assert_identical( expected.reset_coords('x2', drop=True), actual) actual.coords['x3'] = ('x', ['a', 'b']) expected = DataArray([1, 2], {'z': 4, 'x3': ('x', ['a', 'b']), 'x': [1, 2]}, dims='x', name='x') - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) def test_reset_coords(self): data = DataArray(np.zeros((3, 4)), @@ -992,34 +1112,34 @@ def test_reset_coords(self): 'bar': ('x', ['a', 'b', 'c']), 'baz': ('y', range(4)), 'y': range(4)}) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) actual = data.reset_coords(['bar', 'baz']) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) actual = data.reset_coords('bar') expected = Dataset({'foo': (['x', 'y'], np.zeros((3, 4))), 'bar': ('x', ['a', 'b', 'c'])}, {'baz': ('y', range(4)), 'y': range(4)}) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) actual = data.reset_coords(['bar']) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) actual = data.reset_coords(drop=True) expected = DataArray(np.zeros((3, 4)), coords={'y': range(4)}, dims=['x', 'y'], name='foo') - self.assertDataArrayIdentical(actual, expected) + assert_identical(actual, expected) actual = data.copy() actual.reset_coords(drop=True, inplace=True) - self.assertDataArrayIdentical(actual, expected) + assert_identical(actual, expected) actual = data.reset_coords('bar', drop=True) expected = DataArray(np.zeros((3, 4)), {'baz': ('y', range(4)), 'y': range(4)}, dims=['x', 'y'], name='foo') - self.assertDataArrayIdentical(actual, expected) + assert_identical(actual, expected) with raises_regex(ValueError, 'cannot reset coord'): data.reset_coords(inplace=True) @@ -1034,13 +1154,13 @@ def test_assign_coords(self): array = DataArray(10) actual = array.assign_coords(c=42) expected = DataArray(10, {'c': 42}) - self.assertDataArrayIdentical(actual, expected) + assert_identical(actual, expected) array = DataArray([1, 2, 3, 4], {'c': ('x', [0, 0, 1, 1])}, dims='x') actual = array.groupby('c').assign_coords(d=lambda a: a.mean()) expected = array.copy() expected.coords['d'] = ('x', [1.5, 1.5, 3.5, 3.5]) - self.assertDataArrayIdentical(actual, expected) + assert_identical(actual, expected) with raises_regex(ValueError, 'conflicting MultiIndex'): self.mda.assign_coords(level_1=range(4)) @@ -1054,7 +1174,7 @@ def test_coords_alignment(self): coords={'rhs': ('x', [np.nan, 2, 3]), 'x': [0, 1, 2]}, dims='x') - self.assertDataArrayIdentical(lhs, expected) + assert_identical(lhs, expected) def test_coords_replacement_alignment(self): # regression test for GH725 @@ -1062,28 +1182,28 @@ def test_coords_replacement_alignment(self): new_coord = DataArray([1, 2, 3], dims=['abc'], coords=[[1, 2, 3]]) arr['abc'] = new_coord expected = DataArray([0, 1, 2], coords=[('abc', [1, 2, 3])]) - self.assertDataArrayIdentical(arr, expected) + assert_identical(arr, expected) def test_coords_non_string(self): arr = DataArray(0, coords={1: 2}) actual = arr.coords[1] expected = DataArray(2, coords={1: 2}, name=1) - self.assertDataArrayIdentical(actual, expected) + assert_identical(actual, expected) def test_reindex_like(self): foo = DataArray(np.random.randn(5, 6), [('x', range(5)), ('y', range(6))]) bar = foo[:2, :2] - self.assertDataArrayIdentical(foo.reindex_like(bar), bar) + assert_identical(foo.reindex_like(bar), bar) expected = foo.copy() expected[:] = np.nan expected[:2, :2] = bar - self.assertDataArrayIdentical(bar.reindex_like(foo), expected) + assert_identical(bar.reindex_like(foo), expected) def test_reindex_like_no_index(self): foo = DataArray(np.random.randn(5, 6), dims=['x', 'y']) - self.assertDatasetIdentical(foo, foo.reindex_like(foo)) + assert_identical(foo, foo.reindex_like(foo)) bar = foo[:4] with raises_regex( @@ -1095,44 +1215,44 @@ def test_reindex_regressions(self): expected = DataArray(np.random.randn(5), coords=[("time", range(5))]) time2 = DataArray(np.arange(5), dims="time2") actual = expected.reindex(time=time2) - self.assertDataArrayIdentical(actual, expected) + assert_identical(actual, expected) # regression test for #736, reindex can not change complex nums dtype x = np.array([1, 2, 3], dtype=np.complex) x = DataArray(x, coords=[[0.1, 0.2, 0.3]]) y = DataArray([2, 5, 6, 7, 8], coords=[[-1.1, 0.21, 0.31, 0.41, 0.51]]) re_dtype = x.reindex_like(y, method='pad').dtype - self.assertEqual(x.dtype, re_dtype) + assert x.dtype == re_dtype def test_reindex_method(self): x = DataArray([10, 20], dims='y', coords={'y': [0, 1]}) y = [-0.1, 0.5, 1.1] actual = x.reindex(y=y, method='backfill', tolerance=0.2) expected = DataArray([10, np.nan, np.nan], coords=[('y', y)]) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) alt = Dataset({'y': y}) actual = x.reindex_like(alt, method='backfill') expected = DataArray([10, 20, np.nan], coords=[('y', y)]) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_rename(self): renamed = self.dv.rename('bar') - self.assertDatasetIdentical( + assert_identical( renamed.to_dataset(), self.ds.rename({'foo': 'bar'})) - self.assertEqual(renamed.name, 'bar') + assert renamed.name == 'bar' renamed = self.dv.x.rename({'x': 'z'}).rename('z') - self.assertDatasetIdentical( + assert_identical( renamed, self.ds.rename({'x': 'z'}).z) - self.assertEqual(renamed.name, 'z') - self.assertEqual(renamed.dims, ('z',)) + assert renamed.name == 'z' + assert renamed.dims == ('z',) def test_swap_dims(self): array = DataArray(np.random.randn(3), {'y': ('x', list('abc'))}, 'x') expected = DataArray(array.values, {'y': list('abc')}, dims='y') actual = array.swap_dims({'x': 'y'}) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) def test_expand_dims_error(self): array = DataArray(np.random.randn(3, 4), dims=['x', 'dim_0'], @@ -1174,9 +1294,9 @@ def test_expand_dims(self): dims=['y', 'x', 'dim_0'], coords={'x': np.linspace(0.0, 1.0, 3)}, attrs={'key': 'entry'}) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) roundtripped = actual.squeeze('y', drop=True) - self.assertDatasetIdentical(array, roundtripped) + assert_identical(array, roundtripped) # pass multiple dims actual = array.expand_dims(dim=['y', 'z']) @@ -1185,9 +1305,9 @@ def test_expand_dims(self): dims=['y', 'z', 'x', 'dim_0'], coords={'x': np.linspace(0.0, 1.0, 3)}, attrs={'key': 'entry'}) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) roundtripped = actual.squeeze(['y', 'z'], drop=True) - self.assertDatasetIdentical(array, roundtripped) + assert_identical(array, roundtripped) # pass multiple dims and axis. Axis is out of order actual = array.expand_dims(dim=['z', 'y'], axis=[2, 1]) @@ -1196,11 +1316,11 @@ def test_expand_dims(self): dims=['x', 'y', 'z', 'dim_0'], coords={'x': np.linspace(0.0, 1.0, 3)}, attrs={'key': 'entry'}) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) # make sure the attrs are tracked - self.assertTrue(actual.attrs['key'] == 'entry') + assert actual.attrs['key'] == 'entry' roundtripped = actual.squeeze(['z', 'y'], drop=True) - self.assertDatasetIdentical(array, roundtripped) + assert_identical(array, roundtripped) # Negative axis and they are out of order actual = array.expand_dims(dim=['y', 'z'], axis=[-1, -2]) @@ -1209,10 +1329,10 @@ def test_expand_dims(self): dims=['x', 'dim_0', 'z', 'y'], coords={'x': np.linspace(0.0, 1.0, 3)}, attrs={'key': 'entry'}) - self.assertDataArrayIdentical(expected, actual) - self.assertTrue(actual.attrs['key'] == 'entry') + assert_identical(expected, actual) + assert actual.attrs['key'] == 'entry' roundtripped = actual.squeeze(['y', 'z'], drop=True) - self.assertDatasetIdentical(array, roundtripped) + assert_identical(array, roundtripped) def test_expand_dims_with_scalar_coordinate(self): array = DataArray(np.random.randn(3, 4), dims=['x', 'dim_0'], @@ -1224,9 +1344,9 @@ def test_expand_dims_with_scalar_coordinate(self): coords={'x': np.linspace(0.0, 1.0, 3), 'z': np.ones(1)}, attrs={'key': 'entry'}) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) roundtripped = actual.squeeze(['z'], drop=False) - self.assertDatasetIdentical(array, roundtripped) + assert_identical(array, roundtripped) def test_set_index(self): indexes = [self.mindex.get_level_values(n) for n in self.mindex.names] @@ -1238,14 +1358,14 @@ def test_set_index(self): expected['level_3'] = level_3 obj = array.set_index(x=self.mindex.names) - self.assertDataArrayIdentical(obj, expected) + assert_identical(obj, expected) obj = obj.set_index(x='level_3', append=True) expected = array.set_index(x=['level_1', 'level_2', 'level_3']) - self.assertDataArrayIdentical(obj, expected) + assert_identical(obj, expected) array.set_index(x=['level_1', 'level_2', 'level_3'], inplace=True) - self.assertDataArrayIdentical(array, expected) + assert_identical(array, expected) array2d = DataArray(np.random.rand(2, 2), coords={'x': ('x', [0, 1]), @@ -1260,42 +1380,42 @@ def test_reset_index(self): expected = DataArray(self.mda.values, coords=coords, dims='x') obj = self.mda.reset_index('x') - self.assertDataArrayIdentical(obj, expected) + assert_identical(obj, expected) obj = self.mda.reset_index(self.mindex.names) - self.assertDataArrayIdentical(obj, expected) + assert_identical(obj, expected) obj = self.mda.reset_index(['x', 'level_1']) - self.assertDataArrayIdentical(obj, expected) + assert_identical(obj, expected) coords = {'x': ('x', self.mindex.droplevel('level_1')), 'level_1': ('x', self.mindex.get_level_values('level_1'))} expected = DataArray(self.mda.values, coords=coords, dims='x') obj = self.mda.reset_index(['level_1']) - self.assertDataArrayIdentical(obj, expected) + assert_identical(obj, expected) expected = DataArray(self.mda.values, dims='x') obj = self.mda.reset_index('x', drop=True) - self.assertDataArrayIdentical(obj, expected) + assert_identical(obj, expected) array = self.mda.copy() array.reset_index(['x'], drop=True, inplace=True) - self.assertDataArrayIdentical(array, expected) + assert_identical(array, expected) # single index array = DataArray([1, 2], coords={'x': ['a', 'b']}, dims='x') expected = DataArray([1, 2], coords={'x_': ('x', ['a', 'b'])}, dims='x') - self.assertDataArrayIdentical(array.reset_index('x'), expected) + assert_identical(array.reset_index('x'), expected) def test_reorder_levels(self): midx = self.mindex.reorder_levels(['level_2', 'level_1']) expected = DataArray(self.mda.values, coords={'x': midx}, dims='x') obj = self.mda.reorder_levels(x=['level_2', 'level_1']) - self.assertDataArrayIdentical(obj, expected) + assert_identical(obj, expected) array = self.mda.copy() array.reorder_levels(x=['level_2', 'level_1'], inplace=True) - self.assertDataArrayIdentical(array, expected) + assert_identical(array, expected) array = DataArray([1, 2], dims='x') with pytest.raises(KeyError): @@ -1307,21 +1427,21 @@ def test_reorder_levels(self): def test_dataset_getitem(self): dv = self.ds['foo'] - self.assertDataArrayIdentical(dv, self.dv) + assert_identical(dv, self.dv) def test_array_interface(self): - self.assertArrayEqual(np.asarray(self.dv), self.x) + assert_array_equal(np.asarray(self.dv), self.x) # test patched in methods - self.assertArrayEqual(self.dv.astype(float), self.v.astype(float)) + assert_array_equal(self.dv.astype(float), self.v.astype(float)) assert_array_equal(self.dv.argsort(), self.v.argsort()) assert_array_equal(self.dv.clip(2, 3), self.v.clip(2, 3)) # test ufuncs expected = deepcopy(self.ds) expected['foo'][:] = np.sin(self.x) - self.assertDataArrayEqual(expected['foo'], np.sin(self.dv)) + assert_equal(expected['foo'], np.sin(self.dv)) assert_array_equal(self.dv, np.maximum(self.v, self.dv)) bar = Variable(['x', 'y'], np.zeros((10, 20))) - self.assertDataArrayEqual(self.dv, np.maximum(self.dv, bar)) + assert_equal(self.dv, np.maximum(self.dv, bar)) def test_is_null(self): x = np.random.RandomState(42).randn(5, 6) @@ -1329,8 +1449,8 @@ def test_is_null(self): original = DataArray(x, [-np.arange(5), np.arange(6)], ['x', 'y']) expected = DataArray(pd.isnull(x), [-np.arange(5), np.arange(6)], ['x', 'y']) - self.assertDataArrayIdentical(expected, original.isnull()) - self.assertDataArrayIdentical(~expected, original.notnull()) + assert_identical(expected, original.isnull()) + assert_identical(~expected, original.notnull()) def test_math(self): x = self.x @@ -1338,33 +1458,33 @@ def test_math(self): a = self.dv # variable math was already tested extensively, so let's just make sure # that all types are properly converted here - self.assertDataArrayEqual(a, +a) - self.assertDataArrayEqual(a, a + 0) - self.assertDataArrayEqual(a, 0 + a) - self.assertDataArrayEqual(a, a + 0 * v) - self.assertDataArrayEqual(a, 0 * v + a) - self.assertDataArrayEqual(a, a + 0 * x) - self.assertDataArrayEqual(a, 0 * x + a) - self.assertDataArrayEqual(a, a + 0 * a) - self.assertDataArrayEqual(a, 0 * a + a) + assert_equal(a, +a) + assert_equal(a, a + 0) + assert_equal(a, 0 + a) + assert_equal(a, a + 0 * v) + assert_equal(a, 0 * v + a) + assert_equal(a, a + 0 * x) + assert_equal(a, 0 * x + a) + assert_equal(a, a + 0 * a) + assert_equal(a, 0 * a + a) def test_math_automatic_alignment(self): a = DataArray(range(5), [('x', range(5))]) b = DataArray(range(5), [('x', range(1, 6))]) expected = DataArray(np.ones(4), [('x', [1, 2, 3, 4])]) - self.assertDataArrayIdentical(a - b, expected) + assert_identical(a - b, expected) def test_non_overlapping_dataarrays_return_empty_result(self): a = DataArray(range(5), [('x', range(5))]) result = a.isel(x=slice(2)) + a.isel(x=slice(2, None)) - self.assertEqual(len(result['x']), 0) + assert len(result['x']) == 0 def test_empty_dataarrays_return_empty_result(self): a = DataArray(data=[]) result = a * a - self.assertEqual(len(result['dim_0']), 0) + assert len(result['dim_0']) == 0 def test_inplace_math_basics(self): x = self.x @@ -1372,10 +1492,10 @@ def test_inplace_math_basics(self): v = a.variable b = a b += 1 - self.assertIs(b, a) - self.assertIs(b.variable, v) - self.assertArrayEqual(b.values, x) - self.assertIs(source_ndarray(b.values), x) + assert b is a + assert b.variable is v + assert_array_equal(b.values, x) + assert source_ndarray(b.values) is x def test_inplace_math_automatic_alignment(self): a = DataArray(range(5), [('x', range(5))]) @@ -1391,14 +1511,14 @@ def test_math_name(self): # the other object has the same name or no name attribute and this # object isn't a coordinate; otherwise reset to None. a = self.dv - self.assertEqual((+a).name, 'foo') - self.assertEqual((a + 0).name, 'foo') - self.assertIs((a + a.rename(None)).name, None) - self.assertIs((a + a.rename('bar')).name, None) - self.assertEqual((a + a).name, 'foo') - self.assertIs((+a['x']).name, 'x') - self.assertIs((a['x'] + 0).name, 'x') - self.assertIs((a + a['x']).name, None) + assert (+a).name == 'foo' + assert (a + 0).name == 'foo' + assert (a + a.rename(None)).name is None + assert (a + a.rename('bar')).name is None + assert (a + a).name == 'foo' + assert (+a['x']).name is 'x' + assert (a['x'] + 0).name is 'x' + assert (a + a['x']).name is None def test_math_with_coords(self): coords = {'x': [-1, -2], 'y': ['ab', 'cd', 'ef'], @@ -1408,63 +1528,63 @@ def test_math_with_coords(self): actual = orig + 1 expected = DataArray(orig.values + 1, orig.coords) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = 1 + orig - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = orig + orig[0, 0] exp_coords = dict((k, v) for k, v in coords.items() if k != 'lat') expected = DataArray(orig.values + orig.values[0, 0], exp_coords, dims=['x', 'y']) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = orig[0, 0] + orig - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = orig[0, 0] + orig[-1, -1] expected = DataArray(orig.values[0, 0] + orig.values[-1, -1], {'c': -999}) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = orig[:, 0] + orig[0, :] exp_values = orig[:, 0].values[:, None] + orig[0, :].values[None, :] expected = DataArray(exp_values, exp_coords, dims=['x', 'y']) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = orig[0, :] + orig[:, 0] - self.assertDataArrayIdentical(expected.T, actual) + assert_identical(expected.T, actual) actual = orig - orig.T expected = DataArray(np.zeros((2, 3)), orig.coords) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = orig.T - orig - self.assertDataArrayIdentical(expected.T, actual) + assert_identical(expected.T, actual) alt = DataArray([1, 1], {'x': [-1, -2], 'c': 'foo', 'd': 555}, 'x') actual = orig + alt expected = orig + 1 expected.coords['d'] = 555 del expected.coords['c'] - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = alt + orig - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) def test_index_math(self): orig = DataArray(range(3), dims='x', name='x') actual = orig + 1 expected = DataArray(1 + np.arange(3), dims='x', name='x') - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) # regression tests for #254 actual = orig[0] < orig expected = DataArray([False, True, True], dims='x', name='x') - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = orig > orig[0] - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) def test_dataset_math(self): # more comprehensive tests with multiple dataset variables @@ -1475,11 +1595,11 @@ def test_dataset_math(self): actual = 2 * obs['tmax'] expected = DataArray(2 * (10 + np.arange(5)), obs.coords, name='tmax') - self.assertDataArrayIdentical(actual, expected) + assert_identical(actual, expected) actual = obs['tmax'] - obs['tmin'] expected = DataArray(10 * np.ones(5), obs.coords) - self.assertDataArrayIdentical(actual, expected) + assert_identical(actual, expected) sim = Dataset({'tmin': ('x', 1 + np.arange(5)), 'tmax': ('x', 11 + np.arange(5)), @@ -1488,30 +1608,30 @@ def test_dataset_math(self): actual = sim['tmin'] - obs['tmin'] expected = DataArray(np.ones(5), obs.coords, name='tmin') - self.assertDataArrayIdentical(actual, expected) + assert_identical(actual, expected) actual = -obs['tmin'] + sim['tmin'] - self.assertDataArrayIdentical(actual, expected) + assert_identical(actual, expected) actual = sim['tmin'].copy() actual -= obs['tmin'] - self.assertDataArrayIdentical(actual, expected) + assert_identical(actual, expected) actual = sim.copy() actual['tmin'] = sim['tmin'] - obs['tmin'] expected = Dataset({'tmin': ('x', np.ones(5)), 'tmax': ('x', sim['tmax'].values)}, obs.coords) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) actual = sim.copy() actual['tmin'] -= obs['tmin'] - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) def test_stack_unstack(self): orig = DataArray([[0, 1], [2, 3]], dims=['x', 'y'], attrs={'foo': 2}) actual = orig.stack(z=['x', 'y']).unstack('z').drop(['x', 'y']) - self.assertDataArrayIdentical(orig, actual) + assert_identical(orig, actual) def test_stack_unstack_decreasing_coordinate(self): # regression test for GH980 @@ -1520,7 +1640,7 @@ def test_stack_unstack_decreasing_coordinate(self): 'y': np.arange(3, 0, -1)}) stacked = orig.stack(allpoints=['y', 'x']) actual = stacked.unstack('allpoints') - self.assertDataArrayIdentical(orig, actual) + assert_identical(orig, actual) def test_unstack_pandas_consistency(self): df = pd.DataFrame({'foo': range(3), @@ -1529,11 +1649,11 @@ def test_unstack_pandas_consistency(self): s = df.set_index(['x', 'y'])['foo'] expected = DataArray(s.unstack(), name='foo') actual = DataArray(s, dims='z').unstack('z') - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) def test_transpose(self): - self.assertVariableEqual(self.dv.variable.transpose(), - self.dv.transpose().variable) + assert_equal(self.dv.variable.transpose(), + self.dv.transpose().variable) def test_squeeze(self): assert_equal(self.dv.variable.squeeze(), self.dv.squeeze().variable) @@ -1542,18 +1662,18 @@ def test_squeeze_drop(self): array = DataArray([1], [('x', [0])]) expected = DataArray(1) actual = array.squeeze(drop=True) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) expected = DataArray(1, {'x': 0}) actual = array.squeeze(drop=False) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) def test_drop_coordinates(self): expected = DataArray(np.random.randn(2, 3), dims=['x', 'y']) arr = expected.copy() arr.coords['z'] = 2 actual = arr.drop('z') - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) with pytest.raises(ValueError): arr.drop('not found') @@ -1570,7 +1690,7 @@ def test_drop_index_labels(self): dims=['x', 'y']) actual = arr.drop([0, 1], dim='y') expected = arr[:, 2:] - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) def test_dropna(self): x = np.random.randn(4, 4) @@ -1579,23 +1699,23 @@ def test_dropna(self): actual = arr.dropna('a') expected = arr[1::2] - self.assertDataArrayIdentical(actual, expected) + assert_identical(actual, expected) actual = arr.dropna('b', how='all') - self.assertDataArrayIdentical(actual, arr) + assert_identical(actual, arr) actual = arr.dropna('a', thresh=1) - self.assertDataArrayIdentical(actual, arr) + assert_identical(actual, arr) actual = arr.dropna('b', thresh=3) expected = arr[:, 1:] - self.assertDataArrayIdentical(actual, expected) + assert_identical(actual, expected) def test_where(self): arr = DataArray(np.arange(4), dims='x') expected = arr.sel(x=slice(2)) actual = arr.where(arr.x < 2, drop=True) - self.assertDataArrayIdentical(actual, expected) + assert_identical(actual, expected) def test_cumops(self): coords = {'x': [-1, -2], 'y': ['ab', 'cd', 'ef'], @@ -1607,21 +1727,21 @@ def test_cumops(self): actual = orig.cumsum('x') expected = DataArray([[-1, 0, 1], [-4, 0, 4]], coords, dims=['x', 'y']) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = orig.cumsum('y') expected = DataArray([[-1, -1, 0], [-3, -3, 0]], coords, dims=['x', 'y']) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = orig.cumprod('x') expected = DataArray([[-1, 0, 1], [3, 0, 3]], coords, dims=['x', 'y']) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = orig.cumprod('y') expected = DataArray([[-1, 0, 0], [-3, 0, 0]], coords, dims=['x', 'y']) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) def test_reduce(self): coords = {'x': [-1, -2], 'y': ['ab', 'cd', 'ef'], @@ -1631,29 +1751,29 @@ def test_reduce(self): actual = orig.mean() expected = DataArray(0, {'c': -999}) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = orig.mean(['x', 'y']) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = orig.mean('x') expected = DataArray([-2, 0, 2], {'y': coords['y'], 'c': -999}, 'y') - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = orig.mean(['x']) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = orig.mean('y') expected = DataArray([0, 0], {'x': coords['x'], 'c': -999}, 'x') - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) - self.assertVariableEqual(self.dv.reduce(np.mean, 'x').variable, - self.v.reduce(np.mean, 'x')) + assert_equal(self.dv.reduce(np.mean, 'x').variable, + self.v.reduce(np.mean, 'x')) orig = DataArray([[1, 0, np.nan], [3, 0, 3]], coords, dims=['x', 'y']) actual = orig.count() expected = DataArray(5, {'c': -999}) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) # uint support orig = DataArray(np.arange(6).reshape(3, 2).astype('uint'), @@ -1662,7 +1782,25 @@ def test_reduce(self): actual = orig.mean(dim='x', skipna=True) expected = DataArray(orig.values.astype(int), dims=['x', 'y']).mean('x') - self.assertDataArrayEqual(actual, expected) + assert_equal(actual, expected) + + def test_reduce_dtype(self): + coords = {'x': [-1, -2], 'y': ['ab', 'cd', 'ef'], + 'lat': (['x', 'y'], [[1, 2, 3], [-1, -2, -3]]), + 'c': -999} + orig = DataArray([[-1, 0, 1], [-3, 0, 3]], coords, dims=['x', 'y']) + + for dtype in [np.float16, np.float32, np.float64]: + assert orig.astype(float).mean(dtype=dtype).dtype == dtype + + def test_reduce_out(self): + coords = {'x': [-1, -2], 'y': ['ab', 'cd', 'ef'], + 'lat': (['x', 'y'], [[1, 2, 3], [-1, -2, -3]]), + 'c': -999} + orig = DataArray([[-1, 0, 1], [-3, 0, 3]], coords, dims=['x', 'y']) + + with pytest.raises(TypeError): + orig.mean(out=np.ones(orig.shape)) # skip due to bug in older versions of numpy.nanpercentile def test_quantile(self): @@ -1677,13 +1815,13 @@ def test_quantile(self): def test_reduce_keep_attrs(self): # Test dropped attrs vm = self.va.mean() - self.assertEqual(len(vm.attrs), 0) - self.assertEqual(vm.attrs, OrderedDict()) + assert len(vm.attrs) == 0 + assert vm.attrs == OrderedDict() # Test kept attrs vm = self.va.mean(keep_attrs=True) - self.assertEqual(len(vm.attrs), len(self.attrs)) - self.assertEqual(vm.attrs, self.attrs) + assert len(vm.attrs) == len(self.attrs) + assert vm.attrs == self.attrs def test_assign_attrs(self): expected = DataArray([], attrs=dict(a=1, b=2)) @@ -1691,33 +1829,33 @@ def test_assign_attrs(self): expected.attrs['b'] = 2 new = DataArray([]) actual = DataArray([]).assign_attrs(a=1, b=2) - self.assertDatasetIdentical(actual, expected) - self.assertEqual(new.attrs, {}) + assert_identical(actual, expected) + assert new.attrs == {} expected.attrs['c'] = 3 new_actual = actual.assign_attrs({'c': 3}) - self.assertDatasetIdentical(new_actual, expected) - self.assertEqual(actual.attrs, {'a': 1, 'b': 2}) + assert_identical(new_actual, expected) + assert actual.attrs == {'a': 1, 'b': 2} def test_fillna(self): a = DataArray([np.nan, 1, np.nan, 3], coords={'x': range(4)}, dims='x') actual = a.fillna(-1) expected = DataArray([-1, 1, -1, 3], coords={'x': range(4)}, dims='x') - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) b = DataArray(range(4), coords={'x': range(4)}, dims='x') actual = a.fillna(b) expected = b.copy() - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = a.fillna(range(4)) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = a.fillna(b[:3]) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = a.fillna(b[:0]) - self.assertDataArrayIdentical(a, actual) + assert_identical(a, actual) with raises_regex(TypeError, 'fillna on a DataArray'): a.fillna({0: 0}) @@ -1729,21 +1867,21 @@ def test_fillna(self): actual = a.fillna(fill_value) expected = DataArray([[0, 1], [1, 1], [0, 1], [3, 3]], coords={'x': range(4)}, dims=('x', 'y')) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) expected = b.copy() for target in [a, expected]: target.coords['b'] = ('x', [0, 0, 1, 1]) actual = a.groupby('b').fillna(DataArray([0, 2], dims='b')) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) def test_groupby_iter(self): for ((act_x, act_dv), (exp_x, exp_ds)) in \ zip(self.dv.groupby('y'), self.ds.groupby('y')): - self.assertEqual(exp_x, act_x) - self.assertDataArrayIdentical(exp_ds['foo'], act_dv) + assert exp_x == act_x + assert_identical(exp_ds['foo'], act_dv) for ((_, exp_dv), act_dv) in zip(self.dv.groupby('x'), self.dv): - self.assertDataArrayIdentical(exp_dv, act_dv) + assert_identical(exp_dv, act_dv) def make_groupby_example_array(self): da = self.dv.copy() @@ -1754,10 +1892,10 @@ def make_groupby_example_array(self): def test_groupby_properties(self): grouped = self.make_groupby_example_array().groupby('abc') expected_groups = {'a': range(0, 9), 'c': [9], 'b': range(10, 20)} - self.assertItemsEqual(expected_groups.keys(), grouped.groups.keys()) + assert expected_groups.keys() == grouped.groups.keys() for key in expected_groups: - self.assertArrayEqual(expected_groups[key], grouped.groups[key]) - self.assertEqual(3, len(grouped)) + assert_array_equal(expected_groups[key], grouped.groups[key]) + assert 3 == len(grouped) def test_groupby_apply_identity(self): expected = self.make_groupby_example_array() @@ -1771,7 +1909,7 @@ def identity(x): for squeeze in [False, True]: grouped = expected.groupby(g, squeeze=squeeze) actual = grouped.apply(identity, shortcut=shortcut) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) def test_groupby_sum(self): array = self.make_groupby_example_array() @@ -1782,25 +1920,24 @@ def test_groupby_sum(self): self.x[:, 10:].sum(), self.x[:, 9:10].sum()]).T), 'abc': Variable(['abc'], np.array(['a', 'b', 'c']))})['foo'] - self.assertDataArrayAllClose(expected_sum_all, grouped.reduce(np.sum)) - self.assertDataArrayAllClose(expected_sum_all, grouped.sum()) + assert_allclose(expected_sum_all, grouped.reduce(np.sum)) + assert_allclose(expected_sum_all, grouped.sum()) expected = DataArray([array['y'].values[idx].sum() for idx in [slice(9), slice(10, None), slice(9, 10)]], [['a', 'b', 'c']], ['abc']) actual = array['y'].groupby('abc').apply(np.sum) - self.assertDataArrayAllClose(expected, actual) + assert_allclose(expected, actual) actual = array['y'].groupby('abc').sum() - self.assertDataArrayAllClose(expected, actual) + assert_allclose(expected, actual) expected_sum_axis1 = Dataset( {'foo': (['x', 'abc'], np.array([self.x[:, :9].sum(1), self.x[:, 10:].sum(1), self.x[:, 9:10].sum(1)]).T), 'abc': Variable(['abc'], np.array(['a', 'b', 'c']))})['foo'] - self.assertDataArrayAllClose(expected_sum_axis1, - grouped.reduce(np.sum, 'y')) - self.assertDataArrayAllClose(expected_sum_axis1, grouped.sum('y')) + assert_allclose(expected_sum_axis1, grouped.reduce(np.sum, 'y')) + assert_allclose(expected_sum_axis1, grouped.sum('y')) def test_groupby_count(self): array = DataArray( @@ -1809,7 +1946,7 @@ def test_groupby_count(self): dims='x') actual = array.groupby('cat').count() expected = DataArray([1, 1, 2], coords=[('cat', ['a', 'b', 'c'])]) - self.assertDataArrayIdentical(actual, expected) + assert_identical(actual, expected) @unittest.skip('needs to be fixed for shortcut=False, keep_attrs=False') def test_groupby_reduce_attrs(self): @@ -1824,7 +1961,7 @@ def test_groupby_reduce_attrs(self): expected = array.groupby('abc').mean() if keep_attrs: expected.attrs['foo'] = 'bar' - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) def test_groupby_apply_center(self): def center(x): @@ -1839,14 +1976,14 @@ def center(x): center(self.x[:, 10:])]) expected_ds['foo'] = (['x', 'y'], exp_data) expected_centered = expected_ds['foo'] - self.assertDataArrayAllClose(expected_centered, grouped.apply(center)) + assert_allclose(expected_centered, grouped.apply(center)) def test_groupby_apply_ndarray(self): # regression test for #326 array = self.make_groupby_example_array() grouped = array.groupby('abc') actual = grouped.apply(np.asarray) - self.assertDataArrayEqual(array, actual) + assert_equal(array, actual) def test_groupby_apply_changes_metadata(self): def change_metadata(x): @@ -1859,7 +1996,7 @@ def change_metadata(x): actual = grouped.apply(change_metadata) expected = array.copy() expected = change_metadata(expected) - self.assertDataArrayEqual(expected, actual) + assert_equal(expected, actual) def test_groupby_math(self): array = self.make_groupby_example_array() @@ -1868,24 +2005,24 @@ def test_groupby_math(self): expected = array + array.coords['x'] actual = grouped + array.coords['x'] - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = array.coords['x'] + grouped - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) ds = array.coords['x'].to_dataset('X') expected = array + ds actual = grouped + ds - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) actual = ds + grouped - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) grouped = array.groupby('abc') expected_agg = (grouped.mean() - np.arange(3)).rename(None) actual = grouped - DataArray(range(3), [('abc', ['a', 'b', 'c'])]) actual_agg = actual.groupby('abc').mean() - self.assertDataArrayAllClose(expected_agg, actual_agg) + assert_allclose(expected_agg, actual_agg) with raises_regex(TypeError, 'only support binary ops'): grouped + 1 @@ -1901,18 +2038,18 @@ def test_groupby_math_not_aligned(self): other = DataArray([10], coords={'b': [0]}, dims='b') actual = array.groupby('b') + other expected = DataArray([10, 11, np.nan, np.nan], array.coords) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) other = DataArray([10], coords={'c': 123, 'b': [0]}, dims='b') actual = array.groupby('b') + other expected.coords['c'] = (['x'], [123] * 2 + [np.nan] * 2) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) other = Dataset({'a': ('b', [10])}, {'b': [0]}) actual = array.groupby('b') + other expected = Dataset({'a': ('x', [10, 11, np.nan, np.nan])}, array.coords) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_groupby_restore_dim_order(self): array = DataArray(np.random.randn(5, 3), @@ -1923,7 +2060,7 @@ def test_groupby_restore_dim_order(self): ('a', ('a', 'y')), ('b', ('x', 'b'))]: result = array.groupby(by).apply(lambda x: x.squeeze()) - self.assertEqual(result.dims, expected_dims) + assert result.dims == expected_dims def test_groupby_first_and_last(self): array = DataArray([1, 2, 3, 4, 5], dims='x') @@ -1931,20 +2068,20 @@ def test_groupby_first_and_last(self): expected = DataArray([1, 3], [('ab', ['a', 'b'])]) actual = array.groupby(by).first() - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) expected = DataArray([2, 5], [('ab', ['a', 'b'])]) actual = array.groupby(by).last() - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) array = DataArray(np.random.randn(5, 3), dims=['x', 'y']) expected = DataArray(array[[0, 2]], {'ab': ['a', 'b']}, ['ab', 'y']) actual = array.groupby(by).first() - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = array.groupby('x').first() expected = array # should be a no-op - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) def make_groupby_multidim_example_array(self): return DataArray([[[0, 1], [2, 3]], [[5, 10], [15, 20]]], @@ -1959,7 +2096,7 @@ def test_groupby_multidim(self): coords=[('lon', [30., 40., 50.])])), ('lat', DataArray([16, 40], coords=[('lat', [10., 20.])]))]: actual_sum = array.groupby(dim).sum() - self.assertDataArrayIdentical(expected_sum, actual_sum) + assert_identical(expected_sum, actual_sum) def test_groupby_multidim_apply(self): array = self.make_groupby_multidim_example_array() @@ -1967,7 +2104,7 @@ def test_groupby_multidim_apply(self): expected = DataArray([[[-2.5, -6.], [-5., -8.5]], [[2.5, 3.], [8., 8.5]]], coords=array.coords, dims=array.dims) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) def test_groupby_bins(self): array = DataArray(np.arange(4), dims='dim_0') @@ -1982,9 +2119,9 @@ def test_groupby_bins(self): # the problem with this is that it overwrites the dimensions of array! # actual = array.groupby('dim_0', bins=bins).sum() actual = array.groupby_bins('dim_0', bins).apply(lambda x: x.sum()) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) # make sure original array dims are unchanged - self.assertEqual(len(array.dim_0), 4) + assert len(array.dim_0) == 4 def test_groupby_bins_empty(self): array = DataArray(np.arange(4), [('x', range(4))]) @@ -1994,10 +2131,10 @@ def test_groupby_bins_empty(self): actual = array.groupby_bins('x', bins).sum() expected = DataArray([6, np.nan], dims='x_bins', coords={'x_bins': bin_coords}) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) # make sure original array is unchanged # (was a problem in earlier versions) - self.assertEqual(len(array.x), 4) + assert len(array.x) == 4 def test_groupby_bins_multidim(self): array = self.make_groupby_multidim_example_array() @@ -2006,13 +2143,13 @@ def test_groupby_bins_multidim(self): expected = DataArray([16, 40], dims='lat_bins', coords={'lat_bins': bin_coords}) actual = array.groupby_bins('lat', bins).apply(lambda x: x.sum()) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) # modify the array coordinates to be non-monotonic after unstacking array['lat'].data = np.array([[10., 20.], [20., 10.]]) expected = DataArray([28, 28], dims='lat_bins', coords={'lat_bins': bin_coords}) actual = array.groupby_bins('lat', bins).apply(lambda x: x.sum()) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) def test_groupby_bins_sort(self): data = xr.DataArray( @@ -2027,10 +2164,10 @@ def test_resample(self): actual = array.resample(time='24H').mean() expected = DataArray(array.to_series().resample('24H').mean()) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = array.resample(time='24H').reduce(np.mean) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) with raises_regex(ValueError, 'index must be monotonic'): array[[2, 0, 1]].resample(time='1D') @@ -2041,23 +2178,23 @@ def test_resample_first(self): actual = array.resample(time='1D').first() expected = DataArray([0, 4, 8], [('time', times[::4])]) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) # verify that labels don't use the first value actual = array.resample(time='24H').first() expected = DataArray(array.to_series().resample('24H').first()) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) # missing values array = array.astype(float) array[:2] = np.nan actual = array.resample(time='1D').first() expected = DataArray([2, 4, 8], [('time', times[::4])]) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = array.resample(time='1D').first(skipna=False) expected = DataArray([np.nan, 4, 8], [('time', times[::4])]) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) # regression test for http://stackoverflow.com/questions/33158558/ array = Dataset({'time': times})['time'] @@ -2066,7 +2203,7 @@ def test_resample_first(self): '2000-01-03T06']) expected = DataArray(expected_times, [('time', times[::4])], name='time') - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) def test_resample_bad_resample_dim(self): times = pd.date_range('2000-01-01', freq='6H', periods=10) @@ -2080,7 +2217,7 @@ def test_resample_drop_nondim_coords(self): ys = np.arange(3) times = pd.date_range('2000-01-01', freq='6H', periods=5) data = np.tile(np.arange(5), (6, 3, 1)) - xx, yy = np.meshgrid(xs*5, ys*2.5) + xx, yy = np.meshgrid(xs * 5, ys * 2.5) tt = np.arange(len(times), dtype=int) array = DataArray(data, {'time': times, 'x': xs, 'y': ys}, @@ -2115,7 +2252,7 @@ def test_resample_old_vs_new_api(self): with pytest.warns(DeprecationWarning): old_mean = array.resample('1D', 'time', how='mean') new_mean = array.resample(time='1D').mean() - self.assertDataArrayIdentical(old_mean, new_mean) + assert_identical(old_mean, new_mean) # Mean, while keeping attributes attr_array = array.copy() @@ -2125,8 +2262,8 @@ def test_resample_old_vs_new_api(self): old_mean = attr_array.resample('1D', dim='time', how='mean', keep_attrs=True) new_mean = attr_array.resample(time='1D').mean(keep_attrs=True) - self.assertEqual(old_mean.attrs, new_mean.attrs) - self.assertDatasetIdentical(old_mean, new_mean) + assert old_mean.attrs == new_mean.attrs + assert_identical(old_mean, new_mean) # Mean, with NaN to skip nan_array = array.copy() @@ -2137,8 +2274,8 @@ def test_resample_old_vs_new_api(self): skipna=False) new_mean = nan_array.resample(time='1D').mean(skipna=False) expected = DataArray([np.nan, 1, 1], [('time', times[::4])]) - self.assertDataArrayIdentical(old_mean, expected) - self.assertDataArrayIdentical(new_mean, expected) + assert_identical(old_mean, expected) + assert_identical(new_mean, expected) # Try other common resampling methods resampler = array.resample(time='1D') @@ -2148,12 +2285,12 @@ def test_resample_old_vs_new_api(self): new_api = getattr(resampler, method)(keep_attrs=False) with pytest.warns(DeprecationWarning): old_api = array.resample('1D', dim='time', how=method) - self.assertDatasetIdentical(new_api, old_api) + assert_identical(new_api, old_api) for method in [np.mean, np.sum, np.max, np.min]: new_api = resampler.reduce(method) with pytest.warns(DeprecationWarning): old_api = array.resample('1D', dim='time', how=method) - self.assertDatasetIdentical(new_api, old_api) + assert_identical(new_api, old_api) def test_upsample(self): times = pd.date_range('2000-01-01', freq='6H', periods=5) @@ -2162,22 +2299,22 @@ def test_upsample(self): # Forward-fill actual = array.resample(time='3H').ffill() expected = DataArray(array.to_series().resample('3H').ffill()) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) # Backward-fill actual = array.resample(time='3H').bfill() expected = DataArray(array.to_series().resample('3H').bfill()) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) # As frequency actual = array.resample(time='3H').asfreq() expected = DataArray(array.to_series().resample('3H').asfreq()) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) # Pad actual = array.resample(time='3H').pad() expected = DataArray(array.to_series().resample('3H').pad()) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) # Nearest rs = array.resample(time='3H') @@ -2186,7 +2323,7 @@ def test_upsample(self): expected = DataArray( array.reindex(time=new_times, method='nearest') ) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) def test_upsample_nd(self): # Same as before, but now we try on multi-dimensional DataArrays. @@ -2206,7 +2343,7 @@ def test_upsample_nd(self): expected = DataArray(expected_data, {'time': expected_times, 'x': xs, 'y': ys}, ('x', 'y', 'time')) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) # Backward-fill actual = array.resample(time='3H').ffill() @@ -2217,7 +2354,7 @@ def test_upsample_nd(self): expected = DataArray(expected_data, {'time': expected_times, 'x': xs, 'y': ys}, ('x', 'y', 'time')) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) # As frequency actual = array.resample(time='3H').asfreq() @@ -2227,7 +2364,7 @@ def test_upsample_nd(self): expected = DataArray(expected_data, {'time': expected_times, 'x': xs, 'y': ys}, ('x', 'y', 'time')) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) # Pad actual = array.resample(time='3H').pad() @@ -2238,7 +2375,7 @@ def test_upsample_nd(self): expected = DataArray(expected_data, {'time': expected_times, 'x': xs, 'y': ys}, ('x', 'y', 'time')) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) @requires_scipy def test_upsample_interpolate(self): @@ -2256,7 +2393,7 @@ def test_upsample_interpolate(self): expected_times = times.to_series().resample('1H').asfreq().index # Split the times into equal sub-intervals to simulate the 6 hour # to 1 hour up-sampling - new_times_idx = np.linspace(0, len(times)-1, len(times)*5) + new_times_idx = np.linspace(0, len(times) - 1, len(times) * 5) for kind in ['linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic']: actual = array.resample(time='1H').interpolate(kind) @@ -2269,7 +2406,7 @@ def test_upsample_interpolate(self): # Use AllClose because there are some small differences in how # we upsample timeseries versus the integer indexing as I've # done here due to floating point arithmetic - self.assertDataArrayAllClose(expected, actual, rtol=1e-16) + assert_allclose(expected, actual, rtol=1e-16) @requires_scipy def test_upsample_interpolate_regression_1605(self): @@ -2295,15 +2432,15 @@ def test_upsample_interpolate_dask(self): ('x', 'y', 'time')) with raises_regex(TypeError, - "dask arrays are not yet supported"): + "dask arrays are not yet supported"): array.resample(time='1H').interpolate('linear') def test_align(self): array = DataArray(np.random.random((6, 8)), coords={'x': list('abcdef')}, dims=['x', 'y']) array1, array2 = align(array, array[:5], join='inner') - self.assertDataArrayIdentical(array1, array[:5]) - self.assertDataArrayIdentical(array2, array[:5]) + assert_identical(array1, array[:5]) + assert_identical(array2, array[:5]) def test_align_dtype(self): # regression test for #264 @@ -2312,7 +2449,7 @@ def test_align_dtype(self): a = DataArray(np.random.random((30,)).astype(np.float32), [('x', x1)]) b = DataArray(np.random.random((30,)).astype(np.float32), [('x', x2)]) c, d = align(a, b, join='outer') - self.assertEqual(c.dtype, np.float32) + assert c.dtype == np.float32 def test_align_copy(self): x = DataArray([1, 2, 3], coords=[('a', [1, 2, 3])]) @@ -2322,23 +2459,23 @@ def test_align_copy(self): expected_y2 = DataArray([2, np.nan, 1], coords=[('a', [1, 2, 3])]) x2, y2 = align(x, y, join='outer', copy=False) - self.assertDataArrayIdentical(expected_x2, x2) - self.assertDataArrayIdentical(expected_y2, y2) + assert_identical(expected_x2, x2) + assert_identical(expected_y2, y2) assert source_ndarray(x2.data) is source_ndarray(x.data) x2, y2 = align(x, y, join='outer', copy=True) - self.assertDataArrayIdentical(expected_x2, x2) - self.assertDataArrayIdentical(expected_y2, y2) + assert_identical(expected_x2, x2) + assert_identical(expected_y2, y2) assert source_ndarray(x2.data) is not source_ndarray(x.data) # Trivial align - 1 element x = DataArray([1, 2, 3], coords=[('a', [1, 2, 3])]) x2, = align(x, copy=False) - self.assertDataArrayIdentical(x, x2) + assert_identical(x, x2) assert source_ndarray(x2.data) is source_ndarray(x.data) x2, = align(x, copy=True) - self.assertDataArrayIdentical(x, x2) + assert_identical(x, x2) assert source_ndarray(x2.data) is not source_ndarray(x.data) def test_align_exclude(self): @@ -2355,9 +2492,9 @@ def test_align_exclude(self): coords=[('a', [-2, -1, 20]), ('b', [5, 6])]) expected_z2 = DataArray([np.nan, np.nan, 1], dims=['a'], coords={'a': [-2, -1, 20], 'b': 7}) - self.assertDataArrayIdentical(expected_x2, x2) - self.assertDataArrayIdentical(expected_y2, y2) - self.assertDataArrayIdentical(expected_z2, z2) + assert_identical(expected_x2, x2) + assert_identical(expected_y2, y2) + assert_identical(expected_z2, z2) def test_align_indexes(self): x = DataArray([1, 2, 3], coords=[('a', [-1, 10, -2])]) @@ -2366,32 +2503,32 @@ def test_align_indexes(self): x2, y2 = align(x, y, join='outer', indexes={'a': [10, -1, -2]}) expected_x2 = DataArray([2, 1, 3], coords=[('a', [10, -1, -2])]) expected_y2 = DataArray([np.nan, 2, 1], coords=[('a', [10, -1, -2])]) - self.assertDataArrayIdentical(expected_x2, x2) - self.assertDataArrayIdentical(expected_y2, y2) + assert_identical(expected_x2, x2) + assert_identical(expected_y2, y2) x2, = align(x, join='outer', indexes={'a': [-2, 7, 10, -1]}) expected_x2 = DataArray([3, np.nan, 2, 1], coords=[('a', [-2, 7, 10, -1])]) - self.assertDataArrayIdentical(expected_x2, x2) + assert_identical(expected_x2, x2) def test_align_without_indexes_exclude(self): arrays = [DataArray([1, 2, 3], dims=['x']), DataArray([1, 2], dims=['x'])] result0, result1 = align(*arrays, exclude=['x']) - self.assertDatasetIdentical(result0, arrays[0]) - self.assertDatasetIdentical(result1, arrays[1]) + assert_identical(result0, arrays[0]) + assert_identical(result1, arrays[1]) def test_align_mixed_indexes(self): array_no_coord = DataArray([1, 2], dims=['x']) array_with_coord = DataArray([1, 2], coords=[('x', ['a', 'b'])]) result0, result1 = align(array_no_coord, array_with_coord) - self.assertDatasetIdentical(result0, array_with_coord) - self.assertDatasetIdentical(result1, array_with_coord) + assert_identical(result0, array_with_coord) + assert_identical(result1, array_with_coord) result0, result1 = align(array_no_coord, array_with_coord, exclude=['x']) - self.assertDatasetIdentical(result0, array_no_coord) - self.assertDatasetIdentical(result1, array_with_coord) + assert_identical(result0, array_no_coord) + assert_identical(result1, array_with_coord) def test_align_without_indexes_errors(self): with raises_regex(ValueError, 'cannot be aligned'): @@ -2409,16 +2546,16 @@ def test_broadcast_arrays(self): expected_coords = [('a', [-1, -2]), ('b', [3, 4])] expected_x2 = DataArray([[1, 1], [2, 2]], expected_coords, name='x') expected_y2 = DataArray([[1, 2], [1, 2]], expected_coords, name='y') - self.assertDataArrayIdentical(expected_x2, x2) - self.assertDataArrayIdentical(expected_y2, y2) + assert_identical(expected_x2, x2) + assert_identical(expected_y2, y2) x = DataArray(np.random.randn(2, 3), dims=['a', 'b']) y = DataArray(np.random.randn(3, 2), dims=['b', 'a']) x2, y2 = broadcast(x, y) expected_x2 = x expected_y2 = y.T - self.assertDataArrayIdentical(expected_x2, x2) - self.assertDataArrayIdentical(expected_y2, y2) + assert_identical(expected_x2, x2) + assert_identical(expected_y2, y2) def test_broadcast_arrays_misaligned(self): # broadcast on misaligned coords must auto-align @@ -2430,8 +2567,8 @@ def test_broadcast_arrays_misaligned(self): expected_y2 = DataArray([[np.nan, np.nan], [1, 1], [2, 2]], coords=[('a', [-2, -1, 20]), ('b', [3, 4])]) x2, y2 = broadcast(x, y) - self.assertDataArrayIdentical(expected_x2, x2) - self.assertDataArrayIdentical(expected_y2, y2) + assert_identical(expected_x2, x2) + assert_identical(expected_y2, y2) def test_broadcast_arrays_nocopy(self): # Test that input data is not copied over in case @@ -2442,13 +2579,13 @@ def test_broadcast_arrays_nocopy(self): expected_y2 = DataArray([3, 3], coords=[('a', [-1, -2])], name='y') x2, y2 = broadcast(x, y) - self.assertDataArrayIdentical(expected_x2, x2) - self.assertDataArrayIdentical(expected_y2, y2) + assert_identical(expected_x2, x2) + assert_identical(expected_y2, y2) assert source_ndarray(x2.data) is source_ndarray(x.data) # single-element broadcast (trivial case) x2, = broadcast(x) - self.assertDataArrayIdentical(x, x2) + assert_identical(x, x2) assert source_ndarray(x2.data) is source_ndarray(x.data) def test_broadcast_arrays_exclude(self): @@ -2463,52 +2600,52 @@ def test_broadcast_arrays_exclude(self): expected_y2 = DataArray([np.nan, 1, 2], coords=[('a', [-2, -1, 20])]) expected_z2 = DataArray([5, 5, 5], dims=['a'], coords={'a': [-2, -1, 20], 'b': 5}) - self.assertDataArrayIdentical(expected_x2, x2) - self.assertDataArrayIdentical(expected_y2, y2) - self.assertDataArrayIdentical(expected_z2, z2) + assert_identical(expected_x2, x2) + assert_identical(expected_y2, y2) + assert_identical(expected_z2, z2) def test_broadcast_coordinates(self): # regression test for GH649 ds = Dataset({'a': (['x', 'y'], np.ones((5, 6)))}) x_bc, y_bc, a_bc = broadcast(ds.x, ds.y, ds.a) - self.assertDataArrayIdentical(ds.a, a_bc) + assert_identical(ds.a, a_bc) X, Y = np.meshgrid(np.arange(5), np.arange(6), indexing='ij') exp_x = DataArray(X, dims=['x', 'y'], name='x') exp_y = DataArray(Y, dims=['x', 'y'], name='y') - self.assertDataArrayIdentical(exp_x, x_bc) - self.assertDataArrayIdentical(exp_y, y_bc) + assert_identical(exp_x, x_bc) + assert_identical(exp_y, y_bc) def test_to_pandas(self): # 0d actual = DataArray(42).to_pandas() expected = np.array(42) - self.assertArrayEqual(actual, expected) + assert_array_equal(actual, expected) # 1d values = np.random.randn(3) index = pd.Index(['a', 'b', 'c'], name='x') da = DataArray(values, coords=[index]) actual = da.to_pandas() - self.assertArrayEqual(actual.values, values) - self.assertArrayEqual(actual.index, index) - self.assertArrayEqual(actual.index.name, 'x') + assert_array_equal(actual.values, values) + assert_array_equal(actual.index, index) + assert_array_equal(actual.index.name, 'x') # 2d values = np.random.randn(3, 2) da = DataArray(values, coords=[('x', ['a', 'b', 'c']), ('y', [0, 1])], name='foo') actual = da.to_pandas() - self.assertArrayEqual(actual.values, values) - self.assertArrayEqual(actual.index, ['a', 'b', 'c']) - self.assertArrayEqual(actual.columns, [0, 1]) + assert_array_equal(actual.values, values) + assert_array_equal(actual.index, ['a', 'b', 'c']) + assert_array_equal(actual.columns, [0, 1]) # roundtrips for shape in [(3,), (3, 4), (3, 4, 5)]: dims = list('abc')[:len(shape)] da = DataArray(np.random.randn(*shape), dims=dims) roundtripped = DataArray(da.to_pandas()).drop(dims) - self.assertDataArrayIdentical(da, roundtripped) + assert_identical(da, roundtripped) with raises_regex(ValueError, 'cannot convert'): DataArray(np.random.randn(1, 2, 3, 4, 5)).to_pandas() @@ -2519,9 +2656,9 @@ def test_to_dataframe(self): [('B', [1, 2, 3]), ('A', list('cdef'))], name='foo') expected = arr.to_series() actual = arr.to_dataframe()['foo'] - self.assertArrayEqual(expected.values, actual.values) - self.assertArrayEqual(expected.name, actual.name) - self.assertArrayEqual(expected.index.values, actual.index.values) + assert_array_equal(expected.values, actual.values) + assert_array_equal(expected.name, actual.name) + assert_array_equal(expected.index.values, actual.index.values) # regression test for coords with different dimensions arr.coords['C'] = ('B', [-1, -2, -3]) @@ -2529,9 +2666,9 @@ def test_to_dataframe(self): expected['C'] = [-1] * 4 + [-2] * 4 + [-3] * 4 expected = expected[['C', 'foo']] actual = arr.to_dataframe() - self.assertArrayEqual(expected.values, actual.values) - self.assertArrayEqual(expected.columns.values, actual.columns.values) - self.assertArrayEqual(expected.index.values, actual.index.values) + assert_array_equal(expected.values, actual.values) + assert_array_equal(expected.columns.values, actual.columns.values) + assert_array_equal(expected.index.values, actual.index.values) arr.name = None # unnamed with raises_regex(ValueError, 'unnamed'): @@ -2541,29 +2678,29 @@ def test_to_pandas_name_matches_coordinate(self): # coordinate with same name as array arr = DataArray([1, 2, 3], dims='x', name='x') series = arr.to_series() - self.assertArrayEqual([1, 2, 3], series.values) - self.assertArrayEqual([0, 1, 2], series.index.values) - self.assertEqual('x', series.name) - self.assertEqual('x', series.index.name) + assert_array_equal([1, 2, 3], series.values) + assert_array_equal([0, 1, 2], series.index.values) + assert 'x' == series.name + assert 'x' == series.index.name frame = arr.to_dataframe() expected = series.to_frame() - self.assertTrue(expected.equals(frame)) + assert expected.equals(frame) def test_to_and_from_series(self): expected = self.dv.to_dataframe()['foo'] actual = self.dv.to_series() - self.assertArrayEqual(expected.values, actual.values) - self.assertArrayEqual(expected.index.values, actual.index.values) - self.assertEqual('foo', actual.name) + assert_array_equal(expected.values, actual.values) + assert_array_equal(expected.index.values, actual.index.values) + assert 'foo' == actual.name # test roundtrip - self.assertDataArrayIdentical( + assert_identical( self.dv, DataArray.from_series(actual).drop(['x', 'y'])) # test name is None actual.name = None expected_da = self.dv.rename(None) - self.assertDataArrayIdentical( + assert_identical( expected_da, DataArray.from_series(actual).drop(['x', 'y'])) @@ -2589,21 +2726,21 @@ def test_to_and_from_dict(self): actual = array.to_dict() # check that they are identical - self.assertEqual(expected, actual) + assert expected == actual # check roundtrip - self.assertDataArrayIdentical(array, DataArray.from_dict(actual)) + assert_identical(array, DataArray.from_dict(actual)) # a more bare bones representation still roundtrips d = {'name': 'foo', 'dims': ('x', 'y'), 'data': array.values.tolist(), 'coords': {'x': {'dims': 'x', 'data': ['a', 'b']}}} - self.assertDataArrayIdentical(array, DataArray.from_dict(d)) + assert_identical(array, DataArray.from_dict(d)) # and the most bare bones representation still roundtrips d = {'name': 'foo', 'dims': ('x', 'y'), 'data': array.values} - self.assertDataArrayIdentical(array.drop('x'), DataArray.from_dict(d)) + assert_identical(array.drop('x'), DataArray.from_dict(d)) # missing a dims in the coords d = {'dims': ('x', 'y'), @@ -2626,7 +2763,7 @@ def test_to_and_from_dict_with_time_dim(self): lat = [77.7, 83.2, 76] da = DataArray(x, {'t': t, 'lat': lat}, dims=['t', 'lat']) roundtripped = DataArray.from_dict(da.to_dict()) - self.assertDataArrayIdentical(da, roundtripped) + assert_identical(da, roundtripped) def test_to_and_from_dict_with_nan_nat(self): y = np.random.randn(10, 3) @@ -2636,7 +2773,7 @@ def test_to_and_from_dict_with_nan_nat(self): lat = [77.7, 83.2, 76] da = DataArray(y, {'t': t, 'lat': lat}, dims=['t', 'lat']) roundtripped = DataArray.from_dict(da.to_dict()) - self.assertDataArrayIdentical(da, roundtripped) + assert_identical(da, roundtripped) def test_to_dict_with_numpy_attrs(self): # this doesn't need to roundtrip @@ -2654,7 +2791,7 @@ def test_to_dict_with_numpy_attrs(self): actual = da.to_dict() # check that they are identical - self.assertEqual(expected_attrs, actual['attrs']) + assert expected_attrs == actual['attrs'] def test_to_masked_array(self): rs = np.random.RandomState(44) @@ -2665,38 +2802,38 @@ def test_to_masked_array(self): # Test round trip x_masked_2 = da.to_masked_array() da_2 = DataArray(x_masked_2) - self.assertArrayEqual(x_masked, x_masked_2) - self.assertDataArrayEqual(da, da_2) + assert_array_equal(x_masked, x_masked_2) + assert_equal(da, da_2) da_masked_array = da.to_masked_array(copy=True) - self.assertTrue(isinstance(da_masked_array, np.ma.MaskedArray)) + assert isinstance(da_masked_array, np.ma.MaskedArray) # Test masks - self.assertArrayEqual(da_masked_array.mask, x_masked.mask) + assert_array_equal(da_masked_array.mask, x_masked.mask) # Test that mask is unpacked correctly - self.assertArrayEqual(da.values, x_masked.filled(np.nan)) + assert_array_equal(da.values, x_masked.filled(np.nan)) # Test that the underlying data (including nans) hasn't changed - self.assertArrayEqual(da_masked_array, x_masked.filled(np.nan)) + assert_array_equal(da_masked_array, x_masked.filled(np.nan)) # Test that copy=False gives access to values masked_array = da.to_masked_array(copy=False) masked_array[0, 0] = 10. - self.assertEqual(masked_array[0, 0], 10.) - self.assertEqual(da[0, 0].values, 10.) - self.assertTrue(masked_array.base is da.values) - self.assertIsInstance(masked_array, np.ma.MaskedArray) + assert masked_array[0, 0] == 10. + assert da[0, 0].values == 10. + assert masked_array.base is da.values + assert isinstance(masked_array, np.ma.MaskedArray) # Test with some odd arrays for v in [4, np.nan, True, '4', 'four']: da = DataArray(v) ma = da.to_masked_array() - self.assertIsInstance(ma, np.ma.MaskedArray) + assert isinstance(ma, np.ma.MaskedArray) # Fix GH issue 684 - masked arrays mask should be an array not a scalar N = 4 v = range(N) da = DataArray(v) ma = da.to_masked_array() - self.assertEqual(len(ma.mask), N) + assert len(ma.mask) == N def test_to_and_from_cdms2(self): pytest.importorskip('cdms2') @@ -2709,20 +2846,163 @@ def test_to_and_from_cdms2(self): expected_coords = [IndexVariable('distance', [-2, 2]), IndexVariable('time', [0, 1, 2])] actual = original.to_cdms2() - self.assertArrayEqual(actual, original) - self.assertEqual(actual.id, original.name) + assert_array_equal(actual, original) + assert actual.id == original.name self.assertItemsEqual(actual.getAxisIds(), original.dims) for axis, coord in zip(actual.getAxisList(), expected_coords): - self.assertEqual(axis.id, coord.name) - self.assertArrayEqual(axis, coord.values) - self.assertEqual(actual.baz, original.attrs['baz']) + assert axis.id == coord.name + assert_array_equal(axis, coord.values) + assert actual.baz == original.attrs['baz'] component_times = actual.getAxis(1).asComponentTime() - self.assertEqual(len(component_times), 3) - self.assertEqual(str(component_times[0]), '2000-1-1 0:0:0.0') + assert len(component_times) == 3 + assert str(component_times[0]) == '2000-1-1 0:0:0.0' roundtripped = DataArray.from_cdms2(actual) - self.assertDataArrayIdentical(original, roundtripped) + assert_identical(original, roundtripped) + + def test_to_and_from_iris(self): + try: + import iris + import cf_units + except ImportError: + raise unittest.SkipTest('iris not installed') + + coord_dict = OrderedDict() + coord_dict['distance'] = ('distance', [-2, 2], {'units': 'meters'}) + coord_dict['time'] = ('time', pd.date_range('2000-01-01', periods=3)) + coord_dict['height'] = 10 + coord_dict['distance2'] = ('distance', [0, 1], {'foo': 'bar'}) + coord_dict['time2'] = (('distance', 'time'), [[0, 1, 2], [2, 3, 4]]) + + original = DataArray(np.arange(6, dtype='float').reshape(2, 3), + coord_dict, name='Temperature', + attrs={'baz': 123, 'units': 'Kelvin', + 'standard_name': 'fire_temperature', + 'long_name': 'Fire Temperature'}, + dims=('distance', 'time')) + + # Set a bad value to test the masking logic + original.data[0, 2] = np.NaN + + original.attrs['cell_methods'] = \ + 'height: mean (comment: A cell method)' + actual = original.to_iris() + assert_array_equal(actual.data, original.data) + assert actual.var_name == original.name + self.assertItemsEqual([d.var_name for d in actual.dim_coords], + original.dims) + assert (actual.cell_methods == (iris.coords.CellMethod( + method='mean', + coords=('height', ), + intervals=(), + comments=('A cell method', )), )) + + for coord, orginal_key in zip((actual.coords()), original.coords): + original_coord = original.coords[orginal_key] + assert coord.var_name == original_coord.name + assert_array_equal( + coord.points, CFDatetimeCoder().encode(original_coord).values) + assert (actual.coord_dims(coord) == + original.get_axis_num( + original.coords[coord.var_name].dims)) + + assert (actual.coord('distance2').attributes['foo'] == + original.coords['distance2'].attrs['foo']) + assert (actual.coord('distance').units == + cf_units.Unit(original.coords['distance'].units)) + assert actual.attributes['baz'] == original.attrs['baz'] + assert actual.standard_name == original.attrs['standard_name'] + + roundtripped = DataArray.from_iris(actual) + assert_identical(original, roundtripped) + + actual.remove_coord('time') + auto_time_dimension = DataArray.from_iris(actual) + assert auto_time_dimension.dims == ('distance', 'dim_1') + + actual.coord('distance').var_name = None + with raises_regex(ValueError, 'no var_name attribute'): + DataArray.from_iris(actual) + + @requires_dask + def test_to_and_from_iris_dask(self): + import dask.array as da + try: + import iris + import cf_units + except ImportError: + raise unittest.SkipTest('iris not installed') + + coord_dict = OrderedDict() + coord_dict['distance'] = ('distance', [-2, 2], {'units': 'meters'}) + coord_dict['time'] = ('time', pd.date_range('2000-01-01', periods=3)) + coord_dict['height'] = 10 + coord_dict['distance2'] = ('distance', [0, 1], {'foo': 'bar'}) + coord_dict['time2'] = (('distance', 'time'), [[0, 1, 2], [2, 3, 4]]) + + original = DataArray( + da.from_array(np.arange(-1, 5, dtype='float').reshape(2, 3), 3), + coord_dict, + name='Temperature', + attrs=dict(baz=123, units='Kelvin', + standard_name='fire_temperature', + long_name='Fire Temperature'), + dims=('distance', 'time')) + + # Set a bad value to test the masking logic + original.data = da.ma.masked_less(original.data, 0) + + original.attrs['cell_methods'] = \ + 'height: mean (comment: A cell method)' + actual = original.to_iris() + + # Be careful not to trigger the loading of the iris data + actual_data = actual.core_data() if \ + hasattr(actual, 'core_data') else actual.data + assert_array_equal(actual_data, original.data) + assert actual.var_name == original.name + self.assertItemsEqual([d.var_name for d in actual.dim_coords], + original.dims) + assert (actual.cell_methods == (iris.coords.CellMethod( + method='mean', + coords=('height', ), + intervals=(), + comments=('A cell method', )), )) + + for coord, orginal_key in zip((actual.coords()), original.coords): + original_coord = original.coords[orginal_key] + assert coord.var_name == original_coord.name + assert_array_equal( + coord.points, CFDatetimeCoder().encode(original_coord).values) + assert (actual.coord_dims(coord) == + original.get_axis_num( + original.coords[coord.var_name].dims)) + + assert (actual.coord('distance2').attributes['foo'] == original.coords[ + 'distance2'].attrs['foo']) + assert (actual.coord('distance').units == + cf_units.Unit(original.coords['distance'].units)) + assert actual.attributes['baz'] == original.attrs['baz'] + assert actual.standard_name == original.attrs['standard_name'] + + roundtripped = DataArray.from_iris(actual) + assert_identical(original, roundtripped) + + # If the Iris version supports it then we should get a dask array back + if hasattr(actual, 'core_data'): + pass + # TODO This currently fails due to the decoding loading + # the data (#1372) + # self.assertEqual(type(original.data), type(roundtripped.data)) + + actual.remove_coord('time') + auto_time_dimension = DataArray.from_iris(actual) + assert auto_time_dimension.dims == ('distance', 'dim_1') + + actual.coord('distance').var_name = None + with raises_regex(ValueError, 'no var_name attribute'): + DataArray.from_iris(actual) def test_to_dataset_whole(self): unnamed = DataArray([1, 2], dims='x') @@ -2731,17 +3011,17 @@ def test_to_dataset_whole(self): actual = unnamed.to_dataset(name='foo') expected = Dataset({'foo': ('x', [1, 2])}) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) named = DataArray([1, 2], dims='x', name='foo') actual = named.to_dataset() expected = Dataset({'foo': ('x', [1, 2])}) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) expected = Dataset({'bar': ('x', [1, 2])}) with pytest.warns(FutureWarning): actual = named.to_dataset('bar') - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_to_dataset_split(self): array = DataArray([1, 2, 3], coords=[('x', list('abc'))], @@ -2749,18 +3029,18 @@ def test_to_dataset_split(self): expected = Dataset(OrderedDict([('a', 1), ('b', 2), ('c', 3)]), attrs={'a': 1}) actual = array.to_dataset('x') - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) with pytest.raises(TypeError): array.to_dataset('x', name='foo') roundtripped = actual.to_array(dim='x') - self.assertDataArrayIdentical(array, roundtripped) + assert_identical(array, roundtripped) array = DataArray([1, 2, 3], dims='x') expected = Dataset(OrderedDict([(0, 1), (1, 2), (2, 3)])) actual = array.to_dataset('x') - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_to_dataset_retains_keys(self): @@ -2774,18 +3054,18 @@ def test_to_dataset_retains_keys(self): # convert to dateset and back again result = array.to_dataset('x').to_array(dim='x') - self.assertDatasetEqual(array, result) + assert_equal(array, result) def test__title_for_slice(self): array = DataArray(np.ones((4, 3, 2)), dims=['a', 'b', 'c'], coords={'a': range(4), 'b': range(3), 'c': range(2)}) - self.assertEqual('', array._title_for_slice()) - self.assertEqual('c = 0', array.isel(c=0)._title_for_slice()) + assert '' == array._title_for_slice() + assert 'c = 0' == array.isel(c=0)._title_for_slice() title = array.isel(b=1, c=0)._title_for_slice() - self.assertTrue('b = 1, c = 0' == title or 'c = 0, b = 1' == title) + assert 'b = 1, c = 0' == title or 'c = 0, b = 1' == title a2 = DataArray(np.ones((4, 1)), dims=['a', 'b']) - self.assertEqual('', a2._title_for_slice()) + assert '' == a2._title_for_slice() def test__title_for_slice_truncate(self): array = DataArray(np.ones((4))) @@ -2795,14 +3075,14 @@ def test__title_for_slice_truncate(self): nchar = 80 title = array._title_for_slice(truncate=nchar) - self.assertEqual(nchar, len(title)) - self.assertTrue(title.endswith('...')) + assert nchar == len(title) + assert title.endswith('...') def test_dataarray_diff_n1(self): da = DataArray(np.random.randn(3, 4), dims=['x', 'y']) actual = da.diff('y') expected = DataArray(np.diff(da.values, axis=1), dims=['x', 'y']) - self.assertDataArrayEqual(expected, actual) + assert_equal(expected, actual) def test_coordinate_diff(self): # regression test for GH634 @@ -2811,30 +3091,30 @@ def test_coordinate_diff(self): expected = DataArray([1] * 9, dims=['lon'], coords=[range(1, 10)], name='lon') actual = lon.diff('lon') - self.assertDataArrayEqual(expected, actual) + assert_equal(expected, actual) def test_shift(self): arr = DataArray([1, 2, 3], dims='x') actual = arr.shift(x=1) expected = DataArray([np.nan, 1, 2], dims='x') - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) arr = DataArray([1, 2, 3], [('x', ['a', 'b', 'c'])]) for offset in [-5, -2, -1, 0, 1, 2, 5]: expected = DataArray(arr.to_pandas().shift(offset)) actual = arr.shift(x=offset) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) def test_roll(self): arr = DataArray([1, 2, 3], coords={'x': range(3)}, dims='x') actual = arr.roll(x=1) expected = DataArray([3, 1, 2], coords=[('x', [2, 0, 1])]) - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) def test_real_and_imag(self): array = DataArray(1 + 2j) - self.assertDataArrayIdentical(array.real, DataArray(1)) - self.assertDataArrayIdentical(array.imag, DataArray(2)) + assert_identical(array.real, DataArray(1)) + assert_identical(array.imag, DataArray(2)) def test_setattr_raises(self): array = DataArray(0, coords={'scalar': 1}, attrs={'foo': 'bar'}) @@ -2856,13 +3136,13 @@ def test_full_like(self): actual = full_like(da, 2) expect = da.copy(deep=True) expect.values = [[2.0, 2.0], [2.0, 2.0]] - self.assertDataArrayIdentical(expect, actual) + assert_identical(expect, actual) # override dtype actual = full_like(da, fill_value=True, dtype=bool) expect.values = [[True, True], [True, True]] assert expect.dtype == bool - self.assertDataArrayIdentical(expect, actual) + assert_identical(expect, actual) def test_dot(self): x = np.linspace(-3, 3, 6) @@ -2878,14 +3158,14 @@ def test_dot(self): actual = da.dot(dm) expected_vals = np.tensordot(da_vals, dm_vals, [2, 0]) expected = DataArray(expected_vals, coords=[x, y], dims=['x', 'y']) - self.assertDataArrayEqual(expected, actual) + assert_equal(expected, actual) # all shared dims actual = da.dot(da) expected_vals = np.tensordot(da_vals, da_vals, axes=([0, 1, 2], [0, 1, 2])) expected = DataArray(expected_vals) - self.assertDataArrayEqual(expected, actual) + assert_equal(expected, actual) # multiple shared dims dm_vals = np.arange(20 * 5 * 4).reshape((20, 5, 4)) @@ -2894,7 +3174,7 @@ def test_dot(self): actual = da.dot(dm) expected_vals = np.tensordot(da_vals, dm_vals, axes=([1, 2], [1, 2])) expected = DataArray(expected_vals, coords=[x, j], dims=['x', 'j']) - self.assertDataArrayEqual(expected, actual) + assert_equal(expected, actual) with pytest.raises(NotImplementedError): da.dot(dm.to_dataset(name='dm')) @@ -2915,7 +3195,7 @@ def test_binary_op_join_setting(self): missing_3, join=align_type) expected = xr.DataArray([np.nan, 2, 4, np.nan], [(dim, [0, 1, 2, 3])]) - self.assertDataArrayEqual(actual, expected) + assert_equal(actual, expected) def test_combine_first(self): ar0 = DataArray([[0, 0], [0, 0]], [('x', ['a', 'b']), ('y', [-1, 0])]) @@ -2925,17 +3205,17 @@ def test_combine_first(self): actual = ar0.combine_first(ar1) expected = DataArray([[0, 0, np.nan], [0, 0, 1], [np.nan, 1, 1]], [('x', ['a', 'b', 'c']), ('y', [-1, 0, 1])]) - self.assertDataArrayEqual(actual, expected) + assert_equal(actual, expected) actual = ar1.combine_first(ar0) expected = DataArray([[0, 0, np.nan], [0, 1, 1], [np.nan, 1, 1]], [('x', ['a', 'b', 'c']), ('y', [-1, 0, 1])]) - self.assertDataArrayEqual(actual, expected) + assert_equal(actual, expected) actual = ar0.combine_first(ar2) expected = DataArray([[0, 0], [0, 0], [2, 2]], [('x', ['a', 'b', 'd']), ('y', [-1, 0])]) - self.assertDataArrayEqual(actual, expected) + assert_equal(actual, expected) def test_sortby(self): da = DataArray([[1, 2], [3, 4], [5, 6]], @@ -2950,34 +3230,53 @@ def test_sortby(self): expected = sorted1d dax = DataArray([100, 99, 98], [('x', ['c', 'b', 'a'])]) actual = da.sortby(dax) - self.assertDatasetEqual(actual, expected) + assert_equal(actual, expected) # test descending order sort actual = da.sortby(dax, ascending=False) - self.assertDatasetEqual(actual, da) + assert_equal(actual, da) # test alignment (fills in nan for 'c') dax_short = DataArray([98, 97], [('x', ['b', 'a'])]) actual = da.sortby(dax_short) - self.assertDatasetEqual(actual, expected) + assert_equal(actual, expected) # test multi-dim sort by 1D dataarray values expected = sorted2d dax = DataArray([100, 99, 98], [('x', ['c', 'b', 'a'])]) day = DataArray([90, 80], [('y', [1, 0])]) actual = da.sortby([day, dax]) - self.assertDataArrayEqual(actual, expected) + assert_equal(actual, expected) if LooseVersion(np.__version__) < LooseVersion('1.11.0'): pytest.skip('numpy 1.11.0 or later to support object data-type.') expected = sorted1d actual = da.sortby('x') - self.assertDataArrayEqual(actual, expected) + assert_equal(actual, expected) expected = sorted2d actual = da.sortby(['x', 'y']) - self.assertDataArrayEqual(actual, expected) + assert_equal(actual, expected) + + @requires_bottleneck + def test_rank(self): + # floats + ar = DataArray([[3, 4, np.nan, 1]]) + expect_0 = DataArray([[1, 1, np.nan, 1]]) + expect_1 = DataArray([[2, 3, np.nan, 1]]) + assert_equal(ar.rank('dim_0'), expect_0) + assert_equal(ar.rank('dim_1'), expect_1) + # int + x = DataArray([3, 2, 1]) + assert_equal(x.rank('dim_0'), x) + # str + y = DataArray(['c', 'b', 'a']) + assert_equal(y.rank('dim_0'), x) + + x = DataArray([3.0, 1.0, np.nan, 2.0, 4.0], dims=('z',)) + y = DataArray([0.75, 0.25, np.nan, 0.5, 1.0], dims=('z',)) + assert_equal(y.rank('z', pct=True), y) @pytest.fixture(params=[1]) diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py index 192624b..09d6761 100644 --- a/xarray/tests/test_dataset.py +++ b/xarray/tests/test_dataset.py @@ -28,10 +28,9 @@ from xarray.core.common import full_like from . import (TestCase, raises_regex, InaccessibleArray, UnexpectedDataAccess, - requires_dask, source_ndarray) - -from xarray.tests import (assert_equal, assert_allclose, - assert_array_equal, requires_scipy) + requires_dask, source_ndarray, assert_array_equal, assert_equal, + assert_allclose, assert_identical, requires_bottleneck, + requires_scipy) def create_test_data(seed=None): @@ -102,10 +101,10 @@ def test_repr(self): var2 (dim1, dim2) float64 1.162 -1.097 -2.123 1.04 -0.4034 -0.126 ... var3 (dim3, dim1) float64 0.5565 -0.2121 0.4563 1.545 -0.2397 0.1433 ... Attributes: - foo: bar""") % data['dim3'].dtype + foo: bar""") % data['dim3'].dtype # noqa: E501 actual = '\n'.join(x.rstrip() for x in repr(data).split('\n')) print(actual) - self.assertEqual(expected, actual) + assert expected == actual with set_options(display_width=100): max_len = max(map(len, repr(data).split('\n'))) @@ -118,7 +117,7 @@ def test_repr(self): *empty*""") actual = '\n'.join(x.rstrip() for x in repr(Dataset()).split('\n')) print(actual) - self.assertEqual(expected, actual) + assert expected == actual # verify that ... doesn't appear for scalar coordinates data = Dataset({'foo': ('x', np.ones(10))}).mean() @@ -129,11 +128,11 @@ def test_repr(self): foo float64 1.0""") actual = '\n'.join(x.rstrip() for x in repr(data).split('\n')) print(actual) - self.assertEqual(expected, actual) + assert expected == actual # verify long attributes are truncated data = Dataset(attrs={'foo': 'bar' * 1000}) - self.assertTrue(len(repr(data)) < 1000) + assert len(repr(data)) < 1000 def test_repr_multiindex(self): data = create_test_multiindex() @@ -148,7 +147,7 @@ def test_repr_multiindex(self): *empty*""") actual = '\n'.join(x.rstrip() for x in repr(data).split('\n')) print(actual) - self.assertEqual(expected, actual) + assert expected == actual # verify that long level names are not truncated mindex = pd.MultiIndex.from_product( @@ -166,11 +165,12 @@ def test_repr_multiindex(self): *empty*""") actual = '\n'.join(x.rstrip() for x in repr(data).split('\n')) print(actual) - self.assertEqual(expected, actual) + assert expected == actual def test_repr_period_index(self): data = create_test_data(seed=456) - data.coords['time'] = pd.period_range('2000-01-01', periods=20, freq='B') + data.coords['time'] = pd.period_range( + '2000-01-01', periods=20, freq='B') # check that creating the repr doesn't raise an error #GH645 repr(data) @@ -190,7 +190,7 @@ def test_unicode_data(self): Attributes: å: ∑""" % u'ba®') actual = unicode_type(data) - self.assertEqual(expected, actual) + assert expected == actual def test_info(self): ds = create_test_data(seed=123) @@ -225,7 +225,7 @@ def test_info(self): \t:string_attr = bar ; }''') actual = buf.getvalue() - self.assertEqual(expected, actual) + assert expected == actual buf.close() def test_constructor(self): @@ -245,7 +245,7 @@ def test_constructor(self): # verify handling of DataArrays expected = Dataset({'x': x1, 'z': z}) actual = Dataset({'z': expected['z']}) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_constructor_invalid_dims(self): # regression for GH1120 @@ -256,16 +256,16 @@ def test_constructor_invalid_dims(self): def test_constructor_1d(self): expected = Dataset({'x': (['x'], 5.0 + np.arange(5))}) actual = Dataset({'x': 5.0 + np.arange(5)}) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) actual = Dataset({'x': [5, 6, 7, 8, 9]}) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_constructor_0d(self): expected = Dataset({'x': ([], 1)}) for arg in [1, np.array(1), expected['x']]: actual = Dataset({'x': arg}) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) class Arbitrary(object): pass @@ -278,7 +278,7 @@ class Arbitrary(object): print(arg) expected = Dataset({'x': ([], arg)}) actual = Dataset({'x': arg}) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_constructor_deprecated(self): with raises_regex(ValueError, 'DataArray dimensions'): @@ -293,22 +293,22 @@ def test_constructor_auto_align(self): 'b': ('x', [np.nan, 3, 4])}, {'x': [0, 1, 2]}) actual = Dataset({'a': a, 'b': b}) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) # regression test for GH346 - self.assertIsInstance(actual.variables['x'], IndexVariable) + assert isinstance(actual.variables['x'], IndexVariable) # variable with different dimensions c = ('y', [3, 4]) expected2 = expected.merge({'c': c}) actual = Dataset({'a': a, 'b': b, 'c': c}) - self.assertDatasetIdentical(expected2, actual) + assert_identical(expected2, actual) # variable that is only aligned against the aligned variables d = ('x', [3, 2, 1]) expected3 = expected.merge({'d': d}) actual = Dataset({'a': a, 'b': b, 'd': d}) - self.assertDatasetIdentical(expected3, actual) + assert_identical(expected3, actual) e = ('x', [0, 0]) with raises_regex(ValueError, 'conflicting sizes'): @@ -318,33 +318,32 @@ def test_constructor_pandas_sequence(self): ds = self.make_example_math_dataset() pandas_objs = OrderedDict( - (var_name, ds[var_name].to_pandas()) for var_name in ['foo','bar'] + (var_name, ds[var_name].to_pandas()) for var_name in ['foo', 'bar'] ) ds_based_on_pandas = Dataset(pandas_objs, ds.coords, attrs=ds.attrs) del ds_based_on_pandas['x'] - self.assertDatasetEqual(ds, ds_based_on_pandas) + assert_equal(ds, ds_based_on_pandas) # reindex pandas obj, check align works rearranged_index = reversed(pandas_objs['foo'].index) pandas_objs['foo'] = pandas_objs['foo'].reindex(rearranged_index) ds_based_on_pandas = Dataset(pandas_objs, ds.coords, attrs=ds.attrs) del ds_based_on_pandas['x'] - self.assertDatasetEqual(ds, ds_based_on_pandas) + assert_equal(ds, ds_based_on_pandas) def test_constructor_pandas_single(self): das = [ DataArray(np.random.rand(4), dims=['a']), # series - DataArray(np.random.rand(4,3), dims=['a', 'b']), # df - DataArray(np.random.rand(4,3,2), dims=['a','b','c']), # panel - ] + DataArray(np.random.rand(4, 3), dims=['a', 'b']), # df + DataArray(np.random.rand(4, 3, 2), dims=['a', 'b', 'c']), # panel + ] - for da in das: - pandas_obj = da.to_pandas() + for a in das: + pandas_obj = a.to_pandas() ds_based_on_pandas = Dataset(pandas_obj) for dim in ds_based_on_pandas.data_vars: - self.assertArrayEqual(ds_based_on_pandas[dim], pandas_obj[dim]) - + assert_array_equal(ds_based_on_pandas[dim], pandas_obj[dim]) def test_constructor_compat(self): data = OrderedDict([('x', DataArray(0, coords={'y': 1})), @@ -353,14 +352,14 @@ def test_constructor_compat(self): Dataset(data, compat='equals') expected = Dataset({'x': 0}, {'y': ('z', [1, 1, 1])}) actual = Dataset(data) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) actual = Dataset(data, compat='broadcast_equals') - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) data = OrderedDict([('y', ('z', [1, 1, 1])), ('x', DataArray(0, coords={'y': 1}))]) actual = Dataset(data) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) original = Dataset({'a': (('x', 'y'), np.ones((2, 3)))}, {'c': (('x', 'y'), np.zeros((2, 3))), 'x': [0, 1]}) @@ -372,7 +371,7 @@ def test_constructor_compat(self): # dimensions in 'c' actual = Dataset(OrderedDict([('a', original['a'][:, 0]), ('b', original['a'][0].drop('x'))])) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) data = {'x': DataArray(0, coords={'y': 3}), 'y': ('z', [1, 1, 1])} with pytest.raises(MergeError): @@ -381,14 +380,14 @@ def test_constructor_compat(self): data = {'x': DataArray(0, coords={'y': 1}), 'y': [1, 1]} actual = Dataset(data) expected = Dataset({'x': 0}, {'y': [1, 1]}) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_constructor_with_coords(self): with raises_regex(ValueError, 'found in both data_vars and'): Dataset({'a': ('x', [1])}, {'a': ('x', [1])}) ds = Dataset({}, {'a': ('x', [1])}) - self.assertFalse(ds.data_vars) + assert not ds.data_vars self.assertItemsEqual(ds.coords.keys(), ['a']) mindex = pd.MultiIndex.from_product([['a', 'b'], [1, 2]], @@ -399,48 +398,48 @@ def test_constructor_with_coords(self): def test_properties(self): ds = create_test_data() - self.assertEqual(ds.dims, - {'dim1': 8, 'dim2': 9, 'dim3': 10, 'time': 20}) - self.assertEqual(list(ds.dims), sorted(ds.dims)) - self.assertEqual(ds.sizes, ds.dims) + assert ds.dims == \ + {'dim1': 8, 'dim2': 9, 'dim3': 10, 'time': 20} + assert list(ds.dims) == sorted(ds.dims) + assert ds.sizes == ds.dims # These exact types aren't public API, but this makes sure we don't # change them inadvertently: - self.assertIsInstance(ds.dims, utils.Frozen) - self.assertIsInstance(ds.dims.mapping, utils.SortedKeysDict) - self.assertIs(type(ds.dims.mapping.mapping), dict) + assert isinstance(ds.dims, utils.Frozen) + assert isinstance(ds.dims.mapping, utils.SortedKeysDict) + assert type(ds.dims.mapping.mapping) is dict with pytest.warns(FutureWarning): self.assertItemsEqual(ds, list(ds.variables)) with pytest.warns(FutureWarning): self.assertItemsEqual(ds.keys(), list(ds.variables)) - self.assertNotIn('aasldfjalskdfj', ds.variables) - self.assertIn('dim1', repr(ds.variables)) + assert 'aasldfjalskdfj' not in ds.variables + assert 'dim1' in repr(ds.variables) with pytest.warns(FutureWarning): - self.assertEqual(len(ds), 7) + assert len(ds) == 7 with pytest.warns(FutureWarning): - self.assertEqual(bool(ds), True) + assert bool(ds) self.assertItemsEqual(ds.data_vars, ['var1', 'var2', 'var3']) self.assertItemsEqual(ds.data_vars.keys(), ['var1', 'var2', 'var3']) - self.assertIn('var1', ds.data_vars) - self.assertNotIn('dim1', ds.data_vars) - self.assertNotIn('numbers', ds.data_vars) - self.assertEqual(len(ds.data_vars), 3) + assert 'var1' in ds.data_vars + assert 'dim1' not in ds.data_vars + assert 'numbers' not in ds.data_vars + assert len(ds.data_vars) == 3 self.assertItemsEqual(ds.indexes, ['dim2', 'dim3', 'time']) - self.assertEqual(len(ds.indexes), 3) - self.assertIn('dim2', repr(ds.indexes)) + assert len(ds.indexes) == 3 + assert 'dim2' in repr(ds.indexes) self.assertItemsEqual(ds.coords, ['time', 'dim2', 'dim3', 'numbers']) - self.assertIn('dim2', ds.coords) - self.assertIn('numbers', ds.coords) - self.assertNotIn('var1', ds.coords) - self.assertNotIn('dim1', ds.coords) - self.assertEqual(len(ds.coords), 4) + assert 'dim2' in ds.coords + assert 'numbers' in ds.coords + assert 'var1' not in ds.coords + assert 'dim1' not in ds.coords + assert len(ds.coords) == 4 - self.assertEqual(Dataset({'x': np.int64(1), - 'y': np.float32([1, 2])}).nbytes, 16) + assert Dataset({'x': np.int64(1), + 'y': np.float32([1, 2])}).nbytes == 16 def test_get_index(self): ds = Dataset({'foo': (('x', 'y'), np.zeros((2, 3)))}, @@ -453,30 +452,30 @@ def test_get_index(self): def test_attr_access(self): ds = Dataset({'tmin': ('x', [42], {'units': 'Celcius'})}, attrs={'title': 'My test data'}) - self.assertDataArrayIdentical(ds.tmin, ds['tmin']) - self.assertDataArrayIdentical(ds.tmin.x, ds.x) + assert_identical(ds.tmin, ds['tmin']) + assert_identical(ds.tmin.x, ds.x) - self.assertEqual(ds.title, ds.attrs['title']) - self.assertEqual(ds.tmin.units, ds['tmin'].attrs['units']) + assert ds.title == ds.attrs['title'] + assert ds.tmin.units == ds['tmin'].attrs['units'] - self.assertLessEqual(set(['tmin', 'title']), set(dir(ds))) - self.assertIn('units', set(dir(ds.tmin))) + assert set(['tmin', 'title']) <= set(dir(ds)) + assert 'units' in set(dir(ds.tmin)) # should defer to variable of same name ds.attrs['tmin'] = -999 - self.assertEqual(ds.attrs['tmin'], -999) - self.assertDataArrayIdentical(ds.tmin, ds['tmin']) + assert ds.attrs['tmin'] == -999 + assert_identical(ds.tmin, ds['tmin']) def test_variable(self): a = Dataset() d = np.random.random((10, 3)) a['foo'] = (('time', 'x',), d) - self.assertTrue('foo' in a.variables) - self.assertTrue('foo' in a) + assert 'foo' in a.variables + assert 'foo' in a a['bar'] = (('time', 'x',), d) # order of creation is preserved - self.assertEqual(list(a.variables), ['foo', 'bar']) - self.assertArrayEqual(a['foo'].values, d) + assert list(a.variables) == ['foo', 'bar'] + assert_array_equal(a['foo'].values, d) # try to add variable with dim (10,3) with data that's (3,10) with pytest.raises(ValueError): a['qux'] = (('time', 'x'), d.T) @@ -486,13 +485,13 @@ def test_modify_inplace(self): vec = np.random.random((10,)) attributes = {'foo': 'bar'} a['x'] = ('x', vec, attributes) - self.assertTrue('x' in a.coords) - self.assertIsInstance(a.coords['x'].to_index(), pd.Index) - self.assertVariableIdentical(a.coords['x'].variable, a.variables['x']) + assert 'x' in a.coords + assert isinstance(a.coords['x'].to_index(), pd.Index) + assert_identical(a.coords['x'].variable, a.variables['x']) b = Dataset() b['x'] = ('x', vec, attributes) - self.assertVariableIdentical(a['x'], b['x']) - self.assertEqual(a.dims, b.dims) + assert_identical(a['x'], b['x']) + assert a.dims == b.dims # this should work a['x'] = ('x', vec[:5]) a['z'] = ('x', np.arange(5)) @@ -505,7 +504,7 @@ def test_modify_inplace(self): a['y'] = ('y', arr) with pytest.raises(ValueError): a['y'] = ('y', scal) - self.assertTrue('y' not in a.dims) + assert 'y' not in a.dims def test_coords_properties(self): # use an OrderedDict for coordinates to ensure order across python @@ -518,17 +517,17 @@ def test_coords_properties(self): OrderedDict([('a', ('x', np.array([4, 5], 'int64'))), ('b', np.int64(-10))])) - self.assertEqual(4, len(data.coords)) + assert 4 == len(data.coords) self.assertItemsEqual(['x', 'y', 'a', 'b'], list(data.coords)) - self.assertVariableIdentical(data.coords['x'].variable, data['x'].variable) - self.assertVariableIdentical(data.coords['y'].variable, data['y'].variable) + assert_identical(data.coords['x'].variable, data['x'].variable) + assert_identical(data.coords['y'].variable, data['y'].variable) - self.assertIn('x', data.coords) - self.assertIn('a', data.coords) - self.assertNotIn(0, data.coords) - self.assertNotIn('foo', data.coords) + assert 'x' in data.coords + assert 'a' in data.coords + assert 0 not in data.coords + assert 'foo' not in data.coords with pytest.raises(KeyError): data.coords['foo'] @@ -542,9 +541,9 @@ def test_coords_properties(self): a (x) int64 4 5 b int64 -10""") actual = repr(data.coords) - self.assertEqual(expected, actual) + assert expected == actual - self.assertEqual({'x': 2, 'y': 3}, data.coords.dims) + assert {'x': 2, 'y': 3} == data.coords.dims def test_coords_modify(self): data = Dataset({'x': ('x', [-1, -2]), @@ -554,21 +553,21 @@ def test_coords_modify(self): actual = data.copy(deep=True) actual.coords['x'] = ('x', ['a', 'b']) - self.assertArrayEqual(actual['x'], ['a', 'b']) + assert_array_equal(actual['x'], ['a', 'b']) actual = data.copy(deep=True) actual.coords['z'] = ('z', ['a', 'b']) - self.assertArrayEqual(actual['z'], ['a', 'b']) + assert_array_equal(actual['z'], ['a', 'b']) actual = data.copy(deep=True) with raises_regex(ValueError, 'conflicting sizes'): actual.coords['x'] = ('x', [-1]) - self.assertDatasetIdentical(actual, data) # should not be modified + assert_identical(actual, data) # should not be modified actual = data.copy() del actual.coords['b'] expected = data.reset_coords('b', drop=True) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) with pytest.raises(KeyError): del data.coords['not_found'] @@ -579,13 +578,13 @@ def test_coords_modify(self): actual = data.copy(deep=True) actual.coords.update({'c': 11}) expected = data.merge({'c': 11}).set_coords('c') - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_coords_setitem_with_new_dimension(self): actual = Dataset() actual.coords['foo'] = ('x', [1, 2, 3]) expected = Dataset(coords={'foo': ('x', [1, 2, 3])}) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_coords_setitem_multiindex(self): data = create_test_multiindex() @@ -604,42 +603,42 @@ def test_coords_set(self): 'zzz': ('x', [2])}) actual = one_coord.set_coords('x') - self.assertDatasetIdentical(one_coord, actual) + assert_identical(one_coord, actual) actual = one_coord.set_coords(['x']) - self.assertDatasetIdentical(one_coord, actual) + assert_identical(one_coord, actual) actual = one_coord.set_coords('yy') - self.assertDatasetIdentical(two_coords, actual) + assert_identical(two_coords, actual) actual = one_coord.set_coords(['yy', 'zzz']) - self.assertDatasetIdentical(all_coords, actual) + assert_identical(all_coords, actual) actual = one_coord.reset_coords() - self.assertDatasetIdentical(one_coord, actual) + assert_identical(one_coord, actual) actual = two_coords.reset_coords() - self.assertDatasetIdentical(one_coord, actual) + assert_identical(one_coord, actual) actual = all_coords.reset_coords() - self.assertDatasetIdentical(one_coord, actual) + assert_identical(one_coord, actual) actual = all_coords.reset_coords(['yy', 'zzz']) - self.assertDatasetIdentical(one_coord, actual) + assert_identical(one_coord, actual) actual = all_coords.reset_coords('zzz') - self.assertDatasetIdentical(two_coords, actual) + assert_identical(two_coords, actual) with raises_regex(ValueError, 'cannot remove index'): one_coord.reset_coords('x') actual = all_coords.reset_coords('zzz', drop=True) expected = all_coords.drop('zzz') - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) expected = two_coords.drop('zzz') - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_coords_to_dataset(self): orig = Dataset({'foo': ('y', [-1, 0, 1])}, {'x': 10, 'y': [2, 3, 4]}) expected = Dataset(coords={'x': 10, 'y': [2, 3, 4]}) actual = orig.coords.to_dataset() - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_coords_merge(self): orig_coords = Dataset(coords={'a': ('x', [1, 2]), 'x': [0, 1]}).coords @@ -649,9 +648,9 @@ def test_coords_merge(self): 'b': ('x', ['a', 'b']), 'x': [0, 1]}) actual = orig_coords.merge(other_coords) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) actual = other_coords.merge(orig_coords) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) other_coords = Dataset(coords={'x': ('x', ['a'])}).coords with pytest.raises(MergeError): @@ -666,124 +665,124 @@ def test_coords_merge(self): other_coords = Dataset(coords={'a': ('x', [8, 9])}).coords expected = Dataset(coords={'x': range(2)}) actual = orig_coords.merge(other_coords) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) actual = other_coords.merge(orig_coords) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) other_coords = Dataset(coords={'x': np.nan}).coords actual = orig_coords.merge(other_coords) - self.assertDatasetIdentical(orig_coords.to_dataset(), actual) + assert_identical(orig_coords.to_dataset(), actual) actual = other_coords.merge(orig_coords) - self.assertDatasetIdentical(orig_coords.to_dataset(), actual) + assert_identical(orig_coords.to_dataset(), actual) def test_coords_merge_mismatched_shape(self): orig_coords = Dataset(coords={'a': ('x', [1, 1])}).coords other_coords = Dataset(coords={'a': 1}).coords expected = orig_coords.to_dataset() actual = orig_coords.merge(other_coords) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) other_coords = Dataset(coords={'a': ('y', [1])}).coords expected = Dataset(coords={'a': (['x', 'y'], [[1], [1]])}) actual = orig_coords.merge(other_coords) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) actual = other_coords.merge(orig_coords) - self.assertDatasetIdentical(expected.transpose(), actual) + assert_identical(expected.transpose(), actual) orig_coords = Dataset(coords={'a': ('x', [np.nan])}).coords other_coords = Dataset(coords={'a': np.nan}).coords expected = orig_coords.to_dataset() actual = orig_coords.merge(other_coords) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_data_vars_properties(self): ds = Dataset() ds['foo'] = (('x',), [1.0]) ds['bar'] = 2.0 - self.assertEqual(set(ds.data_vars), {'foo', 'bar'}) - self.assertIn('foo', ds.data_vars) - self.assertNotIn('x', ds.data_vars) - self.assertDataArrayIdentical(ds['foo'], ds.data_vars['foo']) + assert set(ds.data_vars) == {'foo', 'bar'} + assert 'foo' in ds.data_vars + assert 'x' not in ds.data_vars + assert_identical(ds['foo'], ds.data_vars['foo']) expected = dedent("""\ Data variables: foo (x) float64 1.0 bar float64 2.0""") actual = repr(ds.data_vars) - self.assertEqual(expected, actual) + assert expected == actual def test_equals_and_identical(self): data = create_test_data(seed=42) - self.assertTrue(data.equals(data)) - self.assertTrue(data.identical(data)) + assert data.equals(data) + assert data.identical(data) data2 = create_test_data(seed=42) data2.attrs['foobar'] = 'baz' - self.assertTrue(data.equals(data2)) - self.assertFalse(data.identical(data2)) + assert data.equals(data2) + assert not data.identical(data2) del data2['time'] - self.assertFalse(data.equals(data2)) + assert not data.equals(data2) data = create_test_data(seed=42).rename({'var1': None}) - self.assertTrue(data.equals(data)) - self.assertTrue(data.identical(data)) + assert data.equals(data) + assert data.identical(data) data2 = data.reset_coords() - self.assertFalse(data2.equals(data)) - self.assertFalse(data2.identical(data)) + assert not data2.equals(data) + assert not data2.identical(data) def test_equals_failures(self): data = create_test_data() - self.assertFalse(data.equals('foo')) - self.assertFalse(data.identical(123)) - self.assertFalse(data.broadcast_equals({1: 2})) + assert not data.equals('foo') + assert not data.identical(123) + assert not data.broadcast_equals({1: 2}) def test_broadcast_equals(self): data1 = Dataset(coords={'x': 0}) data2 = Dataset(coords={'x': [0]}) - self.assertTrue(data1.broadcast_equals(data2)) - self.assertFalse(data1.equals(data2)) - self.assertFalse(data1.identical(data2)) + assert data1.broadcast_equals(data2) + assert not data1.equals(data2) + assert not data1.identical(data2) def test_attrs(self): data = create_test_data(seed=42) data.attrs = {'foobar': 'baz'} - self.assertTrue(data.attrs['foobar'], 'baz') - self.assertIsInstance(data.attrs, OrderedDict) + assert data.attrs['foobar'], 'baz' + assert isinstance(data.attrs, OrderedDict) @requires_dask def test_chunk(self): data = create_test_data() for v in data.variables.values(): - self.assertIsInstance(v.data, np.ndarray) - self.assertEqual(data.chunks, {}) + assert isinstance(v.data, np.ndarray) + assert data.chunks == {} reblocked = data.chunk() for k, v in reblocked.variables.items(): if k in reblocked.dims: - self.assertIsInstance(v.data, np.ndarray) + assert isinstance(v.data, np.ndarray) else: - self.assertIsInstance(v.data, da.Array) + assert isinstance(v.data, da.Array) expected_chunks = {'dim1': (8,), 'dim2': (9,), 'dim3': (10,)} - self.assertEqual(reblocked.chunks, expected_chunks) + assert reblocked.chunks == expected_chunks reblocked = data.chunk({'time': 5, 'dim1': 5, 'dim2': 5, 'dim3': 5}) # time is not a dim in any of the data_vars, so it # doesn't get chunked expected_chunks = {'dim1': (5, 3), 'dim2': (5, 4), 'dim3': (5, 5)} - self.assertEqual(reblocked.chunks, expected_chunks) + assert reblocked.chunks == expected_chunks reblocked = data.chunk(expected_chunks) - self.assertEqual(reblocked.chunks, expected_chunks) + assert reblocked.chunks == expected_chunks # reblock on already blocked data reblocked = reblocked.chunk(expected_chunks) - self.assertEqual(reblocked.chunks, expected_chunks) - self.assertDatasetIdentical(reblocked, data) + assert reblocked.chunks == expected_chunks + assert_identical(reblocked, data) with raises_regex(ValueError, 'some chunks'): data.chunk({'foo': 10}) @@ -819,14 +818,14 @@ def test_isel(self): self.assertItemsEqual(data.dims, ret.dims) for d in data.dims: if d in slicers: - self.assertEqual(ret.dims[d], - np.arange(data.dims[d])[slicers[d]].size) + assert ret.dims[d] == \ + np.arange(data.dims[d])[slicers[d]].size else: - self.assertEqual(data.dims[d], ret.dims[d]) + assert data.dims[d] == ret.dims[d] # Verify that the data is what we expect for v in data.variables: - self.assertEqual(data[v].dims, ret[v].dims) - self.assertEqual(data[v].attrs, ret[v].attrs) + assert data[v].dims == ret[v].dims + assert data[v].attrs == ret[v].attrs slice_list = [slice(None)] * data[v].values.ndim for d, s in iteritems(slicers): if d in data[v].dims: @@ -841,13 +840,13 @@ def test_isel(self): data.isel(not_a_dim=slice(0, 2)) ret = data.isel(dim1=0) - self.assertEqual({'time': 20, 'dim2': 9, 'dim3': 10}, ret.dims) + assert {'time': 20, 'dim2': 9, 'dim3': 10} == ret.dims self.assertItemsEqual(data.data_vars, ret.data_vars) self.assertItemsEqual(data.coords, ret.coords) self.assertItemsEqual(data.indexes, ret.indexes) ret = data.isel(time=slice(2), dim1=0, dim2=slice(5)) - self.assertEqual({'time': 2, 'dim2': 5, 'dim3': 10}, ret.dims) + assert {'time': 2, 'dim2': 5, 'dim3': 10} == ret.dims self.assertItemsEqual(data.data_vars, ret.data_vars) self.assertItemsEqual(data.coords, ret.coords) self.assertItemsEqual(data.indexes, ret.indexes) @@ -880,7 +879,7 @@ def test_isel_fancy(self): expected = data.isel(dim1=(('test_coord', ), pdim1), dim2=(('test_coord', ), pdim2), dim3=(('test_coord', ), pdim3)) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) # DataArray with coordinate idx1 = DataArray(pdim1, dims=['a'], coords={'a': np.random.randn(3)}) @@ -899,7 +898,7 @@ def test_isel_fancy(self): dim3=(('c', ), pdim3)) expected = expected.assign_coords(a=idx1['a'], b=idx2['b'], c=idx3['c']) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) idx1 = DataArray(pdim1, dims=['a'], coords={'a': np.random.randn(3)}) idx2 = DataArray(pdim2, dims=['a']) @@ -914,7 +913,7 @@ def test_isel_fancy(self): dim2=(('a', ), pdim2), dim3=(('a', ), pdim3)) expected = expected.assign_coords(a=idx1['a']) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) actual = data.isel(dim1=(('points', ), pdim1), dim2=(('points', ), pdim2)) @@ -924,13 +923,13 @@ def test_isel_fancy(self): np.testing.assert_array_equal(data['dim2'][pdim2], actual['dim2']) # test that the order of the indexers doesn't matter - self.assertDatasetIdentical(data.isel(dim1=(('points', ), pdim1), - dim2=(('points', ), pdim2)), - data.isel(dim2=(('points', ), pdim2), - dim1=(('points', ), pdim1))) + assert_identical(data.isel(dim1=(('points', ), pdim1), + dim2=(('points', ), pdim2)), + data.isel(dim2=(('points', ), pdim2), + dim1=(('points', ), pdim1))) # make sure we're raising errors in the right places with raises_regex(IndexError, - 'Dimensions of indexers mismatch'): + 'Dimensions of indexers mismatch'): data.isel(dim1=(('points', ), [1, 2]), dim2=(('points', ), [1, 2, 3])) with raises_regex(TypeError, 'cannot use a Dataset'): @@ -939,7 +938,7 @@ def test_isel_fancy(self): # test to be sure we keep around variables that were not indexed ds = Dataset({'x': [1, 2, 3, 4], 'y': 0}) actual = ds.isel(x=(('points', ), [0, 1, 2])) - self.assertDataArrayIdentical(ds['y'], actual['y']) + assert_identical(ds['y'], actual['y']) # tests using index or DataArray as indexers stations = Dataset() @@ -951,8 +950,8 @@ def test_isel_fancy(self): dim2=stations['dim2s']) assert 'station' in actual.coords assert 'station' in actual.dims - self.assertDataArrayIdentical(actual['station'].drop(['dim2']), - stations['station']) + assert_identical(actual['station'].drop(['dim2']), + stations['station']) with raises_regex(ValueError, 'conflicting values for '): data.isel(dim1=DataArray([0, 1, 2], dims='station', @@ -974,19 +973,19 @@ def test_isel_fancy(self): assert 'dim2' in actual.coords assert 'a' in actual['dim2'].dims - self.assertDataArrayIdentical(actual['a'].drop(['dim2']), - stations['a']) - self.assertDataArrayIdentical(actual['b'], stations['b']) + assert_identical(actual['a'].drop(['dim2']), + stations['a']) + assert_identical(actual['b'], stations['b']) expected_var1 = data['var1'].variable[stations['dim1s'].variable, stations['dim2s'].variable] expected_var2 = data['var2'].variable[stations['dim1s'].variable, stations['dim2s'].variable] expected_var3 = data['var3'].variable[slice(None), stations['dim1s'].variable] - self.assertDataArrayEqual(actual['a'].drop('dim2'), stations['a']) - self.assertArrayEqual(actual['var1'], expected_var1) - self.assertArrayEqual(actual['var2'], expected_var2) - self.assertArrayEqual(actual['var3'], expected_var3) + assert_equal(actual['a'].drop('dim2'), stations['a']) + assert_array_equal(actual['var1'], expected_var1) + assert_array_equal(actual['var2'], expected_var2) + assert_array_equal(actual['var3'], expected_var3) def test_isel_dataarray(self): """ Test for indexing by DataArray """ @@ -995,42 +994,39 @@ def test_isel_dataarray(self): indexing_da = DataArray(np.arange(1, 4), dims=['dim1'], coords={'dim1': np.random.randn(3)}) actual = data.isel(dim1=indexing_da) - self.assertDataArrayIdentical(indexing_da['dim1'], actual['dim1']) - self.assertDataArrayIdentical(data['dim2'], actual['dim2']) + assert_identical(indexing_da['dim1'], actual['dim1']) + assert_identical(data['dim2'], actual['dim2']) # Conflict in the dimension coordinate indexing_da = DataArray(np.arange(1, 4), dims=['dim2'], coords={'dim2': np.random.randn(3)}) - with raises_regex( - IndexError, "dimension coordinate 'dim2'"): + with raises_regex(IndexError, "dimension coordinate 'dim2'"): actual = data.isel(dim2=indexing_da) # Also the case for DataArray - with raises_regex( - IndexError, "dimension coordinate 'dim2'"): + with raises_regex(IndexError, "dimension coordinate 'dim2'"): actual = data['var2'].isel(dim2=indexing_da) - with raises_regex( - IndexError, "dimension coordinate 'dim2'"): + with raises_regex(IndexError, "dimension coordinate 'dim2'"): data['dim2'].isel(dim2=indexing_da) # same name coordinate which does not conflict indexing_da = DataArray(np.arange(1, 4), dims=['dim2'], coords={'dim2': data['dim2'].values[1:4]}) actual = data.isel(dim2=indexing_da) - self.assertDataArrayIdentical(actual['dim2'], indexing_da['dim2']) + assert_identical(actual['dim2'], indexing_da['dim2']) # Silently drop conflicted (non-dimensional) coordinate of indexer indexing_da = DataArray(np.arange(1, 4), dims=['dim2'], coords={'dim2': data['dim2'].values[1:4], 'numbers': ('dim2', np.arange(2, 5))}) actual = data.isel(dim2=indexing_da) - self.assertDataArrayIdentical(actual['numbers'], data['numbers']) + assert_identical(actual['numbers'], data['numbers']) # boolean data array with coordinate with the same name indexing_da = DataArray(np.arange(1, 10), dims=['dim2'], coords={'dim2': data['dim2'].values}) indexing_da = (indexing_da < 3) actual = data.isel(dim2=indexing_da) - self.assertDataArrayIdentical(actual['dim2'], data['dim2'][:2]) + assert_identical(actual['dim2'], data['dim2'][:2]) # boolean data array with non-dimensioncoordinate indexing_da = DataArray(np.arange(1, 10), dims=['dim2'], @@ -1040,11 +1036,11 @@ def test_isel_dataarray(self): 'non_dim2': 0}) indexing_da = (indexing_da < 3) actual = data.isel(dim2=indexing_da) - self.assertDataArrayIdentical( + assert_identical( actual['dim2'].drop('non_dim').drop('non_dim2'), data['dim2'][:2]) - self.assertDataArrayIdentical( + assert_identical( actual['non_dim'], indexing_da['non_dim'][:2]) - self.assertDataArrayIdentical( + assert_identical( actual['non_dim2'], indexing_da['non_dim2']) # non-dimension coordinate will be also attached @@ -1076,45 +1072,45 @@ def test_sel(self): loc_slicers = {'dim1': slice(None, None, 2), 'dim2': slice(0, 0.5), 'dim3': slice('a', 'c')} - self.assertDatasetEqual(data.isel(**int_slicers), - data.sel(**loc_slicers)) + assert_equal(data.isel(**int_slicers), + data.sel(**loc_slicers)) data['time'] = ('time', pd.date_range('2000-01-01', periods=20)) - self.assertDatasetEqual(data.isel(time=0), - data.sel(time='2000-01-01')) - self.assertDatasetEqual(data.isel(time=slice(10)), - data.sel(time=slice('2000-01-01', - '2000-01-10'))) - self.assertDatasetEqual(data, data.sel(time=slice('1999', '2005'))) + assert_equal(data.isel(time=0), + data.sel(time='2000-01-01')) + assert_equal(data.isel(time=slice(10)), + data.sel(time=slice('2000-01-01', + '2000-01-10'))) + assert_equal(data, data.sel(time=slice('1999', '2005'))) times = pd.date_range('2000-01-01', periods=3) - self.assertDatasetEqual(data.isel(time=slice(3)), - data.sel(time=times)) - self.assertDatasetEqual(data.isel(time=slice(3)), - data.sel(time=(data['time.dayofyear'] <= 3))) + assert_equal(data.isel(time=slice(3)), + data.sel(time=times)) + assert_equal(data.isel(time=slice(3)), + data.sel(time=(data['time.dayofyear'] <= 3))) td = pd.to_timedelta(np.arange(3), unit='days') data = Dataset({'x': ('td', np.arange(3)), 'td': td}) - self.assertDatasetEqual(data, data.sel(td=td)) - self.assertDatasetEqual(data, data.sel(td=slice('3 days'))) - self.assertDatasetEqual(data.isel(td=0), - data.sel(td=pd.Timedelta('0 days'))) - self.assertDatasetEqual(data.isel(td=0), - data.sel(td=pd.Timedelta('0h'))) - self.assertDatasetEqual(data.isel(td=slice(1, 3)), - data.sel(td=slice('1 days', '2 days'))) + assert_equal(data, data.sel(td=td)) + assert_equal(data, data.sel(td=slice('3 days'))) + assert_equal(data.isel(td=0), + data.sel(td=pd.Timedelta('0 days'))) + assert_equal(data.isel(td=0), + data.sel(td=pd.Timedelta('0h'))) + assert_equal(data.isel(td=slice(1, 3)), + data.sel(td=slice('1 days', '2 days'))) def test_sel_dataarray(self): data = create_test_data() ind = DataArray([0.0, 0.5, 1.0], dims=['dim2']) actual = data.sel(dim2=ind) - self.assertDatasetEqual(actual, data.isel(dim2=[0, 1, 2])) + assert_equal(actual, data.isel(dim2=[0, 1, 2])) # with different dimension ind = DataArray([0.0, 0.5, 1.0], dims=['new_dim']) actual = data.sel(dim2=ind) expected = data.isel(dim2=Variable('new_dim', [0, 1, 2])) assert 'new_dim' in actual.dims - self.assertDatasetEqual(actual, expected) + assert_equal(actual, expected) # Multi-dimensional ind = DataArray([[0.0], [0.5], [1.0]], dims=['new_dim', 'new_dim2']) @@ -1123,7 +1119,7 @@ def test_sel_dataarray(self): [[0], [1], [2]])) assert 'new_dim' in actual.dims assert 'new_dim2' in actual.dims - self.assertDatasetEqual(actual, expected) + assert_equal(actual, expected) # with coordinate ind = DataArray([0.0, 0.5, 1.0], dims=['new_dim'], @@ -1132,29 +1128,29 @@ def test_sel_dataarray(self): expected = data.isel(dim2=[0, 1, 2]).rename({'dim2': 'new_dim'}) assert 'new_dim' in actual.dims assert 'new_dim' in actual.coords - self.assertDatasetEqual(actual.drop('new_dim').drop('dim2'), - expected.drop('new_dim')) - self.assertDataArrayEqual(actual['new_dim'].drop('dim2'), - ind['new_dim']) + assert_equal(actual.drop('new_dim').drop('dim2'), + expected.drop('new_dim')) + assert_equal(actual['new_dim'].drop('dim2'), + ind['new_dim']) # with conflicted coordinate (silently ignored) ind = DataArray([0.0, 0.5, 1.0], dims=['dim2'], coords={'dim2': ['a', 'b', 'c']}) actual = data.sel(dim2=ind) expected = data.isel(dim2=[0, 1, 2]) - self.assertDatasetEqual(actual, expected) + assert_equal(actual, expected) # with conflicted coordinate (silently ignored) ind = DataArray([0.0, 0.5, 1.0], dims=['new_dim'], coords={'new_dim': ['a', 'b', 'c'], 'dim2': 3}) actual = data.sel(dim2=ind) - self.assertDataArrayEqual(actual['new_dim'].drop('dim2'), - ind['new_dim'].drop('dim2')) + assert_equal(actual['new_dim'].drop('dim2'), + ind['new_dim'].drop('dim2')) expected = data.isel(dim2=[0, 1, 2]) expected['dim2'] = (('new_dim'), expected['dim2'].values) - self.assertDataArrayEqual(actual['dim2'].drop('new_dim'), - expected['dim2']) + assert_equal(actual['dim2'].drop('new_dim'), + expected['dim2']) assert actual['var1'].dims == ('dim1', 'new_dim') # with non-dimensional coordinate @@ -1164,7 +1160,7 @@ def test_sel_dataarray(self): 'new_dim': ('dim2', [1.1, 1.2, 1.3])}) actual = data.sel(dim2=ind) expected = data.isel(dim2=[0, 1, 2]) - self.assertDatasetEqual(actual.drop('new_dim'), expected) + assert_equal(actual.drop('new_dim'), expected) assert np.allclose(actual['new_dim'].values, ind['new_dim'].values) def test_sel_dataarray_mindex(self): @@ -1177,13 +1173,13 @@ def test_sel_dataarray_mindex(self): actual_sel = mds.sel(x=DataArray(mds.indexes['x'][:3], dims='x')) assert actual_isel['x'].dims == ('x', ) assert actual_sel['x'].dims == ('x', ) - self.assertDatasetIdentical(actual_isel, actual_sel) + assert_identical(actual_isel, actual_sel) actual_isel = mds.isel(x=xr.DataArray(np.arange(3), dims='z')) actual_sel = mds.sel(x=Variable('z', mds.indexes['x'][:3])) assert actual_isel['x'].dims == ('z', ) assert actual_sel['x'].dims == ('z', ) - self.assertDatasetIdentical(actual_isel, actual_sel) + assert_identical(actual_isel, actual_sel) # with coordinate actual_isel = mds.isel(x=xr.DataArray(np.arange(3), dims='z', @@ -1192,15 +1188,15 @@ def test_sel_dataarray_mindex(self): coords={'z': [0, 1, 2]})) assert actual_isel['x'].dims == ('z', ) assert actual_sel['x'].dims == ('z', ) - self.assertDatasetIdentical(actual_isel, actual_sel) + assert_identical(actual_isel, actual_sel) # Vectorized indexing with level-variables raises an error with raises_regex(ValueError, 'Vectorized selection is '): mds.sel(one=['a', 'b']) with raises_regex(ValueError, 'Vectorized selection is ' - 'not available along MultiIndex variable:' - ' x'): + 'not available along MultiIndex variable:' + ' x'): mds.sel(x=xr.DataArray([np.array(midx[:2]), np.array(midx[-2:])], dims=['a', 'b'])) @@ -1208,26 +1204,26 @@ def test_sel_drop(self): data = Dataset({'foo': ('x', [1, 2, 3])}, {'x': [0, 1, 2]}) expected = Dataset({'foo': 1}) selected = data.sel(x=0, drop=True) - self.assertDatasetIdentical(expected, selected) + assert_identical(expected, selected) expected = Dataset({'foo': 1}, {'x': 0}) selected = data.sel(x=0, drop=False) - self.assertDatasetIdentical(expected, selected) + assert_identical(expected, selected) data = Dataset({'foo': ('x', [1, 2, 3])}) expected = Dataset({'foo': 1}) selected = data.sel(x=0, drop=True) - self.assertDatasetIdentical(expected, selected) + assert_identical(expected, selected) def test_isel_drop(self): data = Dataset({'foo': ('x', [1, 2, 3])}, {'x': [0, 1, 2]}) expected = Dataset({'foo': 1}) selected = data.isel(x=0, drop=True) - self.assertDatasetIdentical(expected, selected) + assert_identical(expected, selected) expected = Dataset({'foo': 1}, {'x': 0}) selected = data.isel(x=0, drop=False) - self.assertDatasetIdentical(expected, selected) + assert_identical(expected, selected) def test_isel_points(self): data = create_test_data() @@ -1247,31 +1243,31 @@ def test_isel_points(self): np.testing.assert_array_equal(data['dim2'][pdim2], actual['dim2']) # test that the order of the indexers doesn't matter - self.assertDatasetIdentical(data.isel_points(dim1=pdim1, dim2=pdim2), - data.isel_points(dim2=pdim2, dim1=pdim1)) + assert_identical(data.isel_points(dim1=pdim1, dim2=pdim2), + data.isel_points(dim2=pdim2, dim1=pdim1)) # make sure we're raising errors in the right places with raises_regex(ValueError, - 'All indexers must be the same length'): + 'All indexers must be the same length'): data.isel_points(dim1=[1, 2], dim2=[1, 2, 3]) with raises_regex(ValueError, - 'dimension bad_key does not exist'): + 'dimension bad_key does not exist'): data.isel_points(bad_key=[1, 2]) with raises_regex(TypeError, 'Indexers must be integers'): data.isel_points(dim1=[1.5, 2.2]) with raises_regex(TypeError, 'Indexers must be integers'): data.isel_points(dim1=[1, 2, 3], dim2=slice(3)) with raises_regex(ValueError, - 'Indexers must be 1 dimensional'): + 'Indexers must be 1 dimensional'): data.isel_points(dim1=1, dim2=2) with raises_regex(ValueError, - 'Existing dimension names are not valid'): + 'Existing dimension names are not valid'): data.isel_points(dim1=[1, 2], dim2=[1, 2], dim='dim2') # test to be sure we keep around variables that were not indexed ds = Dataset({'x': [1, 2, 3, 4], 'y': 0}) actual = ds.isel_points(x=[0, 1, 2]) - self.assertDataArrayIdentical(ds['y'], actual['y']) + assert_identical(ds['y'], actual['y']) # tests using index or DataArray as a dim stations = Dataset() @@ -1284,10 +1280,10 @@ def test_isel_points(self): dim=stations['station']) assert 'station' in actual.coords assert 'station' in actual.dims - self.assertDataArrayIdentical(actual['station'].drop(['dim2']), - stations['station']) + assert_identical(actual['station'].drop(['dim2']), + stations['station']) - # make sure we get the default 'points' coordinate when a list is passed + # make sure we get the default 'points' coordinate when passed a list actual = data.isel_points(dim1=stations['dim1s'], dim2=stations['dim2s'], dim=['A', 'B', 'C']) @@ -1297,7 +1293,8 @@ def test_isel_points(self): # test index actual = data.isel_points(dim1=stations['dim1s'].values, dim2=stations['dim2s'].values, - dim=pd.Index(['A', 'B', 'C'], name='letters')) + dim=pd.Index(['A', 'B', 'C'], + name='letters')) assert 'letters' in actual.coords # can pass a numpy array @@ -1318,19 +1315,19 @@ def test_sel_points(self): dim='test_coord') actual = data.sel_points(dim1=data.dim1[pdim1], dim2=data.dim2[pdim2], dim3=data.dim3[pdim3], dim='test_coord') - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) data = Dataset({'foo': (('x', 'y'), np.arange(9).reshape(3, 3))}) expected = Dataset({'foo': ('points', [0, 4, 8])}) actual = data.sel_points(x=[0, 1, 2], y=[0, 1, 2]) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) data.coords.update({'x': [0, 1, 2], 'y': [0, 1, 2]}) expected.coords.update({'x': ('points', [0, 1, 2]), 'y': ('points', [0, 1, 2])}) actual = data.sel_points(x=[0.1, 1.1, 2.5], y=[0, 1.2, 2.0], method='pad') - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) with pytest.raises(KeyError): data.sel_points(x=[2.5], y=[2.0], method='pad', tolerance=1e-3) @@ -1350,7 +1347,7 @@ def test_sel_fancy(self): actual = data.sel(dim1=Variable(('test_coord', ), data.dim1[pdim1]), dim2=Variable(('test_coord', ), data.dim2[pdim2]), dim3=Variable(('test_coord', ), data.dim3[pdim3])) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) # DataArray Indexer idx_t = DataArray(data['time'][[3, 2, 1]].values, dims=['a'], @@ -1364,7 +1361,7 @@ def test_sel_fancy(self): dim2=Variable(('a', ), [3, 2, 1]), dim3=Variable(('a', ), [3, 2, 1])) expected = expected.assign_coords(a=idx_t['a']) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) idx_t = DataArray(data['time'][[3, 2, 1]].values, dims=['a'], coords={'a': ['a', 'b', 'c']}) @@ -1378,7 +1375,7 @@ def test_sel_fancy(self): dim3=Variable(('c', ), [1, 2, 1])) expected = expected.assign_coords(a=idx_t['a'], b=idx_2['b'], c=idx_3['c']) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) # test from sel_points data = Dataset({'foo': (('x', 'y'), np.arange(9).reshape(3, 3))}) @@ -1389,22 +1386,22 @@ def test_sel_fancy(self): 'y': Variable(('points', ), [0, 1, 2])}) actual = data.sel(x=Variable(('points', ), [0, 1, 2]), y=Variable(('points', ), [0, 1, 2])) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) expected.coords.update({'x': ('points', [0, 1, 2]), 'y': ('points', [0, 1, 2])}) actual = data.sel(x=Variable(('points', ), [0.1, 1.1, 2.5]), y=Variable(('points', ), [0, 1.2, 2.0]), method='pad') - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) idx_x = DataArray([0, 1, 2], dims=['a'], coords={'a': ['a', 'b', 'c']}) idx_y = DataArray([0, 2, 1], dims=['b'], coords={'b': [0, 3, 6]}) expected_ary = data['foo'][[0, 1, 2], [0, 2, 1]] actual = data.sel(x=idx_x, y=idx_y) - self.assertArrayEqual(expected_ary, actual['foo']) - self.assertDataArrayIdentical(actual['a'].drop('x'), idx_x['a']) - self.assertDataArrayIdentical(actual['b'].drop('y'), idx_y['b']) + assert_array_equal(expected_ary, actual['foo']) + assert_identical(actual['a'].drop('x'), idx_x['a']) + assert_identical(actual['b'].drop('y'), idx_y['b']) with pytest.raises(KeyError): data.sel_points(x=[2.5], y=[2.0], method='pad', tolerance=1e-3) @@ -1414,17 +1411,17 @@ def test_sel_method(self): expected = data.sel(dim2=1) actual = data.sel(dim2=0.95, method='nearest') - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) actual = data.sel(dim2=0.95, method='nearest', tolerance=1) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) with pytest.raises(KeyError): actual = data.sel(dim2=np.pi, method='nearest', tolerance=0) expected = data.sel(dim2=[1.5]) actual = data.sel(dim2=[1.45], method='backfill') - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) with raises_regex(NotImplementedError, 'slice objects'): data.sel(dim2=slice(1, 3), method='ffill') @@ -1441,7 +1438,7 @@ def test_loc(self): data = create_test_data() expected = data.sel(dim3='a') actual = data.loc[dict(dim3='a')] - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) with raises_regex(TypeError, 'can only lookup dict'): data.loc['a'] with pytest.raises(TypeError): @@ -1458,13 +1455,13 @@ def test_sel(lab_indexer, pos_indexer, replaced_idx=False, ds = mdata.sel(x=lab_indexer) expected_ds = mdata.isel(x=pos_indexer) if not replaced_idx: - self.assertDatasetIdentical(ds, expected_ds) + assert_identical(ds, expected_ds) else: if renamed_dim: - self.assertEqual(ds['var'].dims[0], renamed_dim) + assert ds['var'].dims[0] == renamed_dim ds = ds.rename({renamed_dim: 'x'}) - self.assertVariableIdentical(ds['var'].variable, - expected_ds['var'].variable) + assert_identical(ds['var'].variable, + expected_ds['var'].variable) self.assertVariableNotEqual(ds['x'], expected_ds['x']) test_sel(('a', 1, -1), 0) @@ -1480,17 +1477,17 @@ def test_sel(lab_indexer, pos_indexer, replaced_idx=False, renamed_dim='three') test_sel({'one': 'a'}, range(4), replaced_idx=True) - self.assertDatasetIdentical(mdata.loc[{'x': {'one': 'a'}}], - mdata.sel(x={'one': 'a'})) - self.assertDatasetIdentical(mdata.loc[{'x': 'a'}], - mdata.sel(x='a')) - self.assertDatasetIdentical(mdata.loc[{'x': ('a', 1)}], - mdata.sel(x=('a', 1))) - self.assertDatasetIdentical(mdata.loc[{'x': ('a', 1, -1)}], - mdata.sel(x=('a', 1, -1))) + assert_identical(mdata.loc[{'x': {'one': 'a'}}], + mdata.sel(x={'one': 'a'})) + assert_identical(mdata.loc[{'x': 'a'}], + mdata.sel(x='a')) + assert_identical(mdata.loc[{'x': ('a', 1)}], + mdata.sel(x=('a', 1))) + assert_identical(mdata.loc[{'x': ('a', 1, -1)}], + mdata.sel(x=('a', 1, -1))) - self.assertDatasetIdentical(mdata.sel(x={'one': 'a', 'two': 1}), - mdata.sel(one='a', two=1)) + assert_identical(mdata.sel(x={'one': 'a', 'two': 1}), + mdata.sel(one='a', two=1)) def test_reindex_like(self): data = create_test_data() @@ -1498,11 +1495,11 @@ def test_reindex_like(self): expected = data.isel(dim1=slice(10), time=slice(13)) actual = data.reindex_like(expected) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) expected = data.copy(deep=True) expected['dim3'] = ('dim3', list('cdefghijkl')) - expected['var3'][:-2] = expected['var3'][2:] + expected['var3'][:-2] = expected['var3'][2:].values expected['var3'][-2:] = np.nan expected['letters'] = expected['letters'].astype(object) expected['letters'][-2:] = np.nan @@ -1510,21 +1507,21 @@ def test_reindex_like(self): expected['numbers'][:-2] = expected['numbers'][2:].values expected['numbers'][-2:] = np.nan actual = data.reindex_like(expected) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) def test_reindex(self): data = create_test_data() - self.assertDatasetIdentical(data, data.reindex()) + assert_identical(data, data.reindex()) expected = data.assign_coords(dim1=data['dim1']) actual = data.reindex(dim1=data['dim1']) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) actual = data.reindex(dim1=data['dim1'].values) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) actual = data.reindex(dim1=data['dim1'].to_index()) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) with raises_regex( ValueError, 'cannot reindex or align along dimension'): @@ -1532,12 +1529,12 @@ def test_reindex(self): expected = data.isel(dim2=slice(5)) actual = data.reindex(dim2=data['dim2'][:5]) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) # test dict-like argument actual = data.reindex({'dim2': data['dim2']}) expected = data - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) with raises_regex(ValueError, 'cannot specify both'): data.reindex({'x': 0}, x=0) with raises_regex(ValueError, 'dictionary'): @@ -1550,7 +1547,7 @@ def test_reindex(self): # out of order expected = data.sel(dim2=data['dim2'][:5:-1]) actual = data.reindex(dim2=data['dim2'][:5:-1]) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) # regression test for #279 expected = Dataset({'x': ('time', np.random.randn(5))}, @@ -1558,7 +1555,7 @@ def test_reindex(self): time2 = DataArray(np.arange(5), dims="time2") with pytest.warns(FutureWarning): actual = expected.reindex(time=time2) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) # another regression test ds = Dataset({'foo': (['x', 'y'], np.zeros((3, 4)))}, @@ -1567,7 +1564,7 @@ def test_reindex(self): {'x': [0, 1, 3], 'y': [0, 1]}) expected['foo'][-1] = np.nan actual = ds.reindex(x=[0, 1, 3], y=[0, 1]) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_reindex_warning(self): data = create_test_data() @@ -1596,57 +1593,62 @@ def test_reindex_method(self): y = [-0.5, 0.5, 1.5] actual = ds.reindex(y=y, method='backfill') expected = Dataset({'x': ('y', [10, 20, np.nan]), 'y': y}) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) actual = ds.reindex(y=y, method='backfill', tolerance=0.1) expected = Dataset({'x': ('y', 3 * [np.nan]), 'y': y}) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) actual = ds.reindex(y=y, method='pad') expected = Dataset({'x': ('y', [np.nan, 10, 20]), 'y': y}) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) alt = Dataset({'y': y}) actual = ds.reindex_like(alt, method='pad') - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_align(self): left = create_test_data() right = left.copy(deep=True) right['dim3'] = ('dim3', list('cdefghijkl')) - right['var3'][:-2] = right['var3'][2:] + right['var3'][:-2] = right['var3'][2:].values right['var3'][-2:] = np.random.randn(*right['var3'][-2:].shape) - right['numbers'][:-2] = right['numbers'][2:] + right['numbers'][:-2] = right['numbers'][2:].values right['numbers'][-2:] = -10 intersection = list('cdefghij') union = list('abcdefghijkl') left2, right2 = align(left, right, join='inner') - self.assertArrayEqual(left2['dim3'], intersection) - self.assertDatasetIdentical(left2, right2) + assert_array_equal(left2['dim3'], intersection) + assert_identical(left2, right2) left2, right2 = align(left, right, join='outer') - self.assertVariableEqual(left2['dim3'].variable, right2['dim3'].variable) - self.assertArrayEqual(left2['dim3'], union) - self.assertDatasetIdentical(left2.sel(dim3=intersection), - right2.sel(dim3=intersection)) - self.assertTrue(np.isnan(left2['var3'][-2:]).all()) - self.assertTrue(np.isnan(right2['var3'][:2]).all()) + + assert_array_equal(left2['dim3'], union) + assert_equal(left2['dim3'].variable, right2['dim3'].variable) + + assert_identical(left2.sel(dim3=intersection), + right2.sel(dim3=intersection)) + assert np.isnan(left2['var3'][-2:]).all() + assert np.isnan(right2['var3'][:2]).all() left2, right2 = align(left, right, join='left') - self.assertVariableEqual(left2['dim3'].variable, right2['dim3'].variable) - self.assertVariableEqual(left2['dim3'].variable, left['dim3'].variable) - self.assertDatasetIdentical(left2.sel(dim3=intersection), - right2.sel(dim3=intersection)) - self.assertTrue(np.isnan(right2['var3'][:2]).all()) + assert_equal(left2['dim3'].variable, right2['dim3'].variable) + assert_equal(left2['dim3'].variable, left['dim3'].variable) + + assert_identical(left2.sel(dim3=intersection), + right2.sel(dim3=intersection)) + assert np.isnan(right2['var3'][:2]).all() left2, right2 = align(left, right, join='right') - self.assertVariableEqual(left2['dim3'].variable, right2['dim3'].variable) - self.assertVariableEqual(left2['dim3'].variable, right['dim3'].variable) - self.assertDatasetIdentical(left2.sel(dim3=intersection), - right2.sel(dim3=intersection)) - self.assertTrue(np.isnan(left2['var3'][-2:]).all()) + assert_equal(left2['dim3'].variable, right2['dim3'].variable) + assert_equal(left2['dim3'].variable, right['dim3'].variable) + + assert_identical(left2.sel(dim3=intersection), + right2.sel(dim3=intersection)) + + assert np.isnan(left2['var3'][-2:]).all() with raises_regex(ValueError, 'invalid value for join'): align(left, right, join='foobar') @@ -1658,8 +1660,8 @@ def test_align_exact(self): right = xr.Dataset(coords={'x': [1, 2]}) left1, left2 = xr.align(left, left, join='exact') - self.assertDatasetIdentical(left1, left) - self.assertDatasetIdentical(left2, left) + assert_identical(left1, left) + assert_identical(left2, left) with raises_regex(ValueError, 'indexes .* not equal'): xr.align(left, right, join='exact') @@ -1679,33 +1681,35 @@ def test_align_exclude(self): {'bar': DataArray([[1, 2], [np.nan, np.nan], [3, 4]], dims=['x', 'y'], coords={'x': [1, 2, 3], 'y': [5, 6]})}) - self.assertDatasetIdentical(expected_x2, x2) - self.assertDatasetIdentical(expected_y2, y2) + assert_identical(expected_x2, x2) + assert_identical(expected_y2, y2) def test_align_nocopy(self): x = Dataset({'foo': DataArray([1, 2, 3], coords=[('x', [1, 2, 3])])}) y = Dataset({'foo': DataArray([1, 2], coords=[('x', [1, 2])])}) expected_x2 = x expected_y2 = Dataset({'foo': DataArray([1, 2, np.nan], - coords=[('x', [1, 2, 3])])}) + coords=[('x', [1, 2, 3])])}) x2, y2 = align(x, y, copy=False, join='outer') - self.assertDatasetIdentical(expected_x2, x2) - self.assertDatasetIdentical(expected_y2, y2) + assert_identical(expected_x2, x2) + assert_identical(expected_y2, y2) assert source_ndarray(x['foo'].data) is source_ndarray(x2['foo'].data) x2, y2 = align(x, y, copy=True, join='outer') - self.assertDatasetIdentical(expected_x2, x2) - self.assertDatasetIdentical(expected_y2, y2) - assert source_ndarray(x['foo'].data) is not source_ndarray(x2['foo'].data) + assert source_ndarray(x['foo'].data) is not \ + source_ndarray(x2['foo'].data) + assert_identical(expected_x2, x2) + assert_identical(expected_y2, y2) def test_align_indexes(self): x = Dataset({'foo': DataArray([1, 2, 3], dims='x', - coords=[('x', [1, 2, 3])])}) + coords=[('x', [1, 2, 3])])}) x2, = align(x, indexes={'x': [2, 3, 1]}) expected_x2 = Dataset({'foo': DataArray([2, 3, 1], dims='x', - coords={'x': [2, 3, 1]})}) - self.assertDatasetIdentical(expected_x2, x2) + coords={'x': [2, 3, 1]})}) + + assert_identical(expected_x2, x2) def test_align_non_unique(self): x = Dataset({'foo': ('x', [3, 4, 5]), 'x': [0, 0, 1]}) @@ -1722,23 +1726,23 @@ def test_broadcast(self): expected = Dataset({'foo': (('x', 'y'), [[0, 0]]), 'bar': (('x', 'y'), [[1, 1]]), 'baz': (('x', 'y'), [[2, 3]])}, - {'c': ('x', [4])}) + {'c': ('x', [4])}) actual, = broadcast(ds) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) ds_x = Dataset({'foo': ('x', [1])}) ds_y = Dataset({'bar': ('y', [2, 3])}) expected_x = Dataset({'foo': (('x', 'y'), [[1, 1]])}) expected_y = Dataset({'bar': (('x', 'y'), [[2, 3]])}) actual_x, actual_y = broadcast(ds_x, ds_y) - self.assertDatasetIdentical(expected_x, actual_x) - self.assertDatasetIdentical(expected_y, actual_y) + assert_identical(expected_x, actual_x) + assert_identical(expected_y, actual_y) array_y = ds_y['bar'] expected_y = expected_y['bar'] actual_x, actual_y = broadcast(ds_x, array_y) - self.assertDatasetIdentical(expected_x, actual_x) - self.assertDataArrayIdentical(expected_y, actual_y) + assert_identical(expected_x, actual_x) + assert_identical(expected_y, actual_y) def test_broadcast_nocopy(self): # Test that data is not copied if not needed @@ -1746,35 +1750,43 @@ def test_broadcast_nocopy(self): y = Dataset({'bar': ('y', [2, 3])}) actual_x, = broadcast(x) - self.assertDatasetIdentical(x, actual_x) - assert source_ndarray(actual_x['foo'].data) is source_ndarray(x['foo'].data) + assert_identical(x, actual_x) + assert source_ndarray(actual_x['foo'].data) is source_ndarray( + x['foo'].data) actual_x, actual_y = broadcast(x, y) - self.assertDatasetIdentical(x, actual_x) - assert source_ndarray(actual_x['foo'].data) is source_ndarray(x['foo'].data) + assert_identical(x, actual_x) + assert source_ndarray(actual_x['foo'].data) is source_ndarray( + x['foo'].data) def test_broadcast_exclude(self): x = Dataset({ - 'foo': DataArray([[1, 2],[3, 4]], dims=['x', 'y'], coords={'x': [1, 2], 'y': [3, 4]}), + 'foo': DataArray([[1, 2], [3, 4]], dims=['x', 'y'], + coords={'x': [1, 2], 'y': [3, 4]}), 'bar': DataArray(5), }) y = Dataset({ - 'foo': DataArray([[1, 2]], dims=['z', 'y'], coords={'z': [1], 'y': [5, 6]}), + 'foo': DataArray([[1, 2]], dims=['z', 'y'], + coords={'z': [1], 'y': [5, 6]}), }) x2, y2 = broadcast(x, y, exclude=['y']) expected_x2 = Dataset({ - 'foo': DataArray([[[1, 2]], [[3, 4]]], dims=['x', 'z', 'y'], coords={'z': [1], 'x': [1, 2], 'y': [3, 4]}), - 'bar': DataArray([[5], [5]], dims=['x', 'z'], coords={'x': [1, 2], 'z': [1]}), + 'foo': DataArray([[[1, 2]], [[3, 4]]], dims=['x', 'z', 'y'], + coords={'z': [1], 'x': [1, 2], 'y': [3, 4]}), + 'bar': DataArray([[5], [5]], dims=['x', 'z'], + coords={'x': [1, 2], 'z': [1]}), }) expected_y2 = Dataset({ - 'foo': DataArray([[[1, 2]], [[1, 2]]], dims=['x', 'z', 'y'], coords={'z': [1], 'x': [1, 2], 'y': [5, 6]}), + 'foo': DataArray([[[1, 2]], [[1, 2]]], dims=['x', 'z', 'y'], + coords={'z': [1], 'x': [1, 2], 'y': [5, 6]}), }) - self.assertDatasetIdentical(expected_x2, x2) - self.assertDatasetIdentical(expected_y2, y2) + assert_identical(expected_x2, x2) + assert_identical(expected_y2, y2) def test_broadcast_misaligned(self): - x = Dataset({'foo': DataArray([1, 2, 3], coords=[('x', [-1, -2, -3])])}) + x = Dataset({'foo': DataArray([1, 2, 3], + coords=[('x', [-1, -2, -3])])}) y = Dataset({'bar': DataArray([[1, 2], [3, 4]], dims=['y', 'x'], coords={'y': [1, 2], 'x': [10, -3]})}) x2, y2 = broadcast(x, y) @@ -1786,33 +1798,33 @@ def test_broadcast_misaligned(self): {'bar': DataArray( [[2, 4], [np.nan, np.nan], [np.nan, np.nan], [1, 3]], dims=['x', 'y'], coords={'y': [1, 2], 'x': [-3, -2, -1, 10]})}) - self.assertDatasetIdentical(expected_x2, x2) - self.assertDatasetIdentical(expected_y2, y2) + assert_identical(expected_x2, x2) + assert_identical(expected_y2, y2) def test_variable_indexing(self): data = create_test_data() v = data['var1'] d1 = data['dim1'] d2 = data['dim2'] - self.assertVariableEqual(v, v[d1.values]) - self.assertVariableEqual(v, v[d1]) - self.assertVariableEqual(v[:3], v[d1 < 3]) - self.assertVariableEqual(v[:, 3:], v[:, d2 >= 1.5]) - self.assertVariableEqual(v[:3, 3:], v[d1 < 3, d2 >= 1.5]) - self.assertVariableEqual(v[:3, :2], v[range(3), range(2)]) - self.assertVariableEqual(v[:3, :2], v.loc[d1[:3], d2[:2]]) + assert_equal(v, v[d1.values]) + assert_equal(v, v[d1]) + assert_equal(v[:3], v[d1 < 3]) + assert_equal(v[:, 3:], v[:, d2 >= 1.5]) + assert_equal(v[:3, 3:], v[d1 < 3, d2 >= 1.5]) + assert_equal(v[:3, :2], v[range(3), range(2)]) + assert_equal(v[:3, :2], v.loc[d1[:3], d2[:2]]) def test_drop_variables(self): data = create_test_data() - self.assertDatasetIdentical(data, data.drop([])) + assert_identical(data, data.drop([])) expected = Dataset(dict((k, data[k]) for k in data.variables if k != 'time')) actual = data.drop('time') - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) actual = data.drop(['time']) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) with raises_regex(ValueError, 'cannot be found'): data.drop('not_found_here') @@ -1823,11 +1835,11 @@ def test_drop_index_labels(self): actual = data.drop(['a'], 'x') expected = data.isel(x=[1]) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) actual = data.drop(['a', 'b'], 'x') expected = data.isel(x=slice(0, 0)) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) with pytest.raises(ValueError): # not contained in axis @@ -1841,8 +1853,8 @@ def test_copy(self): data = create_test_data() for copied in [data.copy(deep=False), copy(data)]: - self.assertDatasetIdentical(data, copied) - self.assertEqual(data.encoding, copied.encoding) + assert_identical(data, copied) + assert data.encoding == copied.encoding # Note: IndexVariable objects with string dtype are always # copied because of xarray.core.util.safe_cast_to_index. # Limiting the test to data variables. @@ -1851,13 +1863,13 @@ def test_copy(self): v1 = copied.variables[k] assert source_ndarray(v0.data) is source_ndarray(v1.data) copied['foo'] = ('z', np.arange(5)) - self.assertNotIn('foo', data) + assert 'foo' not in data for copied in [data.copy(deep=True), deepcopy(data)]: - self.assertDatasetIdentical(data, copied) + assert_identical(data, copied) for k, v0 in data.variables.items(): v1 = copied.variables[k] - self.assertIsNot(v0, v1) + assert v0 is not v1 def test_rename(self): data = create_test_data() @@ -1874,13 +1886,13 @@ def test_rename(self): if name in dims: dims[dims.index(name)] = newname - self.assertVariableEqual(Variable(dims, v.values, v.attrs), - renamed[k].variable.to_base_variable()) - self.assertEqual(v.encoding, renamed[k].encoding) - self.assertEqual(type(v), type(renamed.variables[k])) + assert_equal(Variable(dims, v.values, v.attrs), + renamed[k].variable.to_base_variable()) + assert v.encoding == renamed[k].encoding + assert type(v) == type(renamed.variables[k]) # noqa: E721 - self.assertTrue('var1' not in renamed) - self.assertTrue('dim2' not in renamed) + assert 'var1' not in renamed + assert 'dim2' not in renamed with raises_regex(ValueError, "cannot rename 'not_a_var'"): data.rename({'not_a_var': 'nada'}) @@ -1909,7 +1921,7 @@ def test_rename_same_name(self): data = create_test_data() newnames = {'var1': 'var1', 'dim2': 'dim2'} renamed = data.rename(newnames) - self.assertDatasetIdentical(renamed, data) + assert_identical(renamed, data) def test_rename_inplace(self): times = pd.date_range('2000-01-01', periods=3) @@ -1917,26 +1929,27 @@ def test_rename_inplace(self): copied = data.copy() renamed = data.rename({'x': 'y'}) data.rename({'x': 'y'}, inplace=True) - self.assertDatasetIdentical(data, renamed) - self.assertFalse(data.equals(copied)) + assert_identical(data, renamed) + assert not data.equals(copied) assert data.dims == {'y': 3, 't': 3} # check virtual variables - self.assertArrayEqual(data['t.dayofyear'], [1, 2, 3]) + assert_array_equal(data['t.dayofyear'], [1, 2, 3]) def test_swap_dims(self): original = Dataset({'x': [1, 2, 3], 'y': ('x', list('abc')), 'z': 42}) - expected = Dataset({'z': 42}, {'x': ('y', [1, 2, 3]), 'y': list('abc')}) + expected = Dataset({'z': 42}, + {'x': ('y', [1, 2, 3]), 'y': list('abc')}) actual = original.swap_dims({'x': 'y'}) - self.assertDatasetIdentical(expected, actual) - self.assertIsInstance(actual.variables['y'], IndexVariable) - self.assertIsInstance(actual.variables['x'], Variable) + assert_identical(expected, actual) + assert isinstance(actual.variables['y'], IndexVariable) + assert isinstance(actual.variables['x'], Variable) roundtripped = actual.swap_dims({'y': 'x'}) - self.assertDatasetIdentical(original.set_coords('y'), roundtripped) + assert_identical(original.set_coords('y'), roundtripped) actual = original.copy() actual.swap_dims({'x': 'y'}, inplace=True) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) with raises_regex(ValueError, 'cannot swap'): original.swap_dims({'y': 'x'}) @@ -1976,10 +1989,10 @@ def test_expand_dims(self): 'b': np.linspace(0, 1, 4), 'c': np.linspace(0, 1, 5)}, attrs={'key': 'entry'}) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) # make sure squeeze restores the original data set. roundtripped = actual.squeeze('z') - self.assertDatasetIdentical(original, roundtripped) + assert_identical(original, roundtripped) # another test with a negative axis actual = original.expand_dims(['z'], [-1]) @@ -1989,10 +2002,10 @@ def test_expand_dims(self): 'b': np.linspace(0, 1, 4), 'c': np.linspace(0, 1, 5)}, attrs={'key': 'entry'}) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) # make sure squeeze restores the original data set. roundtripped = actual.squeeze('z') - self.assertDatasetIdentical(original, roundtripped) + assert_identical(original, roundtripped) def test_set_index(self): expected = create_test_multiindex() @@ -2002,16 +2015,16 @@ def test_set_index(self): ds = Dataset({}, coords=coords) obj = ds.set_index(x=mindex.names) - self.assertDatasetIdentical(obj, expected) + assert_identical(obj, expected) ds.set_index(x=mindex.names, inplace=True) - self.assertDatasetIdentical(ds, expected) + assert_identical(ds, expected) # ensure set_index with no existing index and a single data var given # doesn't return multi-index ds = Dataset(data_vars={'x_var': ('x', [0, 1, 2])}) expected = Dataset(coords={'x': [0, 1, 2]}) - self.assertDataArrayIdentical(ds.set_index(x='x_var'), expected) + assert_identical(ds.set_index(x='x_var'), expected) def test_reset_index(self): ds = create_test_multiindex() @@ -2021,10 +2034,10 @@ def test_reset_index(self): expected = Dataset({}, coords=coords) obj = ds.reset_index('x') - self.assertDatasetIdentical(obj, expected) + assert_identical(obj, expected) ds.reset_index('x', inplace=True) - self.assertDatasetIdentical(ds, expected) + assert_identical(ds, expected) def test_reorder_levels(self): ds = create_test_multiindex() @@ -2033,10 +2046,10 @@ def test_reorder_levels(self): expected = Dataset({}, coords={'x': midx}) reindexed = ds.reorder_levels(x=['level_2', 'level_1']) - self.assertDatasetIdentical(reindexed, expected) + assert_identical(reindexed, expected) ds.reorder_levels(x=['level_2', 'level_1'], inplace=True) - self.assertDatasetIdentical(ds, expected) + assert_identical(ds, expected) ds = Dataset({}, coords={'x': [1, 2]}) with raises_regex(ValueError, 'has no MultiIndex'): @@ -2053,7 +2066,7 @@ def test_stack(self): 'b': ('z', [0, 1, 2, 3]), 'z': exp_index}) actual = ds.stack(z=['x', 'y']) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) exp_index = pd.MultiIndex.from_product([['a', 'b'], [0, 1]], names=['y', 'x']) @@ -2061,7 +2074,7 @@ def test_stack(self): 'b': ('z', [0, 2, 1, 3]), 'z': exp_index}) actual = ds.stack(z=['y', 'x']) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_unstack(self): index = pd.MultiIndex.from_product([[0, 1], ['a', 'b']], @@ -2071,7 +2084,7 @@ def test_unstack(self): 'x': [0, 1], 'y': ['a', 'b']}) actual = ds.unstack('z') - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) def test_unstack_errors(self): ds = Dataset({'x': [1, 2, 3]}) @@ -2097,22 +2110,22 @@ def test_update(self): var2 = Variable('dim1', np.arange(8)) actual = data.update({'var2': var2}) expected['var2'] = var2 - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) actual = data.copy() actual_result = actual.update(data, inplace=True) - self.assertIs(actual_result, actual) - self.assertDatasetIdentical(expected, actual) + assert actual_result is actual + assert_identical(expected, actual) actual = data.update(data, inplace=False) expected = data - self.assertIsNot(actual, expected) - self.assertDatasetIdentical(expected, actual) + assert actual is not expected + assert_identical(expected, actual) other = Dataset(attrs={'new': 'attr'}) actual = data.copy() actual.update(other) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_update_auto_align(self): ds = Dataset({'x': ('t', [3, 4])}, {'t': [0, 1]}) @@ -2124,19 +2137,19 @@ def test_update_auto_align(self): with raises_regex(ValueError, 'conflicting sizes'): actual.update(other) actual.update(Dataset(other)) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) actual = ds.copy() other = Dataset({'y': ('t', [5]), 't': [100]}) actual.update(other) expected = Dataset({'x': ('t', [3, 4]), 'y': ('t', [np.nan] * 2)}, {'t': [0, 1]}) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_getitem(self): data = create_test_data() - self.assertIsInstance(data['var1'], DataArray) - self.assertVariableEqual(data['var1'].variable, data.variables['var1']) + assert isinstance(data['var1'], DataArray) + assert_equal(data['var1'].variable, data.variables['var1']) with pytest.raises(KeyError): data['notfound'] with pytest.raises(KeyError): @@ -2144,25 +2157,25 @@ def test_getitem(self): actual = data[['var1', 'var2']] expected = Dataset({'var1': data['var1'], 'var2': data['var2']}) - self.assertDatasetEqual(expected, actual) + assert_equal(expected, actual) actual = data['numbers'] expected = DataArray(data['numbers'].variable, {'dim3': data['dim3'], 'numbers': data['numbers']}, dims='dim3', name='numbers') - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = data[dict(dim1=0)] expected = data.isel(dim1=0) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_getitem_hashable(self): data = create_test_data() data[(3, 4)] = data['var1'] + 1 expected = data['var1'] + 1 expected.name = (3, 4) - self.assertDataArrayIdentical(expected, data[(3, 4)]) + assert_identical(expected, data[(3, 4)]) with raises_regex(KeyError, "('var1', 'var2')"): data[('var1', 'var2')] @@ -2170,33 +2183,33 @@ def test_virtual_variables_default_coords(self): dataset = Dataset({'foo': ('x', range(10))}) expected = DataArray(range(10), dims='x', name='x') actual = dataset['x'] - self.assertDataArrayIdentical(expected, actual) - self.assertIsInstance(actual.variable, IndexVariable) + assert_identical(expected, actual) + assert isinstance(actual.variable, IndexVariable) actual = dataset[['x', 'foo']] expected = dataset.assign_coords(x=range(10)) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_virtual_variables_time(self): # access virtual variables data = create_test_data() expected = DataArray(1 + np.arange(20), coords=[data['time']], dims='time', name='dayofyear') - self.assertDataArrayIdentical(expected, data['time.dayofyear']) - self.assertArrayEqual(data['time.month'].values, - data.variables['time'].to_index().month) - self.assertArrayEqual(data['time.season'].values, 'DJF') + + assert_array_equal(data['time.month'].values, + data.variables['time'].to_index().month) + assert_array_equal(data['time.season'].values, 'DJF') # test virtual variable math - self.assertArrayEqual(data['time.dayofyear'] + 1, 2 + np.arange(20)) - self.assertArrayEqual(np.sin(data['time.dayofyear']), - np.sin(1 + np.arange(20))) + assert_array_equal(data['time.dayofyear'] + 1, 2 + np.arange(20)) + assert_array_equal(np.sin(data['time.dayofyear']), + np.sin(1 + np.arange(20))) # ensure they become coordinates expected = Dataset({}, {'dayofyear': data['time.dayofyear']}) actual = data[['time.dayofyear']] - self.assertDatasetEqual(expected, actual) + assert_equal(expected, actual) # non-coordinate variables ds = Dataset({'t': ('x', pd.date_range('2000-01-01', periods=3))}) - self.assertTrue((ds['t.year'] == 2000).all()) + assert (ds['t.year'] == 2000).all() def test_virtual_variable_same_name(self): # regression test for GH367 @@ -2204,14 +2217,14 @@ def test_virtual_variable_same_name(self): data = Dataset({'time': times}) actual = data['time.time'] expected = DataArray(times.time, [('time', times)], name='time') - self.assertDataArrayIdentical(actual, expected) + assert_identical(actual, expected) def test_virtual_variable_multiindex(self): # access multi-index levels as virtual variables data = create_test_multiindex() expected = DataArray(['a', 'a', 'b', 'b'], name='level_1', coords=[data['x'].to_index()], dims='x') - self.assertDataArrayIdentical(expected, data['level_1']) + assert_identical(expected, data['level_1']) # combine multi-index level and datetime dr_index = pd.date_range('1/1/2011', periods=4, freq='H') @@ -2220,21 +2233,22 @@ def test_virtual_variable_multiindex(self): data = Dataset({}, {'x': mindex}) expected = DataArray(mindex.get_level_values('level_date').hour, name='hour', coords=[mindex], dims='x') - self.assertDataArrayIdentical(expected, data['level_date.hour']) + assert_identical(expected, data['level_date.hour']) # attribute style access - self.assertDataArrayIdentical(data.level_str, data['level_str']) + assert_identical(data.level_str, data['level_str']) def test_time_season(self): ds = Dataset({'t': pd.date_range('2000-01-01', periods=12, freq='M')}) - expected = ['DJF'] * 2 + ['MAM'] * 3 + ['JJA'] * 3 + ['SON'] * 3 + ['DJF'] - self.assertArrayEqual(expected, ds['t.season']) + seas = ['DJF'] * 2 + ['MAM'] * 3 + ['JJA'] * 3 + ['SON'] * 3 + ['DJF'] + assert_array_equal(seas, ds['t.season']) def test_slice_virtual_variable(self): data = create_test_data() - self.assertVariableEqual(data['time.dayofyear'][:10].variable, - Variable(['time'], 1 + np.arange(10))) - self.assertVariableEqual(data['time.dayofyear'][0].variable, Variable([], 1)) + assert_equal(data['time.dayofyear'][:10].variable, + Variable(['time'], 1 + np.arange(10))) + assert_equal( + data['time.dayofyear'][0].variable, Variable([], 1)) def test_setitem(self): # assign a variable @@ -2243,24 +2257,24 @@ def test_setitem(self): data1['A'] = var data2 = data1.copy() data2['A'] = var - self.assertDatasetIdentical(data1, data2) + assert_identical(data1, data2) # assign a dataset array dv = 2 * data2['A'] data1['B'] = dv.variable data2['B'] = dv - self.assertDatasetIdentical(data1, data2) + assert_identical(data1, data2) # can't assign an ND array without dimensions with raises_regex(ValueError, - 'without explicit dimension names'): + 'without explicit dimension names'): data2['C'] = var.values.reshape(2, 4) # but can assign a 1D array data1['C'] = var.values data2['C'] = ('C', var.values) - self.assertDatasetIdentical(data1, data2) + assert_identical(data1, data2) # can assign a scalar data1['scalar'] = 0 data2['scalar'] = ([], 0) - self.assertDatasetIdentical(data1, data2) + assert_identical(data1, data2) # can't use the same dimension name as a scalar var with raises_regex(ValueError, 'already exists as a scalar'): data1['newvar'] = ('scalar', [3, 4, 5]) @@ -2269,7 +2283,7 @@ def test_setitem(self): data1['dim1'] = data1['dim1'][:5] # override an existing value data1['A'] = 3 * data2['A'] - self.assertVariableEqual(data1['A'], 3 * data2['A']) + assert_equal(data1['A'], 3 * data2['A']) with pytest.raises(NotImplementedError): data1[{'x': 0}] = 0 @@ -2281,30 +2295,30 @@ def test_setitem_pandas(self): ds_copy = ds.copy() ds_copy['bar'] = ds['bar'].to_pandas() - self.assertDatasetEqual(ds, ds_copy) + assert_equal(ds, ds_copy) def test_setitem_auto_align(self): ds = Dataset() ds['x'] = ('y', range(3)) ds['y'] = 1 + np.arange(3) expected = Dataset({'x': ('y', range(3)), 'y': 1 + np.arange(3)}) - self.assertDatasetIdentical(ds, expected) + assert_identical(ds, expected) ds['y'] = DataArray(range(3), dims='y') expected = Dataset({'x': ('y', range(3))}, {'y': range(3)}) - self.assertDatasetIdentical(ds, expected) + assert_identical(ds, expected) ds['x'] = DataArray([1, 2], coords=[('y', [0, 1])]) expected = Dataset({'x': ('y', [1, 2, np.nan])}, {'y': range(3)}) - self.assertDatasetIdentical(ds, expected) + assert_identical(ds, expected) ds['x'] = 42 expected = Dataset({'x': 42, 'y': range(3)}) - self.assertDatasetIdentical(ds, expected) + assert_identical(ds, expected) ds['x'] = DataArray([4, 5, 6, 7], coords=[('y', [0, 1, 2, 3])]) expected = Dataset({'x': ('y', [4, 5, 6])}, {'y': range(3)}) - self.assertDatasetIdentical(ds, expected) + assert_identical(ds, expected) def test_setitem_align_new_indexes(self): ds = Dataset({'foo': ('x', [1, 2, 3])}, {'x': [0, 1, 2]}) @@ -2312,48 +2326,48 @@ def test_setitem_align_new_indexes(self): expected = Dataset({'foo': ('x', [1, 2, 3]), 'bar': ('x', [np.nan, 2, 3])}, {'x': [0, 1, 2]}) - self.assertDatasetIdentical(ds, expected) + assert_identical(ds, expected) def test_assign(self): ds = Dataset() actual = ds.assign(x=[0, 1, 2], y=2) expected = Dataset({'x': [0, 1, 2], 'y': 2}) - self.assertDatasetIdentical(actual, expected) - self.assertEqual(list(actual.variables), ['x', 'y']) - self.assertDatasetIdentical(ds, Dataset()) + assert_identical(actual, expected) + assert list(actual.variables) == ['x', 'y'] + assert_identical(ds, Dataset()) actual = actual.assign(y=lambda ds: ds.x ** 2) expected = Dataset({'y': ('x', [0, 1, 4]), 'x': [0, 1, 2]}) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) actual = actual.assign_coords(z=2) expected = Dataset({'y': ('x', [0, 1, 4])}, {'z': 2, 'x': [0, 1, 2]}) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) ds = Dataset({'a': ('x', range(3))}, {'b': ('x', ['A'] * 2 + ['B'])}) actual = ds.groupby('b').assign(c=lambda ds: 2 * ds.a) expected = ds.merge({'c': ('x', [0, 2, 4])}) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) actual = ds.groupby('b').assign(c=lambda ds: ds.a.sum()) expected = ds.merge({'c': ('x', [1, 1, 2])}) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) actual = ds.groupby('b').assign_coords(c=lambda ds: ds.a.sum()) expected = expected.set_coords('c') - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) def test_assign_attrs(self): expected = Dataset(attrs=dict(a=1, b=2)) new = Dataset() actual = new.assign_attrs(a=1, b=2) - self.assertDatasetIdentical(actual, expected) - self.assertEqual(new.attrs, {}) + assert_identical(actual, expected) + assert new.attrs == {} expected.attrs['c'] = 3 new_actual = actual.assign_attrs({'c': 3}) - self.assertDatasetIdentical(new_actual, expected) - self.assertEqual(actual.attrs, dict(a=1, b=2)) + assert_identical(new_actual, expected) + assert actual.attrs == dict(a=1, b=2) def test_assign_multiindex_level(self): data = create_test_multiindex() @@ -2369,15 +2383,15 @@ def test_setitem_original_non_unique_index(self): actual = original.copy() actual['x'] = list(range(5)) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) actual = original.copy() actual['x'] = ('x', list(range(5))) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) actual = original.copy() actual.coords['x'] = list(range(5)) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) def test_setitem_both_non_unique_index(self): # regression test for GH956 @@ -2388,7 +2402,7 @@ def test_setitem_both_non_unique_index(self): expected = Dataset({'first': array, 'second': array}) actual = array.rename('first').to_dataset() actual['second'] = array - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_setitem_multiindex_level(self): data = create_test_multiindex() @@ -2404,7 +2418,7 @@ def test_delitem(self): del data['numbers'] self.assertItemsEqual(data.variables, all_items - set(['var1', 'numbers'])) - self.assertNotIn('numbers', data.coords) + assert 'numbers' not in data.coords def test_squeeze(self): data = Dataset({'foo': (['x', 'y', 'z'], [[[1], [2]]])}) @@ -2414,7 +2428,7 @@ def get_args(v): expected = Dataset(dict((k, v.squeeze(*get_args(v))) for k, v in iteritems(data.variables))) expected.set_coords(data.coords, inplace=True) - self.assertDatasetIdentical(expected, data.squeeze(*args)) + assert_identical(expected, data.squeeze(*args)) # invalid squeeze with raises_regex(ValueError, 'cannot select a dimension'): data.squeeze('y') @@ -2423,24 +2437,24 @@ def test_squeeze_drop(self): data = Dataset({'foo': ('x', [1])}, {'x': [0]}) expected = Dataset({'foo': 1}) selected = data.squeeze(drop=True) - self.assertDatasetIdentical(expected, selected) + assert_identical(expected, selected) expected = Dataset({'foo': 1}, {'x': 0}) selected = data.squeeze(drop=False) - self.assertDatasetIdentical(expected, selected) + assert_identical(expected, selected) data = Dataset({'foo': (('x', 'y'), [[1]])}, {'x': [0], 'y': [0]}) expected = Dataset({'foo': 1}) selected = data.squeeze(drop=True) - self.assertDatasetIdentical(expected, selected) + assert_identical(expected, selected) expected = Dataset({'foo': ('x', [1])}, {'x': [0]}) selected = data.squeeze(dim='y', drop=True) - self.assertDatasetIdentical(expected, selected) + assert_identical(expected, selected) data = Dataset({'foo': (('x',), [])}, {'x': []}) selected = data.squeeze(drop=True) - self.assertDatasetIdentical(data, selected) + assert_identical(data, selected) def test_groupby(self): data = Dataset({'z': (['x', 'y'], np.random.randn(3, 5))}, @@ -2448,39 +2462,41 @@ def test_groupby(self): 'c': ('x', [0, 1, 0]), 'y': range(5)}) groupby = data.groupby('x') - self.assertEqual(len(groupby), 3) + assert len(groupby) == 3 expected_groups = {'a': 0, 'b': 1, 'c': 2} - self.assertEqual(groupby.groups, expected_groups) + assert groupby.groups == expected_groups expected_items = [('a', data.isel(x=0)), ('b', data.isel(x=1)), ('c', data.isel(x=2))] for actual, expected in zip(groupby, expected_items): - self.assertEqual(actual[0], expected[0]) - self.assertDatasetEqual(actual[1], expected[1]) + assert actual[0] == expected[0] + assert_equal(actual[1], expected[1]) + + def identity(x): + return x - identity = lambda x: x for k in ['x', 'c', 'y']: actual = data.groupby(k, squeeze=False).apply(identity) - self.assertDatasetEqual(data, actual) + assert_equal(data, actual) def test_groupby_returns_new_type(self): data = Dataset({'z': (['x', 'y'], np.random.randn(3, 5))}) actual = data.groupby('x').apply(lambda ds: ds['z']) expected = data['z'] - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = data['z'].groupby('x').apply(lambda x: x.to_dataset()) expected = data - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_groupby_iter(self): data = create_test_data() for n, (t, sub) in enumerate(list(data.groupby('dim1'))[:3]): - self.assertEqual(data['dim1'][n], t) - self.assertVariableEqual(data['var1'][n], sub['var1']) - self.assertVariableEqual(data['var2'][n], sub['var2']) - self.assertVariableEqual(data['var3'][:, n], sub['var3']) + assert data['dim1'][n] == t + assert_equal(data['var1'][n], sub['var1']) + assert_equal(data['var2'][n], sub['var2']) + assert_equal(data['var3'][:, n], sub['var3']) def test_groupby_errors(self): data = create_test_data() @@ -2500,10 +2516,10 @@ def test_groupby_reduce(self): expected = data.mean('y') expected['yonly'] = expected['yonly'].variable.set_dims({'x': 3}) actual = data.groupby('x').mean() - self.assertDatasetAllClose(expected, actual) + assert_allclose(expected, actual) actual = data.groupby('x').mean('y') - self.assertDatasetAllClose(expected, actual) + assert_allclose(expected, actual) letters = data['letters'] expected = Dataset({'xy': data['xy'].groupby(letters).mean(), @@ -2511,10 +2527,11 @@ def test_groupby_reduce(self): .set_dims({'letters': 2})), 'yonly': data['yonly'].groupby(letters).mean()}) actual = data.groupby('letters').mean() - self.assertDatasetAllClose(expected, actual) + assert_allclose(expected, actual) def test_groupby_math(self): - reorder_dims = lambda x: x.transpose('dim1', 'dim2', 'dim3', 'time') + def reorder_dims(x): + return x.transpose('dim1', 'dim2', 'dim3', 'time') ds = create_test_data() ds['dim1'] = ds['dim1'] @@ -2523,28 +2540,28 @@ def test_groupby_math(self): expected = reorder_dims(ds + ds.coords['dim1']) actual = grouped + ds.coords['dim1'] - self.assertDatasetIdentical(expected, reorder_dims(actual)) + assert_identical(expected, reorder_dims(actual)) actual = ds.coords['dim1'] + grouped - self.assertDatasetIdentical(expected, reorder_dims(actual)) + assert_identical(expected, reorder_dims(actual)) ds2 = 2 * ds expected = reorder_dims(ds + ds2) actual = grouped + ds2 - self.assertDatasetIdentical(expected, reorder_dims(actual)) + assert_identical(expected, reorder_dims(actual)) actual = ds2 + grouped - self.assertDatasetIdentical(expected, reorder_dims(actual)) + assert_identical(expected, reorder_dims(actual)) grouped = ds.groupby('numbers') zeros = DataArray([0, 0, 0, 0], [('numbers', range(4))]) expected = ((ds + Variable('dim3', np.zeros(10))) .transpose('dim3', 'dim1', 'dim2', 'time')) actual = grouped + zeros - self.assertDatasetEqual(expected, actual) + assert_equal(expected, actual) actual = zeros + grouped - self.assertDatasetEqual(expected, actual) + assert_equal(expected, actual) with raises_regex(ValueError, 'incompat.* grouped binary'): grouped + ds @@ -2569,7 +2586,7 @@ def test_groupby_math_virtual(self): actual = grouped - grouped.mean() expected = Dataset({'x': ('t', [0, 0, 0])}, ds[['t', 't.day']]) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) def test_groupby_nan(self): # nan should be excluded from groupby @@ -2577,7 +2594,7 @@ def test_groupby_nan(self): {'bar': ('x', [1, 1, 2, np.nan])}) actual = ds.groupby('bar').mean() expected = Dataset({'foo': ('bar', [1.5, 3]), 'bar': [1, 2]}) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) def test_groupby_order(self): # groupby should preserve variables order @@ -2585,13 +2602,13 @@ def test_groupby_order(self): ds = Dataset() for vn in ['a', 'b', 'c']: ds[vn] = DataArray(np.arange(10), dims=['t']) - all_vars_ref = list(ds.variables.keys()) data_vars_ref = list(ds.data_vars.keys()) ds = ds.groupby('t').mean() - all_vars = list(ds.variables.keys()) data_vars = list(ds.data_vars.keys()) - self.assertEqual(data_vars, data_vars_ref) + assert data_vars == data_vars_ref # coords are now at the end of the list, so the test below fails + # all_vars = list(ds.variables.keys()) + # all_vars_ref = list(ds.variables.keys()) # self.assertEqual(all_vars, all_vars_ref) def test_resample_and_first(self): @@ -2602,7 +2619,7 @@ def test_resample_and_first(self): actual = ds.resample(time='1D').first(keep_attrs=True) expected = ds.isel(time=[0, 4, 8]) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) # upsampling expected_time = pd.date_range('2000-01-01', freq='3H', periods=19) @@ -2611,10 +2628,10 @@ def test_resample_and_first(self): for how in ['mean', 'sum', 'first', 'last', ]: method = getattr(actual, how) result = method() - self.assertDatasetEqual(expected, result) + assert_equal(expected, result) for method in [np.mean, ]: result = actual.reduce(method) - self.assertDatasetEqual(expected, result) + assert_equal(expected, result) def test_resample_by_mean_with_keep_attrs(self): times = pd.date_range('2000-01-01', freq='6H', periods=10) @@ -2626,11 +2643,11 @@ def test_resample_by_mean_with_keep_attrs(self): resampled_ds = ds.resample(time='1D').mean(keep_attrs=True) actual = resampled_ds['bar'].attrs expected = ds['bar'].attrs - self.assertEqual(expected, actual) + assert expected == actual actual = resampled_ds.attrs expected = ds.attrs - self.assertEqual(expected, actual) + assert expected == actual def test_resample_by_mean_discarding_attrs(self): times = pd.date_range('2000-01-01', freq='6H', periods=10) @@ -2662,7 +2679,7 @@ def test_resample_drop_nondim_coords(self): ys = np.arange(3) times = pd.date_range('2000-01-01', freq='6H', periods=5) data = np.tile(np.arange(5), (6, 3, 1)) - xx, yy = np.meshgrid(xs*5, ys*2.5) + xx, yy = np.meshgrid(xs * 5, ys * 2.5) tt = np.arange(len(times), dtype=int) array = DataArray(data, {'time': times, 'x': xs, 'y': ys}, @@ -2701,7 +2718,7 @@ def test_resample_old_vs_new_api(self): new_api = getattr(resampler, method)(keep_attrs=False) with pytest.warns(DeprecationWarning): old_api = ds.resample('1D', dim='time', how=method) - self.assertDatasetIdentical(new_api, old_api) + assert_identical(new_api, old_api) def test_to_array(self): ds = Dataset(OrderedDict([('a', 1), ('b', ('x', [1, 2, 3]))]), @@ -2711,11 +2728,11 @@ def test_to_array(self): dims = ('variable', 'x') expected = DataArray(data, coords, dims, attrs=ds.attrs) actual = ds.to_array() - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) actual = ds.to_array('abc', name='foo') expected = expected.rename({'variable': 'abc'}).rename('foo') - self.assertDataArrayIdentical(expected, actual) + assert_identical(expected, actual) def test_to_and_from_dataframe(self): x = np.random.randn(10) @@ -2735,7 +2752,7 @@ def test_to_and_from_dataframe(self): assert expected.equals(actual), (expected, actual) # check roundtrip - self.assertDatasetIdentical(ds, Dataset.from_dataframe(actual)) + assert_identical(ds, Dataset.from_dataframe(actual)) # test a case with a MultiIndex w = np.random.randn(2, 3) @@ -2746,28 +2763,29 @@ def test_to_and_from_dataframe(self): names=['x', 'y']) expected = pd.DataFrame(w.reshape(-1), columns=['w'], index=exp_index) actual = ds.to_dataframe() - self.assertTrue(expected.equals(actual)) + assert expected.equals(actual) # check roundtrip - self.assertDatasetIdentical(ds.assign_coords(x=[0, 1]), - Dataset.from_dataframe(actual)) + assert_identical(ds.assign_coords(x=[0, 1]), + Dataset.from_dataframe(actual)) # check pathological cases df = pd.DataFrame([1]) actual = Dataset.from_dataframe(df) expected = Dataset({0: ('index', [1])}, {'index': [0]}) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) df = pd.DataFrame() actual = Dataset.from_dataframe(df) expected = Dataset(coords={'index': []}) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) # GH697 - df = pd.DataFrame({'A' : []}) + df = pd.DataFrame({'A': []}) actual = Dataset.from_dataframe(df) - expected = Dataset({'A': DataArray([], dims=('index',))}, {'index': []}) - self.assertDatasetIdentical(expected, actual) + expected = Dataset({'A': DataArray([], dims=('index',))}, + {'index': []}) + assert_identical(expected, actual) # regression test for GH278 # use int64 to ensure consistent results for the pandas .equals method @@ -2843,16 +2861,16 @@ def test_to_and_from_dict(self): actual = ds.to_dict() # check that they are identical - self.assertEqual(expected, actual) + assert expected == actual # check roundtrip - self.assertDatasetIdentical(ds, Dataset.from_dict(actual)) + assert_identical(ds, Dataset.from_dict(actual)) # verify coords are included roundtrip expected = ds.set_coords('b') actual = Dataset.from_dict(expected.to_dict()) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) # test some incomplete dicts: # this one has no attrs field, the dims are strings, and x, y are @@ -2862,20 +2880,20 @@ def test_to_and_from_dict(self): 'dims': 't', 'data_vars': {'a': {'dims': 't', 'data': x}, 'b': {'dims': 't', 'data': y}}} - self.assertDatasetIdentical(ds, Dataset.from_dict(d)) + assert_identical(ds, Dataset.from_dict(d)) # this is kind of a flattened version with no coords, or data_vars d = {'a': {'dims': 't', 'data': x}, 't': {'data': t, 'dims': 't'}, 'b': {'dims': 't', 'data': y}} - self.assertDatasetIdentical(ds, Dataset.from_dict(d)) + assert_identical(ds, Dataset.from_dict(d)) # this one is missing some necessary information d = {'a': {'data': x}, 't': {'data': t, 'dims': 't'}, 'b': {'dims': 't', 'data': y}} with raises_regex(ValueError, "cannot convert dict " - "without the key 'dims'"): + "without the key 'dims'"): Dataset.from_dict(d) def test_to_and_from_dict_with_time_dim(self): @@ -2888,7 +2906,7 @@ def test_to_and_from_dict_with_time_dim(self): ('t', ('t', t)), ('lat', ('lat', lat))])) roundtripped = Dataset.from_dict(ds.to_dict()) - self.assertDatasetIdentical(ds, roundtripped) + assert_identical(ds, roundtripped) def test_to_and_from_dict_with_nan_nat(self): x = np.random.randn(10, 3) @@ -2903,7 +2921,7 @@ def test_to_and_from_dict_with_nan_nat(self): ('t', ('t', t)), ('lat', ('lat', lat))])) roundtripped = Dataset.from_dict(ds.to_dict()) - self.assertDatasetIdentical(ds, roundtripped) + assert_identical(ds, roundtripped) def test_to_dict_with_numpy_attrs(self): # this doesn't need to roundtrip @@ -2922,14 +2940,14 @@ def test_to_dict_with_numpy_attrs(self): actual = ds.to_dict() # check that they are identical - self.assertEqual(expected_attrs, actual['data_vars']['a']['attrs']) + assert expected_attrs == actual['data_vars']['a']['attrs'] def test_pickle(self): data = create_test_data() roundtripped = pickle.loads(pickle.dumps(data)) - self.assertDatasetIdentical(data, roundtripped) + assert_identical(data, roundtripped) # regression test for #167: - self.assertEqual(data.dims, roundtripped.dims) + assert data.dims == roundtripped.dims def test_lazy_load(self): store = InaccessibleVariableDataStore() @@ -2955,49 +2973,49 @@ def test_dropna(self): expected = ds.isel(a=slice(1, None, 2)) actual = ds.dropna('a') - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) expected = ds.isel(b=slice(1, 3)) actual = ds.dropna('b') - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) actual = ds.dropna('b', subset=['foo', 'bar']) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) expected = ds.isel(b=slice(1, None)) actual = ds.dropna('b', subset=['foo']) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) expected = ds.isel(b=slice(3)) actual = ds.dropna('b', subset=['bar']) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) actual = ds.dropna('a', subset=[]) - self.assertDatasetIdentical(actual, ds) + assert_identical(actual, ds) actual = ds.dropna('a', subset=['bar']) - self.assertDatasetIdentical(actual, ds) + assert_identical(actual, ds) actual = ds.dropna('a', how='all') - self.assertDatasetIdentical(actual, ds) + assert_identical(actual, ds) actual = ds.dropna('b', how='all', subset=['bar']) expected = ds.isel(b=[0, 1, 2]) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) actual = ds.dropna('b', thresh=1, subset=['bar']) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) actual = ds.dropna('b', thresh=2) - self.assertDatasetIdentical(actual, ds) + assert_identical(actual, ds) actual = ds.dropna('b', thresh=4) expected = ds.isel(b=[1, 2, 3]) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) actual = ds.dropna('a', thresh=3) expected = ds.isel(a=[1, 3]) - self.assertDatasetIdentical(actual, ds) + assert_identical(actual, ds) with raises_regex(ValueError, 'a single dataset dimension'): ds.dropna('foo') @@ -3013,39 +3031,39 @@ def test_fillna(self): # fill with -1 actual = ds.fillna(-1) expected = Dataset({'a': ('x', [-1, 1, -1, 3])}, {'x': [0, 1, 2, 3]}) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) actual = ds.fillna({'a': -1}) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) other = Dataset({'a': -1}) actual = ds.fillna(other) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) actual = ds.fillna({'a': other.a}) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) # fill with range(4) b = DataArray(range(4), coords=[('x', range(4))]) actual = ds.fillna(b) expected = b.rename('a').to_dataset() - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) actual = ds.fillna(expected) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) actual = ds.fillna(range(4)) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) actual = ds.fillna(b[:3]) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) # okay to only include some data variables ds['b'] = np.nan actual = ds.fillna({'a': -1}) expected = Dataset({'a': ('x', [-1, 1, -1, 3]), 'b': np.nan}, {'x': [0, 1, 2, 3]}) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) # but new data variables is not okay with raises_regex(ValueError, 'must be contained'): @@ -3053,66 +3071,66 @@ def test_fillna(self): # empty argument should be OK result = ds.fillna({}) - self.assertDatasetIdentical(ds, result) + assert_identical(ds, result) result = ds.fillna(Dataset(coords={'c': 42})) expected = ds.assign_coords(c=42) - self.assertDatasetIdentical(expected, result) + assert_identical(expected, result) # groupby expected = Dataset({'a': ('x', range(4))}, {'x': [0, 1, 2, 3]}) for target in [ds, expected]: target.coords['b'] = ('x', [0, 0, 1, 1]) actual = ds.groupby('b').fillna(DataArray([0, 2], dims='b')) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) actual = ds.groupby('b').fillna(Dataset({'a': ('b', [0, 2])})) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) # attrs with groupby ds.attrs['attr'] = 'ds' ds.a.attrs['attr'] = 'da' actual = ds.groupby('b').fillna(Dataset({'a': ('b', [0, 2])})) - self.assertEqual(actual.attrs, ds.attrs) - self.assertEqual(actual.a.name, 'a') - self.assertEqual(actual.a.attrs, ds.a.attrs) + assert actual.attrs == ds.attrs + assert actual.a.name == 'a' + assert actual.a.attrs == ds.a.attrs da = DataArray(range(5), name='a', attrs={'attr': 'da'}) actual = da.fillna(1) - self.assertEqual(actual.name, 'a') - self.assertEqual(actual.attrs, da.attrs) + assert actual.name == 'a' + assert actual.attrs == da.attrs ds = Dataset({'a': da}, attrs={'attr': 'ds'}) actual = ds.fillna({'a': 1}) - self.assertEqual(actual.attrs, ds.attrs) - self.assertEqual(actual.a.name, 'a') - self.assertEqual(actual.a.attrs, ds.a.attrs) + assert actual.attrs == ds.attrs + assert actual.a.name == 'a' + assert actual.a.attrs == ds.a.attrs def test_where(self): ds = Dataset({'a': ('x', range(5))}) expected = Dataset({'a': ('x', [np.nan, np.nan, 2, 3, 4])}) actual = ds.where(ds > 1) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) actual = ds.where(ds.a > 1) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) actual = ds.where(ds.a.values > 1) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) actual = ds.where(True) - self.assertDatasetIdentical(ds, actual) + assert_identical(ds, actual) expected = ds.copy(deep=True) expected['a'].values = [np.nan] * 5 actual = ds.where(False) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) # 2d ds = Dataset({'a': (('x', 'y'), [[0, 1], [2, 3]])}) expected = Dataset({'a': (('x', 'y'), [[np.nan, 1], [2, 3]])}) actual = ds.where(ds > 0) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) # groupby ds = Dataset({'a': ('x', range(5))}, {'c': ('x', [0, 0, 1, 1, 1])}) @@ -3120,27 +3138,27 @@ def test_where(self): expected = ds.copy(deep=True) expected['a'].values = [0, 1] + [np.nan] * 3 actual = ds.groupby('c').where(cond) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) # attrs with groupby ds.attrs['attr'] = 'ds' ds.a.attrs['attr'] = 'da' actual = ds.groupby('c').where(cond) - self.assertEqual(actual.attrs, ds.attrs) - self.assertEqual(actual.a.name, 'a') - self.assertEqual(actual.a.attrs, ds.a.attrs) + assert actual.attrs == ds.attrs + assert actual.a.name == 'a' + assert actual.a.attrs == ds.a.attrs # attrs da = DataArray(range(5), name='a', attrs={'attr': 'da'}) actual = da.where(da.values > 1) - self.assertEqual(actual.name, 'a') - self.assertEqual(actual.attrs, da.attrs) + assert actual.name == 'a' + assert actual.attrs == da.attrs ds = Dataset({'a': da}, attrs={'attr': 'ds'}) actual = ds.where(ds > 0) - self.assertEqual(actual.attrs, ds.attrs) - self.assertEqual(actual.a.name, 'a') - self.assertEqual(actual.a.attrs, ds.a.attrs) + assert actual.attrs == ds.attrs + assert actual.a.name == 'a' + assert actual.a.attrs == ds.a.attrs def test_where_other(self): ds = Dataset({'a': ('x', range(5))}, {'x': range(5)}) @@ -3166,54 +3184,59 @@ def test_where_drop(self): array = DataArray(range(5), coords=[range(5)], dims=['x']) expected = DataArray(range(5)[2:], coords=[range(5)[2:]], dims=['x']) actual = array.where(array > 1, drop=True) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) # dataset case ds = Dataset({'a': array}) expected = Dataset({'a': expected}) actual = ds.where(ds > 1, drop=True) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) actual = ds.where(ds.a > 1, drop=True) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) with raises_regex(TypeError, 'must be a'): ds.where(np.arange(5) > 1, drop=True) # 1d with odd coordinates - array = DataArray(np.array([2, 7, 1, 8, 3]), coords=[np.array([3, 1, 4, 5, 9])], dims=['x']) - expected = DataArray(np.array([7, 8, 3]), coords=[np.array([1, 5, 9])], dims=['x']) + array = DataArray(np.array([2, 7, 1, 8, 3]), + coords=[np.array([3, 1, 4, 5, 9])], dims=['x']) + expected = DataArray(np.array([7, 8, 3]), coords=[np.array([1, 5, 9])], + dims=['x']) actual = array.where(array > 2, drop=True) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) # 1d multiple variables ds = Dataset({'a': (('x'), [0, 1, 2, 3]), 'b': (('x'), [4, 5, 6, 7])}) - expected = Dataset({'a': (('x'), [np.nan, 1, 2, 3]), 'b': (('x'), [4, 5, 6, np.nan])}) + expected = Dataset({'a': (('x'), [np.nan, 1, 2, 3]), + 'b': (('x'), [4, 5, 6, np.nan])}) actual = ds.where((ds > 0) & (ds < 7), drop=True) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) # 2d ds = Dataset({'a': (('x', 'y'), [[0, 1], [2, 3]])}) expected = Dataset({'a': (('x', 'y'), [[np.nan, 1], [2, 3]])}) actual = ds.where(ds > 0, drop=True) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) # 2d with odd coordinates - ds = Dataset({'a': (('x', 'y'), [[0, 1], [2, 3]])}, - coords={'x': [4, 3], 'y': [1, 2], - 'z' : (['x','y'], [[np.e, np.pi], [np.pi*np.e, np.pi*3]])}) + ds = Dataset({'a': (('x', 'y'), [[0, 1], [2, 3]])}, coords={ + 'x': [4, 3], 'y': [1, 2], + 'z': (['x', 'y'], [[np.e, np.pi], [np.pi * np.e, np.pi * 3]])}) expected = Dataset({'a': (('x', 'y'), [[3]])}, - coords={'x': [3], 'y': [2], - 'z' : (['x','y'], [[np.pi*3]])}) + coords={'x': [3], 'y': [2], + 'z': (['x', 'y'], [[np.pi * 3]])}) actual = ds.where(ds > 2, drop=True) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) # 2d multiple variables - ds = Dataset({'a': (('x', 'y'), [[0, 1], [2, 3]]), 'b': (('x','y'), [[4, 5], [6, 7]])}) - expected = Dataset({'a': (('x', 'y'), [[np.nan, 1], [2, 3]]), 'b': (('x', 'y'), [[4, 5], [6,7]])}) + ds = Dataset({'a': (('x', 'y'), [[0, 1], [2, 3]]), + 'b': (('x', 'y'), [[4, 5], [6, 7]])}) + expected = Dataset({'a': (('x', 'y'), [[np.nan, 1], [2, 3]]), + 'b': (('x', 'y'), [[4, 5], [6, 7]])}) actual = ds.where(ds > 0, drop=True) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_where_drop_empty(self): # regression test for GH1341 @@ -3222,26 +3245,26 @@ def test_where_drop_empty(self): mask = DataArray(np.zeros((100,), dtype='bool'), dims='nCells') actual = array.where(mask, drop=True) expected = DataArray(np.zeros((0, 10)), dims=['nCells', 'nVertLevels']) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_where_drop_no_indexes(self): ds = Dataset({'foo': ('x', [0.0, 1.0])}) expected = Dataset({'foo': ('x', [1.0])}) actual = ds.where(ds == 1, drop=True) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_reduce(self): data = create_test_data() - self.assertEqual(len(data.mean().coords), 0) + assert len(data.mean().coords) == 0 actual = data.max() expected = Dataset(dict((k, v.max()) for k, v in iteritems(data.data_vars))) - self.assertDatasetEqual(expected, actual) + assert_equal(expected, actual) - self.assertDatasetEqual(data.min(dim=['dim1']), - data.min(dim='dim1')) + assert_equal(data.min(dim=['dim1']), + data.min(dim='dim1')) for reduct, expected in [('dim2', ['dim1', 'dim3', 'time']), (['dim2', 'time'], ['dim1', 'dim3']), @@ -3251,7 +3274,7 @@ def test_reduce(self): print(reduct, actual, expected) self.assertItemsEqual(actual, expected) - self.assertDatasetEqual(data.mean(dim=[]), data) + assert_equal(data.mean(dim=[]), data) # uint support data = xr.Dataset({'a': (('x', 'y'), @@ -3260,28 +3283,32 @@ def test_reduce(self): actual = data.mean('x', skipna=True) expected = xr.Dataset({'a': data['a'].mean('x'), 'b': data['b'].mean('x', skipna=True)}) - self.assertDatasetIdentical(actual, expected) + assert_identical(actual, expected) def test_reduce_bad_dim(self): data = create_test_data() with raises_regex(ValueError, 'Dataset does not contain'): - ds = data.mean(dim='bad_dim') + data.mean(dim='bad_dim') def test_reduce_cumsum_test_dims(self): data = create_test_data() for cumfunc in ['cumsum', 'cumprod']: - with raises_regex(ValueError, "must supply either single 'dim' or 'axis'"): - ds = getattr(data, cumfunc)() - with raises_regex(ValueError, "must supply either single 'dim' or 'axis'"): - ds = getattr(data, cumfunc)(dim=['dim1', 'dim2']) + with raises_regex(ValueError, + "must supply either single 'dim' or 'axis'"): + getattr(data, cumfunc)() + with raises_regex(ValueError, + "must supply either single 'dim' or 'axis'"): + getattr(data, cumfunc)(dim=['dim1', 'dim2']) with raises_regex(ValueError, 'Dataset does not contain'): - ds = getattr(data, cumfunc)(dim='bad_dim') + getattr(data, cumfunc)(dim='bad_dim') # ensure dimensions are correct - for reduct, expected in [('dim1', ['dim1', 'dim2', 'dim3', 'time']), - ('dim2', ['dim1', 'dim2', 'dim3', 'time']), - ('dim3', ['dim1', 'dim2', 'dim3', 'time']), - ('time', ['dim1', 'dim2', 'dim3'])]: + for reduct, expected in [ + ('dim1', ['dim1', 'dim2', 'dim3', 'time']), + ('dim2', ['dim1', 'dim2', 'dim3', 'time']), + ('dim3', ['dim1', 'dim2', 'dim3', 'time']), + ('time', ['dim1', 'dim2', 'dim3']) + ]: actual = getattr(data, cumfunc)(dim=reduct).dims print(reduct, actual, expected) self.assertItemsEqual(actual, expected) @@ -3295,53 +3322,53 @@ def test_reduce_non_numeric(self): data = np.random.randint(0, 100, size=size).astype(np.str_) data1[v] = (dims, data, {'foo': 'variable'}) - self.assertTrue('var4' not in data1.mean()) - self.assertDatasetEqual(data1.mean(), data2.mean()) - self.assertDatasetEqual(data1.mean(dim='dim1'), - data2.mean(dim='dim1')) + assert 'var4' not in data1.mean() + assert_equal(data1.mean(), data2.mean()) + assert_equal(data1.mean(dim='dim1'), + data2.mean(dim='dim1')) def test_reduce_strings(self): expected = Dataset({'x': 'a'}) ds = Dataset({'x': ('y', ['a', 'b'])}) actual = ds.min() - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) expected = Dataset({'x': 'b'}) actual = ds.max() - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) expected = Dataset({'x': 0}) actual = ds.argmin() - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) expected = Dataset({'x': 1}) actual = ds.argmax() - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) expected = Dataset({'x': b'a'}) ds = Dataset({'x': ('y', np.array(['a', 'b'], 'S1'))}) actual = ds.min() - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) expected = Dataset({'x': u'a'}) ds = Dataset({'x': ('y', np.array(['a', 'b'], 'U1'))}) actual = ds.min() - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_reduce_dtypes(self): # regression test for GH342 expected = Dataset({'x': 1}) actual = Dataset({'x': True}).sum() - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) # regression test for GH505 expected = Dataset({'x': 3}) actual = Dataset({'x': ('y', np.array([1, 2], 'uint16'))}).sum() - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) expected = Dataset({'x': 1 + 1j}) actual = Dataset({'x': ('y', [1, 1j])}).sum() - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_reduce_keep_attrs(self): data = create_test_data() @@ -3352,31 +3379,31 @@ def test_reduce_keep_attrs(self): # Test dropped attrs ds = data.mean() - self.assertEqual(ds.attrs, {}) + assert ds.attrs == {} for v in ds.data_vars.values(): - self.assertEqual(v.attrs, {}) + assert v.attrs == {} # Test kept attrs ds = data.mean(keep_attrs=True) - self.assertEqual(ds.attrs, attrs) + assert ds.attrs == attrs for k, v in ds.data_vars.items(): - self.assertEqual(v.attrs, data[k].attrs) + assert v.attrs == data[k].attrs def test_reduce_argmin(self): # regression test for #205 ds = Dataset({'a': ('x', [0, 1])}) expected = Dataset({'a': ([], 0)}) actual = ds.argmin() - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) actual = ds.argmin('x') - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_reduce_scalars(self): ds = Dataset({'x': ('a', [2, 2]), 'y': 2, 'z': ('b', [2])}) expected = Dataset({'x': 0, 'y': 0, 'z': 0}) actual = ds.var() - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_reduce_only_one_axis(self): @@ -3388,7 +3415,7 @@ def mean_only_one_axis(x, axis): ds = Dataset({'a': (['x', 'y'], [[0, 1, 2, 3, 4]])}) expected = Dataset({'a': ('x', [2])}) actual = ds.reduce(mean_only_one_axis, 'y') - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) with raises_regex(TypeError, 'non-integer axis'): ds.reduce(mean_only_one_axis) @@ -3406,42 +3433,59 @@ def test_quantile(self): assert 'quantile' in ds_quantile for var, dar in ds.data_vars.items(): assert var in ds_quantile - self.assertDataArrayIdentical( + assert_identical( ds_quantile[var], dar.quantile(q, dim=dim)) dim = ['dim1', 'dim2'] ds_quantile = ds.quantile(q, dim=dim) assert 'dim3' in ds_quantile.dims assert all(d not in ds_quantile.dims for d in dim) + @requires_bottleneck + def test_rank(self): + ds = create_test_data(seed=1234) + # only ds.var3 depends on dim3 + z = ds.rank('dim3') + self.assertItemsEqual(['var3'], list(z.data_vars)) + # same as dataarray version + x = z.var3 + y = ds.var3.rank('dim3') + assert_equal(x, y) + # coordinates stick + self.assertItemsEqual(list(z.coords), list(ds.coords)) + self.assertItemsEqual(list(x.coords), list(y.coords)) + # invalid dim + with raises_regex(ValueError, 'does not contain'): + x.rank('invalid_dim') + def test_count(self): ds = Dataset({'x': ('a', [np.nan, 1]), 'y': 0, 'z': np.nan}) expected = Dataset({'x': 1, 'y': 1, 'z': 0}) actual = ds.count() - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_apply(self): data = create_test_data() data.attrs['foo'] = 'bar' - self.assertDatasetIdentical(data.apply(np.mean), data.mean()) + assert_identical(data.apply(np.mean), data.mean()) expected = data.mean(keep_attrs=True) actual = data.apply(lambda x: x.mean(keep_attrs=True), keep_attrs=True) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) - self.assertDatasetIdentical(data.apply(lambda x: x, keep_attrs=True), - data.drop('time')) + assert_identical(data.apply(lambda x: x, keep_attrs=True), + data.drop('time')) def scale(x, multiple=1): return multiple * x actual = data.apply(scale, multiple=2) - self.assertDataArrayEqual(actual['var1'], 2 * data['var1']) - self.assertDataArrayIdentical(actual['numbers'], data['numbers']) + assert_equal(actual['var1'], 2 * data['var1']) + assert_identical(actual['numbers'], data['numbers']) actual = data.apply(np.asarray) - expected = data.drop('time') # time is not used on a data var - self.assertDatasetEqual(expected, actual) + expected = data.drop('time') # time is not used on a data var + assert_equal(expected, actual) def make_example_math_dataset(self): variables = OrderedDict( @@ -3456,28 +3500,28 @@ def make_example_math_dataset(self): def test_dataset_number_math(self): ds = self.make_example_math_dataset() - self.assertDatasetIdentical(ds, +ds) - self.assertDatasetIdentical(ds, ds + 0) - self.assertDatasetIdentical(ds, 0 + ds) - self.assertDatasetIdentical(ds, ds + np.array(0)) - self.assertDatasetIdentical(ds, np.array(0) + ds) + assert_identical(ds, +ds) + assert_identical(ds, ds + 0) + assert_identical(ds, 0 + ds) + assert_identical(ds, ds + np.array(0)) + assert_identical(ds, np.array(0) + ds) actual = ds.copy(deep=True) actual += 0 - self.assertDatasetIdentical(ds, actual) + assert_identical(ds, actual) def test_unary_ops(self): ds = self.make_example_math_dataset() - self.assertDatasetIdentical(ds.apply(abs), abs(ds)) - self.assertDatasetIdentical(ds.apply(lambda x: x + 4), ds + 4) + assert_identical(ds.apply(abs), abs(ds)) + assert_identical(ds.apply(lambda x: x + 4), ds + 4) for func in [lambda x: x.isnull(), lambda x: x.round(), lambda x: x.astype(int)]: - self.assertDatasetIdentical(ds.apply(func), func(ds)) + assert_identical(ds.apply(func), func(ds)) - self.assertDatasetIdentical(ds.isnull(), ~ds.notnull()) + assert_identical(ds.isnull(), ~ds.notnull()) # don't actually patch these methods in with pytest.raises(AttributeError): @@ -3489,78 +3533,78 @@ def test_dataset_array_math(self): ds = self.make_example_math_dataset() expected = ds.apply(lambda x: x - ds['foo']) - self.assertDatasetIdentical(expected, ds - ds['foo']) - self.assertDatasetIdentical(expected, -ds['foo'] + ds) - self.assertDatasetIdentical(expected, ds - ds['foo'].variable) - self.assertDatasetIdentical(expected, -ds['foo'].variable + ds) + assert_identical(expected, ds - ds['foo']) + assert_identical(expected, -ds['foo'] + ds) + assert_identical(expected, ds - ds['foo'].variable) + assert_identical(expected, -ds['foo'].variable + ds) actual = ds.copy(deep=True) actual -= ds['foo'] - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) expected = ds.apply(lambda x: x + ds['bar']) - self.assertDatasetIdentical(expected, ds + ds['bar']) + assert_identical(expected, ds + ds['bar']) actual = ds.copy(deep=True) actual += ds['bar'] - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) expected = Dataset({'bar': ds['bar'] + np.arange(3)}) - self.assertDatasetIdentical(expected, ds[['bar']] + np.arange(3)) - self.assertDatasetIdentical(expected, np.arange(3) + ds[['bar']]) + assert_identical(expected, ds[['bar']] + np.arange(3)) + assert_identical(expected, np.arange(3) + ds[['bar']]) def test_dataset_dataset_math(self): ds = self.make_example_math_dataset() - self.assertDatasetIdentical(ds, ds + 0 * ds) - self.assertDatasetIdentical(ds, ds + {'foo': 0, 'bar': 0}) + assert_identical(ds, ds + 0 * ds) + assert_identical(ds, ds + {'foo': 0, 'bar': 0}) expected = ds.apply(lambda x: 2 * x) - self.assertDatasetIdentical(expected, 2 * ds) - self.assertDatasetIdentical(expected, ds + ds) - self.assertDatasetIdentical(expected, ds + ds.data_vars) - self.assertDatasetIdentical(expected, ds + dict(ds.data_vars)) + assert_identical(expected, 2 * ds) + assert_identical(expected, ds + ds) + assert_identical(expected, ds + ds.data_vars) + assert_identical(expected, ds + dict(ds.data_vars)) actual = ds.copy(deep=True) expected_id = id(actual) actual += ds - self.assertDatasetIdentical(expected, actual) - self.assertEqual(expected_id, id(actual)) + assert_identical(expected, actual) + assert expected_id == id(actual) - self.assertDatasetIdentical(ds == ds, ds.notnull()) + assert_identical(ds == ds, ds.notnull()) subsampled = ds.isel(y=slice(2)) expected = 2 * subsampled - self.assertDatasetIdentical(expected, subsampled + ds) - self.assertDatasetIdentical(expected, ds + subsampled) + assert_identical(expected, subsampled + ds) + assert_identical(expected, ds + subsampled) def test_dataset_math_auto_align(self): ds = self.make_example_math_dataset() subset = ds.isel(y=[1, 3]) expected = 2 * subset actual = ds + subset - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) actual = ds.isel(y=slice(1)) + ds.isel(y=slice(1, None)) expected = 2 * ds.drop(ds.y, dim='y') - self.assertDatasetEqual(actual, expected) + assert_equal(actual, expected) actual = ds + ds[['bar']] expected = (2 * ds[['bar']]).merge(ds.coords) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) - self.assertDatasetIdentical(ds + Dataset(), ds.coords.to_dataset()) - self.assertDatasetIdentical(Dataset() + Dataset(), Dataset()) + assert_identical(ds + Dataset(), ds.coords.to_dataset()) + assert_identical(Dataset() + Dataset(), Dataset()) ds2 = Dataset(coords={'bar': 42}) - self.assertDatasetIdentical(ds + ds2, ds.coords.merge(ds2)) + assert_identical(ds + ds2, ds.coords.merge(ds2)) # maybe unary arithmetic with empty datasets should raise instead? - self.assertDatasetIdentical(Dataset() + 1, Dataset()) + assert_identical(Dataset() + 1, Dataset()) actual = ds.copy(deep=True) other = ds.isel(y=slice(2)) actual += other expected = ds + other.reindex_like(ds) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) def test_dataset_math_errors(self): ds = self.make_example_math_dataset() @@ -3579,7 +3623,7 @@ def test_dataset_math_errors(self): actual = ds.copy(deep=True) with pytest.raises(TypeError): actual += other - self.assertDatasetIdentical(actual, ds) + assert_identical(actual, ds) def test_dataset_transpose(self): ds = Dataset({'a': (('x', 'y'), np.random.randn(3, 4)), @@ -3587,26 +3631,26 @@ def test_dataset_transpose(self): actual = ds.transpose() expected = ds.apply(lambda x: x.transpose()) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) with pytest.warns(FutureWarning): actual = ds.T - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) actual = ds.transpose('x', 'y') expected = ds.apply(lambda x: x.transpose('x', 'y')) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) ds = create_test_data() actual = ds.transpose() for k in ds.variables: - self.assertEqual(actual[k].dims[::-1], ds[k].dims) + assert actual[k].dims[::-1] == ds[k].dims new_order = ('dim2', 'dim3', 'dim1', 'time') actual = ds.transpose(*new_order) for k in ds.variables: expected_dims = tuple(d for d in new_order if d in ds[k].dims) - self.assertEqual(actual[k].dims, expected_dims) + assert actual[k].dims == expected_dims with raises_regex(ValueError, 'arguments to transpose'): ds.transpose('dim1', 'dim2', 'dim3') @@ -3622,23 +3666,23 @@ def test_dataset_retains_period_index_on_transpose(self): transposed = ds.transpose() - self.assertIsInstance(transposed.time.to_index(), pd.PeriodIndex) + assert isinstance(transposed.time.to_index(), pd.PeriodIndex) def test_dataset_diff_n1_simple(self): ds = Dataset({'foo': ('x', [5, 5, 6, 6])}) actual = ds.diff('x') expected = Dataset({'foo': ('x', [0, 1, 0])}) - self.assertDatasetEqual(expected, actual) + assert_equal(expected, actual) def test_dataset_diff_n1_label(self): ds = Dataset({'foo': ('x', [5, 5, 6, 6])}, {'x': [0, 1, 2, 3]}) actual = ds.diff('x', label='lower') expected = Dataset({'foo': ('x', [0, 1, 0])}, {'x': [0, 1, 2]}) - self.assertDatasetEqual(expected, actual) + assert_equal(expected, actual) actual = ds.diff('x', label='upper') expected = Dataset({'foo': ('x', [0, 1, 0])}, {'x': [1, 2, 3]}) - self.assertDatasetEqual(expected, actual) + assert_equal(expected, actual) def test_dataset_diff_n1(self): ds = create_test_data(seed=1) @@ -3653,7 +3697,7 @@ def test_dataset_diff_n1(self): expected['var3'] = ds['var3'] expected = Dataset(expected, coords={'time': ds['time'].values}) expected.coords['numbers'] = ('dim3', ds['numbers'].values) - self.assertDatasetEqual(expected, actual) + assert_equal(expected, actual) def test_dataset_diff_n2(self): ds = create_test_data(seed=1) @@ -3668,7 +3712,7 @@ def test_dataset_diff_n2(self): expected['var3'] = ds['var3'] expected = Dataset(expected, coords={'time': ds['time'].values}) expected.coords['numbers'] = ('dim3', ds['numbers'].values) - self.assertDatasetEqual(expected, actual) + assert_equal(expected, actual) def test_dataset_diff_exception_n_neg(self): ds = create_test_data(seed=1) @@ -3686,7 +3730,7 @@ def test_shift(self): ds = Dataset({'foo': ('x', [1, 2, 3])}, coords, attrs) actual = ds.shift(x=1) expected = Dataset({'foo': ('x', [np.nan, 1, 2])}, coords, attrs) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) with raises_regex(ValueError, 'dimensions'): ds.shift(foo=123) @@ -3699,7 +3743,7 @@ def test_roll(self): ex_coords = {'bar': ('x', list('cab')), 'x': [2, -4, 3]} expected = Dataset({'foo': ('x', [3, 1, 2])}, ex_coords, attrs) - self.assertDatasetIdentical(expected, actual) + assert_identical(expected, actual) with raises_regex(ValueError, 'dimensions'): ds.roll(foo=123) @@ -3709,10 +3753,10 @@ def test_real_and_imag(self): ds = Dataset({'x': ((), 1 + 2j, attrs)}, attrs=attrs) expected_re = Dataset({'x': ((), 1, attrs)}, attrs=attrs) - self.assertDatasetIdentical(ds.real, expected_re) + assert_identical(ds.real, expected_re) expected_im = Dataset({'x': ((), 2, attrs)}, attrs=attrs) - self.assertDatasetIdentical(ds.imag, expected_im) + assert_identical(ds.imag, expected_im) def test_setattr_raises(self): ds = Dataset({}, coords={'scalar': 1}, attrs={'foo': 'bar'}) @@ -3735,29 +3779,32 @@ def test_filter_by_attrs(self): # Test return empty Dataset. ds.filter_by_attrs(standard_name='invalid_standard_name') new_ds = ds.filter_by_attrs(standard_name='invalid_standard_name') - self.assertFalse(bool(new_ds.data_vars)) + assert not bool(new_ds.data_vars) # Test return one DataArray. - new_ds = ds.filter_by_attrs(standard_name='convective_precipitation_flux') - self.assertEqual(new_ds['precipitation'].standard_name, 'convective_precipitation_flux') - self.assertDatasetEqual(new_ds['precipitation'], ds['precipitation']) + new_ds = ds.filter_by_attrs( + standard_name='convective_precipitation_flux') + assert (new_ds['precipitation'].standard_name == + 'convective_precipitation_flux') + + assert_equal(new_ds['precipitation'], ds['precipitation']) # Test return more than one DataArray. new_ds = ds.filter_by_attrs(standard_name='air_potential_temperature') - self.assertEqual(len(new_ds.data_vars), 2) + assert len(new_ds.data_vars) == 2 for var in new_ds.data_vars: - self.assertEqual(new_ds[var].standard_name, 'air_potential_temperature') + assert new_ds[var].standard_name == 'air_potential_temperature' # Test callable. new_ds = ds.filter_by_attrs(height=lambda v: v is not None) - self.assertEqual(len(new_ds.data_vars), 2) + assert len(new_ds.data_vars) == 2 for var in new_ds.data_vars: - self.assertEqual(new_ds[var].standard_name, 'air_potential_temperature') + assert new_ds[var].standard_name == 'air_potential_temperature' new_ds = ds.filter_by_attrs(height='10 m') - self.assertEqual(len(new_ds.data_vars), 1) + assert len(new_ds.data_vars) == 1 for var in new_ds.data_vars: - self.assertEqual(new_ds[var].height, '10 m') + assert new_ds[var].height == '10 m' def test_binary_op_join_setting(self): # arithmetic_join applies to data array coordinates @@ -3766,35 +3813,35 @@ def test_binary_op_join_setting(self): with xr.set_options(arithmetic_join='outer'): actual = missing_2 + missing_0 expected = xr.Dataset({'x': [0, 1, 2]}) - self.assertDatasetEqual(actual, expected) + assert_equal(actual, expected) # arithmetic join also applies to data_vars ds1 = xr.Dataset({'foo': 1, 'bar': 2}) ds2 = xr.Dataset({'bar': 2, 'baz': 3}) expected = xr.Dataset({'bar': 4}) # default is inner joining actual = ds1 + ds2 - self.assertDatasetEqual(actual, expected) + assert_equal(actual, expected) with xr.set_options(arithmetic_join='outer'): expected = xr.Dataset({'foo': np.nan, 'bar': 4, 'baz': np.nan}) actual = ds1 + ds2 - self.assertDatasetEqual(actual, expected) + assert_equal(actual, expected) with xr.set_options(arithmetic_join='left'): expected = xr.Dataset({'foo': np.nan, 'bar': 4}) actual = ds1 + ds2 - self.assertDatasetEqual(actual, expected) + assert_equal(actual, expected) with xr.set_options(arithmetic_join='right'): expected = xr.Dataset({'bar': 4, 'baz': np.nan}) actual = ds1 + ds2 - self.assertDatasetEqual(actual, expected) + assert_equal(actual, expected) def test_full_like(self): # For more thorough tests, see test_variable.py # Note: testing data_vars with mismatched dtypes ds = Dataset({ - 'd1': DataArray([1,2,3], dims=['x'], coords={'x': [10, 20, 30]}), + 'd1': DataArray([1, 2, 3], dims=['x'], coords={'x': [10, 20, 30]}), 'd2': DataArray([1.1, 2.2, 3.3], dims=['y']) }, attrs={'foo': 'bar'}) actual = full_like(ds, 2) @@ -3802,18 +3849,18 @@ def test_full_like(self): expect = ds.copy(deep=True) expect['d1'].values = [2, 2, 2] expect['d2'].values = [2.0, 2.0, 2.0] - self.assertEqual(expect['d1'].dtype, int) - self.assertEqual(expect['d2'].dtype, float) - self.assertDatasetIdentical(expect, actual) + assert expect['d1'].dtype == int + assert expect['d2'].dtype == float + assert_identical(expect, actual) # override dtype actual = full_like(ds, fill_value=True, dtype=bool) expect = ds.copy(deep=True) expect['d1'].values = [True, True, True] expect['d2'].values = [True, True, True] - self.assertEqual(expect['d1'].dtype, bool) - self.assertEqual(expect['d2'].dtype, bool) - self.assertDatasetIdentical(expect, actual) + assert expect['d1'].dtype == bool + assert expect['d2'].dtype == bool + assert_identical(expect, actual) def test_combine_first(self): dsx0 = DataArray([0, 0], [('x', ['a', 'b'])]).to_dataset(name='dsx0') @@ -3823,15 +3870,15 @@ def test_combine_first(self): expected = Dataset({'dsx0': ('x', [0, 0, np.nan]), 'dsx1': ('x', [np.nan, 1, 1])}, coords={'x': ['a', 'b', 'c']}) - self.assertDatasetEqual(actual, expected) - self.assertDatasetEqual(actual, xr.merge([dsx0, dsx1])) + assert_equal(actual, expected) + assert_equal(actual, xr.merge([dsx0, dsx1])) # works just like xr.merge([self, other]) dsy2 = DataArray([2, 2, 2], [('x', ['b', 'c', 'd'])]).to_dataset(name='dsy2') actual = dsx0.combine_first(dsy2) expected = xr.merge([dsy2, dsx0]) - self.assertDatasetEqual(actual, expected) + assert_equal(actual, expected) def test_sortby(self): ds = Dataset({'A': DataArray([[1, 2], [3, 4], [5, 6]], @@ -3855,16 +3902,16 @@ def test_sortby(self): expected = sorted1d dax = DataArray([100, 99, 98], [('x', ['c', 'b', 'a'])]) actual = ds.sortby(dax) - self.assertDatasetEqual(actual, expected) + assert_equal(actual, expected) # test descending order sort actual = ds.sortby(dax, ascending=False) - self.assertDatasetEqual(actual, ds) + assert_equal(actual, ds) # test alignment (fills in nan for 'c') dax_short = DataArray([98, 97], [('x', ['b', 'a'])]) actual = ds.sortby(dax_short) - self.assertDatasetEqual(actual, expected) + assert_equal(actual, expected) # test 1-D lexsort # dax0 is sorted first to give indices of [1, 2, 0] @@ -3872,13 +3919,13 @@ def test_sortby(self): dax0 = DataArray([100, 95, 95], [('x', ['c', 'b', 'a'])]) dax1 = DataArray([0, 1, 0], [('x', ['c', 'b', 'a'])]) actual = ds.sortby([dax0, dax1]) # lexsort underneath gives [2, 1, 0] - self.assertDatasetEqual(actual, expected) + assert_equal(actual, expected) expected = sorted2d # test multi-dim sort by 1D dataarray values day = DataArray([90, 80], [('y', [1, 0])]) actual = ds.sortby([day, dax]) - self.assertDatasetEqual(actual, expected) + assert_equal(actual, expected) # test exception-raising with pytest.raises(KeyError) as excinfo: @@ -3893,7 +3940,7 @@ def test_sortby(self): expected = sorted1d actual = ds.sortby('x') - self.assertDatasetEqual(actual, expected) + assert_equal(actual, expected) # test pandas.MultiIndex indices = (('b', 1), ('b', 0), ('a', 1), ('a', 0)) @@ -3910,26 +3957,26 @@ def test_sortby(self): ('y', [1, 0])]), 'B': DataArray([[11, 12], [9, 10], [7, 8], [5, 6]], dims=['x', 'y'])}) - self.assertDatasetEqual(actual, expected) + assert_equal(actual, expected) # multi-dim sort by coordinate objects expected = sorted2d actual = ds.sortby(['x', 'y']) - self.assertDatasetEqual(actual, expected) + assert_equal(actual, expected) # test descending order sort actual = ds.sortby(['x', 'y'], ascending=False) - self.assertDatasetEqual(actual, ds) + assert_equal(actual, ds) def test_attribute_access(self): ds = create_test_data(seed=1) for key in ['var1', 'var2', 'var3', 'time', 'dim1', 'dim2', 'dim3', 'numbers']: - self.assertDataArrayEqual(ds[key], getattr(ds, key)) + assert_equal(ds[key], getattr(ds, key)) assert key in dir(ds) for key in ['dim3', 'dim1', 'numbers']: - self.assertDataArrayEqual(ds['var3'][key], getattr(ds.var3, key)) + assert_equal(ds['var3'][key], getattr(ds.var3, key)) assert key in dir(ds['var3']) # attrs assert ds['var3'].attrs['foo'] == ds.var3.foo @@ -3995,12 +4042,14 @@ def test_dir_expected_attrs(data_set): result = dir(data_set) assert set(result) >= some_expected_attrs + def test_dir_non_string(data_set): # add a numbered key to ensure this doesn't break dir data_set[5] = 'foo' result = dir(data_set) assert not (5 in result) + def test_dir_unicode(data_set): data_set[u'unicode'] = 'uni' result = dir(data_set) diff --git a/xarray/tests/test_distributed.py b/xarray/tests/test_distributed.py index 2761f85..1d450ff 100644 --- a/xarray/tests/test_distributed.py +++ b/xarray/tests/test_distributed.py @@ -2,18 +2,19 @@ import pytest import xarray as xr -from xarray.core.pycompat import suppress distributed = pytest.importorskip('distributed') da = pytest.importorskip('dask.array') import dask -from distributed.utils_test import cluster, loop, gen_cluster -from distributed.client import futures_of, wait +from distributed.utils_test import cluster, gen_cluster +from distributed.utils_test import loop # flake8: noqa +from distributed.client import futures_of from xarray.tests.test_backends import create_tmp_file, ON_WINDOWS from xarray.tests.test_dataset import create_test_data -from . import assert_allclose, has_scipy, has_netCDF4, has_h5netcdf +from . import (assert_allclose, has_scipy, has_netCDF4, has_h5netcdf, + requires_zarr) ENGINES = [] @@ -28,7 +29,7 @@ @pytest.mark.xfail(sys.platform == 'win32', reason='https://github.com/pydata/xarray/issues/1738') @pytest.mark.parametrize('engine', ENGINES) -def test_dask_distributed_integration_test(loop, engine): +def test_dask_distributed_netcdf_integration_test(loop, engine): with cluster() as (s, _): with distributed.Client(s['address'], loop=loop): original = create_test_data() @@ -40,6 +41,19 @@ def test_dask_distributed_integration_test(loop, engine): assert_allclose(original, computed) +@requires_zarr +def test_dask_distributed_zarr_integration_test(loop): + with cluster() as (s, _): + with distributed.Client(s['address'], loop=loop): + original = create_test_data() + with create_tmp_file(allow_cleanup_failure=ON_WINDOWS) as filename: + original.to_zarr(filename) + with xr.open_zarr(filename) as restored: + assert isinstance(restored.var1.data, da.Array) + computed = restored.compute() + assert_allclose(original, computed) + + @pytest.mark.skipif(distributed.__version__ <= '1.19.3', reason='Need recent distributed version to clean up get') @gen_cluster(client=True, timeout=None) diff --git a/xarray/tests/test_duck_array_ops.py b/xarray/tests/test_duck_array_ops.py index 121f401..9fb1b1a 100644 --- a/xarray/tests/test_duck_array_ops.py +++ b/xarray/tests/test_duck_array_ops.py @@ -4,6 +4,7 @@ from pytest import mark import numpy as np from numpy import array, nan +from . import assert_array_equal from xarray.core.duck_array_ops import ( first, last, count, mean, array_notnull_equiv, ) @@ -32,15 +33,15 @@ def test_first(self): for axis, expected in zip([0, 1, 2, -3, -2, -1], 2 * expected_results): actual = first(self.x, axis) - self.assertArrayEqual(expected, actual) + assert_array_equal(expected, actual) expected = self.x[0] actual = first(self.x, axis=0, skipna=False) - self.assertArrayEqual(expected, actual) + assert_array_equal(expected, actual) expected = self.x[..., 0] actual = first(self.x, axis=-1, skipna=False) - self.assertArrayEqual(expected, actual) + assert_array_equal(expected, actual) with raises_regex(IndexError, 'out of bounds'): first(self.x, 3) @@ -56,24 +57,24 @@ def test_last(self): for axis, expected in zip([0, 1, 2, -3, -2, -1], 2 * expected_results): actual = last(self.x, axis) - self.assertArrayEqual(expected, actual) + assert_array_equal(expected, actual) expected = self.x[-1] actual = last(self.x, axis=0, skipna=False) - self.assertArrayEqual(expected, actual) + assert_array_equal(expected, actual) expected = self.x[..., -1] actual = last(self.x, axis=-1, skipna=False) - self.assertArrayEqual(expected, actual) + assert_array_equal(expected, actual) with raises_regex(IndexError, 'out of bounds'): last(self.x, 3) def test_count(self): - self.assertEqual(12, count(self.x)) + assert 12 == count(self.x) expected = array([[1, 2, 3], [3, 2, 1]]) - self.assertArrayEqual(expected, count(self.x, axis=-1)) + assert_array_equal(expected, count(self.x, axis=-1)) def test_all_nan_arrays(self): assert np.isnan(mean([np.nan, np.nan])) diff --git a/xarray/tests/test_extensions.py b/xarray/tests/test_extensions.py index 27a838b..9456f33 100644 --- a/xarray/tests/test_extensions.py +++ b/xarray/tests/test_extensions.py @@ -9,12 +9,14 @@ import xarray as xr from . import TestCase, raises_regex +import pytest @xr.register_dataset_accessor('example_accessor') @xr.register_dataarray_accessor('example_accessor') class ExampleAccessor(object): """For the pickling tests below.""" + def __init__(self, xarray_obj): self.obj = xarray_obj @@ -26,6 +28,7 @@ def test_register(self): @xr.register_dataarray_accessor('demo') class DemoAccessor(object): """Demo accessor.""" + def __init__(self, xarray_obj): self._obj = xarray_obj @@ -52,7 +55,7 @@ def foo(self): del xr.Dataset.demo assert not hasattr(xr.Dataset, 'demo') - with self.assertWarns('overriding a preexisting attribute'): + with pytest.warns(Warning, match='overriding a preexisting attribute'): @xr.register_dataarray_accessor('demo') class Foo(object): pass diff --git a/xarray/tests/test_formatting.py b/xarray/tests/test_formatting.py index 2c2c9bd..5334282 100644 --- a/xarray/tests/test_formatting.py +++ b/xarray/tests/test_formatting.py @@ -25,10 +25,10 @@ def test_get_indexer_at_least_n_items(self): ((2, 5, 1,), (slice(2), slice(None), slice(None))), ((2, 5, 3,), (0, slice(4), slice(None))), ((2, 3, 3,), (slice(2), slice(None), slice(None))), - ] + ] for shape, expected in cases: actual = formatting._get_indexer_at_least_n_items(shape, 10) - self.assertEqual(expected, actual) + assert expected == actual def test_first_n_items(self): array = np.arange(100).reshape(10, 5, 2) @@ -48,7 +48,7 @@ def test_last_item(self): for r in reshape: result = formatting.last_item(array.reshape(r)) - self.assertEqual(result, expected) + assert result == expected def test_format_item(self): cases = [ @@ -67,7 +67,7 @@ def test_format_item(self): ] for item, expected in cases: actual = formatting.format_item(item) - self.assertEqual(expected, actual) + assert expected == actual def test_format_items(self): cases = [ @@ -85,62 +85,62 @@ def test_format_items(self): ] for item, expected in cases: actual = ' '.join(formatting.format_items(item)) - self.assertEqual(expected, actual) + assert expected == actual def test_format_array_flat(self): actual = formatting.format_array_flat(np.arange(100), 13) expected = '0 1 2 3 4 ...' - self.assertEqual(expected, actual) + assert expected == actual actual = formatting.format_array_flat(np.arange(100.0), 11) expected = '0.0 1.0 ...' - self.assertEqual(expected, actual) + assert expected == actual actual = formatting.format_array_flat(np.arange(100.0), 1) expected = '0.0 ...' - self.assertEqual(expected, actual) + assert expected == actual actual = formatting.format_array_flat(np.arange(3), 5) expected = '0 1 2' - self.assertEqual(expected, actual) + assert expected == actual actual = formatting.format_array_flat(np.arange(4.0), 11) expected = '0.0 1.0 ...' - self.assertEqual(expected, actual) + assert expected == actual actual = formatting.format_array_flat(np.arange(4), 0) expected = '0 ...' - self.assertEqual(expected, actual) + assert expected == actual def test_pretty_print(self): - self.assertEqual(formatting.pretty_print('abcdefghij', 8), 'abcde...') - self.assertEqual(formatting.pretty_print(u'ß', 1), u'ß') + assert formatting.pretty_print('abcdefghij', 8) == 'abcde...' + assert formatting.pretty_print(u'ß', 1) == u'ß' def test_maybe_truncate(self): - self.assertEqual(formatting.maybe_truncate(u'ß', 10), u'ß') + assert formatting.maybe_truncate(u'ß', 10) == u'ß' def test_format_timestamp_out_of_bounds(self): from datetime import datetime date = datetime(1300, 12, 1) expected = '1300-12-01' result = formatting.format_timestamp(date) - self.assertEqual(result, expected) + assert result == expected date = datetime(2300, 12, 1) expected = '2300-12-01' result = formatting.format_timestamp(date) - self.assertEqual(result, expected) + assert result == expected def test_attribute_repr(self): short = formatting.summarize_attr(u'key', u'Short string') long = formatting.summarize_attr(u'key', 100 * u'Very long string ') newlines = formatting.summarize_attr(u'key', u'\n\n\n') tabs = formatting.summarize_attr(u'key', u'\t\t\t') - self.assertEqual(short, ' key: Short string') - self.assertLessEqual(len(long), 80) - self.assertTrue(long.endswith(u'...')) - self.assertNotIn(u'\n', newlines) - self.assertNotIn(u'\t', tabs) + assert short == ' key: Short string' + assert len(long) <= 80 + assert long.endswith(u'...') + assert u'\n' not in newlines + assert u'\t' not in tabs def test_set_numpy_options(): diff --git a/xarray/tests/test_groupby.py b/xarray/tests/test_groupby.py index 7245685..f1d8095 100644 --- a/xarray/tests/test_groupby.py +++ b/xarray/tests/test_groupby.py @@ -13,8 +13,8 @@ def test_consolidate_slices(): assert _consolidate_slices([slice(3), slice(3, 5)]) == [slice(5)] assert _consolidate_slices([slice(2, 3), slice(3, 6)]) == [slice(2, 6)] - assert (_consolidate_slices([slice(2, 3, 1), slice(3, 6, 1)]) - == [slice(2, 6, 1)]) + assert (_consolidate_slices([slice(2, 3, 1), slice(3, 6, 1)]) == + [slice(2, 6, 1)]) slices = [slice(2, 3), slice(5, 6)] assert _consolidate_slices(slices) == slices @@ -51,15 +51,18 @@ def test_groupby_da_datetime(): # test groupby with a DataArray of dtype datetime for GH1132 # create test data times = pd.date_range('2000-01-01', periods=4) - foo = xr.DataArray([1,2,3,4], coords=dict(time=times), dims='time') + foo = xr.DataArray([1, 2, 3, 4], coords=dict(time=times), dims='time') # create test index dd = times.to_pydatetime() reference_dates = [dd[0], dd[2]] - labels = reference_dates[0:1]*2 + reference_dates[1:2]*2 - ind = xr.DataArray(labels, coords=dict(time=times), dims='time', name='reference_date') + labels = reference_dates[0:1] * 2 + reference_dates[1:2] * 2 + ind = xr.DataArray(labels, coords=dict(time=times), dims='time', + name='reference_date') g = foo.groupby(ind) actual = g.sum(dim='time') - expected = xr.DataArray([3,7], coords=dict(reference_date=reference_dates), dims='reference_date') + expected = xr.DataArray([3, 7], + coords=dict(reference_date=reference_dates), + dims='reference_date') assert actual.equals(expected) diff --git a/xarray/tests/test_indexing.py b/xarray/tests/test_indexing.py index 28fecdb..3d93afb 100644 --- a/xarray/tests/test_indexing.py +++ b/xarray/tests/test_indexing.py @@ -12,7 +12,8 @@ from xarray.core import indexing from xarray.core import nputils from xarray.core.pycompat import native_int_types -from . import TestCase, ReturnItem, raises_regex, IndexerMaker +from . import ( + TestCase, ReturnItem, raises_regex, IndexerMaker, assert_array_equal) B = IndexerMaker(indexing.BasicIndexer) @@ -27,14 +28,14 @@ def set_to_zero(self, x, i): def test_expanded_indexer(self): x = np.random.randn(10, 11, 12, 13, 14) y = np.arange(5) - I = ReturnItem() + I = ReturnItem() # noqa: E741 # allow ambiguous name for i in [I[:], I[...], I[0, :, 10], I[..., 10], I[:5, ..., 0], I[..., 0, :], I[y], I[y, y], I[..., y, y], I[..., 0, 1, 2, 3, 4]]: j = indexing.expanded_indexer(i, x.ndim) - self.assertArrayEqual(x[i], x[j]) - self.assertArrayEqual(self.set_to_zero(x, i), - self.set_to_zero(x, j)) + assert_array_equal(x[i], x[j]) + assert_array_equal(self.set_to_zero(x, i), + self.set_to_zero(x, j)) with raises_regex(IndexError, 'too many indices'): indexing.expanded_indexer(I[1, 2, 3], 2) @@ -86,7 +87,7 @@ def test_get_dim_indexers(self): mdata = DataArray(range(4), [('x', mindex)]) dim_indexers = indexing.get_dim_indexers(mdata, {'one': 'a', 'two': 1}) - self.assertEqual(dim_indexers, {'x': {'one': 'a', 'two': 1}}) + assert dim_indexers == {'x': {'one': 'a', 'two': 1}} with raises_regex(ValueError, 'cannot combine'): indexing.get_dim_indexers(mdata, {'x': 'a', 'two': 1}) @@ -100,8 +101,8 @@ def test_get_dim_indexers(self): def test_remap_label_indexers(self): def test_indexer(data, x, expected_pos, expected_idx=None): pos, idx = indexing.remap_label_indexers(data, {'x': x}) - self.assertArrayEqual(pos.get('x'), expected_pos) - self.assertArrayEqual(idx.get('x'), expected_idx) + assert_array_equal(pos.get('x'), expected_pos) + assert_array_equal(idx.get('x'), expected_idx) data = Dataset({'x': ('x', [1, 2, 3])}) mindex = pd.MultiIndex.from_product([['a', 'b'], [1, 2], [-1, -2]], @@ -137,7 +138,7 @@ def test_indexer(data, x, expected_pos, expected_idx=None): class TestLazyArray(TestCase): def test_slice_slice(self): - I = ReturnItem() + I = ReturnItem() # noqa: E741 # allow ambiguous name x = np.arange(100) slices = [I[:3], I[:4], I[2:4], I[:1], I[:-1], I[5:-1], I[-5:-1], I[::-1], I[5::-1], I[:3:-1], I[:30:-1], I[10:4:], I[::4], @@ -147,7 +148,7 @@ def test_slice_slice(self): expected = x[i][j] new_slice = indexing.slice_slice(i, j, size=100) actual = x[new_slice] - self.assertArrayEqual(expected, actual) + assert_array_equal(expected, actual) def test_lazily_indexed_array(self): original = np.random.rand(10, 20, 30) @@ -155,7 +156,7 @@ def test_lazily_indexed_array(self): v = Variable(['i', 'j', 'k'], original) lazy = indexing.LazilyIndexedArray(x) v_lazy = Variable(['i', 'j', 'k'], lazy) - I = ReturnItem() + I = ReturnItem() # noqa: E741 # allow ambiguous name # test orthogonally applied indexers indexers = [I[:], 0, -2, I[:3], [0, 1, 2, 3], [0], np.arange(10) < 5] for i in indexers: @@ -169,8 +170,8 @@ def test_lazily_indexed_array(self): for actual in [v_lazy[i, j, k], v_lazy[:, j, k][i], v_lazy[:, :, k][:, j][i]]: - self.assertEqual(expected.shape, actual.shape) - self.assertArrayEqual(expected, actual) + assert expected.shape == actual.shape + assert_array_equal(expected, actual) assert isinstance(actual._data, indexing.LazilyIndexedArray) @@ -189,8 +190,8 @@ def test_lazily_indexed_array(self): for i, j in indexers: expected = np.asarray(v[i][j]) actual = v_lazy[i][j] - self.assertEqual(expected.shape, actual.shape) - self.assertArrayEqual(expected, actual) + assert expected.shape == actual.shape + assert_array_equal(expected, actual) assert isinstance(actual._data, indexing.LazilyIndexedArray) assert isinstance(actual._data.array, indexing.NumpyIndexingAdapter) @@ -201,18 +202,18 @@ def test_setitem(self): original = np.arange(10) wrapped = indexing.CopyOnWriteArray(original) wrapped[B[:]] = 0 - self.assertArrayEqual(original, np.arange(10)) - self.assertArrayEqual(wrapped, np.zeros(10)) + assert_array_equal(original, np.arange(10)) + assert_array_equal(wrapped, np.zeros(10)) def test_sub_array(self): original = np.arange(10) wrapped = indexing.CopyOnWriteArray(original) child = wrapped[B[:5]] - self.assertIsInstance(child, indexing.CopyOnWriteArray) + assert isinstance(child, indexing.CopyOnWriteArray) child[B[:]] = 0 - self.assertArrayEqual(original, np.arange(10)) - self.assertArrayEqual(wrapped, np.arange(10)) - self.assertArrayEqual(child, np.zeros(5)) + assert_array_equal(original, np.arange(10)) + assert_array_equal(wrapped, np.arange(10)) + assert_array_equal(child, np.zeros(5)) def test_index_scalar(self): # regression test for GH1374 @@ -224,23 +225,23 @@ class TestMemoryCachedArray(TestCase): def test_wrapper(self): original = indexing.LazilyIndexedArray(np.arange(10)) wrapped = indexing.MemoryCachedArray(original) - self.assertArrayEqual(wrapped, np.arange(10)) - self.assertIsInstance(wrapped.array, indexing.NumpyIndexingAdapter) + assert_array_equal(wrapped, np.arange(10)) + assert isinstance(wrapped.array, indexing.NumpyIndexingAdapter) def test_sub_array(self): original = indexing.LazilyIndexedArray(np.arange(10)) wrapped = indexing.MemoryCachedArray(original) child = wrapped[B[:5]] - self.assertIsInstance(child, indexing.MemoryCachedArray) - self.assertArrayEqual(child, np.arange(5)) - self.assertIsInstance(child.array, indexing.NumpyIndexingAdapter) - self.assertIsInstance(wrapped.array, indexing.LazilyIndexedArray) + assert isinstance(child, indexing.MemoryCachedArray) + assert_array_equal(child, np.arange(5)) + assert isinstance(child.array, indexing.NumpyIndexingAdapter) + assert isinstance(wrapped.array, indexing.LazilyIndexedArray) def test_setitem(self): original = np.arange(10) wrapped = indexing.MemoryCachedArray(original) wrapped[B[:]] = 0 - self.assertArrayEqual(original, np.zeros(10)) + assert_array_equal(original, np.zeros(10)) def test_index_scalar(self): # regression test for GH1374 @@ -328,6 +329,9 @@ def test_vectorized_indexer(): check_slice(indexing.VectorizedIndexer) check_array1d(indexing.VectorizedIndexer) check_array2d(indexing.VectorizedIndexer) + with raises_regex(ValueError, 'numbers of dimensions'): + indexing.VectorizedIndexer((np.array(1, dtype=np.int64), + np.arange(5, dtype=np.int64))) def test_unwrap_explicit_indexer(): @@ -363,7 +367,7 @@ def nonzero(x): original = np.random.rand(10, 20, 30) v = Variable(['i', 'j', 'k'], original) - I = ReturnItem() + I = ReturnItem() # noqa: E741 # allow ambiguous name # test orthogonally applied indexers indexers = [I[:], 0, -2, I[:3], np.array([0, 1, 2, 3]), np.array([0]), np.arange(10) < 5] @@ -385,3 +389,79 @@ def nonzero(x): actual = indexing._outer_to_numpy_indexer(outer_index, v.shape) actual_data = v.data[actual] np.testing.assert_array_equal(actual_data, expected_data) + + +def test_create_mask_outer_indexer(): + indexer = indexing.OuterIndexer((np.array([0, -1, 2]),)) + expected = np.array([False, True, False]) + actual = indexing.create_mask(indexer, (5,)) + np.testing.assert_array_equal(expected, actual) + + indexer = indexing.OuterIndexer((1, slice(2), np.array([0, -1, 2]),)) + expected = np.array(2 * [[False, True, False]]) + actual = indexing.create_mask(indexer, (5, 5, 5,)) + np.testing.assert_array_equal(expected, actual) + + +def test_create_mask_vectorized_indexer(): + indexer = indexing.VectorizedIndexer( + (np.array([0, -1, 2]), np.array([0, 1, -1]))) + expected = np.array([False, True, True]) + actual = indexing.create_mask(indexer, (5,)) + np.testing.assert_array_equal(expected, actual) + + indexer = indexing.VectorizedIndexer( + (np.array([0, -1, 2]), slice(None), np.array([0, 1, -1]))) + expected = np.array([[False, True, True]] * 2).T + actual = indexing.create_mask(indexer, (5, 2)) + np.testing.assert_array_equal(expected, actual) + + +def test_create_mask_basic_indexer(): + indexer = indexing.BasicIndexer((-1,)) + actual = indexing.create_mask(indexer, (3,)) + np.testing.assert_array_equal(True, actual) + + indexer = indexing.BasicIndexer((0,)) + actual = indexing.create_mask(indexer, (3,)) + np.testing.assert_array_equal(False, actual) + + +def test_create_mask_dask(): + da = pytest.importorskip('dask.array') + + indexer = indexing.OuterIndexer((1, slice(2), np.array([0, -1, 2]),)) + expected = np.array(2 * [[False, True, False]]) + actual = indexing.create_mask(indexer, (5, 5, 5,), + chunks_hint=((1, 1), (2, 1))) + assert actual.chunks == ((1, 1), (2, 1)) + np.testing.assert_array_equal(expected, actual) + + indexer = indexing.VectorizedIndexer( + (np.array([0, -1, 2]), slice(None), np.array([0, 1, -1]))) + expected = np.array([[False, True, True]] * 2).T + actual = indexing.create_mask(indexer, (5, 2), chunks_hint=((3,), (2,))) + assert isinstance(actual, da.Array) + np.testing.assert_array_equal(expected, actual) + + with pytest.raises(ValueError): + indexing.create_mask(indexer, (5, 2), chunks_hint=()) + + +def test_create_mask_error(): + with raises_regex(TypeError, 'unexpected key type'): + indexing.create_mask((1, 2), (3, 4)) + + +@pytest.mark.parametrize('indices, expected', [ + (np.arange(5), np.arange(5)), + (np.array([0, -1, -1]), np.array([0, 0, 0])), + (np.array([-1, 1, -1]), np.array([1, 1, 1])), + (np.array([-1, -1, 2]), np.array([2, 2, 2])), + (np.array([-1]), np.array([0])), + (np.array([0, -1, 1, -1, -1]), np.array([0, 0, 1, 1, 1])), + (np.array([0, -1, -1, -1, 1]), np.array([0, 0, 0, 0, 1])), +]) +def test_posify_mask_subindexer(indices, expected): + actual = indexing._posify_mask_subindexer(indices) + np.testing.assert_array_equal(expected, actual) diff --git a/xarray/tests/test_merge.py b/xarray/tests/test_merge.py index 532b9ee..409ad86 100644 --- a/xarray/tests/test_merge.py +++ b/xarray/tests/test_merge.py @@ -76,9 +76,9 @@ def test_merge_no_conflicts_single_var(self): ds2 = xr.Dataset({'a': ('x', [2, 3]), 'x': [1, 2]}) expected = xr.Dataset({'a': ('x', [1, 2, 3]), 'x': [0, 1, 2]}) assert expected.identical(xr.merge([ds1, ds2], - compat='no_conflicts')) + compat='no_conflicts')) assert expected.identical(xr.merge([ds2, ds1], - compat='no_conflicts')) + compat='no_conflicts')) assert ds1.identical(xr.merge([ds1, ds2], compat='no_conflicts', join='left')) diff --git a/xarray/tests/test_missing.py b/xarray/tests/test_missing.py new file mode 100644 index 0000000..ce735d7 --- /dev/null +++ b/xarray/tests/test_missing.py @@ -0,0 +1,457 @@ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function +import numpy as np +import pandas as pd +import pytest +import itertools + +import xarray as xr + +from xarray.core.missing import (NumpyInterpolator, ScipyInterpolator, + SplineInterpolator) +from xarray.core.pycompat import dask_array_type + +from xarray.tests import (assert_equal, assert_array_equal, raises_regex, + requires_scipy, requires_bottleneck, requires_dask, + requires_np112) + + +@pytest.fixture +def da(): + return xr.DataArray([0, np.nan, 1, 2, np.nan, 3, 4, 5, np.nan, 6, 7], + dims='time') + + +@pytest.fixture +def ds(): + ds = xr.Dataset() + ds['var1'] = xr.DataArray([0, np.nan, 1, 2, np.nan, 3, 4, 5, np.nan, 6, 7], + dims='time') + ds['var2'] = xr.DataArray([10, np.nan, 11, 12, np.nan, 13, 14, 15, np.nan, + 16, 17], dims='x') + return ds + + +def make_interpolate_example_data(shape, frac_nan, seed=12345, + non_uniform=False): + rs = np.random.RandomState(seed) + vals = rs.normal(size=shape) + if frac_nan == 1: + vals[:] = np.nan + elif frac_nan == 0: + pass + else: + n_missing = int(vals.size * frac_nan) + + ys = np.arange(shape[0]) + xs = np.arange(shape[1]) + if n_missing: + np.random.shuffle(ys) + ys = ys[:n_missing] + + np.random.shuffle(xs) + xs = xs[:n_missing] + + vals[ys, xs] = np.nan + + if non_uniform: + # construct a datetime index that has irregular spacing + deltas = pd.TimedeltaIndex(unit='d', data=rs.normal(size=shape[0], + scale=10)) + coords = {'time': (pd.Timestamp('2000-01-01') + deltas).sort_values()} + else: + coords = {'time': pd.date_range('2000-01-01', freq='D', + periods=shape[0])} + da = xr.DataArray(vals, dims=('time', 'x'), coords=coords) + df = da.to_pandas() + + return da, df + + +@requires_np112 +@requires_scipy +def test_interpolate_pd_compat(): + shapes = [(8, 8), (1, 20), (20, 1), (100, 100)] + frac_nans = [0, 0.5, 1] + methods = ['linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic'] + + for (shape, frac_nan, method) in itertools.product(shapes, frac_nans, + methods): + + da, df = make_interpolate_example_data(shape, frac_nan) + + for dim in ['time', 'x']: + actual = da.interpolate_na(method=method, dim=dim, + fill_value=np.nan) + expected = df.interpolate(method=method, axis=da.get_axis_num(dim), + fill_value=(np.nan, np.nan)) + # Note, Pandas does some odd things with the left/right fill_value + # for the linear methods. This next line inforces the xarray + # fill_value convention on the pandas output. Therefore, this test + # only checks that interpolated values are the same (not nans) + expected.values[pd.isnull(actual.values)] = np.nan + + np.testing.assert_allclose(actual.values, expected.values) + + +@requires_np112 +@requires_scipy +def test_scipy_methods_function(): + for method in ['barycentric', 'krog', 'pchip', 'spline', 'akima']: + kwargs = {} + # Note: Pandas does some wacky things with these methods and the full + # integration tests wont work. + da, _ = make_interpolate_example_data((25, 25), 0.4, non_uniform=True) + actual = da.interpolate_na(method=method, dim='time', **kwargs) + assert (da.count('time') <= actual.count('time')).all() + + +@requires_np112 +@requires_scipy +def test_interpolate_pd_compat_non_uniform_index(): + shapes = [(8, 8), (1, 20), (20, 1), (100, 100)] + frac_nans = [0, 0.5, 1] + methods = ['time', 'index', 'values'] + + for (shape, frac_nan, method) in itertools.product(shapes, frac_nans, + methods): + + da, df = make_interpolate_example_data(shape, frac_nan, + non_uniform=True) + for dim in ['time', 'x']: + if method == 'time' and dim != 'time': + continue + actual = da.interpolate_na(method='linear', dim=dim, + use_coordinate=True, fill_value=np.nan) + expected = df.interpolate(method=method, axis=da.get_axis_num(dim), + fill_value=np.nan) + + # Note, Pandas does some odd things with the left/right fill_value + # for the linear methods. This next line inforces the xarray + # fill_value convention on the pandas output. Therefore, this test + # only checks that interpolated values are the same (not nans) + expected.values[pd.isnull(actual.values)] = np.nan + + np.testing.assert_allclose(actual.values, expected.values) + + +@requires_np112 +@requires_scipy +def test_interpolate_pd_compat_polynomial(): + shapes = [(8, 8), (1, 20), (20, 1), (100, 100)] + frac_nans = [0, 0.5, 1] + orders = [1, 2, 3] + + for (shape, frac_nan, order) in itertools.product(shapes, frac_nans, + orders): + + da, df = make_interpolate_example_data(shape, frac_nan) + + for dim in ['time', 'x']: + actual = da.interpolate_na(method='polynomial', order=order, + dim=dim, use_coordinate=False) + expected = df.interpolate(method='polynomial', order=order, + axis=da.get_axis_num(dim)) + np.testing.assert_allclose(actual.values, expected.values) + + +@requires_np112 +@requires_scipy +def test_interpolate_unsorted_index_raises(): + vals = np.array([1, 2, 3], dtype=np.float64) + expected = xr.DataArray(vals, dims='x', coords={'x': [2, 1, 3]}) + with raises_regex(ValueError, 'Index must be monotonicly increasing'): + expected.interpolate_na(dim='x', method='index') + + +def test_interpolate_no_dim_raises(): + da = xr.DataArray(np.array([1, 2, np.nan, 5], dtype=np.float64), dims='x') + with raises_regex(NotImplementedError, 'dim is a required argument'): + da.interpolate_na(method='linear') + + +def test_interpolate_invalid_interpolator_raises(): + da = xr.DataArray(np.array([1, 2, np.nan, 5], dtype=np.float64), dims='x') + with raises_regex(ValueError, 'not a valid'): + da.interpolate_na(dim='x', method='foo') + + +def test_interpolate_multiindex_raises(): + data = np.random.randn(2, 3) + data[1, 1] = np.nan + da = xr.DataArray(data, coords=[('x', ['a', 'b']), ('y', [0, 1, 2])]) + das = da.stack(z=('x', 'y')) + with raises_regex(TypeError, 'Index must be castable to float64'): + das.interpolate_na(dim='z') + + +def test_interpolate_2d_coord_raises(): + coords = {'x': xr.Variable(('a', 'b'), np.arange(6).reshape(2, 3)), + 'y': xr.Variable(('a', 'b'), np.arange(6).reshape(2, 3)) * 2} + + data = np.random.randn(2, 3) + data[1, 1] = np.nan + da = xr.DataArray(data, dims=('a', 'b'), coords=coords) + with raises_regex(ValueError, 'interpolation must be 1D'): + da.interpolate_na(dim='a', use_coordinate='x') + + +@requires_np112 +@requires_scipy +def test_interpolate_kwargs(): + da = xr.DataArray(np.array([4, 5, np.nan], dtype=np.float64), dims='x') + expected = xr.DataArray(np.array([4, 5, 6], dtype=np.float64), dims='x') + actual = da.interpolate_na(dim='x', fill_value='extrapolate') + assert_equal(actual, expected) + + expected = xr.DataArray(np.array([4, 5, -999], dtype=np.float64), dims='x') + actual = da.interpolate_na(dim='x', fill_value=-999) + assert_equal(actual, expected) + + +@requires_np112 +def test_interpolate(): + + vals = np.array([1, 2, 3, 4, 5, 6], dtype=np.float64) + expected = xr.DataArray(vals, dims='x') + mvals = vals.copy() + mvals[2] = np.nan + missing = xr.DataArray(mvals, dims='x') + + actual = missing.interpolate_na(dim='x') + + assert_equal(actual, expected) + + +@requires_np112 +def test_interpolate_nonans(): + + vals = np.array([1, 2, 3, 4, 5, 6], dtype=np.float64) + expected = xr.DataArray(vals, dims='x') + actual = expected.interpolate_na(dim='x') + assert_equal(actual, expected) + + +@requires_np112 +@requires_scipy +def test_interpolate_allnans(): + vals = np.full(6, np.nan, dtype=np.float64) + expected = xr.DataArray(vals, dims='x') + actual = expected.interpolate_na(dim='x') + + assert_equal(actual, expected) + + +@requires_np112 +@requires_bottleneck +def test_interpolate_limits(): + da = xr.DataArray(np.array([1, 2, np.nan, np.nan, np.nan, 6], + dtype=np.float64), dims='x') + + actual = da.interpolate_na(dim='x', limit=None) + assert actual.isnull().sum() == 0 + + actual = da.interpolate_na(dim='x', limit=2) + expected = xr.DataArray(np.array([1, 2, 3, 4, np.nan, 6], + dtype=np.float64), dims='x') + + assert_equal(actual, expected) + + +@requires_np112 +@requires_scipy +def test_interpolate_methods(): + for method in ['linear', 'nearest', 'zero', 'slinear', 'quadratic', + 'cubic']: + kwargs = {} + da = xr.DataArray(np.array([0, 1, 2, np.nan, np.nan, np.nan, 6, 7, 8], + dtype=np.float64), dims='x') + actual = da.interpolate_na('x', method=method, **kwargs) + assert actual.isnull().sum() == 0 + + actual = da.interpolate_na('x', method=method, limit=2, **kwargs) + assert actual.isnull().sum() == 1 + + +@requires_scipy +@requires_np112 +def test_interpolators(): + for method, interpolator in [('linear', NumpyInterpolator), + ('linear', ScipyInterpolator), + ('spline', SplineInterpolator)]: + xi = np.array([-1, 0, 1, 2, 5], dtype=np.float64) + yi = np.array([-10, 0, 10, 20, 50], dtype=np.float64) + x = np.array([3, 4], dtype=np.float64) + + f = interpolator(xi, yi, method=method) + out = f(x) + assert pd.isnull(out).sum() == 0 + + +@requires_np112 +def test_interpolate_use_coordinate(): + xc = xr.Variable('x', [100, 200, 300, 400, 500, 600]) + da = xr.DataArray(np.array([1, 2, np.nan, np.nan, np.nan, 6], + dtype=np.float64), + dims='x', coords={'xc': xc}) + + # use_coordinate == False is same as using the default index + actual = da.interpolate_na(dim='x', use_coordinate=False) + expected = da.interpolate_na(dim='x') + assert_equal(actual, expected) + + # possible to specify non index coordinate + actual = da.interpolate_na(dim='x', use_coordinate='xc') + expected = da.interpolate_na(dim='x') + assert_equal(actual, expected) + + # possible to specify index coordinate by name + actual = da.interpolate_na(dim='x', use_coordinate='x') + expected = da.interpolate_na(dim='x') + assert_equal(actual, expected) + + +@requires_np112 +@requires_dask +def test_interpolate_dask(): + da, _ = make_interpolate_example_data((40, 40), 0.5) + da = da.chunk({'x': 5}) + actual = da.interpolate_na('time') + expected = da.load().interpolate_na('time') + assert isinstance(actual.data, dask_array_type) + assert_equal(actual.compute(), expected) + + # with limit + da = da.chunk({'x': 5}) + actual = da.interpolate_na('time', limit=3) + expected = da.load().interpolate_na('time', limit=3) + assert isinstance(actual.data, dask_array_type) + assert_equal(actual, expected) + + +@requires_np112 +@requires_dask +def test_interpolate_dask_raises_for_invalid_chunk_dim(): + da, _ = make_interpolate_example_data((40, 40), 0.5) + da = da.chunk({'time': 5}) + with raises_regex(ValueError, "dask='parallelized' consists of multiple"): + da.interpolate_na('time') + + +@requires_np112 +@requires_bottleneck +def test_ffill(): + da = xr.DataArray(np.array([4, 5, np.nan], dtype=np.float64), dims='x') + expected = xr.DataArray(np.array([4, 5, 5], dtype=np.float64), dims='x') + actual = da.ffill('x') + assert_equal(actual, expected) + + +@requires_np112 +@requires_bottleneck +@requires_dask +def test_ffill_dask(): + da, _ = make_interpolate_example_data((40, 40), 0.5) + da = da.chunk({'x': 5}) + actual = da.ffill('time') + expected = da.load().ffill('time') + assert isinstance(actual.data, dask_array_type) + assert_equal(actual, expected) + + # with limit + da = da.chunk({'x': 5}) + actual = da.ffill('time', limit=3) + expected = da.load().ffill('time', limit=3) + assert isinstance(actual.data, dask_array_type) + assert_equal(actual, expected) + + +@requires_bottleneck +@requires_dask +def test_bfill_dask(): + da, _ = make_interpolate_example_data((40, 40), 0.5) + da = da.chunk({'x': 5}) + actual = da.bfill('time') + expected = da.load().bfill('time') + assert isinstance(actual.data, dask_array_type) + assert_equal(actual, expected) + + # with limit + da = da.chunk({'x': 5}) + actual = da.bfill('time', limit=3) + expected = da.load().bfill('time', limit=3) + assert isinstance(actual.data, dask_array_type) + assert_equal(actual, expected) + + +@requires_bottleneck +@requires_np112 +def test_ffill_bfill_nonans(): + + vals = np.array([1, 2, 3, 4, 5, 6], dtype=np.float64) + expected = xr.DataArray(vals, dims='x') + + actual = expected.ffill(dim='x') + assert_equal(actual, expected) + + actual = expected.bfill(dim='x') + assert_equal(actual, expected) + + +@requires_bottleneck +@requires_np112 +def test_ffill_bfill_allnans(): + + vals = np.full(6, np.nan, dtype=np.float64) + expected = xr.DataArray(vals, dims='x') + + actual = expected.ffill(dim='x') + assert_equal(actual, expected) + + actual = expected.bfill(dim='x') + assert_equal(actual, expected) + + +@requires_bottleneck +@requires_np112 +def test_ffill_functions(da): + result = da.ffill('time') + assert result.isnull().sum() == 0 + + +@requires_bottleneck +@requires_np112 +def test_ffill_limit(): + da = xr.DataArray( + [0, np.nan, np.nan, np.nan, np.nan, 3, 4, 5, np.nan, 6, 7], + dims='time') + result = da.ffill('time') + expected = xr.DataArray([0, 0, 0, 0, 0, 3, 4, 5, 5, 6, 7], dims='time') + assert_array_equal(result, expected) + + result = da.ffill('time', limit=1) + expected = xr.DataArray( + [0, 0, np.nan, np.nan, np.nan, 3, 4, 5, 5, 6, 7], dims='time') + + +@requires_np112 +def test_interpolate_dataset(ds): + actual = ds.interpolate_na(dim='time') + # no missing values in var1 + assert actual['var1'].count('time') == actual.dims['time'] + + # var2 should be the same as it was + assert_array_equal(actual['var2'], ds['var2']) + + +@requires_bottleneck +@requires_np112 +def test_ffill_dataset(ds): + ds.ffill(dim='time') + + +@requires_bottleneck +@requires_np112 +def test_bfill_dataset(ds): + ds.ffill(dim='time') diff --git a/xarray/tests/test_plot.py b/xarray/tests/test_plot.py index ea0ffa6..1573577 100644 --- a/xarray/tests/test_plot.py +++ b/xarray/tests/test_plot.py @@ -20,11 +20,11 @@ import xarray.plot as xplt from xarray.plot.plot import _infer_interval_breaks -from xarray.plot.utils import (_determine_cmap_params, - _build_discrete_cmap, +from xarray.plot.utils import (_determine_cmap_params, _build_discrete_cmap, _color_palette, import_seaborn) -from . import TestCase, requires_matplotlib, requires_seaborn, raises_regex +from . import (TestCase, requires_matplotlib, requires_seaborn, raises_regex, + assert_equal, assert_array_equal) @pytest.mark.flaky @@ -64,7 +64,6 @@ def easy_array(shape, start=0, stop=1): @requires_matplotlib class PlotTestCase(TestCase): - def tearDown(self): # Remove all matplotlib figures plt.close('all') @@ -72,7 +71,7 @@ def tearDown(self): def pass_in_axis(self, plotmethod): fig, axes = plt.subplots(ncols=2) plotmethod(ax=axes[0]) - self.assertTrue(axes[0].has_data()) + assert axes[0].has_data() @pytest.mark.slow def imshow_called(self, plotmethod): @@ -87,32 +86,70 @@ def contourf_called(self, plotmethod): class TestPlot(PlotTestCase): - def setUp(self): self.darray = DataArray(easy_array((2, 3, 4))) def test1d(self): self.darray[:, 0, 0].plot() + with raises_regex(ValueError, 'dimension'): + self.darray[:, 0, 0].plot(x='dim_1') + + def test_2d_line(self): + with raises_regex(ValueError, 'hue'): + self.darray[:, :, 0].plot.line() + + self.darray[:, :, 0].plot.line(hue='dim_1') + + def test_2d_line_accepts_legend_kw(self): + self.darray[:, :, 0].plot.line(x='dim_0', add_legend=False) + assert not plt.gca().get_legend() + plt.cla() + self.darray[:, :, 0].plot.line(x='dim_0', add_legend=True) + assert plt.gca().get_legend() + # check whether legend title is set + assert plt.gca().get_legend().get_title().get_text() \ + == 'dim_1' + + def test_2d_line_accepts_x_kw(self): + self.darray[:, :, 0].plot.line(x='dim_0') + assert plt.gca().get_xlabel() == 'dim_0' + plt.cla() + self.darray[:, :, 0].plot.line(x='dim_1') + assert plt.gca().get_xlabel() == 'dim_1' + + def test_2d_line_accepts_hue_kw(self): + self.darray[:, :, 0].plot.line(hue='dim_0') + assert plt.gca().get_legend().get_title().get_text() \ + == 'dim_0' + plt.cla() + self.darray[:, :, 0].plot.line(hue='dim_1') + assert plt.gca().get_legend().get_title().get_text() \ + == 'dim_1' + def test_2d_before_squeeze(self): a = DataArray(easy_array((1, 5))) a.plot() def test2d_uniform_calls_imshow(self): - self.assertTrue(self.imshow_called(self.darray[:, :, 0].plot.imshow)) + assert self.imshow_called(self.darray[:, :, 0].plot.imshow) @pytest.mark.slow def test2d_nonuniform_calls_contourf(self): a = self.darray[:, :, 0] a.coords['dim_1'] = [2, 1, 89] - self.assertTrue(self.contourf_called(a.plot.contourf)) + assert self.contourf_called(a.plot.contourf) def test2d_1d_2d_coordinates_contourf(self): sz = (20, 10) depth = easy_array(sz) - a = DataArray(easy_array(sz), dims=['z', 'time'], - coords={'depth': (['z', 'time'], depth), - 'time': np.linspace(0, 1, sz[1])}) + a = DataArray( + easy_array(sz), + dims=['z', 'time'], + coords={ + 'depth': (['z', 'time'], depth), + 'time': np.linspace(0, 1, sz[1]) + }) a.plot.contourf(x='time', y='depth') @@ -123,10 +160,10 @@ def test_can_pass_in_axis(self): self.pass_in_axis(self.darray.plot) def test__infer_interval_breaks(self): - self.assertArrayEqual([-0.5, 0.5, 1.5], _infer_interval_breaks([0, 1])) - self.assertArrayEqual([-0.5, 0.5, 5.0, 9.5, 10.5], - _infer_interval_breaks([0, 1, 9, 10])) - self.assertArrayEqual( + assert_array_equal([-0.5, 0.5, 1.5], _infer_interval_breaks([0, 1])) + assert_array_equal([-0.5, 0.5, 5.0, 9.5, 10.5], + _infer_interval_breaks([0, 1, 9, 10])) + assert_array_equal( pd.date_range('20000101', periods=4) - np.timedelta64(12, 'h'), _infer_interval_breaks(pd.date_range('20000101', periods=3))) @@ -145,11 +182,12 @@ def test_datetime_dimension(self): nrow = 3 ncol = 4 time = pd.date_range('2000-01-01', periods=nrow) - a = DataArray(easy_array((nrow, ncol)), - coords=[('time', time), ('y', range(ncol))]) + a = DataArray( + easy_array((nrow, ncol)), + coords=[('time', time), ('y', range(ncol))]) a.plot() ax = plt.gca() - self.assertTrue(ax.has_data()) + assert ax.has_data() @pytest.mark.slow def test_convenient_facetgrid(self): @@ -158,9 +196,9 @@ def test_convenient_facetgrid(self): d.coords['z'] = list('abcd') g = d.plot(x='x', y='y', col='z', col_wrap=2, cmap='cool') - self.assertArrayEqual(g.axes.shape, [2, 2]) + assert_array_equal(g.axes.shape, [2, 2]) for ax in g.axes.flat: - self.assertTrue(ax.has_data()) + assert ax.has_data() with raises_regex(ValueError, '[Ff]acet'): d.plot(x='x', y='y', col='z', ax=plt.gca()) @@ -173,15 +211,20 @@ def test_subplot_kws(self): a = easy_array((10, 15, 4)) d = DataArray(a, dims=['y', 'x', 'z']) d.coords['z'] = list('abcd') - g = d.plot(x='x', y='y', col='z', col_wrap=2, cmap='cool', - subplot_kws=dict(facecolor='r')) + g = d.plot( + x='x', + y='y', + col='z', + col_wrap=2, + cmap='cool', + subplot_kws=dict(facecolor='r')) for ax in g.axes.flat: try: # mpl V2 - self.assertEqual(ax.get_facecolor()[0:3], - mpl.colors.to_rgb('r')) + assert ax.get_facecolor()[0:3] == \ + mpl.colors.to_rgb('r') except AttributeError: - self.assertEqual(ax.get_axis_bgcolor(), 'r') + assert ax.get_axis_bgcolor() == 'r' @pytest.mark.slow def test_plot_size(self): @@ -215,38 +258,32 @@ def test_convenient_facetgrid_4d(self): d = DataArray(a, dims=['y', 'x', 'columns', 'rows']) g = d.plot(x='x', y='y', col='columns', row='rows') - self.assertArrayEqual(g.axes.shape, [3, 2]) + assert_array_equal(g.axes.shape, [3, 2]) for ax in g.axes.flat: - self.assertTrue(ax.has_data()) + assert ax.has_data() with raises_regex(ValueError, '[Ff]acet'): d.plot(x='x', y='y', col='columns', ax=plt.gca()) class TestPlot1D(PlotTestCase): - def setUp(self): d = [0, 1.1, 0, 2] - self.darray = DataArray(d, coords={'period': range(len(d))}, - dims='period') + self.darray = DataArray( + d, coords={'period': range(len(d))}, dims='period') def test_xlabel_is_index_name(self): self.darray.plot() - self.assertEqual('period', plt.gca().get_xlabel()) + assert 'period' == plt.gca().get_xlabel() def test_no_label_name_on_y_axis(self): self.darray.plot() - self.assertEqual('', plt.gca().get_ylabel()) + assert '' == plt.gca().get_ylabel() def test_ylabel_is_data_name(self): self.darray.name = 'temperature' self.darray.plot() - self.assertEqual(self.darray.name, plt.gca().get_ylabel()) - - def test_wrong_dims_raises_valueerror(self): - twodims = DataArray(easy_array((2, 5))) - with pytest.raises(ValueError): - twodims.plot.line() + assert self.darray.name == plt.gca().get_ylabel() def test_format_string(self): self.darray.plot.line('ro') @@ -255,14 +292,13 @@ def test_can_pass_in_axis(self): self.pass_in_axis(self.darray.plot.line) def test_nonnumeric_index_raises_typeerror(self): - a = DataArray([1, 2, 3], {'letter': ['a', 'b', 'c']}, - dims='letter') + a = DataArray([1, 2, 3], {'letter': ['a', 'b', 'c']}, dims='letter') with raises_regex(TypeError, r'[Pp]lot'): a.plot.line() def test_primitive_returned(self): p = self.darray.plot.line() - self.assertTrue(isinstance(p[0], mpl.lines.Line2D)) + assert isinstance(p[0], mpl.lines.Line2D) @pytest.mark.slow def test_plot_nans(self): @@ -274,17 +310,16 @@ def test_x_ticks_are_rotated_for_time(self): a = DataArray(np.arange(len(time)), [('t', time)]) a.plot.line() rotation = plt.gca().get_xticklabels()[0].get_rotation() - self.assertFalse(rotation == 0) + assert rotation != 0 def test_slice_in_title(self): self.darray.coords['d'] = 10 self.darray.plot.line() title = plt.gca().get_title() - self.assertEqual('d = 10', title) + assert 'd = 10' == title class TestPlotHistogram(PlotTestCase): - def setUp(self): self.darray = DataArray(easy_array((2, 3, 4))) @@ -293,28 +328,28 @@ def test_3d_array(self): def test_title_no_name(self): self.darray.plot.hist() - self.assertEqual('', plt.gca().get_title()) + assert '' == plt.gca().get_title() def test_title_uses_name(self): self.darray.name = 'testpoints' self.darray.plot.hist() - self.assertIn(self.darray.name, plt.gca().get_title()) + assert self.darray.name in plt.gca().get_title() def test_ylabel_is_count(self): self.darray.plot.hist() - self.assertEqual('Count', plt.gca().get_ylabel()) + assert 'Count' == plt.gca().get_ylabel() def test_can_pass_in_kwargs(self): nbins = 5 self.darray.plot.hist(bins=nbins) - self.assertEqual(nbins, len(plt.gca().patches)) + assert nbins == len(plt.gca().patches) def test_can_pass_in_axis(self): self.pass_in_axis(self.darray.plot.hist) def test_primitive_returned(self): h = self.darray.plot.hist() - self.assertTrue(isinstance(h[-1][0], mpl.patches.Rectangle)) + assert isinstance(h[-1][0], mpl.patches.Rectangle) @pytest.mark.slow def test_plot_nans(self): @@ -324,26 +359,25 @@ def test_plot_nans(self): @requires_matplotlib class TestDetermineCmapParams(TestCase): - def setUp(self): self.data = np.linspace(0, 1, num=100) def test_robust(self): cmap_params = _determine_cmap_params(self.data, robust=True) - self.assertEqual(cmap_params['vmin'], np.percentile(self.data, 2)) - self.assertEqual(cmap_params['vmax'], np.percentile(self.data, 98)) - self.assertEqual(cmap_params['cmap'].name, 'viridis') - self.assertEqual(cmap_params['extend'], 'both') - self.assertIsNone(cmap_params['levels']) - self.assertIsNone(cmap_params['norm']) + assert cmap_params['vmin'] == np.percentile(self.data, 2) + assert cmap_params['vmax'] == np.percentile(self.data, 98) + assert cmap_params['cmap'].name == 'viridis' + assert cmap_params['extend'] == 'both' + assert cmap_params['levels'] is None + assert cmap_params['norm'] is None def test_center(self): cmap_params = _determine_cmap_params(self.data, center=0.5) - self.assertEqual(cmap_params['vmax'] - 0.5, 0.5 - cmap_params['vmin']) - self.assertEqual(cmap_params['cmap'], 'RdBu_r') - self.assertEqual(cmap_params['extend'], 'neither') - self.assertIsNone(cmap_params['levels']) - self.assertIsNone(cmap_params['norm']) + assert cmap_params['vmax'] - 0.5 == 0.5 - cmap_params['vmin'] + assert cmap_params['cmap'] == 'RdBu_r' + assert cmap_params['extend'] == 'neither' + assert cmap_params['levels'] is None + assert cmap_params['norm'] is None @pytest.mark.slow def test_integer_levels(self): @@ -352,53 +386,52 @@ def test_integer_levels(self): # default is to cover full data range but with no guarantee on Nlevels for level in np.arange(2, 10, dtype=int): cmap_params = _determine_cmap_params(data, levels=level) - self.assertEqual(cmap_params['vmin'], cmap_params['levels'][0]) - self.assertEqual(cmap_params['vmax'], cmap_params['levels'][-1]) - self.assertEqual(cmap_params['extend'], 'neither') + assert cmap_params['vmin'] == cmap_params['levels'][0] + assert cmap_params['vmax'] == cmap_params['levels'][-1] + assert cmap_params['extend'] == 'neither' # with min max we are more strict - cmap_params = _determine_cmap_params(data, levels=5, vmin=0, vmax=5, - cmap='Blues') - self.assertEqual(cmap_params['vmin'], 0) - self.assertEqual(cmap_params['vmax'], 5) - self.assertEqual(cmap_params['vmin'], cmap_params['levels'][0]) - self.assertEqual(cmap_params['vmax'], cmap_params['levels'][-1]) - self.assertEqual(cmap_params['cmap'].name, 'Blues') - self.assertEqual(cmap_params['extend'], 'neither') - self.assertEqual(cmap_params['cmap'].N, 4) - self.assertEqual(cmap_params['norm'].N, 5) - - cmap_params = _determine_cmap_params(data, levels=5, - vmin=0.5, vmax=1.5) - self.assertEqual(cmap_params['cmap'].name, 'viridis') - self.assertEqual(cmap_params['extend'], 'max') - - cmap_params = _determine_cmap_params(data, levels=5, - vmin=1.5) - self.assertEqual(cmap_params['cmap'].name, 'viridis') - self.assertEqual(cmap_params['extend'], 'min') - - cmap_params = _determine_cmap_params(data, levels=5, - vmin=1.3, vmax=1.5) - self.assertEqual(cmap_params['cmap'].name, 'viridis') - self.assertEqual(cmap_params['extend'], 'both') + cmap_params = _determine_cmap_params( + data, levels=5, vmin=0, vmax=5, cmap='Blues') + assert cmap_params['vmin'] == 0 + assert cmap_params['vmax'] == 5 + assert cmap_params['vmin'] == cmap_params['levels'][0] + assert cmap_params['vmax'] == cmap_params['levels'][-1] + assert cmap_params['cmap'].name == 'Blues' + assert cmap_params['extend'] == 'neither' + assert cmap_params['cmap'].N == 4 + assert cmap_params['norm'].N == 5 + + cmap_params = _determine_cmap_params( + data, levels=5, vmin=0.5, vmax=1.5) + assert cmap_params['cmap'].name == 'viridis' + assert cmap_params['extend'] == 'max' + + cmap_params = _determine_cmap_params(data, levels=5, vmin=1.5) + assert cmap_params['cmap'].name == 'viridis' + assert cmap_params['extend'] == 'min' + + cmap_params = _determine_cmap_params( + data, levels=5, vmin=1.3, vmax=1.5) + assert cmap_params['cmap'].name == 'viridis' + assert cmap_params['extend'] == 'both' def test_list_levels(self): data = self.data + 1 orig_levels = [0, 1, 2, 3, 4, 5] # vmin and vmax should be ignored if levels are explicitly provided - cmap_params = _determine_cmap_params(data, levels=orig_levels, - vmin=0, vmax=3) - self.assertEqual(cmap_params['vmin'], 0) - self.assertEqual(cmap_params['vmax'], 5) - self.assertEqual(cmap_params['cmap'].N, 5) - self.assertEqual(cmap_params['norm'].N, 6) + cmap_params = _determine_cmap_params( + data, levels=orig_levels, vmin=0, vmax=3) + assert cmap_params['vmin'] == 0 + assert cmap_params['vmax'] == 5 + assert cmap_params['cmap'].N == 5 + assert cmap_params['norm'].N == 6 for wrap_levels in [list, np.array, pd.Index, DataArray]: cmap_params = _determine_cmap_params( data, levels=wrap_levels(orig_levels)) - self.assertArrayEqual(cmap_params['levels'], orig_levels) + assert_array_equal(cmap_params['levels'], orig_levels) def test_divergentcontrol(self): neg = self.data - 0.1 @@ -406,76 +439,75 @@ def test_divergentcontrol(self): # Default with positive data will be a normal cmap cmap_params = _determine_cmap_params(pos) - self.assertEqual(cmap_params['vmin'], 0) - self.assertEqual(cmap_params['vmax'], 1) - self.assertEqual(cmap_params['cmap'].name, "viridis") + assert cmap_params['vmin'] == 0 + assert cmap_params['vmax'] == 1 + assert cmap_params['cmap'].name == "viridis" # Default with negative data will be a divergent cmap cmap_params = _determine_cmap_params(neg) - self.assertEqual(cmap_params['vmin'], -0.9) - self.assertEqual(cmap_params['vmax'], 0.9) - self.assertEqual(cmap_params['cmap'], "RdBu_r") + assert cmap_params['vmin'] == -0.9 + assert cmap_params['vmax'] == 0.9 + assert cmap_params['cmap'] == "RdBu_r" # Setting vmin or vmax should prevent this only if center is false cmap_params = _determine_cmap_params(neg, vmin=-0.1, center=False) - self.assertEqual(cmap_params['vmin'], -0.1) - self.assertEqual(cmap_params['vmax'], 0.9) - self.assertEqual(cmap_params['cmap'].name, "viridis") + assert cmap_params['vmin'] == -0.1 + assert cmap_params['vmax'] == 0.9 + assert cmap_params['cmap'].name == "viridis" cmap_params = _determine_cmap_params(neg, vmax=0.5, center=False) - self.assertEqual(cmap_params['vmin'], -0.1) - self.assertEqual(cmap_params['vmax'], 0.5) - self.assertEqual(cmap_params['cmap'].name, "viridis") + assert cmap_params['vmin'] == -0.1 + assert cmap_params['vmax'] == 0.5 + assert cmap_params['cmap'].name == "viridis" # Setting center=False too cmap_params = _determine_cmap_params(neg, center=False) - self.assertEqual(cmap_params['vmin'], -0.1) - self.assertEqual(cmap_params['vmax'], 0.9) - self.assertEqual(cmap_params['cmap'].name, "viridis") + assert cmap_params['vmin'] == -0.1 + assert cmap_params['vmax'] == 0.9 + assert cmap_params['cmap'].name == "viridis" # However, I should still be able to set center and have a div cmap cmap_params = _determine_cmap_params(neg, center=0) - self.assertEqual(cmap_params['vmin'], -0.9) - self.assertEqual(cmap_params['vmax'], 0.9) - self.assertEqual(cmap_params['cmap'], "RdBu_r") + assert cmap_params['vmin'] == -0.9 + assert cmap_params['vmax'] == 0.9 + assert cmap_params['cmap'] == "RdBu_r" # Setting vmin or vmax alone will force symmetric bounds around center cmap_params = _determine_cmap_params(neg, vmin=-0.1) - self.assertEqual(cmap_params['vmin'], -0.1) - self.assertEqual(cmap_params['vmax'], 0.1) - self.assertEqual(cmap_params['cmap'], "RdBu_r") + assert cmap_params['vmin'] == -0.1 + assert cmap_params['vmax'] == 0.1 + assert cmap_params['cmap'] == "RdBu_r" cmap_params = _determine_cmap_params(neg, vmax=0.5) - self.assertEqual(cmap_params['vmin'], -0.5) - self.assertEqual(cmap_params['vmax'], 0.5) - self.assertEqual(cmap_params['cmap'], "RdBu_r") + assert cmap_params['vmin'] == -0.5 + assert cmap_params['vmax'] == 0.5 + assert cmap_params['cmap'] == "RdBu_r" cmap_params = _determine_cmap_params(neg, vmax=0.6, center=0.1) - self.assertEqual(cmap_params['vmin'], -0.4) - self.assertEqual(cmap_params['vmax'], 0.6) - self.assertEqual(cmap_params['cmap'], "RdBu_r") + assert cmap_params['vmin'] == -0.4 + assert cmap_params['vmax'] == 0.6 + assert cmap_params['cmap'] == "RdBu_r" # But this is only true if vmin or vmax are negative cmap_params = _determine_cmap_params(pos, vmin=-0.1) - self.assertEqual(cmap_params['vmin'], -0.1) - self.assertEqual(cmap_params['vmax'], 0.1) - self.assertEqual(cmap_params['cmap'], "RdBu_r") + assert cmap_params['vmin'] == -0.1 + assert cmap_params['vmax'] == 0.1 + assert cmap_params['cmap'] == "RdBu_r" cmap_params = _determine_cmap_params(pos, vmin=0.1) - self.assertEqual(cmap_params['vmin'], 0.1) - self.assertEqual(cmap_params['vmax'], 1) - self.assertEqual(cmap_params['cmap'].name, "viridis") + assert cmap_params['vmin'] == 0.1 + assert cmap_params['vmax'] == 1 + assert cmap_params['cmap'].name == "viridis" cmap_params = _determine_cmap_params(pos, vmax=0.5) - self.assertEqual(cmap_params['vmin'], 0) - self.assertEqual(cmap_params['vmax'], 0.5) - self.assertEqual(cmap_params['cmap'].name, "viridis") + assert cmap_params['vmin'] == 0 + assert cmap_params['vmax'] == 0.5 + assert cmap_params['cmap'].name == "viridis" # If both vmin and vmax are provided, output is non-divergent cmap_params = _determine_cmap_params(neg, vmin=-0.2, vmax=0.6) - self.assertEqual(cmap_params['vmin'], -0.2) - self.assertEqual(cmap_params['vmax'], 0.6) - self.assertEqual(cmap_params['cmap'].name, "viridis") + assert cmap_params['vmin'] == -0.2 + assert cmap_params['vmax'] == 0.6 + assert cmap_params['cmap'].name == "viridis" @requires_matplotlib class TestDiscreteColorMap(TestCase): - def setUp(self): x = np.arange(start=0, stop=10, step=2) y = np.arange(start=9, stop=-7, step=-3) @@ -488,73 +520,72 @@ def setUp(self): @pytest.mark.slow def test_recover_from_seaborn_jet_exception(self): pal = _color_palette('jet', 4) - self.assertTrue(type(pal) == np.ndarray) - self.assertEqual(len(pal), 4) + assert type(pal) == np.ndarray + assert len(pal) == 4 @pytest.mark.slow def test_build_discrete_cmap(self): for (cmap, levels, extend, filled) in [('jet', [0, 1], 'both', False), ('hot', [-4, 4], 'max', True)]: ncmap, cnorm = _build_discrete_cmap(cmap, levels, extend, filled) - self.assertEqual(ncmap.N, len(levels) - 1) - self.assertEqual(len(ncmap.colors), len(levels) - 1) - self.assertEqual(cnorm.N, len(levels)) - self.assertArrayEqual(cnorm.boundaries, levels) - self.assertEqual(max(levels), cnorm.vmax) - self.assertEqual(min(levels), cnorm.vmin) + assert ncmap.N == len(levels) - 1 + assert len(ncmap.colors) == len(levels) - 1 + assert cnorm.N == len(levels) + assert_array_equal(cnorm.boundaries, levels) + assert max(levels) == cnorm.vmax + assert min(levels) == cnorm.vmin if filled: - self.assertEqual(ncmap.colorbar_extend, extend) + assert ncmap.colorbar_extend == extend else: - self.assertEqual(ncmap.colorbar_extend, 'max') + assert ncmap.colorbar_extend == 'max' @pytest.mark.slow def test_discrete_colormap_list_of_levels(self): - for extend, levels in [('max', [-1, 2, 4, 8, 10]), - ('both', [2, 5, 10, 11]), - ('neither', [0, 5, 10, 15]), - ('min', [2, 5, 10, 15])]: + for extend, levels in [('max', [-1, 2, 4, 8, 10]), ('both', + [2, 5, 10, 11]), + ('neither', [0, 5, 10, 15]), ('min', + [2, 5, 10, 15])]: for kind in ['imshow', 'pcolormesh', 'contourf', 'contour']: primitive = getattr(self.darray.plot, kind)(levels=levels) - self.assertArrayEqual(levels, primitive.norm.boundaries) - self.assertEqual(max(levels), primitive.norm.vmax) - self.assertEqual(min(levels), primitive.norm.vmin) + assert_array_equal(levels, primitive.norm.boundaries) + assert max(levels) == primitive.norm.vmax + assert min(levels) == primitive.norm.vmin if kind != 'contour': - self.assertEqual(extend, primitive.cmap.colorbar_extend) + assert extend == primitive.cmap.colorbar_extend else: - self.assertEqual('max', primitive.cmap.colorbar_extend) - self.assertEqual(len(levels) - 1, len(primitive.cmap.colors)) + assert 'max' == primitive.cmap.colorbar_extend + assert len(levels) - 1 == len(primitive.cmap.colors) @pytest.mark.slow def test_discrete_colormap_int_levels(self): - for extend, levels, vmin, vmax in [('neither', 7, None, None), - ('neither', 7, None, 20), - ('both', 7, 4, 8), - ('min', 10, 4, 15)]: + for extend, levels, vmin, vmax in [('neither', 7, None, + None), ('neither', 7, None, 20), + ('both', 7, 4, 8), ('min', 10, 4, + 15)]: for kind in ['imshow', 'pcolormesh', 'contourf', 'contour']: - primitive = getattr(self.darray.plot, kind)(levels=levels, - vmin=vmin, - vmax=vmax) - self.assertGreaterEqual(levels, - len(primitive.norm.boundaries) - 1) + primitive = getattr(self.darray.plot, kind)( + levels=levels, vmin=vmin, vmax=vmax) + assert levels >= \ + len(primitive.norm.boundaries) - 1 if vmax is None: - self.assertGreaterEqual(primitive.norm.vmax, self.data_max) + assert primitive.norm.vmax >= self.data_max else: - self.assertGreaterEqual(primitive.norm.vmax, vmax) + assert primitive.norm.vmax >= vmax if vmin is None: - self.assertLessEqual(primitive.norm.vmin, self.data_min) + assert primitive.norm.vmin <= self.data_min else: - self.assertLessEqual(primitive.norm.vmin, vmin) + assert primitive.norm.vmin <= vmin if kind != 'contour': - self.assertEqual(extend, primitive.cmap.colorbar_extend) + assert extend == primitive.cmap.colorbar_extend else: - self.assertEqual('max', primitive.cmap.colorbar_extend) - self.assertGreaterEqual(levels, len(primitive.cmap.colors)) + assert 'max' == primitive.cmap.colorbar_extend + assert levels >= len(primitive.cmap.colors) def test_discrete_colormap_list_levels_and_vmin_or_vmax(self): levels = [0, 5, 10, 15] primitive = self.darray.plot(levels=levels, vmin=-3, vmax=20) - self.assertEqual(primitive.norm.vmax, max(levels)) - self.assertEqual(primitive.norm.vmin, min(levels)) + assert primitive.norm.vmax == max(levels) + assert primitive.norm.vmin == min(levels) class Common2dMixin: @@ -566,8 +597,7 @@ class Common2dMixin: """ def setUp(self): - da = DataArray(easy_array( - (10, 15), start=-1), dims=['y', 'x']) + da = DataArray(easy_array((10, 15), start=-1), dims=['y', 'x']) # add 2d coords ds = da.to_dataset(name='testvar') x, y = np.meshgrid(da.x.values, da.y.values) @@ -580,8 +610,8 @@ def setUp(self): def test_label_names(self): self.plotmethod() - self.assertEqual('x', plt.gca().get_xlabel()) - self.assertEqual('y', plt.gca().get_ylabel()) + assert 'x' == plt.gca().get_xlabel() + assert 'y' == plt.gca().get_ylabel() def test_1d_raises_valueerror(self): with raises_regex(ValueError, r'DataArray must be 2d'): @@ -589,12 +619,13 @@ def test_1d_raises_valueerror(self): def test_3d_raises_valueerror(self): a = DataArray(easy_array((2, 3, 4))) + if self.plotfunc.__name__ == 'imshow': + pytest.skip() with raises_regex(ValueError, r'DataArray must be 2d'): self.plotfunc(a) def test_nonnumeric_index_raises_typeerror(self): - a = DataArray(easy_array((3, 2)), - coords=[['a', 'b', 'c'], ['d', 'e']]) + a = DataArray(easy_array((3, 2)), coords=[['a', 'b', 'c'], ['d', 'e']]) with raises_regex(TypeError, r'[Pp]lot'): self.plotfunc(a) @@ -606,14 +637,22 @@ def test_xyincrease_false_changes_axes(self): xlim = plt.gca().get_xlim() ylim = plt.gca().get_ylim() diffs = xlim[0] - 14, xlim[1] - 0, ylim[0] - 9, ylim[1] - 0 - self.assertTrue(all(abs(x) < 1 for x in diffs)) + assert all(abs(x) < 1 for x in diffs) def test_xyincrease_true_changes_axes(self): self.plotmethod(xincrease=True, yincrease=True) xlim = plt.gca().get_xlim() ylim = plt.gca().get_ylim() diffs = xlim[0] - 0, xlim[1] - 14, ylim[0] - 0, ylim[1] - 9 - self.assertTrue(all(abs(x) < 1 for x in diffs)) + assert all(abs(x) < 1 for x in diffs) + + def test_x_ticks_are_rotated_for_time(self): + time = pd.date_range('2000-01-01', '2000-01-10') + a = DataArray( + np.random.randn(2, len(time)), [('xx', [1, 2]), ('t', time)]) + a.plot(x='t') + rotation = plt.gca().get_xticklabels()[0].get_rotation() + assert rotation != 0 def test_plot_nans(self): x1 = self.darray[:5] @@ -622,66 +661,77 @@ def test_plot_nans(self): clim1 = self.plotfunc(x1).get_clim() clim2 = self.plotfunc(x2).get_clim() - self.assertEqual(clim1, clim2) + assert clim1 == clim2 + + def test_can_plot_all_nans(self): + # regression test for issue #1780 + self.plotfunc(DataArray(np.full((2, 2), np.nan))) + + def test_can_plot_axis_size_one(self): + if self.plotfunc.__name__ not in ('contour', 'contourf'): + self.plotfunc(DataArray(np.ones((1, 1)))) + + def test_disallows_rgb_arg(self): + with pytest.raises(ValueError): + # Always invalid for most plots. Invalid for imshow with 2D data. + self.plotfunc(DataArray(np.ones((2, 2))), rgb='not None') def test_viridis_cmap(self): cmap_name = self.plotmethod(cmap='viridis').get_cmap().name - self.assertEqual('viridis', cmap_name) + assert 'viridis' == cmap_name def test_default_cmap(self): cmap_name = self.plotmethod().get_cmap().name - self.assertEqual('RdBu_r', cmap_name) + assert 'RdBu_r' == cmap_name cmap_name = self.plotfunc(abs(self.darray)).get_cmap().name - self.assertEqual('viridis', cmap_name) + assert 'viridis' == cmap_name @requires_seaborn def test_seaborn_palette_as_cmap(self): - cmap_name = self.plotmethod( - levels=2, cmap='husl').get_cmap().name - self.assertEqual('husl', cmap_name) + cmap_name = self.plotmethod(levels=2, cmap='husl').get_cmap().name + assert 'husl' == cmap_name def test_can_change_default_cmap(self): cmap_name = self.plotmethod(cmap='Blues').get_cmap().name - self.assertEqual('Blues', cmap_name) + assert 'Blues' == cmap_name def test_diverging_color_limits(self): artist = self.plotmethod() vmin, vmax = artist.get_clim() - self.assertAlmostEqual(-vmin, vmax) + assert round(abs(-vmin - vmax), 7) == 0 def test_xy_strings(self): self.plotmethod('y', 'x') ax = plt.gca() - self.assertEqual('y', ax.get_xlabel()) - self.assertEqual('x', ax.get_ylabel()) + assert 'y' == ax.get_xlabel() + assert 'x' == ax.get_ylabel() def test_positional_coord_string(self): self.plotmethod(y='x') ax = plt.gca() - self.assertEqual('x', ax.get_ylabel()) - self.assertEqual('y', ax.get_xlabel()) + assert 'x' == ax.get_ylabel() + assert 'y' == ax.get_xlabel() self.plotmethod(x='x') ax = plt.gca() - self.assertEqual('x', ax.get_xlabel()) - self.assertEqual('y', ax.get_ylabel()) + assert 'x' == ax.get_xlabel() + assert 'y' == ax.get_ylabel() def test_bad_x_string_exception(self): - with raises_regex( - ValueError, 'x and y must be coordinate variables'): + with raises_regex(ValueError, 'x and y must be coordinate variables'): self.plotmethod('not_a_real_dim', 'y') - with raises_regex( - ValueError, 'x must be a dimension name if y is not supplied'): + with raises_regex(ValueError, + 'x must be a dimension name if y is not supplied'): self.plotmethod(x='not_a_real_dim') - with raises_regex( - ValueError, 'y must be a dimension name if x is not supplied'): + with raises_regex(ValueError, + 'y must be a dimension name if x is not supplied'): self.plotmethod(y='not_a_real_dim') self.darray.coords['z'] = 100 def test_coord_strings(self): # 1d coords (same as dims) - self.assertEqual({'x', 'y'}, set(self.darray.dims)) + assert {'x', 'y'} == set(self.darray.dims) self.plotmethod(y='y', x='x') def test_non_linked_coords(self): @@ -690,11 +740,11 @@ def test_non_linked_coords(self): # Normal case, without transpose self.plotfunc(self.darray, x='x', y='newy') ax = plt.gca() - self.assertEqual('x', ax.get_xlabel()) - self.assertEqual('newy', ax.get_ylabel()) + assert 'x' == ax.get_xlabel() + assert 'newy' == ax.get_ylabel() # ax limits might change between plotfuncs # simply ensure that these high coords were passed over - self.assertTrue(np.min(ax.get_ylim()) > 100.) + assert np.min(ax.get_ylim()) > 100. def test_non_linked_coords_transpose(self): # plot with coordinate names that are not dimensions, @@ -704,11 +754,11 @@ def test_non_linked_coords_transpose(self): self.darray.coords['newy'] = self.darray.y + 150 self.plotfunc(self.darray, x='newy', y='x') ax = plt.gca() - self.assertEqual('newy', ax.get_xlabel()) - self.assertEqual('x', ax.get_ylabel()) + assert 'newy' == ax.get_xlabel() + assert 'x' == ax.get_ylabel() # ax limits might change between plotfuncs # simply ensure that these high coords were passed over - self.assertTrue(np.min(ax.get_xlim()) > 100.) + assert np.min(ax.get_xlim()) > 100. def test_default_title(self): a = DataArray(easy_array((4, 3, 2)), dims=['a', 'b', 'c']) @@ -716,56 +766,72 @@ def test_default_title(self): a.coords['d'] = u'foo' self.plotfunc(a.isel(c=1)) title = plt.gca().get_title() - self.assertTrue('c = 1, d = foo' == title or 'd = foo, c = 1' == title) + assert 'c = 1, d = foo' == title or 'd = foo, c = 1' == title def test_colorbar_default_label(self): self.darray.name = 'testvar' self.plotmethod(add_colorbar=True) - self.assertIn(self.darray.name, text_in_fig()) + assert self.darray.name in text_in_fig() def test_no_labels(self): self.darray.name = 'testvar' self.plotmethod(add_labels=False) alltxt = text_in_fig() for string in ['x', 'y', 'testvar']: - self.assertNotIn(string, alltxt) + assert string not in alltxt def test_colorbar_kwargs(self): # replace label self.darray.name = 'testvar' - self.plotmethod(add_colorbar=True, cbar_kwargs={'label':'MyLabel'}) + self.plotmethod(add_colorbar=True, cbar_kwargs={'label': 'MyLabel'}) alltxt = text_in_fig() - self.assertIn('MyLabel', alltxt) - self.assertNotIn('testvar', alltxt) + assert 'MyLabel' in alltxt + assert 'testvar' not in alltxt # you can use mapping types as well - self.plotmethod(add_colorbar=True, cbar_kwargs=(('label', 'MyLabel'),)) + self.plotmethod( + add_colorbar=True, cbar_kwargs=(('label', 'MyLabel'), )) alltxt = text_in_fig() - self.assertIn('MyLabel', alltxt) - self.assertNotIn('testvar', alltxt) + assert 'MyLabel' in alltxt + assert 'testvar' not in alltxt # change cbar ax fig, (ax, cax) = plt.subplots(1, 2) - self.plotmethod(ax=ax, cbar_ax=cax, add_colorbar=True, - cbar_kwargs={'label':'MyBar'}) - self.assertTrue(ax.has_data()) - self.assertTrue(cax.has_data()) + self.plotmethod( + ax=ax, + cbar_ax=cax, + add_colorbar=True, + cbar_kwargs={ + 'label': 'MyBar' + }) + assert ax.has_data() + assert cax.has_data() alltxt = text_in_fig() - self.assertIn('MyBar', alltxt) - self.assertNotIn('testvar', alltxt) + assert 'MyBar' in alltxt + assert 'testvar' not in alltxt # note that there are two ways to achieve this fig, (ax, cax) = plt.subplots(1, 2) - self.plotmethod(ax=ax, add_colorbar=True, - cbar_kwargs={'label':'MyBar', 'cax':cax}) - self.assertTrue(ax.has_data()) - self.assertTrue(cax.has_data()) + self.plotmethod( + ax=ax, + add_colorbar=True, + cbar_kwargs={ + 'label': 'MyBar', + 'cax': cax + }) + assert ax.has_data() + assert cax.has_data() alltxt = text_in_fig() - self.assertIn('MyBar', alltxt) - self.assertNotIn('testvar', alltxt) + assert 'MyBar' in alltxt + assert 'testvar' not in alltxt # see that no colorbar is respected self.plotmethod(add_colorbar=False) - self.assertNotIn('testvar', text_in_fig()) + assert 'testvar' not in text_in_fig() # check that error is raised - pytest.raises(ValueError, self.plotmethod, - add_colorbar=False, cbar_kwargs= {'label':'label'}) + pytest.raises( + ValueError, + self.plotmethod, + add_colorbar=False, + cbar_kwargs={ + 'label': 'label' + }) def test_verbose_facetgrid(self): a = easy_array((10, 15, 3)) @@ -773,54 +839,54 @@ def test_verbose_facetgrid(self): g = xplt.FacetGrid(d, col='z') g.map_dataarray(self.plotfunc, 'x', 'y') for ax in g.axes.flat: - self.assertTrue(ax.has_data()) + assert ax.has_data() def test_2d_function_and_method_signature_same(self): func_sig = inspect.getcallargs(self.plotfunc, self.darray) method_sig = inspect.getcallargs(self.plotmethod) del method_sig['_PlotMethods_obj'] del func_sig['darray'] - self.assertEqual(func_sig, method_sig) + assert func_sig == method_sig def test_convenient_facetgrid(self): a = easy_array((10, 15, 4)) d = DataArray(a, dims=['y', 'x', 'z']) g = self.plotfunc(d, x='x', y='y', col='z', col_wrap=2) - self.assertArrayEqual(g.axes.shape, [2, 2]) + assert_array_equal(g.axes.shape, [2, 2]) for (y, x), ax in np.ndenumerate(g.axes): - self.assertTrue(ax.has_data()) + assert ax.has_data() if x == 0: - self.assertEqual('y', ax.get_ylabel()) + assert 'y' == ax.get_ylabel() else: - self.assertEqual('', ax.get_ylabel()) + assert '' == ax.get_ylabel() if y == 1: - self.assertEqual('x', ax.get_xlabel()) + assert 'x' == ax.get_xlabel() else: - self.assertEqual('', ax.get_xlabel()) + assert '' == ax.get_xlabel() # Infering labels g = self.plotfunc(d, col='z', col_wrap=2) - self.assertArrayEqual(g.axes.shape, [2, 2]) + assert_array_equal(g.axes.shape, [2, 2]) for (y, x), ax in np.ndenumerate(g.axes): - self.assertTrue(ax.has_data()) + assert ax.has_data() if x == 0: - self.assertEqual('y', ax.get_ylabel()) + assert 'y' == ax.get_ylabel() else: - self.assertEqual('', ax.get_ylabel()) + assert '' == ax.get_ylabel() if y == 1: - self.assertEqual('x', ax.get_xlabel()) + assert 'x' == ax.get_xlabel() else: - self.assertEqual('', ax.get_xlabel()) + assert '' == ax.get_xlabel() def test_convenient_facetgrid_4d(self): a = easy_array((10, 15, 2, 3)) d = DataArray(a, dims=['y', 'x', 'columns', 'rows']) g = self.plotfunc(d, x='x', y='y', col='columns', row='rows') - self.assertArrayEqual(g.axes.shape, [3, 2]) + assert_array_equal(g.axes.shape, [3, 2]) for ax in g.axes.flat: - self.assertTrue(ax.has_data()) + assert ax.has_data() def test_facetgrid_cmap(self): # Regression test for GH592 @@ -828,9 +894,9 @@ def test_facetgrid_cmap(self): d = DataArray(data, dims=['x', 'y', 'time']) fg = d.plot.pcolormesh(col='time') # check that all color limits are the same - self.assertEqual(len(set(m.get_clim() for m in fg._mappables)), 1) + assert len(set(m.get_clim() for m in fg._mappables)) == 1 # check that all colormaps are the same - self.assertEqual(len(set(m.get_cmap().name for m in fg._mappables)), 1) + assert len(set(m.get_cmap().name for m in fg._mappables)) == 1 @pytest.mark.slow @@ -841,46 +907,46 @@ class TestContourf(Common2dMixin, PlotTestCase): @pytest.mark.slow def test_contourf_called(self): # Having both statements ensures the test works properly - self.assertFalse(self.contourf_called(self.darray.plot.imshow)) - self.assertTrue(self.contourf_called(self.darray.plot.contourf)) + assert not self.contourf_called(self.darray.plot.imshow) + assert self.contourf_called(self.darray.plot.contourf) def test_primitive_artist_returned(self): artist = self.plotmethod() - self.assertTrue(isinstance(artist, mpl.contour.QuadContourSet)) + assert isinstance(artist, mpl.contour.QuadContourSet) @pytest.mark.slow def test_extend(self): artist = self.plotmethod() - self.assertEqual(artist.extend, 'neither') + assert artist.extend == 'neither' self.darray[0, 0] = -100 self.darray[-1, -1] = 100 artist = self.plotmethod(robust=True) - self.assertEqual(artist.extend, 'both') + assert artist.extend == 'both' self.darray[0, 0] = 0 self.darray[-1, -1] = 0 artist = self.plotmethod(vmin=-0, vmax=10) - self.assertEqual(artist.extend, 'min') + assert artist.extend == 'min' artist = self.plotmethod(vmin=-10, vmax=0) - self.assertEqual(artist.extend, 'max') + assert artist.extend == 'max' @pytest.mark.slow def test_2d_coord_names(self): self.plotmethod(x='x2d', y='y2d') # make sure labels came out ok ax = plt.gca() - self.assertEqual('x2d', ax.get_xlabel()) - self.assertEqual('y2d', ax.get_ylabel()) + assert 'x2d' == ax.get_xlabel() + assert 'y2d' == ax.get_ylabel() @pytest.mark.slow def test_levels(self): artist = self.plotmethod(levels=[-0.5, -0.4, 0.1]) - self.assertEqual(artist.extend, 'both') + assert artist.extend == 'both' artist = self.plotmethod(levels=3) - self.assertEqual(artist.extend, 'neither') + assert artist.extend == 'neither' @pytest.mark.slow @@ -893,28 +959,24 @@ def test_colors(self): # when seaborn is used, instead we get an rgb tuple def _color_as_tuple(c): return tuple(c[:3]) + artist = self.plotmethod(colors='k') - self.assertEqual( - _color_as_tuple(artist.cmap.colors[0]), - (0.0, 0.0, 0.0)) + assert _color_as_tuple(artist.cmap.colors[0]) == \ + (0.0, 0.0, 0.0) artist = self.plotmethod(colors=['k', 'b']) - self.assertEqual( - _color_as_tuple(artist.cmap.colors[1]), - (0.0, 0.0, 1.0)) - - artist = self.darray.plot.contour(levels=[-0.5, 0., 0.5, 1.], - colors=['k', 'r', 'w', 'b']) - self.assertEqual( - _color_as_tuple(artist.cmap.colors[1]), - (1.0, 0.0, 0.0)) - self.assertEqual( - _color_as_tuple(artist.cmap.colors[2]), - (1.0, 1.0, 1.0)) + assert _color_as_tuple(artist.cmap.colors[1]) == \ + (0.0, 0.0, 1.0) + + artist = self.darray.plot.contour( + levels=[-0.5, 0., 0.5, 1.], colors=['k', 'r', 'w', 'b']) + assert _color_as_tuple(artist.cmap.colors[1]) == \ + (1.0, 0.0, 0.0) + assert _color_as_tuple(artist.cmap.colors[2]) == \ + (1.0, 1.0, 1.0) # the last color is now under "over" - self.assertEqual( - _color_as_tuple(artist.cmap._rgba_over), - (0.0, 0.0, 1.0)) + assert _color_as_tuple(artist.cmap._rgba_over) == \ + (0.0, 0.0, 1.0) def test_cmap_and_color_both(self): with pytest.raises(ValueError): @@ -929,8 +991,8 @@ def test_2d_coord_names(self): self.plotmethod(x='x2d', y='y2d') # make sure labels came out ok ax = plt.gca() - self.assertEqual('x2d', ax.get_xlabel()) - self.assertEqual('y2d', ax.get_ylabel()) + assert 'x2d' == ax.get_xlabel() + assert 'y2d' == ax.get_ylabel() def test_single_level(self): # this used to raise an error, but not anymore since @@ -945,19 +1007,19 @@ class TestPcolormesh(Common2dMixin, PlotTestCase): def test_primitive_artist_returned(self): artist = self.plotmethod() - self.assertTrue(isinstance(artist, mpl.collections.QuadMesh)) + assert isinstance(artist, mpl.collections.QuadMesh) def test_everything_plotted(self): artist = self.plotmethod() - self.assertEqual(artist.get_array().size, self.darray.size) + assert artist.get_array().size == self.darray.size @pytest.mark.slow def test_2d_coord_names(self): self.plotmethod(x='x2d', y='y2d') # make sure labels came out ok ax = plt.gca() - self.assertEqual('x2d', ax.get_xlabel()) - self.assertEqual('y2d', ax.get_ylabel()) + assert 'x2d' == ax.get_xlabel() + assert 'y2d' == ax.get_ylabel() def test_dont_infer_interval_breaks_for_cartopy(self): # Regression for GH 781 @@ -965,9 +1027,9 @@ def test_dont_infer_interval_breaks_for_cartopy(self): # Simulate a Cartopy Axis setattr(ax, 'projection', True) artist = self.plotmethod(x='x2d', y='y2d', ax=ax) - self.assertTrue(isinstance(artist, mpl.collections.QuadMesh)) + assert isinstance(artist, mpl.collections.QuadMesh) # Let cartopy handle the axis limits and artist size - self.assertTrue(artist.get_array().size <= self.darray.size) + assert artist.get_array().size <= self.darray.size @pytest.mark.slow @@ -978,17 +1040,17 @@ class TestImshow(Common2dMixin, PlotTestCase): @pytest.mark.slow def test_imshow_called(self): # Having both statements ensures the test works properly - self.assertFalse(self.imshow_called(self.darray.plot.contourf)) - self.assertTrue(self.imshow_called(self.darray.plot.imshow)) + assert not self.imshow_called(self.darray.plot.contourf) + assert self.imshow_called(self.darray.plot.imshow) def test_xy_pixel_centered(self): self.darray.plot.imshow(yincrease=False) - self.assertTrue(np.allclose([-0.5, 14.5], plt.gca().get_xlim())) - self.assertTrue(np.allclose([9.5, -0.5], plt.gca().get_ylim())) + assert np.allclose([-0.5, 14.5], plt.gca().get_xlim()) + assert np.allclose([9.5, -0.5], plt.gca().get_ylim()) def test_default_aspect_is_auto(self): self.darray.plot.imshow() - self.assertEqual('auto', plt.gca().get_aspect()) + assert 'auto' == plt.gca().get_aspect() @pytest.mark.slow def test_cannot_change_mpl_aspect(self): @@ -998,13 +1060,13 @@ def test_cannot_change_mpl_aspect(self): # with numbers we fall back to fig control self.darray.plot.imshow(size=5, aspect=2) - self.assertEqual('auto', plt.gca().get_aspect()) + assert 'auto' == plt.gca().get_aspect() assert tuple(plt.gcf().get_size_inches()) == (10, 5) @pytest.mark.slow def test_primitive_artist_returned(self): artist = self.plotmethod() - self.assertTrue(isinstance(artist, mpl.image.AxesImage)) + assert isinstance(artist, mpl.image.AxesImage) @pytest.mark.slow @requires_seaborn @@ -1016,13 +1078,82 @@ def test_2d_coord_names(self): with raises_regex(ValueError, 'requires 1D coordinates'): self.plotmethod(x='x2d', y='y2d') + def test_plot_rgb_image(self): + DataArray( + easy_array((10, 15, 3), start=0), + dims=['y', 'x', 'band'], + ).plot.imshow() + assert 0 == len(find_possible_colorbars()) + + def test_plot_rgb_image_explicit(self): + DataArray( + easy_array((10, 15, 3), start=0), + dims=['y', 'x', 'band'], + ).plot.imshow( + y='y', x='x', rgb='band') + assert 0 == len(find_possible_colorbars()) + + def test_plot_rgb_faceted(self): + DataArray( + easy_array((2, 2, 10, 15, 3), start=0), + dims=['a', 'b', 'y', 'x', 'band'], + ).plot.imshow( + row='a', col='b') + assert 0 == len(find_possible_colorbars()) + + def test_plot_rgba_image_transposed(self): + # We can handle the color axis being in any position + DataArray( + easy_array((4, 10, 15), start=0), + dims=['band', 'y', 'x'], + ).plot.imshow() + + def test_warns_ambigious_dim(self): + arr = DataArray(easy_array((3, 3, 3)), dims=['y', 'x', 'band']) + with pytest.warns(UserWarning): + arr.plot.imshow() + # but doesn't warn if dimensions specified + arr.plot.imshow(rgb='band') + arr.plot.imshow(x='x', y='y') + + def test_rgb_errors_too_many_dims(self): + arr = DataArray(easy_array((3, 3, 3, 3)), dims=['y', 'x', 'z', 'band']) + with pytest.raises(ValueError): + arr.plot.imshow(rgb='band') + + def test_rgb_errors_bad_dim_sizes(self): + arr = DataArray(easy_array((5, 5, 5)), dims=['y', 'x', 'band']) + with pytest.raises(ValueError): + arr.plot.imshow(rgb='band') + + def test_normalize_rgb_imshow(self): + for kwds in ( + dict(vmin=-1), dict(vmax=2), + dict(vmin=-1, vmax=1), dict(vmin=0, vmax=0), + dict(vmin=0, robust=True), dict(vmax=-1, robust=True), + ): + da = DataArray(easy_array((5, 5, 3), start=-0.6, stop=1.4)) + arr = da.plot.imshow(**kwds).get_array() + assert 0 <= arr.min() <= arr.max() <= 1, kwds + + def test_normalize_rgb_one_arg_error(self): + da = DataArray(easy_array((5, 5, 3), start=-0.6, stop=1.4)) + # If passed one bound that implies all out of range, error: + for kwds in [dict(vmax=-1), dict(vmin=2)]: + with pytest.raises(ValueError): + da.plot.imshow(**kwds) + # If passed two that's just moving the range, *not* an error: + for kwds in [dict(vmax=-1, vmin=-1.2), dict(vmin=2, vmax=2.1)]: + da.plot.imshow(**kwds) -class TestFacetGrid(PlotTestCase): +class TestFacetGrid(PlotTestCase): def setUp(self): d = easy_array((10, 15, 3)) - self.darray = DataArray(d, dims=['y', 'x', 'z'], - coords={'z': ['a', 'b', 'c']}) + self.darray = DataArray( + d, dims=['y', 'x', 'z'], coords={ + 'z': ['a', 'b', 'c'] + }) self.g = xplt.FacetGrid(self.darray, col='z') @pytest.mark.slow @@ -1031,22 +1162,22 @@ def test_no_args(self): # Don't want colorbar labeled with 'None' alltxt = text_in_fig() - self.assertNotIn('None', alltxt) + assert 'None' not in alltxt for ax in self.g.axes.flat: - self.assertTrue(ax.has_data()) + assert ax.has_data() @pytest.mark.slow def test_names_appear_somewhere(self): self.darray.name = 'testvar' self.g.map_dataarray(xplt.contourf, 'x', 'y') for k, ax in zip('abc', self.g.axes.flat): - self.assertEqual('z = {0}'.format(k), ax.get_title()) + assert 'z = {0}'.format(k) == ax.get_title() alltxt = text_in_fig() - self.assertIn(self.darray.name, alltxt) + assert self.darray.name in alltxt for label in ['x', 'y']: - self.assertIn(label, alltxt) + assert label in alltxt @pytest.mark.slow def test_text_not_super_long(self): @@ -1055,10 +1186,10 @@ def test_text_not_super_long(self): g.map_dataarray(xplt.contour, 'x', 'y') alltxt = text_in_fig() maxlen = max(len(txt) for txt in alltxt) - self.assertLess(maxlen, 50) + assert maxlen < 50 t0 = g.axes[0, 0].get_title() - self.assertTrue(t0.endswith('...')) + assert t0.endswith('...') @pytest.mark.slow def test_colorbar(self): @@ -1070,9 +1201,9 @@ def test_colorbar(self): for image in plt.gcf().findobj(mpl.image.AxesImage): clim = np.array(image.get_clim()) - self.assertTrue(np.allclose(expected, clim)) + assert np.allclose(expected, clim) - self.assertEqual(1, len(find_possible_colorbars())) + assert 1 == len(find_possible_colorbars()) @pytest.mark.slow def test_empty_cell(self): @@ -1080,8 +1211,8 @@ def test_empty_cell(self): g.map_dataarray(xplt.imshow, 'x', 'y') bottomright = g.axes[-1, -1] - self.assertFalse(bottomright.has_data()) - self.assertFalse(bottomright.get_visible()) + assert not bottomright.has_data() + assert not bottomright.get_visible() @pytest.mark.slow def test_norow_nocol_error(self): @@ -1095,7 +1226,7 @@ def test_groups(self): upperleft_array = self.darray.loc[upperleft_dict] z0 = self.darray.isel(z=0) - self.assertDataArrayEqual(upperleft_array, z0) + assert_equal(upperleft_array, z0) @pytest.mark.slow def test_float_index(self): @@ -1129,7 +1260,7 @@ def test_robust(self): except ValueError: pass largest = max(abs(x) for x in numbers) - self.assertLess(largest, 21) + assert largest < 21 @pytest.mark.slow def test_can_set_vmin_vmax(self): @@ -1139,31 +1270,31 @@ def test_can_set_vmin_vmax(self): for image in plt.gcf().findobj(mpl.image.AxesImage): clim = np.array(image.get_clim()) - self.assertTrue(np.allclose(expected, clim)) + assert np.allclose(expected, clim) @pytest.mark.slow def test_can_set_norm(self): norm = mpl.colors.SymLogNorm(0.1) self.g.map_dataarray(xplt.imshow, 'x', 'y', norm=norm) for image in plt.gcf().findobj(mpl.image.AxesImage): - self.assertIs(image.norm, norm) + assert image.norm is norm @pytest.mark.slow def test_figure_size(self): - self.assertArrayEqual(self.g.fig.get_size_inches(), (10, 3)) + assert_array_equal(self.g.fig.get_size_inches(), (10, 3)) g = xplt.FacetGrid(self.darray, col='z', size=6) - self.assertArrayEqual(g.fig.get_size_inches(), (19, 6)) + assert_array_equal(g.fig.get_size_inches(), (19, 6)) g = self.darray.plot.imshow(col='z', size=6) - self.assertArrayEqual(g.fig.get_size_inches(), (19, 6)) + assert_array_equal(g.fig.get_size_inches(), (19, 6)) g = xplt.FacetGrid(self.darray, col='z', size=4, aspect=0.5) - self.assertArrayEqual(g.fig.get_size_inches(), (7, 4)) + assert_array_equal(g.fig.get_size_inches(), (7, 4)) g = xplt.FacetGrid(self.darray, col='z', figsize=(9, 4)) - self.assertArrayEqual(g.fig.get_size_inches(), (9, 4)) + assert_array_equal(g.fig.get_size_inches(), (9, 4)) with raises_regex(ValueError, "cannot provide both"): g = xplt.plot(self.darray, row=2, col='z', figsize=(6, 4), size=6) @@ -1181,10 +1312,10 @@ def test_num_ticks(self): for ax in self.g.axes.flat: xticks = len(ax.get_xticks()) yticks = len(ax.get_yticks()) - self.assertLessEqual(xticks, maxticks) - self.assertLessEqual(yticks, maxticks) - self.assertGreaterEqual(xticks, nticks / 2.0) - self.assertGreaterEqual(yticks, nticks / 2.0) + assert xticks <= maxticks + assert yticks <= maxticks + assert xticks >= nticks / 2.0 + assert yticks >= nticks / 2.0 @pytest.mark.slow def test_map(self): @@ -1198,17 +1329,17 @@ def test_map_dataset(self): alltxt = text_in_fig() for label in ['x', 'y']: - self.assertIn(label, alltxt) + assert label in alltxt # everything has a label - self.assertNotIn('None', alltxt) + assert 'None' not in alltxt # colorbar can't be inferred automatically - self.assertNotIn('foo', alltxt) - self.assertEqual(0, len(find_possible_colorbars())) + assert 'foo' not in alltxt + assert 0 == len(find_possible_colorbars()) g.add_colorbar(label='colors!') - self.assertIn('colors!', text_in_fig()) - self.assertEqual(1, len(find_possible_colorbars())) + assert 'colors!' in text_in_fig() + assert 1 == len(find_possible_colorbars()) @pytest.mark.slow def test_set_axis_labels(self): @@ -1216,7 +1347,7 @@ def test_set_axis_labels(self): g.set_axis_labels('longitude', 'latitude') alltxt = text_in_fig() for label in ['longitude', 'latitude']: - self.assertIn(label, alltxt) + assert label in alltxt @pytest.mark.slow def test_facetgrid_colorbar(self): @@ -1224,52 +1355,52 @@ def test_facetgrid_colorbar(self): d = DataArray(a, dims=['y', 'x', 'z'], name='foo') d.plot.imshow(x='x', y='y', col='z') - self.assertEqual(1, len(find_possible_colorbars())) + assert 1 == len(find_possible_colorbars()) d.plot.imshow(x='x', y='y', col='z', add_colorbar=True) - self.assertEqual(1, len(find_possible_colorbars())) + assert 1 == len(find_possible_colorbars()) d.plot.imshow(x='x', y='y', col='z', add_colorbar=False) - self.assertEqual(0, len(find_possible_colorbars())) + assert 0 == len(find_possible_colorbars()) @pytest.mark.slow def test_facetgrid_polar(self): # test if polar projection in FacetGrid does not raise an exception - self.darray.plot.pcolormesh(col='z', - subplot_kws=dict(projection='polar'), - sharex=False, sharey=False) + self.darray.plot.pcolormesh( + col='z', + subplot_kws=dict(projection='polar'), + sharex=False, + sharey=False) class TestFacetGrid4d(PlotTestCase): - def setUp(self): a = easy_array((10, 15, 3, 2)) darray = DataArray(a, dims=['y', 'x', 'col', 'row']) - darray.coords['col'] = np.array(['col' + str(x) for x in - darray.coords['col'].values]) - darray.coords['row'] = np.array(['row' + str(x) for x in - darray.coords['row'].values]) + darray.coords['col'] = np.array( + ['col' + str(x) for x in darray.coords['col'].values]) + darray.coords['row'] = np.array( + ['row' + str(x) for x in darray.coords['row'].values]) self.darray = darray @pytest.mark.slow def test_default_labels(self): g = xplt.FacetGrid(self.darray, col='col', row='row') - self.assertEqual((2, 3), g.axes.shape) + assert (2, 3) == g.axes.shape g.map_dataarray(xplt.imshow, 'x', 'y') # Rightmost column should be labeled for label, ax in zip(self.darray.coords['row'].values, g.axes[:, -1]): - self.assertTrue(substring_in_axes(label, ax)) + assert substring_in_axes(label, ax) # Top row should be labeled for label, ax in zip(self.darray.coords['col'].values, g.axes[0, :]): - self.assertTrue(substring_in_axes(label, ax)) + assert substring_in_axes(label, ax) class TestDatetimePlot(PlotTestCase): - def setUp(self): ''' Create a DataArray with a time-axis that contains datetime objects. diff --git a/xarray/tests/test_tutorial.py b/xarray/tests/test_tutorial.py index 56bdcce..9ad797a 100644 --- a/xarray/tests/test_tutorial.py +++ b/xarray/tests/test_tutorial.py @@ -3,12 +3,11 @@ from __future__ import print_function import os -import pytest from xarray import tutorial, DataArray from xarray.core.pycompat import suppress -from . import TestCase, network +from . import TestCase, network, assert_identical @network @@ -26,4 +25,4 @@ def setUp(self): def test_download_from_github(self): ds = tutorial.load_dataset(self.testfile) tiny = DataArray(range(5), name='tiny').to_dataset() - self.assertDatasetIdentical(ds, tiny) + assert_identical(ds, tiny) diff --git a/xarray/tests/test_ufuncs.py b/xarray/tests/test_ufuncs.py index af7d6e1..a428196 100644 --- a/xarray/tests/test_ufuncs.py +++ b/xarray/tests/test_ufuncs.py @@ -8,16 +8,17 @@ import xarray.ufuncs as xu import xarray as xr -from . import TestCase, raises_regex +from . import ( + TestCase, raises_regex, assert_identical, assert_array_equal) class TestOps(TestCase): - def assertIdentical(self, a, b): + def assert_identical(self, a, b): assert type(a) is type(b) or (float(a) == float(b)) try: assert a.identical(b), (a, b) except AttributeError: - self.assertArrayEqual(a, b) + assert_array_equal(a, b) def test_unary(self): args = [0, @@ -26,7 +27,7 @@ def test_unary(self): xr.DataArray([0, 0], dims='x'), xr.Dataset({'y': ('x', [0, 0])})] for a in args: - self.assertIdentical(a + 1, xu.cos(a)) + self.assert_identical(a + 1, xu.cos(a)) def test_binary(self): args = [0, @@ -36,10 +37,10 @@ def test_binary(self): xr.Dataset({'y': ('x', [0, 0])})] for n, t1 in enumerate(args): for t2 in args[n:]: - self.assertIdentical(t2 + 1, xu.maximum(t1, t2 + 1)) - self.assertIdentical(t2 + 1, xu.maximum(t2, t1 + 1)) - self.assertIdentical(t2 + 1, xu.maximum(t1 + 1, t2)) - self.assertIdentical(t2 + 1, xu.maximum(t2 + 1, t1)) + self.assert_identical(t2 + 1, xu.maximum(t1, t2 + 1)) + self.assert_identical(t2 + 1, xu.maximum(t2, t1 + 1)) + self.assert_identical(t2 + 1, xu.maximum(t1 + 1, t2)) + self.assert_identical(t2 + 1, xu.maximum(t2 + 1, t1)) def test_groupby(self): ds = xr.Dataset({'a': ('x', [0, 0, 0])}, {'c': ('x', [0, 0, 1])}) @@ -47,17 +48,17 @@ def test_groupby(self): group_mean = ds_grouped.mean('x') arr_grouped = ds['a'].groupby('c') - self.assertIdentical(ds, xu.maximum(ds_grouped, group_mean)) - self.assertIdentical(ds, xu.maximum(group_mean, ds_grouped)) + assert_identical(ds, xu.maximum(ds_grouped, group_mean)) + assert_identical(ds, xu.maximum(group_mean, ds_grouped)) - self.assertIdentical(ds, xu.maximum(arr_grouped, group_mean)) - self.assertIdentical(ds, xu.maximum(group_mean, arr_grouped)) + assert_identical(ds, xu.maximum(arr_grouped, group_mean)) + assert_identical(ds, xu.maximum(group_mean, arr_grouped)) - self.assertIdentical(ds, xu.maximum(ds_grouped, group_mean['a'])) - self.assertIdentical(ds, xu.maximum(group_mean['a'], ds_grouped)) + assert_identical(ds, xu.maximum(ds_grouped, group_mean['a'])) + assert_identical(ds, xu.maximum(group_mean['a'], ds_grouped)) - self.assertIdentical(ds.a, xu.maximum(arr_grouped, group_mean.a)) - self.assertIdentical(ds.a, xu.maximum(group_mean.a, arr_grouped)) + assert_identical(ds.a, xu.maximum(arr_grouped, group_mean.a)) + assert_identical(ds.a, xu.maximum(group_mean.a, arr_grouped)) with raises_regex(TypeError, 'only support binary ops'): xu.maximum(ds.a.variable, ds_grouped) @@ -65,4 +66,4 @@ def test_groupby(self): def test_pickle(self): a = 1.0 cos_pickled = pickle.loads(pickle.dumps(xu.cos)) - self.assertIdentical(cos_pickled(a), xu.cos(a)) + self.assert_identical(cos_pickled(a), xu.cos(a)) diff --git a/xarray/tests/test_utils.py b/xarray/tests/test_utils.py index c1df1da..1a008ef 100644 --- a/xarray/tests/test_utils.py +++ b/xarray/tests/test_utils.py @@ -1,7 +1,6 @@ from __future__ import absolute_import from __future__ import division from __future__ import print_function -import pickle import pytest import numpy as np @@ -9,7 +8,7 @@ from xarray.core import duck_array_ops, utils from xarray.core.pycompat import OrderedDict -from . import TestCase, requires_dask +from . import TestCase, requires_dask, assert_array_equal class TestAlias(TestCase): @@ -18,7 +17,7 @@ def new_method(): pass old_method = utils.alias(new_method, 'old_method') assert 'deprecated' in old_method.__doc__ - with self.assertWarns('deprecated'): + with pytest.warns(Warning, match='deprecated'): old_method() @@ -32,10 +31,10 @@ def test(self): (pd.Index(x, dtype=object), x.astype(object)), (pd.Index(td), td), (pd.Index(td, dtype=object), td.astype(object)), - ]: + ]: actual = utils.safe_cast_to_index(array) - self.assertArrayEqual(expected, actual) - self.assertEqual(expected.dtype, actual.dtype) + assert_array_equal(expected, actual) + assert expected.dtype == actual.dtype def test_multiindex_from_product_levels(): @@ -53,12 +52,10 @@ class TestArrayEquiv(TestCase): def test_0d(self): # verify our work around for pd.isnull not working for 0-dimensional # object arrays - self.assertTrue( - duck_array_ops.array_equiv(0, np.array(0, dtype=object))) - self.assertTrue( - duck_array_ops.array_equiv(np.nan, np.array(np.nan, dtype=object))) - self.assertFalse( - duck_array_ops.array_equiv(0, np.array(1, dtype=object))) + assert duck_array_ops.array_equiv(0, np.array(0, dtype=object)) + assert duck_array_ops.array_equiv(np.nan, + np.array(np.nan, dtype=object)) + assert not duck_array_ops.array_equiv(0, np.array(1, dtype=object)) class TestDictionaries(TestCase): @@ -68,13 +65,13 @@ def setUp(self): self.z = {'a': 'Z'} def test_equivalent(self): - self.assertTrue(utils.equivalent(0, 0)) - self.assertTrue(utils.equivalent(np.nan, np.nan)) - self.assertTrue(utils.equivalent(0, np.array(0.0))) - self.assertTrue(utils.equivalent([0], np.array([0]))) - self.assertTrue(utils.equivalent(np.array([0]), [0])) - self.assertTrue(utils.equivalent(np.arange(3), 1.0 * np.arange(3))) - self.assertFalse(utils.equivalent(0, np.zeros(3))) + assert utils.equivalent(0, 0) + assert utils.equivalent(np.nan, np.nan) + assert utils.equivalent(0, np.array(0.0)) + assert utils.equivalent([0], np.array([0])) + assert utils.equivalent(np.array([0]), [0]) + assert utils.equivalent(np.arange(3), 1.0 * np.arange(3)) + assert not utils.equivalent(0, np.zeros(3)) def test_safe(self): # should not raise exception: @@ -85,9 +82,9 @@ def test_unsafe(self): utils.update_safety_check(self.x, self.z) def test_ordered_dict_intersection(self): - self.assertEqual({'b': 'B'}, - utils.ordered_dict_intersection(self.x, self.y)) - self.assertEqual({}, utils.ordered_dict_intersection(self.x, self.z)) + assert {'b': 'B'} == \ + utils.ordered_dict_intersection(self.x, self.y) + assert {} == utils.ordered_dict_intersection(self.x, self.z) def test_dict_equiv(self): x = OrderedDict() @@ -96,23 +93,23 @@ def test_dict_equiv(self): y = OrderedDict() y['b'] = np.array([1.0, 2.0, 3.0]) y['a'] = 3 - self.assertTrue(utils.dict_equiv(x, y)) # two nparrays are equal + assert utils.dict_equiv(x, y) # two nparrays are equal y['b'] = [1, 2, 3] # np.array not the same as a list - self.assertTrue(utils.dict_equiv(x, y)) # nparray == list + assert utils.dict_equiv(x, y) # nparray == list x['b'] = [1.0, 2.0, 3.0] - self.assertTrue(utils.dict_equiv(x, y)) # list vs. list + assert utils.dict_equiv(x, y) # list vs. list x['c'] = None - self.assertFalse(utils.dict_equiv(x, y)) # new key in x + assert not utils.dict_equiv(x, y) # new key in x x['c'] = np.nan y['c'] = np.nan - self.assertTrue(utils.dict_equiv(x, y)) # as intended, nan is nan + assert utils.dict_equiv(x, y) # as intended, nan is nan x['c'] = np.inf y['c'] = np.inf - self.assertTrue(utils.dict_equiv(x, y)) # inf == inf + assert utils.dict_equiv(x, y) # inf == inf y = dict(y) - self.assertTrue(utils.dict_equiv(x, y)) # different dictionary types are fine + assert utils.dict_equiv(x, y) # different dictionary types are fine y['b'] = 3 * np.arange(3) - self.assertFalse(utils.dict_equiv(x, y)) # not equal when arrays differ + assert not utils.dict_equiv(x, y) # not equal when arrays differ def test_frozen(self): x = utils.Frozen(self.x) @@ -122,28 +119,28 @@ def test_frozen(self): del x['a'] with pytest.raises(AttributeError): x.update(self.y) - self.assertEqual(x.mapping, self.x) - self.assertIn(repr(x), ("Frozen({'a': 'A', 'b': 'B'})", - "Frozen({'b': 'B', 'a': 'A'})")) + assert x.mapping == self.x + assert repr(x) in ("Frozen({'a': 'A', 'b': 'B'})", + "Frozen({'b': 'B', 'a': 'A'})") def test_sorted_keys_dict(self): x = {'a': 1, 'b': 2, 'c': 3} y = utils.SortedKeysDict(x) self.assertItemsEqual(y, ['a', 'b', 'c']) - self.assertEqual(repr(utils.SortedKeysDict()), - "SortedKeysDict({})") + assert repr(utils.SortedKeysDict()) == \ + "SortedKeysDict({})" def test_chain_map(self): m = utils.ChainMap({'x': 0, 'y': 1}, {'x': -100, 'z': 2}) - self.assertIn('x', m) - self.assertIn('y', m) - self.assertIn('z', m) - self.assertEqual(m['x'], 0) - self.assertEqual(m['y'], 1) - self.assertEqual(m['z'], 2) + assert 'x' in m + assert 'y' in m + assert 'z' in m + assert m['x'] == 0 + assert m['y'] == 1 + assert m['z'] == 2 m['x'] = 100 - self.assertEqual(m['x'], 100) - self.assertEqual(m.maps[0]['x'], 100) + assert m['x'] == 100 + assert m.maps[0]['x'] == 100 self.assertItemsEqual(['x', 'y', 'z'], m) @@ -155,31 +152,31 @@ def test_repr_object(): class Test_is_uniform_and_sorted(TestCase): def test_sorted_uniform(self): - self.assertTrue(utils.is_uniform_spaced(np.arange(5))) + assert utils.is_uniform_spaced(np.arange(5)) def test_sorted_not_uniform(self): - self.assertEqual(False, utils.is_uniform_spaced([-2, 1, 89])) + assert not utils.is_uniform_spaced([-2, 1, 89]) def test_not_sorted_uniform(self): - self.assertEqual(False, utils.is_uniform_spaced([1, -1, 3])) + assert not utils.is_uniform_spaced([1, -1, 3]) def test_not_sorted_not_uniform(self): - self.assertEqual(False, utils.is_uniform_spaced([4, 1, 89])) + assert not utils.is_uniform_spaced([4, 1, 89]) def test_two_numbers(self): - self.assertTrue(utils.is_uniform_spaced([0, 1.7])) + assert utils.is_uniform_spaced([0, 1.7]) def test_relative_tolerance(self): - self.assertTrue(utils.is_uniform_spaced([0, 0.97, 2], rtol=0.1)) + assert utils.is_uniform_spaced([0, 0.97, 2], rtol=0.1) class Test_hashable(TestCase): def test_hashable(self): for v in [False, 1, (2, ), (3, 4), 'four']: - self.assertTrue(utils.hashable(v)) + assert utils.hashable(v) for v in [[5, 6], ['seven', '8'], {9: 'ten'}]: - self.assertFalse(utils.hashable(v)) + assert not utils.hashable(v) @requires_dask @@ -189,3 +186,18 @@ def test_dask_array_is_scalar(): y = da.arange(8, chunks=4) assert not utils.is_scalar(y) + + +def test_hidden_key_dict(): + hidden_key = '_hidden_key' + data = {'a': 1, 'b': 2, hidden_key: 3} + data_expected = {'a': 1, 'b': 2} + hkd = utils.HiddenKeyDict(data, [hidden_key]) + assert len(hkd) == 2 + assert hidden_key not in hkd + for k, v in data_expected.items(): + assert hkd[k] == v + with pytest.raises(KeyError): + hkd[hidden_key] + with pytest.raises(KeyError): + del hkd[hidden_key] diff --git a/xarray/tests/test_variable.py b/xarray/tests/test_variable.py index bdaee5e..5a89627 100644 --- a/xarray/tests/test_variable.py +++ b/xarray/tests/test_variable.py @@ -1,3 +1,4 @@ + from __future__ import absolute_import from __future__ import division from __future__ import print_function @@ -24,39 +25,43 @@ from xarray.core.common import full_like, zeros_like, ones_like from xarray.core.utils import NDArrayMixin -from . import TestCase, source_ndarray, requires_dask, raises_regex +from . import ( + TestCase, source_ndarray, requires_dask, raises_regex, assert_identical, + assert_array_equal, assert_equal, assert_allclose) + +from xarray.tests import requires_bottleneck class VariableSubclassTestCases(object): def test_properties(self): data = 0.5 * np.arange(10) v = self.cls(['time'], data, {'foo': 'bar'}) - self.assertEqual(v.dims, ('time',)) - self.assertArrayEqual(v.values, data) - self.assertEqual(v.dtype, float) - self.assertEqual(v.shape, (10,)) - self.assertEqual(v.size, 10) - self.assertEqual(v.sizes, {'time': 10}) - self.assertEqual(v.nbytes, 80) - self.assertEqual(v.ndim, 1) - self.assertEqual(len(v), 10) - self.assertEqual(v.attrs, {'foo': u'bar'}) + assert v.dims == ('time',) + assert_array_equal(v.values, data) + assert v.dtype == float + assert v.shape == (10,) + assert v.size == 10 + assert v.sizes == {'time': 10} + assert v.nbytes == 80 + assert v.ndim == 1 + assert len(v) == 10 + assert v.attrs == {'foo': u'bar'} def test_attrs(self): v = self.cls(['time'], 0.5 * np.arange(10)) - self.assertEqual(v.attrs, {}) + assert v.attrs == {} attrs = {'foo': 'bar'} v.attrs = attrs - self.assertEqual(v.attrs, attrs) - self.assertIsInstance(v.attrs, OrderedDict) + assert v.attrs == attrs + assert isinstance(v.attrs, OrderedDict) v.attrs['foo'] = 'baz' - self.assertEqual(v.attrs['foo'], 'baz') + assert v.attrs['foo'] == 'baz' def test_getitem_dict(self): v = self.cls(['x'], np.random.randn(5)) actual = v[{'x': 0}] expected = v[0] - self.assertVariableIdentical(expected, actual) + assert_identical(expected, actual) def test_getitem_1d(self): data = np.array([0, 1, 2]) @@ -64,24 +69,24 @@ def test_getitem_1d(self): v_new = v[dict(x=[0, 1])] assert v_new.dims == ('x', ) - self.assertArrayEqual(v_new, data[[0, 1]]) + assert_array_equal(v_new, data[[0, 1]]) v_new = v[dict(x=slice(None))] assert v_new.dims == ('x', ) - self.assertArrayEqual(v_new, data) + assert_array_equal(v_new, data) v_new = v[dict(x=Variable('a', [0, 1]))] assert v_new.dims == ('a', ) - self.assertArrayEqual(v_new, data[[0, 1]]) + assert_array_equal(v_new, data[[0, 1]]) v_new = v[dict(x=1)] assert v_new.dims == () - self.assertArrayEqual(v_new, data[1]) + assert_array_equal(v_new, data[1]) # tuple argument v_new = v[slice(None)] assert v_new.dims == ('x', ) - self.assertArrayEqual(v_new, data) + assert_array_equal(v_new, data) def test_getitem_1d_fancy(self): v = self.cls(['x'], [0, 1, 2]) @@ -90,41 +95,62 @@ def test_getitem_1d_fancy(self): v_new = v[ind] assert v_new.dims == ('a', 'b') expected = np.array(v._data)[([0, 1], [0, 1]), ] - self.assertArrayEqual(v_new, expected) + assert_array_equal(v_new, expected) # boolean indexing ind = Variable(('x', ), [True, False, True]) v_new = v[ind] - self.assertVariableIdentical(v[[0, 2]], v_new) + assert_identical(v[[0, 2]], v_new) v_new = v[[True, False, True]] - self.assertVariableIdentical(v[[0, 2]], v_new) + assert_identical(v[[0, 2]], v_new) with raises_regex(IndexError, "Boolean indexer should"): ind = Variable(('a', ), [True, False, True]) v[ind] + def test_getitem_with_mask(self): + v = self.cls(['x'], [0, 1, 2]) + assert_identical(v._getitem_with_mask(-1), Variable((), np.nan)) + assert_identical(v._getitem_with_mask([0, -1, 1]), + self.cls(['x'], [0, np.nan, 1])) + assert_identical(v._getitem_with_mask(slice(2)), + self.cls(['x'], [0, 1])) + assert_identical(v._getitem_with_mask([0, -1, 1], fill_value=-99), + self.cls(['x'], [0, -99, 1])) + + def test_getitem_with_mask_size_zero(self): + v = self.cls(['x'], []) + assert_identical(v._getitem_with_mask(-1), Variable((), np.nan)) + assert_identical(v._getitem_with_mask([-1, -1, -1]), + self.cls(['x'], [np.nan, np.nan, np.nan])) + + def test_getitem_with_mask_nd_indexer(self): + v = self.cls(['x'], [0, 1, 2]) + indexer = Variable(('x', 'y'), [[0, -1], [-1, 2]]) + assert_identical(v._getitem_with_mask(indexer, fill_value=-1), indexer) + def _assertIndexedLikeNDArray(self, variable, expected_value0, expected_dtype=None): """Given a 1-dimensional variable, verify that the variable is indexed like a numpy.ndarray. """ - self.assertEqual(variable[0].shape, ()) - self.assertEqual(variable[0].ndim, 0) - self.assertEqual(variable[0].size, 1) + assert variable[0].shape == () + assert variable[0].ndim == 0 + assert variable[0].size == 1 # test identity - self.assertTrue(variable.equals(variable.copy())) - self.assertTrue(variable.identical(variable.copy())) + assert variable.equals(variable.copy()) + assert variable.identical(variable.copy()) # check value is equal for both ndarray and Variable - self.assertEqual(variable.values[0], expected_value0) - self.assertEqual(variable[0].values, expected_value0) + assert variable.values[0] == expected_value0 + assert variable[0].values == expected_value0 # check type or dtype is consistent for both ndarray and Variable if expected_dtype is None: # check output type instead of array dtype - self.assertEqual(type(variable.values[0]), type(expected_value0)) - self.assertEqual(type(variable[0].values), type(expected_value0)) + assert type(variable.values[0]) == type(expected_value0) + assert type(variable[0].values) == type(expected_value0) elif expected_dtype is not False: - self.assertEqual(variable.values[0].dtype, expected_dtype) - self.assertEqual(variable[0].values.dtype, expected_dtype) + assert variable.values[0].dtype == expected_dtype + assert variable[0].values.dtype == expected_dtype def test_index_0d_int(self): for value, dtype in [(0, np.int_), @@ -159,10 +185,12 @@ def test_index_0d_timedelta64(self): td = timedelta(hours=1) x = self.cls(['x'], [np.timedelta64(td)]) - self._assertIndexedLikeNDArray(x, np.timedelta64(td), 'timedelta64[ns]') + self._assertIndexedLikeNDArray( + x, np.timedelta64(td), 'timedelta64[ns]') x = self.cls(['x'], pd.to_timedelta([td])) - self._assertIndexedLikeNDArray(x, np.timedelta64(td), 'timedelta64[ns]') + self._assertIndexedLikeNDArray( + x, np.timedelta64(td), 'timedelta64[ns]') def test_index_0d_not_a_time(self): d = np.datetime64('NaT', 'ns') @@ -192,9 +220,9 @@ def test_0d_object_array_with_list(self): listarray = np.empty((1,), dtype=object) listarray[0] = [1, 2, 3] x = self.cls('x', listarray) - self.assertArrayEqual(x.data, listarray) - self.assertArrayEqual(x[0].data, listarray.squeeze()) - self.assertArrayEqual(x.squeeze().data, listarray.squeeze()) + assert_array_equal(x.data, listarray) + assert_array_equal(x[0].data, listarray.squeeze()) + assert_array_equal(x.squeeze().data, listarray.squeeze()) def test_index_and_concat_datetime(self): # regression test for #125 @@ -206,61 +234,61 @@ def test_index_and_concat_datetime(self): [expected[i:(i + 1)] for i in range(10)], [expected[[i]] for i in range(10)]]: actual = Variable.concat(times, 't') - self.assertEqual(expected.dtype, actual.dtype) - self.assertArrayEqual(expected, actual) + assert expected.dtype == actual.dtype + assert_array_equal(expected, actual) def test_0d_time_data(self): # regression test for #105 x = self.cls('time', pd.date_range('2000-01-01', periods=5)) expected = np.datetime64('2000-01-01', 'ns') - self.assertEqual(x[0].values, expected) + assert x[0].values == expected def test_datetime64_conversion(self): times = pd.date_range('2000-01-01', periods=3) for values, preserve_source in [ - (times, True), - (times.values, True), - (times.values.astype('datetime64[s]'), False), - (times.to_pydatetime(), False), - ]: + (times, True), + (times.values, True), + (times.values.astype('datetime64[s]'), False), + (times.to_pydatetime(), False), + ]: v = self.cls(['t'], values) - self.assertEqual(v.dtype, np.dtype('datetime64[ns]')) - self.assertArrayEqual(v.values, times.values) - self.assertEqual(v.values.dtype, np.dtype('datetime64[ns]')) + assert v.dtype == np.dtype('datetime64[ns]') + assert_array_equal(v.values, times.values) + assert v.values.dtype == np.dtype('datetime64[ns]') same_source = source_ndarray(v.values) is source_ndarray(values) assert preserve_source == same_source def test_timedelta64_conversion(self): times = pd.timedelta_range(start=0, periods=3) for values, preserve_source in [ - (times, True), - (times.values, True), - (times.values.astype('timedelta64[s]'), False), - (times.to_pytimedelta(), False), - ]: + (times, True), + (times.values, True), + (times.values.astype('timedelta64[s]'), False), + (times.to_pytimedelta(), False), + ]: v = self.cls(['t'], values) - self.assertEqual(v.dtype, np.dtype('timedelta64[ns]')) - self.assertArrayEqual(v.values, times.values) - self.assertEqual(v.values.dtype, np.dtype('timedelta64[ns]')) + assert v.dtype == np.dtype('timedelta64[ns]') + assert_array_equal(v.values, times.values) + assert v.values.dtype == np.dtype('timedelta64[ns]') same_source = source_ndarray(v.values) is source_ndarray(values) assert preserve_source == same_source def test_object_conversion(self): data = np.arange(5).astype(str).astype(object) actual = self.cls('x', data) - self.assertEqual(actual.dtype, data.dtype) + assert actual.dtype == data.dtype def test_pandas_data(self): v = self.cls(['x'], pd.Series([0, 1, 2], index=[3, 2, 1])) - self.assertVariableIdentical(v, v[[0, 1, 2]]) + assert_identical(v, v[[0, 1, 2]]) v = self.cls(['x'], pd.Index([0, 1, 2])) - self.assertEqual(v[0].values, v.values[0]) + assert v[0].values == v.values[0] def test_pandas_period_index(self): v = self.cls(['x'], pd.period_range(start='2000', periods=20, freq='B')) v = v.load() # for dask-based Variable - self.assertEqual(v[0], pd.Period('2000', freq='B')) + assert v[0] == pd.Period('2000', freq='B') assert "Period('2000-01-03', 'B')" in repr(v) def test_1d_math(self): @@ -272,65 +300,63 @@ def test_1d_math(self): v = self.cls(['x'], x) base_v = v.to_base_variable() # unary ops - self.assertVariableIdentical(base_v, +v) - self.assertVariableIdentical(base_v, abs(v)) - self.assertArrayEqual((-v).values, -x) + assert_identical(base_v, +v) + assert_identical(base_v, abs(v)) + assert_array_equal((-v).values, -x) # binary ops with numbers - self.assertVariableIdentical(base_v, v + 0) - self.assertVariableIdentical(base_v, 0 + v) - self.assertVariableIdentical(base_v, v * 1) - self.assertArrayEqual((v > 2).values, x > 2) - self.assertArrayEqual((0 == v).values, 0 == x) - self.assertArrayEqual((v - 1).values, x - 1) - self.assertArrayEqual((1 - v).values, 1 - x) + assert_identical(base_v, v + 0) + assert_identical(base_v, 0 + v) + assert_identical(base_v, v * 1) # binary ops with numpy arrays - self.assertArrayEqual((v * x).values, x ** 2) - self.assertArrayEqual((x * v).values, x ** 2) - self.assertArrayEqual(v - y, v - 1) - self.assertArrayEqual(y - v, 1 - v) + assert_array_equal((v * x).values, x ** 2) + assert_array_equal((x * v).values, x ** 2) + assert_array_equal(v - y, v - 1) + assert_array_equal(y - v, 1 - v) # verify attributes are dropped v2 = self.cls(['x'], x, {'units': 'meters'}) - self.assertVariableIdentical(base_v, +v2) + assert_identical(base_v, +v2) # binary ops with all variables - self.assertArrayEqual(v + v, 2 * v) + assert_array_equal(v + v, 2 * v) w = self.cls(['x'], y, {'foo': 'bar'}) - self.assertVariableIdentical(v + w, self.cls(['x'], x + y).to_base_variable()) - self.assertArrayEqual((v * w).values, x * y) + assert_identical(v + w, self.cls(['x'], x + y).to_base_variable()) + assert_array_equal((v * w).values, x * y) + # something complicated - self.assertArrayEqual((v ** 2 * w - 1 + x).values, x ** 2 * y - 1 + x) + assert_array_equal((v ** 2 * w - 1 + x).values, x ** 2 * y - 1 + x) # make sure dtype is preserved (for Index objects) - self.assertEqual(float, (+v).dtype) - self.assertEqual(float, (+v).values.dtype) - self.assertEqual(float, (0 + v).dtype) - self.assertEqual(float, (0 + v).values.dtype) + assert float == (+v).dtype + assert float == (+v).values.dtype + assert float == (0 + v).dtype + assert float == (0 + v).values.dtype # check types of returned data - self.assertIsInstance(+v, Variable) - self.assertNotIsInstance(+v, IndexVariable) - self.assertIsInstance(0 + v, Variable) - self.assertNotIsInstance(0 + v, IndexVariable) + assert isinstance(+v, Variable) + assert not isinstance(+v, IndexVariable) + assert isinstance(0 + v, Variable) + assert not isinstance(0 + v, IndexVariable) def test_1d_reduce(self): x = np.arange(5) v = self.cls(['x'], x) actual = v.sum() expected = Variable((), 10) - self.assertVariableIdentical(expected, actual) - self.assertIs(type(actual), Variable) + assert_identical(expected, actual) + assert type(actual) is Variable def test_array_interface(self): x = np.arange(5) v = self.cls(['x'], x) - self.assertArrayEqual(np.asarray(v), x) + assert_array_equal(np.asarray(v), x) # test patched in methods - self.assertArrayEqual(v.astype(float), x.astype(float)) + assert_array_equal(v.astype(float), x.astype(float)) # think this is a break, that argsort changes the type - self.assertVariableIdentical(v.argsort(), v.to_base_variable()) - self.assertVariableIdentical(v.clip(2, 3), - self.cls('x', x.clip(2, 3)).to_base_variable()) + assert_identical(v.argsort(), v.to_base_variable()) + assert_identical(v.clip(2, 3), + self.cls('x', x.clip(2, 3)).to_base_variable()) # test ufuncs - self.assertVariableIdentical(np.sin(v), self.cls(['x'], np.sin(x)).to_base_variable()) - self.assertIsInstance(np.sin(v), Variable) - self.assertNotIsInstance(np.sin(v), IndexVariable) + assert_identical(np.sin(v), + self.cls(['x'], np.sin(x)).to_base_variable()) + assert isinstance(np.sin(v), Variable) + assert not isinstance(np.sin(v), IndexVariable) def example_1d_objects(self): for data in [range(3), @@ -342,23 +368,23 @@ def example_1d_objects(self): def test___array__(self): for v, data in self.example_1d_objects(): - self.assertArrayEqual(v.values, np.asarray(data)) - self.assertArrayEqual(np.asarray(v), np.asarray(data)) - self.assertEqual(v[0].values, np.asarray(data)[0]) - self.assertEqual(np.asarray(v[0]), np.asarray(data)[0]) + assert_array_equal(v.values, np.asarray(data)) + assert_array_equal(np.asarray(v), np.asarray(data)) + assert v[0].values == np.asarray(data)[0] + assert np.asarray(v[0]) == np.asarray(data)[0] def test_equals_all_dtypes(self): for v, _ in self.example_1d_objects(): v2 = v.copy() - self.assertTrue(v.equals(v2)) - self.assertTrue(v.identical(v2)) - self.assertTrue(v.no_conflicts(v2)) - self.assertTrue(v[0].equals(v2[0])) - self.assertTrue(v[0].identical(v2[0])) - self.assertTrue(v[0].no_conflicts(v2[0])) - self.assertTrue(v[:2].equals(v2[:2])) - self.assertTrue(v[:2].identical(v2[:2])) - self.assertTrue(v[:2].no_conflicts(v2[:2])) + assert v.equals(v2) + assert v.identical(v2) + assert v.no_conflicts(v2) + assert v[0].equals(v2[0]) + assert v[0].identical(v2[0]) + assert v[0].no_conflicts(v2[0]) + assert v[:2].equals(v2[:2]) + assert v[:2].identical(v2[:2]) + assert v[:2].no_conflicts(v2[:2]) def test_eq_all_dtypes(self): # ensure that we don't choke on comparisons for which numpy returns @@ -366,9 +392,9 @@ def test_eq_all_dtypes(self): expected = Variable('x', 3 * [False]) for v, _ in self.example_1d_objects(): actual = 'z' == v - self.assertVariableIdentical(expected, actual) + assert_identical(expected, actual) actual = ~('z' != v) - self.assertVariableIdentical(expected, actual) + assert_identical(expected, actual) def test_encoding_preserved(self): expected = self.cls('x', range(3), {'foo': 1}, {'bar': 2}) @@ -380,21 +406,21 @@ def test_encoding_preserved(self): expected.copy(deep=True), expected.copy(deep=False)]: - self.assertVariableIdentical(expected.to_base_variable(), - actual.to_base_variable()) - self.assertEqual(expected.encoding, actual.encoding) + assert_identical(expected.to_base_variable(), + actual.to_base_variable()) + assert expected.encoding == actual.encoding def test_concat(self): x = np.arange(5) y = np.arange(5, 10) v = self.cls(['a'], x) w = self.cls(['a'], y) - self.assertVariableIdentical(Variable(['b', 'a'], np.array([x, y])), - Variable.concat([v, w], 'b')) - self.assertVariableIdentical(Variable(['b', 'a'], np.array([x, y])), - Variable.concat((v, w), 'b')) - self.assertVariableIdentical(Variable(['b', 'a'], np.array([x, y])), - Variable.concat((v, w), 'b')) + assert_identical(Variable(['b', 'a'], np.array([x, y])), + Variable.concat([v, w], 'b')) + assert_identical(Variable(['b', 'a'], np.array([x, y])), + Variable.concat((v, w), 'b')) + assert_identical(Variable(['b', 'a'], np.array([x, y])), + Variable.concat((v, w), 'b')) with raises_regex(ValueError, 'inconsistent dimensions'): Variable.concat([v, Variable(['c'], y)], 'b') # test indexers @@ -403,14 +429,14 @@ def test_concat(self): positions=[np.arange(0, 10, 2), np.arange(1, 10, 2)], dim='a') expected = Variable('a', np.array([x, y]).ravel(order='F')) - self.assertVariableIdentical(expected, actual) + assert_identical(expected, actual) # test concatenating along a dimension v = Variable(['time', 'x'], np.random.random((10, 8))) - self.assertVariableIdentical(v, Variable.concat([v[:5], v[5:]], 'time')) - self.assertVariableIdentical(v, Variable.concat([v[:5], v[5:6], v[6:]], 'time')) - self.assertVariableIdentical(v, Variable.concat([v[:1], v[1:]], 'time')) + assert_identical(v, Variable.concat([v[:5], v[5:]], 'time')) + assert_identical(v, Variable.concat([v[:5], v[5:6], v[6:]], 'time')) + assert_identical(v, Variable.concat([v[:1], v[1:]], 'time')) # test dimension order - self.assertVariableIdentical(v, Variable.concat([v[:, :5], v[:, 5:]], 'x')) + assert_identical(v, Variable.concat([v[:, :5], v[:, 5:]], 'x')) with raises_regex(ValueError, 'all input arrays must have'): Variable.concat([v[:, 0], v[:, 1:]], 'x') @@ -418,13 +444,14 @@ def test_concat_attrs(self): # different or conflicting attributes should be removed v = self.cls('a', np.arange(5), {'foo': 'bar'}) w = self.cls('a', np.ones(5)) - expected = self.cls('a', np.concatenate([np.arange(5), np.ones(5)])).to_base_variable() - self.assertVariableIdentical(expected, Variable.concat([v, w], 'a')) + expected = self.cls( + 'a', np.concatenate([np.arange(5), np.ones(5)])).to_base_variable() + assert_identical(expected, Variable.concat([v, w], 'a')) w.attrs['foo'] = 2 - self.assertVariableIdentical(expected, Variable.concat([v, w], 'a')) + assert_identical(expected, Variable.concat([v, w], 'a')) w.attrs['foo'] = 'bar' expected.attrs['foo'] = 'bar' - self.assertVariableIdentical(expected, Variable.concat([v, w], 'a')) + assert_identical(expected, Variable.concat([v, w], 'a')) def test_concat_fixed_len_str(self): # regression test for #217 @@ -434,7 +461,7 @@ def test_concat_fixed_len_str(self): actual = Variable.concat([x, y], 'animal') expected = Variable( 'animal', np.array(['horse', 'aardvark'], dtype=kind)) - self.assertVariableEqual(expected, actual) + assert_equal(expected, actual) def test_concat_number_strings(self): # regression test for #305 @@ -442,25 +469,25 @@ def test_concat_number_strings(self): b = self.cls('x', ['3', '4']) actual = Variable.concat([a, b], dim='x') expected = Variable('x', np.arange(5).astype(str).astype(object)) - self.assertVariableIdentical(expected, actual) - self.assertEqual(expected.dtype, object) - self.assertEqual(type(expected.values[0]), str) + assert_identical(expected, actual) + assert expected.dtype == object + assert type(expected.values[0]) == str def test_copy(self): v = self.cls('x', 0.5 * np.arange(10), {'foo': 'bar'}) for deep in [True, False]: w = v.copy(deep=deep) - self.assertIs(type(v), type(w)) - self.assertVariableIdentical(v, w) - self.assertEqual(v.dtype, w.dtype) + assert type(v) is type(w) + assert_identical(v, w) + assert v.dtype == w.dtype if self.cls is Variable: if deep: - self.assertIsNot(source_ndarray(v.values), - source_ndarray(w.values)) + assert source_ndarray(v.values) is not \ + source_ndarray(w.values) else: - self.assertIs(source_ndarray(v.values), - source_ndarray(w.values)) - self.assertVariableIdentical(v, copy(v)) + assert source_ndarray(v.values) is \ + source_ndarray(w.values) + assert_identical(v, copy(v)) def test_copy_index(self): midx = pd.MultiIndex.from_product([['a', 'b'], [1, 2], [-1, -2]], @@ -468,26 +495,27 @@ def test_copy_index(self): v = self.cls('x', midx) for deep in [True, False]: w = v.copy(deep=deep) - self.assertIsInstance(w._data, PandasIndexAdapter) - self.assertIsInstance(w.to_index(), pd.MultiIndex) - self.assertArrayEqual(v._data.array, w._data.array) + assert isinstance(w._data, PandasIndexAdapter) + assert isinstance(w.to_index(), pd.MultiIndex) + assert_array_equal(v._data.array, w._data.array) def test_real_and_imag(self): v = self.cls('x', np.arange(3) - 1j * np.arange(3), {'foo': 'bar'}) expected_re = self.cls('x', np.arange(3), {'foo': 'bar'}) - self.assertVariableIdentical(v.real, expected_re) + assert_identical(v.real, expected_re) expected_im = self.cls('x', -np.arange(3), {'foo': 'bar'}) - self.assertVariableIdentical(v.imag, expected_im) + assert_identical(v.imag, expected_im) - expected_abs = self.cls('x', np.sqrt(2 * np.arange(3) ** 2)).to_base_variable() - self.assertVariableAllClose(abs(v), expected_abs) + expected_abs = self.cls( + 'x', np.sqrt(2 * np.arange(3) ** 2)).to_base_variable() + assert_allclose(abs(v), expected_abs) def test_aggregate_complex(self): # should skip NaNs v = self.cls('x', [1, 2j, np.nan]) expected = Variable((), 0.5 + 1j) - self.assertVariableAllClose(v.mean(), expected) + assert_allclose(v.mean(), expected) def test_pandas_cateogrical_dtype(self): data = pd.Categorical(np.arange(10, dtype='int64')) @@ -508,8 +536,8 @@ def test_pandas_datetime64_with_tz(self): def test_multiindex(self): idx = pd.MultiIndex.from_product([list('abc'), [0, 1]]) v = self.cls('x', idx) - self.assertVariableIdentical(Variable((), ('a', 0)), v[0]) - self.assertVariableIdentical(v, v[:]) + assert_identical(Variable((), ('a', 0)), v[0]) + assert_identical(v, v[:]) def test_load(self): array = self.cls('x', np.arange(5)) @@ -519,7 +547,7 @@ def test_load(self): array.load() assert type(array._data) is type(orig_data) assert type(copied._data) is type(orig_data) - self.assertVariableIdentical(array, copied) + assert_identical(array, copied) def test_getitem_advanced(self): v = self.cls(['x', 'y'], [[0, 1, 2], [3, 4, 5]]) @@ -528,28 +556,28 @@ def test_getitem_advanced(self): # orthogonal indexing v_new = v[([0, 1], [1, 0])] assert v_new.dims == ('x', 'y') - self.assertArrayEqual(v_new, v_data[[0, 1]][:, [1, 0]]) + assert_array_equal(v_new, v_data[[0, 1]][:, [1, 0]]) v_new = v[[0, 1]] assert v_new.dims == ('x', 'y') - self.assertArrayEqual(v_new, v_data[[0, 1]]) + assert_array_equal(v_new, v_data[[0, 1]]) # with mixed arguments ind = Variable(['a'], [0, 1]) v_new = v[dict(x=[0, 1], y=ind)] assert v_new.dims == ('x', 'a') - self.assertArrayEqual(v_new, v_data[[0, 1]][:, [0, 1]]) + assert_array_equal(v_new, v_data[[0, 1]][:, [0, 1]]) # boolean indexing v_new = v[dict(x=[True, False], y=[False, True, False])] assert v_new.dims == ('x', 'y') - self.assertArrayEqual(v_new, v_data[0][1]) + assert_array_equal(v_new, v_data[0][1]) # with scalar variable ind = Variable((), 2) v_new = v[dict(y=ind)] expected = v[dict(y=2)] - self.assertArrayEqual(v_new, expected) + assert_array_equal(v_new, expected) # with boolean variable with wrong shape ind = np.array([True, False]) @@ -567,9 +595,9 @@ def test_getitem_uint_1d(self): v_data = v.compute().data v_new = v[np.array([0])] - self.assertArrayEqual(v_new, v_data[0]) + assert_array_equal(v_new, v_data[0]) v_new = v[np.array([0], dtype="uint64")] - self.assertArrayEqual(v_new, v_data[0]) + assert_array_equal(v_new, v_data[0]) def test_getitem_uint(self): # regression test for #1405 @@ -577,12 +605,12 @@ def test_getitem_uint(self): v_data = v.compute().data v_new = v[np.array([0])] - self.assertArrayEqual(v_new, v_data[[0], :]) + assert_array_equal(v_new, v_data[[0], :]) v_new = v[np.array([0], dtype="uint64")] - self.assertArrayEqual(v_new, v_data[[0], :]) + assert_array_equal(v_new, v_data[[0], :]) v_new = v[np.uint64(0)] - self.assertArrayEqual(v_new, v_data[0, :]) + assert_array_equal(v_new, v_data[0, :]) def test_getitem_0d_array(self): # make sure 0d-np.array can be used as an indexer @@ -590,7 +618,7 @@ def test_getitem_0d_array(self): v_data = v.compute().data v_new = v[np.array([0])[0]] - self.assertArrayEqual(v_new, v_data[0]) + assert_array_equal(v_new, v_data[0]) def test_getitem_fancy(self): v = self.cls(['x', 'y'], [[0, 1, 2], [3, 4, 5]]) @@ -599,72 +627,72 @@ def test_getitem_fancy(self): ind = Variable(['a', 'b'], [[0, 1, 1], [1, 1, 0]]) v_new = v[ind] assert v_new.dims == ('a', 'b', 'y') - self.assertArrayEqual(v_new, v_data[[[0, 1, 1], [1, 1, 0]], :]) + assert_array_equal(v_new, v_data[[[0, 1, 1], [1, 1, 0]], :]) # It would be ok if indexed with the multi-dimensional array including # the same name ind = Variable(['x', 'b'], [[0, 1, 1], [1, 1, 0]]) v_new = v[ind] assert v_new.dims == ('x', 'b', 'y') - self.assertArrayEqual(v_new, v_data[[[0, 1, 1], [1, 1, 0]], :]) + assert_array_equal(v_new, v_data[[[0, 1, 1], [1, 1, 0]], :]) ind = Variable(['a', 'b'], [[0, 1, 2], [2, 1, 0]]) v_new = v[dict(y=ind)] assert v_new.dims == ('x', 'a', 'b') - self.assertArrayEqual(v_new, v_data[:, ([0, 1, 2], [2, 1, 0])]) + assert_array_equal(v_new, v_data[:, ([0, 1, 2], [2, 1, 0])]) ind = Variable(['a', 'b'], [[0, 0], [1, 1]]) v_new = v[dict(x=[1, 0], y=ind)] assert v_new.dims == ('x', 'a', 'b') - self.assertArrayEqual(v_new, v_data[[1, 0]][:, ind]) + assert_array_equal(v_new, v_data[[1, 0]][:, ind]) # along diagonal ind = Variable(['a'], [0, 1]) v_new = v[ind, ind] assert v_new.dims == ('a',) - self.assertArrayEqual(v_new, v_data[[0, 1], [0, 1]]) + assert_array_equal(v_new, v_data[[0, 1], [0, 1]]) # with integer ind = Variable(['a', 'b'], [[0, 0], [1, 1]]) v_new = v[dict(x=0, y=ind)] assert v_new.dims == ('a', 'b') - self.assertArrayEqual(v_new[0], v_data[0][[0, 0]]) - self.assertArrayEqual(v_new[1], v_data[0][[1, 1]]) + assert_array_equal(v_new[0], v_data[0][[0, 0]]) + assert_array_equal(v_new[1], v_data[0][[1, 1]]) # with slice ind = Variable(['a', 'b'], [[0, 0], [1, 1]]) v_new = v[dict(x=slice(None), y=ind)] assert v_new.dims == ('x', 'a', 'b') - self.assertArrayEqual(v_new, v_data[:, [[0, 0], [1, 1]]]) + assert_array_equal(v_new, v_data[:, [[0, 0], [1, 1]]]) ind = Variable(['a', 'b'], [[0, 0], [1, 1]]) v_new = v[dict(x=ind, y=slice(None))] assert v_new.dims == ('a', 'b', 'y') - self.assertArrayEqual(v_new, v_data[[[0, 0], [1, 1]], :]) + assert_array_equal(v_new, v_data[[[0, 0], [1, 1]], :]) ind = Variable(['a', 'b'], [[0, 0], [1, 1]]) v_new = v[dict(x=ind, y=slice(None, 1))] assert v_new.dims == ('a', 'b', 'y') - self.assertArrayEqual(v_new, v_data[[[0, 0], [1, 1]], slice(None, 1)]) + assert_array_equal(v_new, v_data[[[0, 0], [1, 1]], slice(None, 1)]) # slice matches explicit dimension ind = Variable(['y'], [0, 1]) v_new = v[ind, :2] assert v_new.dims == ('y',) - self.assertArrayEqual(v_new, v_data[[0, 1], [0, 1]]) + assert_array_equal(v_new, v_data[[0, 1], [0, 1]]) # with multiple slices v = self.cls(['x', 'y', 'z'], [[[1, 2, 3], [4, 5, 6]]]) ind = Variable(['a', 'b'], [[0]]) v_new = v[ind, :, :] expected = Variable(['a', 'b', 'y', 'z'], v.data[np.newaxis, ...]) - self.assertVariableIdentical(v_new, expected) + assert_identical(v_new, expected) v = Variable(['w', 'x', 'y', 'z'], [[[[1, 2, 3], [4, 5, 6]]]]) ind = Variable(['y'], [0]) v_new = v[ind, :, 1:2, 2] expected = Variable(['y', 'x'], [[6]]) - self.assertVariableIdentical(v_new, expected) + assert_identical(v_new, expected) # slice and vector mixed indexing resulting in the same dimension v = Variable(['x', 'y', 'z'], np.arange(60).reshape(3, 4, 5)) @@ -674,7 +702,7 @@ def test_getitem_fancy(self): expected[0] = v.data[0, 0] expected[1] = v.data[1, 1] expected[2] = v.data[2, 2] - self.assertVariableIdentical(v_new, expected) + assert_identical(v_new, expected) v_new = v[:, ind.data] assert v_new.shape == (3, 3, 5) @@ -708,70 +736,70 @@ def setUp(self): def test_data_and_values(self): v = Variable(['time', 'x'], self.d) - self.assertArrayEqual(v.data, self.d) - self.assertArrayEqual(v.values, self.d) - self.assertIs(source_ndarray(v.values), self.d) + assert_array_equal(v.data, self.d) + assert_array_equal(v.values, self.d) + assert source_ndarray(v.values) is self.d with pytest.raises(ValueError): # wrong size v.values = np.random.random(5) d2 = np.random.random((10, 3)) v.values = d2 - self.assertIs(source_ndarray(v.values), d2) + assert source_ndarray(v.values) is d2 d3 = np.random.random((10, 3)) v.data = d3 - self.assertIs(source_ndarray(v.data), d3) + assert source_ndarray(v.data) is d3 def test_numpy_same_methods(self): v = Variable([], np.float32(0.0)) - self.assertEqual(v.item(), 0) - self.assertIs(type(v.item()), float) + assert v.item() == 0 + assert type(v.item()) is float v = IndexVariable('x', np.arange(5)) - self.assertEqual(2, v.searchsorted(2)) + assert 2 == v.searchsorted(2) def test_datetime64_conversion_scalar(self): expected = np.datetime64('2000-01-01', 'ns') for values in [ - np.datetime64('2000-01-01'), - pd.Timestamp('2000-01-01T00'), - datetime(2000, 1, 1), - ]: + np.datetime64('2000-01-01'), + pd.Timestamp('2000-01-01T00'), + datetime(2000, 1, 1), + ]: v = Variable([], values) - self.assertEqual(v.dtype, np.dtype('datetime64[ns]')) - self.assertEqual(v.values, expected) - self.assertEqual(v.values.dtype, np.dtype('datetime64[ns]')) + assert v.dtype == np.dtype('datetime64[ns]') + assert v.values == expected + assert v.values.dtype == np.dtype('datetime64[ns]') def test_timedelta64_conversion_scalar(self): expected = np.timedelta64(24 * 60 * 60 * 10 ** 9, 'ns') for values in [ - np.timedelta64(1, 'D'), - pd.Timedelta('1 day'), - timedelta(days=1), - ]: + np.timedelta64(1, 'D'), + pd.Timedelta('1 day'), + timedelta(days=1), + ]: v = Variable([], values) - self.assertEqual(v.dtype, np.dtype('timedelta64[ns]')) - self.assertEqual(v.values, expected) - self.assertEqual(v.values.dtype, np.dtype('timedelta64[ns]')) + assert v.dtype == np.dtype('timedelta64[ns]') + assert v.values == expected + assert v.values.dtype == np.dtype('timedelta64[ns]') def test_0d_str(self): v = Variable([], u'foo') - self.assertEqual(v.dtype, np.dtype('U3')) - self.assertEqual(v.values, 'foo') + assert v.dtype == np.dtype('U3') + assert v.values == 'foo' v = Variable([], np.string_('foo')) - self.assertEqual(v.dtype, np.dtype('S3')) - self.assertEqual(v.values, bytes('foo', 'ascii') if PY3 else 'foo') + assert v.dtype == np.dtype('S3') + assert v.values == bytes('foo', 'ascii') if PY3 else 'foo' def test_0d_datetime(self): v = Variable([], pd.Timestamp('2000-01-01')) - self.assertEqual(v.dtype, np.dtype('datetime64[ns]')) - self.assertEqual(v.values, np.datetime64('2000-01-01', 'ns')) + assert v.dtype == np.dtype('datetime64[ns]') + assert v.values == np.datetime64('2000-01-01', 'ns') def test_0d_timedelta(self): for td in [pd.to_timedelta('1s'), np.timedelta64(1, 's')]: v = Variable([], td) - self.assertEqual(v.dtype, np.dtype('timedelta64[ns]')) - self.assertEqual(v.values, np.timedelta64(10 ** 9, 'ns')) + assert v.dtype == np.dtype('timedelta64[ns]') + assert v.values == np.timedelta64(10 ** 9, 'ns') def test_equals_and_identical(self): d = np.random.rand(10, 3) @@ -780,62 +808,62 @@ def test_equals_and_identical(self): attrs={'att1': 3, 'att2': [1, 2, 3]}) v2 = Variable(('dim1', 'dim2'), data=d, attrs={'att1': 3, 'att2': [1, 2, 3]}) - self.assertTrue(v1.equals(v2)) - self.assertTrue(v1.identical(v2)) + assert v1.equals(v2) + assert v1.identical(v2) v3 = Variable(('dim1', 'dim3'), data=d) - self.assertFalse(v1.equals(v3)) + assert not v1.equals(v3) v4 = Variable(('dim1', 'dim2'), data=d) - self.assertTrue(v1.equals(v4)) - self.assertFalse(v1.identical(v4)) + assert v1.equals(v4) + assert not v1.identical(v4) v5 = deepcopy(v1) v5.values[:] = np.random.rand(10, 3) - self.assertFalse(v1.equals(v5)) + assert not v1.equals(v5) - self.assertFalse(v1.equals(None)) - self.assertFalse(v1.equals(d)) + assert not v1.equals(None) + assert not v1.equals(d) - self.assertFalse(v1.identical(None)) - self.assertFalse(v1.identical(d)) + assert not v1.identical(None) + assert not v1.identical(d) def test_broadcast_equals(self): v1 = Variable((), np.nan) v2 = Variable(('x'), [np.nan, np.nan]) - self.assertTrue(v1.broadcast_equals(v2)) - self.assertFalse(v1.equals(v2)) - self.assertFalse(v1.identical(v2)) + assert v1.broadcast_equals(v2) + assert not v1.equals(v2) + assert not v1.identical(v2) v3 = Variable(('x'), [np.nan]) - self.assertTrue(v1.broadcast_equals(v3)) - self.assertFalse(v1.equals(v3)) - self.assertFalse(v1.identical(v3)) + assert v1.broadcast_equals(v3) + assert not v1.equals(v3) + assert not v1.identical(v3) - self.assertFalse(v1.broadcast_equals(None)) + assert not v1.broadcast_equals(None) v4 = Variable(('x'), [np.nan] * 3) - self.assertFalse(v2.broadcast_equals(v4)) + assert not v2.broadcast_equals(v4) def test_no_conflicts(self): v1 = Variable(('x'), [1, 2, np.nan, np.nan]) v2 = Variable(('x'), [np.nan, 2, 3, np.nan]) - self.assertTrue(v1.no_conflicts(v2)) - self.assertFalse(v1.equals(v2)) - self.assertFalse(v1.broadcast_equals(v2)) - self.assertFalse(v1.identical(v2)) + assert v1.no_conflicts(v2) + assert not v1.equals(v2) + assert not v1.broadcast_equals(v2) + assert not v1.identical(v2) - self.assertFalse(v1.no_conflicts(None)) + assert not v1.no_conflicts(None) v3 = Variable(('y'), [np.nan, 2, 3, np.nan]) - self.assertFalse(v3.no_conflicts(v1)) + assert not v3.no_conflicts(v1) d = np.array([1, 2, np.nan, np.nan]) - self.assertFalse(v1.no_conflicts(d)) - self.assertFalse(v2.no_conflicts(d)) + assert not v1.no_conflicts(d) + assert not v2.no_conflicts(d) v4 = Variable(('w', 'x'), [d]) - self.assertTrue(v1.no_conflicts(v4)) + assert v1.no_conflicts(v4) def test_as_variable(self): data = np.arange(10) @@ -843,32 +871,32 @@ def test_as_variable(self): expected_extra = Variable('x', data, attrs={'myattr': 'val'}, encoding={'scale_factor': 1}) - self.assertVariableIdentical(expected, as_variable(expected)) + assert_identical(expected, as_variable(expected)) ds = Dataset({'x': expected}) var = as_variable(ds['x']).to_base_variable() - self.assertVariableIdentical(expected, var) - self.assertNotIsInstance(ds['x'], Variable) - self.assertIsInstance(as_variable(ds['x']), Variable) + assert_identical(expected, var) + assert not isinstance(ds['x'], Variable) + assert isinstance(as_variable(ds['x']), Variable) FakeVariable = namedtuple('FakeVariable', 'values dims') fake_xarray = FakeVariable(expected.values, expected.dims) - self.assertVariableIdentical(expected, as_variable(fake_xarray)) + assert_identical(expected, as_variable(fake_xarray)) FakeVariable = namedtuple('FakeVariable', 'data dims') fake_xarray = FakeVariable(expected.data, expected.dims) - self.assertVariableIdentical(expected, as_variable(fake_xarray)) + assert_identical(expected, as_variable(fake_xarray)) FakeVariable = namedtuple('FakeVariable', 'data values dims attrs encoding') fake_xarray = FakeVariable(expected_extra.data, expected_extra.values, expected_extra.dims, expected_extra.attrs, expected_extra.encoding) - self.assertVariableIdentical(expected_extra, as_variable(fake_xarray)) + assert_identical(expected_extra, as_variable(fake_xarray)) xarray_tuple = (expected_extra.dims, expected_extra.values, expected_extra.attrs, expected_extra.encoding) - self.assertVariableIdentical(expected_extra, as_variable(xarray_tuple)) + assert_identical(expected_extra, as_variable(xarray_tuple)) with raises_regex(TypeError, 'tuples to convert'): as_variable(tuple(data)) @@ -877,11 +905,11 @@ def test_as_variable(self): as_variable(data) actual = as_variable(data, name='x') - self.assertVariableIdentical(expected.to_index_variable(), actual) + assert_identical(expected.to_index_variable(), actual) actual = as_variable(0) expected = Variable([], 0) - self.assertVariableIdentical(expected, actual) + assert_identical(expected, actual) data = np.arange(9).reshape((3, 3)) expected = Variable(('x', 'y'), data) @@ -901,12 +929,12 @@ def test_repr(self): Attributes: foo: bar """).strip() - self.assertEqual(expected, repr(v)) + assert expected == repr(v) def test_repr_lazy_data(self): v = Variable('x', LazilyIndexedArray(np.arange(2e5))) - self.assertIn('200000 values with dtype', repr(v)) - self.assertIsInstance(v._data, LazilyIndexedArray) + assert '200000 values with dtype' in repr(v) + assert isinstance(v._data, LazilyIndexedArray) def test_detect_indexer_type(self): """ Tests indexer type was correctly detected. """ @@ -984,128 +1012,134 @@ def test_items(self): data = np.random.random((10, 11)) v = Variable(['x', 'y'], data) # test slicing - self.assertVariableIdentical(v, v[:]) - self.assertVariableIdentical(v, v[...]) - self.assertVariableIdentical(Variable(['y'], data[0]), v[0]) - self.assertVariableIdentical(Variable(['x'], data[:, 0]), v[:, 0]) - self.assertVariableIdentical(Variable(['x', 'y'], data[:3, :2]), - v[:3, :2]) + assert_identical(v, v[:]) + assert_identical(v, v[...]) + assert_identical(Variable(['y'], data[0]), v[0]) + assert_identical(Variable(['x'], data[:, 0]), v[:, 0]) + assert_identical(Variable(['x', 'y'], data[:3, :2]), + v[:3, :2]) # test array indexing x = Variable(['x'], np.arange(10)) y = Variable(['y'], np.arange(11)) - self.assertVariableIdentical(v, v[x.values]) - self.assertVariableIdentical(v, v[x]) - self.assertVariableIdentical(v[:3], v[x < 3]) - self.assertVariableIdentical(v[:, 3:], v[:, y >= 3]) - self.assertVariableIdentical(v[:3, 3:], v[x < 3, y >= 3]) - self.assertVariableIdentical(v[:3, :2], v[x[:3], y[:2]]) - self.assertVariableIdentical(v[:3, :2], v[range(3), range(2)]) + assert_identical(v, v[x.values]) + assert_identical(v, v[x]) + assert_identical(v[:3], v[x < 3]) + assert_identical(v[:, 3:], v[:, y >= 3]) + assert_identical(v[:3, 3:], v[x < 3, y >= 3]) + assert_identical(v[:3, :2], v[x[:3], y[:2]]) + assert_identical(v[:3, :2], v[range(3), range(2)]) # test iteration for n, item in enumerate(v): - self.assertVariableIdentical(Variable(['y'], data[n]), item) + assert_identical(Variable(['y'], data[n]), item) with raises_regex(TypeError, 'iteration over a 0-d'): iter(Variable([], 0)) # test setting v.values[:] = 0 - self.assertTrue(np.all(v.values == 0)) + assert np.all(v.values == 0) # test orthogonal setting v[range(10), range(11)] = 1 - self.assertArrayEqual(v.values, np.ones((10, 11))) + assert_array_equal(v.values, np.ones((10, 11))) def test_getitem_basic(self): v = self.cls(['x', 'y'], [[0, 1, 2], [3, 4, 5]]) v_new = v[dict(x=0)] assert v_new.dims == ('y', ) - self.assertArrayEqual(v_new, v._data[0]) + assert_array_equal(v_new, v._data[0]) v_new = v[dict(x=0, y=slice(None))] assert v_new.dims == ('y', ) - self.assertArrayEqual(v_new, v._data[0]) + assert_array_equal(v_new, v._data[0]) v_new = v[dict(x=0, y=1)] assert v_new.dims == () - self.assertArrayEqual(v_new, v._data[0, 1]) + assert_array_equal(v_new, v._data[0, 1]) v_new = v[dict(y=1)] assert v_new.dims == ('x', ) - self.assertArrayEqual(v_new, v._data[:, 1]) + assert_array_equal(v_new, v._data[:, 1]) # tuple argument v_new = v[(slice(None), 1)] assert v_new.dims == ('x', ) - self.assertArrayEqual(v_new, v._data[:, 1]) + assert_array_equal(v_new, v._data[:, 1]) + + def test_getitem_with_mask_2d_input(self): + v = Variable(('x', 'y'), [[0, 1, 2], [3, 4, 5]]) + assert_identical(v._getitem_with_mask(([-1, 0], [1, -1])), + Variable(('x', 'y'), [[np.nan, np.nan], [1, np.nan]])) + assert_identical(v._getitem_with_mask((slice(2), [0, 1, 2])), v) def test_isel(self): v = Variable(['time', 'x'], self.d) - self.assertVariableIdentical(v.isel(time=slice(None)), v) - self.assertVariableIdentical(v.isel(time=0), v[0]) - self.assertVariableIdentical(v.isel(time=slice(0, 3)), v[:3]) - self.assertVariableIdentical(v.isel(x=0), v[:, 0]) + assert_identical(v.isel(time=slice(None)), v) + assert_identical(v.isel(time=0), v[0]) + assert_identical(v.isel(time=slice(0, 3)), v[:3]) + assert_identical(v.isel(x=0), v[:, 0]) with raises_regex(ValueError, 'do not exist'): v.isel(not_a_dim=0) def test_index_0d_numpy_string(self): # regression test to verify our work around for indexing 0d strings v = Variable([], np.string_('asdf')) - self.assertVariableIdentical(v[()], v) + assert_identical(v[()], v) v = Variable([], np.unicode_(u'asdf')) - self.assertVariableIdentical(v[()], v) + assert_identical(v[()], v) def test_indexing_0d_unicode(self): # regression test for GH568 actual = Variable(('x'), [u'tmax'])[0][()] expected = Variable((), u'tmax') - self.assertVariableIdentical(actual, expected) + assert_identical(actual, expected) def test_shift(self): v = Variable('x', [1, 2, 3, 4, 5]) - self.assertVariableIdentical(v, v.shift(x=0)) - self.assertIsNot(v, v.shift(x=0)) + assert_identical(v, v.shift(x=0)) + assert v is not v.shift(x=0) expected = Variable('x', [np.nan, 1, 2, 3, 4]) - self.assertVariableIdentical(expected, v.shift(x=1)) + assert_identical(expected, v.shift(x=1)) expected = Variable('x', [np.nan, np.nan, 1, 2, 3]) - self.assertVariableIdentical(expected, v.shift(x=2)) + assert_identical(expected, v.shift(x=2)) expected = Variable('x', [2, 3, 4, 5, np.nan]) - self.assertVariableIdentical(expected, v.shift(x=-1)) + assert_identical(expected, v.shift(x=-1)) expected = Variable('x', [np.nan] * 5) - self.assertVariableIdentical(expected, v.shift(x=5)) - self.assertVariableIdentical(expected, v.shift(x=6)) + assert_identical(expected, v.shift(x=5)) + assert_identical(expected, v.shift(x=6)) with raises_regex(ValueError, 'dimension'): v.shift(z=0) v = Variable('x', [1, 2, 3, 4, 5], {'foo': 'bar'}) - self.assertVariableIdentical(v, v.shift(x=0)) + assert_identical(v, v.shift(x=0)) expected = Variable('x', [np.nan, 1, 2, 3, 4], {'foo': 'bar'}) - self.assertVariableIdentical(expected, v.shift(x=1)) + assert_identical(expected, v.shift(x=1)) def test_shift2d(self): v = Variable(('x', 'y'), [[1, 2], [3, 4]]) expected = Variable(('x', 'y'), [[np.nan, np.nan], [np.nan, 1]]) - self.assertVariableIdentical(expected, v.shift(x=1, y=1)) + assert_identical(expected, v.shift(x=1, y=1)) def test_roll(self): v = Variable('x', [1, 2, 3, 4, 5]) - self.assertVariableIdentical(v, v.roll(x=0)) - self.assertIsNot(v, v.roll(x=0)) + assert_identical(v, v.roll(x=0)) + assert v is not v.roll(x=0) expected = Variable('x', [5, 1, 2, 3, 4]) - self.assertVariableIdentical(expected, v.roll(x=1)) - self.assertVariableIdentical(expected, v.roll(x=-4)) - self.assertVariableIdentical(expected, v.roll(x=6)) + assert_identical(expected, v.roll(x=1)) + assert_identical(expected, v.roll(x=-4)) + assert_identical(expected, v.roll(x=6)) expected = Variable('x', [4, 5, 1, 2, 3]) - self.assertVariableIdentical(expected, v.roll(x=2)) - self.assertVariableIdentical(expected, v.roll(x=-3)) + assert_identical(expected, v.roll(x=2)) + assert_identical(expected, v.roll(x=-3)) with raises_regex(ValueError, 'dimension'): v.roll(z=0) @@ -1117,21 +1151,21 @@ def test_roll_consistency(self): for shift in [-3, 0, 1, 7, 11]: expected = np.roll(v.values, shift, axis=axis) actual = v.roll(**{dim: shift}).values - self.assertArrayEqual(expected, actual) + assert_array_equal(expected, actual) def test_transpose(self): v = Variable(['time', 'x'], self.d) v2 = Variable(['x', 'time'], self.d.T) - self.assertVariableIdentical(v, v2.transpose()) - self.assertVariableIdentical(v.transpose(), v.T) + assert_identical(v, v2.transpose()) + assert_identical(v.transpose(), v.T) x = np.random.randn(2, 3, 4, 5) w = Variable(['a', 'b', 'c', 'd'], x) w2 = Variable(['d', 'b', 'c', 'a'], np.einsum('abcd->dbca', x)) - self.assertEqual(w2.shape, (5, 3, 4, 2)) - self.assertVariableIdentical(w2, w.transpose('d', 'b', 'c', 'a')) - self.assertVariableIdentical(w, w2.transpose('a', 'b', 'c', 'd')) + assert w2.shape == (5, 3, 4, 2) + assert_identical(w2, w.transpose('d', 'b', 'c', 'a')) + assert_identical(w, w2.transpose('a', 'b', 'c', 'd')) w3 = Variable(['b', 'c', 'd', 'a'], np.einsum('abcd->bcda', x)) - self.assertVariableIdentical(w, w3.transpose('a', 'b', 'c', 'd')) + assert_identical(w, w3.transpose('a', 'b', 'c', 'd')) def test_transpose_0d(self): for value in [ @@ -1141,31 +1175,31 @@ def test_transpose_0d(self): np.timedelta64(1, 'h'), None, object(), - ]: + ]: variable = Variable([], value) actual = variable.transpose() assert actual.identical(variable) def test_squeeze(self): v = Variable(['x', 'y'], [[1]]) - self.assertVariableIdentical(Variable([], 1), v.squeeze()) - self.assertVariableIdentical(Variable(['y'], [1]), v.squeeze('x')) - self.assertVariableIdentical(Variable(['y'], [1]), v.squeeze(['x'])) - self.assertVariableIdentical(Variable(['x'], [1]), v.squeeze('y')) - self.assertVariableIdentical(Variable([], 1), v.squeeze(['x', 'y'])) + assert_identical(Variable([], 1), v.squeeze()) + assert_identical(Variable(['y'], [1]), v.squeeze('x')) + assert_identical(Variable(['y'], [1]), v.squeeze(['x'])) + assert_identical(Variable(['x'], [1]), v.squeeze('y')) + assert_identical(Variable([], 1), v.squeeze(['x', 'y'])) v = Variable(['x', 'y'], [[1, 2]]) - self.assertVariableIdentical(Variable(['y'], [1, 2]), v.squeeze()) - self.assertVariableIdentical(Variable(['y'], [1, 2]), v.squeeze('x')) + assert_identical(Variable(['y'], [1, 2]), v.squeeze()) + assert_identical(Variable(['y'], [1, 2]), v.squeeze('x')) with raises_regex(ValueError, 'cannot select a dimension'): v.squeeze('y') def test_get_axis_num(self): v = Variable(['x', 'y', 'z'], np.random.randn(2, 3, 4)) - self.assertEqual(v.get_axis_num('x'), 0) - self.assertEqual(v.get_axis_num(['x']), (0,)) - self.assertEqual(v.get_axis_num(['x', 'y']), (0, 1)) - self.assertEqual(v.get_axis_num(['z', 'y', 'x']), (2, 1, 0)) + assert v.get_axis_num('x') == 0 + assert v.get_axis_num(['x']) == (0,) + assert v.get_axis_num(['x', 'y']) == (0, 1) + assert v.get_axis_num(['z', 'y', 'x']) == (2, 1, 0) with raises_regex(ValueError, 'not found in array dim'): v.get_axis_num('foobar') @@ -1173,19 +1207,19 @@ def test_set_dims(self): v = Variable(['x'], [0, 1]) actual = v.set_dims(['x', 'y']) expected = Variable(['x', 'y'], [[0], [1]]) - self.assertVariableIdentical(actual, expected) + assert_identical(actual, expected) actual = v.set_dims(['y', 'x']) - self.assertVariableIdentical(actual, expected.T) + assert_identical(actual, expected.T) actual = v.set_dims(OrderedDict([('x', 2), ('y', 2)])) expected = Variable(['x', 'y'], [[0, 0], [1, 1]]) - self.assertVariableIdentical(actual, expected) + assert_identical(actual, expected) v = Variable(['foo'], [0, 1]) actual = v.set_dims('foo') expected = v - self.assertVariableIdentical(actual, expected) + assert_identical(actual, expected) with raises_regex(ValueError, 'must be a superset'): v.set_dims(['z']) @@ -1203,18 +1237,18 @@ def test_stack(self): v = Variable(['x', 'y'], [[0, 1], [2, 3]], {'foo': 'bar'}) actual = v.stack(z=('x', 'y')) expected = Variable('z', [0, 1, 2, 3], v.attrs) - self.assertVariableIdentical(actual, expected) + assert_identical(actual, expected) actual = v.stack(z=('x',)) expected = Variable(('y', 'z'), v.data.T, v.attrs) - self.assertVariableIdentical(actual, expected) + assert_identical(actual, expected) actual = v.stack(z=(),) - self.assertVariableIdentical(actual, v) + assert_identical(actual, v) actual = v.stack(X=('x',), Y=('y',)).transpose('X', 'Y') expected = Variable(('X', 'Y'), v.data, v.attrs) - self.assertVariableIdentical(actual, expected) + assert_identical(actual, expected) def test_stack_errors(self): v = Variable(['x', 'y'], [[0, 1], [2, 3]], {'foo': 'bar'}) @@ -1228,15 +1262,15 @@ def test_unstack(self): v = Variable('z', [0, 1, 2, 3], {'foo': 'bar'}) actual = v.unstack(z=OrderedDict([('x', 2), ('y', 2)])) expected = Variable(('x', 'y'), [[0, 1], [2, 3]], v.attrs) - self.assertVariableIdentical(actual, expected) + assert_identical(actual, expected) actual = v.unstack(z=OrderedDict([('x', 4), ('y', 1)])) expected = Variable(('x', 'y'), [[0], [1], [2], [3]], v.attrs) - self.assertVariableIdentical(actual, expected) + assert_identical(actual, expected) actual = v.unstack(z=OrderedDict([('x', 4)])) expected = Variable('x', [0, 1, 2, 3], v.attrs) - self.assertVariableIdentical(actual, expected) + assert_identical(actual, expected) def test_unstack_errors(self): v = Variable('z', [0, 1, 2, 3]) @@ -1251,44 +1285,44 @@ def test_unstack_2d(self): v = Variable(['x', 'y'], [[0, 1], [2, 3]]) actual = v.unstack(y={'z': 2}) expected = Variable(['x', 'z'], v.data) - self.assertVariableIdentical(actual, expected) + assert_identical(actual, expected) actual = v.unstack(x={'z': 2}) expected = Variable(['y', 'z'], v.data.T) - self.assertVariableIdentical(actual, expected) + assert_identical(actual, expected) def test_stack_unstack_consistency(self): v = Variable(['x', 'y'], [[0, 1], [2, 3]]) actual = (v.stack(z=('x', 'y')) .unstack(z=OrderedDict([('x', 2), ('y', 2)]))) - self.assertVariableIdentical(actual, v) + assert_identical(actual, v) def test_broadcasting_math(self): x = np.random.randn(2, 3) v = Variable(['a', 'b'], x) # 1d to 2d broadcasting - self.assertVariableIdentical( + assert_identical( v * v, Variable(['a', 'b'], np.einsum('ab,ab->ab', x, x))) - self.assertVariableIdentical( + assert_identical( v * v[0], Variable(['a', 'b'], np.einsum('ab,b->ab', x, x[0]))) - self.assertVariableIdentical( + assert_identical( v[0] * v, Variable(['b', 'a'], np.einsum('b,ab->ba', x[0], x))) - self.assertVariableIdentical( + assert_identical( v[0] * v[:, 0], Variable(['b', 'a'], np.einsum('b,a->ba', x[0], x[:, 0]))) # higher dim broadcasting y = np.random.randn(3, 4, 5) w = Variable(['b', 'c', 'd'], y) - self.assertVariableIdentical( + assert_identical( v * w, Variable(['a', 'b', 'c', 'd'], np.einsum('ab,bcd->abcd', x, y))) - self.assertVariableIdentical( + assert_identical( w * v, Variable(['b', 'c', 'd', 'a'], np.einsum('bcd,ab->bcda', y, x))) - self.assertVariableIdentical( + assert_identical( v * w[0], Variable(['a', 'b', 'c', 'd'], np.einsum('ab,cd->abcd', x, y[0]))) @@ -1306,28 +1340,28 @@ def test_inplace_math(self): v = Variable(['x'], x) v2 = v v2 += 1 - self.assertIs(v, v2) + assert v is v2 # since we provided an ndarray for data, it is also modified in-place - self.assertIs(source_ndarray(v.values), x) - self.assertArrayEqual(v.values, np.arange(5) + 1) + assert source_ndarray(v.values) is x + assert_array_equal(v.values, np.arange(5) + 1) with raises_regex(ValueError, 'dimensions cannot change'): v += Variable('y', np.arange(5)) def test_reduce(self): v = Variable(['x', 'y'], self.d, {'ignored': 'attributes'}) - self.assertVariableIdentical(v.reduce(np.std, 'x'), - Variable(['y'], self.d.std(axis=0))) - self.assertVariableIdentical(v.reduce(np.std, axis=0), - v.reduce(np.std, dim='x')) - self.assertVariableIdentical(v.reduce(np.std, ['y', 'x']), - Variable([], self.d.std(axis=(0, 1)))) - self.assertVariableIdentical(v.reduce(np.std), - Variable([], self.d.std())) - self.assertVariableIdentical( + assert_identical(v.reduce(np.std, 'x'), + Variable(['y'], self.d.std(axis=0))) + assert_identical(v.reduce(np.std, axis=0), + v.reduce(np.std, dim='x')) + assert_identical(v.reduce(np.std, ['y', 'x']), + Variable([], self.d.std(axis=(0, 1)))) + assert_identical(v.reduce(np.std), + Variable([], self.d.std())) + assert_identical( v.reduce(np.mean, 'x').reduce(np.std, 'y'), Variable([], self.d.mean(axis=0).std())) - self.assertVariableAllClose(v.mean('x'), v.reduce(np.mean, 'x')) + assert_allclose(v.mean('x'), v.reduce(np.mean, 'x')) with raises_regex(ValueError, 'cannot supply both'): v.mean(dim='x', axis=0) @@ -1353,41 +1387,73 @@ def test_quantile_dask_raises(self): with raises_regex(TypeError, 'arrays stored as dask'): v.quantile(0.5, dim='x') + @requires_dask + @requires_bottleneck + def test_rank_dask_raises(self): + v = Variable(['x'], [3.0, 1.0, np.nan, 2.0, 4.0]).chunk(2) + with raises_regex(TypeError, 'arrays stored as dask'): + v.rank('x') + + @requires_bottleneck + def test_rank(self): + import bottleneck as bn + # floats + v = Variable(['x', 'y'], [[3, 4, np.nan, 1]]) + expect_0 = bn.nanrankdata(v.data, axis=0) + expect_1 = bn.nanrankdata(v.data, axis=1) + np.testing.assert_allclose(v.rank('x').values, expect_0) + np.testing.assert_allclose(v.rank('y').values, expect_1) + # int + v = Variable(['x'], [3, 2, 1]) + expect = bn.rankdata(v.data, axis=0) + np.testing.assert_allclose(v.rank('x').values, expect) + # str + v = Variable(['x'], ['c', 'b', 'a']) + expect = bn.rankdata(v.data, axis=0) + np.testing.assert_allclose(v.rank('x').values, expect) + # pct + v = Variable(['x'], [3.0, 1.0, np.nan, 2.0, 4.0]) + v_expect = Variable(['x'], [0.75, 0.25, np.nan, 0.5, 1.0]) + assert_equal(v.rank('x', pct=True), v_expect) + # invalid dim + with raises_regex(ValueError, 'not found'): + v.rank('y') + def test_big_endian_reduce(self): # regression test for GH489 data = np.ones(5, dtype='>f4') v = Variable(['x'], data) expected = Variable([], 5) - self.assertVariableIdentical(expected, v.sum()) + assert_identical(expected, v.sum()) def test_reduce_funcs(self): v = Variable('x', np.array([1, np.nan, 2, 3])) - self.assertVariableIdentical(v.mean(), Variable([], 2)) - self.assertVariableIdentical(v.mean(skipna=True), Variable([], 2)) - self.assertVariableIdentical(v.mean(skipna=False), Variable([], np.nan)) - self.assertVariableIdentical(np.mean(v), Variable([], 2)) - - self.assertVariableIdentical(v.prod(), Variable([], 6)) - self.assertVariableIdentical(v.cumsum(axis=0), - Variable('x', np.array([1, 1, 3, 6]))) - self.assertVariableIdentical(v.cumprod(axis=0), - Variable('x', np.array([1, 1, 2, 6]))) - self.assertVariableIdentical(v.var(), Variable([], 2.0 / 3)) + assert_identical(v.mean(), Variable([], 2)) + assert_identical(v.mean(skipna=True), Variable([], 2)) + assert_identical(v.mean(skipna=False), Variable([], np.nan)) + assert_identical(np.mean(v), Variable([], 2)) + + assert_identical(v.prod(), Variable([], 6)) + assert_identical(v.cumsum(axis=0), + Variable('x', np.array([1, 1, 3, 6]))) + assert_identical(v.cumprod(axis=0), + Variable('x', np.array([1, 1, 2, 6]))) + assert_identical(v.var(), Variable([], 2.0 / 3)) if LooseVersion(np.__version__) < '1.9': with pytest.raises(NotImplementedError): v.median() else: - self.assertVariableIdentical(v.median(), Variable([], 2)) + assert_identical(v.median(), Variable([], 2)) v = Variable('x', [True, False, False]) - self.assertVariableIdentical(v.any(), Variable([], True)) - self.assertVariableIdentical(v.all(dim='x'), Variable([], False)) + assert_identical(v.any(), Variable([], True)) + assert_identical(v.all(dim='x'), Variable([], False)) v = Variable('t', pd.date_range('2000-01-01', periods=3)) with pytest.raises(NotImplementedError): v.max(skipna=True) - self.assertVariableIdentical( + assert_identical( v.max(), Variable([], pd.Timestamp('2000-01-03'))) def test_reduce_keep_attrs(self): @@ -1397,55 +1463,105 @@ def test_reduce_keep_attrs(self): # Test dropped attrs vm = v.mean() - self.assertEqual(len(vm.attrs), 0) - self.assertEqual(vm.attrs, OrderedDict()) + assert len(vm.attrs) == 0 + assert vm.attrs == OrderedDict() # Test kept attrs vm = v.mean(keep_attrs=True) - self.assertEqual(len(vm.attrs), len(_attrs)) - self.assertEqual(vm.attrs, _attrs) + assert len(vm.attrs) == len(_attrs) + assert vm.attrs == _attrs def test_count(self): expected = Variable([], 3) actual = Variable(['x'], [1, 2, 3, np.nan]).count() - self.assertVariableIdentical(expected, actual) + assert_identical(expected, actual) v = Variable(['x'], np.array(['1', '2', '3', np.nan], dtype=object)) actual = v.count() - self.assertVariableIdentical(expected, actual) + assert_identical(expected, actual) actual = Variable(['x'], [True, False, True]).count() - self.assertVariableIdentical(expected, actual) - self.assertEqual(actual.dtype, int) + assert_identical(expected, actual) + assert actual.dtype == int expected = Variable(['x'], [2, 3]) actual = Variable(['x', 'y'], [[1, 0, np.nan], [1, 1, 1]]).count('y') - self.assertVariableIdentical(expected, actual) + assert_identical(expected, actual) def test_setitem(self): v = Variable(['x', 'y'], [[0, 3, 2], [3, 4, 5]]) v[0, 1] = 1 - self.assertTrue(v[0, 1] == 1) + assert v[0, 1] == 1 v = Variable(['x', 'y'], [[0, 3, 2], [3, 4, 5]]) v[dict(x=[0, 1])] = 1 - self.assertArrayEqual(v[[0, 1]], np.ones_like(v[[0, 1]])) + assert_array_equal(v[[0, 1]], np.ones_like(v[[0, 1]])) # boolean indexing v = Variable(['x', 'y'], [[0, 3, 2], [3, 4, 5]]) v[dict(x=[True, False])] = 1 - self.assertArrayEqual(v[0], np.ones_like(v[0])) + assert_array_equal(v[0], np.ones_like(v[0])) v = Variable(['x', 'y'], [[0, 3, 2], [3, 4, 5]]) v[dict(x=[True, False], y=[False, True, False])] = 1 - self.assertTrue(v[0, 1] == 1) + assert v[0, 1] == 1 + + def test_setitem_fancy(self): + # assignment which should work as np.ndarray does + def assert_assigned_2d(array, key_x, key_y, values): + expected = array.copy() + expected[key_x, key_y] = values + v = Variable(['x', 'y'], array) + v[dict(x=key_x, y=key_y)] = values + assert_array_equal(expected, v) + + # 1d vectorized indexing + assert_assigned_2d(np.random.randn(4, 3), + key_x=Variable(['a'], [0, 1]), + key_y=Variable(['a'], [0, 1]), + values=0) + assert_assigned_2d(np.random.randn(4, 3), + key_x=Variable(['a'], [0, 1]), + key_y=Variable(['a'], [0, 1]), + values=Variable((), 0)) + assert_assigned_2d(np.random.randn(4, 3), + key_x=Variable(['a'], [0, 1]), + key_y=Variable(['a'], [0, 1]), + values=Variable(('a'), [3, 2])) + assert_assigned_2d(np.random.randn(4, 3), + key_x=slice(None), + key_y=Variable(['a'], [0, 1]), + values=Variable(('a'), [3, 2])) + + # 2d-vectorized indexing + assert_assigned_2d(np.random.randn(4, 3), + key_x=Variable(['a', 'b'], [[0, 1]]), + key_y=Variable(['a', 'b'], [[1, 0]]), + values=0) + assert_assigned_2d(np.random.randn(4, 3), + key_x=Variable(['a', 'b'], [[0, 1]]), + key_y=Variable(['a', 'b'], [[1, 0]]), + values=[0]) + assert_assigned_2d(np.random.randn(5, 4), + key_x=Variable(['a', 'b'], [[0, 1], [2, 3]]), + key_y=Variable(['a', 'b'], [[1, 0], [3, 3]]), + values=[2, 3]) + + # vindex with slice + v = Variable(['x', 'y', 'z'], np.ones((4, 3, 2))) + ind = Variable(['a'], [0, 1]) + v[dict(x=ind, z=ind)] = 0 + expected = Variable(['x', 'y', 'z'], np.ones((4, 3, 2))) + expected[0, :, 0] = 0 + expected[1, :, 1] = 0 + assert_identical(expected, v) # dimension broadcast v = Variable(['x', 'y'], np.ones((3, 2))) ind = Variable(['a', 'b'], [[0, 1]]) v[ind, :] = 0 expected = Variable(['x', 'y'], [[0, 0], [0, 0], [1, 1]]) - self.assertVariableIdentical(expected, v) + assert_identical(expected, v) with raises_regex(ValueError, "shape mismatch"): v[ind, ind] = np.zeros((1, 2, 1)) @@ -1453,8 +1569,8 @@ def test_setitem(self): v = Variable(['x', 'y'], [[0, 3, 2], [3, 4, 5]]) ind = Variable(['a'], [0, 1]) v[dict(x=ind)] = Variable(['a', 'y'], np.ones((2, 3), dtype=int) * 10) - self.assertArrayEqual(v[0], np.ones_like(v[0]) * 10) - self.assertArrayEqual(v[1], np.ones_like(v[1]) * 10) + assert_array_equal(v[0], np.ones_like(v[0]) * 10) + assert_array_equal(v[1], np.ones_like(v[1]) * 10) assert v.dims == ('x', 'y') # dimension should not change # increment @@ -1462,12 +1578,12 @@ def test_setitem(self): ind = Variable(['a'], [0, 1]) v[dict(x=ind)] += 1 expected = Variable(['x', 'y'], [[1, 2], [3, 4], [4, 5]]) - self.assertVariableIdentical(v, expected) + assert_identical(v, expected) ind = Variable(['a'], [0, 0]) v[dict(x=ind)] += 1 expected = Variable(['x', 'y'], [[2, 3], [3, 4], [4, 5]]) - self.assertVariableIdentical(v, expected) + assert_identical(v, expected) @requires_dask @@ -1503,6 +1619,13 @@ def test_getitem_1d_fancy(self): pytest.xfail("vindex from latest dask is required") super(TestVariableWithDask, self).test_getitem_1d_fancy() + def test_getitem_with_mask_nd_indexer(self): + import dask.array as da + v = Variable(['x'], da.arange(3, chunks=3)) + indexer = Variable(('x', 'y'), [[0, -1], [-1, 2]]) + assert_identical(v._getitem_with_mask(indexer, fill_value=-1), + self.cls(('x', 'y'), [[0, -1], [-1, 2]])) + class TestIndexVariable(TestCase, VariableSubclassTestCases): cls = staticmethod(IndexVariable) @@ -1514,26 +1637,26 @@ def test_init(self): def test_to_index(self): data = 0.5 * np.arange(10) v = IndexVariable(['time'], data, {'foo': 'bar'}) - self.assertTrue(pd.Index(data, name='time').identical(v.to_index())) + assert pd.Index(data, name='time').identical(v.to_index()) def test_multiindex_default_level_names(self): midx = pd.MultiIndex.from_product([['a', 'b'], [1, 2]]) v = IndexVariable(['x'], midx, {'foo': 'bar'}) - self.assertEqual(v.to_index().names, ('x_level_0', 'x_level_1')) + assert v.to_index().names == ('x_level_0', 'x_level_1') def test_data(self): x = IndexVariable('x', np.arange(3.0)) - self.assertIsInstance(x._data, PandasIndexAdapter) - self.assertIsInstance(x.data, np.ndarray) - self.assertEqual(float, x.dtype) - self.assertArrayEqual(np.arange(3), x) - self.assertEqual(float, x.values.dtype) + assert isinstance(x._data, PandasIndexAdapter) + assert isinstance(x.data, np.ndarray) + assert float == x.dtype + assert_array_equal(np.arange(3), x) + assert float == x.values.dtype with raises_regex(TypeError, 'cannot be modified'): x[:] = 0 def test_name(self): coord = IndexVariable('x', [10.0]) - self.assertEqual(coord.name, 'x') + assert coord.name == 'x' with pytest.raises(AttributeError): coord.name = 'y' @@ -1542,23 +1665,24 @@ def test_level_names(self): midx = pd.MultiIndex.from_product([['a', 'b'], [1, 2]], names=['level_1', 'level_2']) x = IndexVariable('x', midx) - self.assertEqual(x.level_names, midx.names) + assert x.level_names == midx.names - self.assertIsNone(IndexVariable('y', [10.0]).level_names) + assert IndexVariable('y', [10.0]).level_names is None def test_get_level_variable(self): midx = pd.MultiIndex.from_product([['a', 'b'], [1, 2]], names=['level_1', 'level_2']) x = IndexVariable('x', midx) level_1 = IndexVariable('x', midx.get_level_values('level_1')) - self.assertVariableIdentical(x.get_level_variable('level_1'), level_1) + assert_identical(x.get_level_variable('level_1'), level_1) with raises_regex(ValueError, 'has no MultiIndex'): IndexVariable('y', [10.0]).get_level_variable('level') def test_concat_periods(self): periods = pd.period_range('2000-01-01', periods=10) - coords = [IndexVariable('t', periods[:5]), IndexVariable('t', periods[5:])] + coords = [IndexVariable('t', periods[:5]), + IndexVariable('t', periods[5:])] expected = IndexVariable('t', periods) actual = IndexVariable.concat(coords, dim='t') assert actual.identical(expected) @@ -1578,9 +1702,9 @@ def test_concat_multiindex(self): assert isinstance(actual.to_index(), pd.MultiIndex) def test_coordinate_alias(self): - with self.assertWarns('deprecated'): + with pytest.warns(Warning, match='deprecated'): x = Coordinate('x', [1, 2, 3]) - self.assertIsInstance(x, IndexVariable) + assert isinstance(x, IndexVariable) # These tests make use of multi-dimensional variables, which are not valid # IndexVariable objects: @@ -1609,69 +1733,69 @@ def test_unchanged_types(self): pd.date_range('2000-01-01', periods=3), pd.date_range('2000-01-01', periods=3).values]: x = t(data) - self.assertIs(source_ndarray(x), - source_ndarray(as_compatible_data(x))) + assert source_ndarray(x) is \ + source_ndarray(as_compatible_data(x)) def test_converted_types(self): for input_array in [[[0, 1, 2]], pd.DataFrame([[0, 1, 2]])]: actual = as_compatible_data(input_array) - self.assertArrayEqual(np.asarray(input_array), actual) - self.assertEqual(np.ndarray, type(actual)) - self.assertEqual(np.asarray(input_array).dtype, actual.dtype) + assert_array_equal(np.asarray(input_array), actual) + assert np.ndarray == type(actual) + assert np.asarray(input_array).dtype == actual.dtype def test_masked_array(self): original = np.ma.MaskedArray(np.arange(5)) expected = np.arange(5) actual = as_compatible_data(original) - self.assertArrayEqual(expected, actual) - self.assertEqual(np.dtype(int), actual.dtype) + assert_array_equal(expected, actual) + assert np.dtype(int) == actual.dtype original = np.ma.MaskedArray(np.arange(5), mask=4 * [False] + [True]) expected = np.arange(5.0) expected[-1] = np.nan actual = as_compatible_data(original) - self.assertArrayEqual(expected, actual) - self.assertEqual(np.dtype(float), actual.dtype) + assert_array_equal(expected, actual) + assert np.dtype(float) == actual.dtype def test_datetime(self): expected = np.datetime64('2000-01-01') actual = as_compatible_data(expected) - self.assertEqual(expected, actual) - self.assertEqual(np.ndarray, type(actual)) - self.assertEqual(np.dtype('datetime64[ns]'), actual.dtype) + assert expected == actual + assert np.ndarray == type(actual) + assert np.dtype('datetime64[ns]') == actual.dtype expected = np.array([np.datetime64('2000-01-01')]) actual = as_compatible_data(expected) - self.assertEqual(np.asarray(expected), actual) - self.assertEqual(np.ndarray, type(actual)) - self.assertEqual(np.dtype('datetime64[ns]'), actual.dtype) + assert np.asarray(expected) == actual + assert np.ndarray == type(actual) + assert np.dtype('datetime64[ns]') == actual.dtype expected = np.array([np.datetime64('2000-01-01', 'ns')]) actual = as_compatible_data(expected) - self.assertEqual(np.asarray(expected), actual) - self.assertEqual(np.ndarray, type(actual)) - self.assertEqual(np.dtype('datetime64[ns]'), actual.dtype) - self.assertIs(expected, source_ndarray(np.asarray(actual))) + assert np.asarray(expected) == actual + assert np.ndarray == type(actual) + assert np.dtype('datetime64[ns]') == actual.dtype + assert expected is source_ndarray(np.asarray(actual)) expected = np.datetime64('2000-01-01', 'ns') actual = as_compatible_data(datetime(2000, 1, 1)) - self.assertEqual(np.asarray(expected), actual) - self.assertEqual(np.ndarray, type(actual)) - self.assertEqual(np.dtype('datetime64[ns]'), actual.dtype) + assert np.asarray(expected) == actual + assert np.ndarray == type(actual) + assert np.dtype('datetime64[ns]') == actual.dtype def test_full_like(self): # For more thorough tests, see test_variable.py - orig = Variable(dims=('x', 'y'), data=[[1.5 ,2.0], [3.1, 4.3]], + orig = Variable(dims=('x', 'y'), data=[[1.5, 2.0], [3.1, 4.3]], attrs={'foo': 'bar'}) expect = orig.copy(deep=True) expect.values = [[2.0, 2.0], [2.0, 2.0]] - self.assertVariableIdentical(expect, full_like(orig, 2)) + assert_identical(expect, full_like(orig, 2)) # override dtype expect.values = [[True, True], [True, True]] assert expect.dtype == bool - self.assertVariableIdentical(expect, full_like(orig, True, dtype=bool)) + assert_identical(expect, full_like(orig, True, dtype=bool)) @requires_dask def test_full_like_dask(self): @@ -1679,12 +1803,12 @@ def test_full_like_dask(self): attrs={'foo': 'bar'}).chunk(((1, 1), (2,))) def check(actual, expect_dtype, expect_values): - self.assertEqual(actual.dtype, expect_dtype) - self.assertEqual(actual.shape, orig.shape) - self.assertEqual(actual.dims, orig.dims) - self.assertEqual(actual.attrs, orig.attrs) - self.assertEqual(actual.chunks, orig.chunks) - self.assertArrayEqual(actual.values, expect_values) + assert actual.dtype == expect_dtype + assert actual.shape == orig.shape + assert actual.dims == orig.dims + assert actual.attrs == orig.attrs + assert actual.chunks == orig.chunks + assert_array_equal(actual.values, expect_values) check(full_like(orig, 2), orig.dtype, np.full_like(orig.values, 2)) @@ -1703,20 +1827,20 @@ def check(actual, expect_dtype, expect_values): assert not isinstance(v, np.ndarray) def test_zeros_like(self): - orig = Variable(dims=('x', 'y'), data=[[1.5 ,2.0], [3.1, 4.3]], + orig = Variable(dims=('x', 'y'), data=[[1.5, 2.0], [3.1, 4.3]], attrs={'foo': 'bar'}) - self.assertVariableIdentical(zeros_like(orig), - full_like(orig, 0)) - self.assertVariableIdentical(zeros_like(orig, dtype=int), - full_like(orig, 0, dtype=int)) + assert_identical(zeros_like(orig), + full_like(orig, 0)) + assert_identical(zeros_like(orig, dtype=int), + full_like(orig, 0, dtype=int)) def test_ones_like(self): - orig = Variable(dims=('x', 'y'), data=[[1.5 ,2.0], [3.1, 4.3]], + orig = Variable(dims=('x', 'y'), data=[[1.5, 2.0], [3.1, 4.3]], attrs={'foo': 'bar'}) - self.assertVariableIdentical(ones_like(orig), - full_like(orig, 1)) - self.assertVariableIdentical(ones_like(orig, dtype=int), - full_like(orig, 1, dtype=int)) + assert_identical(ones_like(orig), + full_like(orig, 1)) + assert_identical(ones_like(orig, dtype=int), + full_like(orig, 1, dtype=int)) def test_unsupported_type(self): # Non indexable type @@ -1744,6 +1868,7 @@ def test_raise_no_warning_for_nan_in_binary_ops(): class TestBackendIndexing(TestCase): """ Make sure all the array wrappers can be indexed. """ + def setUp(self): self.d = np.random.random((10, 3)).astype(np.float64) @@ -1763,7 +1888,7 @@ def test_NumpyIndexingAdapter(self): # could not doubly wrapping with raises_regex(TypeError, 'NumpyIndexingAdapter only wraps '): v = Variable(dims=('x', 'y'), data=NumpyIndexingAdapter( - NumpyIndexingAdapter(self.d))) + NumpyIndexingAdapter(self.d))) def test_LazilyIndexedArray(self): v = Variable(dims=('x', 'y'), data=LazilyIndexedArray(self.d)) diff --git a/xarray/ufuncs.py b/xarray/ufuncs.py index 557e741..1990ac5 100644 --- a/xarray/ufuncs.py +++ b/xarray/ufuncs.py @@ -41,6 +41,7 @@ def _dispatch_priority(obj): class _UFuncDispatcher(object): """Wrapper for dispatching ufuncs.""" + def __init__(self, name): self._name = name diff --git a/xarray/util/print_versions.py b/xarray/util/print_versions.py index 095c7ad..2c9b194 100755 --- a/xarray/util/print_versions.py +++ b/xarray/util/print_versions.py @@ -25,7 +25,7 @@ def get_sys_info(): stdout=subprocess.PIPE, stderr=subprocess.PIPE) so, serr = pipe.communicate() - except: + except Exception: pass else: if pipe.returncode == 0: @@ -55,7 +55,7 @@ def get_sys_info(): ("LOCALE", "%s.%s" % locale.getlocale()), ]) - except: + except Exception: pass return blob @@ -75,9 +75,11 @@ def show_versions(as_json=False): # ("pydap", lambda mod: mod.version.version), ("h5netcdf", lambda mod: mod.__version__), ("Nio", lambda mod: mod.__version__), + ("zarr", lambda mod: mod.__version__), ("bottleneck", lambda mod: mod.__version__), ("cyordereddict", lambda mod: mod.__version__), ("dask", lambda mod: mod.__version__), + ("distributed", lambda mod: mod.__version__), ("matplotlib", lambda mod: mod.__version__), ("cartopy", lambda mod: mod.__version__), ("seaborn", lambda mod: mod.__version__), @@ -100,13 +102,13 @@ def show_versions(as_json=False): mod = importlib.import_module(modname) ver = ver_f(mod) deps_blob.append((modname, ver)) - except: + except Exception: deps_blob.append((modname, None)) if (as_json): try: import json - except: + except Exception: import simplejson as json j = dict(system=dict(sys_info), dependencies=dict(deps_blob))